modelfactory.class.inc.php 45 KB

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