modelfactory.class.inc.php 52 KB

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