compiler.class.inc.php 48 KB

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