modelfactory.class.inc.php 63 KB

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