modelfactory.class.inc.php 49 KB

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