compiler.class.inc.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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['allowed_values'] = 'null';
  656. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  657. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  658. $sEditMode = $oField->GetChildText('edit_mode');
  659. if (!is_null($sEditMode))
  660. {
  661. $aParameters['edit_mode'] = $this->EditModeToPHP($sEditMode);
  662. }
  663. $aParameters['depends_on'] = $sDependencies;
  664. }
  665. elseif ($sAttType == 'AttributeExternalKey')
  666. {
  667. $aParameters['targetclass'] = $this->GetPropString($oField, 'target_class', '');
  668. // deprecated: $aParameters['jointype'] = 'null';
  669. if ($sOql = $oField->GetChildText('filter'))
  670. {
  671. $sEscapedOql = self::QuoteForPHP($sOql);
  672. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  673. }
  674. else
  675. {
  676. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  677. }
  678. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  679. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  680. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  681. $aParameters['depends_on'] = $sDependencies;
  682. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  683. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  684. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  685. }
  686. elseif ($sAttType == 'AttributeHierarchicalKey')
  687. {
  688. if ($sOql = $oField->GetChildText('filter'))
  689. {
  690. $sEscapedOql = self::QuoteForPHP($sOql);
  691. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  692. }
  693. else
  694. {
  695. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  696. }
  697. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  698. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  699. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  700. $aParameters['depends_on'] = $sDependencies;
  701. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  702. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  703. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  704. }
  705. elseif ($sAttType == 'AttributeExternalField')
  706. {
  707. $aParameters['allowed_values'] = 'null';
  708. $aParameters['extkey_attcode'] = $this->GetPropString($oField, 'extkey_attcode', '');
  709. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode', '');
  710. }
  711. elseif ($sAttType == 'AttributeURL')
  712. {
  713. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  714. $aParameters['allowed_values'] = 'null';
  715. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  716. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  717. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  718. $aParameters['depends_on'] = $sDependencies;
  719. }
  720. elseif ($sAttType == 'AttributeEnum')
  721. {
  722. $oValues = $oField->GetUniqueElement('values');
  723. $oValueNodes = $oValues->getElementsByTagName('value');
  724. $aValues = array();
  725. foreach($oValueNodes as $oValue)
  726. {
  727. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  728. $aValues[] = $oValue->textContent;
  729. }
  730. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  731. $sValues = '"'.implode(',', $aValues).'"';
  732. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  733. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  734. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  735. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  736. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  737. $aParameters['depends_on'] = $sDependencies;
  738. }
  739. elseif ($sAttType == 'AttributeBlob')
  740. {
  741. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  742. $aParameters['depends_on'] = $sDependencies;
  743. }
  744. elseif ($sAttType == 'AttributeStopWatch')
  745. {
  746. $oStates = $oField->GetUniqueElement('states');
  747. $oStateNodes = $oStates->getElementsByTagName('state');
  748. $aStates = array();
  749. foreach($oStateNodes as $oState)
  750. {
  751. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  752. }
  753. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  754. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  755. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', ''); // Blank (different than DefaultWorkingTimeComputer)
  756. $oThresholds = $oField->GetUniqueElement('thresholds');
  757. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  758. $aThresholds = array();
  759. foreach($oThresholdNodes as $oThreshold)
  760. {
  761. $iPercent = $this->GetPropNumber($oThreshold, 'percent');
  762. $oActions = $oThreshold->GetUniqueElement('actions');
  763. $oActionNodes = $oActions->getElementsByTagName('action');
  764. $aActions = array();
  765. foreach($oActionNodes as $oAction)
  766. {
  767. $oParams = $oAction->GetOptionalElement('params');
  768. $aActionParams = array();
  769. if ($oParams)
  770. {
  771. $oParamNodes = $oParams->getElementsByTagName('param');
  772. foreach($oParamNodes as $oParam)
  773. {
  774. $aActionParams[] = self::QuoteForPHP($oParam->textContent);
  775. }
  776. }
  777. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  778. $sVerb = $this->GetPropString($oAction, 'verb');
  779. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  780. }
  781. $sActions = 'array('.implode(', ', $aActions).')';
  782. $aThresholds[] = $iPercent." => array('percent' => $iPercent, 'actions' => $sActions)";
  783. }
  784. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  785. }
  786. elseif ($sAttType == 'AttributeSubItem')
  787. {
  788. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode');
  789. $aParameters['item_code'] = $this->GetPropString($oField, 'item_code');
  790. }
  791. else
  792. {
  793. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  794. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  795. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  796. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  797. $aParameters['depends_on'] = $sDependencies;
  798. }
  799. // Optional parameters (more for historical reasons)
  800. // Added if present...
  801. //
  802. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  803. $aParameters['width'] = $this->GetPropNumber($oField, 'width');
  804. $aParameters['height'] = $this->GetPropNumber($oField, 'height');
  805. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  806. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  807. $aParameters['always_load_in_tables'] = $this->GetPropBoolean($oField, 'always_load_in_tables', false);
  808. $sTrackingLevel = $oField->GetChildText('tracking_level');
  809. if (!is_null($sTrackingLevel))
  810. {
  811. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sAttType, $sTrackingLevel);
  812. }
  813. $aParams = array();
  814. foreach($aParameters as $sKey => $sValue)
  815. {
  816. if (!is_null($sValue))
  817. {
  818. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  819. }
  820. }
  821. $sParams = implode(', ', $aParams);
  822. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  823. }
  824. // Lifecycle
  825. //
  826. $sLifecycle = '';
  827. if ($oLifecycle)
  828. {
  829. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  830. $sLifecycle .= "\t\t//\n";
  831. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  832. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  833. {
  834. $sStimulus = $oStimulus->getAttribute('id');
  835. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  836. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  837. }
  838. $oStates = $oLifecycle->GetUniqueElement('states');
  839. foreach ($oStates->getElementsByTagName('state') as $oState)
  840. {
  841. $sState = $oState->getAttribute('id');
  842. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  843. if ($oInitialStatePath)
  844. {
  845. $aInitialStatePath = array();
  846. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  847. {
  848. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  849. }
  850. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  851. }
  852. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  853. $sLifecycle .= " \"".$sState."\",\n";
  854. $sLifecycle .= " array(\n";
  855. $sLifecycle .= " \"attribute_inherit\" => '',\n";
  856. $sLifecycle .= " \"attribute_list\" => array(\n";
  857. $oFlags = $oState->GetUniqueElement('flags');
  858. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  859. {
  860. $sFlags = $this->FlagsToPHP($oAttributeNode);
  861. if (strlen($sFlags) > 0)
  862. {
  863. $sAttCode = $oAttributeNode->GetAttribute('id');
  864. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  865. }
  866. }
  867. $sLifecycle .= " ),\n";
  868. if (!is_null($oInitialStatePath))
  869. {
  870. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  871. }
  872. $sLifecycle .= " )\n";
  873. $sLifecycle .= " );\n";
  874. $oTransitions = $oState->GetUniqueElement('transitions');
  875. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  876. {
  877. $sStimulus = $oTransition->GetChildText('stimulus');
  878. $sTargetState = $oTransition->GetChildText('target');
  879. $oActions = $oTransition->GetUniqueElement('actions');
  880. $aVerbs = array();
  881. foreach ($oActions->getElementsByTagName('action') as $oAction)
  882. {
  883. $sVerb = $oAction->GetChildText('verb');
  884. $aVerbs[] = "'$sVerb'";
  885. }
  886. $sActions = implode(', ', $aVerbs);
  887. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  888. }
  889. }
  890. }
  891. // ZLists
  892. //
  893. $aListRef = array(
  894. 'details' => 'details',
  895. 'standard_search' => 'search',
  896. 'list' => 'list'
  897. );
  898. $oPresentation = $oClass->GetUniqueElement('presentation');
  899. $sZlists = '';
  900. foreach ($aListRef as $sListCode => $sListTag)
  901. {
  902. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  903. if ($oListNode)
  904. {
  905. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  906. $this->ArrayOfItemsToZList($aAttributes);
  907. $sZAttributes = var_export($aAttributes, true);
  908. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  909. }
  910. }
  911. // Methods
  912. $sMethods = "";
  913. $oMethods = $oClass->GetUniqueElement('methods');
  914. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  915. {
  916. $sMethodCode = $oMethod->GetChildText('code');
  917. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  918. {
  919. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  920. }
  921. else
  922. {
  923. $sMethods .= "\n\n".$sMethodCode."\n";
  924. }
  925. }
  926. // Let's make the whole class declaration
  927. //
  928. $sPHP = "\n\n$sCodeComment\n";
  929. $sParentClass = $oClass->GetChildText('php_parent');
  930. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  931. if ($oPhpParent)
  932. {
  933. $sParentClass = $oPhpParent->GetChildText('name', '');
  934. if ($sParentClass == '')
  935. {
  936. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sRelativeDir': missing required tag 'name' under 'php_parent'.");
  937. }
  938. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  939. if ($sIncludeFile != '')
  940. {
  941. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  942. }
  943. //TODO fix this !!!
  944. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  945. // if (!file_exists($sFullPath))
  946. // {
  947. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  948. // }
  949. }
  950. else
  951. {
  952. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  953. }
  954. if ($oProperties->GetChildText('abstract') == 'true')
  955. {
  956. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  957. }
  958. else
  959. {
  960. $sPHP .= 'class '.$oClass->getAttribute('id');
  961. }
  962. $sPHP .= " extends $sParentClass\n";
  963. $sPHP .=
  964. <<<EOF
  965. {
  966. public static function Init()
  967. {
  968. \$aParams = array
  969. (
  970. $sClassParams
  971. );
  972. MetaModel::Init_Params(\$aParams);
  973. MetaModel::Init_InheritAttributes();
  974. $sAttributes
  975. $sLifecycle
  976. $sZlists
  977. }
  978. $sMethods
  979. }
  980. EOF;
  981. return $sPHP;
  982. }// function CompileClass()
  983. protected function CompileMenu($oMenu, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  984. {
  985. $this->CompileFiles($oMenu, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, $sModuleRelativeDir);
  986. $sMenuId = $oMenu->getAttribute("id");
  987. $sMenuClass = $oMenu->getAttribute("xsi:type");
  988. $sParent = $oMenu->GetChildText('parent', null);
  989. if ($sParent)
  990. {
  991. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  992. }
  993. else
  994. {
  995. $sParentSpec = '-1';
  996. }
  997. $fRank = (float) $oMenu->GetChildText('rank');
  998. switch($sMenuClass)
  999. {
  1000. case 'WebPageMenuNode':
  1001. $sUrl = $oMenu->GetChildText('url');
  1002. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  1003. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  1004. break;
  1005. case 'DashboardMenuNode':
  1006. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  1007. if ($sTemplateFile != '')
  1008. {
  1009. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1010. }
  1011. else
  1012. {
  1013. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  1014. if ($oDashboardDefinition == null)
  1015. {
  1016. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  1017. }
  1018. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  1019. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  1020. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  1021. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1022. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1023. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  1024. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1025. $oXMLDoc->appendChild($oRootNode);
  1026. foreach($oDashboardDefinition->childNodes as $oNode)
  1027. {
  1028. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  1029. $oRootNode->appendChild($oDefNode);
  1030. }
  1031. $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  1032. }
  1033. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1034. break;
  1035. case 'ShortcutContainerMenuNode':
  1036. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1037. break;
  1038. case 'OQLMenuNode':
  1039. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1040. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1041. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch);";
  1042. break;
  1043. case 'NewObjectMenuNode':
  1044. $sClass = $oMenu->GetChildText('class');
  1045. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1046. break;
  1047. case 'SearchMenuNode':
  1048. $sClass = $oMenu->GetChildText('class');
  1049. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1050. break;
  1051. case 'TemplateMenuNode':
  1052. $sTemplateFile = $oMenu->GetChildText('template_file');
  1053. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1054. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1055. {
  1056. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1057. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1058. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1059. if ($sEnableStimulus != null)
  1060. {
  1061. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1062. }
  1063. else
  1064. {
  1065. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1066. }
  1067. }
  1068. else
  1069. {
  1070. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1071. }
  1072. break;
  1073. case 'MenuGroup':
  1074. default:
  1075. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1076. {
  1077. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1078. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1079. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1080. if ($sEnableStimulus != null)
  1081. {
  1082. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1083. }
  1084. else
  1085. {
  1086. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1087. }
  1088. }
  1089. else
  1090. {
  1091. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1092. }
  1093. }
  1094. $sIndent = '';
  1095. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1096. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1097. {
  1098. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1099. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1100. }
  1101. $sAdminOnly = $oMenu->GetChildText('enable_admin_only');
  1102. if ($sAdminOnly && ($sAdminOnly == '1'))
  1103. {
  1104. $sPHP = $sIndent."if (UserRights::IsAdministrator())\n";
  1105. $sPHP .= $sIndent."{\n";
  1106. foreach($aPHPMenu as $sPHPLine)
  1107. {
  1108. $sPHP .= $sIndent." $sPHPLine\n";
  1109. }
  1110. $sPHP .= $sIndent."}\n";
  1111. }
  1112. else
  1113. {
  1114. $sPHP = '';
  1115. foreach($aPHPMenu as $sPHPLine)
  1116. {
  1117. $sPHP .= $sIndent.$sPHPLine."\n";
  1118. }
  1119. }
  1120. return $sPHP;
  1121. } // function CompileMenu
  1122. /**
  1123. * Helper to compute the grant, taking any existing grant into account
  1124. */
  1125. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1126. {
  1127. if (isset($aGrants[$sKey]))
  1128. {
  1129. if (!$bGrant)
  1130. {
  1131. $aGrants[$sKey] = false;
  1132. }
  1133. }
  1134. else
  1135. {
  1136. $aGrants[$sKey] = $bGrant;
  1137. }
  1138. }
  1139. protected function CompileUserRights($oUserRightsNode)
  1140. {
  1141. static $aActionsInShort = array(
  1142. 'read' => 'r',
  1143. 'bulk read' => 'br',
  1144. 'write' => 'w',
  1145. 'bulk write' => 'bw',
  1146. 'delete' => 'd',
  1147. 'bulk delete' => 'bd',
  1148. );
  1149. // Preliminary : create an index so that links will be taken into account implicitely
  1150. $aLinkToClasses = array();
  1151. $oClasses = $this->oFactory->ListAllClasses();
  1152. foreach($oClasses as $oClass)
  1153. {
  1154. $bIsLink = false;
  1155. $oProperties = $oClass->GetOptionalElement('properties');
  1156. if ($oProperties)
  1157. {
  1158. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1159. }
  1160. if ($bIsLink)
  1161. {
  1162. foreach($this->oFactory->ListFields($oClass) as $oField)
  1163. {
  1164. $sAttType = $oField->getAttribute('xsi:type');
  1165. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1166. {
  1167. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1168. if ($sOnTargetDel == 'DEL_AUTO')
  1169. {
  1170. $sTargetClass = $oField->GetChildText('target_class');
  1171. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. // Groups
  1178. //
  1179. $aGroupClasses = array();
  1180. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1181. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1182. {
  1183. $sGroupId = $oGroup->getAttribute("id");
  1184. $aClasses = array();
  1185. $oClasses = $oGroup->GetUniqueElement('classes');
  1186. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1187. {
  1188. $sClass = $oClass->getAttribute("id");
  1189. $aClasses[] = $sClass;
  1190. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1191. //if ($bSubclasses)...
  1192. }
  1193. $aGroupClasses[$sGroupId] = $aClasses;
  1194. }
  1195. // Profiles and grants
  1196. //
  1197. $aProfiles = array();
  1198. // Hardcode the administrator profile
  1199. $aProfiles[1] = array(
  1200. 'name' => 'Administrator',
  1201. 'description' => 'Has the rights on everything (bypassing any control)'
  1202. );
  1203. $aGrants = array();
  1204. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1205. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1206. {
  1207. $iProfile = $oProfile->getAttribute("id");
  1208. $sName = $oProfile->GetChildText('name');
  1209. $sDescription = $oProfile->GetChildText('description');
  1210. $oGroups = $oProfile->GetUniqueElement('groups');
  1211. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1212. {
  1213. $sGroupId = $oGroup->getAttribute("id");
  1214. $aActions = array();
  1215. $oActions = $oGroup->GetUniqueElement('actions');
  1216. foreach($oActions->getElementsByTagName('action') as $oAction)
  1217. {
  1218. $sAction = $oAction->getAttribute("id");
  1219. $sType = $oAction->getAttribute("xsi:type");
  1220. $sGrant = $oAction->GetText();
  1221. $bGrant = ($sGrant == 'allow');
  1222. if ($sGroupId == '*')
  1223. {
  1224. $aGrantClasses = array('*');
  1225. }
  1226. else
  1227. {
  1228. $aGrantClasses = $aGroupClasses[$sGroupId];
  1229. }
  1230. foreach ($aGrantClasses as $sClass)
  1231. {
  1232. if ($sType == 'stimulus')
  1233. {
  1234. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sAction, $bGrant);
  1235. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sAction, $bGrant); // subclasses inherit this grant
  1236. }
  1237. else
  1238. {
  1239. $sAction = $aActionsInShort[$sType];
  1240. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sAction, $bGrant);
  1241. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sAction, $bGrant); // subclasses inherit this grant
  1242. }
  1243. }
  1244. }
  1245. }
  1246. $aProfiles[$iProfile] = array(
  1247. 'name' => $sName,
  1248. 'description' => $sDescription
  1249. );
  1250. }
  1251. $sProfiles = var_export($aProfiles, true);
  1252. $sGrants = var_export($aGrants, true);
  1253. $sLinkToClasses = var_export($aLinkToClasses, true);
  1254. $sPHP =
  1255. <<<EOF
  1256. //
  1257. // List of constant profiles
  1258. // - used by the class URP_Profiles at setup (create/update/delete records)
  1259. // - used by the addon UserRightsProfile to determine user rights
  1260. //
  1261. class ProfilesConfig
  1262. {
  1263. protected static \$aPROFILES = $sProfiles;
  1264. protected static \$aGRANTS = $sGrants;
  1265. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1266. public static function GetLinkClasses()
  1267. {
  1268. return self::\$aLINKTOCLASSES;
  1269. }
  1270. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1271. {
  1272. // Search for a grant, starting from the most explicit declaration,
  1273. // then searching for less and less explicit declaration
  1274. // 1 - The class itself
  1275. //
  1276. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1277. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1278. {
  1279. return self::\$aGRANTS[\$sGrantKey];
  1280. }
  1281. // 2 - The parent classes, up to the root class
  1282. //
  1283. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1284. {
  1285. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1286. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1287. {
  1288. return self::\$aGRANTS[\$sGrantKey];
  1289. }
  1290. }
  1291. // 3 - The related classes (if the current is an N-N link with AUTO_DEL)
  1292. //
  1293. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1294. {
  1295. // Get the grant for the remote classes. The resulting grant is:
  1296. // - One YES => YES
  1297. // - 100% undefined => undefined
  1298. // - otherwise => NO
  1299. //
  1300. // Having write allowed on the remote class implies write + delete on the N-N link class
  1301. if (\$sAction == 'd')
  1302. {
  1303. \$sRemoteAction = 'w';
  1304. }
  1305. elseif (\$sAction == 'bd')
  1306. {
  1307. \$sRemoteAction = 'bw';
  1308. }
  1309. else
  1310. {
  1311. \$sRemoteAction = \$sAction;
  1312. }
  1313. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1314. {
  1315. \$bUndefined = true;
  1316. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1317. if (\$bGrant === true)
  1318. {
  1319. return true;
  1320. }
  1321. if (\$bGrant === false)
  1322. {
  1323. \$bUndefined = false;
  1324. }
  1325. }
  1326. if (!\$bUndefined)
  1327. {
  1328. return false;
  1329. }
  1330. }
  1331. // 4 - All
  1332. //
  1333. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1334. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1335. {
  1336. return self::\$aGRANTS[\$sGrantKey];
  1337. }
  1338. // Still undefined for this class
  1339. return null;
  1340. }
  1341. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1342. {
  1343. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1344. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1345. {
  1346. return self::\$aGRANTS[\$sGrantKey];
  1347. }
  1348. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1349. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1350. {
  1351. return self::\$aGRANTS[\$sGrantKey];
  1352. }
  1353. return null;
  1354. }
  1355. // returns an array of id => array of column => php value(so-called "real value")
  1356. public static function GetProfilesValues()
  1357. {
  1358. return self::\$aPROFILES;
  1359. }
  1360. }
  1361. EOF;
  1362. return $sPHP;
  1363. } // function CompileUserRights
  1364. protected function CompileDictionary($oDictionaryNode, $sTempTargetDir, $sFinalTargetDir)
  1365. {
  1366. $sLang = $oDictionaryNode->getAttribute('id');
  1367. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1368. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1369. $aEntriesPHP = array();
  1370. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1371. foreach($oEntries->getElementsByTagName('entry') as $oEntry)
  1372. {
  1373. $sStringCode = $oEntry->getAttribute('id');
  1374. $sValue = $oEntry->GetText();
  1375. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP($sValue, true).",";
  1376. }
  1377. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1378. $sEscEnglishLanguageDesc = self::QuoteForPHP($sEnglishLanguageDesc);
  1379. $sEscLocalizedLanguageDesc = self::QuoteForPHP($sLocalizedLanguageDesc);
  1380. $sPHPDict =
  1381. <<<EOF
  1382. <?php
  1383. //
  1384. // Dictionary built by the compiler for the language "$sLang"
  1385. //
  1386. Dict::Add('$sLang', $sEscEnglishLanguageDesc, $sEscLocalizedLanguageDesc, array(
  1387. $sEntriesPHP
  1388. ));
  1389. EOF;
  1390. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1391. $sDictFile = $sTempTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1392. file_put_contents($sDictFile, $sPHPDict);
  1393. }
  1394. // Transform the file references into the corresponding filename (and create the file in the relevant directory)
  1395. //
  1396. protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath)
  1397. {
  1398. $oFileRefs = $oNode->GetNodes(".//fileref");
  1399. foreach ($oFileRefs as $oFileRef)
  1400. {
  1401. $sFileId = $oFileRef->getAttribute('ref');
  1402. if ($sFileId !== '')
  1403. {
  1404. $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id='$sFileId']");
  1405. if ($oNodes->length == 0)
  1406. {
  1407. throw new DOMFormatException('Could not find the file with ref '.$sFileId);
  1408. }
  1409. $sName = $oNodes->item(0)->GetChildText('name');
  1410. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  1411. $aPathInfo = pathinfo($sName);
  1412. $sFile = $sFileId.'.'.$aPathInfo['extension'];
  1413. $sFilePath = $sTempTargetDir.'/images/'.$sFile;
  1414. @mkdir($sTempTargetDir.'/images');
  1415. file_put_contents($sFilePath, $sData);
  1416. if (!file_exists($sFilePath))
  1417. {
  1418. throw new Exception('Could not write icon file '.$sFilePath);
  1419. }
  1420. $oParentNode = $oFileRef->parentNode;
  1421. $oParentNode->removeChild($oFileRef);
  1422. $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile);
  1423. $oParentNode->appendChild($oTextNode);
  1424. }
  1425. }
  1426. }
  1427. protected function CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $sNodeName, $sTargetFile)
  1428. {
  1429. if (($sIcon = $oBrandingNode->GetChildText($sNodeName)) && (strlen($sIcon) > 0))
  1430. {
  1431. if (substr($sIcon, 0, 8) == 'branding')
  1432. {
  1433. $sSourceFile = $sTempTargetDir.'/'.$sIcon;
  1434. }
  1435. else
  1436. {
  1437. $sSourceFile = APPROOT.$sIcon;
  1438. }
  1439. $sTargetFile = $sTempTargetDir.'/branding/'.$sTargetFile.'.png';
  1440. if (!file_exists($sSourceFile))
  1441. {
  1442. throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)");
  1443. }
  1444. // 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)
  1445. copy($sSourceFile, $sTargetFile);
  1446. }
  1447. }
  1448. protected function CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir)
  1449. {
  1450. if ($oBrandingNode)
  1451. {
  1452. // Transform file refs into files in the images folder
  1453. SetupUtils::builddir($sTempTargetDir.'/branding');
  1454. $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding');
  1455. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'main_logo', 'main-logo');
  1456. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'login_logo', 'login-logo');
  1457. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'portal_logo', 'portal-logo');
  1458. // Cleanup the images directory (made by CompileFiles)
  1459. SetupUtils::rrmdir($sTempTargetDir.'/branding/images');
  1460. }
  1461. }
  1462. }
  1463. ?>