modelfactory.class.inc.php 50 KB

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