modelfactory.class.inc.php 60 KB

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