modelfactory.class.inc.php 63 KB

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