compiler.class.inc.php 73 KB

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