modelfactory.class.inc.php 63 KB

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