modelfactory.class.inc.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. <?php
  2. // Copyright (C) 2011 Combodo SARL
  3. //
  4. /**
  5. * ModelFactory: in-memory manipulation of the XML MetaModel
  6. *
  7. * @author Erwan Taloc <erwan.taloc@combodo.com>
  8. * @author Romain Quetiez <romain.quetiez@combodo.com>
  9. * @author Denis Flaven <denis.flaven@combodo.com>
  10. * @license Combodo Private
  11. */
  12. require_once(APPROOT.'setup/moduleinstaller.class.inc.php');
  13. /**
  14. * ModelFactoryModule: the representation of a Module (i.e. element that can be selected during the setup)
  15. * @package ModelFactory
  16. */
  17. class MFModule
  18. {
  19. protected $sId;
  20. protected $sName;
  21. protected $sVersion;
  22. protected $sRootDir;
  23. protected $sLabel;
  24. protected $aDataModels;
  25. public function __construct($sId, $sRootDir, $sLabel)
  26. {
  27. $this->sId = $sId;
  28. list($this->sName, $this->sVersion) = ModuleDiscovery::GetModuleName($sId);
  29. if (strlen($this->sVersion) == 0)
  30. {
  31. $this->sVersion = '1.0.0';
  32. }
  33. $this->sRootDir = $sRootDir;
  34. $this->sLabel = $sLabel;
  35. $this->aDataModels = array();
  36. // Scan the module's root directory to find the datamodel(*).xml files
  37. if ($hDir = opendir($sRootDir))
  38. {
  39. // This is the correct way to loop over the directory. (according to the documentation)
  40. while (($sFile = readdir($hDir)) !== false)
  41. {
  42. if (preg_match('/^datamodel(.*)\.xml$/i', $sFile, $aMatches))
  43. {
  44. $this->aDataModels[] = $this->sRootDir.'/'.$aMatches[0];
  45. }
  46. }
  47. closedir($hDir);
  48. }
  49. }
  50. public function GetId()
  51. {
  52. return $this->sId;
  53. }
  54. public function GetName()
  55. {
  56. return $this->sName;
  57. }
  58. public function GetVersion()
  59. {
  60. return $this->sVersion;
  61. }
  62. public function GetLabel()
  63. {
  64. return $this->sLabel;
  65. }
  66. public function GetRootDir()
  67. {
  68. return $this->sRootDir;
  69. }
  70. public function GetModuleDir()
  71. {
  72. return basename($this->sRootDir);
  73. }
  74. public function GetDataModelFiles()
  75. {
  76. return $this->aDataModels;
  77. }
  78. /**
  79. * List all classes in this module
  80. */
  81. public function ListClasses()
  82. {
  83. return array();
  84. }
  85. }
  86. /**
  87. * ModelFactory: the class that manages the in-memory representation of the XML MetaModel
  88. * @package ModelFactory
  89. */
  90. class ModelFactory
  91. {
  92. protected $sRootDir;
  93. protected $oDOMDocument;
  94. protected $oRoot;
  95. protected $oModules;
  96. protected $oClasses;
  97. protected $oMenus;
  98. static protected $aLoadedClasses;
  99. static protected $aWellKnownParents = array('DBObject', 'CMDBObject','cmdbAbstractObject');
  100. // static protected $aWellKnownMenus = array('DataAdministration', 'Catalogs', 'ConfigManagement', 'Contact', 'ConfigManagementCI', 'ConfigManagement:Shortcuts', 'ServiceManagement');
  101. static protected $aLoadedModules;
  102. static protected $aLoadErrors;
  103. public function __construct($sRootDir, $aRootNodeExtensions = array())
  104. {
  105. $this->sRootDir = $sRootDir;
  106. $this->oDOMDocument = new MFDocument();
  107. $this->oRoot = $this->oDOMDocument->CreateElement('itop_design');
  108. $this->oDOMDocument->AppendChild($this->oRoot);
  109. $this->oModules = $this->oDOMDocument->CreateElement('loaded_modules');
  110. $this->oRoot->AppendChild($this->oModules);
  111. $this->oClasses = $this->oDOMDocument->CreateElement('classes');
  112. $this->oRoot->AppendChild($this->oClasses);
  113. foreach (self::$aWellKnownParents as $sWellKnownParent)
  114. {
  115. $oWKClass = $this->oDOMDocument->CreateElement('class');
  116. $oWKClass->setAttribute('id', $sWellKnownParent);
  117. $this->oClasses->AppendChild($oWKClass);
  118. }
  119. $this->oMenus = $this->oDOMDocument->CreateElement('menus');
  120. $this->oRoot->AppendChild($this->oMenus);
  121. foreach($aRootNodeExtensions as $sElementName)
  122. {
  123. $oElement = $this->oDOMDocument->CreateElement($sElementName);
  124. $this->oRoot->AppendChild($oElement);
  125. }
  126. self::$aLoadedModules = array();
  127. self::$aLoadErrors = array();
  128. libxml_use_internal_errors(true);
  129. }
  130. public function Dump($oNode = null)
  131. {
  132. if (is_null($oNode))
  133. {
  134. $oNode = $this->oRoot;
  135. }
  136. $oNode->Dump();
  137. }
  138. public function LoadFromFile($sCacheFile)
  139. {
  140. $this->oDOMDocument->load($sCacheFile);
  141. $this->oRoot = $this->oDOMDocument->firstChild;
  142. $this->oModules = $this->oRoot->getElementsByTagName('loaded_modules')->item(0);
  143. self::$aLoadedModules = array();
  144. foreach($this->oModules->getElementsByTagName('module') as $oModuleNode)
  145. {
  146. $sId = $oModuleNode->getAttribute('id');
  147. $sRootDir = $oModuleNode->GetChildText('root_dir');
  148. $sLabel = $oModuleNode->GetChildText('label');
  149. self::$aLoadedModules[] = new MFModule($sId, $sRootDir, $sLabel);
  150. }
  151. }
  152. public function SaveToFile($sCacheFile)
  153. {
  154. $this->oDOMDocument->save($sCacheFile);
  155. }
  156. /**
  157. * To progressively replace LoadModule
  158. * @param xxx xxx
  159. */
  160. public function LoadDelta(DOMDocument $oDeltaDoc, $oSourceNode, $oTargetParentNode)
  161. {
  162. if (!$oSourceNode instanceof DOMElement) return;
  163. //echo "Load $oSourceNode->tagName::".$oSourceNode->getAttribute('id')." (".$oSourceNode->getAttribute('_delta').")<br/>\n";
  164. $oTarget = $this->oDOMDocument;
  165. if (($oSourceNode->tagName == 'class') && ($oSourceNode->parentNode->tagName == 'classes'))
  166. {
  167. if ($oSourceNode->getAttribute('_delta') == 'define')
  168. {
  169. // This tag is organized in hierarchy: determine the real parent node (as a subnode of the current node)
  170. $sParentId = $oSourceNode->GetChildText('parent');
  171. $oTargetParentNode = $oTarget->GetNodeById('/itop_design/classes//class', $sParentId)->item(0);
  172. if (!$oTargetParentNode)
  173. {
  174. echo "Dumping target doc - looking for '$sPath'<br/>\n";
  175. $this->oDOMDocument->firstChild->Dump();
  176. throw new Exception("XML datamodel loader: could not find parent node for $oSourceNode->tagName/".$oSourceNode->getAttribute('id')." with parent id $sParentId");
  177. }
  178. }
  179. else
  180. {
  181. $oTargetNode = $oTarget->GetNodeById('/itop_design/classes//class', $oSourceNode->getAttribute('id'))->item(0);
  182. if (!$oTargetNode)
  183. {
  184. echo "Dumping target doc - looking for '$sPath'<br/>\n";
  185. $this->oDOMDocument->firstChild->Dump();
  186. throw new Exception("XML datamodel loader: could not find node for $oSourceNode->tagName/".$oSourceNode->getAttribute('id'));
  187. }
  188. else
  189. {
  190. $oTargetParentNode = $oTargetNode->parentNode;
  191. }
  192. }
  193. }
  194. switch ($oSourceNode->getAttribute('_delta'))
  195. {
  196. case 'must_exist':
  197. case 'merge':
  198. case '':
  199. $bMustExist = ($oSourceNode->getAttribute('_delta') == 'must_exist');
  200. $sSearchId = $oSourceNode->hasAttribute('_rename_from') ? $oSourceNode->getAttribute('_rename_from') : $oSourceNode->getAttribute('id');
  201. $oTargetNode = $oSourceNode->MergeInto($oTargetParentNode, $sSearchId, $bMustExist);
  202. foreach($oSourceNode->childNodes as $oSourceChild)
  203. {
  204. // Continue deeper
  205. $this->LoadDelta($oDeltaDoc, $oSourceChild, $oTargetNode);
  206. }
  207. break;
  208. case 'define':
  209. // New node - copy child nodes as well
  210. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  211. $oTargetParentNode->AddChildNode($oTargetNode);
  212. break;
  213. case 'redefine':
  214. // Replace the existing node by the given node - copy child nodes as well
  215. $oTargetNode = $oTarget->ImportNode($oSourceNode, true);
  216. $oTargetParentNode->RedefineChildNode($oTargetNode);
  217. break;
  218. case 'delete':
  219. $oTargetNode = $oTargetParentNode->FindExistingChildNode($oSourceNode);
  220. $oTargetNode->Delete();
  221. break;
  222. }
  223. if ($oSourceNode->hasAttribute('_rename_from'))
  224. {
  225. $oTargetNode->Rename($oSourceNode->getAttribute('id'));
  226. }
  227. if ($oTargetNode->hasAttribute('_delta'))
  228. {
  229. $oTargetNode->removeAttribute('_delta');
  230. }
  231. }
  232. /**
  233. * Loads the definitions corresponding to the given Module
  234. * @param MFModule $oModule
  235. */
  236. public function LoadModule(MFModule $oModule)
  237. {
  238. $aDataModels = $oModule->GetDataModelFiles();
  239. $sModuleName = $oModule->GetName();
  240. $aClasses = array();
  241. self::$aLoadedModules[] = $oModule;
  242. // For persistence in the cache
  243. $oModuleNode = $this->oDOMDocument->CreateElement('module');
  244. $oModuleNode->setAttribute('id', $oModule->GetId());
  245. $oModuleNode->AppendChild($this->oDOMDocument->CreateElement('root_dir', $oModule->GetRootDir()));
  246. $oModuleNode->AppendChild($this->oDOMDocument->CreateElement('label', $oModule->GetLabel()));
  247. $this->oModules->AppendChild($oModuleNode);
  248. foreach($aDataModels as $sXmlFile)
  249. {
  250. $oDocument = new MFDocument();
  251. libxml_clear_errors();
  252. $oDocument->load($sXmlFile);
  253. //$bValidated = $oDocument->schemaValidate(APPROOT.'setup/itop_design.xsd');
  254. $aErrors = libxml_get_errors();
  255. if (count($aErrors) > 0)
  256. {
  257. self::$aLoadErrors[$sModuleName] = $aErrors;
  258. return;
  259. }
  260. $oXPath = new DOMXPath($oDocument);
  261. $oNodeList = $oXPath->query('/itop_design/classes//class');
  262. foreach($oNodeList as $oNode)
  263. {
  264. $oNode->SetAttribute('_created_in', $sModuleName);
  265. }
  266. $oNodeList = $oXPath->query('/itop_design/menus/menu');
  267. foreach($oNodeList as $oNode)
  268. {
  269. $oNode->SetAttribute('_created_in', $sModuleName);
  270. }
  271. $oDeltaRoot = $oDocument->childNodes->item(0);
  272. $this->LoadDelta($oDocument, $oDeltaRoot, $this->oDOMDocument);
  273. }
  274. }
  275. /**
  276. * XML load errors (XML format and validation)
  277. */
  278. function HasLoadErrors()
  279. {
  280. return (count(self::$aLoadErrors) > 0);
  281. }
  282. function GetLoadErrors()
  283. {
  284. return self::$aLoadErrors;
  285. }
  286. function GetLoadedModules($bExcludeWorkspace = true)
  287. {
  288. if ($bExcludeWorkspace)
  289. {
  290. $aModules = array();
  291. foreach(self::$aLoadedModules as $oModule)
  292. {
  293. if (!$oModule instanceof MFWorkspace)
  294. {
  295. $aModules[] = $oModule;
  296. }
  297. }
  298. }
  299. else
  300. {
  301. $aModules = self::$aLoadedModules;
  302. }
  303. return $aModules;
  304. }
  305. function GetModule($sModuleName)
  306. {
  307. foreach(self::$aLoadedModules as $oModule)
  308. {
  309. if ($oModule->GetName() == $sModuleName) return $oModule;
  310. }
  311. return null;
  312. }
  313. public function CreateElement($sTagName, $sValue = '')
  314. {
  315. return $this->oDOMDocument->createElement($sTagName, $sValue);
  316. }
  317. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  318. {
  319. return $this->oDOMDocument->GetNodeById($sXPath, $sId, $oContextNode);
  320. }
  321. /**
  322. * Check if the class specified by the given node already exists in the loaded DOM
  323. * @param DOMNode $oClassNode The node corresponding to the class to load
  324. * @throws Exception
  325. * @return bool True if the class exists, false otherwise
  326. */
  327. protected function ClassExists(DOMNode $oClassNode)
  328. {
  329. assert(false);
  330. if ($oClassNode->hasAttribute('id'))
  331. {
  332. $sClassName = $oClassNode->GetAttribute('id');
  333. }
  334. else
  335. {
  336. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  337. }
  338. return (array_key_exists($sClassName, self::$aLoadedClasses));
  339. }
  340. /**
  341. * Check if the class specified by the given name already exists in the loaded DOM
  342. * @param string $sClassName The node corresponding to the class to load
  343. * @throws Exception
  344. * @return bool True if the class exists, false otherwise
  345. */
  346. protected function ClassNameExists($sClassName, $bFlattenLayers = true)
  347. {
  348. return !is_null($this->GetClass($sClassName, $bFlattenLayers));
  349. }
  350. /**
  351. * Add the given class to the DOM
  352. * @param DOMNode $oClassNode
  353. * @param string $sModuleName The name of the module in which this class is declared
  354. * @throws Exception
  355. */
  356. public function AddClass(DOMNode $oClassNode, $sModuleName)
  357. {
  358. if ($oClassNode->hasAttribute('id'))
  359. {
  360. $sClassName = $oClassNode->GetAttribute('id');
  361. }
  362. else
  363. {
  364. throw new Exception('ModelFactory::AddClass: Cannot add a class with no name');
  365. }
  366. if ($this->ClassNameExists($oClassNode->getAttribute('id')))
  367. {
  368. throw new Exception("ModelFactory::AddClass: Cannot add the already existing class $sClassName");
  369. }
  370. $sParentClass = $oClassNode->GetChildText('parent', '');
  371. $oParentNode = $this->GetClass($sParentClass);
  372. if ($oParentNode == null)
  373. {
  374. throw new Exception("ModelFactory::AddClass: Cannot find the parent class of '$sClassName': '$sParentClass'");
  375. }
  376. else
  377. {
  378. if ($sModuleName != '')
  379. {
  380. $oClassNode->SetAttribute('_created_in', $sModuleName);
  381. }
  382. $oParentNode->AddChildNode($this->oDOMDocument->importNode($oClassNode, true));
  383. }
  384. }
  385. /**
  386. * Remove a class from the DOM
  387. * @param string $sClass
  388. * @throws Exception
  389. */
  390. public function RemoveClass($sClass)
  391. {
  392. $oClassNode = $this->GetClass($sClass);
  393. if ($oClassNode == null)
  394. {
  395. throw new Exception("ModelFactory::RemoveClass: Cannot remove the non existing class $sClass");
  396. }
  397. // Note: the child classes are removed entirely
  398. $oClassNode->Delete();
  399. }
  400. /**
  401. * Modify a class within the DOM
  402. * @param string $sMenuId
  403. * @param DOMNode $oMenuNode
  404. * @throws Exception
  405. */
  406. public function AlterClass($sClassName, DOMNode $oClassNode)
  407. {
  408. $sOriginalName = $sClassName;
  409. if ($this->ClassNameExists($sClassName))
  410. {
  411. $oDestNode = self::$aLoadedClasses[$sClassName];
  412. }
  413. else
  414. {
  415. $sOriginalName = $oClassNode->getAttribute('_original_name');
  416. if ($this->ClassNameExists($sOriginalName))
  417. {
  418. // Class was renamed !
  419. $oDestNode = self::$aLoadedClasses[$sOriginalName];
  420. }
  421. else
  422. {
  423. throw new Exception("ModelFactory::AddClass: Cannot alter the non-existing class $sClassName / $sOriginalName");
  424. }
  425. }
  426. $this->_priv_AlterNode($oDestNode, $oClassNode);
  427. $sClassName = $oDestNode->getAttribute('id');
  428. if ($sOriginalName != $sClassName)
  429. {
  430. unset(self::$aLoadedClasses[$sOriginalName]);
  431. self::$aLoadedClasses[$sClassName] = $oDestNode;
  432. }
  433. $this->_priv_SetFlag($oDestNode, 'modified');
  434. }
  435. public function GetClassXMLTemplate($sName, $sIcon)
  436. {
  437. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  438. return
  439. <<<EOF
  440. $sHeader
  441. <class id="$sName">
  442. <comment/>
  443. <properties>
  444. </properties>
  445. <naming format=""><attributes/></naming>
  446. <reconciliation><attributes/></reconciliation>
  447. <display_template/>
  448. <icon>$sIcon</icon>
  449. </properties>
  450. <fields/>
  451. <lifecycle/>
  452. <methods/>
  453. <presentation>
  454. <details><items/></details>
  455. <search><items/></search>
  456. <list><items/></list>
  457. </presentation>
  458. </class>
  459. EOF
  460. ;
  461. }
  462. /**
  463. * List all classes from the DOM, for a given module
  464. * @param string $sModuleNale
  465. * @param bool $bFlattenLayers
  466. * @throws Exception
  467. */
  468. public function ListClasses($sModuleName, $bFlattenLayers = true)
  469. {
  470. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName']";
  471. if ($bFlattenLayers)
  472. {
  473. $sXPath = "/itop_design/classes//class[@_created_in='$sModuleName' and (not(@_alteration) or @_alteration!='removed')]";
  474. }
  475. return $this->GetNodes($sXPath);
  476. }
  477. /**
  478. * List all classes from the DOM, for a given module
  479. * @param string $sModuleNale
  480. * @param bool $bFlattenLayers
  481. * @throws Exception
  482. */
  483. public function ListAllClasses($bFlattenLayers = true)
  484. {
  485. $sXPath = "/itop_design/classes//class";
  486. if ($bFlattenLayers)
  487. {
  488. $sXPath = "/itop_design/classes//class[not(@_alteration) or @_alteration!='removed']";
  489. }
  490. return $this->GetNodes($sXPath);
  491. }
  492. public function GetClass($sClassName, $bFlattenLayers = true)
  493. {
  494. $oClassNode = $this->GetNodes("/itop_design/classes//class[@id='$sClassName']")->item(0);
  495. if ($oClassNode == null)
  496. {
  497. return null;
  498. }
  499. elseif ($bFlattenLayers)
  500. {
  501. $sOperation = $oClassNode->getAttribute('_alteration');
  502. if ($sOperation == 'removed')
  503. {
  504. $oClassNode = null;
  505. }
  506. }
  507. return $oClassNode;
  508. }
  509. public function GetChildClasses($oClassNode, $bFlattenLayers = true)
  510. {
  511. $sXPath = "class";
  512. if ($bFlattenLayers)
  513. {
  514. $sXPath = "class[(@_operation!='removed')]";
  515. }
  516. return $this->GetNodes($sXPath, $oClassNode);
  517. }
  518. public function GetField($sClassName, $sAttCode, $bFlattenLayers = true)
  519. {
  520. if (!$this->ClassNameExists($sClassName))
  521. {
  522. return null;
  523. }
  524. $oClassNode = self::$aLoadedClasses[$sClassName];
  525. if ($bFlattenLayers)
  526. {
  527. $sOperation = $oClassNode->getAttribute('_operation');
  528. if ($sOperation == 'removed')
  529. {
  530. $oClassNode = null;
  531. }
  532. }
  533. $sXPath = "fields/field[@id='$sAttCode']";
  534. if ($bFlattenLayers)
  535. {
  536. $sXPath = "fields/field[(@id='$sAttCode' and (not(@_operation) or @_operation!='removed'))]";
  537. }
  538. $oFieldNode = $this->GetNodes($sXPath, $oClassNode)->item(0);
  539. if (($oFieldNode == null) && ($sParentClass = $oClassNode->GetChildText('parent')))
  540. {
  541. return $this->GetField($sParentClass, $sAttCode, $bFlattenLayers);
  542. }
  543. return $oFieldNode;
  544. }
  545. /**
  546. * List all classes from the DOM
  547. * @param bool $bFlattenLayers
  548. * @throws Exception
  549. */
  550. public function ListFields(DOMNode $oClassNode, $bFlattenLayers = true)
  551. {
  552. $sXPath = "fields/field";
  553. if ($bFlattenLayers)
  554. {
  555. $sXPath = "fields/field[not(@_alteration) or @_alteration!='removed']";
  556. }
  557. return $this->GetNodes($sXPath, $oClassNode);
  558. }
  559. public function AddField(DOMNode $oClassNode, $sFieldCode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  560. {
  561. $oNewField = $this->oDOMDocument->createElement('field');
  562. $oNewField->setAttribute('id', $sFieldCode);
  563. $this->_priv_AlterField($oNewField, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams);
  564. $oFields = $oClassNode->getElementsByTagName('fields')->item(0);
  565. $oFields->AppendChild($oNewField);
  566. $this->_priv_SetFlag($oNewField, 'added');
  567. }
  568. public function RemoveField(DOMNode $oClassNode, $sFieldCode)
  569. {
  570. $sXPath = "fields/field[@id='$sFieldCode']";
  571. $oFieldNodes = $this->GetNodes($sXPath, $oClassNode);
  572. if (is_object($oFieldNodes) && (is_object($oFieldNodes->item(0))))
  573. {
  574. $oFieldNode = $oFieldNodes->item(0);
  575. $sOpCode = $oFieldNode->getAttribute('_operation');
  576. if ($oFieldNode->getAttribute('_operation') == 'added')
  577. {
  578. $oFieldNode->parentNode->removeChild($oFieldNode);
  579. }
  580. else
  581. {
  582. $this->_priv_SetFlag($oFieldNode, 'removed');
  583. }
  584. }
  585. }
  586. public function AlterField(DOMNode $oClassNode, $sFieldCode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  587. {
  588. $sXPath = "fields/field[@id='$sFieldCode']";
  589. $oFieldNodes = $this->GetNodes($sXPath, $oClassNode);
  590. if (is_object($oFieldNodes) && (is_object($oFieldNodes->item(0))))
  591. {
  592. $oFieldNode = $oFieldNodes->item(0);
  593. //@@TODO: if the field was 'added' => then let it as 'added'
  594. $sOpCode = $oFieldNode->getAttribute('_operation');
  595. switch($sOpCode)
  596. {
  597. case 'added':
  598. case 'modified':
  599. // added or modified, let it as it is
  600. break;
  601. default:
  602. $this->_priv_SetFlag($oFieldNodes->item(0), 'modified');
  603. }
  604. $this->_priv_AlterField($oFieldNodes->item(0), $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams);
  605. }
  606. }
  607. protected function _priv_AlterField(DOMNode $oFieldNode, $sFieldType, $sSQL, $defaultValue, $bIsNullAllowed, $aExtraParams)
  608. {
  609. switch($sFieldType)
  610. {
  611. case 'Blob':
  612. case 'Boolean':
  613. case 'CaseLog':
  614. case 'Deadline':
  615. case 'Duration':
  616. case 'EmailAddress':
  617. case 'EncryptedString':
  618. case 'HTML':
  619. case 'IPAddress':
  620. case 'LongText':
  621. case 'OQL':
  622. case 'OneWayPassword':
  623. case 'Password':
  624. case 'Percentage':
  625. case 'String':
  626. case 'Text':
  627. case 'Text':
  628. case 'TemplateHTML':
  629. case 'TemplateString':
  630. case 'TemplateText':
  631. case 'URL':
  632. case 'Date':
  633. case 'DateTime':
  634. case 'Decimal':
  635. case 'Integer':
  636. break;
  637. case 'ExternalKey':
  638. $this->_priv_AddFieldAttribute($oFieldNode, 'target_class', $aExtraParams);
  639. // Fall through
  640. case 'HierarchicalKey':
  641. $this->_priv_AddFieldAttribute($oFieldNode, 'on_target_delete', $aExtraParams);
  642. $this->_priv_AddFieldAttribute($oFieldNode, 'filter', $aExtraParams);
  643. break;
  644. case 'ExternalField':
  645. $this->_priv_AddFieldAttribute($oFieldNode, 'extkey_attcode', $aExtraParams);
  646. $this->_priv_AddFieldAttribute($oFieldNode, 'target_attcode', $aExtraParams);
  647. break;
  648. case 'Enum':
  649. $this->_priv_SetFieldValues($oFieldNode, $aExtraParams);
  650. break;
  651. case 'LinkedSetIndirect':
  652. $this->_priv_AddFieldAttribute($oFieldNode, 'ext_key_to_remote', $aExtraParams);
  653. // Fall through
  654. case 'LinkedSet':
  655. $this->_priv_AddFieldAttribute($oFieldNode, 'linked_class', $aExtraParams);
  656. $this->_priv_AddFieldAttribute($oFieldNode, 'ext_key_to_me', $aExtraParams);
  657. $this->_priv_AddFieldAttribute($oFieldNode, 'count_min', $aExtraParams);
  658. $this->_priv_AddFieldAttribute($oFieldNode, 'count_max', $aExtraParams);
  659. break;
  660. default:
  661. throw(new Exception('Unsupported type of field: '.$sFieldType));
  662. }
  663. $this->_priv_SetFieldDependencies($oFieldNode, $aExtraParams);
  664. $oFieldNode->setAttribute('type', $sFieldType);
  665. $oFieldNode->setAttribute('sql', $sSQL);
  666. $oFieldNode->setAttribute('default_value', $defaultValue);
  667. $oFieldNode->setAttribute('is_null_alllowed', $bIsNullAllowed ? 'true' : 'false');
  668. }
  669. protected function _priv_AddFieldAttribute(DOMNode $oFieldNode, $sAttributeCode, $aExtraParams, $bMandatory = false)
  670. {
  671. $value = array_key_exists($sAttributeCode, $aExtraParams) ? $aExtraParams[$sAttributeCode] : '';
  672. if (($value == '') && (!$bMandatory)) return;
  673. $oFieldNode->setAttribute($sAttributeCode, $value);
  674. }
  675. protected function _priv_SetFieldDependencies($oFieldNode, $aExtraParams)
  676. {
  677. $aDeps = array_key_exists('dependencies', $aExtraParams) ? $aExtraParams['dependencies'] : '';
  678. $oDependencies = $oFieldNode->getElementsByTagName('dependencies')->item(0);
  679. // No dependencies before, and no dependencies to add, exit
  680. if (($oDependencies == null) && ($aDeps == '')) return;
  681. // Remove the previous dependencies
  682. $oFieldNode->removeChild($oDependencies);
  683. // If no dependencies, exit
  684. if ($aDeps == '') return;
  685. // Build the new list of dependencies
  686. $oDependencies = $this->oDOMDocument->createElement('dependencies');
  687. foreach($aDeps as $sAttCode)
  688. {
  689. $oDep = $this->oDOMDocument->createElement('attribute');
  690. $oDep->setAttribute('id', $sAttCode);
  691. $oDependencies->addChild($oDep);
  692. }
  693. $oFieldNode->addChild($oDependencies);
  694. }
  695. protected function _priv_SetFieldValues($oFieldNode, $aExtraParams)
  696. {
  697. $aVals = array_key_exists('values', $aExtraParams) ? $aExtraParams['values'] : '';
  698. $oValues = $oFieldNode->getElementsByTagName('values')->item(0);
  699. // No dependencies before, and no dependencies to add, exit
  700. if (($oValues == null) && ($aVals == '')) return;
  701. // Remove the previous dependencies
  702. $oFieldNode->removeChild($oValues);
  703. // If no dependencies, exit
  704. if ($aVals == '') return;
  705. // Build the new list of dependencies
  706. $oValues = $this->oDOMDocument->createElement('values');
  707. foreach($aVals as $sValue)
  708. {
  709. $oVal = $this->oDOMDocument->createElement('value', $sValue);
  710. $oValues->appendChild($oVal);
  711. }
  712. $oFieldNode->appendChild($oValues);
  713. }
  714. public function SetPresentation(DOMNode $oClassNode, $sPresentationCode, $aPresentation)
  715. {
  716. $oPresentation = $oClassNode->getElementsByTagName('presentation')->item(0);
  717. if (!is_object($oPresentation))
  718. {
  719. $oPresentation = $this->oDOMDocument->createElement('presentation');
  720. $oClassNode->appendChild($oPresentation);
  721. }
  722. $oZlist = $oPresentation->getElementsByTagName($sPresentationCode)->item(0);
  723. if (is_object($oZlist))
  724. {
  725. // Remove the previous Zlist
  726. $oPresentation->removeChild($oZlist);
  727. }
  728. // Create the ZList anew
  729. $oZlist = $this->oDOMDocument->createElement($sPresentationCode);
  730. $oPresentation->appendChild($oZlist);
  731. $this->AddZListItem($oZlist, $aPresentation);
  732. $this->_priv_SetFlag($oZlist, 'replaced');
  733. }
  734. protected function AddZListItem($oXMLNode, $value)
  735. {
  736. if (is_array($value))
  737. {
  738. $oXmlItems = $this->oDOMDocument->CreateElement('items');
  739. $oXMLNode->appendChild($oXmlItems);
  740. foreach($value as $key => $item)
  741. {
  742. $oXmlItem = $this->oDOMDocument->CreateElement('item');
  743. $oXmlItems->appendChild($oXmlItem);
  744. if (is_string($key))
  745. {
  746. $oXmlItem->SetAttribute('key', $key);
  747. }
  748. $this->AddZListItem($oXmlItem, $item);
  749. }
  750. }
  751. else
  752. {
  753. $oXmlText = $this->oDOMDocument->CreateTextNode((string) $value);
  754. $oXMLNode->appendChild($oXmlText);
  755. }
  756. }
  757. /**
  758. * List all transitions from a given state
  759. * @param DOMNode $oStateNode The state
  760. * @param bool $bFlattenLayers
  761. * @throws Exception
  762. */
  763. public function ListTransitions(DOMNode $oStateNode, $bFlattenLayers = true)
  764. {
  765. $sXPath = "transitions/transition";
  766. if ($bFlattenLayers)
  767. {
  768. //$sXPath = "transitions/transition[@_operation!='removed']";
  769. }
  770. return $this->GetNodes($sXPath, $oStateNode);
  771. }
  772. /**
  773. * List all states of a given class
  774. * @param DOMNode $oClassNode The class
  775. * @param bool $bFlattenLayers
  776. * @throws Exception
  777. */
  778. public function ListStates(DOMNode $oClassNode, $bFlattenLayers = true)
  779. {
  780. $sXPath = "lifecycle/states/state";
  781. if ($bFlattenLayers)
  782. {
  783. //$sXPath = "lifecycle/states/state[@_operation!='removed']";
  784. }
  785. return $this->GetNodes($sXPath, $oClassNode);
  786. }
  787. /**
  788. * List Zlists from the DOM for a given class
  789. * @param bool $bFlattenLayers
  790. * @throws Exception
  791. */
  792. public function ListZLists(DOMNode $oClassNode, $bFlattenLayers = true)
  793. {
  794. // Not yet implemented !!!
  795. return array();
  796. }
  797. public function ApplyChanges()
  798. {
  799. $oNodes = $this->ListChanges();
  800. foreach($oNodes as $oNode)
  801. {
  802. $sOperation = $oNode->GetAttribute('_alteration');
  803. switch($sOperation)
  804. {
  805. case 'added':
  806. case 'replaced':
  807. // marked as added or modified, just reset the flag
  808. $oNode->removeAttribute('_alteration');
  809. break;
  810. case 'removed':
  811. // marked as deleted, let's remove the node from the tree
  812. $oNode->parentNode->removeChild($oNode);
  813. // TODO!!!!!!!
  814. //unset(self::$aLoadedClasses[$sClass]);
  815. break;
  816. }
  817. if ($oNode->hasAttribute('_old_id'))
  818. {
  819. $oNode->removeAttribute('_old_id');
  820. }
  821. }
  822. }
  823. public function ListChanges()
  824. {
  825. return $this->GetNodes('//*[@_alteration or @_old_id]');
  826. }
  827. /**
  828. * Create path for the delta
  829. * @param DOMDocument oTargetDoc Where to attach the top of the hierarchy
  830. * @param MFElement oNode The node to import with its path
  831. */
  832. protected function ImportNodeAndPathDelta($oTargetDoc, $oNode)
  833. {
  834. // Preliminary: skip the parent if this node is organized hierarchically into the DOM
  835. // The criteria to detect a hierarchy is: same tag + have an id
  836. $oParent = $oNode->parentNode;
  837. while (($oParent instanceof DOMElement) && ($oParent->tagName == $oNode->tagName) && $oParent->hasAttribute('id'))
  838. {
  839. $oParent = $oParent->parentNode;
  840. }
  841. // Recursively create the path for the parent
  842. if ($oParent instanceof DOMElement)
  843. {
  844. $oParentClone = $this->ImportNodeAndPathDelta($oTargetDoc, $oParent);
  845. }
  846. else
  847. {
  848. // We've reached the top let's add the node into the root recipient
  849. $oParentClone = $oTargetDoc;
  850. }
  851. // Look for the node into the parent node
  852. // Note: this is an identified weakness of the algorithm,
  853. // because for each node modified, and each node of its path
  854. // we will have to lookup for the existing entry
  855. // Anyhow, this loop is quite quick to execute because in the delta
  856. // the number of nodes is limited
  857. $oNodeClone = null;
  858. foreach ($oParentClone->childNodes as $oChild)
  859. {
  860. if (($oChild instanceof DOMElement) && ($oChild->tagName == $oNode->tagName))
  861. {
  862. if (!$oNode->hasAttribute('id') || ($oNode->getAttribute('id') == $oChild->getAttribute('id')))
  863. {
  864. $oNodeClone = $oChild;
  865. break;
  866. }
  867. }
  868. }
  869. if (!$oNodeClone)
  870. {
  871. $sAlteration = $oNode->getAttribute('_alteration');
  872. $bCopyContents = ($sAlteration == 'replaced') || ($sAlteration == 'added');
  873. $oNodeClone = $oTargetDoc->importNode($oNode->cloneNode($bCopyContents), $bCopyContents);
  874. $oNodeClone->removeAttribute('_alteration');
  875. if ($oNodeClone->hasAttribute('_old_id'))
  876. {
  877. $oNodeClone->setAttribute('_rename_from', $oNodeClone->getAttribute('_old_id'));
  878. $oNodeClone->removeAttribute('_old_id');
  879. }
  880. switch ($sAlteration)
  881. {
  882. case '':
  883. if ($oNodeClone->hasAttribute('id'))
  884. {
  885. $oNodeClone->setAttribute('_delta', 'must_exist');
  886. }
  887. break;
  888. case 'added':
  889. $oNodeClone->setAttribute('_delta', 'define');
  890. break;
  891. case 'replaced':
  892. $oNodeClone->setAttribute('_delta', 'redefine');
  893. break;
  894. case 'removed':
  895. $oNodeClone->setAttribute('_delta', 'delete');
  896. break;
  897. }
  898. $oParentClone->appendChild($oNodeClone);
  899. }
  900. return $oNodeClone;
  901. }
  902. /**
  903. * Get the text/XML version of the delta
  904. */
  905. public function GetDelta()
  906. {
  907. $oDelta = new MFDocument();
  908. foreach($this->ListChanges() as $oAlteredNode)
  909. {
  910. $this->ImportNodeAndPathDelta($oDelta, $oAlteredNode);
  911. }
  912. return $oDelta->saveXML();
  913. }
  914. /**
  915. * Searches on disk in the root directory for module description files
  916. * and returns an array of MFModules
  917. * @return array Array of MFModules
  918. */
  919. public function FindModules($sSubDirectory = '')
  920. {
  921. $aAvailableModules = ModuleDiscovery::GetAvailableModules($this->sRootDir, $sSubDirectory);
  922. $aResult = array();
  923. foreach($aAvailableModules as $sId => $aModule)
  924. {
  925. $aResult[] = new MFModule($sId, $aModule['root_dir'], $aModule['label']);
  926. }
  927. return $aResult;
  928. }
  929. public function TestAlteration()
  930. {
  931. if (false)
  932. {
  933. echo "<h4>Extrait des données chargées</h4>\n";
  934. $oRoot = $this->GetNodes("//class[@id='Contact']")->item(0);
  935. $oRoot->Dump();
  936. return;
  937. }
  938. $sHeader = '<?xml version="1.0" encoding="utf-8"?'.'>';
  939. $sOriginalXML =
  940. <<<EOF
  941. $sHeader
  942. <itop_design>
  943. <a id="first a">
  944. <b>Text</b>
  945. <c id="1">
  946. <d>D1</d>
  947. <d>D2</d>
  948. </c>
  949. </a>
  950. <a id="second a">
  951. <parent>first a</parent>
  952. </a>
  953. <a id="third a">
  954. <parent>first a</parent>
  955. <x>blah</x>
  956. </a>
  957. </itop_design>
  958. EOF;
  959. $this->oDOMDocument = new MFDocument();
  960. $this->oDOMDocument->loadXML($sOriginalXML);
  961. echo "<h4>Données d'origine</h4>\n";
  962. $oRoot = $this->GetNodes('//itop_design')->item(0);
  963. $oRoot->Dump();
  964. $oNode = $oRoot->GetNodes('a/b')->item(0);
  965. $oNew = $this->oDOMDocument->CreateElement('b', 'New text');
  966. $oNode->parentNode->RedefineChildNode($oNew);
  967. $oNode = $oRoot->GetNodes('a/c')->item(0);
  968. $oNew = $this->oDOMDocument->CreateElement('c');
  969. $oNew->setAttribute('id', '1');
  970. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'x'));
  971. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'y'));
  972. $oNew->appendChild($this->oDOMDocument->CreateElement('d', 'z'));
  973. $oNode->parentNode->RedefineChildNode($oNew);
  974. $oNode = $oRoot->GetNodes("//a[@id='second a']")->item(0);
  975. $oNode->Rename('el secundo A');
  976. $oNew = $this->oDOMDocument->CreateElement('e', 'Something new here');
  977. $oNode->AddChildNode($oNew);
  978. $oNew = $this->oDOMDocument->CreateElement('a');
  979. $oNew->setAttribute('id', 'new a');
  980. $oNew->appendChild($this->oDOMDocument->CreateElement('parent', 'el secundo A'));
  981. $oNew->appendChild($this->oDOMDocument->CreateElement('f', 'Welcome to the newcomer'));
  982. $oNode->AddChildNode($oNew);
  983. $oNode = $oRoot->GetNodes("//a[@id='third a']")->item(0);
  984. $oNode->Delete();
  985. echo "<h4>Après modifications (avec les APIs de ModelFactory)</h4>\n";
  986. $oRoot->Dump();
  987. echo "<h4>Delta calculé</h4>\n";
  988. $sDeltaXML = $this->GetDelta();
  989. echo "<pre>\n";
  990. echo htmlentities($sDeltaXML);
  991. echo "</pre>\n";
  992. echo "<h4>Réitération: on recharge le modèle épuré</h4>\n";
  993. $this->oDOMDocument = new MFDocument();
  994. $this->oDOMDocument->loadXML($sOriginalXML);
  995. $oRoot = $this->GetNodes('//itop_design')->item(0);
  996. $oRoot->Dump();
  997. echo "<h4>On lui applique le delta calculé vu ci-dessus, et on obtient...</h4>\n";
  998. $oDeltaDoc = new MFDocument();
  999. $oDeltaDoc->loadXML($sDeltaXML);
  1000. $oDeltaDoc->Dump();
  1001. $this->oDOMDocument->Dump();
  1002. $oDeltaRoot = $oDeltaDoc->childNodes->item(0);
  1003. $this->LoadDelta($oDeltaDoc, $oDeltaRoot, $this->oDOMDocument);
  1004. $oRoot->Dump();
  1005. } // TEST !
  1006. /**
  1007. * Extracts some nodes from the DOM
  1008. * @param string $sXPath A XPath expression
  1009. * @return DOMNodeList
  1010. */
  1011. public function GetNodes($sXPath, $oContextNode = null)
  1012. {
  1013. return $this->oDOMDocument->GetNodes($sXPath, $oContextNode);
  1014. }
  1015. public function ListActiveChildNodes($sContextXPath, $sTagName)
  1016. {
  1017. $oContextPath = $this->oRoot->GetNodes($sContextXPath)->item(0);
  1018. return $oContextPath->ListActiveChildNodes($sTagName);
  1019. }
  1020. }
  1021. /**
  1022. * MFElement: helper to read/change the DOM
  1023. * @package ModelFactory
  1024. */
  1025. class MFElement extends DOMElement
  1026. {
  1027. /**
  1028. * Extracts some nodes from the DOM
  1029. * @param string $sXPath A XPath expression
  1030. * @return DOMNodeList
  1031. */
  1032. public function GetNodes($sXPath)
  1033. {
  1034. return $this->ownerDocument->GetNodes($sXPath, $this);
  1035. }
  1036. /**
  1037. * For debugging purposes
  1038. */
  1039. public function Dump()
  1040. {
  1041. echo "<pre>\n";
  1042. echo htmlentities($this->ownerDocument->saveXML($this));
  1043. echo "</pre>\n";
  1044. }
  1045. /**
  1046. * Returns the node directly under the given node
  1047. */
  1048. public function GetUniqueElement($sTagName, $bMustExist = true)
  1049. {
  1050. $oNode = null;
  1051. foreach($this->childNodes as $oChildNode)
  1052. {
  1053. if ($oChildNode->nodeName == $sTagName)
  1054. {
  1055. $oNode = $oChildNode;
  1056. break;
  1057. }
  1058. }
  1059. if ($bMustExist && is_null($oNode))
  1060. {
  1061. throw new DOMFormatException('Missing unique tag: '.$sTagName);
  1062. }
  1063. return $oNode;
  1064. }
  1065. /**
  1066. * Returns the node directly under the current node, or null if missing
  1067. */
  1068. public function GetOptionalElement($sTagName)
  1069. {
  1070. return $this->GetUniqueElement($sTagName, false);
  1071. }
  1072. /**
  1073. * Returns the TEXT of the current node (possibly from several subnodes)
  1074. */
  1075. public function GetText($sDefault = null)
  1076. {
  1077. $sText = null;
  1078. foreach($this->childNodes as $oChildNode)
  1079. {
  1080. if ($oChildNode instanceof DOMCharacterData) // Base class of DOMText and DOMCdataSection
  1081. {
  1082. if (is_null($sText)) $sText = '';
  1083. $sText .= $oChildNode->wholeText;
  1084. }
  1085. }
  1086. if (is_null($sText))
  1087. {
  1088. return $sDefault;
  1089. }
  1090. else
  1091. {
  1092. return $sText;
  1093. }
  1094. }
  1095. /**
  1096. * Get the TEXT value from the child node
  1097. */
  1098. public function GetChildText($sTagName, $sDefault = null)
  1099. {
  1100. $sRet = $sDefault;
  1101. if ($oChild = $this->GetOptionalElement($sTagName))
  1102. {
  1103. $sRet = $oChild->GetText($sDefault);
  1104. }
  1105. return $sRet;
  1106. }
  1107. /**
  1108. * Assumes the current node to be either a text or
  1109. * <items>
  1110. * <item [key]="..."]>value<item>
  1111. * <item [key]="..."]>value<item>
  1112. * </items>
  1113. * where value can be the either a text or an array of items... recursively
  1114. * Returns a PHP array
  1115. */
  1116. public function GetNodeAsArrayOfItems($sElementName = 'items')
  1117. {
  1118. $oItems = $this->GetOptionalElement($sElementName);
  1119. if ($oItems)
  1120. {
  1121. $res = array();
  1122. foreach($oItems->childNodes as $oItem)
  1123. {
  1124. // When an attribute is missing
  1125. if ($oItem->hasAttribute('id'))
  1126. {
  1127. $key = $oItem->getAttribute('id');
  1128. $res[$key] = $oItem->GetNodeAsArrayOfItems();
  1129. }
  1130. else
  1131. {
  1132. $res[] = $oItem->GetNodeAsArrayOfItems();
  1133. }
  1134. }
  1135. }
  1136. else
  1137. {
  1138. $res = $this->GetText();
  1139. }
  1140. return $res;
  1141. }
  1142. public function SetNodeAsArrayOfItems($aList)
  1143. {
  1144. $oNewNode = $this->ownerDocument->CreateElement($this->tagName);
  1145. if ($this->getAttribute('id') != '')
  1146. {
  1147. $oNewNode->setAttribute('id', $this->getAttribute('id'));
  1148. }
  1149. self::AddItemToNode($this->ownerDocument, $oNewNode, $aList);
  1150. $this->parentNode->RedefineChildNode($oNewNode);
  1151. }
  1152. protected static function AddItemToNode($oXmlDoc, $oXMLNode, $itemValue)
  1153. {
  1154. if (is_array($itemValue))
  1155. {
  1156. $oXmlItems = $oXmlDoc->CreateElement('items');
  1157. $oXMLNode->AppendChild($oXmlItems);
  1158. foreach($itemValue as $key => $item)
  1159. {
  1160. $oXmlItem = $oXmlDoc->CreateElement('item');
  1161. $oXmlItems->AppendChild($oXmlItem);
  1162. if (is_string($key))
  1163. {
  1164. $oXmlItem->SetAttribute('key', $key);
  1165. }
  1166. self::AddItemToNode($oXmlDoc, $oXmlItem, $item);
  1167. }
  1168. }
  1169. else
  1170. {
  1171. $oXmlText = $oXmlDoc->CreateTextNode((string) $itemValue);
  1172. $oXMLNode->AppendChild($oXmlText);
  1173. }
  1174. }
  1175. /**
  1176. * Helper to remove child nodes
  1177. */
  1178. public function DeleteChildren()
  1179. {
  1180. while (isset($this->firstChild))
  1181. {
  1182. if ($this->firstChild instanceof MFElement)
  1183. {
  1184. $this->firstChild->DeleteChildren();
  1185. }
  1186. $this->removeChild($this->firstChild);
  1187. }
  1188. }
  1189. /**
  1190. * Find the child node matching the given node
  1191. * @param MFElement $oRefNode The node to search for
  1192. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1193. */
  1194. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1195. {
  1196. return self::FindNode($this, $oRefNode, $sSearchId);
  1197. }
  1198. /**
  1199. * Find the child node matching the given node
  1200. * @param DOMNode $oParent The node to look into (could be DOMDocument, DOMElement...)
  1201. * @param MFElement $oRefNode The node to search for
  1202. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1203. */
  1204. public static function FindNodeSlow(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1205. {
  1206. $oRes = null;
  1207. if ($oRefNode->hasAttribute('id'))
  1208. {
  1209. // Find the first element having the same tag name and id
  1210. if (!$sSearchId)
  1211. {
  1212. $sSearchId = $oRefNode->getAttribute('id');
  1213. }
  1214. foreach($oParent->childNodes as $oChildNode)
  1215. {
  1216. if (($oChildNode instanceof DOMElement) && ($oChildNode->tagName == $oRefNode->tagName))
  1217. {
  1218. if ($oChildNode->hasAttribute('id') && ($oChildNode->getAttribute('id') == $sSearchId))
  1219. {
  1220. $oRes = $oChildNode;
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. else
  1227. {
  1228. // Get the first one having the same tag name (ignore others)
  1229. foreach($oParent->childNodes as $oChildNode)
  1230. {
  1231. if (($oChildNode instanceof DOMElement) && ($oChildNode->tagName == $oRefNode->tagName))
  1232. {
  1233. $oRes = $oChildNode;
  1234. break;
  1235. }
  1236. }
  1237. }
  1238. return $oRes;
  1239. }
  1240. /**
  1241. * Seems to work fine (and is about 10 times faster than above) EXCEPT for menus !!!!
  1242. * @param unknown_type $oParent
  1243. * @param unknown_type $oRefNode
  1244. * @param unknown_type $sSearchId
  1245. * @throws Exception
  1246. */
  1247. public static function FindNode(DOMNode $oParent, MFElement $oRefNode, $sSearchId = null)
  1248. {
  1249. $oRes = null;
  1250. if ($oParent instanceof DOMDocument)
  1251. {
  1252. $oDoc = $oParent->firstChild->ownerDocument;
  1253. $oRoot = $oParent;
  1254. }
  1255. else
  1256. {
  1257. $oDoc = $oParent->ownerDocument;
  1258. $oRoot = $oParent;
  1259. }
  1260. $oXPath = new DOMXPath($oDoc);
  1261. if ($oRefNode->hasAttribute('id'))
  1262. {
  1263. // Find the first element having the same tag name and id
  1264. if (!$sSearchId)
  1265. {
  1266. $sSearchId = $oRefNode->getAttribute('id');
  1267. }
  1268. $sXPath = './'.$oRefNode->tagName."[@id='$sSearchId']";
  1269. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1270. }
  1271. else
  1272. {
  1273. // Get the first one having the same tag name (ignore others)
  1274. $sXPath = './'.$oRefNode->tagName;
  1275. $oRes = $oXPath->query($sXPath, $oRoot)->item(0);
  1276. }
  1277. return $oRes;
  1278. }
  1279. public function ListActiveChildNodes($sTagName)
  1280. {
  1281. $sXPath = $sTagName."[not(@_alteration) or @_alteration!='removed']";
  1282. return $this->GetNodes($sXPath);
  1283. }
  1284. /**
  1285. * Add a node and set the flags that will be used to compute the delta
  1286. * @param MFElement $oNode The node (including all subnodes) to add
  1287. */
  1288. public function AddChildNode(MFElement $oNode)
  1289. {
  1290. $sFlag = null;
  1291. $oExisting = $this->FindExistingChildNode($oNode);
  1292. if ($oExisting)
  1293. {
  1294. if ($oExisting->getAttribute('_alteration') != 'removed')
  1295. {
  1296. throw new Exception("Attempting to add a node that already exists: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1297. }
  1298. $sFlag = 'replaced';
  1299. $oExisting->ReplaceWith($oNode);
  1300. }
  1301. else
  1302. {
  1303. $this->appendChild($oNode);
  1304. $sFlag = 'added';
  1305. // Iterate through the parents: reset the flag if any of them has a flag set
  1306. for($oParent = $oNode ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1307. {
  1308. if ($oParent->getAttribute('_alteration') != '')
  1309. {
  1310. $sFlag = null;
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. if ($sFlag)
  1316. {
  1317. $oNode->setAttribute('_alteration', $sFlag);
  1318. }
  1319. }
  1320. /**
  1321. * Modify a node and set the flags that will be used to compute the delta
  1322. * @param MFElement $oNode The node (including all subnodes) to set
  1323. */
  1324. public function RedefineChildNode(MFElement $oNode)
  1325. {
  1326. $oExisting = $this->FindExistingChildNode($oNode);
  1327. if (!$oExisting)
  1328. {
  1329. throw new Exception("Attempting to modify a non existing node: $oNode->tagName (id: ".$oNode->getAttribute('id').")");
  1330. }
  1331. if ($oExisting->getAttribute('_alteration') == 'removed')
  1332. {
  1333. throw new Exception("Attempting to modify a deleted node: $oNode->tagName (id: ".$oNode->getAttribute('id')."");
  1334. }
  1335. $oExisting->ReplaceWith($oNode);
  1336. if ($oNode->getAttribute('_alteration') != '')
  1337. {
  1338. // added or modified: leave the flag unchanged
  1339. $sFlag = null;
  1340. }
  1341. else
  1342. {
  1343. $sFlag = 'replaced';
  1344. // Iterate through the parents: reset the flag if any of them has a flag set
  1345. for($oParent = $oNode ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1346. {
  1347. if ($oParent->getAttribute('_alteration') != '')
  1348. {
  1349. $sFlag = null;
  1350. break;
  1351. }
  1352. }
  1353. }
  1354. if ($sFlag)
  1355. {
  1356. $oNode->setAttribute('_alteration', $sFlag);
  1357. }
  1358. }
  1359. /**
  1360. * Replaces a node by another one, making sure that recursive nodes are preserved
  1361. * @param MFElement $oNewNode The replacement
  1362. */
  1363. protected function ReplaceWith($oNewNode)
  1364. {
  1365. // Move the classes from the old node into the new one
  1366. foreach($this->GetNodes('class') as $oChild)
  1367. {
  1368. $oNewNode->appendChild($oChild);
  1369. }
  1370. $oParentNode = $this->parentNode;
  1371. $oParentNode->replaceChild($oNewNode, $this);
  1372. }
  1373. /**
  1374. * Remove a node and set the flags that will be used to compute the delta
  1375. */
  1376. public function Delete()
  1377. {
  1378. $oParent = $this->parentNode;
  1379. switch ($this->getAttribute('_alteration'))
  1380. {
  1381. case 'replaced':
  1382. $sFlag = 'removed';
  1383. break;
  1384. case 'added':
  1385. $sFlag = null;
  1386. break;
  1387. case 'removed':
  1388. throw new Exception("Attempting to remove a deleted node: $this->tagName (id: ".$this->getAttribute('id')."");
  1389. default:
  1390. $sFlag = 'removed';
  1391. // Iterate through the parents: reset the flag if any of them has a flag set
  1392. for($oParent = $this ; $oParent instanceof MFElement ; $oParent = $oParent->parentNode)
  1393. {
  1394. if ($oParent->getAttribute('_alteration') != '')
  1395. {
  1396. $sFlag = null;
  1397. break;
  1398. }
  1399. }
  1400. }
  1401. if ($sFlag)
  1402. {
  1403. $this->setAttribute('_alteration', $sFlag);
  1404. $this->DeleteChildren();
  1405. }
  1406. else
  1407. {
  1408. // Remove the node entirely
  1409. $oParent->removeChild($this);
  1410. }
  1411. }
  1412. /**
  1413. * Merge the current node into the given container
  1414. *
  1415. * @param DOMNode $oContainer An element or a document
  1416. * @param string $sSearchId The id to consider (could be blank)
  1417. * @param bool $bMustExist Throw an exception if the node must already be found (and not marked as deleted!)
  1418. */
  1419. public function MergeInto($oContainer, $sSearchId, $bMustExist)
  1420. {
  1421. $oTargetNode = $oContainer->FindExistingChildNode($this, $sSearchId);
  1422. if ($oTargetNode)
  1423. {
  1424. if ($oTargetNode->getAttribute('_alteration') == 'removed')
  1425. {
  1426. if ($bMustExist)
  1427. {
  1428. throw new Exception("XML datamodel loader: found mandatory node $this->tagName/$sSearchId marked as deleted in $oContainer->tagName");
  1429. }
  1430. $oTargetNode = $oContainer->ownerDocument->ImportNode($this, false);
  1431. $oContainer->AddChildNode($oTargetNode);
  1432. }
  1433. }
  1434. else
  1435. {
  1436. if ($bMustExist)
  1437. {
  1438. echo "Dumping parent node<br/>\n";
  1439. $oContainer->Dump();
  1440. throw new Exception("XML datamodel loader: could not find $this->tagName/$sSearchId in $oContainer->tagName");
  1441. }
  1442. $oTargetNode = $oContainer->ownerDocument->ImportNode($this, false);
  1443. $oContainer->AddChildNode($oTargetNode);
  1444. }
  1445. return $oTargetNode;
  1446. }
  1447. /**
  1448. * Renames a node and set the flags that will be used to compute the delta
  1449. * @param String $sNewId The new id
  1450. */
  1451. public function Rename($sId)
  1452. {
  1453. $sOriginalId = $this->getAttribute('_old_id');
  1454. if ($sOriginalId == '')
  1455. {
  1456. $this->setAttribute('_old_id', $this->getAttribute('id'));
  1457. }
  1458. else if($sOriginalId == $sId)
  1459. {
  1460. $this->removeAttribute('_old_id');
  1461. }
  1462. $this->setAttribute('id', $sId);
  1463. }
  1464. }
  1465. /**
  1466. * MFDocument - formating rules for XML input/output
  1467. * @package ModelFactory
  1468. */
  1469. class MFDocument extends DOMDocument
  1470. {
  1471. public function __construct()
  1472. {
  1473. parent::__construct('1.0', 'UTF-8');
  1474. $this->registerNodeClass('DOMElement', 'MFElement');
  1475. $this->formatOutput = true; // indent (must by loaded with option LIBXML_NOBLANKS)
  1476. $this->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1477. }
  1478. /**
  1479. * Overload of the standard API
  1480. */
  1481. public function load($filename, $options = 0)
  1482. {
  1483. parent::load($filename, LIBXML_NOBLANKS);
  1484. }
  1485. /**
  1486. * Overload of the standard API
  1487. */
  1488. public function loadXML($source, $options = 0)
  1489. {
  1490. parent::loadXML($source, LIBXML_NOBLANKS);
  1491. }
  1492. /**
  1493. * Overload the standard API
  1494. */
  1495. public function saveXML(DOMNode $node = null, $options = 0)
  1496. {
  1497. $oRootNode = $this->firstChild;
  1498. if (!$oRootNode)
  1499. {
  1500. $oRootNode = $this->createElement('itop_design'); // make sure that the document is not empty
  1501. $this->appendChild($oRootNode);
  1502. }
  1503. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1504. return parent::saveXML();
  1505. }
  1506. /**
  1507. * For debugging purposes
  1508. */
  1509. public function Dump()
  1510. {
  1511. echo "<pre>\n";
  1512. echo htmlentities($this->saveXML());
  1513. echo "</pre>\n";
  1514. }
  1515. /**
  1516. * Find the child node matching the given node
  1517. * @param MFElement $oRefNode The node to search for
  1518. * @param bool $sSearchId substitutes to the value of the 'id' attribute
  1519. */
  1520. public function FindExistingChildNode(MFElement $oRefNode, $sSearchId = null)
  1521. {
  1522. return MFElement::FindNode($this, $oRefNode, $sSearchId);
  1523. }
  1524. /**
  1525. * Extracts some nodes from the DOM
  1526. * @param string $sXPath A XPath expression
  1527. * @return DOMNodeList
  1528. */
  1529. public function GetNodes($sXPath, $oContextNode = null)
  1530. {
  1531. $oXPath = new DOMXPath($this);
  1532. if (is_null($oContextNode))
  1533. {
  1534. return $oXPath->query($sXPath);
  1535. }
  1536. else
  1537. {
  1538. return $oXPath->query($sXPath, $oContextNode);
  1539. }
  1540. }
  1541. public function GetNodeById($sXPath, $sId, $oContextNode = null)
  1542. {
  1543. $oXPath = new DOMXPath($this);
  1544. $sXPath .= "[@id='$sId' and(not(@_alteration) or @_alteration!='removed')]";
  1545. if (is_null($oContextNode))
  1546. {
  1547. return $oXPath->query($sXPath);
  1548. }
  1549. else
  1550. {
  1551. return $oXPath->query($sXPath, $oContextNode);
  1552. }
  1553. }
  1554. }