modelfactory.class.inc.php 62 KB

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