modelfactory.class.inc.php 56 KB

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