modelfactory.class.inc.php 49 KB

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