modelfactory.class.inc.php 66 KB

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