modelfactory.class.inc.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  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. * Set the value for a given trace attribute
  853. * See MFElement::SetTrace to enable/disable change traces
  854. */
  855. public function SetTraceValue($sAttribute, $sPreviousValue, $sNewValue)
  856. {
  857. // Search into the deleted node as well!
  858. $oNodeSet = $this->oDOMDocument->GetNodes("//*[@$sAttribute='$sPreviousValue']", null, false);
  859. foreach($oNodeSet as $oTouchedNode)
  860. {
  861. $oTouchedNode->setAttribute($sAttribute, $sNewValue);
  862. }
  863. }
  864. /**
  865. * Get the document version of the delta
  866. */
  867. public function GetDeltaDocument($aNodesToIgnore = array(), $aAttributes = null)
  868. {
  869. $oDelta = new MFDocument();
  870. foreach($this->ListChanges() as $oAlteredNode)
  871. {
  872. $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode);
  873. }
  874. foreach($aNodesToIgnore as $sXPath)
  875. {
  876. $oNodesToRemove = $oDelta->GetNodes($sXPath);
  877. foreach($oNodesToRemove as $oNode)
  878. {
  879. if ($oNode instanceof DOMAttr)
  880. {
  881. $oNode->ownerElement->removeAttributeNode($oNode);
  882. }
  883. else
  884. {
  885. $oNode->parentNode->removeChild($oNode);
  886. }
  887. }
  888. }
  889. if ($aAttributes != null)
  890. {
  891. foreach ($aAttributes as $sAttribute => $value)
  892. {
  893. $oDelta->documentElement->setAttribute($sAttribute, $value);
  894. }
  895. }
  896. return $oDelta;
  897. }
  898. /**
  899. * Get the text/XML version of the delta
  900. */
  901. public function GetDelta($aNodesToIgnore = array(), $aAttributes = null)
  902. {
  903. $oDelta = $this->GetDeltaDocument($aNodesToIgnore, $aAttributes);
  904. return $oDelta->saveXML();
  905. }
  906. /**
  907. * Searches on disk in the root directories for module description files
  908. * and returns an array of MFModules
  909. * @return array Array of MFModules
  910. */
  911. public function FindModules()
  912. {
  913. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->aRootDirs);
  914. $aResult = array();
  915. foreach($aAvailableModules as $sId => $aModule)
  916. {
  917. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  918. }
  919. return $aResult;
  920. }
  921. public function TestAlteration()
  922. {
  923. try
  924. {
  925. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  926. $sOriginalXML =
  927. <<<EOF
  928. $sHeader
  929. <itop_design>
  930. <a id="first a">
  931. <b>Text</b>
  932. <c id="1">
  933. <d>D1</d>
  934. <d>D2</d>
  935. </c>
  936. </a>
  937. <a id="second a">
  938. <parent>first a</parent>
  939. </a>
  940. <a id="third a">
  941. <parent>first a</parent>
  942. <x>blah</x>
  943. </a>
  944. </itop_design>
  945. EOF;
  946. $this->oDOMDocument = new MFDocument();
  947. $this->oDOMDocument->loadXML($sOriginalXML);
  948. // DOM Get the original values, then modify its contents by the mean of the API
  949. $oRoot = $this->GetNodes('//itop_design')->item(0);
  950. //$oRoot->Dump();
  951. $sDOMOriginal = $oRoot->Dump(true);
  952. $oNode = $oRoot->GetNodes('a/b')->item(0);
  953. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  954. $oNode->parentNode->RedefineChildNode($oNew);
  955. $oNode = $oRoot->GetNodes('a/c')->item(0);
  956. $oNewC = $this->oDOMDocument->CreateElement('c');
  957. $oNewC->setAttribute('id', '1');
  958. $oNode->parentNode->RedefineChildNode($oNewC);
  959. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  960. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  961. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  962. $oNamedNode = $this->oDOMDocument->CreateElement('z');
  963. $oNamedNode->setAttribute('id', 'abc');
  964. $oNewC->AddChildNode($oNamedNode);
  965. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('r', 'to be replaced'));
  966. // Alter this "modified node", no flag should be set in its subnodes
  967. $oNewC->Rename('blah');
  968. $oNewC->Rename('foo');
  969. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('y', '(no flag)'));
  970. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  971. $oSubNode = $oNewC->GetUniqueElement('z');
  972. $oSubNode->Rename('abcdef');
  973. $oSubNode = $oNewC->GetUniqueElement('x');
  974. $oSubNode->Delete();
  975. $oNewC->RedefineChildNode($this->oDOMDocument->CreateElement('r', 'replacement'));
  976. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  977. $oNode->Rename('el 2o A');
  978. $oNode->Rename('el secundo A');
  979. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  980. $oNode->AddChildNode($oNew);
  981. $oNewA = $this->oDOMDocument->CreateElement('a');
  982. $oNewA->setAttribute('id', 'new a');
  983. $oNode->AddChildNode($oNewA);
  984. $oSubnode = $this->oDOMDocument->CreateElement('parent', 'el secundo A');
  985. $oSubnode->setAttribute('id', 'to be changed');
  986. $oNewA->AddChildNode($oSubnode);
  987. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  988. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  989. // Alter this "new a", as it is new, no flag should be set
  990. $oNewA->Rename('new_a');
  991. $oSubNode = $oNewA->GetUniqueElement('parent');
  992. $oSubNode->Rename('alter ego');
  993. $oNewA->RedefineChildNode($this->oDOMDocument->CreateElement('f', 'dummy data'));
  994. $oSubNode = $oNewA->GetUniqueElement('x');
  995. $oSubNode->Delete();
  996. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  997. $oNode->Delete();
  998. //$oRoot->Dump();
  999. $sDOMModified = $oRoot->Dump(true);
  1000. // Compute the delta
  1001. //
  1002. $sDeltaXML = $this->GetDelta();
  1003. //echo "<pre>\n";
  1004. //echo htmlentities($sDeltaXML);
  1005. //echo "</pre>\n";
  1006. // Reiterating - try to remake the DOM by applying the computed delta
  1007. //
  1008. $this->oDOMDocument = new MFDocument();
  1009. $this->oDOMDocument->loadXML($sOriginalXML);
  1010. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1011. //$oRoot->Dump();
  1012. echo "<h4>Rebuild the DOM - Delta applied...</h4>\n";
  1013. $oDeltaDoc = new MFDocument();
  1014. $oDeltaDoc->loadXML($sDeltaXML);
  1015. //$oDeltaDoc->Dump();
  1016. //$this->oDOMDocument->Dump();
  1017. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  1018. $this->LoadDelta($oDeltaRoot, $this->oDOMDocument);
  1019. //$oRoot->Dump();
  1020. $sDOMRebuilt = $oRoot->Dump(true);
  1021. }
  1022. catch (Exception $e)
  1023. {
  1024. echo "<h1>Exception: ".$e->getMessage()."</h1>\n";
  1025. echo "<pre>\n";
  1026. debug_print_backtrace();
  1027. echo "</pre>\n";
  1028. }
  1029. $sArrStyle = "font-size: 40;";
  1030. echo "<table>\n";
  1031. echo " <tr>\n";
  1032. echo " <td width=\"50%\">\n";
  1033. echo " <h4>DOM - Original values</h4>\n";
  1034. echo " <pre>".htmlentities($sDOMOriginal)."</pre>\n";
  1035. echo " </td>\n";
  1036. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1037. echo " </tr>\n";
  1038. 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";
  1039. echo " <tr>\n";
  1040. echo " <td width=\"50%\">\n";
  1041. echo " <h4>DOM - Altered with various changes</h4>\n";
  1042. echo " <pre>".htmlentities($sDOMModified)."</pre>\n";
  1043. echo " </td>\n";
  1044. echo " <td width=\"50%\">\n";
  1045. echo " <h4>DOM - Rebuilt from the Delta</h4>\n";
  1046. echo " <pre>".htmlentities($sDOMRebuilt)."</pre>\n";
  1047. echo " </td>\n";
  1048. echo " </tr>\n";
  1049. echo " <tr><td align=\"center\"><span style=\"$sArrStyle\">&dArr;</div></td><td align=\"center\"><span style=\"$sArrStyle\">&uArr;</div></td></tr>\n";
  1050. echo " <td width=\"50%\">\n";
  1051. echo " <h4>Delta (Computed by ModelFactory)</h4>\n";
  1052. echo " <pre>".htmlentities($sDeltaXML)."</pre>\n";
  1053. echo " </td>\n";
  1054. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1055. echo " </tr>\n";
  1056. echo "</table>\n";
  1057. } // TEST !
  1058. /**
  1059. * Extracts some nodes from the DOM
  1060. * @param string $sXPath A XPath expression
  1061. * @return DOMNodeList
  1062. */
  1063. public function GetNodes($sXPath, $oContextNode = null)
  1064. {
  1065. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode);
  1066. }
  1067. }
  1068. /**
  1069. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1070. */
  1071. if (!class_exists('DOMElement'))
  1072. {
  1073. class DOMElement {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1074. }
  1075. /**
  1076. * MFElement: helper to read/change the DOM
  1077. * @package ModelFactory
  1078. */
  1079. class MFElement extends DOMElement
  1080. {
  1081. /**
  1082. * Extracts some nodes from the DOM
  1083. * @param string $sXPath A XPath expression
  1084. * @return DOMNodeList
  1085. */
  1086. public function GetNodes($sXPath)
  1087. {
  1088. return $this->ownerDocument->GetNodes($sXPath, $this);
  1089. }
  1090. /**
  1091. * Extracts some nodes from the DOM (active nodes only !!!)
  1092. * @param string $sXPath A XPath expression
  1093. * @return DOMNodeList
  1094. */
  1095. public function GetNodeById($sXPath, $sId)
  1096. {
  1097. return $this->ownerDocument->GetNodeById($sXPath, $sId, $this);
  1098. }
  1099. /**
  1100. * For debugging purposes
  1101. */
  1102. public function Dump($bReturnRes = false)
  1103. {
  1104. $oMFDoc = new MFDocument();
  1105. $oClone = $oMFDoc->importNode($this->cloneNode(true), true);
  1106. $oMFDoc->appendChild($oClone);
  1107. $sXml = $oMFDoc->saveXML($oClone);
  1108. if ($bReturnRes)
  1109. {
  1110. return $sXml;
  1111. }
  1112. else
  1113. {
  1114. echo "<pre>\n";
  1115. echo htmlentities($sXml);
  1116. echo "</pre>\n";
  1117. }
  1118. }
  1119. /**
  1120. * Returns the node directly under the given node
  1121. */
  1122. public function GetUniqueElement($sTagName, $bMustExist = true)
  1123. {
  1124. $oNode = null;
  1125. foreach($this->childNodes as $oChildNode)
  1126. {
  1127. if (($oChildNode->nodeName == $sTagName) && (($oChildNode->getAttribute('_alteration') != 'removed')))
  1128. {
  1129. $oNode = $oChildNode;
  1130. break;
  1131. }
  1132. }
  1133. if ($bMustExist && is_null($oNode))
  1134. {
  1135. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1136. }
  1137. return $oNode;
  1138. }
  1139. /**
  1140. * Returns the node directly under the current node, or null if missing
  1141. */
  1142. public function GetOptionalElement($sTagName)
  1143. {
  1144. return $this->GetUniqueElement($sTagName, false);
  1145. }
  1146. /**
  1147. * Returns the TEXT of the current node (possibly from several subnodes)
  1148. */
  1149. public function GetText($sDefault = null)
  1150. {
  1151. $sText = null;
  1152. foreach($this->childNodes as $oChildNode)
  1153. {
  1154. if ($oChildNode instanceof DOMCharacterData) // Base class of DOMText and DOMCdataSection
  1155. {
  1156. if (is_null($sText)) $sText = '';
  1157. $sText .= $oChildNode->wholeText;
  1158. }
  1159. }
  1160. if (is_null($sText))
  1161. {
  1162. return $sDefault;
  1163. }
  1164. else
  1165. {
  1166. return $sText;
  1167. }
  1168. }
  1169. /**
  1170. * Get the TEXT value from the child node
  1171. */
  1172. public function GetChildText($sTagName, $sDefault = null)
  1173. {
  1174. $sRet = $sDefault;
  1175. if ($oChild = $this->GetOptionalElement($sTagName))
  1176. {
  1177. $sRet = $oChild->GetText($sDefault);
  1178. }
  1179. return $sRet;
  1180. }
  1181. /**
  1182. * Assumes the current node to be either a text or
  1183. * <items>
  1184. * <item [key]="..."]>value<item>
  1185. * <item [key]="..."]>value<item>
  1186. * </items>
  1187. * where value can be the either a text or an array of items... recursively
  1188. * Returns a PHP array
  1189. */
  1190. public function GetNodeAsArrayOfItems($sElementName = 'items')
  1191. {
  1192. $oItems = $this->GetOptionalElement($sElementName);
  1193. if ($oItems)
  1194. {
  1195. $res = array();
  1196. $aRanks = array();
  1197. foreach($oItems->childNodes as $oItem)
  1198. {
  1199. if ($oItem instanceof DOMElement)
  1200. {
  1201. // When an attribute is missing
  1202. if ($oItem->hasAttribute('id'))
  1203. {
  1204. $key = $oItem->getAttribute('id');
  1205. if (array_key_exists($key, $res))
  1206. {
  1207. // Houston!
  1208. throw new DOMFormatException("Tag ".$oItem->getNodePath().", id '$key' already used!!!");
  1209. }
  1210. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1211. }
  1212. else
  1213. {
  1214. $res[] = $oItem->GetNodeAsArrayOfItems();
  1215. }
  1216. $sRank = $oItem->GetChildText('rank');
  1217. if ($sRank != '')
  1218. {
  1219. $aRanks[] = (float) $sRank;
  1220. }
  1221. else
  1222. {
  1223. $aRanks[] = count($aRanks) > 0 ? max($aRanks) + 1 : 0;
  1224. }
  1225. array_multisort($aRanks, $res);
  1226. }
  1227. }
  1228. }
  1229. else
  1230. {
  1231. $res = $this->GetText();
  1232. }
  1233. return $res;
  1234. }
  1235. public function SetNodeAsArrayOfItems($aList)
  1236. {
  1237. $oNewNode = $this->ownerDocument->CreateElement($this->tagName);
  1238. if ($this->getAttribute('id') != '')
  1239. {
  1240. $oNewNode->setAttribute('id', $this->getAttribute('id'));
  1241. }
  1242. self::AddItemToNode($this->ownerDocument, $oNewNode, $aList);
  1243. $this->parentNode->RedefineChildNode($oNewNode);
  1244. }
  1245. protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue)
  1246. {
  1247. if (is_array($itemValue))
  1248. {
  1249. $oXmlItems = $oXmlDoc->CreateElement('items');
  1250. $oXMLNode->AppendChild($oXmlItems);
  1251. foreach($itemValue as $key => $item)
  1252. {
  1253. $oXmlItem = $oXmlDoc->CreateElement('item');
  1254. $oXmlItems->AppendChild($oXmlItem);
  1255. if (is_string($key))
  1256. {
  1257. $oXmlItem->SetAttribute('key', $key);
  1258. }
  1259. self::AddItemToNode($oXmlDoc, $oXmlItem, $item);
  1260. }
  1261. }
  1262. else
  1263. {
  1264. $oXmlText = $oXmlDoc->CreateTextNode((string) $itemValue);
  1265. $oXMLNode->AppendChild($oXmlText);
  1266. }
  1267. }
  1268. /**
  1269. * Helper to remove child nodes
  1270. */
  1271. protected function DeleteChildren()
  1272. {
  1273. while (isset($this->firstChild))
  1274. {
  1275. if ($this->firstChild instanceof MFElement)
  1276. {
  1277. $this->firstChild->DeleteChildren();
  1278. }
  1279. $this->removeChild($this->firstChild);
  1280. }
  1281. }
  1282. /**
  1283. * Find the child node matching the given node.
  1284. * UNSAFE: may return nodes marked as _alteration="removed"
  1285. * A method with the same signature MUST exist in MFDocument for the recursion to work fine
  1286. * @param MFElement $oRefNode The node to search for
  1287. * @param string $sSearchId substitutes to the value of the 'id' attribute
  1288. */
  1289. public function _FindChildNode(MFElement $oRefNode, $sSearchId = null)
  1290. {
  1291. return self::_FindNode($this, $oRefNode, $sSearchId);
  1292. }
  1293. /**
  1294. * Find the child node matching the given node under the specified parent.
  1295. * UNSAFE: may return nodes marked as _alteration="removed"
  1296. * @param DOMNode $oParent
  1297. * @param MFElement $oRefNode
  1298. * @param string $sSearchId
  1299. * @throws Exception
  1300. */
  1301. public static function _FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1302. {
  1303. $oRes = null;
  1304. if ($oParent instanceof DOMDocument)
  1305. {
  1306. $oDoc = $oParent->firstChild->ownerDocument;
  1307. $oRoot = $oParent;
  1308. }
  1309. else
  1310. {
  1311. $oDoc = $oParent->ownerDocument;
  1312. $oRoot = $oParent;
  1313. }
  1314. $oXPath = new DOMXPath($oDoc);
  1315. if ($oRefNode->hasAttribute('id'))
  1316. {
  1317. // Find the first element having the same tag name and id
  1318. if (!$sSearchId)
  1319. {
  1320. $sSearchId = $oRefNode->getAttribute('id');
  1321. }
  1322. $sXPath = './'.$oRefNode->tagName."[@id='$sSearchId']";
  1323. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1324. }
  1325. else
  1326. {
  1327. // Get the first one having the same tag name (ignore others)
  1328. $sXPath = './'.$oRefNode->tagName;
  1329. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1330. }
  1331. return $oRes;
  1332. }
  1333. /**
  1334. * Check if the current node is under a node 'added' or 'altered'
  1335. * Usage: In such a case, the change must not be tracked
  1336. */
  1337. public function IsInDefinition()
  1338. {
  1339. // Iterate through the parents: reset the flag if any of them has a flag set
  1340. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1341. {
  1342. if ($oParent->getAttribute('_alteration') != '')
  1343. {
  1344. return true;
  1345. }
  1346. }
  1347. return false;
  1348. }
  1349. static $aTraceAttributes = null;
  1350. /**
  1351. * Enable/disable the trace on changed nodes
  1352. *
  1353. *@param aAttributes array Array of attributes (key => value) to be added onto any changed node
  1354. */
  1355. static public function SetTrace($aAttributes = null)
  1356. {
  1357. self::$aTraceAttributes = $aAttributes;
  1358. }
  1359. /**
  1360. * Mark the node as touched (if tracing is active)
  1361. */
  1362. public function AddTrace()
  1363. {
  1364. if (!is_null(self::$aTraceAttributes))
  1365. {
  1366. foreach (self::$aTraceAttributes as $sAttribute => $value)
  1367. {
  1368. $this->setAttribute($sAttribute, $value);
  1369. }
  1370. }
  1371. }
  1372. /**
  1373. * Add a node and set the flags that will be used to compute the delta
  1374. * @param MFElement $oNode The node (including all subnodes) to add
  1375. */
  1376. public function AddChildNode(MFElement $oNode)
  1377. {
  1378. // First: cleanup any flag behind the new node, and eventually add trace data
  1379. $oNode->ApplyChanges();
  1380. $oNode->AddTrace();
  1381. $oExisting = $this->_FindChildNode($oNode);
  1382. if ($oExisting)
  1383. {
  1384. if ($oExisting->getAttribute('_alteration') != 'removed')
  1385. {
  1386. throw new Exception("Attempting to add a node that already exists: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1387. }
  1388. $oExisting->ReplaceWith($oNode);
  1389. $sFlag = 'replaced';
  1390. }
  1391. else
  1392. {
  1393. $this->appendChild($oNode);
  1394. $sFlag = 'added';
  1395. }
  1396. if (!$this->IsInDefinition())
  1397. {
  1398. $oNode->setAttribute('_alteration', $sFlag);
  1399. }
  1400. }
  1401. /**
  1402. * Modify a node and set the flags that will be used to compute the delta
  1403. * @param MFElement $oNode The node (including all subnodes) to set
  1404. */
  1405. public function RedefineChildNode(MFElement $oNode, $sSearchId = null)
  1406. {
  1407. // First: cleanup any flag behind the new node, and eventually add trace data
  1408. $oNode->ApplyChanges();
  1409. $oNode->AddTrace();
  1410. $oExisting = $this->_FindChildNode($oNode, $sSearchId);
  1411. if (!$oExisting)
  1412. {
  1413. throw new Exception("Attempting to modify a non existing node: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1414. }
  1415. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1416. if ($sPrevFlag == 'removed')
  1417. {
  1418. throw new Exception("Attempting to modify a deleted node: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1419. }
  1420. $oExisting->ReplaceWith($oNode);
  1421. if (!$this->IsInDefinition())
  1422. {
  1423. if ($sPrevFlag == '')
  1424. {
  1425. $sPrevFlag = 'replaced';
  1426. }
  1427. $oNode->setAttribute('_alteration', $sPrevFlag);
  1428. }
  1429. }
  1430. /**
  1431. * Combination of AddChildNode or RedefineChildNode... it depends
  1432. * This should become the preferred way of doing things (instead of implementing a test + the call to one of the APIs!
  1433. * @param MFElement $oNode The node (including all subnodes) to set
  1434. */
  1435. public function SetChildNode(MFElement $oNode, $sSearchId = null)
  1436. {
  1437. // First: cleanup any flag behind the new node, and eventually add trace data
  1438. $oNode->ApplyChanges();
  1439. $oNode->AddTrace();
  1440. $oExisting = $this->_FindChildNode($oNode, $sSearchId);
  1441. if ($oExisting)
  1442. {
  1443. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1444. if ($sPrevFlag == 'removed')
  1445. {
  1446. $sFlag = 'replaced';
  1447. }
  1448. else
  1449. {
  1450. $sFlag = $sPrevFlag; // added, replaced or ''
  1451. }
  1452. $oExisting->ReplaceWith($oNode);
  1453. }
  1454. else
  1455. {
  1456. $this->appendChild($oNode);
  1457. $sFlag = 'added';
  1458. }
  1459. if (!$this->IsInDefinition())
  1460. {
  1461. if ($sFlag == '')
  1462. {
  1463. $sFlag = 'replaced';
  1464. }
  1465. $oNode->setAttribute('_alteration', $sFlag);
  1466. }
  1467. }
  1468. /**
  1469. * Check that the current node is actually a class node, under classes
  1470. */
  1471. protected function IsClassNode()
  1472. {
  1473. if ($this->tagName == 'class')
  1474. {
  1475. return $this->parentNode->IsClassNode();
  1476. }
  1477. elseif (($this->tagName == 'classes') && ($this->parentNode->tagName == 'itop_design') ) // Beware: classes/class also exists in the group definition
  1478. {
  1479. return true;
  1480. }
  1481. else
  1482. {
  1483. return false;
  1484. }
  1485. }
  1486. /**
  1487. * Replaces a node by another one, making sure that recursive nodes are preserved
  1488. * @param MFElement $oNewNode The replacement
  1489. */
  1490. protected function ReplaceWith($oNewNode)
  1491. {
  1492. // Move the classes from the old node into the new one
  1493. if ($this->IsClassNode())
  1494. {
  1495. foreach($this->GetNodes('class') as $oChild)
  1496. {
  1497. $oNewNode->appendChild($oChild);
  1498. }
  1499. }
  1500. $oParentNode = $this->parentNode;
  1501. $oParentNode->replaceChild($oNewNode, $this);
  1502. }
  1503. /**
  1504. * Remove a node and set the flags that will be used to compute the delta
  1505. */
  1506. public function Delete()
  1507. {
  1508. $oParent = $this->parentNode;
  1509. switch ($this->getAttribute('_alteration'))
  1510. {
  1511. case 'replaced':
  1512. $sFlag = 'removed';
  1513. break;
  1514. case 'added':
  1515. case 'needed':
  1516. $sFlag = null;
  1517. break;
  1518. case 'removed':
  1519. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1520. default:
  1521. $sFlag = 'removed';
  1522. if ($this->IsInDefinition())
  1523. {
  1524. $sFlag = null;
  1525. break;
  1526. }
  1527. }
  1528. if ($sFlag)
  1529. {
  1530. $this->setAttribute('_alteration', $sFlag);
  1531. $this->DeleteChildren();
  1532. // Add trace data
  1533. $this->AddTrace();
  1534. }
  1535. else
  1536. {
  1537. // Remove the node entirely
  1538. $this->parentNode->removeChild($this);
  1539. }
  1540. }
  1541. /**
  1542. * Merge the current node into the given container
  1543. *
  1544. * @param DOMNode $oContainer An element or a document
  1545. * @param string $sSearchId The id to consider (could be blank)
  1546. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1547. */
  1548. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1549. {
  1550. $oTargetNode = $oContainer->_FindChildNode($this, $sSearchId);
  1551. if ($oTargetNode)
  1552. {
  1553. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1554. {
  1555. if ($bMustExist)
  1556. {
  1557. throw new Exception("found mandatory node $this->tagName(id:$sSearchId) marked as deleted in ".$oContainer->getNodePath());
  1558. }
  1559. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1560. // So use this workaround to import a node and its attributes on *any* PHP version
  1561. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1562. $oContainer->AddChildNode($oTargetNode);
  1563. }
  1564. }
  1565. else
  1566. {
  1567. if ($bMustExist)
  1568. {
  1569. echo "Dumping parent node<br/>\n";
  1570. $oContainer->Dump();
  1571. throw new Exception("could not find $this->tagName(id:$sSearchId) in ".$oContainer->getNodePath());
  1572. }
  1573. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1574. // So use this workaround to import a node and its attributes on *any* PHP version
  1575. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1576. $oContainer->AddChildNode($oTargetNode);
  1577. }
  1578. return $oTargetNode;
  1579. }
  1580. /**
  1581. * Renames a node and set the flags that will be used to compute the delta
  1582. * @param String $sNewId The new id
  1583. */
  1584. public function Rename($sId)
  1585. {
  1586. if (($this->getAttribute('_alteration') == 'replaced') || !$this->IsInDefinition())
  1587. {
  1588. $sOriginalId = $this->getAttribute('_old_id');
  1589. if ($sOriginalId == '')
  1590. {
  1591. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1592. }
  1593. else if($sOriginalId == $sId)
  1594. {
  1595. $this->removeAttribute('_old_id');
  1596. }
  1597. }
  1598. $this->setAttribute('id', $sId);
  1599. // Leave a trace of this change
  1600. $this->AddTrace();
  1601. }
  1602. /**
  1603. * Apply extensibility rules onto this node
  1604. * @param array aRules Array of rules (strings)
  1605. * @return void
  1606. */
  1607. public function RestrictExtensibility($aRules)
  1608. {
  1609. $oRulesNode = $this->GetOptionalElement('rules');
  1610. if ($oRulesNode)
  1611. {
  1612. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1613. $aCurrentRules = array_merge($aCurrentRules, $aRules);
  1614. $oRulesNode->SetNodeAsArrayOfItems($aCurrentRules);
  1615. }
  1616. else
  1617. {
  1618. $oNewNode = $this->ownerDocument->CreateElement('rules');
  1619. $this->appendChild($oNewNode);
  1620. $oNewNode->SetNodeAsArrayOfItems($aRules);
  1621. }
  1622. }
  1623. /**
  1624. * Read extensibility rules for this node
  1625. * @return Array of rules (strings)
  1626. */
  1627. public function GetExtensibilityRules()
  1628. {
  1629. $aCurrentRules = array();
  1630. $oRulesNode = $this->GetOptionalElement('rules');
  1631. if ($oRulesNode)
  1632. {
  1633. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1634. }
  1635. return $aCurrentRules;
  1636. }
  1637. /**
  1638. * List changes below a given node (see also MFDocument::ListChanges)
  1639. */
  1640. public function ListChanges()
  1641. {
  1642. // Note: omitting the dot will make the query be global to the whole document!!!
  1643. return $this->ownerDocument->GetNodes('.//*[@_alteration or @_old_id]', $this, false);
  1644. }
  1645. /**
  1646. * List changes below a given node (see also MFDocument::ApplyChanges)
  1647. */
  1648. public function ApplyChanges()
  1649. {
  1650. $oNodes = $this->ListChanges();
  1651. foreach($oNodes as $oNode)
  1652. {
  1653. $sOperation = $oNode->GetAttribute('_alteration');
  1654. switch($sOperation)
  1655. {
  1656. case 'added':
  1657. case 'replaced':
  1658. case 'needed':
  1659. // marked as added or modified, just reset the flag
  1660. $oNode->removeAttribute('_alteration');
  1661. break;
  1662. case 'removed':
  1663. // marked as deleted, let's remove the node from the tree
  1664. $oNode->parentNode->removeChild($oNode);
  1665. break;
  1666. }
  1667. if ($oNode->hasAttribute('_old_id'))
  1668. {
  1669. $oNode->removeAttribute('_old_id');
  1670. }
  1671. }
  1672. }
  1673. }
  1674. /**
  1675. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1676. */
  1677. if (!class_exists('DOMDocument'))
  1678. {
  1679. class DOMDocument {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1680. }
  1681. /**
  1682. * MFDocument - formating rules for XML input/output
  1683. * @package ModelFactory
  1684. */
  1685. class MFDocument extends DOMDocument
  1686. {
  1687. public function __construct()
  1688. {
  1689. parent::__construct('1.0', 'UTF-8');
  1690. $this->registerNodeClass('DOMElement', 'MFElement');
  1691. $this->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1692. $this->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1693. }
  1694. /**
  1695. * Overload of the standard API
  1696. */
  1697. public function load($filename, $options = 0)
  1698. {
  1699. parent::load($filename, LIBXML_NOBLANKS);
  1700. }
  1701. /**
  1702. * Overload of the standard API
  1703. */
  1704. public function loadXML($source, $options = 0)
  1705. {
  1706. parent::loadXML($source, LIBXML_NOBLANKS);
  1707. }
  1708. /**
  1709. * Overload the standard API
  1710. */
  1711. public function saveXML(DOMNode $node = null, $options = 0)
  1712. {
  1713. $oRootNode = $this->firstChild;
  1714. if (!$oRootNode)
  1715. {
  1716. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1717. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1718. $oRootNode->setAttribute('version', ITOP_DESIGN_LATEST_VERSION);
  1719. $this->appendChild($oRootNode);
  1720. }
  1721. return parent::saveXML();
  1722. }
  1723. /**
  1724. * For debugging purposes
  1725. */
  1726. public function Dump($bReturnRes = false)
  1727. {
  1728. $sXml = $this->saveXML();
  1729. if ($bReturnRes)
  1730. {
  1731. return $sXml;
  1732. }
  1733. else
  1734. {
  1735. echo "<pre>\n";
  1736. echo htmlentities($sXml);
  1737. echo "</pre>\n";
  1738. }
  1739. }
  1740. /**
  1741. * Find the child node matching the given node
  1742. * A method with the same signature MUST exist in MFElement for the recursion to work fine
  1743. * @param MFElement $oRefNode The node to search for
  1744. * @param string $sSearchId substitutes to the value of the 'id' attribute
  1745. */
  1746. public function _FindChildNode(MFElement $oRefNode, $sSearchId = null)
  1747. {
  1748. return MFElement::_FindNode($this, $oRefNode, $sSearchId);
  1749. }
  1750. /**
  1751. * Extracts some nodes from the DOM
  1752. * @param string $sXPath A XPath expression
  1753. * @return DOMNodeList
  1754. */
  1755. public function GetNodes($sXPath, $oContextNode = null, $bSafe = true)
  1756. {
  1757. $oXPath = new DOMXPath($this);
  1758. if ($bSafe)
  1759. {
  1760. $sXPath .= "[not(@_alteration) or @_alteration!='removed']";
  1761. }
  1762. if (is_null($oContextNode))
  1763. {
  1764. $oResult = $oXPath->query($sXPath);
  1765. }
  1766. else
  1767. {
  1768. $oResult = $oXPath->query($sXPath, $oContextNode);
  1769. }
  1770. return $oResult;
  1771. }
  1772. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  1773. {
  1774. $oXPath = new DOMXPath($this);
  1775. $sQuotedId = self::XPathQuote($sId);
  1776. $sXPath .= "[@id=$sQuotedId and(not(@_alteration) or @_alteration!='removed')]";
  1777. if (is_null($oContextNode))
  1778. {
  1779. return $oXPath->query($sXPath);
  1780. }
  1781. else
  1782. {
  1783. return $oXPath->query($sXPath, $oContextNode);
  1784. }
  1785. }
  1786. public static function XPathQuote($sValue)
  1787. {
  1788. if (strpos($sValue, '"') !== false)
  1789. {
  1790. $aParts = explode('"', $sValue);
  1791. $sRet = 'concat("'.implode('", \'"\', "', $aParts).'")';
  1792. }
  1793. else
  1794. {
  1795. $sRet = '"'.$sValue.'"';
  1796. }
  1797. return $sRet;
  1798. }
  1799. /**
  1800. * An alternative to getNodePath, that gives the id of nodes instead of the position within the children
  1801. */
  1802. public static function GetItopNodePath($oNode)
  1803. {
  1804. if ($oNode instanceof DOMDocument) return '';
  1805. $sId = $oNode->getAttribute('id');
  1806. $sNodeDesc = ($sId != '') ? $oNode->nodeName.'['.$sId.']' : $oNode->nodeName;
  1807. return self::GetItopNodePath($oNode->parentNode).'/'.$sNodeDesc;
  1808. }
  1809. }