modelfactory.class.inc.php 50 KB

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