compiler.class.inc.php 63 KB

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