modelfactory.class.inc.php 44 KB

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