modelfactory.class.inc.php 56 KB

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