modelfactory.class.inc.php 59 KB

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