compiler.class.inc.php 58 KB

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