modelfactory.class.inc.php 52 KB

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