compiler.class.inc.php 45 KB

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