compiler.class.inc.php 58 KB

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