modelfactory.class.inc.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221
  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. return $this->oRoot->ApplyChanges();
  791. }
  792. public function ListChanges()
  793. {
  794. return $this->oRoot->ListChanges();
  795. }
  796. /**
  797. * Import the node into the delta
  798. */
  799. protected function SetDeltaFlags($oNodeClone)
  800. {
  801. $sAlteration = $oNodeClone->getAttribute('_alteration');
  802. $oNodeClone->removeAttribute('_alteration');
  803. if ($oNodeClone->hasAttribute('_old_id'))
  804. {
  805. $oNodeClone->setAttribute('_rename_from', $oNodeClone->getAttribute('_old_id'));
  806. $oNodeClone->removeAttribute('_old_id');
  807. }
  808. switch ($sAlteration)
  809. {
  810. case '':
  811. if ($oNodeClone->hasAttribute('id'))
  812. {
  813. $oNodeClone->setAttribute('_delta', 'must_exist');
  814. }
  815. break;
  816. case 'added':
  817. $oNodeClone->setAttribute('_delta', 'define');
  818. break;
  819. case 'replaced':
  820. $oNodeClone->setAttribute('_delta', 'redefine');
  821. break;
  822. case 'removed':
  823. $oNodeClone->setAttribute('_delta', 'delete');
  824. break;
  825. case 'needed':
  826. $oNodeClone->setAttribute('_delta', 'define_if_not_exists');
  827. break;
  828. }
  829. return $oNodeClone;
  830. }
  831. /**
  832. * Create path for the delta
  833. * @param Array aMovedClasses The classes that have been moved in the hierarchy (deleted + created elsewhere)
  834. * @param DOMDocument oTargetDoc Where to attach the top of the hierarchy
  835. * @param MFElement oNode The node to import with its path
  836. */
  837. protected function ImportNodeAndPathDelta($aMovedClasses, $oTargetDoc, $oNode)
  838. {
  839. // Preliminary: skip the parent if this node is organized hierarchically into the DOM
  840. // Only class nodes are organized this way
  841. $oParent = $oNode->parentNode;
  842. if ($oNode->IsClassNode())
  843. {
  844. while (($oParent instanceof DOMElement) && ($oParent->IsClassNode()))
  845. {
  846. $oParent = $oParent->parentNode;
  847. }
  848. }
  849. // Recursively create the path for the parent
  850. if ($oParent instanceof DOMElement)
  851. {
  852. $oParentClone = $this->ImportNodeAndPathDelta($aMovedClasses, $oTargetDoc, $oParent);
  853. }
  854. else
  855. {
  856. // We've reached the top let's add the node into the root recipient
  857. $oParentClone = $oTargetDoc;
  858. }
  859. $sAlteration = $oNode->getAttribute('_alteration');
  860. if ($oNode->IsClassNode() && ($sAlteration != ''))
  861. {
  862. // Handle the moved classes
  863. //
  864. // Import the whole root node
  865. $oNodeClone = $oTargetDoc->importNode($oNode->cloneNode(true), true);
  866. $oParentClone->appendChild($oNodeClone);
  867. $this->SetDeltaFlags($oNodeClone);
  868. // Handle the moved classes found under the root node (or the root node itself)
  869. foreach($oNodeClone->GetNodes("descendant-or-self::class[@id]", false) as $oClassNode)
  870. {
  871. if (array_key_exists($oClassNode->getAttribute('id'), $aMovedClasses))
  872. {
  873. if ($sAlteration == 'removed')
  874. {
  875. // Remove that node: this specification will be overriden by the 'replaced' spec (see below)
  876. $oClassNode->parentNode->removeChild($oClassNode);
  877. }
  878. else
  879. {
  880. // Move the class at the root, with the flag 'modified'
  881. $oParentClone->appendChild($oClassNode);
  882. $oClassNode->setAttribute('_alteration', 'replaced');
  883. $this->SetDeltaFlags($oClassNode);
  884. }
  885. }
  886. }
  887. }
  888. else
  889. {
  890. // Look for the node into the parent node
  891. // Note: this is an identified weakness of the algorithm,
  892. // because for each node modified, and each node of its path
  893. // we will have to lookup for the existing entry
  894. // Anyhow, this loop is quite quick to execute because in the delta
  895. // the number of nodes is limited
  896. $oNodeClone = null;
  897. foreach ($oParentClone->childNodes as $oChild)
  898. {
  899. if (($oChild instanceof DOMElement) && ($oChild->tagName == $oNode->tagName))
  900. {
  901. if (!$oNode->hasAttribute('id') || ($oNode->getAttribute('id') == $oChild->getAttribute('id')))
  902. {
  903. $oNodeClone = $oChild;
  904. break;
  905. }
  906. }
  907. }
  908. if (!$oNodeClone)
  909. {
  910. $bCopyContents = ($sAlteration == 'replaced') || ($sAlteration == 'added') || ($sAlteration == 'needed');
  911. $oNodeClone = $oTargetDoc->importNode($oNode->cloneNode($bCopyContents), $bCopyContents);
  912. $this->SetDeltaFlags($oNodeClone);
  913. $oParentClone->appendChild($oNodeClone);
  914. }
  915. }
  916. return $oNodeClone;
  917. }
  918. /**
  919. * Set the value for a given trace attribute
  920. * See MFElement::SetTrace to enable/disable change traces
  921. */
  922. public function SetTraceValue($sAttribute, $sPreviousValue, $sNewValue)
  923. {
  924. // Search into the deleted node as well!
  925. $oNodeSet = $this->oDOMDocument->GetNodes("//*[@$sAttribute='$sPreviousValue']", null, false);
  926. foreach($oNodeSet as $oTouchedNode)
  927. {
  928. $oTouchedNode->setAttribute($sAttribute, $sNewValue);
  929. }
  930. }
  931. /**
  932. * Get the document version of the delta
  933. */
  934. public function GetDeltaDocument($aNodesToIgnore = array(), $aAttributes = null)
  935. {
  936. $oDelta = new MFDocument();
  937. // Handle classes moved from one parent to another
  938. // This will be done in two steps:
  939. // 1) Identify the moved classes (marked as deleted under the original parent, and created under the new parent)
  940. // 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"
  941. $aMovedClasses = array();
  942. foreach($this->GetNodes("/itop_design/classes//class/class[@_alteration='removed']", null, false) as $oNode)
  943. {
  944. $sId = $oNode->getAttribute('id');
  945. if ($this->GetNodes("/itop_design/classes//class/class[@id='$sId']/properties", null, false)->length > 0)
  946. {
  947. $aMovedClasses[$sId] = true;
  948. }
  949. }
  950. foreach($this->ListChanges() as $oAlteredNode)
  951. {
  952. $this->ImportNodeAndPathDelta($aMovedClasses, $oDelta, $oAlteredNode);
  953. }
  954. foreach($aNodesToIgnore as $sXPath)
  955. {
  956. $oNodesToRemove = $oDelta->GetNodes($sXPath);
  957. foreach($oNodesToRemove as $oNode)
  958. {
  959. if ($oNode instanceof DOMAttr)
  960. {
  961. $oNode->ownerElement->removeAttributeNode($oNode);
  962. }
  963. else
  964. {
  965. $oNode->parentNode->removeChild($oNode);
  966. }
  967. }
  968. }
  969. $oNodesToClean = $oDelta->GetNodes('/itop_design//*[@_altered_in]');
  970. foreach($oNodesToClean as $oNode)
  971. {
  972. $oNode->removeAttribute('_altered_in');
  973. }
  974. if ($aAttributes != null)
  975. {
  976. foreach ($aAttributes as $sAttribute => $value)
  977. {
  978. if ($oDelta->documentElement) // yes, this may happen when still no change has been performed (and a module has been selected for installation)
  979. {
  980. $oDelta->documentElement->setAttribute($sAttribute, $value);
  981. }
  982. }
  983. }
  984. return $oDelta;
  985. }
  986. /**
  987. * Get the text/XML version of the delta
  988. */
  989. public function GetDelta($aNodesToIgnore = array(), $aAttributes = null)
  990. {
  991. $oDelta = $this->GetDeltaDocument($aNodesToIgnore, $aAttributes);
  992. return $oDelta->saveXML();
  993. }
  994. /**
  995. * Searches on disk in the root directories for module description files
  996. * and returns an array of MFModules
  997. * @return array Array of MFModules
  998. */
  999. public function FindModules()
  1000. {
  1001. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->aRootDirs);
  1002. $aAvailableModules = ModuleDiscovery::RemoveDuplicateModules($aAvailableModules);
  1003. $aResult = array();
  1004. foreach($aAvailableModules as $sId => $aModule)
  1005. {
  1006. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  1007. }
  1008. return $aResult;
  1009. }
  1010. public function TestAlteration()
  1011. {
  1012. try
  1013. {
  1014. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  1015. $sOriginalXML =
  1016. <<<EOF
  1017. $sHeader
  1018. <itop_design>
  1019. <a id="first a">
  1020. <b>Text</b>
  1021. <c id="1">
  1022. <d>D1</d>
  1023. <d>D2</d>
  1024. </c>
  1025. </a>
  1026. <a id="second a">
  1027. <parent>first a</parent>
  1028. </a>
  1029. <a id="third a">
  1030. <parent>first a</parent>
  1031. <x>blah</x>
  1032. </a>
  1033. </itop_design>
  1034. EOF;
  1035. $this->oDOMDocument = new MFDocument();
  1036. $this->oDOMDocument->loadXML($sOriginalXML);
  1037. // DOM Get the original values, then modify its contents by the mean of the API
  1038. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1039. //$oRoot->Dump();
  1040. $sDOMOriginal = $oRoot->Dump(true);
  1041. $oNode = $oRoot->GetNodes('a/b')->item(0);
  1042. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  1043. $oNode->parentNode->RedefineChildNode($oNew);
  1044. $oNode = $oRoot->GetNodes('a/c')->item(0);
  1045. $oNewC = $this->oDOMDocument->CreateElement('c');
  1046. $oNewC->setAttribute('id', '1');
  1047. $oNode->parentNode->RedefineChildNode($oNewC);
  1048. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  1049. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  1050. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  1051. $oNamedNode = $this->oDOMDocument->CreateElement('z');
  1052. $oNamedNode->setAttribute('id', 'abc');
  1053. $oNewC->AddChildNode($oNamedNode);
  1054. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('r', 'to be replaced'));
  1055. // Alter this "modified node", no flag should be set in its subnodes
  1056. $oNewC->Rename('blah');
  1057. $oNewC->Rename('foo');
  1058. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('y', '(no flag)'));
  1059. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1060. $oSubNode = $oNewC->GetUniqueElement('z');
  1061. $oSubNode->Rename('abcdef');
  1062. $oSubNode = $oNewC->GetUniqueElement('x');
  1063. $oSubNode->Delete();
  1064. $oNewC->RedefineChildNode($this->oDOMDocument->CreateElement('r', 'replacement'));
  1065. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  1066. $oNode->Rename('el 2o A');
  1067. $oNode->Rename('el secundo A');
  1068. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  1069. $oNode->AddChildNode($oNew);
  1070. $oNewA = $this->oDOMDocument->CreateElement('a');
  1071. $oNewA->setAttribute('id', 'new a');
  1072. $oNode->AddChildNode($oNewA);
  1073. $oSubnode = $this->oDOMDocument->CreateElement('parent', 'el secundo A');
  1074. $oSubnode->setAttribute('id', 'to be changed');
  1075. $oNewA->AddChildNode($oSubnode);
  1076. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  1077. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1078. // Alter this "new a", as it is new, no flag should be set
  1079. $oNewA->Rename('new_a');
  1080. $oSubNode = $oNewA->GetUniqueElement('parent');
  1081. $oSubNode->Rename('alter ego');
  1082. $oNewA->RedefineChildNode($this->oDOMDocument->CreateElement('f', 'dummy data'));
  1083. $oSubNode = $oNewA->GetUniqueElement('x');
  1084. $oSubNode->Delete();
  1085. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  1086. $oNode->Delete();
  1087. //$oRoot->Dump();
  1088. $sDOMModified = $oRoot->Dump(true);
  1089. // Compute the delta
  1090. //
  1091. $sDeltaXML = $this->GetDelta();
  1092. //echo "<pre>\n";
  1093. //echo htmlentities($sDeltaXML);
  1094. //echo "</pre>\n";
  1095. // Reiterating - try to remake the DOM by applying the computed delta
  1096. //
  1097. $this->oDOMDocument = new MFDocument();
  1098. $this->oDOMDocument->loadXML($sOriginalXML);
  1099. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1100. //$oRoot->Dump();
  1101. echo "<h4>Rebuild the DOM - Delta applied...</h4>\n";
  1102. $oDeltaDoc = new MFDocument();
  1103. $oDeltaDoc->loadXML($sDeltaXML);
  1104. //$oDeltaDoc->Dump();
  1105. //$this->oDOMDocument->Dump();
  1106. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  1107. $this->LoadDelta($oDeltaRoot, $this->oDOMDocument);
  1108. //$oRoot->Dump();
  1109. $sDOMRebuilt = $oRoot->Dump(true);
  1110. }
  1111. catch (Exception $e)
  1112. {
  1113. echo "<h1>Exception: ".$e->getMessage()."</h1>\n";
  1114. echo "<pre>\n";
  1115. debug_print_backtrace();
  1116. echo "</pre>\n";
  1117. }
  1118. $sArrStyle = "font-size: 40;";
  1119. echo "<table>\n";
  1120. echo " <tr>\n";
  1121. echo " <td width=\"50%\">\n";
  1122. echo " <h4>DOM - Original values</h4>\n";
  1123. echo " <pre>".htmlentities($sDOMOriginal)."</pre>\n";
  1124. echo " </td>\n";
  1125. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1126. echo " </tr>\n";
  1127. 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";
  1128. echo " <tr>\n";
  1129. echo " <td width=\"50%\">\n";
  1130. echo " <h4>DOM - Altered with various changes</h4>\n";
  1131. echo " <pre>".htmlentities($sDOMModified)."</pre>\n";
  1132. echo " </td>\n";
  1133. echo " <td width=\"50%\">\n";
  1134. echo " <h4>DOM - Rebuilt from the Delta</h4>\n";
  1135. echo " <pre>".htmlentities($sDOMRebuilt)."</pre>\n";
  1136. echo " </td>\n";
  1137. echo " </tr>\n";
  1138. echo " <tr><td align=\"center\"><span style=\"$sArrStyle\">&dArr;</div></td><td align=\"center\"><span style=\"$sArrStyle\">&uArr;</div></td></tr>\n";
  1139. echo " <td width=\"50%\">\n";
  1140. echo " <h4>Delta (Computed by ModelFactory)</h4>\n";
  1141. echo " <pre>".htmlentities($sDeltaXML)."</pre>\n";
  1142. echo " </td>\n";
  1143. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1144. echo " </tr>\n";
  1145. echo "</table>\n";
  1146. } // TEST !
  1147. /**
  1148. * Extracts some nodes from the DOM
  1149. * @param string $sXPath A XPath expression
  1150. * @return DOMNodeList
  1151. */
  1152. public function GetNodes($sXPath, $oContextNode = null, $bSafe = true)
  1153. {
  1154. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode, $bSafe);
  1155. }
  1156. }
  1157. /**
  1158. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1159. */
  1160. if (!class_exists('DOMElement'))
  1161. {
  1162. class DOMElement {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1163. }
  1164. /**
  1165. * MFElement: helper to read/change the DOM
  1166. * @package ModelFactory
  1167. */
  1168. class MFElement extends Combodo\iTop\DesignElement
  1169. {
  1170. /**
  1171. * Extracts some nodes from the DOM
  1172. * @param string $sXPath A XPath expression
  1173. * @return DOMNodeList
  1174. */
  1175. public function GetNodes($sXPath, $bSafe = true)
  1176. {
  1177. return $this->ownerDocument->GetNodes($sXPath, $this, $bSafe);
  1178. }
  1179. /**
  1180. * Extracts some nodes from the DOM (active nodes only !!!)
  1181. * @param string $sXPath A XPath expression
  1182. * @return DOMNodeList
  1183. */
  1184. public function GetNodeById($sXPath, $sId)
  1185. {
  1186. return $this->ownerDocument->GetNodeById($sXPath, $sId, $this);
  1187. }
  1188. /**
  1189. * Returns the node directly under the given node
  1190. */
  1191. public function GetUniqueElement($sTagName, $bMustExist = true)
  1192. {
  1193. $oNode = null;
  1194. foreach($this->childNodes as $oChildNode)
  1195. {
  1196. if (($oChildNode->nodeName == $sTagName) && (($oChildNode->getAttribute('_alteration') != 'removed')))
  1197. {
  1198. $oNode = $oChildNode;
  1199. break;
  1200. }
  1201. }
  1202. if ($bMustExist && is_null($oNode))
  1203. {
  1204. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1205. }
  1206. return $oNode;
  1207. }
  1208. /**
  1209. * Assumes the current node to be either a text or
  1210. * <items>
  1211. * <item [key]="..."]>value<item>
  1212. * <item [key]="..."]>value<item>
  1213. * </items>
  1214. * where value can be the either a text or an array of items... recursively
  1215. * Returns a PHP array
  1216. */
  1217. public function GetNodeAsArrayOfItems($sElementName = 'items')
  1218. {
  1219. $oItems = $this->GetOptionalElement($sElementName);
  1220. if ($oItems)
  1221. {
  1222. $res = array();
  1223. $aRanks = array();
  1224. foreach($oItems->childNodes as $oItem)
  1225. {
  1226. if ($oItem instanceof DOMElement)
  1227. {
  1228. // When an attribute is missing
  1229. if ($oItem->hasAttribute('id'))
  1230. {
  1231. $key = $oItem->getAttribute('id');
  1232. if (array_key_exists($key, $res))
  1233. {
  1234. // Houston!
  1235. throw new DOMFormatException("id '$key' already used", null, null, $oItem);
  1236. }
  1237. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1238. }
  1239. else
  1240. {
  1241. $res[] = $oItem->GetNodeAsArrayOfItems();
  1242. }
  1243. $sRank = $oItem->GetChildText('rank');
  1244. if ($sRank != '')
  1245. {
  1246. $aRanks[] = (float) $sRank;
  1247. }
  1248. else
  1249. {
  1250. $aRanks[] = count($aRanks) > 0 ? max($aRanks) + 1 : 0;
  1251. }
  1252. array_multisort($aRanks, $res);
  1253. }
  1254. }
  1255. }
  1256. else
  1257. {
  1258. $res = $this->GetText();
  1259. }
  1260. return $res;
  1261. }
  1262. public function SetNodeAsArrayOfItems($aList)
  1263. {
  1264. $oNewNode = $this->ownerDocument->CreateElement($this->tagName);
  1265. if ($this->getAttribute('id') != '')
  1266. {
  1267. $oNewNode->setAttribute('id', $this->getAttribute('id'));
  1268. }
  1269. self::AddItemToNode($this->ownerDocument, $oNewNode, $aList);
  1270. $this->parentNode->RedefineChildNode($oNewNode);
  1271. }
  1272. protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue)
  1273. {
  1274. if (is_array($itemValue))
  1275. {
  1276. $oXmlItems = $oXmlDoc->CreateElement('items');
  1277. $oXMLNode->AppendChild($oXmlItems);
  1278. foreach($itemValue as $key => $item)
  1279. {
  1280. $oXmlItem = $oXmlDoc->CreateElement('item');
  1281. $oXmlItems->AppendChild($oXmlItem);
  1282. if (is_string($key))
  1283. {
  1284. $oXmlItem->SetAttribute('key', $key);
  1285. }
  1286. self::AddItemToNode($oXmlDoc, $oXmlItem, $item);
  1287. }
  1288. }
  1289. else
  1290. {
  1291. $oXmlText = $oXmlDoc->CreateTextNode((string) $itemValue);
  1292. $oXMLNode->AppendChild($oXmlText);
  1293. }
  1294. }
  1295. /**
  1296. * Helper to remove child nodes
  1297. */
  1298. protected function DeleteChildren()
  1299. {
  1300. while (isset($this->firstChild))
  1301. {
  1302. if ($this->firstChild instanceof MFElement)
  1303. {
  1304. $this->firstChild->DeleteChildren();
  1305. }
  1306. $this->removeChild($this->firstChild);
  1307. }
  1308. }
  1309. /**
  1310. * Find the child node matching the given node.
  1311. * UNSAFE: may return nodes marked as _alteration="removed"
  1312. * A method with the same signature MUST exist in MFDocument for the recursion to work fine
  1313. * @param MFElement $oRefNode The node to search for
  1314. * @param string $sSearchId substitutes to the value of the 'id' attribute
  1315. */
  1316. public function _FindChildNode(MFElement $oRefNode, $sSearchId = null)
  1317. {
  1318. return self::_FindNode($this, $oRefNode, $sSearchId);
  1319. }
  1320. /**
  1321. * Find the child node matching the given node under the specified parent.
  1322. * UNSAFE: may return nodes marked as _alteration="removed"
  1323. * @param DOMNode $oParent
  1324. * @param MFElement $oRefNode
  1325. * @param string $sSearchId
  1326. * @throws Exception
  1327. */
  1328. public static function _FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1329. {
  1330. $oRes = null;
  1331. if ($oParent instanceof DOMDocument)
  1332. {
  1333. $oDoc = $oParent->firstChild->ownerDocument;
  1334. $oRoot = $oParent;
  1335. }
  1336. else
  1337. {
  1338. $oDoc = $oParent->ownerDocument;
  1339. $oRoot = $oParent;
  1340. }
  1341. $oXPath = new DOMXPath($oDoc);
  1342. if ($oRefNode->hasAttribute('id'))
  1343. {
  1344. // Find the first element having the same tag name and id
  1345. if (!$sSearchId)
  1346. {
  1347. $sSearchId = $oRefNode->getAttribute('id');
  1348. }
  1349. $sXPath = './'.$oRefNode->tagName."[@id='$sSearchId']";
  1350. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1351. }
  1352. else
  1353. {
  1354. // Get the first one having the same tag name (ignore others)
  1355. $sXPath = './'.$oRefNode->tagName;
  1356. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1357. }
  1358. return $oRes;
  1359. }
  1360. /**
  1361. * Check if the current node is under a node 'added' or 'altered'
  1362. * Usage: In such a case, the change must not be tracked
  1363. */
  1364. public function IsInDefinition()
  1365. {
  1366. // Iterate through the parents: reset the flag if any of them has a flag set
  1367. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1368. {
  1369. if ($oParent->getAttribute('_alteration') != '')
  1370. {
  1371. return true;
  1372. }
  1373. }
  1374. return false;
  1375. }
  1376. /**
  1377. * Check if the given node is (a child of a node) altered by one of the supplied modules
  1378. * @param array $aModules The list of module codes to consider
  1379. * @return boolean
  1380. */
  1381. public function IsAlteredByModule($aModules)
  1382. {
  1383. // Iterate through the parents: reset the flag if any of them has a flag set
  1384. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1385. {
  1386. if (in_array($oParent->getAttribute('_altered_in'), $aModules))
  1387. {
  1388. return true;
  1389. }
  1390. }
  1391. return false;
  1392. }
  1393. static $aTraceAttributes = null;
  1394. /**
  1395. * Enable/disable the trace on changed nodes
  1396. *
  1397. *@param aAttributes array Array of attributes (key => value) to be added onto any changed node
  1398. */
  1399. static public function SetTrace($aAttributes = null)
  1400. {
  1401. self::$aTraceAttributes = $aAttributes;
  1402. }
  1403. /**
  1404. * Mark the node as touched (if tracing is active)
  1405. */
  1406. public function AddTrace()
  1407. {
  1408. if (!is_null(self::$aTraceAttributes))
  1409. {
  1410. foreach (self::$aTraceAttributes as $sAttribute => $value)
  1411. {
  1412. $this->setAttribute($sAttribute, $value);
  1413. }
  1414. }
  1415. }
  1416. /**
  1417. * Add a node and set the flags that will be used to compute the delta
  1418. * @param MFElement $oNode The node (including all subnodes) to add
  1419. */
  1420. public function AddChildNode(MFElement $oNode)
  1421. {
  1422. // First: cleanup any flag behind the new node, and eventually add trace data
  1423. $oNode->ApplyChanges();
  1424. $oNode->AddTrace();
  1425. $oExisting = $this->_FindChildNode($oNode);
  1426. if ($oExisting)
  1427. {
  1428. if ($oExisting->getAttribute('_alteration') != 'removed')
  1429. {
  1430. throw new Exception(MFDocument::GetItopNodePath($oNode).' at line '.$oNode->getLineNo().": could not be added (already exists)");
  1431. }
  1432. $oExisting->ReplaceWith($oNode);
  1433. $sFlag = 'replaced';
  1434. }
  1435. else
  1436. {
  1437. $this->appendChild($oNode);
  1438. $sFlag = 'added';
  1439. }
  1440. if (!$this->IsInDefinition())
  1441. {
  1442. $oNode->setAttribute('_alteration', $sFlag);
  1443. }
  1444. }
  1445. /**
  1446. * Modify a node and set the flags that will be used to compute the delta
  1447. * @param MFElement $oNode The node (including all subnodes) to set
  1448. */
  1449. public function RedefineChildNode(MFElement $oNode, $sSearchId = null)
  1450. {
  1451. // First: cleanup any flag behind the new node, and eventually add trace data
  1452. $oNode->ApplyChanges();
  1453. $oNode->AddTrace();
  1454. $oExisting = $this->_FindChildNode($oNode, $sSearchId);
  1455. if (!$oExisting)
  1456. {
  1457. $sSourceNode = MFDocument::GetItopNodePath($this)."/".$oNode->tagName.(is_null($sSearchId) ? '' : "[$sSearchId]").' at line '.$this->getLineNo();
  1458. throw new Exception($sSourceNode.": could not be modified (not found)");
  1459. }
  1460. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1461. if ($sPrevFlag == 'removed')
  1462. {
  1463. $sSourceNode = MFDocument::GetItopNodePath($this)."/".$oNode->tagName.(is_null($sSearchId) ? '' : "[$sSearchId]").' at line '.$this->getLineNo();
  1464. throw new Exception($sSourceNode.": could not be modified (marked as deleted)");
  1465. }
  1466. $oExisting->ReplaceWith($oNode);
  1467. if (!$this->IsInDefinition())
  1468. {
  1469. if ($sPrevFlag == '')
  1470. {
  1471. $sPrevFlag = 'replaced';
  1472. }
  1473. $oNode->setAttribute('_alteration', $sPrevFlag);
  1474. }
  1475. }
  1476. /**
  1477. * Combination of AddChildNode or RedefineChildNode... it depends
  1478. * This should become the preferred way of doing things (instead of implementing a test + the call to one of the APIs!
  1479. * @param MFElement $oNode The node (including all subnodes) to set
  1480. */
  1481. public function SetChildNode(MFElement $oNode, $sSearchId = null)
  1482. {
  1483. // First: cleanup any flag behind the new node, and eventually add trace data
  1484. $oNode->ApplyChanges();
  1485. $oNode->AddTrace();
  1486. $oExisting = $this->_FindChildNode($oNode, $sSearchId);
  1487. if ($oExisting)
  1488. {
  1489. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1490. if ($sPrevFlag == 'removed')
  1491. {
  1492. $sFlag = 'replaced';
  1493. }
  1494. else
  1495. {
  1496. $sFlag = $sPrevFlag; // added, replaced or ''
  1497. }
  1498. $oExisting->ReplaceWith($oNode);
  1499. }
  1500. else
  1501. {
  1502. $this->appendChild($oNode);
  1503. $sFlag = 'added';
  1504. }
  1505. if (!$this->IsInDefinition())
  1506. {
  1507. if ($sFlag == '')
  1508. {
  1509. $sFlag = 'replaced';
  1510. }
  1511. $oNode->setAttribute('_alteration', $sFlag);
  1512. }
  1513. }
  1514. /**
  1515. * Check that the current node is actually a class node, under classes
  1516. */
  1517. public function IsClassNode()
  1518. {
  1519. if ($this->tagName == 'class')
  1520. {
  1521. if (($this->parentNode->tagName == 'classes') && ($this->parentNode->parentNode->tagName == 'itop_design') ) // Beware: classes/class also exists in the group definition
  1522. {
  1523. return true;
  1524. }
  1525. return $this->parentNode->IsClassNode();
  1526. }
  1527. else
  1528. {
  1529. return false;
  1530. }
  1531. }
  1532. /**
  1533. * Replaces a node by another one, making sure that recursive nodes are preserved
  1534. * @param MFElement $oNewNode The replacement
  1535. */
  1536. protected function ReplaceWith($oNewNode)
  1537. {
  1538. // Move the classes from the old node into the new one
  1539. if ($this->IsClassNode())
  1540. {
  1541. foreach($this->GetNodes('class') as $oChild)
  1542. {
  1543. $oNewNode->appendChild($oChild);
  1544. }
  1545. }
  1546. $oParentNode = $this->parentNode;
  1547. $oParentNode->replaceChild($oNewNode, $this);
  1548. }
  1549. /**
  1550. * Remove a node and set the flags that will be used to compute the delta
  1551. */
  1552. public function Delete()
  1553. {
  1554. $oParent = $this->parentNode;
  1555. switch ($this->getAttribute('_alteration'))
  1556. {
  1557. case 'replaced':
  1558. $sFlag = 'removed';
  1559. break;
  1560. case 'added':
  1561. case 'needed':
  1562. $sFlag = null;
  1563. break;
  1564. case 'removed':
  1565. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1566. default:
  1567. $sFlag = 'removed';
  1568. if ($this->IsInDefinition())
  1569. {
  1570. $sFlag = null;
  1571. break;
  1572. }
  1573. }
  1574. if ($sFlag)
  1575. {
  1576. $this->setAttribute('_alteration', $sFlag);
  1577. $this->DeleteChildren();
  1578. // Add trace data
  1579. $this->AddTrace();
  1580. }
  1581. else
  1582. {
  1583. // Remove the node entirely
  1584. $this->parentNode->removeChild($this);
  1585. }
  1586. }
  1587. /**
  1588. * Merge the current node into the given container
  1589. *
  1590. * @param DOMNode $oContainer An element or a document
  1591. * @param string $sSearchId The id to consider (could be blank)
  1592. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1593. */
  1594. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1595. {
  1596. $oTargetNode = $oContainer->_FindChildNode($this, $sSearchId);
  1597. if ($oTargetNode)
  1598. {
  1599. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1600. {
  1601. if ($bMustExist)
  1602. {
  1603. throw new Exception(MFDocument::GetItopNodePath($this).' at line '.$this->getLineNo().": could not be found (marked as deleted)");
  1604. }
  1605. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1606. // So use this workaround to import a node and its attributes on *any* PHP version
  1607. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1608. $oContainer->AddChildNode($oTargetNode);
  1609. }
  1610. }
  1611. else
  1612. {
  1613. if ($bMustExist)
  1614. {
  1615. echo "Dumping parent node<br/>\n";
  1616. $oContainer->Dump();
  1617. throw new Exception(MFDocument::GetItopNodePath($this).' at line '.$this->getLineNo().": could not be found");
  1618. }
  1619. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1620. // So use this workaround to import a node and its attributes on *any* PHP version
  1621. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1622. $oContainer->AddChildNode($oTargetNode);
  1623. }
  1624. return $oTargetNode;
  1625. }
  1626. /**
  1627. * Renames a node and set the flags that will be used to compute the delta
  1628. * @param String $sNewId The new id
  1629. */
  1630. public function Rename($sId)
  1631. {
  1632. if (($this->getAttribute('_alteration') == 'replaced') || !$this->IsInDefinition())
  1633. {
  1634. $sOriginalId = $this->getAttribute('_old_id');
  1635. if ($sOriginalId == '')
  1636. {
  1637. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1638. }
  1639. else if($sOriginalId == $sId)
  1640. {
  1641. $this->removeAttribute('_old_id');
  1642. }
  1643. }
  1644. $this->setAttribute('id', $sId);
  1645. // Leave a trace of this change
  1646. $this->AddTrace();
  1647. }
  1648. /**
  1649. * Apply extensibility rules onto this node
  1650. * @param array aRules Array of rules (strings)
  1651. * @return void
  1652. */
  1653. public function RestrictExtensibility($aRules)
  1654. {
  1655. $oRulesNode = $this->GetOptionalElement('rules');
  1656. if ($oRulesNode)
  1657. {
  1658. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1659. $aCurrentRules = array_merge($aCurrentRules, $aRules);
  1660. $oRulesNode->SetNodeAsArrayOfItems($aCurrentRules);
  1661. }
  1662. else
  1663. {
  1664. $oNewNode = $this->ownerDocument->CreateElement('rules');
  1665. $this->appendChild($oNewNode);
  1666. $oNewNode->SetNodeAsArrayOfItems($aRules);
  1667. }
  1668. }
  1669. /**
  1670. * Read extensibility rules for this node
  1671. * @return Array of rules (strings)
  1672. */
  1673. public function GetExtensibilityRules()
  1674. {
  1675. $aCurrentRules = array();
  1676. $oRulesNode = $this->GetOptionalElement('rules');
  1677. if ($oRulesNode)
  1678. {
  1679. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1680. }
  1681. return $aCurrentRules;
  1682. }
  1683. /**
  1684. * List changes below a given node (see also MFDocument::ListChanges)
  1685. */
  1686. public function ListChanges()
  1687. {
  1688. // Note: omitting the dot will make the query be global to the whole document!!!
  1689. return $this->ownerDocument->GetNodes('.//*[@_alteration or @_old_id]', $this, false);
  1690. }
  1691. /**
  1692. * List changes below a given node (see also MFDocument::ApplyChanges)
  1693. */
  1694. public function ApplyChanges()
  1695. {
  1696. $oNodes = $this->ListChanges();
  1697. foreach($oNodes as $oNode)
  1698. {
  1699. $sOperation = $oNode->GetAttribute('_alteration');
  1700. switch($sOperation)
  1701. {
  1702. case 'added':
  1703. case 'replaced':
  1704. case 'needed':
  1705. // marked as added or modified, just reset the flag
  1706. $oNode->removeAttribute('_alteration');
  1707. break;
  1708. case 'removed':
  1709. // marked as deleted, let's remove the node from the tree
  1710. $oNode->parentNode->removeChild($oNode);
  1711. break;
  1712. }
  1713. if ($oNode->hasAttribute('_old_id'))
  1714. {
  1715. $oNode->removeAttribute('_old_id');
  1716. }
  1717. }
  1718. }
  1719. }
  1720. /**
  1721. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1722. */
  1723. if (!class_exists('DOMDocument'))
  1724. {
  1725. class DOMDocument {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1726. }
  1727. /**
  1728. * MFDocument - formating rules for XML input/output
  1729. * @package ModelFactory
  1730. */
  1731. class MFDocument extends \Combodo\iTop\DesignDocument
  1732. {
  1733. /**
  1734. * Overloadable. Called prior to data loading.
  1735. */
  1736. protected function Init()
  1737. {
  1738. parent::Init();
  1739. $this->registerNodeClass('DOMElement', 'MFElement');
  1740. }
  1741. /**
  1742. * Overload the standard API
  1743. */
  1744. public function saveXML(DOMNode $node = null, $options = 0)
  1745. {
  1746. $oRootNode = $this->firstChild;
  1747. if (!$oRootNode)
  1748. {
  1749. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1750. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1751. $oRootNode->setAttribute('version', ITOP_DESIGN_LATEST_VERSION);
  1752. $this->appendChild($oRootNode);
  1753. }
  1754. return parent::saveXML();
  1755. }
  1756. /**
  1757. * Overload createElement to make sure (via new DOMText) that the XML entities are
  1758. * always properly escaped
  1759. * (non-PHPdoc)
  1760. * @see DOMDocument::createElement()
  1761. */
  1762. function createElement($sName, $value = null, $namespaceURI = null)
  1763. {
  1764. $oElement = $this->importNode(new MFElement($sName, null, $namespaceURI));
  1765. if (!empty($value))
  1766. {
  1767. $oElement->appendChild(new DOMText($value));
  1768. }
  1769. return $oElement;
  1770. }
  1771. /**
  1772. * Find the child node matching the given node
  1773. * A method with the same signature MUST exist in MFElement for the recursion to work fine
  1774. * @param MFElement $oRefNode The node to search for
  1775. * @param string $sSearchId substitutes to the value of the 'id' attribute
  1776. */
  1777. public function _FindChildNode(MFElement $oRefNode, $sSearchId = null)
  1778. {
  1779. return MFElement::_FindNode($this, $oRefNode, $sSearchId);
  1780. }
  1781. /**
  1782. * Extracts some nodes from the DOM
  1783. * @param string $sXPath A XPath expression
  1784. * @return DOMNodeList
  1785. */
  1786. public function GetNodes($sXPath, $oContextNode = null, $bSafe = true)
  1787. {
  1788. $oXPath = new DOMXPath($this);
  1789. if ($bSafe)
  1790. {
  1791. $sXPath .= "[not(@_alteration) or @_alteration!='removed']";
  1792. }
  1793. if (is_null($oContextNode))
  1794. {
  1795. $oResult = $oXPath->query($sXPath);
  1796. }
  1797. else
  1798. {
  1799. $oResult = $oXPath->query($sXPath, $oContextNode);
  1800. }
  1801. return $oResult;
  1802. }
  1803. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  1804. {
  1805. $oXPath = new DOMXPath($this);
  1806. $sQuotedId = self::XPathQuote($sId);
  1807. $sXPath .= "[@id=$sQuotedId and(not(@_alteration) or @_alteration!='removed')]";
  1808. if (is_null($oContextNode))
  1809. {
  1810. return $oXPath->query($sXPath);
  1811. }
  1812. else
  1813. {
  1814. return $oXPath->query($sXPath, $oContextNode);
  1815. }
  1816. }
  1817. }
  1818. /**
  1819. * Helper class manage parameters stored as XML nodes
  1820. * to be converted to a PHP structure during compilation
  1821. * Values can be either a hash, an array, a string, a boolean, an int or a float
  1822. */
  1823. class MFParameters
  1824. {
  1825. protected $aData = null;
  1826. public function __construct(DOMNode $oNode)
  1827. {
  1828. $this->aData = array();
  1829. $this->LoadFromDOM($oNode);
  1830. }
  1831. public function Get($sCode, $default = '')
  1832. {
  1833. if (array_key_exists($sCode, $this->aData))
  1834. {
  1835. return $this->aData[$sCode];
  1836. }
  1837. return $default;
  1838. }
  1839. public function GetAll()
  1840. {
  1841. return $this->aData;
  1842. }
  1843. public function LoadFromDOM(DOMNode $oNode)
  1844. {
  1845. $this->aData = array();
  1846. foreach($oNode->childNodes as $oChildNode)
  1847. {
  1848. if ($oChildNode instanceof DOMElement)
  1849. {
  1850. $this->aData[$oChildNode->nodeName] = $this->ReadElement($oChildNode);
  1851. }
  1852. }
  1853. }
  1854. protected function ReadElement(DOMNode $oNode)
  1855. {
  1856. if ($oNode instanceof DOMElement)
  1857. {
  1858. $sDefaultNodeType = ($this->HasChildNodes($oNode)) ? 'hash' : 'string';
  1859. $sNodeType = $oNode->getAttribute('type');
  1860. if ($sNodeType == '')
  1861. {
  1862. $sNodeType = $sDefaultNodeType;
  1863. }
  1864. switch($sNodeType)
  1865. {
  1866. case 'array':
  1867. $value = array();
  1868. // Treat the current element as zero based array, child tag names are NOT meaningful
  1869. $sFirstTagName = null;
  1870. foreach($oNode->childNodes as $oChildElement)
  1871. {
  1872. if ($oChildElement instanceof DOMElement)
  1873. {
  1874. if ($sFirstTagName == null)
  1875. {
  1876. $sFirstTagName = $oChildElement->nodeName;
  1877. }
  1878. else if ($sFirstTagName != $oChildElement->nodeName)
  1879. {
  1880. throw new Exception("Invalid Parameters: mixed tags ('$sFirstTagName' and '".$oChildElement->nodeName."') inside array '".$oNode->nodeName."'");
  1881. }
  1882. $val = $this->ReadElement($oChildElement);
  1883. // No specific Id, just push the value at the end of the array
  1884. $value[] = $val;
  1885. }
  1886. }
  1887. ksort($value, SORT_NUMERIC);
  1888. break;
  1889. case 'hash':
  1890. $value = array();
  1891. // Treat the current element as a hash, child tag names are keys
  1892. foreach($oNode->childNodes as $oChildElement)
  1893. {
  1894. if ($oChildElement instanceof DOMElement)
  1895. {
  1896. if (array_key_exists($oChildElement->nodeName, $value))
  1897. {
  1898. throw new Exception("Invalid Parameters file: duplicate tags '".$oChildElement->nodeName."' inside hash '".$oNode->nodeName."'");
  1899. }
  1900. $val = $this->ReadElement($oChildElement);
  1901. $value[$oChildElement->nodeName] = $val;
  1902. }
  1903. }
  1904. break;
  1905. case 'int':
  1906. case 'integer':
  1907. $value = (int)$this->GetText($oNode);
  1908. break;
  1909. case 'bool':
  1910. case 'boolean':
  1911. if (($this->GetText($oNode) == 'true') || ($this->GetText($oNode) == 1))
  1912. {
  1913. $value = true;
  1914. }
  1915. else
  1916. {
  1917. $value = false;
  1918. }
  1919. break;
  1920. case 'string':
  1921. default:
  1922. $value = str_replace('\n', "\n", (string)$this->GetText($oNode));
  1923. }
  1924. }
  1925. else if ($oNode instanceof DOMText)
  1926. {
  1927. $value = $oNode->wholeText;
  1928. }
  1929. return $value;
  1930. }
  1931. protected function GetAttribute($sAttName, $oNode, $sDefaultValue)
  1932. {
  1933. $sRet = $sDefaultValue;
  1934. foreach($oNode->attributes as $oAttribute)
  1935. {
  1936. if ($oAttribute->nodeName == $sAttName)
  1937. {
  1938. $sRet = $oAttribute->nodeValue;
  1939. break;
  1940. }
  1941. }
  1942. return $sRet;
  1943. }
  1944. /**
  1945. * Returns the TEXT of the current node (possibly from several subnodes)
  1946. */
  1947. public function GetText($oNode, $sDefault = null)
  1948. {
  1949. $sText = null;
  1950. foreach($oNode->childNodes as $oChildNode)
  1951. {
  1952. if ($oChildNode instanceof DOMText)
  1953. {
  1954. if (is_null($sText)) $sText = '';
  1955. $sText .= $oChildNode->wholeText;
  1956. }
  1957. }
  1958. if (is_null($sText))
  1959. {
  1960. return $sDefault;
  1961. }
  1962. else
  1963. {
  1964. return $sText;
  1965. }
  1966. }
  1967. /**
  1968. * Check if a node has child nodes (apart from text nodes)
  1969. */
  1970. public function HasChildNodes($oNode)
  1971. {
  1972. if ($oNode instanceof DOMElement)
  1973. {
  1974. foreach($oNode->childNodes as $oChildNode)
  1975. {
  1976. if ($oChildNode instanceof DOMElement)
  1977. {
  1978. return true;
  1979. }
  1980. }
  1981. }
  1982. return false;
  1983. }
  1984. function Merge(XMLParameters $oTask)
  1985. {
  1986. //todo: clarify the usage of this function that CANNOT work
  1987. $this->aData = $this->array_merge_recursive_distinct($this->aData, $oTask->aData);
  1988. }
  1989. /**
  1990. * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
  1991. * keys to arrays rather than overwriting the value in the first array with the duplicate
  1992. * value in the second array, as array_merge does. I.e., with array_merge_recursive,
  1993. * this happens (documented behavior):
  1994. *
  1995. * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
  1996. * => array('key' => array('org value', 'new value'));
  1997. *
  1998. * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
  1999. * Matching keys' values in the second array overwrite those in the first array, as is the
  2000. * case with array_merge, i.e.:
  2001. *
  2002. * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
  2003. * => array('key' => array('new value'));
  2004. *
  2005. * Parameters are passed by reference, though only for performance reasons. They're not
  2006. * altered by this function.
  2007. *
  2008. * @param array $array1
  2009. * @param array $array2
  2010. * @return array
  2011. * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
  2012. * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
  2013. */
  2014. protected function array_merge_recursive_distinct ( array &$array1, array &$array2 )
  2015. {
  2016. $merged = $array1;
  2017. foreach ( $array2 as $key => &$value )
  2018. {
  2019. if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
  2020. {
  2021. $merged [$key] = $this->array_merge_recursive_distinct ( $merged [$key], $value );
  2022. }
  2023. else
  2024. {
  2025. $merged [$key] = $value;
  2026. }
  2027. }
  2028. return $merged;
  2029. }
  2030. }