modelfactory.class.inc.php 65 KB

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