modelfactory.class.inc.php 68 KB

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