compiler.class.inc.php 57 KB

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