compiler.class.inc.php 56 KB

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