compiler.class.inc.php 48 KB

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