compiler.class.inc.php 48 KB

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