compiler.class.inc.php 69 KB

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