compiler.class.inc.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. <?php
  2. // Copyright (C) 2011-2015 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 == 'AttributeObjectKey')
  821. {
  822. $aParameters['class_attcode'] = $this->GetMandatoryPropString($oField, 'class_attcode');
  823. $aParameters['allowed_values'] = 'null';
  824. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  825. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  826. $aParameters['depends_on'] = $sDependencies;
  827. }
  828. elseif ($sAttType == 'AttributeHierarchicalKey')
  829. {
  830. if ($sOql = $oField->GetChildText('filter'))
  831. {
  832. $sEscapedOql = self::QuoteForPHP($sOql);
  833. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  834. }
  835. else
  836. {
  837. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  838. }
  839. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  840. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  841. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  842. $aParameters['depends_on'] = $sDependencies;
  843. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  844. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  845. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  846. }
  847. elseif ($sAttType == 'AttributeExternalField')
  848. {
  849. $aParameters['allowed_values'] = 'null';
  850. $aParameters['extkey_attcode'] = $this->GetMandatoryPropString($oField, 'extkey_attcode', '');
  851. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode', '');
  852. }
  853. elseif ($sAttType == 'AttributeURL')
  854. {
  855. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  856. $aParameters['allowed_values'] = 'null';
  857. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  858. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  859. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  860. $aParameters['depends_on'] = $sDependencies;
  861. }
  862. elseif ($sAttType == 'AttributeEnum')
  863. {
  864. $oValues = $oField->GetUniqueElement('values');
  865. $oValueNodes = $oValues->getElementsByTagName('value');
  866. $aValues = array();
  867. foreach($oValueNodes as $oValue)
  868. {
  869. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  870. $aValues[] = $oValue->textContent;
  871. }
  872. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  873. $sValues = '"'.implode(',', $aValues).'"';
  874. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  875. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  876. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  877. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  878. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  879. $aParameters['depends_on'] = $sDependencies;
  880. }
  881. elseif ($sAttType == 'AttributeBlob')
  882. {
  883. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  884. $aParameters['depends_on'] = $sDependencies;
  885. }
  886. elseif ($sAttType == 'AttributeStopWatch')
  887. {
  888. $oStates = $oField->GetUniqueElement('states');
  889. $oStateNodes = $oStates->getElementsByTagName('state');
  890. $aStates = array();
  891. foreach($oStateNodes as $oState)
  892. {
  893. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  894. }
  895. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  896. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  897. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', ''); // Blank (different than DefaultWorkingTimeComputer)
  898. $oThresholds = $oField->GetUniqueElement('thresholds');
  899. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  900. $aThresholds = array();
  901. foreach($oThresholdNodes as $oThreshold)
  902. {
  903. $iPercent = (int)$oThreshold->getAttribute('id');
  904. $oHighlight = $oThreshold->GetUniqueElement('highlight', false);
  905. $sHighlight = '';
  906. if($oHighlight)
  907. {
  908. $sCode = $oHighlight->GetChildText('code');
  909. $sPersistent = $this->GetPropBoolean($oHighlight, 'persistent', false);
  910. $sHighlight = "'highlight' => array('code' => '$sCode', 'persistent' => $sPersistent), ";
  911. }
  912. $oActions = $oThreshold->GetUniqueElement('actions');
  913. $oActionNodes = $oActions->getElementsByTagName('action');
  914. $aActions = array();
  915. foreach($oActionNodes as $oAction)
  916. {
  917. $oParams = $oAction->GetOptionalElement('params');
  918. $aActionParams = array();
  919. if ($oParams)
  920. {
  921. $oParamNodes = $oParams->getElementsByTagName('param');
  922. foreach($oParamNodes as $oParam)
  923. {
  924. $sParamType = $oParam->getAttribute('xsi:type');
  925. if ($sParamType == '')
  926. {
  927. $sParamType = 'string';
  928. }
  929. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  930. }
  931. }
  932. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  933. $sVerb = $this->GetPropString($oAction, 'verb');
  934. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  935. }
  936. $sActions = 'array('.implode(', ', $aActions).')';
  937. $aThresholds[] = $iPercent." => array('percent' => $iPercent, $sHighlight 'actions' => $sActions)";
  938. }
  939. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  940. }
  941. elseif ($sAttType == 'AttributeSubItem')
  942. {
  943. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode');
  944. $aParameters['item_code'] = $this->GetMandatoryPropString($oField, 'item_code');
  945. }
  946. else
  947. {
  948. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  949. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  950. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  951. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  952. $aParameters['depends_on'] = $sDependencies;
  953. }
  954. // Optional parameters (more for historical reasons)
  955. // Added if present...
  956. //
  957. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  958. $aParameters['width'] = $this->GetPropNumber($oField, 'width');
  959. $aParameters['height'] = $this->GetPropNumber($oField, 'height');
  960. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  961. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  962. $aParameters['always_load_in_tables'] = $this->GetPropBoolean($oField, 'always_load_in_tables', false);
  963. $sTrackingLevel = $oField->GetChildText('tracking_level');
  964. if (!is_null($sTrackingLevel))
  965. {
  966. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sAttType, $sTrackingLevel);
  967. }
  968. $aParams = array();
  969. foreach($aParameters as $sKey => $sValue)
  970. {
  971. if (!is_null($sValue))
  972. {
  973. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  974. }
  975. }
  976. $sParams = implode(', ', $aParams);
  977. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  978. }
  979. catch(Exception $e)
  980. {
  981. throw new DOMFormatException("Field: '$sAttCode', (type: $sAttType), ".$e->getMessage());
  982. }
  983. }
  984. // Lifecycle
  985. //
  986. $sLifecycle = '';
  987. $sHighlightScale = '';
  988. if ($oLifecycle)
  989. {
  990. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  991. $sLifecycle .= "\t\t//\n";
  992. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  993. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  994. {
  995. $sStimulus = $oStimulus->getAttribute('id');
  996. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  997. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  998. }
  999. $oHighlightScale = $oLifecycle->GetUniqueElement('highlight_scale', false);
  1000. if ($oHighlightScale)
  1001. {
  1002. $sHighlightScale = "\t\t// Higlight Scale\n";
  1003. $sHighlightScale .= " MetaModel::Init_DefineHighlightScale( array(\n";
  1004. $this->CompileFiles($oHighlightScale, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  1005. foreach ($oHighlightScale->getElementsByTagName('item') as $oItem)
  1006. {
  1007. $sItemCode = $oItem->getAttribute('id');
  1008. $fRank = (float)$oItem->GetChildText('rank');
  1009. $sColor = $oItem->GetChildText('color');
  1010. if (($sIcon = $oItem->GetChildText('icon')) && (strlen($sIcon) > 0))
  1011. {
  1012. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  1013. $sIcon = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  1014. }
  1015. else
  1016. {
  1017. $sIcon = "''";
  1018. }
  1019. switch($sColor)
  1020. {
  1021. // Known PHP constants: keep the literal value as-is
  1022. case 'HILIGHT_CLASS_CRITICAL':
  1023. case 'HIGHLIGHT_CLASS_CRITICAL':
  1024. $sColor = 'HILIGHT_CLASS_CRITICAL';
  1025. break;
  1026. case 'HILIGHT_CLASS_OK':
  1027. case 'HIGHLIGHT_CLASS_OK':
  1028. $sColor = 'HILIGHT_CLASS_OK';
  1029. break;
  1030. case 'HIGHLIGHT_CLASS_WARNING':
  1031. case 'HILIGHT_CLASS_WARNING':
  1032. $sColor = 'HILIGHT_CLASS_WARNING';
  1033. break;
  1034. case 'HIGHLIGHT_CLASS_NONE':
  1035. case 'HILIGHT_CLASS_NONE':
  1036. $sColor = 'HILIGHT_CLASS_NONE';
  1037. break;
  1038. default:
  1039. // Future extension, specify your own color??
  1040. $sColor = "'".addslashes($sColor)."'";
  1041. }
  1042. $sHighlightScale .= " '$sItemCode' => array('rank' => $fRank, 'color' => $sColor, 'icon' => $sIcon),\n";
  1043. }
  1044. $sHighlightScale .= " ));\n";
  1045. }
  1046. $oStates = $oLifecycle->GetUniqueElement('states');
  1047. $aStatesDependencies = array();
  1048. $aStates = array();
  1049. foreach ($oStates->getElementsByTagName('state') as $oState)
  1050. {
  1051. $aStatesDependencies[$oState->getAttribute('id')] = $oState->GetChildText('inherit_flags_from', '');
  1052. $aStates[$oState->getAttribute('id')] = $oState;
  1053. }
  1054. $aStatesOrder = array();
  1055. while (count($aStatesOrder) < count($aStatesDependencies))
  1056. {
  1057. $iResolved = 0;
  1058. foreach($aStatesDependencies as $sState => $sInheritFrom)
  1059. {
  1060. if (is_null($sInheritFrom))
  1061. {
  1062. // Already recorded as resolved
  1063. continue;
  1064. }
  1065. elseif ($sInheritFrom == '')
  1066. {
  1067. // Resolved
  1068. $aStatesOrder[$sState] = $sInheritFrom;
  1069. $aStatesDependencies[$sState] = null;
  1070. $iResolved++;
  1071. }
  1072. elseif (isset($aStatesOrder[$sInheritFrom]))
  1073. {
  1074. // Resolved
  1075. $aStatesOrder[$sState] = $sInheritFrom;
  1076. $aStatesDependencies[$sState] = null;
  1077. $iResolved++;
  1078. }
  1079. }
  1080. if ($iResolved == 0)
  1081. {
  1082. // No change on this loop -> there are unmet dependencies
  1083. $aRemainingDeps = array();
  1084. foreach($aStatesDependencies as $sState => $sParentState)
  1085. {
  1086. if (strlen($sParentState) > 0)
  1087. {
  1088. $aRemainingDeps[] = $sState.' ('.$sParentState.')';
  1089. }
  1090. }
  1091. throw new DOMFormatException("Could not solve inheritance for states: ".implode(', ', $aRemainingDeps));
  1092. }
  1093. }
  1094. foreach ($aStatesOrder as $sState => $foo)
  1095. {
  1096. $oState = $aStates[$sState];
  1097. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  1098. if ($oInitialStatePath)
  1099. {
  1100. $aInitialStatePath = array();
  1101. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  1102. {
  1103. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  1104. }
  1105. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  1106. }
  1107. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  1108. $sLifecycle .= " \"".$sState."\",\n";
  1109. $sLifecycle .= " array(\n";
  1110. $sAttributeInherit = $oState->GetChildText('inherit_flags_from', '');
  1111. $sLifecycle .= " \"attribute_inherit\" => '$sAttributeInherit',\n";
  1112. $oHighlight = $oState->GetUniqueElement('highlight', false);
  1113. if ($oHighlight)
  1114. {
  1115. $sCode = $oHighlight->GetChildText('code', '');
  1116. if ($sCode != '')
  1117. {
  1118. $sLifecycle .= " 'highlight' => array('code' => '$sCode'),\n";
  1119. }
  1120. }
  1121. $sLifecycle .= " \"attribute_list\" => array(\n";
  1122. $oFlags = $oState->GetUniqueElement('flags');
  1123. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  1124. {
  1125. $sFlags = $this->FlagsToPHP($oAttributeNode);
  1126. if (strlen($sFlags) > 0)
  1127. {
  1128. $sAttCode = $oAttributeNode->GetAttribute('id');
  1129. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  1130. }
  1131. }
  1132. $sLifecycle .= " ),\n";
  1133. if (!is_null($oInitialStatePath))
  1134. {
  1135. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  1136. }
  1137. $sLifecycle .= " )\n";
  1138. $sLifecycle .= " );\n";
  1139. $oTransitions = $oState->GetUniqueElement('transitions');
  1140. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  1141. {
  1142. $sStimulus = $oTransition->getAttribute('id');
  1143. $sTargetState = $oTransition->GetChildText('target');
  1144. $oActions = $oTransition->GetUniqueElement('actions');
  1145. $aVerbs = array();
  1146. foreach ($oActions->getElementsByTagName('action') as $oAction)
  1147. {
  1148. $sVerb = $oAction->GetChildText('verb');
  1149. $oParams = $oAction->GetOptionalElement('params');
  1150. $aActionParams = array();
  1151. if ($oParams)
  1152. {
  1153. $oParamNodes = $oParams->getElementsByTagName('param');
  1154. foreach($oParamNodes as $oParam)
  1155. {
  1156. $sParamType = $oParam->getAttribute('xsi:type');
  1157. if ($sParamType == '')
  1158. {
  1159. $sParamType = 'string';
  1160. }
  1161. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  1162. }
  1163. }
  1164. else
  1165. {
  1166. // Old (pre 2.1.0) format, when no parameter is specified, assume 1 parameter: reference sStimulusCode
  1167. $aActionParams[] = "array('type' => 'reference', 'value' => 'sStimulusCode')";
  1168. }
  1169. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  1170. $aVerbs[] = "array('verb' => '$sVerb', 'params' => $sActionParams)";
  1171. }
  1172. $sActions = implode(', ', $aVerbs);
  1173. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  1174. }
  1175. }
  1176. }
  1177. // ZLists
  1178. //
  1179. $aListRef = array(
  1180. 'details' => 'details',
  1181. 'standard_search' => 'search',
  1182. 'list' => 'list'
  1183. );
  1184. $oPresentation = $oClass->GetUniqueElement('presentation');
  1185. $sZlists = '';
  1186. foreach ($aListRef as $sListCode => $sListTag)
  1187. {
  1188. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  1189. if ($oListNode)
  1190. {
  1191. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  1192. $this->ArrayOfItemsToZList($aAttributes);
  1193. $sZAttributes = var_export($aAttributes, true);
  1194. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  1195. }
  1196. }
  1197. // Methods
  1198. $sMethods = "";
  1199. $oMethods = $oClass->GetUniqueElement('methods');
  1200. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  1201. {
  1202. $sMethodCode = $oMethod->GetChildText('code');
  1203. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  1204. {
  1205. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  1206. }
  1207. else
  1208. {
  1209. $sMethods .= "\n\n".$sMethodCode."\n";
  1210. }
  1211. }
  1212. // Let's make the whole class declaration
  1213. //
  1214. $sPHP = "\n\n$sCodeComment\n";
  1215. $sParentClass = $oClass->GetChildText('php_parent');
  1216. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  1217. if ($oPhpParent)
  1218. {
  1219. $sParentClass = $oPhpParent->GetChildText('name', '');
  1220. if ($sParentClass == '')
  1221. {
  1222. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', missing required tag 'name' under 'php_parent'.");
  1223. }
  1224. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  1225. if ($sIncludeFile != '')
  1226. {
  1227. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  1228. }
  1229. //TODO fix this !!!
  1230. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  1231. // if (!file_exists($sFullPath))
  1232. // {
  1233. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  1234. // }
  1235. }
  1236. else
  1237. {
  1238. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  1239. }
  1240. if ($oProperties->GetChildText('abstract') == 'true')
  1241. {
  1242. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  1243. }
  1244. else
  1245. {
  1246. $sPHP .= 'class '.$oClass->getAttribute('id');
  1247. }
  1248. $sPHP .= " extends $sParentClass\n";
  1249. $sPHP .=
  1250. <<<EOF
  1251. {
  1252. public static function Init()
  1253. {
  1254. \$aParams = array
  1255. (
  1256. $sClassParams
  1257. );
  1258. MetaModel::Init_Params(\$aParams);
  1259. MetaModel::Init_InheritAttributes();
  1260. $sAttributes
  1261. $sLifecycle
  1262. $sHighlightScale
  1263. $sZlists
  1264. }
  1265. $sMethods
  1266. }
  1267. EOF;
  1268. return $sPHP;
  1269. }// function CompileClass()
  1270. protected function CompileMenu($oMenu, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  1271. {
  1272. $this->CompileFiles($oMenu, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, $sModuleRelativeDir);
  1273. $sMenuId = $oMenu->getAttribute("id");
  1274. $sMenuClass = $oMenu->getAttribute("xsi:type");
  1275. $sParent = $oMenu->GetChildText('parent', null);
  1276. if ($sParent)
  1277. {
  1278. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  1279. }
  1280. else
  1281. {
  1282. $sParentSpec = '-1';
  1283. }
  1284. $fRank = (float) $oMenu->GetChildText('rank');
  1285. switch($sMenuClass)
  1286. {
  1287. case 'WebPageMenuNode':
  1288. $sUrl = $oMenu->GetChildText('url');
  1289. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  1290. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  1291. break;
  1292. case 'DashboardMenuNode':
  1293. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  1294. if ($sTemplateFile != '')
  1295. {
  1296. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1297. }
  1298. else
  1299. {
  1300. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  1301. if ($oDashboardDefinition == null)
  1302. {
  1303. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  1304. }
  1305. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  1306. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  1307. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  1308. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1309. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1310. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  1311. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1312. $oXMLDoc->appendChild($oRootNode);
  1313. foreach($oDashboardDefinition->childNodes as $oNode)
  1314. {
  1315. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  1316. $oRootNode->appendChild($oDefNode);
  1317. }
  1318. $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  1319. }
  1320. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1321. break;
  1322. case 'ShortcutContainerMenuNode':
  1323. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1324. break;
  1325. case 'OQLMenuNode':
  1326. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1327. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1328. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch);";
  1329. break;
  1330. case 'NewObjectMenuNode':
  1331. $sClass = $oMenu->GetChildText('class');
  1332. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1333. break;
  1334. case 'SearchMenuNode':
  1335. $sClass = $oMenu->GetChildText('class');
  1336. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1337. break;
  1338. case 'TemplateMenuNode':
  1339. $sTemplateFile = $oMenu->GetChildText('template_file');
  1340. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1341. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1342. {
  1343. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1344. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1345. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1346. if ($sEnableStimulus != null)
  1347. {
  1348. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1349. }
  1350. else
  1351. {
  1352. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1353. }
  1354. }
  1355. else
  1356. {
  1357. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1358. }
  1359. break;
  1360. case 'MenuGroup':
  1361. default:
  1362. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1363. {
  1364. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1365. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1366. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1367. if ($sEnableStimulus != null)
  1368. {
  1369. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1370. }
  1371. else
  1372. {
  1373. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1374. }
  1375. }
  1376. else
  1377. {
  1378. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1379. }
  1380. }
  1381. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1382. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1383. {
  1384. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1385. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1386. }
  1387. return $aPHPMenu;
  1388. } // function CompileMenu
  1389. /**
  1390. * Helper to compute the grant, taking any existing grant into account
  1391. */
  1392. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1393. {
  1394. if (isset($aGrants[$sKey]))
  1395. {
  1396. if (!$bGrant)
  1397. {
  1398. $aGrants[$sKey] = false;
  1399. }
  1400. }
  1401. else
  1402. {
  1403. $aGrants[$sKey] = $bGrant;
  1404. }
  1405. }
  1406. protected function CompileUserRights($oUserRightsNode)
  1407. {
  1408. static $aActionsInShort = array(
  1409. 'read' => 'r',
  1410. 'bulk read' => 'br',
  1411. 'write' => 'w',
  1412. 'bulk write' => 'bw',
  1413. 'delete' => 'd',
  1414. 'bulk delete' => 'bd',
  1415. );
  1416. // Preliminary : create an index so that links will be taken into account implicitely
  1417. $aLinkToClasses = array();
  1418. $oClasses = $this->oFactory->ListAllClasses();
  1419. foreach($oClasses as $oClass)
  1420. {
  1421. $bIsLink = false;
  1422. $oProperties = $oClass->GetOptionalElement('properties');
  1423. if ($oProperties)
  1424. {
  1425. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1426. }
  1427. if ($bIsLink)
  1428. {
  1429. foreach($this->oFactory->ListFields($oClass) as $oField)
  1430. {
  1431. $sAttType = $oField->getAttribute('xsi:type');
  1432. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1433. {
  1434. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1435. if (($sOnTargetDel == 'DEL_AUTO') || ($sOnTargetDel == 'DEL_SILENT'))
  1436. {
  1437. $sTargetClass = $oField->GetChildText('target_class');
  1438. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. // Groups
  1445. //
  1446. $aGroupClasses = array();
  1447. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1448. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1449. {
  1450. $sGroupId = $oGroup->getAttribute("id");
  1451. $aClasses = array();
  1452. $oClasses = $oGroup->GetUniqueElement('classes');
  1453. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1454. {
  1455. $sClass = $oClass->getAttribute("id");
  1456. $aClasses[] = $sClass;
  1457. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1458. //if ($bSubclasses)...
  1459. }
  1460. $aGroupClasses[$sGroupId] = $aClasses;
  1461. }
  1462. // Profiles and grants
  1463. //
  1464. $aProfiles = array();
  1465. // Hardcode the administrator profile
  1466. $aProfiles[1] = array(
  1467. 'name' => 'Administrator',
  1468. 'description' => 'Has the rights on everything (bypassing any control)'
  1469. );
  1470. $aGrants = array();
  1471. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1472. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1473. {
  1474. $iProfile = $oProfile->getAttribute("id");
  1475. $sName = $oProfile->GetChildText('name');
  1476. $sDescription = $oProfile->GetChildText('description');
  1477. $oGroups = $oProfile->GetUniqueElement('groups');
  1478. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1479. {
  1480. $sGroupId = $oGroup->getAttribute("id");
  1481. $aActions = array();
  1482. $oActions = $oGroup->GetUniqueElement('actions');
  1483. foreach($oActions->getElementsByTagName('action') as $oAction)
  1484. {
  1485. $sAction = $oAction->getAttribute("id");
  1486. if (strpos($sAction, 'action:') === 0)
  1487. {
  1488. $sType = 'action';
  1489. $sActionCode = substr($sAction, strlen('action:'));
  1490. $sActionCode = $aActionsInShort[$sActionCode];
  1491. }
  1492. else
  1493. {
  1494. $sType = 'stimulus';
  1495. $sActionCode = substr($sAction, strlen('stimulus:'));
  1496. }
  1497. $sGrant = $oAction->GetText();
  1498. $bGrant = ($sGrant == 'allow');
  1499. if ($sGroupId == '*')
  1500. {
  1501. $aGrantClasses = array('*');
  1502. }
  1503. else
  1504. {
  1505. $aGrantClasses = $aGroupClasses[$sGroupId];
  1506. }
  1507. foreach ($aGrantClasses as $sClass)
  1508. {
  1509. if ($sType == 'stimulus')
  1510. {
  1511. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sActionCode, $bGrant);
  1512. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1513. }
  1514. else
  1515. {
  1516. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sActionCode, $bGrant);
  1517. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1518. }
  1519. }
  1520. }
  1521. }
  1522. $aProfiles[$iProfile] = array(
  1523. 'name' => $sName,
  1524. 'description' => $sDescription
  1525. );
  1526. }
  1527. $sProfiles = var_export($aProfiles, true);
  1528. $sGrants = var_export($aGrants, true);
  1529. $sLinkToClasses = var_export($aLinkToClasses, true);
  1530. $sPHP =
  1531. <<<EOF
  1532. //
  1533. // List of constant profiles
  1534. // - used by the class URP_Profiles at setup (create/update/delete records)
  1535. // - used by the addon UserRightsProfile to determine user rights
  1536. //
  1537. class ProfilesConfig
  1538. {
  1539. protected static \$aPROFILES = $sProfiles;
  1540. protected static \$aGRANTS = $sGrants;
  1541. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1542. // Now replaced by MetaModel::GetLinkClasses (working with 1.x)
  1543. // This function could be deprecated
  1544. public static function GetLinkClasses()
  1545. {
  1546. return self::\$aLINKTOCLASSES;
  1547. }
  1548. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1549. {
  1550. \$bLegacyBehavior = MetaModel::GetConfig()->Get('user_rights_legacy');
  1551. // Search for a grant, stoping if any deny is encountered (allowance implies the verification of all paths)
  1552. \$bAllow = null;
  1553. // 1 - The class itself
  1554. //
  1555. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1556. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1557. {
  1558. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1559. if (\$bLegacyBehavior) return \$bAllow;
  1560. if (!\$bAllow) return false;
  1561. }
  1562. // 2 - The parent classes, up to the root class
  1563. //
  1564. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1565. {
  1566. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1567. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1568. {
  1569. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1570. if (\$bLegacyBehavior) return \$bAllow;
  1571. if (!\$bAllow) return false;
  1572. }
  1573. }
  1574. // 3 - The related classes (if the current is an N-N link with DEL_AUTO/DEL_SILENT)
  1575. //
  1576. \$bGrant = self::GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction);
  1577. if (!is_null(\$bGrant))
  1578. {
  1579. \$bAllow = \$bGrant;
  1580. if (\$bLegacyBehavior) return \$bAllow;
  1581. if (!\$bAllow) return false;
  1582. }
  1583. // 4 - All
  1584. //
  1585. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1586. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1587. {
  1588. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1589. if (\$bLegacyBehavior) return \$bAllow;
  1590. if (!\$bAllow) return false;
  1591. }
  1592. // null or true
  1593. return \$bAllow;
  1594. }
  1595. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1596. {
  1597. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1598. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1599. {
  1600. return self::\$aGRANTS[\$sGrantKey];
  1601. }
  1602. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1603. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1604. {
  1605. return self::\$aGRANTS[\$sGrantKey];
  1606. }
  1607. return null;
  1608. }
  1609. // returns an array of id => array of column => php value(so-called "real value")
  1610. public static function GetProfilesValues()
  1611. {
  1612. return self::\$aPROFILES;
  1613. }
  1614. // Propagate the rights on classes onto the links themselves (the external keys must have DEL_AUTO or DEL_SILENT
  1615. //
  1616. protected static function GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction)
  1617. {
  1618. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1619. {
  1620. // Get the grant for the remote classes. The resulting grant is:
  1621. // - One YES => YES
  1622. // - 100% undefined => undefined
  1623. // - otherwise => NO
  1624. //
  1625. // Having write allowed on the remote class implies write + delete on the N-N link class
  1626. if (\$sAction == 'd')
  1627. {
  1628. \$sRemoteAction = 'w';
  1629. }
  1630. elseif (\$sAction == 'bd')
  1631. {
  1632. \$sRemoteAction = 'bw';
  1633. }
  1634. else
  1635. {
  1636. \$sRemoteAction = \$sAction;
  1637. }
  1638. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1639. {
  1640. \$bUndefined = true;
  1641. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1642. if (\$bGrant === true)
  1643. {
  1644. return true;
  1645. }
  1646. if (\$bGrant === false)
  1647. {
  1648. \$bUndefined = false;
  1649. }
  1650. }
  1651. if (!\$bUndefined)
  1652. {
  1653. return false;
  1654. }
  1655. }
  1656. return null;
  1657. }
  1658. }
  1659. EOF;
  1660. return $sPHP;
  1661. } // function CompileUserRights
  1662. protected function CompileDictionary($oDictionaryNode, $sTempTargetDir, $sFinalTargetDir)
  1663. {
  1664. $sLang = $oDictionaryNode->getAttribute('id');
  1665. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1666. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1667. $aEntriesPHP = array();
  1668. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1669. foreach($oEntries->getElementsByTagName('entry') as $oEntry)
  1670. {
  1671. $sStringCode = $oEntry->getAttribute('id');
  1672. $sValue = $oEntry->GetText();
  1673. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP($sValue, true).",";
  1674. }
  1675. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1676. $sEscEnglishLanguageDesc = self::QuoteForPHP($sEnglishLanguageDesc);
  1677. $sEscLocalizedLanguageDesc = self::QuoteForPHP($sLocalizedLanguageDesc);
  1678. $sPHPDict =
  1679. <<<EOF
  1680. <?php
  1681. //
  1682. // Dictionary built by the compiler for the language "$sLang"
  1683. //
  1684. Dict::Add('$sLang', $sEscEnglishLanguageDesc, $sEscLocalizedLanguageDesc, array(
  1685. $sEntriesPHP
  1686. ));
  1687. EOF;
  1688. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1689. $sDictFile = $sTempTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1690. file_put_contents($sDictFile, $sPHPDict);
  1691. }
  1692. // Transform the file references into the corresponding filename (and create the file in the relevant directory)
  1693. //
  1694. protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath)
  1695. {
  1696. $oFileRefs = $oNode->GetNodes(".//fileref");
  1697. foreach ($oFileRefs as $oFileRef)
  1698. {
  1699. $sFileId = $oFileRef->getAttribute('ref');
  1700. if ($sFileId !== '')
  1701. {
  1702. $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id='$sFileId']");
  1703. if ($oNodes->length == 0)
  1704. {
  1705. throw new DOMFormatException('Could not find the file with ref '.$sFileId);
  1706. }
  1707. $sName = $oNodes->item(0)->GetChildText('name');
  1708. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  1709. $aPathInfo = pathinfo($sName);
  1710. $sFile = $sFileId.'.'.$aPathInfo['extension'];
  1711. $sFilePath = $sTempTargetDir.'/images/'.$sFile;
  1712. @mkdir($sTempTargetDir.'/images');
  1713. file_put_contents($sFilePath, $sData);
  1714. if (!file_exists($sFilePath))
  1715. {
  1716. throw new Exception('Could not write icon file '.$sFilePath);
  1717. }
  1718. $oParentNode = $oFileRef->parentNode;
  1719. $oParentNode->removeChild($oFileRef);
  1720. $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile);
  1721. $oParentNode->appendChild($oTextNode);
  1722. }
  1723. }
  1724. }
  1725. protected function CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $sNodeName, $sTargetFile)
  1726. {
  1727. if (($sIcon = $oBrandingNode->GetChildText($sNodeName)) && (strlen($sIcon) > 0))
  1728. {
  1729. if (substr($sIcon, 0, 8) == 'branding')
  1730. {
  1731. $sSourceFile = $sTempTargetDir.'/'.$sIcon;
  1732. }
  1733. else
  1734. {
  1735. $sSourceFile = APPROOT.$sIcon;
  1736. }
  1737. $sTargetFile = $sTempTargetDir.'/branding/'.$sTargetFile.'.png';
  1738. if (!file_exists($sSourceFile))
  1739. {
  1740. throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)");
  1741. }
  1742. // 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)
  1743. copy($sSourceFile, $sTargetFile);
  1744. }
  1745. }
  1746. protected function CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir)
  1747. {
  1748. if ($oBrandingNode)
  1749. {
  1750. // Transform file refs into files in the images folder
  1751. SetupUtils::builddir($sTempTargetDir.'/branding');
  1752. $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding');
  1753. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'main_logo', 'main-logo');
  1754. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'login_logo', 'login-logo');
  1755. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'portal_logo', 'portal-logo');
  1756. // Cleanup the images directory (eventually made by CompileFiles)
  1757. if (file_exists($sTempTargetDir.'/branding/images'))
  1758. {
  1759. SetupUtils::rrmdir($sTempTargetDir.'/branding/images');
  1760. }
  1761. }
  1762. }
  1763. }
  1764. ?>