modelfactory.class.inc.php 49 KB

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