compiler.class.inc.php 70 KB

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