compiler.class.inc.php 49 KB

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