modelfactory.class.inc.php 63 KB

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