compiler.class.inc.php 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. <?php
  2. // Copyright (C) 2011-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once(APPROOT.'setup/setuputils.class.inc.php');
  19. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  20. require_once(APPROOT.'core/moduledesign.class.inc.php');
  21. class DOMFormatException extends Exception
  22. {
  23. /**
  24. * Overrides the Exception default constructor to automatically add informations about the concerned node (path and line number)
  25. *
  26. * @param string $message
  27. * @param type $code
  28. * @param type $previous
  29. * @param DOMNode $node [Optionnal] DOMNode causing the DOMFormatException
  30. */
  31. public function __construct($message, $code = null, $previous = null, DOMNode $node = null)
  32. {
  33. if($node !== null)
  34. {
  35. $message .= ' ('.MFDocument::GetItopNodePath($node).' at line '.$node->getLineNo().')';
  36. }
  37. parent::__construct($message, $code, $previous);
  38. }
  39. }
  40. /**
  41. * Compiler class
  42. */
  43. class MFCompiler
  44. {
  45. protected $oFactory;
  46. protected $aRootClasses;
  47. protected $aLog;
  48. protected $sMainPHPCode; // Code that goes into core/main.php
  49. protected $aSnippets;
  50. protected $aRelations;
  51. public function __construct($oModelFactory)
  52. {
  53. $this->oFactory = $oModelFactory;
  54. $this->oFactory->ApplyChanges();
  55. $this->aLog = array();
  56. $this->sMainPHPCode = '<'.'?'."php\n";
  57. $this->sMainPHPCode .= "/**\n";
  58. $this->sMainPHPCode .= " * This file was automatically generated by the compiler on ".date('Y-m-d H:i:s')." -- DO NOT EDIT\n";
  59. $this->sMainPHPCode .= " */\n";
  60. $this->aSnippets = array();
  61. $this->aRelations = array();
  62. }
  63. protected function Log($sText)
  64. {
  65. $this->aLog[] = $sText;
  66. }
  67. protected function DumpLog($oPage)
  68. {
  69. foreach ($this->aLog as $sText)
  70. {
  71. $oPage->p($sText);
  72. }
  73. }
  74. public function GetLog()
  75. {
  76. return $this->aLog;
  77. }
  78. public function Compile($sTargetDir, $oP = null, $bUseSymbolicLinks = false)
  79. {
  80. $sFinalTargetDir = $sTargetDir;
  81. if ($bUseSymbolicLinks)
  82. {
  83. // Skip the creation of a temporary dictionary, not compatible with symbolic links
  84. $sTempTargetDir = $sFinalTargetDir;
  85. }
  86. else
  87. {
  88. // Create a temporary directory
  89. // Once the compilation is 100% successful, then move the results into the target directory
  90. $sTempTargetDir = tempnam(SetupUtils::GetTmpDir(), 'itop-');
  91. unlink($sTempTargetDir); // I need a directory, not a file...
  92. SetupUtils::builddir($sTempTargetDir); // Here is the directory
  93. }
  94. try
  95. {
  96. $this->DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks);
  97. }
  98. catch (Exception $e)
  99. {
  100. if ($sTempTargetDir != $sFinalTargetDir)
  101. {
  102. // Cleanup the temporary directory
  103. SetupUtils::rrmdir($sTempTargetDir);
  104. }
  105. throw $e;
  106. }
  107. if ($sTempTargetDir != $sFinalTargetDir)
  108. {
  109. // Move the results to the target directory
  110. SetupUtils::movedir($sTempTargetDir, $sFinalTargetDir);
  111. }
  112. }
  113. protected function DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks = false)
  114. {
  115. $aAllClasses = array(); // flat list of classes
  116. // Determine the target modules for the MENUS
  117. //
  118. $aMenuNodes = array();
  119. $aMenusByModule = array();
  120. foreach ($this->oFactory->GetNodes('menus/menu') as $oMenuNode)
  121. {
  122. $sMenuId = $oMenuNode->getAttribute('id');
  123. $aMenuNodes[$sMenuId] = $oMenuNode;
  124. $sModuleMenu = $oMenuNode->getAttribute('_created_in');
  125. $aMenusByModule[$sModuleMenu][] = $sMenuId;
  126. }
  127. // Determine the target module (exactly one!) for USER RIGHTS
  128. // This used to be based solely on the module which created the user_rights node first
  129. // Unfortunately, our sample extension was delivered with the xml structure, resulting in the new module to be the recipient of the compilation
  130. // Then model.itop-profiles-itil would not exist... resulting in an error after the compilation (and the actual product of the compiler would never be included
  131. // The bullet proof implementation would be to compile in a separate directory as it has been done with the dictionaries... that's another story
  132. $aModules = $this->oFactory->GetLoadedModules();
  133. $sUserRightsModule = '';
  134. foreach($aModules as $foo => $oModule)
  135. {
  136. if ($oModule->GetName() == 'itop-profiles-itil')
  137. {
  138. $sUserRightsModule = 'itop-profiles-itil';
  139. break;
  140. }
  141. }
  142. $oUserRightsNode = $this->oFactory->GetNodes('user_rights')->item(0);
  143. if ($oUserRightsNode && ($sUserRightsModule == ''))
  144. {
  145. // Legacy algorithm (itop <= 2.0.3)
  146. $sUserRightsModule = $oUserRightsNode->getAttribute('_created_in');
  147. }
  148. $this->Log("User Rights module found: '$sUserRightsModule'");
  149. // List root classes
  150. //
  151. $this->aRootClasses = array();
  152. foreach ($this->oFactory->ListRootClasses() as $oClass)
  153. {
  154. $this->Log("Root class (with child classes): ".$oClass->getAttribute('id'));
  155. $this->aRootClasses[$oClass->getAttribute('id')] = $oClass;
  156. }
  157. $this->LoadSnippets();
  158. // Compile, module by module
  159. //
  160. $aModules = $this->oFactory->GetLoadedModules();
  161. $aDataModelFiles = array();
  162. $aWebservicesFiles = array();
  163. foreach($aModules as $foo => $oModule)
  164. {
  165. $sModuleName = $oModule->GetName();
  166. $sModuleVersion = $oModule->GetVersion();
  167. $sModuleRootDir = $oModule->GetRootDir();
  168. if ($sModuleRootDir != '')
  169. {
  170. $sModuleRootDir = realpath($sModuleRootDir);
  171. $sRelativeDir = basename($sModuleRootDir);
  172. // Push the other module files
  173. SetupUtils::copydir($sModuleRootDir, $sTempTargetDir.'/'.$sRelativeDir, $bUseSymbolicLinks);
  174. }
  175. $sCompiledCode = '';
  176. $oConstants = $this->oFactory->ListConstants($sModuleName);
  177. if ($oConstants->length > 0)
  178. {
  179. foreach($oConstants as $oConstant)
  180. {
  181. $sCompiledCode .= $this->CompileConstant($oConstant)."\n";
  182. }
  183. }
  184. if (array_key_exists($sModuleName, $this->aSnippets))
  185. {
  186. foreach( $this->aSnippets[$sModuleName]['before'] as $aSnippet)
  187. {
  188. $sCompiledCode .= "\n";
  189. $sCompiledCode .= "/**\n";
  190. $sCompiledCode .= " * Snippet: {$aSnippet['snippet_id']}\n";
  191. $sCompiledCode .= " */\n";
  192. $sCompiledCode .= $aSnippet['content']."\n";
  193. }
  194. }
  195. $oClasses = $this->oFactory->ListClasses($sModuleName);
  196. $iClassCount = $oClasses->length;
  197. if ($iClassCount == 0)
  198. {
  199. $this->Log("Found module without classes declared: $sModuleName");
  200. }
  201. else
  202. {
  203. foreach($oClasses as $oClass)
  204. {
  205. $sClass = $oClass->getAttribute("id");
  206. $aAllClasses[] = $sClass;
  207. try
  208. {
  209. $sCompiledCode .= $this->CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir, $oP);
  210. }
  211. catch (DOMFormatException $e)
  212. {
  213. throw new Exception("Failed to process class '$sClass', from '$sModuleRootDir': ".$e->getMessage());
  214. }
  215. }
  216. }
  217. if (!array_key_exists($sModuleName, $aMenusByModule))
  218. {
  219. $this->Log("Found module without menus declared: $sModuleName");
  220. }
  221. else
  222. {
  223. $sMenuCreationClass = 'MenuCreation_'.preg_replace('/[^A-Za-z0-9_]/', '_', $sModuleName);
  224. $sCompiledCode .=
  225. <<<EOF
  226. //
  227. // Menus
  228. //
  229. class $sMenuCreationClass extends ModuleHandlerAPI
  230. {
  231. public static function OnMenuCreation()
  232. {
  233. global \$__comp_menus__; // ensure that the global variable is indeed global !
  234. EOF;
  235. // Preliminary: determine parent menus not defined within the current module
  236. $aMenusToLoad = array();
  237. $aParentMenus = array();
  238. foreach($aMenusByModule[$sModuleName] as $sMenuId)
  239. {
  240. $oMenuNode = $aMenuNodes[$sMenuId];
  241. if ($sParent = $oMenuNode->GetChildText('parent', null))
  242. {
  243. $aMenusToLoad[] = $sParent;
  244. $aParentMenus[] = $sParent;
  245. }
  246. // Note: the order matters: the parents must be defined BEFORE
  247. $aMenusToLoad[] = $sMenuId;
  248. }
  249. $aMenusToLoad = array_unique($aMenusToLoad);
  250. $aMenusForAll = array();
  251. $aMenusForAdmins = array();
  252. foreach($aMenusToLoad as $sMenuId)
  253. {
  254. $oMenuNode = $aMenuNodes[$sMenuId];
  255. if ($oMenuNode->getAttribute("xsi:type") == 'MenuGroup')
  256. {
  257. // Note: this algorithm is wrong
  258. // 1 - the module may appear empty in the current module, while children are defined in other modules
  259. // 2 - check recursively that child nodes are not empty themselves
  260. // Future algorithm:
  261. // a- browse the modules and build the menu tree
  262. // b- browse the tree and blacklist empty menus
  263. // c- before compiling, discard if blacklisted
  264. if (!in_array($oMenuNode->getAttribute("id"), $aParentMenus))
  265. {
  266. // Discard empty menu groups
  267. continue;
  268. }
  269. }
  270. try
  271. {
  272. $aMenuLines = $this->CompileMenu($oMenuNode, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir, $oP);
  273. }
  274. catch (DOMFormatException $e)
  275. {
  276. throw new Exception("Failed to process menu '$sMenuId', from '$sModuleRootDir': ".$e->getMessage());
  277. }
  278. if ($oMenuNode->GetChildText('enable_admin_only') == '1')
  279. {
  280. $aMenusForAdmins = array_merge($aMenusForAdmins, $aMenuLines);
  281. }
  282. else
  283. {
  284. $aMenusForAll = array_merge($aMenusForAll, $aMenuLines);
  285. }
  286. }
  287. $sIndent = "\t\t";
  288. foreach ($aMenusForAll as $sPHPLine)
  289. {
  290. $sCompiledCode .= $sIndent.$sPHPLine."\n";
  291. }
  292. if (count($aMenusForAdmins) > 0)
  293. {
  294. $sCompiledCode .= $sIndent."if (UserRights::IsAdministrator())\n";
  295. $sCompiledCode .= $sIndent."{\n";
  296. foreach ($aMenusForAdmins as $sPHPLine)
  297. {
  298. $sCompiledCode .= $sIndent."\t".$sPHPLine."\n";
  299. }
  300. $sCompiledCode .= $sIndent."}\n";
  301. }
  302. $sCompiledCode .=
  303. <<<EOF
  304. }
  305. } // class $sMenuCreationClass
  306. EOF;
  307. }
  308. // User rights
  309. //
  310. if ($sModuleName == $sUserRightsModule)
  311. {
  312. $sCompiledCode .= $this->CompileUserRights($oUserRightsNode);
  313. }
  314. if (array_key_exists($sModuleName, $this->aSnippets))
  315. {
  316. foreach( $this->aSnippets[$sModuleName]['after'] as $aSnippet)
  317. {
  318. $sCompiledCode .= "\n";
  319. $sCompiledCode .= "/**\n";
  320. $sCompiledCode .= " * Snippet: {$aSnippet['snippet_id']}\n";
  321. $sCompiledCode .= " */\n";
  322. $sCompiledCode .= $aSnippet['content']."\n";
  323. }
  324. }
  325. // Create (overwrite if existing) the compiled file
  326. //
  327. if (strlen($sCompiledCode) > 0)
  328. {
  329. // We have compiled something: write the result file
  330. //
  331. $sResultFile = $sTempTargetDir.'/'.$sRelativeDir.'/model.'.$sModuleName.'.php';
  332. if (is_file($sResultFile))
  333. {
  334. $this->Log("Updating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  335. }
  336. else
  337. {
  338. $sResultDir = dirname($sResultFile);
  339. if (!is_dir($sResultDir))
  340. {
  341. $this->Log("Creating directory $sResultDir");
  342. mkdir($sResultDir, 0777, true);
  343. }
  344. $this->Log("Creating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  345. }
  346. // Compile the module into a single file
  347. //
  348. $sId = $sModuleName;
  349. $sCurrDate = date(DATE_ISO8601);
  350. $sAuthor = 'iTop compiler';
  351. $sLicence = 'http://opensource.org/licenses/AGPL-3.0';
  352. $sFileHeader =
  353. <<<EOF
  354. <?php
  355. //
  356. // File generated by ... on the $sCurrDate
  357. // Please do not edit manually
  358. //
  359. /**
  360. * Classes and menus for $sModuleName (version $sModuleVersion)
  361. *
  362. * @author $sAuthor
  363. * @license $sLicence
  364. */
  365. EOF;
  366. $ret = file_put_contents($sResultFile, $sFileHeader.$sCompiledCode);
  367. if ($ret === false)
  368. {
  369. $iLen = strlen($sFileHeader.$sCompiledCode);
  370. $fFree = @disk_free_space(dirname($sResultFile));
  371. $aErr = error_get_last();
  372. throw new Exception("Failed to write '$sResultFile'. Last error: '{$aErr['message']}', content to write: $iLen bytes, available free space on disk: $fFree.");
  373. }
  374. }
  375. else
  376. {
  377. $this->Log("Compilation of module $sModuleName in version $sModuleVersion produced not code at all. No file written.");
  378. }
  379. // files to include (PHP datamodels)
  380. foreach($oModule->GetFilesToInclude('business') as $sRelFileName)
  381. {
  382. $aDataModelFiles[] = "MetaModel::IncludeModule('".basename($sFinalTargetDir).'/'.$sRelativeDir.'/'.$sRelFileName."');";
  383. }
  384. // files to include (PHP webservices providers)
  385. foreach($oModule->GetFilesToInclude('webservices') as $sRelFileName)
  386. {
  387. $aWebservicesFiles[] = "MetaModel::IncludeModule('".basename($sFinalTargetDir).'/'.$sRelativeDir.'/'.$sRelFileName."');";
  388. }
  389. } // foreach module
  390. // Compile the dictionaries -out of the modules
  391. //
  392. $sDictDir = $sTempTargetDir.'/dictionaries';
  393. if (!is_dir($sDictDir))
  394. {
  395. $this->Log("Creating directory $sDictDir");
  396. mkdir($sDictDir, 0777, true);
  397. }
  398. $oDictionaries = $this->oFactory->GetNodes('dictionaries/dictionary');
  399. $this->CompileDictionaries($oDictionaries, $sTempTargetDir, $sFinalTargetDir);
  400. // Compile the branding
  401. //
  402. $oBrandingNode = $this->oFactory->GetNodes('branding')->item(0);
  403. $this->CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir);
  404. if (array_key_exists('_core_', $this->aSnippets))
  405. {
  406. foreach( $this->aSnippets['_core_']['before'] as $aSnippet)
  407. {
  408. $this->sMainPHPCode .= "\n";
  409. $this->sMainPHPCode .= "/**\n";
  410. $this->sMainPHPCode .= " * Snippet: {$aSnippet['snippet_id']}\n";
  411. $this->sMainPHPCode .= " */\n";
  412. $this->sMainPHPCode .= $aSnippet['content']."\n";
  413. }
  414. }
  415. // Compile the portals
  416. $oPortalsNode = $this->oFactory->GetNodes('/itop_design/portals')->item(0);
  417. $this->CompilePortals($oPortalsNode, $sTempTargetDir, $sFinalTargetDir);
  418. // Create module design XML files
  419. $oModuleDesignsNode = $this->oFactory->GetNodes('/itop_design/module_designs')->item(0);
  420. $this->CompileModuleDesigns($oModuleDesignsNode, $sTempTargetDir, $sFinalTargetDir);
  421. // Compile the XML parameters
  422. $oParametersNode = $this->oFactory->GetNodes('/itop_design/module_parameters')->item(0);
  423. $this->CompileParameters($oParametersNode, $sTempTargetDir, $sFinalTargetDir);
  424. if (array_key_exists('_core_', $this->aSnippets))
  425. {
  426. foreach( $this->aSnippets['_core_']['after'] as $aSnippet)
  427. {
  428. $this->sMainPHPCode .= "\n";
  429. $this->sMainPHPCode .= "/**\n";
  430. $this->sMainPHPCode .= " * Snippet: {$aSnippet['snippet_id']}\n";
  431. $this->sMainPHPCode .= " */\n";
  432. $this->sMainPHPCode .= $aSnippet['content']."\n";
  433. }
  434. }
  435. if (count($this->aRelations) > 0)
  436. {
  437. $this->sMainPHPCode .= "\n";
  438. $this->sMainPHPCode .= "/**\n";
  439. $this->sMainPHPCode .= " * Relations\n";
  440. $this->sMainPHPCode .= " */\n";
  441. foreach($this->aRelations as $sRelationCode => $aData)
  442. {
  443. $sRelCodeSafe = addslashes($sRelationCode);
  444. $this->sMainPHPCode .= "MetaModel::RegisterRelation('$sRelCodeSafe');\n";
  445. }
  446. }
  447. // Write core/main.php
  448. SetupUtils::builddir($sTempTargetDir.'/core');
  449. $sPHPFile = $sTempTargetDir.'/core/main.php';
  450. file_put_contents($sPHPFile, $this->sMainPHPCode);
  451. // Autoload
  452. $sPHPFile = $sTempTargetDir.'/autoload.php';
  453. $sPHPFileContent =
  454. <<<EOF
  455. <?php
  456. //
  457. // File generated on $sCurrDate
  458. // Please do not edit manually
  459. //
  460. EOF
  461. ;
  462. $sPHPFileContent .= "\nMetaModel::IncludeModule('".basename($sFinalTargetDir)."/core/main.php');\n";
  463. $sPHPFileContent .= implode("\n", $aDataModelFiles);
  464. $sPHPFileContent .= implode("\n", $aWebservicesFiles);
  465. file_put_contents($sPHPFile, $sPHPFileContent);
  466. } // DoCompile()
  467. /**
  468. * Helper to form a valid ZList from the array built by GetNodeAsArrayOfItems()
  469. */
  470. protected function ArrayOfItemsToZList(&$aItems)
  471. {
  472. $aTransformed = array();
  473. foreach ($aItems as $key => $value)
  474. {
  475. if (is_null($value))
  476. {
  477. $aTransformed[] = $key;
  478. }
  479. else
  480. {
  481. if (is_array($value))
  482. {
  483. $this->ArrayOfItemsToZList($value);
  484. }
  485. $aTransformed[$key] = $value;
  486. }
  487. }
  488. $aItems = $aTransformed;
  489. }
  490. /**
  491. * Helper to format the flags for an attribute, in a given state
  492. * @param object $oAttNode DOM node containing the information to build the flags
  493. * Returns string PHP flags, based on the OPT_ATT_ constants, or empty (meaning 0, can be omitted)
  494. */
  495. protected function FlagsToPHP($oAttNode)
  496. {
  497. static $aNodeAttributeToFlag = array(
  498. 'mandatory' => 'OPT_ATT_MANDATORY',
  499. 'read_only' => 'OPT_ATT_READONLY',
  500. 'must_prompt' => 'OPT_ATT_MUSTPROMPT',
  501. 'must_change' => 'OPT_ATT_MUSTCHANGE',
  502. 'hidden' => 'OPT_ATT_HIDDEN',
  503. );
  504. $aFlags = array();
  505. foreach ($aNodeAttributeToFlag as $sNodeAttribute => $sFlag)
  506. {
  507. $bFlag = ($oAttNode->GetOptionalElement($sNodeAttribute) != null);
  508. if ($bFlag)
  509. {
  510. $aFlags[] = $sFlag;
  511. }
  512. }
  513. if (empty($aFlags))
  514. {
  515. $aFlags[] = 'OPT_ATT_NORMAL'; // When no flag is defined, reset the state to "normal"
  516. }
  517. $sRes = implode(' | ', $aFlags);
  518. return $sRes;
  519. }
  520. /**
  521. * Helper to format the tracking level for linkset (direct or indirect attributes)
  522. * @param string $sTrackingLevel Value set from within the XML
  523. * Returns string PHP flag
  524. */
  525. protected function TrackingLevelToPHP($sAttType, $sTrackingLevel)
  526. {
  527. static $aXmlToPHP_Links = array(
  528. 'none' => 'LINKSET_TRACKING_NONE',
  529. 'list' => 'LINKSET_TRACKING_LIST',
  530. 'details' => 'LINKSET_TRACKING_DETAILS',
  531. 'all' => 'LINKSET_TRACKING_ALL',
  532. );
  533. static $aXmlToPHP_Others = array(
  534. 'none' => 'ATTRIBUTE_TRACKING_NONE',
  535. 'all' => 'ATTRIBUTE_TRACKING_ALL',
  536. );
  537. switch ($sAttType)
  538. {
  539. case 'AttributeLinkedSetIndirect':
  540. case 'AttributeLinkedSet':
  541. $aXmlToPHP = $aXmlToPHP_Links;
  542. break;
  543. default:
  544. $aXmlToPHP = $aXmlToPHP_Others;
  545. }
  546. if (!array_key_exists($sTrackingLevel, $aXmlToPHP))
  547. {
  548. throw new DOMFormatException("Tracking level: unknown value '$sTrackingLevel', expecting a value in {".implode(', ', array_keys($aXmlToPHP))."}");
  549. }
  550. return $aXmlToPHP[$sTrackingLevel];
  551. }
  552. /**
  553. * Helper to format the edit-mode for direct linkset
  554. * @param string $sEditMode Value set from within the XML
  555. * Returns string PHP flag
  556. */
  557. protected function EditModeToPHP($sEditMode)
  558. {
  559. static $aXmlToPHP = array(
  560. 'none' => 'LINKSET_EDITMODE_NONE',
  561. 'add_only' => 'LINKSET_EDITMODE_ADDONLY',
  562. 'actions' => 'LINKSET_EDITMODE_ACTIONS',
  563. 'in_place' => 'LINKSET_EDITMODE_INPLACE',
  564. 'add_remove' => 'LINKSET_EDITMODE_ADDREMOVE',
  565. );
  566. if (!array_key_exists($sEditMode, $aXmlToPHP))
  567. {
  568. throw new DOMFormatException("Edit mode: unknown value '$sEditMode'");
  569. }
  570. return $aXmlToPHP[$sEditMode];
  571. }
  572. /**
  573. * Format a path (file or url) as an absolute path or relative to the module or the app
  574. */
  575. protected function PathToPHP($sPath, $sModuleRelativeDir, $bIsUrl = false)
  576. {
  577. if ($sPath == '')
  578. {
  579. $sPHP = "''";
  580. }
  581. elseif (substr($sPath, 0, 2) == '$$')
  582. {
  583. // Absolute
  584. $sPHP = self::QuoteForPHP(substr($sPath, 2));
  585. }
  586. elseif (substr($sPath, 0, 1) == '$')
  587. {
  588. // Relative to the application
  589. if ($bIsUrl)
  590. {
  591. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP(substr($sPath, 1));
  592. }
  593. else
  594. {
  595. $sPHP = "APPROOT.".self::QuoteForPHP(substr($sPath, 1));
  596. }
  597. }
  598. else
  599. {
  600. // Relative to the module
  601. if ($bIsUrl)
  602. {
  603. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP($sModuleRelativeDir.''.$sPath);
  604. }
  605. else
  606. {
  607. $sPHP = "dirname(__FILE__).'/$sPath'";
  608. }
  609. }
  610. return $sPHP;
  611. }
  612. protected function GetPropString($oNode, $sTag, $sDefault = null)
  613. {
  614. $val = $oNode->GetChildText($sTag);
  615. if (is_null($val))
  616. {
  617. if (is_null($sDefault))
  618. {
  619. return null;
  620. }
  621. else
  622. {
  623. $val = $sDefault;
  624. }
  625. }
  626. return "'".$val."'";
  627. }
  628. protected function GetMandatoryPropString($oNode, $sTag)
  629. {
  630. $val = $oNode->GetChildText($sTag);
  631. if (!is_null($val) && ($val !== ''))
  632. {
  633. return "'".$val."'";
  634. }
  635. else
  636. {
  637. throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'");
  638. }
  639. }
  640. protected function GetPropBoolean($oNode, $sTag, $bDefault = null)
  641. {
  642. $val = $oNode->GetChildText($sTag);
  643. if (is_null($val))
  644. {
  645. if (is_null($bDefault))
  646. {
  647. return null;
  648. }
  649. else
  650. {
  651. return $bDefault ? 'true' : 'false';
  652. }
  653. }
  654. return $val == 'true' ? 'true' : 'false';
  655. }
  656. protected function GetMandatoryPropBoolean($oNode, $sTag)
  657. {
  658. $val = $oNode->GetChildText($sTag);
  659. if (is_null($val))
  660. {
  661. throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'");
  662. }
  663. return $val == 'true' ? 'true' : 'false';
  664. }
  665. protected function GetPropNumber($oNode, $sTag, $nDefault = null)
  666. {
  667. $val = $oNode->GetChildText($sTag);
  668. if (is_null($val))
  669. {
  670. if (is_null($nDefault))
  671. {
  672. return null;
  673. }
  674. else
  675. {
  676. $val = $nDefault;
  677. }
  678. }
  679. return (string)$val;
  680. }
  681. protected function GetMandatoryPropNumber($oNode, $sTag)
  682. {
  683. $val = $oNode->GetChildText($sTag);
  684. if (is_null($val))
  685. {
  686. throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'");
  687. }
  688. return (string)$val;
  689. }
  690. /**
  691. * Adds quotes and escape characters
  692. */
  693. protected function QuoteForPHP($sStr, $bSimpleQuotes = false)
  694. {
  695. if ($bSimpleQuotes)
  696. {
  697. $sEscaped = str_replace(array('\\', "'"), array('\\\\', "\\'"), $sStr);
  698. $sRet = "'$sEscaped'";
  699. }
  700. else
  701. {
  702. $sEscaped = str_replace(array('\\', '"', "\n"), array('\\\\', '\\"', '\\n'), $sStr);
  703. $sRet = '"'.$sEscaped.'"';
  704. }
  705. return $sRet;
  706. }
  707. protected function CompileConstant($oConstant)
  708. {
  709. $sName = $oConstant->getAttribute('id');
  710. $sType = $oConstant->getAttribute('xsi:type');
  711. $sText = $oConstant->GetText(null);
  712. switch ($sType)
  713. {
  714. case 'integer':
  715. if (is_null($sText))
  716. {
  717. // No data given => null
  718. $sScalar = 'null';
  719. }
  720. else
  721. {
  722. $sScalar = (string)(int)$sText;
  723. }
  724. break;
  725. case 'float':
  726. if (is_null($sText))
  727. {
  728. // No data given => null
  729. $sScalar = 'null';
  730. }
  731. else
  732. {
  733. $sScalar = (string)(float)$sText;
  734. }
  735. break;
  736. case 'bool':
  737. if (is_null($sText))
  738. {
  739. // No data given => null
  740. $sScalar = 'null';
  741. }
  742. else
  743. {
  744. $sScalar = ($sText == 'true') ? 'true' : 'false';
  745. }
  746. break;
  747. case 'string':
  748. default:
  749. $sScalar = $this->QuoteForPHP($sText, true);
  750. }
  751. $sPHPDefine = "define('$sName', $sScalar);";
  752. return $sPHPDefine;
  753. }
  754. protected function CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  755. {
  756. $sClass = $oClass->getAttribute('id');
  757. $oProperties = $oClass->GetUniqueElement('properties');
  758. // Class caracteristics
  759. //
  760. $aClassParams = array();
  761. $aClassParams['category'] = $this->GetPropString($oProperties, 'category', '');
  762. $aClassParams['key_type'] = "'autoincrement'";
  763. if ((bool) $this->GetPropNumber($oProperties, 'is_link', 0))
  764. {
  765. $aClassParams['is_link'] = 'true';
  766. }
  767. if ($oNaming = $oProperties->GetOptionalElement('naming'))
  768. {
  769. $oNameAttributes = $oNaming->GetUniqueElement('attributes');
  770. $oAttributes = $oNameAttributes->getElementsByTagName('attribute');
  771. $aNameAttCodes = array();
  772. foreach($oAttributes as $oAttribute)
  773. {
  774. $aNameAttCodes[] = $oAttribute->getAttribute('id');
  775. }
  776. if (count($aNameAttCodes) > 1)
  777. {
  778. // New style...
  779. $sNameAttCode = "array('".implode("', '", $aNameAttCodes)."')";
  780. }
  781. elseif (count($aNameAttCodes) == 1)
  782. {
  783. // New style...
  784. $sNameAttCode = "'$aNameAttCodes[0]'";
  785. }
  786. else
  787. {
  788. $sNameAttCode = "''";
  789. }
  790. }
  791. else
  792. {
  793. $sNameAttCode = "''";
  794. }
  795. $aClassParams['name_attcode'] = $sNameAttCode;
  796. $oLifecycle = $oClass->GetOptionalElement('lifecycle');
  797. if ($oLifecycle)
  798. {
  799. $sStateAttCode = $oLifecycle->GetChildText('attribute');
  800. }
  801. else
  802. {
  803. $sStateAttCode = "";
  804. }
  805. $aClassParams['state_attcode'] = "'$sStateAttCode'";
  806. if ($oReconciliation = $oProperties->GetOptionalElement('reconciliation'))
  807. {
  808. $oReconcAttributes = $oReconciliation->getElementsByTagName('attribute');
  809. $aReconcAttCodes = array();
  810. foreach($oReconcAttributes as $oAttribute)
  811. {
  812. $aReconcAttCodes[] = $oAttribute->getAttribute('id');
  813. }
  814. $sReconcKeys = "array('".implode("', '", $aReconcAttCodes)."')";
  815. }
  816. else
  817. {
  818. $sReconcKeys = "array()";
  819. }
  820. $aClassParams['reconc_keys'] = $sReconcKeys;
  821. $aClassParams['db_table'] = $this->GetPropString($oProperties, 'db_table', '');
  822. $aClassParams['db_key_field'] = $this->GetPropString($oProperties, 'db_key_field', 'id');
  823. if (array_key_exists($sClass, $this->aRootClasses))
  824. {
  825. $sDefaultFinalClass = 'finalclass';
  826. }
  827. else
  828. {
  829. $sDefaultFinalClass = '';
  830. }
  831. $aClassParams['db_finalclass_field'] = $this->GetPropString($oProperties, 'db_final_class_field', $sDefaultFinalClass);
  832. if (($sDisplayTemplate = $oProperties->GetChildText('display_template')) && (strlen($sDisplayTemplate) > 0))
  833. {
  834. $sDisplayTemplate = $sModuleRelativeDir.'/'.$sDisplayTemplate;
  835. $aClassParams['display_template'] = "utils::GetAbsoluteUrlModulesRoot().'$sDisplayTemplate'";
  836. }
  837. $this->CompileFiles($oProperties, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  838. if (($sIcon = $oProperties->GetChildText('icon')) && (strlen($sIcon) > 0))
  839. {
  840. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  841. $aClassParams['icon'] = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  842. }
  843. $oOrder = $oProperties->GetOptionalElement('order');
  844. if ($oOrder)
  845. {
  846. $oColumnsNode = $oOrder->GetUniqueElement('columns');
  847. $oColumns = $oColumnsNode->getElementsByTagName('column');
  848. $aSortColumns = array();
  849. foreach($oColumns as $oColumn)
  850. {
  851. $aSortColumns[] = "'".$oColumn->getAttribute('id')."' => ".(($oColumn->getAttribute('ascending') == 'true') ? 'true' : 'false');
  852. }
  853. if (count($aSortColumns) > 0)
  854. {
  855. $aClassParams['order_by_default'] = "array(".implode(", ", $aSortColumns).")";
  856. }
  857. }
  858. if ($oIndexes = $oProperties->GetOptionalElement('indexes'))
  859. {
  860. $aIndexes = array();
  861. foreach($oIndexes->getElementsByTagName('index') as $oIndex)
  862. {
  863. $sIndexId = $oIndex->getAttribute('id');
  864. $oAttributes = $oIndex->GetUniqueElement('attributes');
  865. foreach($oAttributes->getElementsByTagName('attribute') as $oAttribute)
  866. {
  867. $aIndexes[$sIndexId][] = $oAttribute->getAttribute('id');
  868. }
  869. }
  870. $aClassParams['indexes'] = var_export($aIndexes, true);
  871. }
  872. // Finalize class params declaration
  873. //
  874. $aClassParamsPHP = array();
  875. foreach($aClassParams as $sKey => $sPHPValue)
  876. {
  877. $aClassParamsPHP[] = " '$sKey' => $sPHPValue,";
  878. }
  879. $sClassParams = implode("\n", $aClassParamsPHP);
  880. // Comment on top of the class declaration
  881. //
  882. $sCodeComment = $oProperties->GetChildText('comment');
  883. // Fields
  884. //
  885. $sAttributes = '';
  886. foreach($this->oFactory->ListFields($oClass) as $oField)
  887. {
  888. try
  889. {
  890. // $oField
  891. $sAttCode = $oField->getAttribute('id');
  892. $sAttType = $oField->getAttribute('xsi:type');
  893. $aDependencies = array();
  894. $oDependencies = $oField->GetOptionalElement('dependencies');
  895. if (!is_null($oDependencies))
  896. {
  897. $oDepNodes = $oDependencies->getElementsByTagName('attribute');
  898. foreach($oDepNodes as $oDepAttribute)
  899. {
  900. $aDependencies[] = "'".$oDepAttribute->getAttribute('id')."'";
  901. }
  902. }
  903. $sDependencies = 'array('.implode(', ', $aDependencies).')';
  904. $aParameters = array();
  905. if ($sAttType == 'AttributeLinkedSetIndirect')
  906. {
  907. $aParameters['linked_class'] = $this->GetMandatoryPropString($oField, 'linked_class');
  908. $aParameters['ext_key_to_me'] = $this->GetMandatoryPropString($oField, 'ext_key_to_me');
  909. $aParameters['ext_key_to_remote'] = $this->GetMandatoryPropString($oField, 'ext_key_to_remote');
  910. $aParameters['allowed_values'] = 'null';
  911. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  912. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  913. $aParameters['duplicates'] = $this->GetPropBoolean($oField, 'duplicates', false);
  914. $aParameters['depends_on'] = $sDependencies;
  915. }
  916. elseif ($sAttType == 'AttributeLinkedSet')
  917. {
  918. $aParameters['linked_class'] = $this->GetMandatoryPropString($oField, 'linked_class');
  919. $aParameters['ext_key_to_me'] = $this->GetMandatoryPropString($oField, 'ext_key_to_me');
  920. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  921. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  922. $sEditMode = $oField->GetChildText('edit_mode');
  923. if (!is_null($sEditMode))
  924. {
  925. $aParameters['edit_mode'] = $this->EditModeToPHP($sEditMode);
  926. }
  927. if ($sOql = $oField->GetChildText('filter'))
  928. {
  929. $sEscapedOql = self::QuoteForPHP($sOql);
  930. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)";
  931. }
  932. else
  933. {
  934. $aParameters['allowed_values'] = 'null';
  935. }
  936. $aParameters['depends_on'] = $sDependencies;
  937. }
  938. elseif ($sAttType == 'AttributeExternalKey')
  939. {
  940. $aParameters['targetclass'] = $this->GetPropString($oField, 'target_class', '');
  941. // deprecated: $aParameters['jointype'] = 'null';
  942. if ($sOql = $oField->GetChildText('filter'))
  943. {
  944. $sEscapedOql = self::QuoteForPHP($sOql);
  945. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  946. }
  947. else
  948. {
  949. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  950. }
  951. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  952. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  953. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  954. $aParameters['depends_on'] = $sDependencies;
  955. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  956. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  957. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  958. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'select');
  959. }
  960. elseif ($sAttType == 'AttributeObjectKey')
  961. {
  962. $aParameters['class_attcode'] = $this->GetMandatoryPropString($oField, 'class_attcode');
  963. $aParameters['allowed_values'] = 'null';
  964. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  965. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  966. $aParameters['depends_on'] = $sDependencies;
  967. }
  968. elseif ($sAttType == 'AttributeHierarchicalKey')
  969. {
  970. if ($sOql = $oField->GetChildText('filter'))
  971. {
  972. $sEscapedOql = self::QuoteForPHP($sOql);
  973. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  974. }
  975. else
  976. {
  977. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  978. }
  979. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  980. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  981. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  982. $aParameters['depends_on'] = $sDependencies;
  983. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  984. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  985. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  986. }
  987. elseif ($sAttType == 'AttributeExternalField')
  988. {
  989. $aParameters['allowed_values'] = 'null';
  990. $aParameters['extkey_attcode'] = $this->GetMandatoryPropString($oField, 'extkey_attcode', '');
  991. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode', '');
  992. }
  993. elseif ($sAttType == 'AttributeURL')
  994. {
  995. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  996. $aParameters['allowed_values'] = 'null';
  997. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  998. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  999. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  1000. $aParameters['depends_on'] = $sDependencies;
  1001. }
  1002. elseif ($sAttType == 'AttributeEnum')
  1003. {
  1004. $oValues = $oField->GetUniqueElement('values');
  1005. $oValueNodes = $oValues->getElementsByTagName('value');
  1006. $aValues = array();
  1007. foreach($oValueNodes as $oValue)
  1008. {
  1009. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  1010. $aValues[] = $oValue->textContent;
  1011. }
  1012. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  1013. $sValues = '"'.implode(',', $aValues).'"';
  1014. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  1015. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  1016. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  1017. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  1018. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  1019. $aParameters['depends_on'] = $sDependencies;
  1020. }
  1021. elseif ($sAttType == 'AttributeMetaEnum')
  1022. {
  1023. $oValues = $oField->GetUniqueElement('values');
  1024. $oValueNodes = $oValues->getElementsByTagName('value');
  1025. $aValues = array();
  1026. foreach($oValueNodes as $oValue)
  1027. {
  1028. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  1029. $aValues[] = $oValue->textContent;
  1030. }
  1031. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  1032. $sValues = '"'.implode(',', $aValues).'"';
  1033. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  1034. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  1035. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  1036. $oMappings = $oField->GetUniqueElement('mappings');
  1037. $oMappingNodes = $oMappings->getElementsByTagName('mapping');
  1038. $aMapping = array();
  1039. foreach ($oMappingNodes as $oMapping)
  1040. {
  1041. $sMappingId = $oMapping->getAttribute('id');
  1042. $sMappingAttCode = $oMapping->GetChildText('attcode');
  1043. $aMapping[$sMappingId]['attcode'] = $sMappingAttCode;
  1044. $aMapping[$sMappingId]['values'] = array();
  1045. $oMetaValues = $oMapping->GetUniqueElement('metavalues');
  1046. foreach ($oMetaValues->getElementsByTagName('metavalue') as $oMetaValue)
  1047. {
  1048. $sMetaValue = $oMetaValue->getAttribute('id');
  1049. $oValues = $oMetaValue->GetUniqueElement('values');
  1050. foreach ($oValues->getElementsByTagName('value') as $oValue)
  1051. {
  1052. $sValue = $oValue->getAttribute('id');
  1053. $aMapping[$sMappingId]['values'][$sValue] = $sMetaValue;
  1054. }
  1055. }
  1056. }
  1057. $aParameters['mapping'] = var_export($aMapping, true);
  1058. }
  1059. elseif ($sAttType == 'AttributeBlob')
  1060. {
  1061. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  1062. $aParameters['depends_on'] = $sDependencies;
  1063. }
  1064. elseif ($sAttType == 'AttributeStopWatch')
  1065. {
  1066. $oStates = $oField->GetUniqueElement('states');
  1067. $oStateNodes = $oStates->getElementsByTagName('state');
  1068. $aStates = array();
  1069. foreach($oStateNodes as $oState)
  1070. {
  1071. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  1072. }
  1073. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  1074. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  1075. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', ''); // Blank (different than DefaultWorkingTimeComputer)
  1076. $oThresholds = $oField->GetUniqueElement('thresholds');
  1077. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  1078. $aThresholds = array();
  1079. foreach($oThresholdNodes as $oThreshold)
  1080. {
  1081. $iPercent = (int)$oThreshold->getAttribute('id');
  1082. $oHighlight = $oThreshold->GetUniqueElement('highlight', false);
  1083. $sHighlight = '';
  1084. if($oHighlight)
  1085. {
  1086. $sCode = $oHighlight->GetChildText('code');
  1087. $sPersistent = $this->GetPropBoolean($oHighlight, 'persistent', false);
  1088. $sHighlight = "'highlight' => array('code' => '$sCode', 'persistent' => $sPersistent), ";
  1089. }
  1090. $oActions = $oThreshold->GetUniqueElement('actions');
  1091. $oActionNodes = $oActions->getElementsByTagName('action');
  1092. $aActions = array();
  1093. foreach($oActionNodes as $oAction)
  1094. {
  1095. $oParams = $oAction->GetOptionalElement('params');
  1096. $aActionParams = array();
  1097. if ($oParams)
  1098. {
  1099. $oParamNodes = $oParams->getElementsByTagName('param');
  1100. foreach($oParamNodes as $oParam)
  1101. {
  1102. $sParamType = $oParam->getAttribute('xsi:type');
  1103. if ($sParamType == '')
  1104. {
  1105. $sParamType = 'string';
  1106. }
  1107. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  1108. }
  1109. }
  1110. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  1111. $sVerb = $this->GetPropString($oAction, 'verb');
  1112. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  1113. }
  1114. $sActions = 'array('.implode(', ', $aActions).')';
  1115. $aThresholds[] = $iPercent." => array('percent' => $iPercent, $sHighlight 'actions' => $sActions)";
  1116. }
  1117. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  1118. }
  1119. elseif ($sAttType == 'AttributeSubItem')
  1120. {
  1121. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode');
  1122. $aParameters['item_code'] = $this->GetMandatoryPropString($oField, 'item_code');
  1123. }
  1124. elseif ($sAttType == 'AttributeRedundancySettings')
  1125. {
  1126. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  1127. $aParameters['relation_code'] = $this->GetMandatoryPropString($oField, 'relation_code');
  1128. $aParameters['from_class'] = $this->GetMandatoryPropString($oField, 'from_class');
  1129. $aParameters['neighbour_id'] = $this->GetMandatoryPropString($oField, 'neighbour_id');
  1130. $aParameters['enabled'] = $this->GetMandatoryPropBoolean($oField, 'enabled');
  1131. $aParameters['enabled_mode'] = $this->GetMandatoryPropString($oField, 'enabled_mode');
  1132. $aParameters['min_up'] = $this->GetMandatoryPropNumber($oField, 'min_up');
  1133. $aParameters['min_up_mode'] = $this->GetMandatoryPropString($oField, 'min_up_mode');
  1134. $aParameters['min_up_type'] = $this->GetMandatoryPropString($oField, 'min_up_type');
  1135. }
  1136. elseif ($sAttType == 'AttributeCustomFields')
  1137. {
  1138. $aParameters['handler_class'] = $this->GetMandatoryPropString($oField, 'handler_class');
  1139. }
  1140. else
  1141. {
  1142. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  1143. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  1144. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  1145. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  1146. $aParameters['depends_on'] = $sDependencies;
  1147. }
  1148. // Optional parameters (more for historical reasons)
  1149. // Added if present...
  1150. //
  1151. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  1152. $aParameters['format'] = $this->GetPropString($oField, 'format');
  1153. $aParameters['width'] = $this->GetPropString($oField, 'width');
  1154. $aParameters['height'] = $this->GetPropString($oField, 'height');
  1155. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  1156. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  1157. $aParameters['always_load_in_tables'] = $this->GetPropBoolean($oField, 'always_load_in_tables', false);
  1158. $sTrackingLevel = $oField->GetChildText('tracking_level');
  1159. if (!is_null($sTrackingLevel))
  1160. {
  1161. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sAttType, $sTrackingLevel);
  1162. }
  1163. $aParams = array();
  1164. foreach($aParameters as $sKey => $sValue)
  1165. {
  1166. if (!is_null($sValue))
  1167. {
  1168. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  1169. }
  1170. }
  1171. $sParams = implode(', ', $aParams);
  1172. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  1173. }
  1174. catch(Exception $e)
  1175. {
  1176. throw new DOMFormatException("Field: '$sAttCode', (type: $sAttType), ".$e->getMessage());
  1177. }
  1178. }
  1179. // Lifecycle
  1180. //
  1181. $sLifecycle = '';
  1182. $sHighlightScale = '';
  1183. if ($oLifecycle)
  1184. {
  1185. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  1186. $sLifecycle .= "\t\t//\n";
  1187. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  1188. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  1189. {
  1190. $sStimulus = $oStimulus->getAttribute('id');
  1191. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  1192. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  1193. }
  1194. $oHighlightScale = $oLifecycle->GetUniqueElement('highlight_scale', false);
  1195. if ($oHighlightScale)
  1196. {
  1197. $sHighlightScale = "\t\t// Higlight Scale\n";
  1198. $sHighlightScale .= " MetaModel::Init_DefineHighlightScale( array(\n";
  1199. $this->CompileFiles($oHighlightScale, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  1200. foreach ($oHighlightScale->getElementsByTagName('item') as $oItem)
  1201. {
  1202. $sItemCode = $oItem->getAttribute('id');
  1203. $fRank = (float)$oItem->GetChildText('rank');
  1204. $sColor = $oItem->GetChildText('color');
  1205. if (($sIcon = $oItem->GetChildText('icon')) && (strlen($sIcon) > 0))
  1206. {
  1207. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  1208. $sIcon = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  1209. }
  1210. else
  1211. {
  1212. $sIcon = "''";
  1213. }
  1214. switch($sColor)
  1215. {
  1216. // Known PHP constants: keep the literal value as-is
  1217. case 'HILIGHT_CLASS_CRITICAL':
  1218. case 'HIGHLIGHT_CLASS_CRITICAL':
  1219. $sColor = 'HILIGHT_CLASS_CRITICAL';
  1220. break;
  1221. case 'HILIGHT_CLASS_OK':
  1222. case 'HIGHLIGHT_CLASS_OK':
  1223. $sColor = 'HILIGHT_CLASS_OK';
  1224. break;
  1225. case 'HIGHLIGHT_CLASS_WARNING':
  1226. case 'HILIGHT_CLASS_WARNING':
  1227. $sColor = 'HILIGHT_CLASS_WARNING';
  1228. break;
  1229. case 'HIGHLIGHT_CLASS_NONE':
  1230. case 'HILIGHT_CLASS_NONE':
  1231. $sColor = 'HILIGHT_CLASS_NONE';
  1232. break;
  1233. default:
  1234. // Future extension, specify your own color??
  1235. $sColor = "'".addslashes($sColor)."'";
  1236. }
  1237. $sHighlightScale .= " '$sItemCode' => array('rank' => $fRank, 'color' => $sColor, 'icon' => $sIcon),\n";
  1238. }
  1239. $sHighlightScale .= " ));\n";
  1240. }
  1241. $oStates = $oLifecycle->GetUniqueElement('states');
  1242. $aStatesDependencies = array();
  1243. $aStates = array();
  1244. foreach ($oStates->getElementsByTagName('state') as $oState)
  1245. {
  1246. $aStatesDependencies[$oState->getAttribute('id')] = $oState->GetChildText('inherit_flags_from', '');
  1247. $aStates[$oState->getAttribute('id')] = $oState;
  1248. }
  1249. $aStatesOrder = array();
  1250. while (count($aStatesOrder) < count($aStatesDependencies))
  1251. {
  1252. $iResolved = 0;
  1253. foreach($aStatesDependencies as $sState => $sInheritFrom)
  1254. {
  1255. if (is_null($sInheritFrom))
  1256. {
  1257. // Already recorded as resolved
  1258. continue;
  1259. }
  1260. elseif ($sInheritFrom == '')
  1261. {
  1262. // Resolved
  1263. $aStatesOrder[$sState] = $sInheritFrom;
  1264. $aStatesDependencies[$sState] = null;
  1265. $iResolved++;
  1266. }
  1267. elseif (isset($aStatesOrder[$sInheritFrom]))
  1268. {
  1269. // Resolved
  1270. $aStatesOrder[$sState] = $sInheritFrom;
  1271. $aStatesDependencies[$sState] = null;
  1272. $iResolved++;
  1273. }
  1274. }
  1275. if ($iResolved == 0)
  1276. {
  1277. // No change on this loop -> there are unmet dependencies
  1278. $aRemainingDeps = array();
  1279. foreach($aStatesDependencies as $sState => $sParentState)
  1280. {
  1281. if (strlen($sParentState) > 0)
  1282. {
  1283. $aRemainingDeps[] = $sState.' ('.$sParentState.')';
  1284. }
  1285. }
  1286. throw new DOMFormatException("Could not solve inheritance for states: ".implode(', ', $aRemainingDeps));
  1287. }
  1288. }
  1289. foreach ($aStatesOrder as $sState => $foo)
  1290. {
  1291. $oState = $aStates[$sState];
  1292. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  1293. if ($oInitialStatePath)
  1294. {
  1295. $aInitialStatePath = array();
  1296. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  1297. {
  1298. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  1299. }
  1300. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  1301. }
  1302. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  1303. $sLifecycle .= " \"".$sState."\",\n";
  1304. $sLifecycle .= " array(\n";
  1305. $sAttributeInherit = $oState->GetChildText('inherit_flags_from', '');
  1306. $sLifecycle .= " \"attribute_inherit\" => '$sAttributeInherit',\n";
  1307. $oHighlight = $oState->GetUniqueElement('highlight', false);
  1308. if ($oHighlight)
  1309. {
  1310. $sCode = $oHighlight->GetChildText('code', '');
  1311. if ($sCode != '')
  1312. {
  1313. $sLifecycle .= " 'highlight' => array('code' => '$sCode'),\n";
  1314. }
  1315. }
  1316. $sLifecycle .= " \"attribute_list\" => array(\n";
  1317. $oFlags = $oState->GetUniqueElement('flags');
  1318. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  1319. {
  1320. $sFlags = $this->FlagsToPHP($oAttributeNode);
  1321. if (strlen($sFlags) > 0)
  1322. {
  1323. $sAttCode = $oAttributeNode->GetAttribute('id');
  1324. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  1325. }
  1326. }
  1327. $sLifecycle .= " ),\n";
  1328. if (!is_null($oInitialStatePath))
  1329. {
  1330. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  1331. }
  1332. $sLifecycle .= " )\n";
  1333. $sLifecycle .= " );\n";
  1334. $oTransitions = $oState->GetUniqueElement('transitions');
  1335. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  1336. {
  1337. $sStimulus = $oTransition->getAttribute('id');
  1338. $sTargetState = $oTransition->GetChildText('target');
  1339. $oActions = $oTransition->GetUniqueElement('actions');
  1340. $aVerbs = array();
  1341. foreach ($oActions->getElementsByTagName('action') as $oAction)
  1342. {
  1343. $sVerb = $oAction->GetChildText('verb');
  1344. $oParams = $oAction->GetOptionalElement('params');
  1345. $aActionParams = array();
  1346. if ($oParams)
  1347. {
  1348. $oParamNodes = $oParams->getElementsByTagName('param');
  1349. foreach($oParamNodes as $oParam)
  1350. {
  1351. $sParamType = $oParam->getAttribute('xsi:type');
  1352. if ($sParamType == '')
  1353. {
  1354. $sParamType = 'string';
  1355. }
  1356. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  1357. }
  1358. }
  1359. else
  1360. {
  1361. // Old (pre 2.1.0) format, when no parameter is specified, assume 1 parameter: reference sStimulusCode
  1362. $aActionParams[] = "array('type' => 'reference', 'value' => 'sStimulusCode')";
  1363. }
  1364. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  1365. $aVerbs[] = "array('verb' => '$sVerb', 'params' => $sActionParams)";
  1366. }
  1367. $sActions = implode(', ', $aVerbs);
  1368. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  1369. }
  1370. }
  1371. }
  1372. // ZLists
  1373. //
  1374. $aListRef = array(
  1375. 'details' => 'details',
  1376. 'standard_search' => 'search',
  1377. 'list' => 'list'
  1378. );
  1379. $oPresentation = $oClass->GetUniqueElement('presentation');
  1380. $sZlists = '';
  1381. foreach ($aListRef as $sListCode => $sListTag)
  1382. {
  1383. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  1384. if ($oListNode)
  1385. {
  1386. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  1387. $this->ArrayOfItemsToZList($aAttributes);
  1388. $sZAttributes = var_export($aAttributes, true);
  1389. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  1390. }
  1391. }
  1392. // Methods
  1393. $sMethods = "";
  1394. $oMethods = $oClass->GetUniqueElement('methods');
  1395. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  1396. {
  1397. $sMethodCode = $oMethod->GetChildText('code');
  1398. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  1399. {
  1400. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  1401. }
  1402. else
  1403. {
  1404. $sMethods .= "\n\n".$sMethodCode."\n";
  1405. }
  1406. }
  1407. // Relations
  1408. //
  1409. $oRelations = $oClass->GetOptionalElement('relations');
  1410. if ($oRelations)
  1411. {
  1412. $aRelations = array();
  1413. foreach($oRelations->getElementsByTagName('relation') as $oRelation)
  1414. {
  1415. $sRelationId = $oRelation->getAttribute('id');
  1416. $this->aRelations[$sRelationId] = array('id' => $sRelationId);
  1417. $oNeighbours = $oRelation->GetUniqueElement('neighbours');
  1418. foreach($oNeighbours->getElementsByTagName('neighbour') as $oNeighbour)
  1419. {
  1420. $sNeighbourId = $oNeighbour->getAttribute('id');
  1421. $sDirection = $oNeighbour->GetChildText('direction', 'both');
  1422. $sAttribute = $oNeighbour->GetChildText('attribute');
  1423. $sQueryDown = $oNeighbour->GetChildText('query_down');
  1424. $sQueryUp = $oNeighbour->GetChildText('query_up');
  1425. if (($sQueryDown == '') && ($sAttribute == ''))
  1426. {
  1427. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': either a query or an attribute must be specified");
  1428. }
  1429. if (($sQueryDown != '') && ($sAttribute != ''))
  1430. {
  1431. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': both a query and and attribute have been specified... which one should be used?");
  1432. }
  1433. if ($sDirection == 'both')
  1434. {
  1435. if (($sAttribute == '') && ($sQueryUp == ''))
  1436. {
  1437. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': missing the query_up specification");
  1438. }
  1439. }
  1440. elseif ($sDirection == 'down')
  1441. {
  1442. // Ok
  1443. }
  1444. else
  1445. {
  1446. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': unknown direction ($sDirection), expecting 'both' or 'down'");
  1447. }
  1448. $aRelations[$sRelationId][$sNeighbourId] = array(
  1449. '_legacy_' => false,
  1450. 'sDirection' => $sDirection,
  1451. 'sDefinedInClass' => $sClass,
  1452. 'sNeighbour' => $sNeighbourId,
  1453. 'sQueryDown' => $sQueryDown,
  1454. 'sQueryUp' => $sQueryUp,
  1455. 'sAttribute' => $sAttribute,
  1456. );
  1457. }
  1458. }
  1459. $sMethods .= "\tpublic static function GetRelationQueriesEx(\$sRelCode)\n";
  1460. $sMethods .= "\t{\n";
  1461. $sMethods .= "\t\tswitch (\$sRelCode)\n";
  1462. $sMethods .= "\t\t{\n";
  1463. foreach ($aRelations as $sRelationId => $aRelationData)
  1464. {
  1465. $sMethods .= "\t\tcase '$sRelationId':\n";
  1466. $sMethods .= "\t\t\t\$aRels = array(\n";
  1467. foreach ($aRelationData as $sNeighbourId => $aData)
  1468. {
  1469. //$sData = str_replace("\n", "\n\t\t\t\t", var_export($aData, true));
  1470. $sData = var_export($aData, true);
  1471. $sMethods .= "\t\t\t\t'$sNeighbourId' => $sData,\n";
  1472. }
  1473. $sMethods .= "\t\t\t);\n";
  1474. $sMethods .= "\t\t\treturn array_merge(\$aRels, parent::GetRelationQueriesEx(\$sRelCode));\n\n";
  1475. }
  1476. $sMethods .= "\t\tdefault:\n";
  1477. $sMethods .= "\t\t\treturn parent::GetRelationQueriesEx(\$sRelCode);\n";
  1478. $sMethods .= "\t\t}\n";
  1479. $sMethods .= "\t}\n";
  1480. }
  1481. // Let's make the whole class declaration
  1482. //
  1483. $sPHP = "\n\n$sCodeComment\n";
  1484. $sParentClass = $oClass->GetChildText('php_parent');
  1485. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  1486. if ($oPhpParent)
  1487. {
  1488. $sParentClass = $oPhpParent->GetChildText('name', '');
  1489. if ($sParentClass == '')
  1490. {
  1491. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', missing required tag 'name' under 'php_parent'.");
  1492. }
  1493. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  1494. if ($sIncludeFile != '')
  1495. {
  1496. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  1497. }
  1498. //TODO fix this !!!
  1499. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  1500. // if (!file_exists($sFullPath))
  1501. // {
  1502. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  1503. // }
  1504. }
  1505. else
  1506. {
  1507. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  1508. }
  1509. if ($oProperties->GetChildText('abstract') == 'true')
  1510. {
  1511. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  1512. }
  1513. else
  1514. {
  1515. $sPHP .= 'class '.$oClass->getAttribute('id');
  1516. }
  1517. $sPHP .= " extends $sParentClass\n";
  1518. $sPHP .=
  1519. <<<EOF
  1520. {
  1521. public static function Init()
  1522. {
  1523. \$aParams = array
  1524. (
  1525. $sClassParams
  1526. );
  1527. MetaModel::Init_Params(\$aParams);
  1528. MetaModel::Init_InheritAttributes();
  1529. $sAttributes
  1530. $sLifecycle
  1531. $sHighlightScale
  1532. $sZlists
  1533. }
  1534. $sMethods
  1535. }
  1536. EOF;
  1537. return $sPHP;
  1538. }// function CompileClass()
  1539. protected function CompileMenu($oMenu, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  1540. {
  1541. $this->CompileFiles($oMenu, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, $sModuleRelativeDir);
  1542. $sMenuId = $oMenu->getAttribute("id");
  1543. $sMenuClass = $oMenu->getAttribute("xsi:type");
  1544. $sParent = $oMenu->GetChildText('parent', null);
  1545. if ($sParent)
  1546. {
  1547. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  1548. }
  1549. else
  1550. {
  1551. $sParentSpec = '-1';
  1552. }
  1553. $fRank = (float) $oMenu->GetChildText('rank');
  1554. switch($sMenuClass)
  1555. {
  1556. case 'WebPageMenuNode':
  1557. $sUrl = $oMenu->GetChildText('url');
  1558. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  1559. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  1560. break;
  1561. case 'DashboardMenuNode':
  1562. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  1563. if ($sTemplateFile != '')
  1564. {
  1565. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1566. }
  1567. else
  1568. {
  1569. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  1570. if ($oDashboardDefinition == null)
  1571. {
  1572. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  1573. }
  1574. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  1575. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  1576. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  1577. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1578. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1579. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  1580. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1581. $oXMLDoc->appendChild($oRootNode);
  1582. foreach($oDashboardDefinition->childNodes as $oNode)
  1583. {
  1584. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  1585. $oRootNode->appendChild($oDefNode);
  1586. }
  1587. $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  1588. }
  1589. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1590. break;
  1591. case 'ShortcutContainerMenuNode':
  1592. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1593. break;
  1594. case 'OQLMenuNode':
  1595. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1596. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1597. $sSearchFormOpen = ($oMenu->GetChildText('search_form_open') == '1') ? 'true' : 'false';
  1598. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch, $sSearchFormOpen);";
  1599. break;
  1600. case 'NewObjectMenuNode':
  1601. $sClass = $oMenu->GetChildText('class');
  1602. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1603. break;
  1604. case 'SearchMenuNode':
  1605. $sClass = $oMenu->GetChildText('class');
  1606. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1607. break;
  1608. case 'TemplateMenuNode':
  1609. $sTemplateFile = $oMenu->GetChildText('template_file');
  1610. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1611. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1612. {
  1613. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1614. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1615. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1616. if ($sEnableStimulus != null)
  1617. {
  1618. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1619. }
  1620. else
  1621. {
  1622. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1623. }
  1624. }
  1625. else
  1626. {
  1627. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1628. }
  1629. break;
  1630. case 'MenuGroup':
  1631. default:
  1632. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1633. {
  1634. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1635. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1636. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1637. if ($sEnableStimulus != null)
  1638. {
  1639. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1640. }
  1641. else
  1642. {
  1643. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1644. }
  1645. }
  1646. else
  1647. {
  1648. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1649. }
  1650. }
  1651. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1652. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1653. {
  1654. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1655. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1656. }
  1657. return $aPHPMenu;
  1658. } // function CompileMenu
  1659. /**
  1660. * Helper to compute the grant, taking any existing grant into account
  1661. */
  1662. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1663. {
  1664. if (isset($aGrants[$sKey]))
  1665. {
  1666. if (!$bGrant)
  1667. {
  1668. $aGrants[$sKey] = false;
  1669. }
  1670. }
  1671. else
  1672. {
  1673. $aGrants[$sKey] = $bGrant;
  1674. }
  1675. }
  1676. protected function CompileUserRights($oUserRightsNode)
  1677. {
  1678. static $aActionsInShort = array(
  1679. 'read' => 'r',
  1680. 'bulk read' => 'br',
  1681. 'write' => 'w',
  1682. 'bulk write' => 'bw',
  1683. 'delete' => 'd',
  1684. 'bulk delete' => 'bd',
  1685. );
  1686. // Preliminary : create an index so that links will be taken into account implicitely
  1687. $aLinkToClasses = array();
  1688. $oClasses = $this->oFactory->ListAllClasses();
  1689. foreach($oClasses as $oClass)
  1690. {
  1691. $bIsLink = false;
  1692. $oProperties = $oClass->GetOptionalElement('properties');
  1693. if ($oProperties)
  1694. {
  1695. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1696. }
  1697. if ($bIsLink)
  1698. {
  1699. foreach($this->oFactory->ListFields($oClass) as $oField)
  1700. {
  1701. $sAttType = $oField->getAttribute('xsi:type');
  1702. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1703. {
  1704. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1705. if (($sOnTargetDel == 'DEL_AUTO') || ($sOnTargetDel == 'DEL_SILENT'))
  1706. {
  1707. $sTargetClass = $oField->GetChildText('target_class');
  1708. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1709. }
  1710. }
  1711. }
  1712. }
  1713. }
  1714. // Groups
  1715. //
  1716. $aGroupClasses = array();
  1717. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1718. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1719. {
  1720. $sGroupId = $oGroup->getAttribute("id");
  1721. $aClasses = array();
  1722. $oClasses = $oGroup->GetUniqueElement('classes');
  1723. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1724. {
  1725. $sClass = $oClass->getAttribute("id");
  1726. $aClasses[] = $sClass;
  1727. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1728. //if ($bSubclasses)...
  1729. }
  1730. $aGroupClasses[$sGroupId] = $aClasses;
  1731. }
  1732. // Profiles and grants
  1733. //
  1734. $aProfiles = array();
  1735. // Hardcode the administrator profile
  1736. $aProfiles[1] = array(
  1737. 'name' => 'Administrator',
  1738. 'description' => 'Has the rights on everything (bypassing any control)'
  1739. );
  1740. $aGrants = array();
  1741. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1742. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1743. {
  1744. $iProfile = $oProfile->getAttribute("id");
  1745. $sName = $oProfile->GetChildText('name');
  1746. $sDescription = $oProfile->GetChildText('description');
  1747. $oGroups = $oProfile->GetUniqueElement('groups');
  1748. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1749. {
  1750. $sGroupId = $oGroup->getAttribute("id");
  1751. $aActions = array();
  1752. $oActions = $oGroup->GetUniqueElement('actions');
  1753. foreach($oActions->getElementsByTagName('action') as $oAction)
  1754. {
  1755. $sAction = $oAction->getAttribute("id");
  1756. if (strpos($sAction, 'action:') === 0)
  1757. {
  1758. $sType = 'action';
  1759. $sActionCode = substr($sAction, strlen('action:'));
  1760. $sActionCode = $aActionsInShort[$sActionCode];
  1761. }
  1762. else
  1763. {
  1764. $sType = 'stimulus';
  1765. $sActionCode = substr($sAction, strlen('stimulus:'));
  1766. }
  1767. $sGrant = $oAction->GetText();
  1768. $bGrant = ($sGrant == 'allow');
  1769. if ($sGroupId == '*')
  1770. {
  1771. $aGrantClasses = array('*');
  1772. }
  1773. else
  1774. {
  1775. $aGrantClasses = $aGroupClasses[$sGroupId];
  1776. }
  1777. foreach ($aGrantClasses as $sClass)
  1778. {
  1779. if ($sType == 'stimulus')
  1780. {
  1781. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sActionCode, $bGrant);
  1782. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1783. }
  1784. else
  1785. {
  1786. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sActionCode, $bGrant);
  1787. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1788. }
  1789. }
  1790. }
  1791. }
  1792. $aProfiles[$iProfile] = array(
  1793. 'name' => $sName,
  1794. 'description' => $sDescription
  1795. );
  1796. }
  1797. $sProfiles = var_export($aProfiles, true);
  1798. $sGrants = var_export($aGrants, true);
  1799. $sLinkToClasses = var_export($aLinkToClasses, true);
  1800. $sPHP =
  1801. <<<EOF
  1802. //
  1803. // List of constant profiles
  1804. // - used by the class URP_Profiles at setup (create/update/delete records)
  1805. // - used by the addon UserRightsProfile to determine user rights
  1806. //
  1807. class ProfilesConfig
  1808. {
  1809. protected static \$aPROFILES = $sProfiles;
  1810. protected static \$aGRANTS = $sGrants;
  1811. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1812. // Now replaced by MetaModel::GetLinkClasses (working with 1.x)
  1813. // This function could be deprecated
  1814. public static function GetLinkClasses()
  1815. {
  1816. return self::\$aLINKTOCLASSES;
  1817. }
  1818. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1819. {
  1820. \$bLegacyBehavior = MetaModel::GetConfig()->Get('user_rights_legacy');
  1821. // Search for a grant, stoping if any deny is encountered (allowance implies the verification of all paths)
  1822. \$bAllow = null;
  1823. // 1 - The class itself
  1824. //
  1825. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1826. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1827. {
  1828. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1829. if (\$bLegacyBehavior) return \$bAllow;
  1830. if (!\$bAllow) return false;
  1831. }
  1832. // 2 - The parent classes, up to the root class
  1833. //
  1834. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1835. {
  1836. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1837. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1838. {
  1839. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1840. if (\$bLegacyBehavior) return \$bAllow;
  1841. if (!\$bAllow) return false;
  1842. }
  1843. }
  1844. // 3 - The related classes (if the current is an N-N link with DEL_AUTO/DEL_SILENT)
  1845. //
  1846. \$bGrant = self::GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction);
  1847. if (!is_null(\$bGrant))
  1848. {
  1849. \$bAllow = \$bGrant;
  1850. if (\$bLegacyBehavior) return \$bAllow;
  1851. if (!\$bAllow) return false;
  1852. }
  1853. // 4 - All
  1854. //
  1855. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1856. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1857. {
  1858. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1859. if (\$bLegacyBehavior) return \$bAllow;
  1860. if (!\$bAllow) return false;
  1861. }
  1862. // null or true
  1863. return \$bAllow;
  1864. }
  1865. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1866. {
  1867. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1868. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1869. {
  1870. return self::\$aGRANTS[\$sGrantKey];
  1871. }
  1872. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1873. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1874. {
  1875. return self::\$aGRANTS[\$sGrantKey];
  1876. }
  1877. return null;
  1878. }
  1879. // returns an array of id => array of column => php value(so-called "real value")
  1880. public static function GetProfilesValues()
  1881. {
  1882. return self::\$aPROFILES;
  1883. }
  1884. // Propagate the rights on classes onto the links themselves (the external keys must have DEL_AUTO or DEL_SILENT
  1885. //
  1886. protected static function GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction)
  1887. {
  1888. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1889. {
  1890. // Get the grant for the remote classes. The resulting grant is:
  1891. // - One YES => YES
  1892. // - 100% undefined => undefined
  1893. // - otherwise => NO
  1894. //
  1895. // Having write allowed on the remote class implies write + delete on the N-N link class
  1896. if (\$sAction == 'd')
  1897. {
  1898. \$sRemoteAction = 'w';
  1899. }
  1900. elseif (\$sAction == 'bd')
  1901. {
  1902. \$sRemoteAction = 'bw';
  1903. }
  1904. else
  1905. {
  1906. \$sRemoteAction = \$sAction;
  1907. }
  1908. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1909. {
  1910. \$bUndefined = true;
  1911. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1912. if (\$bGrant === true)
  1913. {
  1914. return true;
  1915. }
  1916. if (\$bGrant === false)
  1917. {
  1918. \$bUndefined = false;
  1919. }
  1920. }
  1921. if (!\$bUndefined)
  1922. {
  1923. return false;
  1924. }
  1925. }
  1926. return null;
  1927. }
  1928. }
  1929. EOF;
  1930. return $sPHP;
  1931. } // function CompileUserRights
  1932. protected function CompileDictionaries($oDictionaries, $sTempTargetDir, $sFinalTargetDir)
  1933. {
  1934. $aLanguages = array();
  1935. foreach($oDictionaries as $oDictionaryNode)
  1936. {
  1937. $sLang = $oDictionaryNode->getAttribute('id');
  1938. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1939. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1940. $aLanguages[$sLang] = array('description' => $sEnglishLanguageDesc, 'localized_description' => $sLocalizedLanguageDesc);
  1941. $aEntriesPHP = array();
  1942. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1943. foreach ($oEntries->getElementsByTagName('entry') as $oEntry)
  1944. {
  1945. $sStringCode = $oEntry->getAttribute('id');
  1946. $sValue = $oEntry->GetText();
  1947. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP(self::FilterDictString($sValue), true).",";
  1948. }
  1949. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1950. $sPHPDict =
  1951. <<<EOF
  1952. <?php
  1953. //
  1954. // Dictionary built by the compiler for the language "$sLang"
  1955. //
  1956. Dict::SetEntries('$sLang', array(
  1957. $sEntriesPHP
  1958. ));
  1959. EOF;
  1960. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1961. $sDictFile = $sTempTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1962. file_put_contents($sDictFile, $sPHPDict);
  1963. }
  1964. $sLanguagesFile = $sTempTargetDir.'/dictionaries/languages.php';
  1965. $sLanguagesDump = var_export($aLanguages, true);
  1966. $sLanguagesFileContent =
  1967. <<<EOF
  1968. <?php
  1969. //
  1970. // Dictionary index built by the compiler
  1971. //
  1972. Dict::SetLanguagesList(
  1973. $sLanguagesDump
  1974. );
  1975. EOF;
  1976. file_put_contents($sLanguagesFile, $sLanguagesFileContent);
  1977. }
  1978. protected static function FilterDictString($s)
  1979. {
  1980. if (strpos($s, '~') !== false)
  1981. {
  1982. return str_replace(array('~~', '~*'), '', $s);
  1983. }
  1984. return $s;
  1985. }
  1986. // Transform the file references into the corresponding filename (and create the file in the relevant directory)
  1987. //
  1988. protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath)
  1989. {
  1990. $oFileRefs = $oNode->GetNodes(".//fileref");
  1991. foreach ($oFileRefs as $oFileRef)
  1992. {
  1993. $sFileId = $oFileRef->getAttribute('ref');
  1994. if ($sFileId !== '')
  1995. {
  1996. $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id='$sFileId']");
  1997. if ($oNodes->length == 0)
  1998. {
  1999. throw new DOMFormatException('Could not find the file with ref '.$sFileId);
  2000. }
  2001. $sName = $oNodes->item(0)->GetChildText('name');
  2002. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  2003. $aPathInfo = pathinfo($sName);
  2004. $sFile = $sFileId.'.'.$aPathInfo['extension'];
  2005. $sFilePath = $sTempTargetDir.'/images/'.$sFile;
  2006. @mkdir($sTempTargetDir.'/images');
  2007. file_put_contents($sFilePath, $sData);
  2008. if (!file_exists($sFilePath))
  2009. {
  2010. throw new Exception('Could not write icon file '.$sFilePath);
  2011. }
  2012. $oParentNode = $oFileRef->parentNode;
  2013. $oParentNode->removeChild($oFileRef);
  2014. $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile);
  2015. $oParentNode->appendChild($oTextNode);
  2016. }
  2017. }
  2018. }
  2019. protected function CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $sNodeName, $sTargetFile)
  2020. {
  2021. if (($sIcon = $oBrandingNode->GetChildText($sNodeName)) && (strlen($sIcon) > 0))
  2022. {
  2023. $sSourceFile = $sTempTargetDir.'/'.$sIcon;
  2024. $sTargetFile = $sTempTargetDir.'/branding/'.$sTargetFile.'.png';
  2025. if (!file_exists($sSourceFile))
  2026. {
  2027. throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)");
  2028. }
  2029. copy($sSourceFile, $sTargetFile);
  2030. }
  2031. }
  2032. protected function CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir)
  2033. {
  2034. // Enable relative paths
  2035. SetupUtils::builddir($sTempTargetDir.'/branding');
  2036. if ($oBrandingNode)
  2037. {
  2038. // Transform file refs into files in the images folder
  2039. $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding');
  2040. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'main_logo', 'main-logo');
  2041. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'login_logo', 'login-logo');
  2042. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'portal_logo', 'portal-logo');
  2043. // Cleanup the images directory (eventually made by CompileFiles)
  2044. if (file_exists($sTempTargetDir.'/branding/images'))
  2045. {
  2046. SetupUtils::rrmdir($sTempTargetDir.'/branding/images');
  2047. }
  2048. }
  2049. }
  2050. protected function CompilePortals($oPortalsNode, $sTempTargetDir, $sFinalTargetDir)
  2051. {
  2052. if ($oPortalsNode)
  2053. {
  2054. // Create some static PHP data in <env-xxx>/core/main.php
  2055. $oPortals = $oPortalsNode->GetNodes('portal');
  2056. $aPortalsConfig = array();
  2057. foreach($oPortals as $oPortal)
  2058. {
  2059. $sPortalId = $oPortal->getAttribute('id');
  2060. $aPortalsConfig[$sPortalId] = array();
  2061. $aPortalsConfig[$sPortalId]['rank'] = (float)$oPortal->GetChildText('rank', 0);
  2062. $aPortalsConfig[$sPortalId]['handler'] = $oPortal->GetChildText('handler', 'PortalDispatcher');
  2063. $aPortalsConfig[$sPortalId]['url'] = $oPortal->GetChildText('url', 'portal/index.php');
  2064. $oAllow = $oPortal->GetOptionalElement('allow');
  2065. $aPortalsConfig[$sPortalId]['allow'] = array();
  2066. if ($oAllow)
  2067. {
  2068. foreach($oAllow->GetNodes('profile') as $oProfile)
  2069. {
  2070. $aPortalsConfig[$sPortalId]['allow'][] = $oProfile->getAttribute('id');
  2071. }
  2072. }
  2073. $oDeny = $oPortal->GetOptionalElement('deny');
  2074. $aPortalsConfig[$sPortalId]['deny'] = array();
  2075. if ($oDeny)
  2076. {
  2077. foreach($oDeny->GetNodes('profile') as $oProfile)
  2078. {
  2079. $aPortalsConfig[$sPortalId]['deny'][] = $oProfile->getAttribute('id');
  2080. }
  2081. }
  2082. }
  2083. uasort($aPortalsConfig, array(get_class($this), 'SortOnRank'));
  2084. $this->sMainPHPCode .= "\n";
  2085. $this->sMainPHPCode .= "/**\n";
  2086. $this->sMainPHPCode .= " * Portal(s) definition(s) extracted from the XML definition at compile time\n";
  2087. $this->sMainPHPCode .= " */\n";
  2088. $this->sMainPHPCode .= "class PortalDispatcherData\n";
  2089. $this->sMainPHPCode .= "{\n";
  2090. $this->sMainPHPCode .= "\tprotected static \$aData = ".var_export($aPortalsConfig, true).";\n\n";
  2091. $this->sMainPHPCode .= "\tpublic static function GetData(\$sPortalId = null)\n";
  2092. $this->sMainPHPCode .= "\t{\n";
  2093. $this->sMainPHPCode .= "\t\tif (\$sPortalId === null) return self::\$aData;\n";
  2094. $this->sMainPHPCode .= "\t\tif (!array_key_exists(\$sPortalId, self::\$aData)) return array();\n";
  2095. $this->sMainPHPCode .= "\t\treturn self::\$aData[\$sPortalId];\n";
  2096. $this->sMainPHPCode .= "\t}\n";
  2097. $this->sMainPHPCode .= "}\n";
  2098. }
  2099. }
  2100. public static function SortOnRank($aConf1, $aConf2)
  2101. {
  2102. return ($aConf1['rank'] < $aConf2['rank']) ? -1 : 1;
  2103. }
  2104. protected function CompileParameters($oParametersNode, $sTempTargetDir, $sFinalTargetDir)
  2105. {
  2106. if ($oParametersNode)
  2107. {
  2108. // Create some static PHP data in <env-xxx>/core/main.php
  2109. $oParameters = $oParametersNode->GetNodes('parameters');
  2110. $aParametersConfig = array();
  2111. foreach($oParameters as $oParams)
  2112. {
  2113. $sModuleId = $oParams->getAttribute('id');
  2114. $oParamsReader = new MFParameters($oParams);
  2115. $aParametersConfig[$sModuleId] = $oParamsReader->GetAll();
  2116. }
  2117. $this->sMainPHPCode .= "\n";
  2118. $this->sMainPHPCode .= "/**\n";
  2119. $this->sMainPHPCode .= " * Modules parameters extracted from the XML definition at compile time\n";
  2120. $this->sMainPHPCode .= " */\n";
  2121. $this->sMainPHPCode .= "class ModulesXMLParameters\n";
  2122. $this->sMainPHPCode .= "{\n";
  2123. $this->sMainPHPCode .= "\tprotected static \$aData = ".var_export($aParametersConfig, true).";\n\n";
  2124. $this->sMainPHPCode .= "\tpublic static function GetData(\$sModuleId = null)\n";
  2125. $this->sMainPHPCode .= "\t{\n";
  2126. $this->sMainPHPCode .= "\t\tif (\$sModuleId === null) return self::\$aData;\n";
  2127. $this->sMainPHPCode .= "\t\tif (!array_key_exists(\$sModuleId, self::\$aData)) return array();\n";
  2128. $this->sMainPHPCode .= "\t\treturn self::\$aData[\$sModuleId];\n";
  2129. $this->sMainPHPCode .= "\t}\n";
  2130. $this->sMainPHPCode .= "}\n";
  2131. }
  2132. }
  2133. protected function CompileModuleDesigns($oDesigns, $sTempTargetDir, $sFinalTargetDir)
  2134. {
  2135. if ($oDesigns)
  2136. {
  2137. SetupUtils::builddir($sTempTargetDir.'/core/module_designs/images');
  2138. $this->CompileFiles($oDesigns, $sTempTargetDir.'/core/module_designs', $sFinalTargetDir.'/core/module_designs', 'core/module_designs');
  2139. foreach ($oDesigns->GetNodes('module_design') as $oDesign)
  2140. {
  2141. $oDoc = new ModuleDesign();
  2142. $oClone = $oDoc->importNode($oDesign->cloneNode(true), true);
  2143. $oDoc->appendChild($oClone);
  2144. $oDoc->save($sTempTargetDir.'/core/module_designs/'.$oDesign->getAttribute('id').'.xml');
  2145. }
  2146. }
  2147. }
  2148. protected function LoadSnippets()
  2149. {
  2150. $oSnippets = $this->oFactory->GetNodes('/itop_design/snippets/snippet');
  2151. foreach($oSnippets as $oSnippet)
  2152. {
  2153. $sSnippetId = $oSnippet->getAttribute('id');
  2154. $sPlacement = $oSnippet->GetChildText('placement', null);
  2155. if ($sPlacement == 'core')
  2156. {
  2157. $sModuleId = '_core_';
  2158. }
  2159. else if ($sPlacement == 'module')
  2160. {
  2161. $sModuleId = $oSnippet->GetChildText('module', null);
  2162. if ($sModuleId == null)
  2163. {
  2164. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId' with placement=module. Missing '<module>' tag.");
  2165. }
  2166. }
  2167. else if ($sPlacement === 'null')
  2168. {
  2169. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Missing <placement> tag.");
  2170. }
  2171. else
  2172. {
  2173. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Incorrect value '$sPlacement' for <placement> tag. The allowed values are either 'core' or 'module'.");
  2174. }
  2175. if (!array_key_exists($sModuleId, $this->aSnippets))
  2176. {
  2177. $this->aSnippets[$sModuleId] = array('before' => array(), 'after' => array());
  2178. }
  2179. $fOrder = (float) $oSnippet->GetChildText('rank', 0);
  2180. $sContent = $oSnippet->GetChildText('content', '');
  2181. if ($fOrder < 0)
  2182. {
  2183. $this->aSnippets[$sModuleId]['before'][] = array(
  2184. 'rank' => $fOrder,
  2185. 'content' => $sContent,
  2186. 'snippet_id' => $sSnippetId,
  2187. );
  2188. }
  2189. else
  2190. {
  2191. $this->aSnippets[$sModuleId]['after'][] = array(
  2192. 'rank' => $fOrder,
  2193. 'content' => $sContent,
  2194. 'snippet_id' => $sSnippetId,
  2195. );
  2196. }
  2197. }
  2198. foreach($this->aSnippets as $sModuleId => $void)
  2199. {
  2200. uasort($this->aSnippets[$sModuleId]['before'], array(get_class($this), 'SortOnRank'));
  2201. }
  2202. }
  2203. }