modelfactory.class.inc.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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. $oTargetNode->setAttribute('_alteration', 'needed');
  288. break;
  289. case 'define':
  290. // New node - copy child nodes as well
  291. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  292. $oTargetParentNode->AddChildNode($oTargetNode);
  293. break;
  294. case 'redefine':
  295. // Replace the existing node by the given node - copy child nodes as well
  296. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  297. $sSearchId = $oSourceNode->hasAttribute('_rename_from') ? $oSourceNode->getAttribute('_rename_from') : $oSourceNode->getAttribute('id');
  298. $oTargetParentNode->RedefineChildNode($oTargetNode, $sSearchId);
  299. break;
  300. case 'delete':
  301. $oTargetNode = $oTargetParentNode->FindExistingChildNode($oSourceNode);
  302. $oTargetNode->Delete();
  303. break;
  304. }
  305. if ($oSourceNode->hasAttribute('_rename_from'))
  306. {
  307. $oTargetNode->Rename($oSourceNode->getAttribute('id'));
  308. }
  309. if ($oTargetNode->hasAttribute('_delta'))
  310. {
  311. $oTargetNode->removeAttribute('_delta');
  312. }
  313. }
  314. /**
  315. * Loads the definitions corresponding to the given Module
  316. * @param MFModule $oModule
  317. * @param Array $aLanguages The list of languages to process (for the dictionaries). If empty all languages are kept
  318. */
  319. public function LoadModule(MFModule $oModule, $aLanguages = array())
  320. {
  321. try
  322. {
  323. $aDataModels = $oModule->GetDataModelFiles();
  324. $sModuleName = $oModule->GetName();
  325. $aClasses = array();
  326. self::$aLoadedModules[] = $oModule;
  327. // For persistence in the cache
  328. $oModuleNode = $this->oDOMDocument->CreateElement('module');
  329. $oModuleNode->setAttribute('id', $oModule->GetId());
  330. $oModuleNode->AppendChild($this->oDOMDocument->CreateElement('root_dir', $oModule->GetRootDir()));
  331. $oModuleNode->AppendChild($this->oDOMDocument->CreateElement('label', $oModule->GetLabel()));
  332. $this->oModules->AppendChild($oModuleNode);
  333. foreach($aDataModels as $sXmlFile)
  334. {
  335. $oDocument = new MFDocument();
  336. libxml_clear_errors();
  337. $oDocument->load($sXmlFile);
  338. //$bValidated = $oDocument->schemaValidate(APPROOT.'setup/itop_design.xsd');
  339. $aErrors = libxml_get_errors();
  340. if (count($aErrors) > 0)
  341. {
  342. self::$aLoadErrors[$sModuleName] = $aErrors;
  343. return;
  344. }
  345. $oXPath = new DOMXPath($oDocument);
  346. $oNodeList = $oXPath->query('/itop_design/classes//class');
  347. foreach($oNodeList as $oNode)
  348. {
  349. if ($oNode->getAttribute('_created_in') == '')
  350. {
  351. $oNode->SetAttribute('_created_in', $sModuleName);
  352. }
  353. }
  354. $oNodeList = $oXPath->query('/itop_design/menus/menu');
  355. foreach($oNodeList as $oNode)
  356. {
  357. if ($oNode->getAttribute('_created_in') == '')
  358. {
  359. $oNode->SetAttribute('_created_in', $sModuleName);
  360. }
  361. }
  362. $oUserRightsNode = $oXPath->query('/itop_design/user_rights')->item(0);
  363. if ($oUserRightsNode)
  364. {
  365. if ($oUserRightsNode->getAttribute('_created_in') == '')
  366. {
  367. $oUserRightsNode->SetAttribute('_created_in', $sModuleName);
  368. }
  369. }
  370. $oDeltaRoot = $oDocument->childNodes->item(0);
  371. $this->LoadDelta($oDocument, $oDeltaRoot, $this->oDOMDocument);
  372. }
  373. $aDictionaries = $oModule->GetDictionaryFiles();
  374. try
  375. {
  376. $this->ResetTempDictionary();
  377. foreach($aDictionaries as $sPHPFile)
  378. {
  379. $sDictFileContents = file_get_contents($sPHPFile);
  380. $sDictFileContents = str_replace(array('<'.'?'.'php', '?'.'>'), '', $sDictFileContents);
  381. $sDictFileContents = str_replace('Dict::Add', '$this->AddToTempDictionary', $sDictFileContents);
  382. eval($sDictFileContents);
  383. }
  384. foreach ($this->aDict as $sLanguageCode => $aDictDefinition)
  385. {
  386. if ((count($aLanguages) > 0 ) && !in_array($sLanguageCode, $aLanguages))
  387. {
  388. // skip some languages if the parameter says so
  389. continue;
  390. }
  391. $oNodes = $this->GetNodeById('dictionary', $sLanguageCode, $this->oDictionaries);
  392. if ($oNodes->length == 0)
  393. {
  394. $oXmlDict = $this->oDOMDocument->CreateElement('dictionary');
  395. $oXmlDict->setAttribute('id', $sLanguageCode);
  396. $this->oDictionaries->AddChildNode($oXmlDict);
  397. $oXmlEntries = $this->oDOMDocument->CreateElement('english_description', $aDictDefinition['english_description']);
  398. $oXmlDict->AppendChild($oXmlEntries);
  399. $oXmlEntries = $this->oDOMDocument->CreateElement('localized_description', $aDictDefinition['localized_description']);
  400. $oXmlDict->AppendChild($oXmlEntries);
  401. $oXmlEntries = $this->oDOMDocument->CreateElement('entries');
  402. $oXmlDict->AppendChild($oXmlEntries);
  403. }
  404. else
  405. {
  406. $oXmlDict = $oNodes->item(0);
  407. $oXmlEntries = $oXmlDict->GetUniqueElement('entries');
  408. }
  409. foreach ($aDictDefinition['entries'] as $sCode => $sLabel)
  410. {
  411. $oXmlEntry = $this->oDOMDocument->CreateElement('entry');
  412. $oXmlEntry->setAttribute('id', $sCode);
  413. $oXmlValue = $this->oDOMDocument->CreateCDATASection($sLabel);
  414. $oXmlEntry->appendChild($oXmlValue);
  415. if (array_key_exists($sLanguageCode, $this->aDictKeys) && array_key_exists($sCode, $this->aDictKeys[$sLanguageCode]))
  416. {
  417. $oXmlEntries->RedefineChildNode($oXmlEntry);
  418. }
  419. else
  420. {
  421. $oXmlEntries->appendChild($oXmlEntry);
  422. }
  423. $this->aDictKeys[$sLanguageCode][$sCode] = true;
  424. }
  425. }
  426. }
  427. catch(Exception $e)
  428. {
  429. throw new Exception('Failed to load dictionary file "'.$sPHPFile.'", reason: '.$e->getMessage());
  430. }
  431. }
  432. catch(Exception $e)
  433. {
  434. $aLoadedModuleNames = array();
  435. foreach (self::$aLoadedModules as $oModule)
  436. {
  437. $aLoadedModuleNames[] = $oModule->GetName();
  438. }
  439. throw new Exception('Error loading module "'.$oModule->GetName().'": '.$e->getMessage().' - Loaded modules: '.implode(',', $aLoadedModuleNames));
  440. }
  441. }
  442. /**
  443. * Collects the PHP Dict entries into the ModelFactory for transforming the dictionary into an XML structure
  444. * @param string $sLanguageCode The language code
  445. * @param string $sEnglishLanguageDesc English description of the language (unused but kept for API compatibility)
  446. * @param string $sLocalizedLanguageDesc Localized description of the language (unused but kept for API compatibility)
  447. * @param hash $aEntries The entries to load: string_code => translation
  448. */
  449. protected function AddToTempDictionary($sLanguageCode, $sEnglishLanguageDesc, $sLocalizedLanguageDesc, $aEntries)
  450. {
  451. $this->aDict[$sLanguageCode]['english_description'] = $sEnglishLanguageDesc;
  452. $this->aDict[$sLanguageCode]['localized_description'] = $sLocalizedLanguageDesc;
  453. if (!array_key_exists('entries', $this->aDict[$sLanguageCode]))
  454. {
  455. $this->aDict[$sLanguageCode]['entries'] = array();
  456. }
  457. foreach($aEntries as $sKey => $sValue)
  458. {
  459. $this->aDict[$sLanguageCode]['entries'][$sKey] = $sValue;
  460. }
  461. }
  462. protected function ResetTempDictionary()
  463. {
  464. $this->aDict = array();
  465. }
  466. /**
  467. * XML load errors (XML format and validation)
  468. */
  469. function HasLoadErrors()
  470. {
  471. return (count(self::$aLoadErrors) > 0);
  472. }
  473. function GetLoadErrors()
  474. {
  475. return self::$aLoadErrors;
  476. }
  477. function GetLoadedModules($bExcludeWorkspace = true)
  478. {
  479. if ($bExcludeWorkspace)
  480. {
  481. $aModules = array();
  482. foreach(self::$aLoadedModules as $oModule)
  483. {
  484. if (!$oModule instanceof MFWorkspace)
  485. {
  486. $aModules[] = $oModule;
  487. }
  488. }
  489. }
  490. else
  491. {
  492. $aModules = self::$aLoadedModules;
  493. }
  494. return $aModules;
  495. }
  496. function GetModule($sModuleName)
  497. {
  498. foreach(self::$aLoadedModules as $oModule)
  499. {
  500. if ($oModule->GetName() == $sModuleName) return $oModule;
  501. }
  502. return null;
  503. }
  504. public function CreateElement($sTagName, $sValue = '')
  505. {
  506. return $this->oDOMDocument->createElement($sTagName, $sValue);
  507. }
  508. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  509. {
  510. return $this->oDOMDocument->GetNodeById($sXPath, $sId, $oContextNode);
  511. }
  512. /**
  513. * Apply extensibility rules into the DOM
  514. * @param array aRestrictionRules Array of array ('selectors' => array of XPaths, 'rules' => array of rules)
  515. * @return void
  516. */
  517. public function RestrictExtensibility($aRestrictionRules)
  518. {
  519. foreach ($aRestrictionRules as $aRestriction)
  520. {
  521. foreach ($aRestriction['selectors'] as $sSelector)
  522. {
  523. foreach($this->GetNodes($sSelector) as $oNode)
  524. {
  525. $oNode->RestrictExtensibility($aRestriction['rules']);
  526. }
  527. }
  528. }
  529. }
  530. /**
  531. * Check if the class specified by the given node already exists in the loaded DOM
  532. * @param DOMNode $oClassNode The node corresponding to the class to load
  533. * @throws Exception
  534. * @return bool True if the class exists, false otherwise
  535. */
  536. protected function ClassExists(DOMNode $oClassNode)
  537. {
  538. assert(false);
  539. if ($oClassNode->hasAttribute('id'))
  540. {
  541. $sClassName = $oClassNode->GetAttribute('id');
  542. }
  543. else
  544. {
  545. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  546. }
  547. return (array_key_exists($sClassName, self::$aLoadedClasses));
  548. }
  549. /**
  550. * Check if the class specified by the given name already exists in the loaded DOM
  551. * @param string $sClassName The node corresponding to the class to load
  552. * @throws Exception
  553. * @return bool True if the class exists, false otherwise
  554. */
  555. protected function ClassNameExists($sClassName, $bFlattenLayers = true)
  556. {
  557. return !is_null($this->GetClass($sClassName, $bFlattenLayers));
  558. }
  559. /**
  560. * Add the given class to the DOM
  561. * @param DOMNode $oClassNode
  562. * @param string $sModuleName The name of the module in which this class is declared
  563. * @throws Exception
  564. */
  565. public function AddClass(DOMNode $oClassNode, $sModuleName)
  566. {
  567. if ($oClassNode->hasAttribute('id'))
  568. {
  569. $sClassName = $oClassNode->GetAttribute('id');
  570. }
  571. else
  572. {
  573. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  574. }
  575. if ($this->ClassNameExists($oClassNode->getAttribute('id')))
  576. {
  577. throw new Exception("ModelFactory::AddClass: Cannot add the already existing class $sClassName");
  578. }
  579. $sParentClass = $oClassNode->GetChildText('parent', '');
  580. $oParentNode = $this->GetClass($sParentClass);
  581. if ($oParentNode == null)
  582. {
  583. throw new Exception("ModelFactory::AddClass: Cannot find the parent class of '$sClassName': '$sParentClass'");
  584. }
  585. else
  586. {
  587. if ($sModuleName != '')
  588. {
  589. $oClassNode->SetAttribute('_created_in', $sModuleName);
  590. }
  591. $oParentNode->AddChildNode($this->oDOMDocument->importNode($oClassNode, true));
  592. if (substr($sParentClass, 0, 1) == '/') // Convention for well known parent classes
  593. {
  594. // Remove the leading slash character
  595. $oParentNameNode = $oClassNode->GetOptionalElement('parent')->firstChild; // Get the DOMCharacterData node
  596. $oParentNameNode->data = substr($sParentClass, 1);
  597. }
  598. }
  599. }
  600. /**
  601. * Remove a class from the DOM
  602. * @param string $sClass
  603. * @throws Exception
  604. */
  605. public function RemoveClass($sClass)
  606. {
  607. $oClassNode = $this->GetClass($sClass);
  608. if ($oClassNode == null)
  609. {
  610. throw new Exception("ModelFactory::RemoveClass: Cannot remove the non existing class $sClass");
  611. }
  612. // Note: the child classes are removed entirely
  613. $oClassNode->Delete();
  614. }
  615. /**
  616. * Modify a class within the DOM
  617. * @param string $sMenuId
  618. * @param DOMNode $oMenuNode
  619. * @throws Exception
  620. */
  621. public function AlterClass($sClassName, DOMNode $oClassNode)
  622. {
  623. $sOriginalName = $sClassName;
  624. if ($this->ClassNameExists($sClassName))
  625. {
  626. $oDestNode = self::$aLoadedClasses[$sClassName];
  627. }
  628. else
  629. {
  630. $sOriginalName = $oClassNode->getAttribute('_original_name');
  631. if ($this->ClassNameExists($sOriginalName))
  632. {
  633. // Class was renamed !
  634. $oDestNode = self::$aLoadedClasses[$sOriginalName];
  635. }
  636. else
  637. {
  638. throw new Exception("ModelFactory::AddClass: Cannot alter the non-existing class $sClassName / $sOriginalName");
  639. }
  640. }
  641. $this->_priv_AlterNode($oDestNode, $oClassNode);
  642. $sClassName = $oDestNode->getAttribute('id');
  643. if ($sOriginalName != $sClassName)
  644. {
  645. unset(self::$aLoadedClasses[$sOriginalName]);
  646. self::$aLoadedClasses[$sClassName] = $oDestNode;
  647. }
  648. $this->_priv_SetFlag($oDestNode, 'modified');
  649. }
  650. public function GetClassXMLTemplate($sName, $sIcon)
  651. {
  652. $sHeader = '<?'.'xml version="1.0" encoding="utf-8"?'.'>';
  653. return
  654. <<<EOF
  655. $sHeader
  656. <class id="$sName">
  657. <comment/>
  658. <properties>
  659. </properties>
  660. <naming format=""><attributes/></naming>
  661. <reconciliation><attributes/></reconciliation>
  662. <display_template/>
  663. <icon>$sIcon</icon>
  664. </properties>
  665. <fields/>
  666. <lifecycle/>
  667. <methods/>
  668. <presentation>
  669. <details><items/></details>
  670. <search><items/></search>
  671. <list><items/></list>
  672. </presentation>
  673. </class>
  674. EOF
  675. ;
  676. }
  677. /**
  678. * List all classes from the DOM, for a given module
  679. * @param string $sModuleNale
  680. * @param bool $bFlattenLayers
  681. * @throws Exception
  682. */
  683. public function ListClasses($sModuleName, $bFlattenLayers = true)
  684. {
  685. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName']";
  686. if ($bFlattenLayers)
  687. {
  688. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName' and (not(@_alteration) or @_alteration!='removed')]";
  689. }
  690. return $this->GetNodes($sXPath);
  691. }
  692. /**
  693. * List all classes from the DOM
  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. case 'needed':
  1039. // marked as added or modified, just reset the flag
  1040. $oNode->removeAttribute('_alteration');
  1041. break;
  1042. case 'removed':
  1043. // marked as deleted, let's remove the node from the tree
  1044. $oNode->parentNode->removeChild($oNode);
  1045. // TODO!!!!!!!
  1046. //unset(self::$aLoadedClasses[$sClass]);
  1047. break;
  1048. }
  1049. if ($oNode->hasAttribute('_old_id'))
  1050. {
  1051. $oNode->removeAttribute('_old_id');
  1052. }
  1053. }
  1054. }
  1055. public function ListChanges()
  1056. {
  1057. return $this->GetNodes('//*[@_alteration or @_old_id]');
  1058. }
  1059. /**
  1060. * Create path for the delta
  1061. * @param DOMDocument oTargetDoc Where to attach the top of the hierarchy
  1062. * @param MFElement oNode The node to import with its path
  1063. */
  1064. protected function ImportNodeAndPathDelta($oTargetDoc, $oNode)
  1065. {
  1066. // Preliminary: skip the parent if this node is organized hierarchically into the DOM
  1067. // Only class nodes are organized this way
  1068. $oParent = $oNode->parentNode;
  1069. if ($oNode->tagName == 'class')
  1070. {
  1071. while (($oParent instanceof DOMElement) && ($oParent->tagName == $oNode->tagName) && $oParent->hasAttribute('id'))
  1072. {
  1073. $oParent = $oParent->parentNode;
  1074. }
  1075. }
  1076. // Recursively create the path for the parent
  1077. if ($oParent instanceof DOMElement)
  1078. {
  1079. $oParentClone = $this->ImportNodeAndPathDelta($oTargetDoc, $oParent);
  1080. }
  1081. else
  1082. {
  1083. // We've reached the top let's add the node into the root recipient
  1084. $oParentClone = $oTargetDoc;
  1085. }
  1086. // Look for the node into the parent node
  1087. // Note: this is an identified weakness of the algorithm,
  1088. // because for each node modified, and each node of its path
  1089. // we will have to lookup for the existing entry
  1090. // Anyhow, this loop is quite quick to execute because in the delta
  1091. // the number of nodes is limited
  1092. $oNodeClone = null;
  1093. foreach ($oParentClone->childNodes as $oChild)
  1094. {
  1095. if (($oChild instanceof DOMElement) && ($oChild->tagName == $oNode->tagName))
  1096. {
  1097. if (!$oNode->hasAttribute('id') || ($oNode->getAttribute('id') == $oChild->getAttribute('id')))
  1098. {
  1099. $oNodeClone = $oChild;
  1100. break;
  1101. }
  1102. }
  1103. }
  1104. if (!$oNodeClone)
  1105. {
  1106. $sAlteration = $oNode->getAttribute('_alteration');
  1107. $bCopyContents = ($sAlteration == 'replaced') || ($sAlteration == 'added') || ($sAlteration == 'needed');
  1108. $oNodeClone = $oTargetDoc->importNode($oNode->cloneNode($bCopyContents), $bCopyContents);
  1109. $oNodeClone->removeAttribute('_alteration');
  1110. if ($oNodeClone->hasAttribute('_old_id'))
  1111. {
  1112. $oNodeClone->setAttribute('_rename_from', $oNodeClone->getAttribute('_old_id'));
  1113. $oNodeClone->removeAttribute('_old_id');
  1114. }
  1115. switch ($sAlteration)
  1116. {
  1117. case '':
  1118. if ($oNodeClone->hasAttribute('id'))
  1119. {
  1120. $oNodeClone->setAttribute('_delta', 'must_exist');
  1121. }
  1122. break;
  1123. case 'added':
  1124. $oNodeClone->setAttribute('_delta', 'define');
  1125. break;
  1126. case 'replaced':
  1127. $oNodeClone->setAttribute('_delta', 'redefine');
  1128. break;
  1129. case 'removed':
  1130. $oNodeClone->setAttribute('_delta', 'delete');
  1131. break;
  1132. case 'needed':
  1133. $oNodeClone->setAttribute('_delta', 'define_if_not_exists');
  1134. break;
  1135. }
  1136. $oParentClone->appendChild($oNodeClone);
  1137. }
  1138. return $oNodeClone;
  1139. }
  1140. /**
  1141. * Get the text/XML version of the delta
  1142. */
  1143. public function GetDelta($aNodesToIgnore = array(), $iRevisionId = null)
  1144. {
  1145. $oDelta = new MFDocument();
  1146. foreach($this->ListChanges() as $oAlteredNode)
  1147. {
  1148. $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode);
  1149. }
  1150. foreach($aNodesToIgnore as $sXPath)
  1151. {
  1152. $oNodesToRemove = $oDelta->GetNodes($sXPath);
  1153. foreach($oNodesToRemove as $oNode)
  1154. {
  1155. $oNode->parentNode->removeChild($oNode);
  1156. }
  1157. }
  1158. if ($iRevisionId != null)
  1159. {
  1160. $oDelta->documentElement->setAttribute('revision_id', $iRevisionId);
  1161. }
  1162. return $oDelta->saveXML();
  1163. }
  1164. /**
  1165. * Searches on disk in the root directories for module description files
  1166. * and returns an array of MFModules
  1167. * @return array Array of MFModules
  1168. */
  1169. public function FindModules()
  1170. {
  1171. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->aRootDirs);
  1172. $aResult = array();
  1173. foreach($aAvailableModules as $sId => $aModule)
  1174. {
  1175. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  1176. }
  1177. return $aResult;
  1178. }
  1179. public function TestAlteration()
  1180. {
  1181. try
  1182. {
  1183. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  1184. $sOriginalXML =
  1185. <<<EOF
  1186. $sHeader
  1187. <itop_design>
  1188. <a id="first a">
  1189. <b>Text</b>
  1190. <c id="1">
  1191. <d>D1</d>
  1192. <d>D2</d>
  1193. </c>
  1194. </a>
  1195. <a id="second a">
  1196. <parent>first a</parent>
  1197. </a>
  1198. <a id="third a">
  1199. <parent>first a</parent>
  1200. <x>blah</x>
  1201. </a>
  1202. </itop_design>
  1203. EOF;
  1204. $this->oDOMDocument = new MFDocument();
  1205. $this->oDOMDocument->loadXML($sOriginalXML);
  1206. // DOM Get the original values, then modify its contents by the mean of the API
  1207. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1208. //$oRoot->Dump();
  1209. $sDOMOriginal = $oRoot->Dump(true);
  1210. $oNode = $oRoot->GetNodes('a/b')->item(0);
  1211. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  1212. $oNode->parentNode->RedefineChildNode($oNew);
  1213. $oNode = $oRoot->GetNodes('a/c')->item(0);
  1214. $oNewC = $this->oDOMDocument->CreateElement('c');
  1215. $oNewC->setAttribute('id', '1');
  1216. $oNode->parentNode->RedefineChildNode($oNewC);
  1217. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  1218. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  1219. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  1220. $oNamedNode = $this->oDOMDocument->CreateElement('z');
  1221. $oNamedNode->setAttribute('id', 'abc');
  1222. $oNewC->AddChildNode($oNamedNode);
  1223. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('r', 'to be replaced'));
  1224. // Alter this "modified node", no flag should be set in its subnodes
  1225. $oNewC->Rename('blah');
  1226. $oNewC->Rename('foo');
  1227. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('y', '(no flag)'));
  1228. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1229. $oSubNode = $oNewC->GetUniqueElement('z');
  1230. $oSubNode->Rename('abcdef');
  1231. $oSubNode = $oNewC->GetUniqueElement('x');
  1232. $oSubNode->Delete();
  1233. $oNewC->RedefineChildNode($this->oDOMDocument->CreateElement('r', 'replacement'));
  1234. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  1235. $oNode->Rename('el 2o A');
  1236. $oNode->Rename('el secundo A');
  1237. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  1238. $oNode->AddChildNode($oNew);
  1239. $oNewA = $this->oDOMDocument->CreateElement('a');
  1240. $oNewA->setAttribute('id', 'new a');
  1241. $oNode->AddChildNode($oNewA);
  1242. $oSubnode = $this->oDOMDocument->CreateElement('parent', 'el secundo A');
  1243. $oSubnode->setAttribute('id', 'to be changed');
  1244. $oNewA->AddChildNode($oSubnode);
  1245. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  1246. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1247. // Alter this "new a", as it is new, no flag should be set
  1248. $oNewA->Rename('new_a');
  1249. $oSubNode = $oNewA->GetUniqueElement('parent');
  1250. $oSubNode->Rename('alter ego');
  1251. $oNewA->RedefineChildNode($this->oDOMDocument->CreateElement('f', 'dummy data'));
  1252. $oSubNode = $oNewA->GetUniqueElement('x');
  1253. $oSubNode->Delete();
  1254. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  1255. $oNode->Delete();
  1256. //$oRoot->Dump();
  1257. $sDOMModified = $oRoot->Dump(true);
  1258. // Compute the delta
  1259. //
  1260. $sDeltaXML = $this->GetDelta();
  1261. //echo "<pre>\n";
  1262. //echo htmlentities($sDeltaXML);
  1263. //echo "</pre>\n";
  1264. // Reiterating - try to remake the DOM by applying the computed delta
  1265. //
  1266. $this->oDOMDocument = new MFDocument();
  1267. $this->oDOMDocument->loadXML($sOriginalXML);
  1268. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1269. //$oRoot->Dump();
  1270. echo "<h4>Rebuild the DOM - Delta applied...</h4>\n";
  1271. $oDeltaDoc = new MFDocument();
  1272. $oDeltaDoc->loadXML($sDeltaXML);
  1273. //$oDeltaDoc->Dump();
  1274. //$this->oDOMDocument->Dump();
  1275. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  1276. $this->LoadDelta($oDeltaDoc, $oDeltaRoot, $this->oDOMDocument);
  1277. //$oRoot->Dump();
  1278. $sDOMRebuilt = $oRoot->Dump(true);
  1279. }
  1280. catch (Exception $e)
  1281. {
  1282. echo "<h1>Exception: ".$e->getMessage()."</h1>\n";
  1283. echo "<pre>\n";
  1284. debug_print_backtrace();
  1285. echo "</pre>\n";
  1286. }
  1287. $sArrStyle = "font-size: 40;";
  1288. echo "<table>\n";
  1289. echo " <tr>\n";
  1290. echo " <td width=\"50%\">\n";
  1291. echo " <h4>DOM - Original values</h4>\n";
  1292. echo " <pre>".htmlentities($sDOMOriginal)."</pre>\n";
  1293. echo " </td>\n";
  1294. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1295. echo " </tr>\n";
  1296. 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";
  1297. echo " <tr>\n";
  1298. echo " <td width=\"50%\">\n";
  1299. echo " <h4>DOM - Altered with various changes</h4>\n";
  1300. echo " <pre>".htmlentities($sDOMModified)."</pre>\n";
  1301. echo " </td>\n";
  1302. echo " <td width=\"50%\">\n";
  1303. echo " <h4>DOM - Rebuilt from the Delta</h4>\n";
  1304. echo " <pre>".htmlentities($sDOMRebuilt)."</pre>\n";
  1305. echo " </td>\n";
  1306. echo " </tr>\n";
  1307. echo " <tr><td align=\"center\"><span style=\"$sArrStyle\">&dArr;</div></td><td align=\"center\"><span style=\"$sArrStyle\">&uArr;</div></td></tr>\n";
  1308. echo " <td width=\"50%\">\n";
  1309. echo " <h4>Delta (Computed by ModelFactory)</h4>\n";
  1310. echo " <pre>".htmlentities($sDeltaXML)."</pre>\n";
  1311. echo " </td>\n";
  1312. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1313. echo " </tr>\n";
  1314. echo "</table>\n";
  1315. } // TEST !
  1316. /**
  1317. * Extracts some nodes from the DOM
  1318. * @param string $sXPath A XPath expression
  1319. * @return DOMNodeList
  1320. */
  1321. public function GetNodes($sXPath, $oContextNode = null)
  1322. {
  1323. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode);
  1324. }
  1325. public function ListActiveChildNodes($sContextXPath, $sTagName)
  1326. {
  1327. $oContextPath = $this->oRoot->GetNodes($sContextXPath)->item(0);
  1328. return $oContextPath->ListActiveChildNodes($sTagName);
  1329. }
  1330. }
  1331. /**
  1332. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1333. */
  1334. if (!class_exists('DOMElement'))
  1335. {
  1336. class DOMElement {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1337. }
  1338. /**
  1339. * MFElement: helper to read/change the DOM
  1340. * @package ModelFactory
  1341. */
  1342. class MFElement extends DOMElement
  1343. {
  1344. /**
  1345. * Extracts some nodes from the DOM
  1346. * @param string $sXPath A XPath expression
  1347. * @return DOMNodeList
  1348. */
  1349. public function GetNodes($sXPath)
  1350. {
  1351. return $this->ownerDocument->GetNodes($sXPath, $this);
  1352. }
  1353. /**
  1354. * Extracts some nodes from the DOM (active nodes only !!!)
  1355. * @param string $sXPath A XPath expression
  1356. * @return DOMNodeList
  1357. */
  1358. public function GetNodeById($sXPath, $sId)
  1359. {
  1360. return $this->ownerDocument->GetNodeById($sXPath, $sId, $this);
  1361. }
  1362. /**
  1363. * For debugging purposes - but this is currently buggy: the whole document is rendered
  1364. */
  1365. public function Dump($bReturnRes = false)
  1366. {
  1367. $oMFDoc = new MFDocument();
  1368. $oClone = $oMFDoc->importNode($this->cloneNode(true), true);
  1369. $oMFDoc->appendChild($oClone);
  1370. $sXml = $oMFDoc->saveXML($oClone);
  1371. if ($bReturnRes)
  1372. {
  1373. return $sXml;
  1374. }
  1375. else
  1376. {
  1377. echo "<pre>\n";
  1378. echo htmlentities($sXml);
  1379. echo "</pre>\n";
  1380. }
  1381. }
  1382. /**
  1383. * Returns the node directly under the given node
  1384. */
  1385. public function GetUniqueElement($sTagName, $bMustExist = true)
  1386. {
  1387. $oNode = null;
  1388. foreach($this->childNodes as $oChildNode)
  1389. {
  1390. if ($oChildNode->nodeName == $sTagName)
  1391. {
  1392. $oNode = $oChildNode;
  1393. break;
  1394. }
  1395. }
  1396. if ($bMustExist && is_null($oNode))
  1397. {
  1398. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1399. }
  1400. return $oNode;
  1401. }
  1402. /**
  1403. * Returns the node directly under the current node, or null if missing
  1404. */
  1405. public function GetOptionalElement($sTagName)
  1406. {
  1407. return $this->GetUniqueElement($sTagName, false);
  1408. }
  1409. /**
  1410. * Returns the TEXT of the current node (possibly from several subnodes)
  1411. */
  1412. public function GetText($sDefault = null)
  1413. {
  1414. $sText = null;
  1415. foreach($this->childNodes as $oChildNode)
  1416. {
  1417. if ($oChildNode instanceof DOMCharacterData) // Base class of DOMText and DOMCdataSection
  1418. {
  1419. if (is_null($sText)) $sText = '';
  1420. $sText .= $oChildNode->wholeText;
  1421. }
  1422. }
  1423. if (is_null($sText))
  1424. {
  1425. return $sDefault;
  1426. }
  1427. else
  1428. {
  1429. return $sText;
  1430. }
  1431. }
  1432. /**
  1433. * Get the TEXT value from the child node
  1434. */
  1435. public function GetChildText($sTagName, $sDefault = null)
  1436. {
  1437. $sRet = $sDefault;
  1438. if ($oChild = $this->GetOptionalElement($sTagName))
  1439. {
  1440. $sRet = $oChild->GetText($sDefault);
  1441. }
  1442. return $sRet;
  1443. }
  1444. /**
  1445. * Assumes the current node to be either a text or
  1446. * <items>
  1447. * <item [key]="..."]>value<item>
  1448. * <item [key]="..."]>value<item>
  1449. * </items>
  1450. * where value can be the either a text or an array of items... recursively
  1451. * Returns a PHP array
  1452. */
  1453. public function GetNodeAsArrayOfItems($sElementName = 'items')
  1454. {
  1455. $oItems = $this->GetOptionalElement($sElementName);
  1456. if ($oItems)
  1457. {
  1458. $res = array();
  1459. $aRanks = array();
  1460. foreach($oItems->childNodes as $oItem)
  1461. {
  1462. if ($oItem instanceof DOMElement)
  1463. {
  1464. // When an attribute is missing
  1465. if ($oItem->hasAttribute('id'))
  1466. {
  1467. $key = $oItem->getAttribute('id');
  1468. if (array_key_exists($key, $res))
  1469. {
  1470. // Houston!
  1471. throw new DOMFormatException("Tag ".$oItem->getNodePath().", id '$key' already used!!!");
  1472. }
  1473. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1474. }
  1475. else
  1476. {
  1477. $res[] = $oItem->GetNodeAsArrayOfItems();
  1478. }
  1479. $sRank = $oItem->GetChildText('rank');
  1480. if ($sRank != '')
  1481. {
  1482. $aRanks[] = (float) $sRank;
  1483. }
  1484. else
  1485. {
  1486. $aRanks[] = count($aRanks) > 0 ? max($aRanks) + 1 : 0;
  1487. }
  1488. array_multisort($aRanks, $res);
  1489. }
  1490. }
  1491. }
  1492. else
  1493. {
  1494. $res = $this->GetText();
  1495. }
  1496. return $res;
  1497. }
  1498. public function SetNodeAsArrayOfItems($aList)
  1499. {
  1500. $oNewNode = $this->ownerDocument->CreateElement($this->tagName);
  1501. if ($this->getAttribute('id') != '')
  1502. {
  1503. $oNewNode->setAttribute('id', $this->getAttribute('id'));
  1504. }
  1505. self::AddItemToNode($this->ownerDocument, $oNewNode, $aList);
  1506. $this->parentNode->RedefineChildNode($oNewNode);
  1507. }
  1508. protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue)
  1509. {
  1510. if (is_array($itemValue))
  1511. {
  1512. $oXmlItems = $oXmlDoc->CreateElement('items');
  1513. $oXMLNode->AppendChild($oXmlItems);
  1514. foreach($itemValue as $key => $item)
  1515. {
  1516. $oXmlItem = $oXmlDoc->CreateElement('item');
  1517. $oXmlItems->AppendChild($oXmlItem);
  1518. if (is_string($key))
  1519. {
  1520. $oXmlItem->SetAttribute('key', $key);
  1521. }
  1522. self::AddItemToNode($oXmlDoc, $oXmlItem, $item);
  1523. }
  1524. }
  1525. else
  1526. {
  1527. $oXmlText = $oXmlDoc->CreateTextNode((string) $itemValue);
  1528. $oXMLNode->AppendChild($oXmlText);
  1529. }
  1530. }
  1531. /**
  1532. * Helper to remove child nodes
  1533. */
  1534. public function DeleteChildren()
  1535. {
  1536. while (isset($this->firstChild))
  1537. {
  1538. if ($this->firstChild instanceof MFElement)
  1539. {
  1540. $this->firstChild->DeleteChildren();
  1541. }
  1542. $this->removeChild($this->firstChild);
  1543. }
  1544. }
  1545. /**
  1546. * Find the child node matching the given node
  1547. * @param MFElement $oRefNode The node to search for
  1548. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1549. */
  1550. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1551. {
  1552. return self::FindNode($this, $oRefNode, $sSearchId);
  1553. }
  1554. /**
  1555. * Seems to work fine (and is about 10 times faster than above) EXCEPT for menus !!!!
  1556. * @param unknown_type $oParent
  1557. * @param unknown_type $oRefNode
  1558. * @param unknown_type $sSearchId
  1559. * @throws Exception
  1560. */
  1561. public static function FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1562. {
  1563. $oRes = null;
  1564. if ($oParent instanceof DOMDocument)
  1565. {
  1566. $oDoc = $oParent->firstChild->ownerDocument;
  1567. $oRoot = $oParent;
  1568. }
  1569. else
  1570. {
  1571. $oDoc = $oParent->ownerDocument;
  1572. $oRoot = $oParent;
  1573. }
  1574. $oXPath = new DOMXPath($oDoc);
  1575. if ($oRefNode->hasAttribute('id'))
  1576. {
  1577. // Find the first element having the same tag name and id
  1578. if (!$sSearchId)
  1579. {
  1580. $sSearchId = $oRefNode->getAttribute('id');
  1581. }
  1582. $sXPath = './'.$oRefNode->tagName."[@id='$sSearchId']";
  1583. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1584. }
  1585. else
  1586. {
  1587. // Get the first one having the same tag name (ignore others)
  1588. $sXPath = './'.$oRefNode->tagName;
  1589. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1590. }
  1591. return $oRes;
  1592. }
  1593. public function ListActiveChildNodes($sTagName)
  1594. {
  1595. $sXPath = $sTagName."[not(@_alteration) or @_alteration!='removed']";
  1596. return $this->GetNodes($sXPath);
  1597. }
  1598. /**
  1599. * Check if the current node is under a node 'added' or 'altered'
  1600. * Usage: In such a case, the change must not be tracked
  1601. */
  1602. public function IsInDefinition()
  1603. {
  1604. // Iterate through the parents: reset the flag if any of them has a flag set
  1605. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1606. {
  1607. if ($oParent->getAttribute('_alteration') != '')
  1608. {
  1609. return true;
  1610. }
  1611. }
  1612. return false;
  1613. }
  1614. /**
  1615. * Add a node and set the flags that will be used to compute the delta
  1616. * @param MFElement $oNode The node (including all subnodes) to add
  1617. */
  1618. public function AddChildNode(MFElement $oNode)
  1619. {
  1620. // First: cleanup any flag behind the new node
  1621. $oNode->ApplyChanges();
  1622. $oExisting = $this->FindExistingChildNode($oNode);
  1623. if ($oExisting)
  1624. {
  1625. if ($oExisting->getAttribute('_alteration') != 'removed')
  1626. {
  1627. throw new Exception("Attempting to add a node that already exists: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1628. }
  1629. $oExisting->ReplaceWith($oNode);
  1630. $sFlag = 'replaced';
  1631. }
  1632. else
  1633. {
  1634. $this->appendChild($oNode);
  1635. $sFlag = 'added';
  1636. }
  1637. if (!$this->IsInDefinition())
  1638. {
  1639. $oNode->setAttribute('_alteration', $sFlag);
  1640. }
  1641. }
  1642. /**
  1643. * Modify a node and set the flags that will be used to compute the delta
  1644. * @param MFElement $oNode The node (including all subnodes) to set
  1645. */
  1646. public function RedefineChildNode(MFElement $oNode, $sSearchId = null)
  1647. {
  1648. // First: cleanup any flag behind the new node
  1649. $oNode->ApplyChanges();
  1650. $oExisting = $this->FindExistingChildNode($oNode, $sSearchId);
  1651. if (!$oExisting)
  1652. {
  1653. throw new Exception("Attempting to modify a non existing node: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1654. }
  1655. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1656. if ($sPrevFlag == 'removed')
  1657. {
  1658. throw new Exception("Attempting to modify a deleted node: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1659. }
  1660. $oExisting->ReplaceWith($oNode);
  1661. if (!$this->IsInDefinition())
  1662. {
  1663. if ($sPrevFlag == '')
  1664. {
  1665. $sPrevFlag = 'replaced';
  1666. }
  1667. $oNode->setAttribute('_alteration', $sPrevFlag);
  1668. }
  1669. }
  1670. /**
  1671. * Combination of AddChildNode or RedefineChildNode... it depends
  1672. * This should become the preferred way of doing things (instead of implementing a test + the call to one of the APIs!
  1673. * @param MFElement $oNode The node (including all subnodes) to set
  1674. */
  1675. public function SetChildNode(MFElement $oNode, $sSearchId = null)
  1676. {
  1677. // First: cleanup any flag behind the new node
  1678. $oNode->ApplyChanges();
  1679. $oExisting = $this->FindExistingChildNode($oNode, $sSearchId);
  1680. if ($oExisting)
  1681. {
  1682. $sPrevFlag = $oExisting->getAttribute('_alteration');
  1683. if ($sPrevFlag == 'removed')
  1684. {
  1685. $sFlag = 'replaced';
  1686. }
  1687. else
  1688. {
  1689. $sFlag = $sPrevFlag; // added, replaced or ''
  1690. }
  1691. $oExisting->ReplaceWith($oNode);
  1692. }
  1693. else
  1694. {
  1695. $this->appendChild($oNode);
  1696. $sFlag = 'added';
  1697. }
  1698. if (!$this->IsInDefinition())
  1699. {
  1700. if ($sFlag == '')
  1701. {
  1702. $sFlag = 'replaced';
  1703. }
  1704. $oNode->setAttribute('_alteration', $sFlag);
  1705. }
  1706. }
  1707. /**
  1708. * Check that the current node is actually a class node, under classes
  1709. */
  1710. protected function IsClassNode()
  1711. {
  1712. if ($this->tagName == 'class')
  1713. {
  1714. return $this->parentNode->IsClassNode();
  1715. }
  1716. elseif ($this->tagName == 'classes')
  1717. {
  1718. return true;
  1719. }
  1720. else
  1721. {
  1722. return false;
  1723. }
  1724. }
  1725. /**
  1726. * Replaces a node by another one, making sure that recursive nodes are preserved
  1727. * @param MFElement $oNewNode The replacement
  1728. */
  1729. protected function ReplaceWith($oNewNode)
  1730. {
  1731. // Move the classes from the old node into the new one
  1732. if ($this->IsClassNode())
  1733. {
  1734. foreach($this->GetNodes('class') as $oChild)
  1735. {
  1736. $oNewNode->appendChild($oChild);
  1737. }
  1738. }
  1739. $oParentNode = $this->parentNode;
  1740. $oParentNode->replaceChild($oNewNode, $this);
  1741. }
  1742. /**
  1743. * Remove a node and set the flags that will be used to compute the delta
  1744. */
  1745. public function Delete()
  1746. {
  1747. $oParent = $this->parentNode;
  1748. switch ($this->getAttribute('_alteration'))
  1749. {
  1750. case 'replaced':
  1751. $sFlag = 'removed';
  1752. break;
  1753. case 'added':
  1754. case 'needed':
  1755. $sFlag = null;
  1756. break;
  1757. case 'removed':
  1758. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1759. default:
  1760. $sFlag = 'removed';
  1761. if ($this->IsInDefinition())
  1762. {
  1763. $sFlag = null;
  1764. break;
  1765. }
  1766. }
  1767. if ($sFlag)
  1768. {
  1769. $this->setAttribute('_alteration', $sFlag);
  1770. $this->DeleteChildren();
  1771. }
  1772. else
  1773. {
  1774. // Remove the node entirely
  1775. $this->parentNode->removeChild($this);
  1776. }
  1777. }
  1778. /**
  1779. * Merge the current node into the given container
  1780. *
  1781. * @param DOMNode $oContainer An element or a document
  1782. * @param string $sSearchId The id to consider (could be blank)
  1783. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1784. */
  1785. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1786. {
  1787. $oTargetNode = $oContainer->FindExistingChildNode($this, $sSearchId);
  1788. if ($oTargetNode)
  1789. {
  1790. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1791. {
  1792. if ($bMustExist)
  1793. {
  1794. throw new Exception("found mandatory node $this->tagName(id:$sSearchId) marked as deleted in ".$oContainer->getNodePath());
  1795. }
  1796. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1797. // So use this workaround to import a node and its attributes on *any* PHP version
  1798. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1799. $oContainer->AddChildNode($oTargetNode);
  1800. }
  1801. }
  1802. else
  1803. {
  1804. if ($bMustExist)
  1805. {
  1806. echo "Dumping parent node<br/>\n";
  1807. $oContainer->Dump();
  1808. throw new Exception("could not find $this->tagName(id:$sSearchId) in ".$oContainer->getNodePath());
  1809. }
  1810. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1811. // So use this workaround to import a node and its attributes on *any* PHP version
  1812. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1813. $oContainer->AddChildNode($oTargetNode);
  1814. }
  1815. return $oTargetNode;
  1816. }
  1817. /**
  1818. * Renames a node and set the flags that will be used to compute the delta
  1819. * @param String $sNewId The new id
  1820. */
  1821. public function Rename($sId)
  1822. {
  1823. if (($this->getAttribute('_alteration') == 'replaced') || !$this->IsInDefinition())
  1824. {
  1825. $sOriginalId = $this->getAttribute('_old_id');
  1826. if ($sOriginalId == '')
  1827. {
  1828. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1829. }
  1830. else if($sOriginalId == $sId)
  1831. {
  1832. $this->removeAttribute('_old_id');
  1833. }
  1834. }
  1835. $this->setAttribute('id', $sId);
  1836. }
  1837. /**
  1838. * Apply extensibility rules onto this node
  1839. * @param array aRules Array of rules (strings)
  1840. * @return void
  1841. */
  1842. public function RestrictExtensibility($aRules)
  1843. {
  1844. $oRulesNode = $this->GetOptionalElement('rules');
  1845. if ($oRulesNode)
  1846. {
  1847. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1848. $aCurrentRules = array_merge($aCurrentRules, $aRules);
  1849. $oRulesNode->SetNodeAsArrayOfItems($aCurrentRules);
  1850. }
  1851. else
  1852. {
  1853. $oNewNode = $this->ownerDocument->CreateElement('rules');
  1854. $this->appendChild($oNewNode);
  1855. $oNewNode->SetNodeAsArrayOfItems($aRules);
  1856. }
  1857. }
  1858. /**
  1859. * Read extensibility rules for this node
  1860. * @return Array of rules (strings)
  1861. */
  1862. public function GetExtensibilityRules()
  1863. {
  1864. $aCurrentRules = array();
  1865. $oRulesNode = $this->GetOptionalElement('rules');
  1866. if ($oRulesNode)
  1867. {
  1868. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1869. }
  1870. return $aCurrentRules;
  1871. }
  1872. /**
  1873. * List changes below a given node (see also MFDocument::ListChanges)
  1874. */
  1875. public function ListChanges()
  1876. {
  1877. // Note: omitting the dot will make the query be global to the whole document!!!
  1878. return $this->GetNodes('.//*[@_alteration or @_old_id]');
  1879. }
  1880. /**
  1881. * List changes below a given node (see also MFDocument::ApplyChanges)
  1882. */
  1883. public function ApplyChanges()
  1884. {
  1885. $oNodes = $this->ListChanges();
  1886. foreach($oNodes as $oNode)
  1887. {
  1888. $sOperation = $oNode->GetAttribute('_alteration');
  1889. switch($sOperation)
  1890. {
  1891. case 'added':
  1892. case 'replaced':
  1893. case 'needed':
  1894. // marked as added or modified, just reset the flag
  1895. $oNode->removeAttribute('_alteration');
  1896. break;
  1897. case 'removed':
  1898. // marked as deleted, let's remove the node from the tree
  1899. $oNode->parentNode->removeChild($oNode);
  1900. break;
  1901. }
  1902. if ($oNode->hasAttribute('_old_id'))
  1903. {
  1904. $oNode->removeAttribute('_old_id');
  1905. }
  1906. }
  1907. }
  1908. }
  1909. /**
  1910. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1911. */
  1912. if (!class_exists('DOMDocument'))
  1913. {
  1914. class DOMDocument {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1915. }
  1916. /**
  1917. * MFDocument - formating rules for XML input/output
  1918. * @package ModelFactory
  1919. */
  1920. class MFDocument extends DOMDocument
  1921. {
  1922. public function __construct()
  1923. {
  1924. parent::__construct('1.0', 'UTF-8');
  1925. $this->registerNodeClass('DOMElement', 'MFElement');
  1926. $this->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1927. $this->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1928. }
  1929. /**
  1930. * Overload of the standard API
  1931. */
  1932. public function load($filename, $options = 0)
  1933. {
  1934. parent::load($filename, LIBXML_NOBLANKS);
  1935. }
  1936. /**
  1937. * Overload of the standard API
  1938. */
  1939. public function loadXML($source, $options = 0)
  1940. {
  1941. parent::loadXML($source, LIBXML_NOBLANKS);
  1942. }
  1943. /**
  1944. * Overload the standard API
  1945. */
  1946. public function saveXML(DOMNode $node = null, $options = 0)
  1947. {
  1948. $oRootNode = $this->firstChild;
  1949. if (!$oRootNode)
  1950. {
  1951. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1952. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1953. $this->appendChild($oRootNode);
  1954. }
  1955. return parent::saveXML();
  1956. }
  1957. /**
  1958. * For debugging purposes
  1959. */
  1960. public function Dump($bReturnRes = false)
  1961. {
  1962. $sXml = $this->saveXML();
  1963. if ($bReturnRes)
  1964. {
  1965. return $sXml;
  1966. }
  1967. else
  1968. {
  1969. echo "<pre>\n";
  1970. echo htmlentities($sXml);
  1971. echo "</pre>\n";
  1972. }
  1973. }
  1974. /**
  1975. * Find the child node matching the given node
  1976. * @param MFElement $oRefNode The node to search for
  1977. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1978. */
  1979. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1980. {
  1981. return MFElement::FindNode($this, $oRefNode, $sSearchId);
  1982. }
  1983. /**
  1984. * Extracts some nodes from the DOM
  1985. * @param string $sXPath A XPath expression
  1986. * @return DOMNodeList
  1987. */
  1988. public function GetNodes($sXPath, $oContextNode = null)
  1989. {
  1990. $oXPath = new DOMXPath($this);
  1991. if (is_null($oContextNode))
  1992. {
  1993. return $oXPath->query($sXPath);
  1994. }
  1995. else
  1996. {
  1997. return $oXPath->query($sXPath, $oContextNode);
  1998. }
  1999. }
  2000. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  2001. {
  2002. $oXPath = new DOMXPath($this);
  2003. $sXPath .= "[@id='$sId' and(not(@_alteration) or @_alteration!='removed')]";
  2004. if (is_null($oContextNode))
  2005. {
  2006. return $oXPath->query($sXPath);
  2007. }
  2008. else
  2009. {
  2010. return $oXPath->query($sXPath, $oContextNode);
  2011. }
  2012. }
  2013. }