modelfactory.class.inc.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  1. <?php
  2. // Copyright (C) 2011 Combodo SARL
  3. //
  4. /**
  5. * ModelFactory: in-memory manipulation of the XML MetaModel
  6. *
  7. * @author Erwan Taloc <erwan.taloc@combodo.com>
  8. * @author Romain Quetiez <romain.quetiez@combodo.com>
  9. * @author Denis Flaven <denis.flaven@combodo.com>
  10. * @license Combodo Private
  11. */
  12. require_once(APPROOT.'setup/moduleinstaller.class.inc.php');
  13. /**
  14. * ModelFactoryModule: the representation of a Module (i.e. element that can be selected during the setup)
  15. * @package ModelFactory
  16. */
  17. class MFModule
  18. {
  19. protected $sId;
  20. protected $sName;
  21. protected $sVersion;
  22. protected $sRootDir;
  23. protected $sLabel;
  24. protected $aDataModels;
  25. public function __construct($sId, $sRootDir, $sLabel)
  26. {
  27. $this->sId = $sId;
  28. list($this->sName, $this->sVersion) = ModuleDiscovery::GetModuleName($sId);
  29. if (strlen($this->sVersion) == 0)
  30. {
  31. $this->sVersion = '1.0.0';
  32. }
  33. $this->sRootDir = $sRootDir;
  34. $this->sLabel = $sLabel;
  35. $this->aDataModels = array();
  36. // Scan the module's root directory to find the datamodel(*).xml files
  37. if ($hDir = opendir($sRootDir))
  38. {
  39. // This is the correct way to loop over the directory. (according to the documentation)
  40. while (($sFile = readdir($hDir)) !== false)
  41. {
  42. if (preg_match('/^datamodel(.*)\.xml$/i', $sFile, $aMatches))
  43. {
  44. $this->aDataModels[] = $this->sRootDir.'/'.$aMatches[0];
  45. }
  46. }
  47. closedir($hDir);
  48. }
  49. }
  50. public function GetId()
  51. {
  52. return $this->sId;
  53. }
  54. public function GetName()
  55. {
  56. return $this->sName;
  57. }
  58. public function GetVersion()
  59. {
  60. return $this->sVersion;
  61. }
  62. public function GetLabel()
  63. {
  64. return $this->sLabel;
  65. }
  66. public function GetRootDir()
  67. {
  68. return $this->sRootDir;
  69. }
  70. public function GetModuleDir()
  71. {
  72. return basename($this->sRootDir);
  73. }
  74. public function GetDataModelFiles()
  75. {
  76. return $this->aDataModels;
  77. }
  78. /**
  79. * List all classes in this module
  80. */
  81. public function ListClasses()
  82. {
  83. return array();
  84. }
  85. }
  86. /**
  87. * ModelFactory: the class that manages the in-memory representation of the XML MetaModel
  88. * @package ModelFactory
  89. */
  90. class ModelFactory
  91. {
  92. protected $sRootDir;
  93. protected $oDOMDocument;
  94. protected $oRoot;
  95. protected $oClasses;
  96. protected $oMenus;
  97. static protected $aLoadedClasses;
  98. static protected $aLoadedMenus;
  99. static protected $aWellKnownParents = array('DBObject', 'CMDBObject','cmdbAbstractObject');
  100. // static protected $aWellKnownMenus = array('DataAdministration', 'Catalogs', 'ConfigManagement', 'Contact', 'ConfigManagementCI', 'ConfigManagement:Shortcuts', 'ServiceManagement');
  101. static protected $aLoadedModules;
  102. static protected $aLoadErrors;
  103. public function __construct($sRootDir, $aRootNodeExtensions = array())
  104. {
  105. $this->sRootDir = $sRootDir;
  106. $this->oDOMDocument = new MFDocument();
  107. $this->oRoot = $this->oDOMDocument->CreateElement('itop_design');
  108. $this->oDOMDocument->AppendChild($this->oRoot);
  109. $this->oClasses = $this->oDOMDocument->CreateElement('classes');
  110. $this->oRoot->AppendChild($this->oClasses);
  111. foreach (self::$aWellKnownParents as $sWellKnownParent)
  112. {
  113. $oWKClass = $this->oDOMDocument->CreateElement('class');
  114. $oWKClass->setAttribute('id', $sWellKnownParent);
  115. $this->oClasses->AppendChild($oWKClass);
  116. }
  117. $this->oMenus = $this->oDOMDocument->CreateElement('menus');
  118. $this->oRoot->AppendChild($this->oMenus);
  119. foreach($aRootNodeExtensions as $sElementName)
  120. {
  121. $oElement = $this->oDOMDocument->CreateElement($sElementName);
  122. $this->oRoot->AppendChild($oElement);
  123. }
  124. self::$aLoadedClasses = array();
  125. self::$aLoadedMenus = array();
  126. self::$aLoadedModules = array();
  127. self::$aLoadErrors = array();
  128. libxml_use_internal_errors(true);
  129. }
  130. public function Dump($oNode = null)
  131. {
  132. if (is_null($oNode))
  133. {
  134. $oNode = $this->oRoot;
  135. }
  136. $oNode->Dump();
  137. }
  138. /**
  139. * To progressively replace LoadModule
  140. * @param xxx xxx
  141. */
  142. public function LoadDelta(DOMDocument $oDeltaDoc, $oSourceNode, $oTargetParentNode)
  143. {
  144. if (!$oSourceNode instanceof DOMElement) return;
  145. //echo "Load $oSourceNode->tagName::".$oSourceNode->getAttribute('id')." (".$oSourceNode->getAttribute('_delta').")<br/>\n";
  146. $oTarget = $this->oDOMDocument;
  147. if (($oSourceNode->tagName == 'class') && ($oSourceNode->parentNode->tagName == 'classes'))
  148. {
  149. if ($oSourceNode->getAttribute('_delta') == 'define')
  150. {
  151. // This tag is organized in hierarchy: determine the real parent node (as a subnode of the current node)
  152. $sParentId = $oSourceNode->GetChildText('parent');
  153. $oTargetParentNode = $oTarget->GetNodeById('/itop_design/classes//class', $sParentId)->item(0);
  154. if (!$oTargetParentNode)
  155. {
  156. echo "Dumping target doc - looking for '$sPath'<br/>\n";
  157. $this->oDOMDocument->firstChild->Dump();
  158. throw new Exception("XML datamodel loader: could not find parent node for $oSourceNode->tagName/".$oSourceNode->getAttribute('id')." with parent id $sParentId");
  159. }
  160. }
  161. else
  162. {
  163. $oTargetNode = $oTarget->GetNodeById('/itop_design/classes//class', $oSourceNode->getAttribute('id'))->item(0);
  164. if (!$oTargetNode)
  165. {
  166. echo "Dumping target doc - looking for '$sPath'<br/>\n";
  167. $this->oDOMDocument->firstChild->Dump();
  168. throw new Exception("XML datamodel loader: could not find node for $oSourceNode->tagName/".$oSourceNode->getAttribute('id'));
  169. }
  170. else
  171. {
  172. $oTargetParentNode = $oTargetNode->parentNode;
  173. }
  174. }
  175. }
  176. switch ($oSourceNode->getAttribute('_delta'))
  177. {
  178. case 'must_exist':
  179. case 'merge':
  180. case '':
  181. $bMustExist = ($oSourceNode->getAttribute('_delta') == 'must_exist');
  182. $sSearchId = $oSourceNode->hasAttribute('_rename_from') ? $oSourceNode->getAttribute('_rename_from') : $oSourceNode->getAttribute('id');
  183. $oTargetNode = $oSourceNode->MergeInto($oTargetParentNode, $sSearchId, $bMustExist);
  184. foreach($oSourceNode->childNodes as $oSourceChild)
  185. {
  186. // Continue deeper
  187. $this->LoadDelta($oDeltaDoc, $oSourceChild, $oTargetNode);
  188. }
  189. break;
  190. case 'define':
  191. // New node - copy child nodes as well
  192. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  193. $oTargetParentNode->AddChildNode($oTargetNode);
  194. break;
  195. case 'redefine':
  196. // Replace the existing node by the given node - copy child nodes as well
  197. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  198. $oTargetParentNode->RedefineChildNode($oTargetNode);
  199. break;
  200. case 'delete':
  201. $oTargetNode = $oTargetParentNode->FindExistingChildNode($oSourceNode);
  202. $oTargetNode->Delete();
  203. break;
  204. }
  205. if ($oSourceNode->hasAttribute('_rename_from'))
  206. {
  207. $oTargetNode->Rename($oSourceNode->getAttribute('id'));
  208. }
  209. if ($oTargetNode->hasAttribute('_delta'))
  210. {
  211. $oTargetNode->removeAttribute('_delta');
  212. }
  213. }
  214. /**
  215. * Loads the definitions corresponding to the given Module
  216. * @param MFModule $oModule
  217. */
  218. public function LoadModule(MFModule $oModule)
  219. {
  220. $aDataModels = $oModule->GetDataModelFiles();
  221. $sModuleName = $oModule->GetName();
  222. $aClasses = array();
  223. self::$aLoadedModules[] = $oModule;
  224. foreach($aDataModels as $sXmlFile)
  225. {
  226. $oDocument = new MFDocument();
  227. libxml_clear_errors();
  228. $oDocument->load($sXmlFile);
  229. //$bValidated = $oDocument->schemaValidate(APPROOT.'setup/itop_design.xsd');
  230. $aErrors = libxml_get_errors();
  231. if (count($aErrors) > 0)
  232. {
  233. self::$aLoadErrors[$sModuleName] = $aErrors;
  234. return;
  235. }
  236. $oXPath = new DOMXPath($oDocument);
  237. $oNodeList = $oXPath->query('/itop_design/classes//class');
  238. foreach($oNodeList as $oNode)
  239. {
  240. $oNode->SetAttribute('_created_in', $sModuleName);
  241. }
  242. $oNodeList = $oXPath->query('/itop_design/menus/menu');
  243. foreach($oNodeList as $oNode)
  244. {
  245. $oNode->SetAttribute('_created_in', $sModuleName);
  246. }
  247. $oDeltaRoot = $oDocument->childNodes->item(0);
  248. $this->LoadDelta($oDocument, $oDeltaRoot, $this->oDOMDocument);
  249. }
  250. }
  251. /**
  252. * XML load errors (XML format and validation)
  253. */
  254. function HasLoadErrors()
  255. {
  256. return (count(self::$aLoadErrors) > 0);
  257. }
  258. function GetLoadErrors()
  259. {
  260. return self::$aLoadErrors;
  261. }
  262. function GetLoadedModules($bExcludeWorkspace = true)
  263. {
  264. if ($bExcludeWorkspace)
  265. {
  266. $aModules = array();
  267. foreach(self::$aLoadedModules as $oModule)
  268. {
  269. if (!$oModule instanceof MFWorkspace)
  270. {
  271. $aModules[] = $oModule;
  272. }
  273. }
  274. }
  275. else
  276. {
  277. $aModules = self::$aLoadedModules;
  278. }
  279. return $aModules;
  280. }
  281. function GetModule($sModuleName)
  282. {
  283. foreach(self::$aLoadedModules as $oModule)
  284. {
  285. if ($oModule->GetName() == $sModuleName) return $oModule;
  286. }
  287. return null;
  288. }
  289. public function CreateElement($sTagName, $sValue = '')
  290. {
  291. return $this->oDOMDocument->createElement($sTagName, $sValue);
  292. }
  293. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  294. {
  295. return $this->oDOMDocument->GetNodeById($sXPath, $sId, $oContextNode);
  296. }
  297. /**
  298. * Check if the class specified by the given node already exists in the loaded DOM
  299. * @param DOMNode $oClassNode The node corresponding to the class to load
  300. * @throws Exception
  301. * @return bool True if the class exists, false otherwise
  302. */
  303. protected function ClassExists(DOMNode $oClassNode)
  304. {
  305. assert(false);
  306. if ($oClassNode->hasAttribute('id'))
  307. {
  308. $sClassName = $oClassNode->GetAttribute('id');
  309. }
  310. else
  311. {
  312. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  313. }
  314. return (array_key_exists($sClassName, self::$aLoadedClasses));
  315. }
  316. /**
  317. * Check if the class specified by the given name already exists in the loaded DOM
  318. * @param string $sClassName The node corresponding to the class to load
  319. * @throws Exception
  320. * @return bool True if the class exists, false otherwise
  321. */
  322. protected function ClassNameExists($sClassName, $bFlattenLayers = true)
  323. {
  324. return !is_null($this->GetClass($sClassName, $bFlattenLayers));
  325. }
  326. /**
  327. * Add the given class to the DOM
  328. * @param DOMNode $oClassNode
  329. * @param string $sModuleName The name of the module in which this class is declared
  330. * @throws Exception
  331. */
  332. public function AddClass(DOMNode $oClassNode, $sModuleName)
  333. {
  334. if ($oClassNode->hasAttribute('id'))
  335. {
  336. $sClassName = $oClassNode->GetAttribute('id');
  337. }
  338. else
  339. {
  340. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  341. }
  342. if ($this->ClassNameExists($oClassNode->getAttribute('id')))
  343. {
  344. throw new Exception("ModelFactory::AddClass: Cannot add the already existing class $sClassName");
  345. }
  346. $sParentClass = $oClassNode->GetChildText('parent', '');
  347. $oParentNode = $this->GetClass($sParentClass);
  348. if ($oParentNode == null)
  349. {
  350. throw new Exception("ModelFactory::AddClass: Cannot find the parent class of '$sClassName': '$sParentClass'");
  351. }
  352. else
  353. {
  354. if ($sModuleName != '')
  355. {
  356. $oClassNode->SetAttribute('_created_in', $sModuleName);
  357. }
  358. $oParentNode->AddChildNode($this->oDOMDocument->importNode($oClassNode, true));
  359. }
  360. }
  361. /**
  362. * Remove a class from the DOM
  363. * @param string $sClass
  364. * @throws Exception
  365. */
  366. public function RemoveClass($sClass)
  367. {
  368. $oClassNode = $this->GetClass($sClass);
  369. if ($oClassNode == null)
  370. {
  371. throw new Exception("ModelFactory::RemoveClass: Cannot remove the non existing class $sClass");
  372. }
  373. // Note: the child classes are removed entirely
  374. $oClassNode->Delete();
  375. }
  376. /**
  377. * Modify a class within the DOM
  378. * @param string $sMenuId
  379. * @param DOMNode $oMenuNode
  380. * @throws Exception
  381. */
  382. public function AlterClass($sClassName, DOMNode $oClassNode)
  383. {
  384. $sOriginalName = $sClassName;
  385. if ($this->ClassNameExists($sClassName))
  386. {
  387. $oDestNode = self::$aLoadedClasses[$sClassName];
  388. }
  389. else
  390. {
  391. $sOriginalName = $oClassNode->getAttribute('_original_name');
  392. if ($this->ClassNameExists($sOriginalName))
  393. {
  394. // Class was renamed !
  395. $oDestNode = self::$aLoadedClasses[$sOriginalName];
  396. }
  397. else
  398. {
  399. throw new Exception("ModelFactory::AddClass: Cannot alter the non-existing class $sClassName / $sOriginalName");
  400. }
  401. }
  402. $this->_priv_AlterNode($oDestNode, $oClassNode);
  403. $sClassName = $oDestNode->getAttribute('id');
  404. if ($sOriginalName != $sClassName)
  405. {
  406. unset(self::$aLoadedClasses[$sOriginalName]);
  407. self::$aLoadedClasses[$sClassName] = $oDestNode;
  408. }
  409. $this->_priv_SetFlag($oDestNode, 'modified');
  410. }
  411. public function GetClassXMLTemplate($sName, $sIcon)
  412. {
  413. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  414. return
  415. <<<EOF
  416. $sHeader
  417. <class id="$sName">
  418. <comment/>
  419. <properties>
  420. </properties>
  421. <naming format=""><attributes/></naming>
  422. <reconciliation><attributes/></reconciliation>
  423. <display_template/>
  424. <icon>$sIcon</icon>
  425. </properties>
  426. <fields/>
  427. <lifecycle/>
  428. <methods/>
  429. <presentation>
  430. <details><items/></details>
  431. <search><items/></search>
  432. <list><items/></list>
  433. </presentation>
  434. </class>
  435. EOF
  436. ;
  437. }
  438. /**
  439. * List all classes from the DOM, for a given module
  440. * @param string $sModuleNale
  441. * @param bool $bFlattenLayers
  442. * @throws Exception
  443. */
  444. public function ListClasses($sModuleName, $bFlattenLayers = true)
  445. {
  446. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName']";
  447. if ($bFlattenLayers)
  448. {
  449. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName' and (not(@_alteration) or @_alteration!='removed')]";
  450. }
  451. return $this->GetNodes($sXPath);
  452. }
  453. /**
  454. * List all classes from the DOM, for a given module
  455. * @param string $sModuleNale
  456. * @param bool $bFlattenLayers
  457. * @throws Exception
  458. */
  459. public function ListAllClasses($bFlattenLayers = true)
  460. {
  461. $sXPath = "/itop_design/classes//class";
  462. if ($bFlattenLayers)
  463. {
  464. $sXPath = "/itop_design/classes//class[not(@_alteration) or @_alteration!='removed']";
  465. }
  466. return $this->GetNodes($sXPath);
  467. }
  468. public function GetClass($sClassName, $bFlattenLayers = true)
  469. {
  470. $oClassNode = $this->GetNodes("/itop_design/classes//class[@id='$sClassName']")->item(0);
  471. if ($oClassNode == null)
  472. {
  473. return null;
  474. }
  475. elseif ($bFlattenLayers)
  476. {
  477. $sOperation = $oClassNode->getAttribute('_alteration');
  478. if ($sOperation == 'removed')
  479. {
  480. $oClassNode = null;
  481. }
  482. }
  483. return $oClassNode;
  484. }
  485. public function GetChildClasses($oClassNode, $bFlattenLayers = true)
  486. {
  487. $sXPath = "class";
  488. if ($bFlattenLayers)
  489. {
  490. $sXPath = "class[(@_operation!='removed')]";
  491. }
  492. return $this->GetNodes($sXPath, $oClassNode);
  493. }
  494. public function GetField($sClassName, $sAttCode, $bFlattenLayers = true)
  495. {
  496. if (!$this->ClassNameExists($sClassName))
  497. {
  498. return null;
  499. }
  500. $oClassNode = self::$aLoadedClasses[$sClassName];
  501. if ($bFlattenLayers)
  502. {
  503. $sOperation = $oClassNode->getAttribute('_operation');
  504. if ($sOperation == 'removed')
  505. {
  506. $oClassNode = null;
  507. }
  508. }
  509. $sXPath = "fields/field[@id='$sAttCode']";
  510. if ($bFlattenLayers)
  511. {
  512. $sXPath = "fields/field[(@id='$sAttCode' and (not(@_operation) or @_operation!='removed'))]";
  513. }
  514. $oFieldNode = $this->GetNodes($sXPath, $oClassNode)->item(0);
  515. if (($oFieldNode == null) && ($sParentClass = $oClassNode->GetChildText('parent')))
  516. {
  517. return $this->GetField($sParentClass, $sAttCode, $bFlattenLayers);
  518. }
  519. return $oFieldNode;
  520. }
  521. /**
  522. * List all classes from the DOM
  523. * @param bool $bFlattenLayers
  524. * @throws Exception
  525. */
  526. public function ListFields(DOMNode $oClassNode, $bFlattenLayers = true)
  527. {
  528. $sXPath = "fields/field";
  529. if ($bFlattenLayers)
  530. {
  531. $sXPath = "fields/field[not(@_alteration) or @_alteration!='removed']";
  532. }
  533. return $this->GetNodes($sXPath, $oClassNode);
  534. }
  535. public function AddField(DOMNode $oClassNode, $sFieldCode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  536. {
  537. $oNewField = $this->oDOMDocument->createElement('field');
  538. $oNewField->setAttribute('id', $sFieldCode);
  539. $this->_priv_AlterField($oNewField, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams);
  540. $oFields = $oClassNode->getElementsByTagName('fields')->item(0);
  541. $oFields->AppendChild($oNewField);
  542. $this->_priv_SetFlag($oNewField, 'added');
  543. }
  544. public function RemoveField(DOMNode $oClassNode, $sFieldCode)
  545. {
  546. $sXPath = "fields/field[@id='$sFieldCode']";
  547. $oFieldNodes = $this->GetNodes($sXPath, $oClassNode);
  548. if (is_object($oFieldNodes) && (is_object($oFieldNodes->item(0))))
  549. {
  550. $oFieldNode = $oFieldNodes->item(0);
  551. $sOpCode = $oFieldNode->getAttribute('_operation');
  552. if ($oFieldNode->getAttribute('_operation') == 'added')
  553. {
  554. $oFieldNode->parentNode->removeChild($oFieldNode);
  555. }
  556. else
  557. {
  558. $this->_priv_SetFlag($oFieldNode, 'removed');
  559. }
  560. }
  561. }
  562. public function AlterField(DOMNode $oClassNode, $sFieldCode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  563. {
  564. $sXPath = "fields/field[@id='$sFieldCode']";
  565. $oFieldNodes = $this->GetNodes($sXPath, $oClassNode);
  566. if (is_object($oFieldNodes) && (is_object($oFieldNodes->item(0))))
  567. {
  568. $oFieldNode = $oFieldNodes->item(0);
  569. //@@TODO: if the field was 'added' => then let it as 'added'
  570. $sOpCode = $oFieldNode->getAttribute('_operation');
  571. switch($sOpCode)
  572. {
  573. case 'added':
  574. case 'modified':
  575. // added or modified, let it as it is
  576. break;
  577. default:
  578. $this->_priv_SetFlag($oFieldNodes->item(0), 'modified');
  579. }
  580. $this->_priv_AlterField($oFieldNodes->item(0), $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams);
  581. }
  582. }
  583. protected function _priv_AlterField(DOMNode $oFieldNode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  584. {
  585. switch($sFieldType)
  586. {
  587. case 'Blob':
  588. case 'Boolean':
  589. case 'CaseLog':
  590. case 'Deadline':
  591. case 'Duration':
  592. case 'EmailAddress':
  593. case 'EncryptedString':
  594. case 'HTML':
  595. case 'IPAddress':
  596. case 'LongText':
  597. case 'OQL':
  598. case 'OneWayPassword':
  599. case 'Password':
  600. case 'Percentage':
  601. case 'String':
  602. case 'Text':
  603. case 'Text':
  604. case 'TemplateHTML':
  605. case 'TemplateString':
  606. case 'TemplateText':
  607. case 'URL':
  608. case 'Date':
  609. case 'DateTime':
  610. case 'Decimal':
  611. case 'Integer':
  612. break;
  613. case 'ExternalKey':
  614. $this->_priv_AddFieldAttribute($oFieldNode, 'target_class', $aExtraParams);
  615. // Fall through
  616. case 'HierarchicalKey':
  617. $this->_priv_AddFieldAttribute($oFieldNode, 'on_target_delete', $aExtraParams);
  618. $this->_priv_AddFieldAttribute($oFieldNode, 'filter', $aExtraParams);
  619. break;
  620. case 'ExternalField':
  621. $this->_priv_AddFieldAttribute($oFieldNode, 'extkey_attcode', $aExtraParams);
  622. $this->_priv_AddFieldAttribute($oFieldNode, 'target_attcode', $aExtraParams);
  623. break;
  624. case 'Enum':
  625. $this->_priv_SetFieldValues($oFieldNode, $aExtraParams);
  626. break;
  627. case 'LinkedSetIndirect':
  628. $this->_priv_AddFieldAttribute($oFieldNode, 'ext_key_to_remote', $aExtraParams);
  629. // Fall through
  630. case 'LinkedSet':
  631. $this->_priv_AddFieldAttribute($oFieldNode, 'linked_class', $aExtraParams);
  632. $this->_priv_AddFieldAttribute($oFieldNode, 'ext_key_to_me', $aExtraParams);
  633. $this->_priv_AddFieldAttribute($oFieldNode, 'count_min', $aExtraParams);
  634. $this->_priv_AddFieldAttribute($oFieldNode, 'count_max', $aExtraParams);
  635. break;
  636. default:
  637. throw(new Exception('Unsupported type of field: '.$sFieldType));
  638. }
  639. $this->_priv_SetFieldDependencies($oFieldNode, $aExtraParams);
  640. $oFieldNode->setAttribute('type', $sFieldType);
  641. $oFieldNode->setAttribute('sql', $sSQL);
  642. $oFieldNode->setAttribute('default_value', $defaultValue);
  643. $oFieldNode->setAttribute('is_null_alllowed', $bIsNullAllowed ? 'true' : 'false');
  644. }
  645. protected function _priv_AddFieldAttribute(DOMNode $oFieldNode, $sAttributeCode, $aExtraParams, $bMandatory = false)
  646. {
  647. $value = array_key_exists($sAttributeCode, $aExtraParams) ? $aExtraParams[$sAttributeCode] : '';
  648. if (($value == '') && (!$bMandatory)) return;
  649. $oFieldNode->setAttribute($sAttributeCode, $value);
  650. }
  651. protected function _priv_SetFieldDependencies($oFieldNode, $aExtraParams)
  652. {
  653. $aDeps = array_key_exists('dependencies', $aExtraParams) ? $aExtraParams['dependencies'] : '';
  654. $oDependencies = $oFieldNode->getElementsByTagName('dependencies')->item(0);
  655. // No dependencies before, and no dependencies to add, exit
  656. if (($oDependencies == null) && ($aDeps == '')) return;
  657. // Remove the previous dependencies
  658. $oFieldNode->removeChild($oDependencies);
  659. // If no dependencies, exit
  660. if ($aDeps == '') return;
  661. // Build the new list of dependencies
  662. $oDependencies = $this->oDOMDocument->createElement('dependencies');
  663. foreach($aDeps as $sAttCode)
  664. {
  665. $oDep = $this->oDOMDocument->createElement('attribute');
  666. $oDep->setAttribute('id', $sAttCode);
  667. $oDependencies->addChild($oDep);
  668. }
  669. $oFieldNode->addChild($oDependencies);
  670. }
  671. protected function _priv_SetFieldValues($oFieldNode, $aExtraParams)
  672. {
  673. $aVals = array_key_exists('values', $aExtraParams) ? $aExtraParams['values'] : '';
  674. $oValues = $oFieldNode->getElementsByTagName('values')->item(0);
  675. // No dependencies before, and no dependencies to add, exit
  676. if (($oValues == null) && ($aVals == '')) return;
  677. // Remove the previous dependencies
  678. $oFieldNode->removeChild($oValues);
  679. // If no dependencies, exit
  680. if ($aVals == '') return;
  681. // Build the new list of dependencies
  682. $oValues = $this->oDOMDocument->createElement('values');
  683. foreach($aVals as $sValue)
  684. {
  685. $oVal = $this->oDOMDocument->createElement('value', $sValue);
  686. $oValues->appendChild($oVal);
  687. }
  688. $oFieldNode->appendChild($oValues);
  689. }
  690. public function SetPresentation(DOMNode $oClassNode, $sPresentationCode, $aPresentation)
  691. {
  692. $oPresentation = $oClassNode->getElementsByTagName('presentation')->item(0);
  693. if (!is_object($oPresentation))
  694. {
  695. $oPresentation = $this->oDOMDocument->createElement('presentation');
  696. $oClassNode->appendChild($oPresentation);
  697. }
  698. $oZlist = $oPresentation->getElementsByTagName($sPresentationCode)->item(0);
  699. if (is_object($oZlist))
  700. {
  701. // Remove the previous Zlist
  702. $oPresentation->removeChild($oZlist);
  703. }
  704. // Create the ZList anew
  705. $oZlist = $this->oDOMDocument->createElement($sPresentationCode);
  706. $oPresentation->appendChild($oZlist);
  707. $this->AddZListItem($oZlist, $aPresentation);
  708. $this->_priv_SetFlag($oZlist, 'replaced');
  709. }
  710. protected function AddZListItem($oXMLNode, $value)
  711. {
  712. if (is_array($value))
  713. {
  714. $oXmlItems = $this->oDOMDocument->CreateElement('items');
  715. $oXMLNode->appendChild($oXmlItems);
  716. foreach($value as $key => $item)
  717. {
  718. $oXmlItem = $this->oDOMDocument->CreateElement('item');
  719. $oXmlItems->appendChild($oXmlItem);
  720. if (is_string($key))
  721. {
  722. $oXmlItem->SetAttribute('key', $key);
  723. }
  724. $this->AddZListItem($oXmlItem, $item);
  725. }
  726. }
  727. else
  728. {
  729. $oXmlText = $this->oDOMDocument->CreateTextNode((string) $value);
  730. $oXMLNode->appendChild($oXmlText);
  731. }
  732. }
  733. /**
  734. * List all transitions from a given state
  735. * @param DOMNode $oStateNode The state
  736. * @param bool $bFlattenLayers
  737. * @throws Exception
  738. */
  739. public function ListTransitions(DOMNode $oStateNode, $bFlattenLayers = true)
  740. {
  741. $sXPath = "transitions/transition";
  742. if ($bFlattenLayers)
  743. {
  744. //$sXPath = "transitions/transition[@_operation!='removed']";
  745. }
  746. return $this->GetNodes($sXPath, $oStateNode);
  747. }
  748. /**
  749. * List all states of a given class
  750. * @param DOMNode $oClassNode The class
  751. * @param bool $bFlattenLayers
  752. * @throws Exception
  753. */
  754. public function ListStates(DOMNode $oClassNode, $bFlattenLayers = true)
  755. {
  756. $sXPath = "lifecycle/states/state";
  757. if ($bFlattenLayers)
  758. {
  759. //$sXPath = "lifecycle/states/state[@_operation!='removed']";
  760. }
  761. return $this->GetNodes($sXPath, $oClassNode);
  762. }
  763. /**
  764. * List Zlists from the DOM for a given class
  765. * @param bool $bFlattenLayers
  766. * @throws Exception
  767. */
  768. public function ListZLists(DOMNode $oClassNode, $bFlattenLayers = true)
  769. {
  770. // Not yet implemented !!!
  771. return array();
  772. }
  773. public function ApplyChanges()
  774. {
  775. $oNodes = $this->ListChanges();
  776. foreach($oNodes as $oNode)
  777. {
  778. $sOperation = $oNode->GetAttribute('_alteration');
  779. switch($sOperation)
  780. {
  781. case 'added':
  782. case 'replaced':
  783. // marked as added or modified, just reset the flag
  784. $oNode->removeAttribute('_alteration');
  785. break;
  786. case 'removed':
  787. // marked as deleted, let's remove the node from the tree
  788. $oNode->parentNode->removeChild($oNode);
  789. // TODO!!!!!!!
  790. //unset(self::$aLoadedClasses[$sClass]);
  791. break;
  792. }
  793. if ($oNode->hasAttribute('_old_id'))
  794. {
  795. $oNode->removeAttribute('_old_id');
  796. }
  797. }
  798. }
  799. public function ListChanges()
  800. {
  801. return $this->GetNodes('//*[@_alteration or @_old_id]');
  802. }
  803. /**
  804. * Create path for the delta
  805. * @param DOMDocument oTargetDoc Where to attach the top of the hierarchy
  806. * @param MFElement oNode The node to import with its path
  807. */
  808. protected function ImportNodeAndPathDelta($oTargetDoc, $oNode)
  809. {
  810. // Preliminary: skip the parent if this node is organized hierarchically into the DOM
  811. // The criteria to detect a hierarchy is: same tag + have an id
  812. $oParent = $oNode->parentNode;
  813. while (($oParent instanceof DOMElement) && ($oParent->tagName == $oNode->tagName) && $oParent->hasAttribute('id'))
  814. {
  815. $oParent = $oParent->parentNode;
  816. }
  817. // Recursively create the path for the parent
  818. if ($oParent instanceof DOMElement)
  819. {
  820. $oParentClone = $this->ImportNodeAndPathDelta($oTargetDoc, $oParent);
  821. }
  822. else
  823. {
  824. // We've reached the top let's add the node into the root recipient
  825. $oParentClone = $oTargetDoc;
  826. }
  827. // Look for the node into the parent node
  828. // Note: this is an identified weakness of the algorithm,
  829. // because for each node modified, and each node of its path
  830. // we will have to lookup for the existing entry
  831. // Anyhow, this loop is quite quick to execute because in the delta
  832. // the number of nodes is limited
  833. $oNodeClone = null;
  834. foreach ($oParentClone->childNodes as $oChild)
  835. {
  836. if (($oChild instanceof DOMElement) && ($oChild->tagName == $oNode->tagName))
  837. {
  838. if (!$oNode->hasAttribute('id') || ($oNode->getAttribute('id') == $oChild->getAttribute('id')))
  839. {
  840. $oNodeClone = $oChild;
  841. break;
  842. }
  843. }
  844. }
  845. if (!$oNodeClone)
  846. {
  847. $sAlteration = $oNode->getAttribute('_alteration');
  848. $bCopyContents = ($sAlteration == 'replaced') || ($sAlteration == 'added');
  849. $oNodeClone = $oTargetDoc->importNode($oNode->cloneNode($bCopyContents), $bCopyContents);
  850. $oNodeClone->removeAttribute('_alteration');
  851. if ($oNodeClone->hasAttribute('_old_id'))
  852. {
  853. $oNodeClone->setAttribute('_rename_from', $oNodeClone->getAttribute('_old_id'));
  854. $oNodeClone->removeAttribute('_old_id');
  855. }
  856. switch ($sAlteration)
  857. {
  858. case '':
  859. if ($oNodeClone->hasAttribute('id'))
  860. {
  861. $oNodeClone->setAttribute('_delta', 'must_exist');
  862. }
  863. break;
  864. case 'added':
  865. $oNodeClone->setAttribute('_delta', 'define');
  866. break;
  867. case 'replaced':
  868. $oNodeClone->setAttribute('_delta', 'redefine');
  869. break;
  870. case 'removed':
  871. $oNodeClone->setAttribute('_delta', 'delete');
  872. break;
  873. }
  874. $oParentClone->appendChild($oNodeClone);
  875. }
  876. return $oNodeClone;
  877. }
  878. /**
  879. * Get the text/XML version of the delta
  880. */
  881. public function GetDelta()
  882. {
  883. $oDelta = new MFDocument();
  884. foreach($this->ListChanges() as $oAlteredNode)
  885. {
  886. $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode);
  887. }
  888. return $oDelta->saveXML();
  889. }
  890. /**
  891. * Searches on disk in the root directory for module description files
  892. * and returns an array of MFModules
  893. * @return array Array of MFModules
  894. */
  895. public function FindModules($sSubDirectory = '')
  896. {
  897. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->sRootDir, $sSubDirectory);
  898. $aResult = array();
  899. foreach($aAvailableModules as $sId => $aModule)
  900. {
  901. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  902. }
  903. return $aResult;
  904. }
  905. public function TestAlteration()
  906. {
  907. if (false)
  908. {
  909. echo "<h4>Extrait des données chargées</h4>\n";
  910. $oRoot = $this->GetNodes("//class[@id='Contact']")->item(0);
  911. $oRoot->Dump();
  912. return;
  913. }
  914. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  915. $sOriginalXML =
  916. <<<EOF
  917. $sHeader
  918. <itop_design>
  919. <a id="first a">
  920. <b>Text</b>
  921. <c id="1">
  922. <d>D1</d>
  923. <d>D2</d>
  924. </c>
  925. </a>
  926. <a id="second a">
  927. <parent>first a</parent>
  928. </a>
  929. <a id="third a">
  930. <parent>first a</parent>
  931. <x>blah</x>
  932. </a>
  933. </itop_design>
  934. EOF;
  935. $this->oDOMDocument = new MFDocument();
  936. $this->oDOMDocument->loadXML($sOriginalXML);
  937. echo "<h4>Données d'origine</h4>\n";
  938. $oRoot = $this->GetNodes('//itop_design')->item(0);
  939. $oRoot->Dump();
  940. $oNode = $oRoot->GetNodes('a/b')->item(0);
  941. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  942. $oNode->parentNode->RedefineChildNode($oNew);
  943. $oNode = $oRoot->GetNodes('a/c')->item(0);
  944. $oNew = $this->oDOMDocument->CreateElement('c');
  945. $oNew->setAttribute('id', '1');
  946. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  947. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  948. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  949. $oNode->parentNode->RedefineChildNode($oNew);
  950. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  951. $oNode->Rename('el secundo A');
  952. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  953. $oNode->AddChildNode($oNew);
  954. $oNew = $this->oDOMDocument->CreateElement('a');
  955. $oNew->setAttribute('id', 'new a');
  956. $oNew->appendChild($this->oDOMDocument->CreateElement('parent', 'el secundo A'));
  957. $oNew->appendChild($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  958. $oNode->AddChildNode($oNew);
  959. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  960. $oNode->Delete();
  961. echo "<h4>Après modifications (avec les APIs de ModelFactory)</h4>\n";
  962. $oRoot->Dump();
  963. echo "<h4>Delta calculé</h4>\n";
  964. $sDeltaXML = $this->GetDelta();
  965. echo "<pre>\n";
  966. echo htmlentities($sDeltaXML);
  967. echo "</pre>\n";
  968. echo "<h4>Réitération: on recharge le modèle épuré</h4>\n";
  969. $this->oDOMDocument = new MFDocument();
  970. $this->oDOMDocument->loadXML($sOriginalXML);
  971. $oRoot = $this->GetNodes('//itop_design')->item(0);
  972. $oRoot->Dump();
  973. echo "<h4>On lui applique le delta calculé vu ci-dessus, et on obtient...</h4>\n";
  974. $oDeltaDoc = new MFDocument();
  975. $oDeltaDoc->loadXML($sDeltaXML);
  976. $oDeltaDoc->Dump();
  977. $this->oDOMDocument->Dump();
  978. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  979. $this->LoadDelta($oDeltaDoc, $oDeltaRoot, $this->oDOMDocument);
  980. $oRoot->Dump();
  981. } // TEST !
  982. /**
  983. * Extracts some nodes from the DOM
  984. * @param string $sXPath A XPath expression
  985. * @return DOMNodeList
  986. */
  987. public function GetNodes($sXPath, $oContextNode = null)
  988. {
  989. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode);
  990. }
  991. public function ListActiveChildNodes($sContextXPath, $sTagName)
  992. {
  993. $oContextPath = $this->oRoot->GetNodes($sContextXPath)->item(0);
  994. return $oContextPath->ListActiveChildNodes($sTagName);
  995. }
  996. }
  997. /**
  998. * MFElement: helper to read/change the DOM
  999. * @package ModelFactory
  1000. */
  1001. class MFElement extends DOMElement
  1002. {
  1003. /**
  1004. * Extracts some nodes from the DOM
  1005. * @param string $sXPath A XPath expression
  1006. * @return DOMNodeList
  1007. */
  1008. public function GetNodes($sXPath)
  1009. {
  1010. return $this->ownerDocument->GetNodes($sXPath, $this);
  1011. }
  1012. /**
  1013. * For debugging purposes
  1014. */
  1015. public function Dump()
  1016. {
  1017. echo "<pre>\n";
  1018. echo htmlentities($this->ownerDocument->saveXML($this));
  1019. echo "</pre>\n";
  1020. }
  1021. /**
  1022. * Returns the node directly under the given node
  1023. */
  1024. public function GetUniqueElement($sTagName, $bMustExist = true)
  1025. {
  1026. $oNode = null;
  1027. foreach($this->childNodes as $oChildNode)
  1028. {
  1029. if ($oChildNode->nodeName == $sTagName)
  1030. {
  1031. $oNode = $oChildNode;
  1032. break;
  1033. }
  1034. }
  1035. if ($bMustExist && is_null($oNode))
  1036. {
  1037. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1038. }
  1039. return $oNode;
  1040. }
  1041. /**
  1042. * Returns the node directly under the current node, or null if missing
  1043. */
  1044. public function GetOptionalElement($sTagName)
  1045. {
  1046. return $this->GetUniqueElement($sTagName, false);
  1047. }
  1048. /**
  1049. * Returns the TEXT of the current node (possibly from several subnodes)
  1050. */
  1051. public function GetText($sDefault = null)
  1052. {
  1053. $sText = null;
  1054. foreach($this->childNodes as $oChildNode)
  1055. {
  1056. if ($oChildNode instanceof DOMCharacterData) // Base class of DOMText and DOMCdataSection
  1057. {
  1058. if (is_null($sText)) $sText = '';
  1059. $sText .= $oChildNode->wholeText;
  1060. }
  1061. }
  1062. if (is_null($sText))
  1063. {
  1064. return $sDefault;
  1065. }
  1066. else
  1067. {
  1068. return $sText;
  1069. }
  1070. }
  1071. /**
  1072. * Get the TEXT value from the child node
  1073. */
  1074. public function GetChildText($sTagName, $sDefault = null)
  1075. {
  1076. $sRet = $sDefault;
  1077. if ($oChild = $this->GetOptionalElement($sTagName))
  1078. {
  1079. $sRet = $oChild->GetText($sDefault);
  1080. }
  1081. return $sRet;
  1082. }
  1083. /**
  1084. * Assumes the current node to be either a text or
  1085. * <items>
  1086. * <item [key]="..."]>value<item>
  1087. * <item [key]="..."]>value<item>
  1088. * </items>
  1089. * where value can be the either a text or an array of items... recursively
  1090. * Returns a PHP array
  1091. */
  1092. public function GetNodeAsArrayOfItems()
  1093. {
  1094. $oItems = $this->GetOptionalElement('items');
  1095. if ($oItems)
  1096. {
  1097. $res = array();
  1098. foreach($oItems->childNodes as $oItem)
  1099. {
  1100. // When an attribute is missing
  1101. if ($oItem->hasAttribute('id'))
  1102. {
  1103. $key = $oItem->getAttribute('id');
  1104. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1105. }
  1106. else
  1107. {
  1108. $res[] = $oItem->GetNodeAsArrayOfItems();
  1109. }
  1110. }
  1111. }
  1112. else
  1113. {
  1114. $res = $this->GetText();
  1115. }
  1116. return $res;
  1117. }
  1118. /**
  1119. * Helper to remove child nodes
  1120. */
  1121. public function DeleteChildren()
  1122. {
  1123. while (isset($this->firstChild))
  1124. {
  1125. if ($this->firstChild instanceof MFElement)
  1126. {
  1127. $this->firstChild->DeleteChildren();
  1128. }
  1129. $this->removeChild($this->firstChild);
  1130. }
  1131. }
  1132. /**
  1133. * Find the child node matching the given node
  1134. * @param MFElement $oRefNode The node to search for
  1135. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1136. */
  1137. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1138. {
  1139. return self::FindNode($this, $oRefNode, $sSearchId);
  1140. }
  1141. /**
  1142. * Find the child node matching the given node
  1143. * @param DOMNode $oParent The node to look into (could be DOMDocument, DOMElement...)
  1144. * @param MFElement $oRefNode The node to search for
  1145. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1146. */
  1147. public static function FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1148. {
  1149. $oRes = null;
  1150. if ($oRefNode->hasAttribute('id'))
  1151. {
  1152. // Find the first element having the same tag name and id
  1153. if (!$sSearchId)
  1154. {
  1155. $sSearchId = $oRefNode->getAttribute('id');
  1156. }
  1157. foreach($oParent->childNodes as $oChildNode)
  1158. {
  1159. if (($oChildNode instanceof DOMElement) && ($oChildNode->tagName == $oRefNode->tagName))
  1160. {
  1161. if ($oChildNode->hasAttribute('id') && ($oChildNode->getAttribute('id') == $sSearchId))
  1162. {
  1163. $oRes = $oChildNode;
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. }
  1169. else
  1170. {
  1171. // Get the first one having the same tag name (ignore others)
  1172. foreach($oParent->childNodes as $oChildNode)
  1173. {
  1174. if (($oChildNode instanceof DOMElement) && ($oChildNode->tagName == $oRefNode->tagName))
  1175. {
  1176. $oRes = $oChildNode;
  1177. break;
  1178. }
  1179. }
  1180. }
  1181. return $oRes;
  1182. }
  1183. public function ListActiveChildNodes($sTagName)
  1184. {
  1185. $sXPath = $sTagName."[not(@_alteration) or @_alteration!='removed']";
  1186. return $this->GetNodes($sXPath);
  1187. }
  1188. /**
  1189. * Add a node and set the flags that will be used to compute the delta
  1190. * @param MFElement $oNode The node (including all subnodes) to add
  1191. */
  1192. public function AddChildNode(MFElement $oNode)
  1193. {
  1194. $sFlag = null;
  1195. $oExisting = $this->FindExistingChildNode($oNode);
  1196. if ($oExisting)
  1197. {
  1198. if ($oExisting->getAttribute('_alteration') != 'removed')
  1199. {
  1200. throw new Exception("Attempting to add a node that already exists: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1201. }
  1202. $sFlag = 'replaced';
  1203. $oExisting->ReplaceWith($oNode);
  1204. }
  1205. else
  1206. {
  1207. $this->appendChild($oNode);
  1208. $sFlag = 'added';
  1209. // Iterate through the parents: reset the flag if any of them has a flag set
  1210. for($oParent = $oNode ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1211. {
  1212. if ($oParent->getAttribute('_alteration') != '')
  1213. {
  1214. $sFlag = null;
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. if ($sFlag)
  1220. {
  1221. $oNode->setAttribute('_alteration', $sFlag);
  1222. }
  1223. }
  1224. /**
  1225. * Modify a node and set the flags that will be used to compute the delta
  1226. * @param MFElement $oNode The node (including all subnodes) to set
  1227. */
  1228. public function RedefineChildNode(MFElement $oNode)
  1229. {
  1230. $oExisting = $this->FindExistingChildNode($oNode);
  1231. if (!$oExisting)
  1232. {
  1233. throw new Exception("Attempting to modify a non existing node: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1234. }
  1235. if ($oExisting->getAttribute('_alteration') == 'removed')
  1236. {
  1237. throw new Exception("Attempting to modify a deleted node: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1238. }
  1239. $oExisting->ReplaceWith($oNode);
  1240. if ($oNode->getAttribute('_alteration') != '')
  1241. {
  1242. // added or modified: leave the flag unchanged
  1243. $sFlag = null;
  1244. }
  1245. else
  1246. {
  1247. $sFlag = 'replaced';
  1248. // Iterate through the parents: reset the flag if any of them has a flag set
  1249. for($oParent = $oNode ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1250. {
  1251. if ($oParent->getAttribute('_alteration') != '')
  1252. {
  1253. $sFlag = null;
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. if ($sFlag)
  1259. {
  1260. $oNode->setAttribute('_alteration', $sFlag);
  1261. }
  1262. }
  1263. /**
  1264. * Replaces a node by another one, making sure that recursive nodes are preserved
  1265. * @param MFElement $oNewNode The replacement
  1266. */
  1267. protected function ReplaceWith($oNewNode)
  1268. {
  1269. // Move the classes from the old node into the new one
  1270. foreach($this->GetNodes('class') as $oChild)
  1271. {
  1272. $oNewNode->appendChild($oChild);
  1273. }
  1274. $oParentNode = $this->parentNode;
  1275. $oParentNode->replaceChild($oNewNode, $this);
  1276. }
  1277. /**
  1278. * Remove a node and set the flags that will be used to compute the delta
  1279. */
  1280. public function Delete()
  1281. {
  1282. $oParent = $this->parentNode;
  1283. switch ($this->getAttribute('_alteration'))
  1284. {
  1285. case 'replaced':
  1286. $sFlag = 'removed';
  1287. break;
  1288. case 'added':
  1289. $sFlag = null;
  1290. break;
  1291. case 'removed':
  1292. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1293. default:
  1294. $sFlag = 'removed';
  1295. // Iterate through the parents: reset the flag if any of them has a flag set
  1296. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1297. {
  1298. if ($oParent->getAttribute('_alteration') != '')
  1299. {
  1300. $sFlag = null;
  1301. break;
  1302. }
  1303. }
  1304. }
  1305. if ($sFlag)
  1306. {
  1307. $this->setAttribute('_alteration', $sFlag);
  1308. $this->DeleteChildren();
  1309. }
  1310. else
  1311. {
  1312. // Remove the node entirely
  1313. $oParent->removeChild($this);
  1314. }
  1315. }
  1316. /**
  1317. * Merge the current node into the given container
  1318. *
  1319. * @param DOMNode $oContainer An element or a document
  1320. * @param string $sSearchId The id to consider (could be blank)
  1321. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1322. */
  1323. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1324. {
  1325. $oTargetNode = $oContainer->FindExistingChildNode($this, $sSearchId);
  1326. if ($oTargetNode)
  1327. {
  1328. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1329. {
  1330. if ($bMustExist)
  1331. {
  1332. throw new Exception("XML datamodel loader: found mandatory node $this->tagName/$sSearchId marked as deleted in $oContainer->tagName");
  1333. }
  1334. $oTargetNode = $oContainer->ownerDocument->ImportNode($this, false);
  1335. $oContainer->AddChildNode($oTargetNode);
  1336. }
  1337. }
  1338. else
  1339. {
  1340. if ($bMustExist)
  1341. {
  1342. echo "Dumping parent node<br/>\n";
  1343. $oContainer->Dump();
  1344. throw new Exception("XML datamodel loader: could not find $this->tagName/$sSearchId in $oContainer->tagName");
  1345. }
  1346. $oTargetNode = $oContainer->ownerDocument->ImportNode($this, false);
  1347. $oContainer->AddChildNode($oTargetNode);
  1348. }
  1349. return $oTargetNode;
  1350. }
  1351. /**
  1352. * Renames a node and set the flags that will be used to compute the delta
  1353. * @param String $sNewId The new id
  1354. */
  1355. public function Rename($sId)
  1356. {
  1357. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1358. $this->setAttribute('id', $sId);
  1359. }
  1360. }
  1361. /**
  1362. * MFDocument - formating rules for XML input/output
  1363. * @package ModelFactory
  1364. */
  1365. class MFDocument extends DOMDocument
  1366. {
  1367. public function __construct()
  1368. {
  1369. parent::__construct('1.0', 'UTF-8');
  1370. $this->registerNodeClass('DOMElement', 'MFElement');
  1371. $this->formatOutput = true; // indent (must by loaded with option LIBXML_NOBLANKS)
  1372. $this->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1373. }
  1374. /**
  1375. * Overload of the standard API
  1376. */
  1377. public function load($filename, $options = 0)
  1378. {
  1379. parent::load($filename, LIBXML_NOBLANKS);
  1380. }
  1381. /**
  1382. * Overload of the standard API
  1383. */
  1384. public function loadXML($source, $options = 0)
  1385. {
  1386. parent::loadXML($source, LIBXML_NOBLANKS);
  1387. }
  1388. /**
  1389. * Overload the standard API
  1390. */
  1391. public function saveXML(DOMNode $node = null, $options = 0)
  1392. {
  1393. $oRootNode = $this->firstChild;
  1394. if (!$oRootNode)
  1395. {
  1396. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1397. $this->appendChild($oRootNode);
  1398. }
  1399. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1400. return parent::saveXML();
  1401. }
  1402. /**
  1403. * For debugging purposes
  1404. */
  1405. public function Dump()
  1406. {
  1407. echo "<pre>\n";
  1408. echo htmlentities($this->saveXML());
  1409. echo "</pre>\n";
  1410. }
  1411. /**
  1412. * Find the child node matching the given node
  1413. * @param MFElement $oRefNode The node to search for
  1414. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1415. */
  1416. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1417. {
  1418. return MFElement::FindNode($this, $oRefNode, $sSearchId);
  1419. }
  1420. /**
  1421. * Extracts some nodes from the DOM
  1422. * @param string $sXPath A XPath expression
  1423. * @return DOMNodeList
  1424. */
  1425. public function GetNodes($sXPath, $oContextNode = null)
  1426. {
  1427. $oXPath = new DOMXPath($this);
  1428. if (is_null($oContextNode))
  1429. {
  1430. return $oXPath->query($sXPath);
  1431. }
  1432. else
  1433. {
  1434. return $oXPath->query($sXPath, $oContextNode);
  1435. }
  1436. }
  1437. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  1438. {
  1439. $oXPath = new DOMXPath($this);
  1440. $sXPath .= "[@id='$sId' and(not(@_alteration) or @_alteration!='removed')]";
  1441. if (is_null($oContextNode))
  1442. {
  1443. return $oXPath->query($sXPath);
  1444. }
  1445. else
  1446. {
  1447. return $oXPath->query($sXPath, $oContextNode);
  1448. }
  1449. }
  1450. }