modelfactory.class.inc.php 58 KB

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