modelfactory.class.inc.php 41 KB

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