modelfactory.class.inc.php 62 KB

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