modelfactory.class.inc.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  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()
  1111. {
  1112. $oDelta = new MFDocument();
  1113. foreach($this->ListChanges() as $oAlteredNode)
  1114. {
  1115. $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode);
  1116. }
  1117. return $oDelta->saveXML();
  1118. }
  1119. /**
  1120. * Searches on disk in the root directories for module description files
  1121. * and returns an array of MFModules
  1122. * @return array Array of MFModules
  1123. */
  1124. public function FindModules()
  1125. {
  1126. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->aRootDirs);
  1127. $aResult = array();
  1128. foreach($aAvailableModules as $sId => $aModule)
  1129. {
  1130. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  1131. }
  1132. return $aResult;
  1133. }
  1134. public function TestAlteration()
  1135. {
  1136. try
  1137. {
  1138. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  1139. $sOriginalXML =
  1140. <<<EOF
  1141. $sHeader
  1142. <itop_design>
  1143. <a id="first a">
  1144. <b>Text</b>
  1145. <c id="1">
  1146. <d>D1</d>
  1147. <d>D2</d>
  1148. </c>
  1149. </a>
  1150. <a id="second a">
  1151. <parent>first a</parent>
  1152. </a>
  1153. <a id="third a">
  1154. <parent>first a</parent>
  1155. <x>blah</x>
  1156. </a>
  1157. </itop_design>
  1158. EOF;
  1159. $this->oDOMDocument = new MFDocument();
  1160. $this->oDOMDocument->loadXML($sOriginalXML);
  1161. // DOM Get the original values, then modify its contents by the mean of the API
  1162. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1163. //$oRoot->Dump();
  1164. $sDOMOriginal = $oRoot->Dump(true);
  1165. $oNode = $oRoot->GetNodes('a/b')->item(0);
  1166. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  1167. $oNode->parentNode->RedefineChildNode($oNew);
  1168. $oNode = $oRoot->GetNodes('a/c')->item(0);
  1169. $oNewC = $this->oDOMDocument->CreateElement('c');
  1170. $oNewC->setAttribute('id', '1');
  1171. $oNode->parentNode->RedefineChildNode($oNewC);
  1172. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  1173. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  1174. $oNewC->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  1175. $oNamedNode = $this->oDOMDocument->CreateElement('z');
  1176. $oNamedNode->setAttribute('id', 'abc');
  1177. $oNewC->AddChildNode($oNamedNode);
  1178. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('r', 'to be replaced'));
  1179. // Alter this "modified node", no flag should be set in its subnodes
  1180. $oNewC->Rename('blah');
  1181. $oNewC->Rename('foo');
  1182. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('y', '(no flag)'));
  1183. $oNewC->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1184. $oSubNode = $oNewC->GetUniqueElement('z');
  1185. $oSubNode->Rename('abcdef');
  1186. $oSubNode = $oNewC->GetUniqueElement('x');
  1187. $oSubNode->Delete();
  1188. $oNewC->RedefineChildNode($this->oDOMDocument->CreateElement('r', 'replacement'));
  1189. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  1190. $oNode->Rename('el 2o A');
  1191. $oNode->Rename('el secundo A');
  1192. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  1193. $oNode->AddChildNode($oNew);
  1194. $oNewA = $this->oDOMDocument->CreateElement('a');
  1195. $oNewA->setAttribute('id', 'new a');
  1196. $oNode->AddChildNode($oNewA);
  1197. $oSubnode = $this->oDOMDocument->CreateElement('parent', 'el secundo A');
  1198. $oSubnode->setAttribute('id', 'to be changed');
  1199. $oNewA->AddChildNode($oSubnode);
  1200. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  1201. $oNewA->AddChildNode($this->oDOMDocument->CreateElement('x', 'To delete programatically'));
  1202. // Alter this "new a", as it is new, no flag should be set
  1203. $oNewA->Rename('new_a');
  1204. $oSubNode = $oNewA->GetUniqueElement('parent');
  1205. $oSubNode->Rename('alter ego');
  1206. $oNewA->RedefineChildNode($this->oDOMDocument->CreateElement('f', 'dummy data'));
  1207. $oSubNode = $oNewA->GetUniqueElement('x');
  1208. $oSubNode->Delete();
  1209. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  1210. $oNode->Delete();
  1211. //$oRoot->Dump();
  1212. $sDOMModified = $oRoot->Dump(true);
  1213. // Compute the delta
  1214. //
  1215. $sDeltaXML = $this->GetDelta();
  1216. //echo "<pre>\n";
  1217. //echo htmlentities($sDeltaXML);
  1218. //echo "</pre>\n";
  1219. // Reiterating - try to remake the DOM by applying the computed delta
  1220. //
  1221. $this->oDOMDocument = new MFDocument();
  1222. $this->oDOMDocument->loadXML($sOriginalXML);
  1223. $oRoot = $this->GetNodes('//itop_design')->item(0);
  1224. //$oRoot->Dump();
  1225. echo "<h4>Rebuild the DOM - Delta applied...</h4>\n";
  1226. $oDeltaDoc = new MFDocument();
  1227. $oDeltaDoc->loadXML($sDeltaXML);
  1228. //$oDeltaDoc->Dump();
  1229. //$this->oDOMDocument->Dump();
  1230. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  1231. $this->LoadDelta($oDeltaDoc, $oDeltaRoot, $this->oDOMDocument);
  1232. //$oRoot->Dump();
  1233. $sDOMRebuilt = $oRoot->Dump(true);
  1234. }
  1235. catch (Exception $e)
  1236. {
  1237. echo "<h1>Exception: ".$e->getMessage()."</h1>\n";
  1238. echo "<pre>\n";
  1239. debug_print_backtrace();
  1240. echo "</pre>\n";
  1241. }
  1242. $sArrStyle = "font-size: 40;";
  1243. echo "<table>\n";
  1244. echo " <tr>\n";
  1245. echo " <td width=\"50%\">\n";
  1246. echo " <h4>DOM - Original values</h4>\n";
  1247. echo " <pre>".htmlentities($sDOMOriginal)."</pre>\n";
  1248. echo " </td>\n";
  1249. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1250. echo " </tr>\n";
  1251. 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";
  1252. echo " <tr>\n";
  1253. echo " <td width=\"50%\">\n";
  1254. echo " <h4>DOM - Altered with various changes</h4>\n";
  1255. echo " <pre>".htmlentities($sDOMModified)."</pre>\n";
  1256. echo " </td>\n";
  1257. echo " <td width=\"50%\">\n";
  1258. echo " <h4>DOM - Rebuilt from the Delta</h4>\n";
  1259. echo " <pre>".htmlentities($sDOMRebuilt)."</pre>\n";
  1260. echo " </td>\n";
  1261. echo " </tr>\n";
  1262. echo " <tr><td align=\"center\"><span style=\"$sArrStyle\">&dArr;</div></td><td align=\"center\"><span style=\"$sArrStyle\">&uArr;</div></td></tr>\n";
  1263. echo " <td width=\"50%\">\n";
  1264. echo " <h4>Delta (Computed by ModelFactory)</h4>\n";
  1265. echo " <pre>".htmlentities($sDeltaXML)."</pre>\n";
  1266. echo " </td>\n";
  1267. echo " <td width=\"50%\" align=\"left\" valign=\"center\"><span style=\"$sArrStyle\">&rArr; &rArr; &rArr;</span></td>\n";
  1268. echo " </tr>\n";
  1269. echo "</table>\n";
  1270. } // TEST !
  1271. /**
  1272. * Extracts some nodes from the DOM
  1273. * @param string $sXPath A XPath expression
  1274. * @return DOMNodeList
  1275. */
  1276. public function GetNodes($sXPath, $oContextNode = null)
  1277. {
  1278. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode);
  1279. }
  1280. public function ListActiveChildNodes($sContextXPath, $sTagName)
  1281. {
  1282. $oContextPath = $this->oRoot->GetNodes($sContextXPath)->item(0);
  1283. return $oContextPath->ListActiveChildNodes($sTagName);
  1284. }
  1285. }
  1286. /**
  1287. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1288. */
  1289. if (!class_exists('DOMElement'))
  1290. {
  1291. class DOMElement {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1292. }
  1293. /**
  1294. * MFElement: helper to read/change the DOM
  1295. * @package ModelFactory
  1296. */
  1297. class MFElement extends DOMElement
  1298. {
  1299. /**
  1300. * Extracts some nodes from the DOM
  1301. * @param string $sXPath A XPath expression
  1302. * @return DOMNodeList
  1303. */
  1304. public function GetNodes($sXPath)
  1305. {
  1306. return $this->ownerDocument->GetNodes($sXPath, $this);
  1307. }
  1308. /**
  1309. * Extracts some nodes from the DOM (active nodes only !!!)
  1310. * @param string $sXPath A XPath expression
  1311. * @return DOMNodeList
  1312. */
  1313. public function GetNodeById($sXPath, $sId)
  1314. {
  1315. return $this->ownerDocument->GetNodeById($sXPath, $sId, $this);
  1316. }
  1317. /**
  1318. * For debugging purposes - but this is currently buggy: the whole document is rendered
  1319. */
  1320. public function Dump($bReturnRes = false)
  1321. {
  1322. $oMFDoc = new MFDocument();
  1323. $oClone = $oMFDoc->importNode($this->cloneNode(true), true);
  1324. $oMFDoc->appendChild($oClone);
  1325. $sXml = $oMFDoc->saveXML($oClone);
  1326. if ($bReturnRes)
  1327. {
  1328. return $sXml;
  1329. }
  1330. else
  1331. {
  1332. echo "<pre>\n";
  1333. echo htmlentities($sXml);
  1334. echo "</pre>\n";
  1335. }
  1336. }
  1337. /**
  1338. * Returns the node directly under the given node
  1339. */
  1340. public function GetUniqueElement($sTagName, $bMustExist = true)
  1341. {
  1342. $oNode = null;
  1343. foreach($this->childNodes as $oChildNode)
  1344. {
  1345. if ($oChildNode->nodeName == $sTagName)
  1346. {
  1347. $oNode = $oChildNode;
  1348. break;
  1349. }
  1350. }
  1351. if ($bMustExist && is_null($oNode))
  1352. {
  1353. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1354. }
  1355. return $oNode;
  1356. }
  1357. /**
  1358. * Returns the node directly under the current node, or null if missing
  1359. */
  1360. public function GetOptionalElement($sTagName)
  1361. {
  1362. return $this->GetUniqueElement($sTagName, false);
  1363. }
  1364. /**
  1365. * Returns the TEXT of the current node (possibly from several subnodes)
  1366. */
  1367. public function GetText($sDefault = null)
  1368. {
  1369. $sText = null;
  1370. foreach($this->childNodes as $oChildNode)
  1371. {
  1372. if ($oChildNode instanceof DOMCharacterData) // Base class of DOMText and DOMCdataSection
  1373. {
  1374. if (is_null($sText)) $sText = '';
  1375. $sText .= $oChildNode->wholeText;
  1376. }
  1377. }
  1378. if (is_null($sText))
  1379. {
  1380. return $sDefault;
  1381. }
  1382. else
  1383. {
  1384. return $sText;
  1385. }
  1386. }
  1387. /**
  1388. * Get the TEXT value from the child node
  1389. */
  1390. public function GetChildText($sTagName, $sDefault = null)
  1391. {
  1392. $sRet = $sDefault;
  1393. if ($oChild = $this->GetOptionalElement($sTagName))
  1394. {
  1395. $sRet = $oChild->GetText($sDefault);
  1396. }
  1397. return $sRet;
  1398. }
  1399. /**
  1400. * Assumes the current node to be either a text or
  1401. * <items>
  1402. * <item [key]="..."]>value<item>
  1403. * <item [key]="..."]>value<item>
  1404. * </items>
  1405. * where value can be the either a text or an array of items... recursively
  1406. * Returns a PHP array
  1407. */
  1408. public function GetNodeAsArrayOfItems($sElementName = 'items')
  1409. {
  1410. $oItems = $this->GetOptionalElement($sElementName);
  1411. if ($oItems)
  1412. {
  1413. $res = array();
  1414. $aRanks = array();
  1415. foreach($oItems->childNodes as $oItem)
  1416. {
  1417. if ($oItem instanceof DOMElement)
  1418. {
  1419. // When an attribute is missing
  1420. if ($oItem->hasAttribute('id'))
  1421. {
  1422. $key = $oItem->getAttribute('id');
  1423. if (array_key_exists($key, $res))
  1424. {
  1425. // Houston!
  1426. throw new DOMFormatException("Tag ".$oItem->getNodePath().", id '$key' already used!!!");
  1427. }
  1428. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1429. }
  1430. else
  1431. {
  1432. $res[] = $oItem->GetNodeAsArrayOfItems();
  1433. }
  1434. $sRank = $oItem->GetChildText('rank');
  1435. if ($sRank != '')
  1436. {
  1437. $aRanks[] = (float) $sRank;
  1438. }
  1439. else
  1440. {
  1441. $aRanks[] = count($aRanks) > 0 ? max($aRanks) + 1 : 0;
  1442. }
  1443. array_multisort($aRanks, $res);
  1444. }
  1445. }
  1446. }
  1447. else
  1448. {
  1449. $res = $this->GetText();
  1450. }
  1451. return $res;
  1452. }
  1453. public function SetNodeAsArrayOfItems($aList)
  1454. {
  1455. $oNewNode = $this->ownerDocument->CreateElement($this->tagName);
  1456. if ($this->getAttribute('id') != '')
  1457. {
  1458. $oNewNode->setAttribute('id', $this->getAttribute('id'));
  1459. }
  1460. self::AddItemToNode($this->ownerDocument, $oNewNode, $aList);
  1461. $this->parentNode->RedefineChildNode($oNewNode);
  1462. }
  1463. protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue)
  1464. {
  1465. if (is_array($itemValue))
  1466. {
  1467. $oXmlItems = $oXmlDoc->CreateElement('items');
  1468. $oXMLNode->AppendChild($oXmlItems);
  1469. foreach($itemValue as $key => $item)
  1470. {
  1471. $oXmlItem = $oXmlDoc->CreateElement('item');
  1472. $oXmlItems->AppendChild($oXmlItem);
  1473. if (is_string($key))
  1474. {
  1475. $oXmlItem->SetAttribute('key', $key);
  1476. }
  1477. self::AddItemToNode($oXmlDoc, $oXmlItem, $item);
  1478. }
  1479. }
  1480. else
  1481. {
  1482. $oXmlText = $oXmlDoc->CreateTextNode((string) $itemValue);
  1483. $oXMLNode->AppendChild($oXmlText);
  1484. }
  1485. }
  1486. /**
  1487. * Helper to remove child nodes
  1488. */
  1489. public function DeleteChildren()
  1490. {
  1491. while (isset($this->firstChild))
  1492. {
  1493. if ($this->firstChild instanceof MFElement)
  1494. {
  1495. $this->firstChild->DeleteChildren();
  1496. }
  1497. $this->removeChild($this->firstChild);
  1498. }
  1499. }
  1500. /**
  1501. * Find the child node matching the given node
  1502. * @param MFElement $oRefNode The node to search for
  1503. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1504. */
  1505. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1506. {
  1507. return self::FindNode($this, $oRefNode, $sSearchId);
  1508. }
  1509. /**
  1510. * Seems to work fine (and is about 10 times faster than above) EXCEPT for menus !!!!
  1511. * @param unknown_type $oParent
  1512. * @param unknown_type $oRefNode
  1513. * @param unknown_type $sSearchId
  1514. * @throws Exception
  1515. */
  1516. public static function FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1517. {
  1518. $oRes = null;
  1519. if ($oParent instanceof DOMDocument)
  1520. {
  1521. $oDoc = $oParent->firstChild->ownerDocument;
  1522. $oRoot = $oParent;
  1523. }
  1524. else
  1525. {
  1526. $oDoc = $oParent->ownerDocument;
  1527. $oRoot = $oParent;
  1528. }
  1529. $oXPath = new DOMXPath($oDoc);
  1530. if ($oRefNode->hasAttribute('id'))
  1531. {
  1532. // Find the first element having the same tag name and id
  1533. if (!$sSearchId)
  1534. {
  1535. $sSearchId = $oRefNode->getAttribute('id');
  1536. }
  1537. $sXPath = './'.$oRefNode->tagName."[@id='$sSearchId']";
  1538. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1539. }
  1540. else
  1541. {
  1542. // Get the first one having the same tag name (ignore others)
  1543. $sXPath = './'.$oRefNode->tagName;
  1544. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1545. }
  1546. return $oRes;
  1547. }
  1548. public function ListActiveChildNodes($sTagName)
  1549. {
  1550. $sXPath = $sTagName."[not(@_alteration) or @_alteration!='removed']";
  1551. return $this->GetNodes($sXPath);
  1552. }
  1553. /**
  1554. * Check if the current node is under a node 'added' or 'altered'
  1555. * Usage: In such a case, the change must not be tracked
  1556. */
  1557. protected function IsInDefinition()
  1558. {
  1559. // Iterate through the parents: reset the flag if any of them has a flag set
  1560. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1561. {
  1562. if ($oParent->getAttribute('_alteration') != '')
  1563. {
  1564. return true;
  1565. }
  1566. }
  1567. return false;
  1568. }
  1569. /**
  1570. * Add a node and set the flags that will be used to compute the delta
  1571. * @param MFElement $oNode The node (including all subnodes) to add
  1572. */
  1573. public function AddChildNode(MFElement $oNode)
  1574. {
  1575. // First: cleanup any flag behind the new node
  1576. $oNode->ApplyChanges();
  1577. $oExisting = $this->FindExistingChildNode($oNode);
  1578. if ($oExisting)
  1579. {
  1580. if ($oExisting->getAttribute('_alteration') != 'removed')
  1581. {
  1582. throw new Exception("Attempting to add a node that already exists: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1583. }
  1584. $oExisting->ReplaceWith($oNode);
  1585. $sFlag = 'replaced';
  1586. }
  1587. else
  1588. {
  1589. $this->appendChild($oNode);
  1590. $sFlag = 'added';
  1591. }
  1592. if (!$this->IsInDefinition())
  1593. {
  1594. $oNode->setAttribute('_alteration', $sFlag);
  1595. }
  1596. }
  1597. /**
  1598. * Modify a node and set the flags that will be used to compute the delta
  1599. * @param MFElement $oNode The node (including all subnodes) to set
  1600. */
  1601. public function RedefineChildNode(MFElement $oNode, $sSearchId = null)
  1602. {
  1603. // First: cleanup any flag behind the new node
  1604. $oNode->ApplyChanges();
  1605. $oExisting = $this->FindExistingChildNode($oNode, $sSearchId);
  1606. if (!$oExisting)
  1607. {
  1608. throw new Exception("Attempting to modify a non existing node: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1609. }
  1610. if ($oExisting->getAttribute('_alteration') == 'removed')
  1611. {
  1612. throw new Exception("Attempting to modify a deleted node: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1613. }
  1614. $oExisting->ReplaceWith($oNode);
  1615. if (!$this->IsInDefinition())
  1616. {
  1617. $oNode->setAttribute('_alteration', 'replaced');
  1618. }
  1619. }
  1620. /**
  1621. * Replaces a node by another one, making sure that recursive nodes are preserved
  1622. * @param MFElement $oNewNode The replacement
  1623. */
  1624. protected function ReplaceWith($oNewNode)
  1625. {
  1626. // Move the classes from the old node into the new one
  1627. foreach($this->GetNodes('class') as $oChild)
  1628. {
  1629. $oNewNode->appendChild($oChild);
  1630. }
  1631. $oParentNode = $this->parentNode;
  1632. $oParentNode->replaceChild($oNewNode, $this);
  1633. }
  1634. /**
  1635. * Remove a node and set the flags that will be used to compute the delta
  1636. */
  1637. public function Delete()
  1638. {
  1639. $oParent = $this->parentNode;
  1640. switch ($this->getAttribute('_alteration'))
  1641. {
  1642. case 'replaced':
  1643. $sFlag = 'removed';
  1644. break;
  1645. case 'added':
  1646. $sFlag = null;
  1647. break;
  1648. case 'removed':
  1649. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1650. default:
  1651. $sFlag = 'removed';
  1652. if ($this->IsInDefinition())
  1653. {
  1654. $sFlag = null;
  1655. break;
  1656. }
  1657. }
  1658. if ($sFlag)
  1659. {
  1660. $this->setAttribute('_alteration', $sFlag);
  1661. $this->DeleteChildren();
  1662. }
  1663. else
  1664. {
  1665. // Remove the node entirely
  1666. $this->parentNode->removeChild($this);
  1667. }
  1668. }
  1669. /**
  1670. * Merge the current node into the given container
  1671. *
  1672. * @param DOMNode $oContainer An element or a document
  1673. * @param string $sSearchId The id to consider (could be blank)
  1674. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1675. */
  1676. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1677. {
  1678. $oTargetNode = $oContainer->FindExistingChildNode($this, $sSearchId);
  1679. if ($oTargetNode)
  1680. {
  1681. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1682. {
  1683. if ($bMustExist)
  1684. {
  1685. throw new Exception("found mandatory node $this->tagName(id:$sSearchId) marked as deleted in ".$oContainer->getNodePath());
  1686. }
  1687. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1688. // So use this workaround to import a node and its attributes on *any* PHP version
  1689. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1690. $oContainer->AddChildNode($oTargetNode);
  1691. }
  1692. }
  1693. else
  1694. {
  1695. if ($bMustExist)
  1696. {
  1697. echo "Dumping parent node<br/>\n";
  1698. $oContainer->Dump();
  1699. throw new Exception("could not find $this->tagName(id:$sSearchId) in ".$oContainer->getNodePath());
  1700. }
  1701. // Beware: ImportNode(xxx, false) DOES NOT copy the node's attribute on *some* PHP versions (<5.2.17)
  1702. // So use this workaround to import a node and its attributes on *any* PHP version
  1703. $oTargetNode = $oContainer->ownerDocument->ImportNode($this->cloneNode(false), true);
  1704. $oContainer->AddChildNode($oTargetNode);
  1705. }
  1706. return $oTargetNode;
  1707. }
  1708. /**
  1709. * Renames a node and set the flags that will be used to compute the delta
  1710. * @param String $sNewId The new id
  1711. */
  1712. public function Rename($sId)
  1713. {
  1714. if (($this->getAttribute('_alteration') == 'replaced') || !$this->IsInDefinition())
  1715. {
  1716. $sOriginalId = $this->getAttribute('_old_id');
  1717. if ($sOriginalId == '')
  1718. {
  1719. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1720. }
  1721. else if($sOriginalId == $sId)
  1722. {
  1723. $this->removeAttribute('_old_id');
  1724. }
  1725. }
  1726. $this->setAttribute('id', $sId);
  1727. }
  1728. /**
  1729. * Apply extensibility rules onto this node
  1730. * @param array aRules Array of rules (strings)
  1731. * @return void
  1732. */
  1733. public function RestrictExtensibility($aRules)
  1734. {
  1735. $oRulesNode = $this->GetOptionalElement('rules');
  1736. if ($oRulesNode)
  1737. {
  1738. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1739. $aCurrentRules = array_merge($aCurrentRules, $aRules);
  1740. $oRulesNode->SetNodeAsArrayOfItems($aCurrentRules);
  1741. }
  1742. else
  1743. {
  1744. $oNewNode = $this->ownerDocument->CreateElement('rules');
  1745. $this->appendChild($oNewNode);
  1746. $oNewNode->SetNodeAsArrayOfItems($aRules);
  1747. }
  1748. }
  1749. /**
  1750. * Read extensibility rules for this node
  1751. * @return Array of rules (strings)
  1752. */
  1753. public function GetExtensibilityRules()
  1754. {
  1755. $aCurrentRules = array();
  1756. $oRulesNode = $this->GetOptionalElement('rules');
  1757. if ($oRulesNode)
  1758. {
  1759. $aCurrentRules = $oRulesNode->GetNodeAsArrayOfItems();
  1760. }
  1761. return $aCurrentRules;
  1762. }
  1763. /**
  1764. * List changes below a given node (see also MFDocument::ListChanges)
  1765. */
  1766. public function ListChanges()
  1767. {
  1768. // Note: omitting the dot will make the query be global to the whole document!!!
  1769. return $this->GetNodes('.//*[@_alteration or @_old_id]');
  1770. }
  1771. /**
  1772. * List changes below a given node (see also MFDocument::ApplyChanges)
  1773. */
  1774. public function ApplyChanges()
  1775. {
  1776. $oNodes = $this->ListChanges();
  1777. foreach($oNodes as $oNode)
  1778. {
  1779. $sOperation = $oNode->GetAttribute('_alteration');
  1780. switch($sOperation)
  1781. {
  1782. case 'added':
  1783. case 'replaced':
  1784. // marked as added or modified, just reset the flag
  1785. $oNode->removeAttribute('_alteration');
  1786. break;
  1787. case 'removed':
  1788. // marked as deleted, let's remove the node from the tree
  1789. $oNode->parentNode->removeChild($oNode);
  1790. break;
  1791. }
  1792. if ($oNode->hasAttribute('_old_id'))
  1793. {
  1794. $oNode->removeAttribute('_old_id');
  1795. }
  1796. }
  1797. }
  1798. }
  1799. /**
  1800. * Allow the setup page to load and perform its checks (including the check about the required extensions)
  1801. */
  1802. if (!class_exists('DOMDocument'))
  1803. {
  1804. class DOMDocument {function __construct(){throw new Exception('The dom extension is not enabled');}}
  1805. }
  1806. /**
  1807. * MFDocument - formating rules for XML input/output
  1808. * @package ModelFactory
  1809. */
  1810. class MFDocument extends DOMDocument
  1811. {
  1812. public function __construct()
  1813. {
  1814. parent::__construct('1.0', 'UTF-8');
  1815. $this->registerNodeClass('DOMElement', 'MFElement');
  1816. $this->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1817. $this->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1818. }
  1819. /**
  1820. * Overload of the standard API
  1821. */
  1822. public function load($filename, $options = 0)
  1823. {
  1824. parent::load($filename, LIBXML_NOBLANKS);
  1825. }
  1826. /**
  1827. * Overload of the standard API
  1828. */
  1829. public function loadXML($source, $options = 0)
  1830. {
  1831. parent::loadXML($source, LIBXML_NOBLANKS);
  1832. }
  1833. /**
  1834. * Overload the standard API
  1835. */
  1836. public function saveXML(DOMNode $node = null, $options = 0)
  1837. {
  1838. $oRootNode = $this->firstChild;
  1839. if (!$oRootNode)
  1840. {
  1841. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1842. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1843. $this->appendChild($oRootNode);
  1844. }
  1845. return parent::saveXML();
  1846. }
  1847. /**
  1848. * For debugging purposes
  1849. */
  1850. public function Dump($bReturnRes = false)
  1851. {
  1852. $sXml = $this->saveXML();
  1853. if ($bReturnRes)
  1854. {
  1855. return $sXml;
  1856. }
  1857. else
  1858. {
  1859. echo "<pre>\n";
  1860. echo htmlentities($sXml);
  1861. echo "</pre>\n";
  1862. }
  1863. }
  1864. /**
  1865. * Find the child node matching the given node
  1866. * @param MFElement $oRefNode The node to search for
  1867. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1868. */
  1869. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1870. {
  1871. return MFElement::FindNode($this, $oRefNode, $sSearchId);
  1872. }
  1873. /**
  1874. * Extracts some nodes from the DOM
  1875. * @param string $sXPath A XPath expression
  1876. * @return DOMNodeList
  1877. */
  1878. public function GetNodes($sXPath, $oContextNode = null)
  1879. {
  1880. $oXPath = new DOMXPath($this);
  1881. if (is_null($oContextNode))
  1882. {
  1883. return $oXPath->query($sXPath);
  1884. }
  1885. else
  1886. {
  1887. return $oXPath->query($sXPath, $oContextNode);
  1888. }
  1889. }
  1890. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  1891. {
  1892. $oXPath = new DOMXPath($this);
  1893. $sXPath .= "[@id='$sId' and(not(@_alteration) or @_alteration!='removed')]";
  1894. if (is_null($oContextNode))
  1895. {
  1896. return $oXPath->query($sXPath);
  1897. }
  1898. else
  1899. {
  1900. return $oXPath->query($sXPath, $oContextNode);
  1901. }
  1902. }
  1903. }