modelfactory.class.inc.php 47 KB

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