modelfactory.class.inc.php 49 KB

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