modelfactory.class.inc.php 64 KB

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