modelfactory.class.inc.php 47 KB

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