modelfactory.class.inc.php 68 KB

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