compiler.class.inc.php 42 KB

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