modelfactory.class.inc.php 64 KB

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