modelfactory.class.inc.php 53 KB

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