compiler.class.inc.php 61 KB

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