modelfactory.class.inc.php 60 KB

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