compiler.class.inc.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. <?php
  2. // Copyright (C) 2011-2012 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. $aAllClasses = array(); // flat list of classes
  53. // Determine the target modules for the MENUS
  54. //
  55. $aMenuNodes = array();
  56. $aMenusByModule = array();
  57. foreach ($this->oFactory->ListActiveChildNodes('menus', 'menu') as $oMenuNode)
  58. {
  59. $sMenuId = $oMenuNode->getAttribute('id');
  60. $aMenuNodes[$sMenuId] = $oMenuNode;
  61. $sModuleMenu = $oMenuNode->getAttribute('_created_in');
  62. $aMenusByModule[$sModuleMenu][] = $sMenuId;
  63. }
  64. // Determine the target module (exactly one!) for USER RIGHTS
  65. //
  66. $sUserRightsModule = '';
  67. $oUserRightsNode = $this->oFactory->GetNodes('user_rights')->item(0);
  68. if ($oUserRightsNode)
  69. {
  70. $sUserRightsModule = $oUserRightsNode->getAttribute('_created_in');
  71. $this->Log("User Rights module found: $sUserRightsModule");
  72. }
  73. // List root classes
  74. //
  75. $this->aRootClasses = array();
  76. foreach ($this->oFactory->ListRootClasses() as $oClass)
  77. {
  78. $this->Log("Root class (with child classes): ".$oClass->getAttribute('id'));
  79. $this->aRootClasses[$oClass->getAttribute('id')] = $oClass;
  80. }
  81. // Compile, module by module
  82. //
  83. $aModules = $this->oFactory->GetLoadedModules();
  84. foreach($aModules as $foo => $oModule)
  85. {
  86. $sModuleName = $oModule->GetName();
  87. $sModuleVersion = $oModule->GetVersion();
  88. $sModuleRootDir = realpath($oModule->GetRootDir());
  89. $sRelativeDir = basename($sModuleRootDir);
  90. // Push the other module files
  91. SetupUtils::copydir($sModuleRootDir, $sTargetDir.'/'.$sRelativeDir, $bUseSymbolicLinks);
  92. $sCompiledCode = '';
  93. $oClasses = $this->oFactory->ListClasses($sModuleName);
  94. $iClassCount = $oClasses->length;
  95. if ($iClassCount == 0)
  96. {
  97. $this->Log("Found module without classes declared: $sModuleName");
  98. }
  99. else
  100. {
  101. foreach($oClasses as $oClass)
  102. {
  103. $sClass = $oClass->getAttribute("id");
  104. $aAllClasses[] = $sClass;
  105. try
  106. {
  107. $sCompiledCode .= $this->CompileClass($oClass, $sTargetDir, $sRelativeDir, $oP);
  108. }
  109. catch (DOMFormatException $e)
  110. {
  111. throw new Exception("Failed to process class '$sClass', from '$sModuleRootDir': ".$e->getMessage());
  112. }
  113. }
  114. }
  115. if (!array_key_exists($sModuleName, $aMenusByModule))
  116. {
  117. $this->Log("Found module without menus declared: $sModuleName");
  118. }
  119. else
  120. {
  121. $sCompiledCode .=
  122. <<<EOF
  123. //
  124. // Menus
  125. //
  126. global \$__comp_menus__; // ensure that the global variable is indeed global !
  127. EOF;
  128. // Preliminary: determine parent menus not defined within the current module
  129. $aMenusToLoad = array();
  130. $aParentMenus = array();
  131. foreach($aMenusByModule[$sModuleName] as $sMenuId)
  132. {
  133. $oMenuNode = $aMenuNodes[$sMenuId];
  134. if ($sParent = $oMenuNode->GetChildText('parent', null))
  135. {
  136. $aMenusToLoad[] = $sParent;
  137. $aParentMenus[] = $sParent;
  138. }
  139. // Note: the order matters: the parents must be defined BEFORE
  140. $aMenusToLoad[] = $sMenuId;
  141. }
  142. $aMenusToLoad = array_unique($aMenusToLoad);
  143. foreach($aMenusToLoad as $sMenuId)
  144. {
  145. $oMenuNode = $aMenuNodes[$sMenuId];
  146. if ($oMenuNode->getAttribute("xsi:type") == 'MenuGroup')
  147. {
  148. // Note: this algorithm is wrong
  149. // 1 - the module may appear empty in the current module, while children are defined in other modules
  150. // 2 - check recursively that child nodes are not empty themselves
  151. // Future algorithm:
  152. // a- browse the modules and build the menu tree
  153. // b- browse the tree and blacklist empty menus
  154. // c- before compiling, discard if blacklisted
  155. if (!in_array($oMenuNode->getAttribute("id"), $aParentMenus))
  156. {
  157. // Discard empty menu groups
  158. continue;
  159. }
  160. }
  161. try
  162. {
  163. $sCompiledCode .= $this->CompileMenu($oMenuNode, $sTargetDir, $sRelativeDir, $oP);
  164. }
  165. catch (DOMFormatException $e)
  166. {
  167. throw new Exception("Failed to process menu '$sMenuId', from '$sModuleRootDir': ".$e->getMessage());
  168. }
  169. }
  170. }
  171. // User rights
  172. //
  173. if ($sModuleName == $sUserRightsModule)
  174. {
  175. $sCompiledCode .= $this->CompileUserRights($oUserRightsNode);
  176. }
  177. // Create (overwrite if existing) the compiled file
  178. //
  179. if (strlen($sCompiledCode) > 0)
  180. {
  181. // We have compiled something: write the result file
  182. //
  183. $sResultFile = $sTargetDir.'/'.$sRelativeDir.'/model.'.$sModuleName.'.php';
  184. if (is_file($sResultFile))
  185. {
  186. $this->Log("Updating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  187. }
  188. else
  189. {
  190. $sResultDir = dirname($sResultFile);
  191. if (!is_dir($sResultDir))
  192. {
  193. $this->Log("Creating directory $sResultDir");
  194. mkdir($sResultDir, 0777, true);
  195. }
  196. $this->Log("Creating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  197. }
  198. // Compile the module into a single file
  199. //
  200. $sId = $sModuleName;
  201. $sCurrDate = date(DATE_ISO8601);
  202. $sAuthor = 'iTop compiler';
  203. $sLicence = 'http://opensource.org/licenses/AGPL-3.0';
  204. $sFileHeader =
  205. <<<EOF
  206. <?php
  207. //
  208. // File generated by ... on the $sCurrDate
  209. // Please do not edit manually
  210. //
  211. /**
  212. * Classes and menus for $sModuleName (version $sModuleVersion)
  213. *
  214. * @author $sAuthor
  215. * @license $sLicence
  216. */
  217. EOF;
  218. $ret = file_put_contents($sResultFile, $sFileHeader.$sCompiledCode);
  219. if ($ret === false)
  220. {
  221. $iLen = strlen($sFileHeader.$sCompiledCode);
  222. $fFree = @disk_free_space(dirname($sResultFile));
  223. $aErr = error_get_last();
  224. throw new Exception("Failed to write '$sResultFile'. Last error: '{$aErr['message']}', content to write: $iLen bytes, available free space on disk: $fFree.");
  225. }
  226. }
  227. else
  228. {
  229. $this->Log("Compilation of module $sModuleName in version $sModuleVersion produced not code at all. No file written.");
  230. }
  231. } // foreach module
  232. // Compile the dictionaries -out of the modules
  233. //
  234. $sDictDir = $sTargetDir.'/dictionaries';
  235. if (!is_dir($sDictDir))
  236. {
  237. $this->Log("Creating directory $sDictDir");
  238. mkdir($sDictDir, 0777, true);
  239. }
  240. $oDictionaries = $this->oFactory->ListActiveChildNodes('dictionaries', 'dictionary');
  241. foreach($oDictionaries as $oDictionaryNode)
  242. {
  243. $this->CompileDictionary($oDictionaryNode, $sTargetDir);
  244. }
  245. }
  246. /**
  247. * Helper to form a valid ZList from the array built by GetNodeAsArrayOfItems()
  248. */
  249. protected function ArrayOfItemsToZList(&$aItems)
  250. {
  251. $aTransformed = array();
  252. foreach ($aItems as $key => $value)
  253. {
  254. if (is_null($value))
  255. {
  256. $aTransformed[] = $key;
  257. }
  258. else
  259. {
  260. if (is_array($value))
  261. {
  262. $this->ArrayOfItemsToZList($value);
  263. }
  264. $aTransformed[$key] = $value;
  265. }
  266. }
  267. $aItems = $aTransformed;
  268. }
  269. /**
  270. * Helper to format the flags for an attribute, in a given state
  271. * @param object $oAttNode DOM node containing the information to build the flags
  272. * Returns string PHP flags, based on the OPT_ATT_ constants, or empty (meaning 0, can be omitted)
  273. */
  274. protected function FlagsToPHP($oAttNode)
  275. {
  276. static $aNodeAttributeToFlag = array(
  277. 'mandatory' => 'OPT_ATT_MANDATORY',
  278. 'read_only' => 'OPT_ATT_READONLY',
  279. 'must_prompt' => 'OPT_ATT_MUSTPROMPT',
  280. 'must_change' => 'OPT_ATT_MUSTCHANGE',
  281. 'hidden' => 'OPT_ATT_HIDDEN',
  282. );
  283. $aFlags = array();
  284. foreach ($aNodeAttributeToFlag as $sNodeAttribute => $sFlag)
  285. {
  286. $bFlag = ($oAttNode->GetOptionalElement($sNodeAttribute) != null);
  287. if ($bFlag)
  288. {
  289. $aFlags[] = $sFlag;
  290. }
  291. }
  292. $sRes = implode(' | ', $aFlags);
  293. return $sRes;
  294. }
  295. /**
  296. * Helper to format the tracking level for linkset (direct or indirect attributes)
  297. * @param string $sTrackingLevel Value set from within the XML
  298. * Returns string PHP flag
  299. */
  300. protected function TrackingLevelToPHP($sTrackingLevel)
  301. {
  302. static $aXmlToPHP = array(
  303. 'none' => 'LINKSET_TRACKING_NONE',
  304. 'list' => 'LINKSET_TRACKING_LIST',
  305. 'details' => 'LINKSET_TRACKING_DETAILS',
  306. 'all' => 'LINKSET_TRACKING_ALL',
  307. );
  308. if (!array_key_exists($sTrackingLevel, $aXmlToPHP))
  309. {
  310. throw new DOMFormatException("Tracking level: unknown value '$sTrackingLevel'");
  311. }
  312. return $aXmlToPHP[$sTrackingLevel];
  313. }
  314. /**
  315. * Helper to format the edit-mode for direct linkset
  316. * @param string $sEditMode Value set from within the XML
  317. * Returns string PHP flag
  318. */
  319. protected function EditModeToPHP($sEditMode)
  320. {
  321. static $aXmlToPHP = array(
  322. 'none' => 'LINKSET_EDITMODE_NONE',
  323. 'add_only' => 'LINKSET_EDITMODE_ADDONLY',
  324. 'actions' => 'LINKSET_EDITMODE_ACTIONS',
  325. 'in_place' => 'LINKSET_EDITMODE_INPLACE',
  326. );
  327. if (!array_key_exists($sEditMode, $aXmlToPHP))
  328. {
  329. throw new DOMFormatException("Edit mode: unknown value '$sTrackingLevel'");
  330. }
  331. return $aXmlToPHP[$sEditMode];
  332. }
  333. /**
  334. * Format a path (file or url) as an absolute path or relative to the module or the app
  335. */
  336. protected function PathToPHP($sPath, $sModuleRelativeDir, $bIsUrl = false)
  337. {
  338. if ($sPath == '')
  339. {
  340. $sPHP = "''";
  341. }
  342. elseif (substr($sPath, 0, 2) == '$$')
  343. {
  344. // Absolute
  345. $sPHP = self::QuoteForPHP(substr($sPath, 2));
  346. }
  347. elseif (substr($sPath, 0, 1) == '$')
  348. {
  349. // Relative to the application
  350. if ($bIsUrl)
  351. {
  352. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP(substr($sPath, 1));
  353. }
  354. else
  355. {
  356. $sPHP = "APPROOT.".self::QuoteForPHP(substr($sPath, 1));
  357. }
  358. }
  359. else
  360. {
  361. // Relative to the module
  362. if ($bIsUrl)
  363. {
  364. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP($sModuleRelativeDir.''.$sPath);
  365. }
  366. else
  367. {
  368. $sPHP = "dirname(__FILE__).'/$sPath'";
  369. }
  370. }
  371. return $sPHP;
  372. }
  373. protected function GetPropString($oNode, $sTag, $sDefault = null)
  374. {
  375. $val = $oNode->GetChildText($sTag);
  376. if (is_null($val))
  377. {
  378. if (is_null($sDefault))
  379. {
  380. return null;
  381. }
  382. else
  383. {
  384. $val = $sDefault;
  385. }
  386. }
  387. return "'".$val."'";
  388. }
  389. protected function GetPropBoolean($oNode, $sTag, $bDefault = null)
  390. {
  391. $val = $oNode->GetChildText($sTag);
  392. if (is_null($val))
  393. {
  394. if (is_null($bDefault))
  395. {
  396. return null;
  397. }
  398. else
  399. {
  400. return $bDefault ? 'true' : 'false';
  401. }
  402. }
  403. return $val == 'true' ? 'true' : 'false';
  404. }
  405. protected function GetPropNumber($oNode, $sTag, $nDefault = null)
  406. {
  407. $val = $oNode->GetChildText($sTag);
  408. if (is_null($val))
  409. {
  410. if (is_null($nDefault))
  411. {
  412. return null;
  413. }
  414. else
  415. {
  416. $val = $nDefault;
  417. }
  418. }
  419. return (string)$val;
  420. }
  421. /**
  422. * Adds quotes and escape characters
  423. */
  424. protected function QuoteForPHP($sStr, $bSimpleQuotes = false)
  425. {
  426. if ($bSimpleQuotes)
  427. {
  428. $sEscaped = str_replace(array('\\', "'"), array('\\\\', "\\'"), $sStr);
  429. $sRet = "'$sEscaped'";
  430. }
  431. else
  432. {
  433. $sEscaped = str_replace(array('\\', '"', "\n"), array('\\\\', '\\"', '\\n'), $sStr);
  434. $sRet = '"'.$sEscaped.'"';
  435. }
  436. return $sRet;
  437. }
  438. protected function CompileClass($oClass, $sTargetDir, $sModuleRelativeDir, $oP)
  439. {
  440. $sClass = $oClass->getAttribute('id');
  441. $oProperties = $oClass->GetUniqueElement('properties');
  442. // Class caracteristics
  443. //
  444. $aClassParams = array();
  445. $aClassParams['category'] = $this->GetPropString($oProperties, 'category', '');
  446. $aClassParams['key_type'] = "'autoincrement'";
  447. if ($oNaming = $oProperties->GetOptionalElement('naming'))
  448. {
  449. $oNameAttributes = $oNaming->GetUniqueElement('attributes');
  450. $oAttributes = $oNameAttributes->getElementsByTagName('attribute');
  451. $aNameAttCodes = array();
  452. foreach($oAttributes as $oAttribute)
  453. {
  454. $aNameAttCodes[] = $oAttribute->getAttribute('id');
  455. }
  456. if (count($aNameAttCodes) > 1)
  457. {
  458. // New style...
  459. $sNameAttCode = "array('".implode("', '", $aNameAttCodes)."')";
  460. }
  461. elseif (count($aNameAttCodes) == 1)
  462. {
  463. // New style...
  464. $sNameAttCode = "'$aNameAttCodes[0]'";
  465. }
  466. else
  467. {
  468. $sNameAttCode = "''";
  469. }
  470. }
  471. else
  472. {
  473. $sNameAttCode = "''";
  474. }
  475. $aClassParams['name_attcode'] = $sNameAttCode;
  476. $oLifecycle = $oClass->GetOptionalElement('lifecycle');
  477. if ($oLifecycle)
  478. {
  479. $sStateAttCode = $oLifecycle->GetChildText('attribute');
  480. }
  481. else
  482. {
  483. $sStateAttCode = "";
  484. }
  485. $aClassParams['state_attcode'] = "'$sStateAttCode'";
  486. if ($oReconciliation = $oProperties->GetOptionalElement('reconciliation'))
  487. {
  488. $oReconcAttributes = $oReconciliation->getElementsByTagName('attribute');
  489. $aReconcAttCodes = array();
  490. foreach($oReconcAttributes as $oAttribute)
  491. {
  492. $aReconcAttCodes[] = $oAttribute->getAttribute('id');
  493. }
  494. $sReconcKeys = "array('".implode("', '", $aReconcAttCodes)."')";
  495. }
  496. else
  497. {
  498. $sReconcKeys = "array()";
  499. }
  500. $aClassParams['reconc_keys'] = $sReconcKeys;
  501. $aClassParams['db_table'] = $this->GetPropString($oProperties, 'db_table', '');
  502. $aClassParams['db_key_field'] = $this->GetPropString($oProperties, 'db_key_field', 'id');
  503. if (array_key_exists($sClass, $this->aRootClasses))
  504. {
  505. $sDefaultFinalClass = 'finalclass';
  506. }
  507. else
  508. {
  509. $sDefaultFinalClass = '';
  510. }
  511. $aClassParams['db_finalclass_field'] = $this->GetPropString($oProperties, 'db_final_class_field', $sDefaultFinalClass);
  512. if (($sDisplayTemplate = $oProperties->GetChildText('display_template')) && (strlen($sDisplayTemplate) > 0))
  513. {
  514. $sDisplayTemplate = $sModuleRelativeDir.'/'.$sDisplayTemplate;
  515. $aClassParams['display_template'] = "utils::GetAbsoluteUrlModulesRoot().'$sDisplayTemplate'";
  516. }
  517. if (($sIcon = $oProperties->GetChildText('icon')) && (strlen($sIcon) > 0))
  518. {
  519. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  520. $aClassParams['icon'] = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  521. }
  522. else // si <fileref ref="nnn">
  523. {
  524. $oIcon = $oProperties->GetOptionalElement('icon');
  525. if ($oIcon)
  526. {
  527. $oFileRef = $oIcon->GetOptionalElement('fileref');
  528. if ($oFileRef)
  529. {
  530. $iFileId = $oFileRef->getAttribute('ref');
  531. $sXPath = "/itop_design/files/file[@id='$iFileId']";
  532. $oNodes = $this->oFactory->GetNodes($sXPath);
  533. if ($oNodes->length == 0)
  534. {
  535. throw new DOMFormatException('Could not find the file with ref '.$iFileId);
  536. }
  537. $sName = $oNodes->item(0)->GetChildText('name');
  538. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  539. $aPathInfo = pathinfo($sName);
  540. $sFile = 'icon-file'.$iFileId.'.'.$aPathInfo['extension'];
  541. $sFilePath = $sTargetDir.'/'.$sModuleRelativeDir.'/'.$sFile;
  542. file_put_contents($sFilePath, $sData);
  543. if (!file_exists($sFilePath))
  544. {
  545. throw new Exception('Could not write icon file '.$sFilePath);
  546. }
  547. $aClassParams['icon'] = "utils::GetAbsoluteUrlModulesRoot().'$sModuleRelativeDir/$sFile'";
  548. }
  549. }
  550. }
  551. $oOrder = $oProperties->GetOptionalElement('order');
  552. if ($oOrder)
  553. {
  554. $oColumnsNode = $oOrder->GetUniqueElement('columns');
  555. $oColumns = $oColumnsNode->getElementsByTagName('column');
  556. $aSortColumns = array();
  557. foreach($oColumns as $oColumn)
  558. {
  559. $aSortColumns[] = "'".$oColumn->getAttribute('id')."' => ".(($oColumn->getAttribute('ascending') == 'true') ? 'true' : 'false');
  560. }
  561. if (count($aSortColumns) > 0)
  562. {
  563. $aClassParams['order_by_default'] = "array(".implode(", ", $aSortColumns).")";
  564. }
  565. }
  566. // Finalize class params declaration
  567. //
  568. $aClassParamsPHP = array();
  569. foreach($aClassParams as $sKey => $sPHPValue)
  570. {
  571. $aClassParamsPHP[] = " '$sKey' => $sPHPValue,";
  572. }
  573. $sClassParams = implode("\n", $aClassParamsPHP);
  574. // Comment on top of the class declaration
  575. //
  576. $sCodeComment = $oProperties->GetChildText('comment');
  577. // Fields
  578. //
  579. $sAttributes = '';
  580. foreach($this->oFactory->ListFields($oClass) as $oField)
  581. {
  582. // $oField
  583. $sAttCode = $oField->getAttribute('id');
  584. $sAttType = $oField->getAttribute('xsi:type');
  585. $aDependencies = array();
  586. $oDependencies = $oField->GetOptionalElement('dependencies');
  587. if (!is_null($oDependencies))
  588. {
  589. $oDepNodes = $oDependencies->getElementsByTagName('attribute');
  590. foreach($oDepNodes as $oDepAttribute)
  591. {
  592. $aDependencies[] = "'".$oDepAttribute->getAttribute('id')."'";
  593. }
  594. }
  595. $sDependencies = 'array('.implode(', ', $aDependencies).')';
  596. $aParameters = array();
  597. if ($sAttType == 'AttributeLinkedSetIndirect')
  598. {
  599. $aParameters['linked_class'] = $this->GetPropString($oField, 'linked_class', '');
  600. $aParameters['ext_key_to_me'] = $this->GetPropString($oField, 'ext_key_to_me', '');
  601. $aParameters['ext_key_to_remote'] = $this->GetPropString($oField, 'ext_key_to_remote', '');
  602. $aParameters['allowed_values'] = 'null';
  603. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  604. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  605. $aParameters['duplicates'] = $this->GetPropBoolean($oField, 'duplicates', false);
  606. $sTrackingLevel = $oField->GetChildText('tracking_level');
  607. if (!is_null($sTrackingLevel))
  608. {
  609. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sTrackingLevel);
  610. }
  611. $aParameters['depends_on'] = $sDependencies;
  612. }
  613. elseif ($sAttType == 'AttributeLinkedSet')
  614. {
  615. $aParameters['linked_class'] = $this->GetPropString($oField, 'linked_class', '');
  616. $aParameters['ext_key_to_me'] = $this->GetPropString($oField, 'ext_key_to_me', '');
  617. $aParameters['allowed_values'] = 'null';
  618. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  619. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  620. $sTrackingLevel = $oField->GetChildText('tracking_level');
  621. if (!is_null($sTrackingLevel))
  622. {
  623. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sTrackingLevel);
  624. }
  625. $sEditMode = $oField->GetChildText('edit_mode');
  626. if (!is_null($sEditMode))
  627. {
  628. $aParameters['edit_mode'] = $this->EditModeToPHP($sEditMode);
  629. }
  630. $aParameters['depends_on'] = $sDependencies;
  631. }
  632. elseif ($sAttType == 'AttributeExternalKey')
  633. {
  634. $aParameters['targetclass'] = $this->GetPropString($oField, 'target_class', '');
  635. // deprecated: $aParameters['jointype'] = 'null';
  636. if ($sOql = $oField->GetChildText('filter'))
  637. {
  638. $sEscapedOql = self::QuoteForPHP($sOql);
  639. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  640. }
  641. else
  642. {
  643. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  644. }
  645. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  646. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  647. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  648. $aParameters['depends_on'] = $sDependencies;
  649. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  650. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  651. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  652. }
  653. elseif ($sAttType == 'AttributeHierarchicalKey')
  654. {
  655. if ($sOql = $oField->GetChildText('filter'))
  656. {
  657. $sEscapedOql = self::QuoteForPHP($sOql);
  658. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  659. }
  660. else
  661. {
  662. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  663. }
  664. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  665. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  666. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  667. $aParameters['depends_on'] = $sDependencies;
  668. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  669. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  670. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  671. }
  672. elseif ($sAttType == 'AttributeExternalField')
  673. {
  674. $aParameters['allowed_values'] = 'null';
  675. $aParameters['extkey_attcode'] = $this->GetPropString($oField, 'extkey_attcode', '');
  676. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode', '');
  677. }
  678. elseif ($sAttType == 'AttributeURL')
  679. {
  680. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  681. $aParameters['allowed_values'] = 'null';
  682. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  683. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  684. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  685. $aParameters['depends_on'] = $sDependencies;
  686. }
  687. elseif ($sAttType == 'AttributeEnum')
  688. {
  689. $oValues = $oField->GetUniqueElement('values');
  690. $oValueNodes = $oValues->getElementsByTagName('value');
  691. $aValues = array();
  692. foreach($oValueNodes as $oValue)
  693. {
  694. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  695. $aValues[] = $oValue->textContent;
  696. }
  697. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  698. $sValues = '"'.implode(',', $aValues).'"';
  699. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  700. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  701. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  702. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  703. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  704. $aParameters['depends_on'] = $sDependencies;
  705. }
  706. elseif ($sAttType == 'AttributeBlob')
  707. {
  708. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  709. $aParameters['depends_on'] = $sDependencies;
  710. }
  711. elseif ($sAttType == 'AttributeStopWatch')
  712. {
  713. $oStates = $oField->GetUniqueElement('states');
  714. $oStateNodes = $oStates->getElementsByTagName('state');
  715. $aStates = array();
  716. foreach($oStateNodes as $oState)
  717. {
  718. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  719. }
  720. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  721. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  722. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', 'DefaultWorkingTimeComputer'); // Optional, defaults to 24x7
  723. $oThresholds = $oField->GetUniqueElement('thresholds');
  724. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  725. $aThresholds = array();
  726. foreach($oThresholdNodes as $oThreshold)
  727. {
  728. $iPercent = $this->GetPropNumber($oThreshold, 'percent');
  729. $oActions = $oThreshold->GetUniqueElement('actions');
  730. $oActionNodes = $oActions->getElementsByTagName('action');
  731. $aActions = array();
  732. foreach($oActionNodes as $oAction)
  733. {
  734. $oParams = $oAction->GetOptionalElement('params');
  735. $aActionParams = array();
  736. if ($oParams)
  737. {
  738. $oParamNodes = $oParams->getElementsByTagName('param');
  739. foreach($oParamNodes as $oParam)
  740. {
  741. $aActionParams[] = self::QuoteForPHP($oParam->textContent);
  742. }
  743. }
  744. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  745. $sVerb = $this->GetPropString($oAction, 'verb');
  746. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  747. }
  748. $sActions = 'array('.implode(', ', $aActions).')';
  749. $aThresholds[] = $iPercent." => array('percent' => $iPercent, 'actions' => $sActions)";
  750. }
  751. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  752. }
  753. elseif ($sAttType == 'AttributeSubItem')
  754. {
  755. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode');
  756. $aParameters['item_code'] = $this->GetPropString($oField, 'item_code');
  757. }
  758. else
  759. {
  760. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  761. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  762. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  763. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  764. $aParameters['depends_on'] = $sDependencies;
  765. }
  766. // Optional parameters (more for historical reasons)
  767. // Added if present...
  768. //
  769. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  770. $aParameters['width'] = $this->GetPropNumber($oField, 'width');
  771. $aParameters['height'] = $this->GetPropNumber($oField, 'height');
  772. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  773. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  774. $aParams = array();
  775. foreach($aParameters as $sKey => $sValue)
  776. {
  777. if (!is_null($sValue))
  778. {
  779. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  780. }
  781. }
  782. $sParams = implode(', ', $aParams);
  783. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  784. }
  785. // Lifecycle
  786. //
  787. $sLifecycle = '';
  788. if ($oLifecycle)
  789. {
  790. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  791. $sLifecycle .= "\t\t//\n";
  792. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  793. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  794. {
  795. $sStimulus = $oStimulus->getAttribute('id');
  796. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  797. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  798. }
  799. $oStates = $oLifecycle->GetUniqueElement('states');
  800. foreach ($oStates->getElementsByTagName('state') as $oState)
  801. {
  802. $sState = $oState->getAttribute('id');
  803. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  804. if ($oInitialStatePath)
  805. {
  806. $aInitialStatePath = array();
  807. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  808. {
  809. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  810. }
  811. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  812. }
  813. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  814. $sLifecycle .= " \"".$sState."\",\n";
  815. $sLifecycle .= " array(\n";
  816. $sLifecycle .= " \"attribute_inherit\" => '',\n";
  817. $sLifecycle .= " \"attribute_list\" => array(\n";
  818. $oFlags = $oState->GetUniqueElement('flags');
  819. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  820. {
  821. $sFlags = $this->FlagsToPHP($oAttributeNode);
  822. if (strlen($sFlags) > 0)
  823. {
  824. $sAttCode = $oAttributeNode->GetAttribute('id');
  825. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  826. }
  827. }
  828. $sLifecycle .= " ),\n";
  829. if (!is_null($oInitialStatePath))
  830. {
  831. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  832. }
  833. $sLifecycle .= " )\n";
  834. $sLifecycle .= " );\n";
  835. $oTransitions = $oState->GetUniqueElement('transitions');
  836. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  837. {
  838. $sStimulus = $oTransition->GetChildText('stimulus');
  839. $sTargetState = $oTransition->GetChildText('target');
  840. $oActions = $oTransition->GetUniqueElement('actions');
  841. $aVerbs = array();
  842. foreach ($oActions->getElementsByTagName('action') as $oAction)
  843. {
  844. $sVerb = $oAction->GetChildText('verb');
  845. $aVerbs[] = "'$sVerb'";
  846. }
  847. $sActions = implode(', ', $aVerbs);
  848. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  849. }
  850. }
  851. }
  852. // ZLists
  853. //
  854. $aListRef = array(
  855. 'details' => 'details',
  856. 'standard_search' => 'search',
  857. 'list' => 'list'
  858. );
  859. $oPresentation = $oClass->GetUniqueElement('presentation');
  860. $sZlists = '';
  861. foreach ($aListRef as $sListCode => $sListTag)
  862. {
  863. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  864. if ($oListNode)
  865. {
  866. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  867. $this->ArrayOfItemsToZList($aAttributes);
  868. $sZAttributes = var_export($aAttributes, true);
  869. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  870. }
  871. }
  872. // Methods
  873. $sMethods = "";
  874. $oMethods = $oClass->GetUniqueElement('methods');
  875. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  876. {
  877. $sMethodCode = $oMethod->GetChildText('code');
  878. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  879. {
  880. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  881. }
  882. else
  883. {
  884. $sMethods .= "\n\n".$sMethodCode."\n";
  885. }
  886. }
  887. // Let's make the whole class declaration
  888. //
  889. $sPHP = "\n\n$sCodeComment\n";
  890. $sParentClass = $oClass->GetChildText('php_parent');
  891. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  892. if ($oPhpParent)
  893. {
  894. $sParentClass = $oPhpParent->GetChildText('name', '');
  895. if ($sParentClass == '')
  896. {
  897. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sRelativeDir': missing required tag 'name' under 'php_parent'.");
  898. }
  899. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  900. if ($sIncludeFile != '')
  901. {
  902. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  903. }
  904. //TODO fix this !!!
  905. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  906. // if (!file_exists($sFullPath))
  907. // {
  908. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  909. // }
  910. }
  911. else
  912. {
  913. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  914. }
  915. if ($oProperties->GetChildText('abstract') == 'true')
  916. {
  917. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  918. }
  919. else
  920. {
  921. $sPHP .= 'class '.$oClass->getAttribute('id');
  922. }
  923. $sPHP .= " extends $sParentClass\n";
  924. $sPHP .=
  925. <<<EOF
  926. {
  927. public static function Init()
  928. {
  929. \$aParams = array
  930. (
  931. $sClassParams
  932. );
  933. MetaModel::Init_Params(\$aParams);
  934. MetaModel::Init_InheritAttributes();
  935. $sAttributes
  936. $sLifecycle
  937. $sZlists
  938. }
  939. $sMethods
  940. }
  941. EOF;
  942. return $sPHP;
  943. }// function CompileClass()
  944. protected function CompileMenu($oMenu, $sTargetDir, $sModuleRelativeDir, $oP)
  945. {
  946. $sMenuId = $oMenu->getAttribute("id");
  947. $sMenuClass = $oMenu->getAttribute("xsi:type");
  948. $sParent = $oMenu->GetChildText('parent', null);
  949. if ($sParent)
  950. {
  951. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  952. }
  953. else
  954. {
  955. $sParentSpec = '-1';
  956. }
  957. $fRank = $oMenu->GetChildText('rank');
  958. switch($sMenuClass)
  959. {
  960. case 'WebPageMenuNode':
  961. $sUrl = $oMenu->GetChildText('url');
  962. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  963. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  964. break;
  965. case 'DashboardMenuNode':
  966. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  967. if ($sTemplateFile != '')
  968. {
  969. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  970. }
  971. else
  972. {
  973. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  974. if ($oDashboardDefinition == null)
  975. {
  976. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  977. }
  978. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  979. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  980. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  981. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  982. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  983. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  984. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  985. $oXMLDoc->appendChild($oRootNode);
  986. foreach($oDashboardDefinition->childNodes as $oNode)
  987. {
  988. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  989. $oRootNode->appendChild($oDefNode);
  990. }
  991. $oXMLDoc->save($sTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  992. }
  993. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  994. break;
  995. case 'TemplateMenuNode':
  996. $sTemplateFile = $oMenu->GetChildText('template_file');
  997. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  998. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  999. break;
  1000. case 'ShortcutContainerMenuNode':
  1001. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1002. break;
  1003. case 'OQLMenuNode':
  1004. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1005. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1006. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch);";
  1007. break;
  1008. case 'NewObjectMenuNode':
  1009. $sClass = $oMenu->GetChildText('class');
  1010. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1011. break;
  1012. case 'SearchMenuNode':
  1013. $sClass = $oMenu->GetChildText('class');
  1014. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1015. break;
  1016. case 'MenuGroup':
  1017. default:
  1018. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1019. {
  1020. $sEnableAction = $oMenu->GetChildText('enable_action');
  1021. $sEnablePermission = $oMenu->GetChildText('enable_permission');
  1022. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1023. if (strlen($sEnableStimulus) > 0)
  1024. {
  1025. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1026. }
  1027. else
  1028. {
  1029. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1030. }
  1031. }
  1032. else
  1033. {
  1034. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1035. }
  1036. }
  1037. $sIndent = '';
  1038. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1039. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1040. {
  1041. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1042. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1043. }
  1044. $sAdminOnly = $oMenu->GetChildText('enable_admin_only');
  1045. if ($sAdminOnly && ($sAdminOnly == '1'))
  1046. {
  1047. $sPHP = $sIndent."if (UserRights::IsAdministrator())\n";
  1048. $sPHP .= $sIndent."{\n";
  1049. foreach($aPHPMenu as $sPHPLine)
  1050. {
  1051. $sPHP .= $sIndent." $sPHPLine\n";
  1052. }
  1053. $sPHP .= $sIndent."}\n";
  1054. }
  1055. else
  1056. {
  1057. $sPHP = '';
  1058. foreach($aPHPMenu as $sPHPLine)
  1059. {
  1060. $sPHP .= $sIndent.$sPHPLine."\n";
  1061. }
  1062. }
  1063. return $sPHP;
  1064. } // function CompileMenu
  1065. /**
  1066. * Helper to compute the grant, taking any existing grant into account
  1067. */
  1068. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1069. {
  1070. if (isset($aGrants[$sKey]))
  1071. {
  1072. if (!$bGrant)
  1073. {
  1074. $aGrants[$sKey] = false;
  1075. }
  1076. }
  1077. else
  1078. {
  1079. $aGrants[$sKey] = $bGrant;
  1080. }
  1081. }
  1082. protected function CompileUserRights($oUserRightsNode)
  1083. {
  1084. static $aActionsInShort = array(
  1085. 'read' => 'r',
  1086. 'bulk read' => 'br',
  1087. 'write' => 'w',
  1088. 'bulk write' => 'bw',
  1089. 'delete' => 'd',
  1090. 'bulk delete' => 'bd',
  1091. );
  1092. // Preliminary : create an index so that links will be taken into account implicitely
  1093. $aLinkToClasses = array();
  1094. $oClasses = $this->oFactory->ListAllClasses();
  1095. foreach($oClasses as $oClass)
  1096. {
  1097. $bIsLink = false;
  1098. $oProperties = $oClass->GetOptionalElement('properties');
  1099. if ($oProperties)
  1100. {
  1101. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1102. }
  1103. if ($bIsLink)
  1104. {
  1105. foreach($this->oFactory->ListFields($oClass) as $oField)
  1106. {
  1107. $sAttType = $oField->getAttribute('xsi:type');
  1108. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1109. {
  1110. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1111. if ($sOnTargetDel == 'DEL_AUTO')
  1112. {
  1113. $sTargetClass = $oField->GetChildText('target_class');
  1114. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. // Groups
  1121. //
  1122. $aGroupClasses = array();
  1123. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1124. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1125. {
  1126. $sGroupId = $oGroup->getAttribute("id");
  1127. $aClasses = array();
  1128. $oClasses = $oGroup->GetUniqueElement('classes');
  1129. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1130. {
  1131. $sClass = $oClass->getAttribute("id");
  1132. $aClasses[] = $sClass;
  1133. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1134. //if ($bSubclasses)...
  1135. }
  1136. $aGroupClasses[$sGroupId] = $aClasses;
  1137. }
  1138. // Profiles and grants
  1139. //
  1140. $aProfiles = array();
  1141. // Hardcode the administrator profile
  1142. $aProfiles[1] = array(
  1143. 'name' => 'Administrator',
  1144. 'description' => 'Has the rights on everything (bypassing any control)'
  1145. );
  1146. $aGrants = array();
  1147. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1148. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1149. {
  1150. $iProfile = $oProfile->getAttribute("id");
  1151. $sName = $oProfile->GetChildText('name');
  1152. $sDescription = $oProfile->GetChildText('description');
  1153. $oGroups = $oProfile->GetUniqueElement('groups');
  1154. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1155. {
  1156. $sGroupId = $oGroup->getAttribute("id");
  1157. $aActions = array();
  1158. $oActions = $oGroup->GetUniqueElement('actions');
  1159. foreach($oActions->getElementsByTagName('action') as $oAction)
  1160. {
  1161. $sAction = $oAction->getAttribute("id");
  1162. $sType = $oAction->getAttribute("xsi:type");
  1163. $sGrant = $oAction->GetText();
  1164. $bGrant = ($sGrant == 'allow');
  1165. if ($sGroupId == '*')
  1166. {
  1167. $aGrantClasses = array('*');
  1168. }
  1169. else
  1170. {
  1171. $aGrantClasses = $aGroupClasses[$sGroupId];
  1172. }
  1173. foreach ($aGrantClasses as $sClass)
  1174. {
  1175. if ($sType == 'stimulus')
  1176. {
  1177. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sAction, $bGrant);
  1178. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sAction, $bGrant); // subclasses inherit this grant
  1179. }
  1180. else
  1181. {
  1182. $sAction = $aActionsInShort[$sType];
  1183. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sAction, $bGrant);
  1184. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sAction, $bGrant); // subclasses inherit this grant
  1185. }
  1186. }
  1187. }
  1188. }
  1189. $aProfiles[$iProfile] = array(
  1190. 'name' => $sName,
  1191. 'description' => $sDescription
  1192. );
  1193. }
  1194. $sProfiles = var_export($aProfiles, true);
  1195. $sGrants = var_export($aGrants, true);
  1196. $sLinkToClasses = var_export($aLinkToClasses, true);
  1197. $sPHP =
  1198. <<<EOF
  1199. //
  1200. // List of constant profiles
  1201. // - used by the class URP_Profiles at setup (create/update/delete records)
  1202. // - used by the addon UserRightsProfile to determine user rights
  1203. //
  1204. class ProfilesConfig
  1205. {
  1206. protected static \$aPROFILES = $sProfiles;
  1207. protected static \$aGRANTS = $sGrants;
  1208. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1209. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1210. {
  1211. // Search for a grant, starting from the most explicit declaration,
  1212. // then searching for less and less explicit declaration
  1213. // 1 - The class itself
  1214. //
  1215. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1216. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1217. {
  1218. return self::\$aGRANTS[\$sGrantKey];
  1219. }
  1220. // 2 - The parent classes, up to the root class
  1221. //
  1222. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1223. {
  1224. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1225. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1226. {
  1227. return self::\$aGRANTS[\$sGrantKey];
  1228. }
  1229. }
  1230. // 3 - The related classes (if the current is an N-N link with AUTO_DEL)
  1231. //
  1232. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1233. {
  1234. // Get the grant for the remote classes. The resulting grant is:
  1235. // - One YES => YES
  1236. // - 100% undefined => undefined
  1237. // - otherwise => NO
  1238. //
  1239. // Having write allowed on the remote class implies write + delete on the N-N link class
  1240. if (\$sAction == 'd')
  1241. {
  1242. \$sRemoteAction = 'w';
  1243. }
  1244. elseif (\$sAction == 'bd')
  1245. {
  1246. \$sRemoteAction = 'bw';
  1247. }
  1248. else
  1249. {
  1250. \$sRemoteAction = \$sAction;
  1251. }
  1252. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1253. {
  1254. \$bUndefined = true;
  1255. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1256. if (\$bGrant === true)
  1257. {
  1258. return true;
  1259. }
  1260. if (\$bGrant === false)
  1261. {
  1262. \$bUndefined = false;
  1263. }
  1264. }
  1265. if (!\$bUndefined)
  1266. {
  1267. return false;
  1268. }
  1269. }
  1270. // 4 - All
  1271. //
  1272. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1273. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1274. {
  1275. return self::\$aGRANTS[\$sGrantKey];
  1276. }
  1277. // Still undefined for this class
  1278. return null;
  1279. }
  1280. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1281. {
  1282. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1283. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1284. {
  1285. return self::\$aGRANTS[\$sGrantKey];
  1286. }
  1287. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1288. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1289. {
  1290. return self::\$aGRANTS[\$sGrantKey];
  1291. }
  1292. return null;
  1293. }
  1294. // returns an array of id => array of column => php value(so-called "real value")
  1295. public static function GetProfilesValues()
  1296. {
  1297. return self::\$aPROFILES;
  1298. }
  1299. }
  1300. EOF;
  1301. return $sPHP;
  1302. } // function CompileUserRights
  1303. protected function CompileDictionary($oDictionaryNode, $sTargetDir)
  1304. {
  1305. $sLang = $oDictionaryNode->getAttribute('id');
  1306. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1307. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1308. $aEntriesPHP = array();
  1309. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1310. foreach($oEntries->getElementsByTagName('entry') as $oEntry)
  1311. {
  1312. $sStringCode = $oEntry->getAttribute('id');
  1313. $sValue = $oEntry->GetText();
  1314. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP($sValue, true).",";
  1315. }
  1316. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1317. $sEscEnglishLanguageDesc = self::QuoteForPHP($sEnglishLanguageDesc);
  1318. $sEscLocalizedLanguageDesc = self::QuoteForPHP($sLocalizedLanguageDesc);
  1319. $sPHPDict =
  1320. <<<EOF
  1321. <?php
  1322. //
  1323. // Dictionary built by the compiler for the language "$sLang"
  1324. //
  1325. Dict::Add('$sLang', $sEscEnglishLanguageDesc, $sEscLocalizedLanguageDesc, array(
  1326. $sEntriesPHP
  1327. ));
  1328. EOF;
  1329. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1330. $sDictFile = $sTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1331. file_put_contents($sDictFile, $sPHPDict);
  1332. }
  1333. }
  1334. ?>