modelfactory.class.inc.php 65 KB

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