modelfactory.class.inc.php 50 KB

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