modelfactory.class.inc.php 62 KB

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