compiler.class.inc.php 44 KB

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