modelfactory.class.inc.php 61 KB

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