modelfactory.class.inc.php 53 KB

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