modelfactory.class.inc.php 41 KB

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