modelfactory.class.inc.php 62 KB

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