modelfactory.class.inc.php 56 KB

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