compiler.class.inc.php 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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 GetMandatoryPropBoolean($oNode, $sTag)
  611. {
  612. $val = $oNode->GetChildText($sTag);
  613. if (is_null($val))
  614. {
  615. throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'");
  616. }
  617. return $val == 'true' ? 'true' : 'false';
  618. }
  619. protected function GetPropNumber($oNode, $sTag, $nDefault = null)
  620. {
  621. $val = $oNode->GetChildText($sTag);
  622. if (is_null($val))
  623. {
  624. if (is_null($nDefault))
  625. {
  626. return null;
  627. }
  628. else
  629. {
  630. $val = $nDefault;
  631. }
  632. }
  633. return (string)$val;
  634. }
  635. protected function GetMandatoryPropNumber($oNode, $sTag)
  636. {
  637. $val = $oNode->GetChildText($sTag);
  638. if (is_null($val))
  639. {
  640. throw new DOMFormatException("missing (or empty) mandatory tag '$sTag' under the tag '".$oNode->nodeName."'");
  641. }
  642. return (string)$val;
  643. }
  644. /**
  645. * Adds quotes and escape characters
  646. */
  647. protected function QuoteForPHP($sStr, $bSimpleQuotes = false)
  648. {
  649. if ($bSimpleQuotes)
  650. {
  651. $sEscaped = str_replace(array('\\', "'"), array('\\\\', "\\'"), $sStr);
  652. $sRet = "'$sEscaped'";
  653. }
  654. else
  655. {
  656. $sEscaped = str_replace(array('\\', '"', "\n"), array('\\\\', '\\"', '\\n'), $sStr);
  657. $sRet = '"'.$sEscaped.'"';
  658. }
  659. return $sRet;
  660. }
  661. protected function CompileConstant($oConstant)
  662. {
  663. $sName = $oConstant->getAttribute('id');
  664. $sType = $oConstant->getAttribute('xsi:type');
  665. $sText = $oConstant->GetText(null);
  666. switch ($sType)
  667. {
  668. case 'integer':
  669. if (is_null($sText))
  670. {
  671. // No data given => null
  672. $sScalar = 'null';
  673. }
  674. else
  675. {
  676. $sScalar = (string)(int)$sText;
  677. }
  678. break;
  679. case 'float':
  680. if (is_null($sText))
  681. {
  682. // No data given => null
  683. $sScalar = 'null';
  684. }
  685. else
  686. {
  687. $sScalar = (string)(float)$sText;
  688. }
  689. break;
  690. case 'bool':
  691. if (is_null($sText))
  692. {
  693. // No data given => null
  694. $sScalar = 'null';
  695. }
  696. else
  697. {
  698. $sScalar = ($sText == 'true') ? 'true' : 'false';
  699. }
  700. break;
  701. case 'string':
  702. default:
  703. $sScalar = $this->QuoteForPHP($sText, true);
  704. }
  705. $sPHPDefine = "define('$sName', $sScalar);";
  706. return $sPHPDefine;
  707. }
  708. protected function CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  709. {
  710. $sClass = $oClass->getAttribute('id');
  711. $oProperties = $oClass->GetUniqueElement('properties');
  712. // Class caracteristics
  713. //
  714. $aClassParams = array();
  715. $aClassParams['category'] = $this->GetPropString($oProperties, 'category', '');
  716. $aClassParams['key_type'] = "'autoincrement'";
  717. if ((bool) $this->GetPropNumber($oProperties, 'is_link', 0))
  718. {
  719. $aClassParams['is_link'] = 'true';
  720. }
  721. if ($oNaming = $oProperties->GetOptionalElement('naming'))
  722. {
  723. $oNameAttributes = $oNaming->GetUniqueElement('attributes');
  724. $oAttributes = $oNameAttributes->getElementsByTagName('attribute');
  725. $aNameAttCodes = array();
  726. foreach($oAttributes as $oAttribute)
  727. {
  728. $aNameAttCodes[] = $oAttribute->getAttribute('id');
  729. }
  730. if (count($aNameAttCodes) > 1)
  731. {
  732. // New style...
  733. $sNameAttCode = "array('".implode("', '", $aNameAttCodes)."')";
  734. }
  735. elseif (count($aNameAttCodes) == 1)
  736. {
  737. // New style...
  738. $sNameAttCode = "'$aNameAttCodes[0]'";
  739. }
  740. else
  741. {
  742. $sNameAttCode = "''";
  743. }
  744. }
  745. else
  746. {
  747. $sNameAttCode = "''";
  748. }
  749. $aClassParams['name_attcode'] = $sNameAttCode;
  750. $oLifecycle = $oClass->GetOptionalElement('lifecycle');
  751. if ($oLifecycle)
  752. {
  753. $sStateAttCode = $oLifecycle->GetChildText('attribute');
  754. }
  755. else
  756. {
  757. $sStateAttCode = "";
  758. }
  759. $aClassParams['state_attcode'] = "'$sStateAttCode'";
  760. if ($oReconciliation = $oProperties->GetOptionalElement('reconciliation'))
  761. {
  762. $oReconcAttributes = $oReconciliation->getElementsByTagName('attribute');
  763. $aReconcAttCodes = array();
  764. foreach($oReconcAttributes as $oAttribute)
  765. {
  766. $aReconcAttCodes[] = $oAttribute->getAttribute('id');
  767. }
  768. $sReconcKeys = "array('".implode("', '", $aReconcAttCodes)."')";
  769. }
  770. else
  771. {
  772. $sReconcKeys = "array()";
  773. }
  774. $aClassParams['reconc_keys'] = $sReconcKeys;
  775. $aClassParams['db_table'] = $this->GetPropString($oProperties, 'db_table', '');
  776. $aClassParams['db_key_field'] = $this->GetPropString($oProperties, 'db_key_field', 'id');
  777. if (array_key_exists($sClass, $this->aRootClasses))
  778. {
  779. $sDefaultFinalClass = 'finalclass';
  780. }
  781. else
  782. {
  783. $sDefaultFinalClass = '';
  784. }
  785. $aClassParams['db_finalclass_field'] = $this->GetPropString($oProperties, 'db_final_class_field', $sDefaultFinalClass);
  786. if (($sDisplayTemplate = $oProperties->GetChildText('display_template')) && (strlen($sDisplayTemplate) > 0))
  787. {
  788. $sDisplayTemplate = $sModuleRelativeDir.'/'.$sDisplayTemplate;
  789. $aClassParams['display_template'] = "utils::GetAbsoluteUrlModulesRoot().'$sDisplayTemplate'";
  790. }
  791. $this->CompileFiles($oProperties, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  792. if (($sIcon = $oProperties->GetChildText('icon')) && (strlen($sIcon) > 0))
  793. {
  794. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  795. $aClassParams['icon'] = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  796. }
  797. $oOrder = $oProperties->GetOptionalElement('order');
  798. if ($oOrder)
  799. {
  800. $oColumnsNode = $oOrder->GetUniqueElement('columns');
  801. $oColumns = $oColumnsNode->getElementsByTagName('column');
  802. $aSortColumns = array();
  803. foreach($oColumns as $oColumn)
  804. {
  805. $aSortColumns[] = "'".$oColumn->getAttribute('id')."' => ".(($oColumn->getAttribute('ascending') == 'true') ? 'true' : 'false');
  806. }
  807. if (count($aSortColumns) > 0)
  808. {
  809. $aClassParams['order_by_default'] = "array(".implode(", ", $aSortColumns).")";
  810. }
  811. }
  812. if ($oIndexes = $oProperties->GetOptionalElement('indexes'))
  813. {
  814. $aIndexes = array();
  815. foreach($oIndexes->getElementsByTagName('index') as $oIndex)
  816. {
  817. $sIndexId = $oIndex->getAttribute('id');
  818. $oAttributes = $oIndex->GetUniqueElement('attributes');
  819. foreach($oAttributes->getElementsByTagName('attribute') as $oAttribute)
  820. {
  821. $aIndexes[$sIndexId][] = $oAttribute->getAttribute('id');
  822. }
  823. }
  824. $aClassParams['indexes'] = var_export($aIndexes, true);
  825. }
  826. // Finalize class params declaration
  827. //
  828. $aClassParamsPHP = array();
  829. foreach($aClassParams as $sKey => $sPHPValue)
  830. {
  831. $aClassParamsPHP[] = " '$sKey' => $sPHPValue,";
  832. }
  833. $sClassParams = implode("\n", $aClassParamsPHP);
  834. // Comment on top of the class declaration
  835. //
  836. $sCodeComment = $oProperties->GetChildText('comment');
  837. // Fields
  838. //
  839. $sAttributes = '';
  840. foreach($this->oFactory->ListFields($oClass) as $oField)
  841. {
  842. try
  843. {
  844. // $oField
  845. $sAttCode = $oField->getAttribute('id');
  846. $sAttType = $oField->getAttribute('xsi:type');
  847. $aDependencies = array();
  848. $oDependencies = $oField->GetOptionalElement('dependencies');
  849. if (!is_null($oDependencies))
  850. {
  851. $oDepNodes = $oDependencies->getElementsByTagName('attribute');
  852. foreach($oDepNodes as $oDepAttribute)
  853. {
  854. $aDependencies[] = "'".$oDepAttribute->getAttribute('id')."'";
  855. }
  856. }
  857. $sDependencies = 'array('.implode(', ', $aDependencies).')';
  858. $aParameters = array();
  859. if ($sAttType == 'AttributeLinkedSetIndirect')
  860. {
  861. $aParameters['linked_class'] = $this->GetMandatoryPropString($oField, 'linked_class');
  862. $aParameters['ext_key_to_me'] = $this->GetMandatoryPropString($oField, 'ext_key_to_me');
  863. $aParameters['ext_key_to_remote'] = $this->GetMandatoryPropString($oField, 'ext_key_to_remote');
  864. $aParameters['allowed_values'] = 'null';
  865. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  866. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  867. $aParameters['duplicates'] = $this->GetPropBoolean($oField, 'duplicates', false);
  868. $aParameters['depends_on'] = $sDependencies;
  869. }
  870. elseif ($sAttType == 'AttributeLinkedSet')
  871. {
  872. $aParameters['linked_class'] = $this->GetMandatoryPropString($oField, 'linked_class');
  873. $aParameters['ext_key_to_me'] = $this->GetMandatoryPropString($oField, 'ext_key_to_me');
  874. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  875. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  876. $sEditMode = $oField->GetChildText('edit_mode');
  877. if (!is_null($sEditMode))
  878. {
  879. $aParameters['edit_mode'] = $this->EditModeToPHP($sEditMode);
  880. }
  881. if ($sOql = $oField->GetChildText('filter'))
  882. {
  883. $sEscapedOql = self::QuoteForPHP($sOql);
  884. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)";
  885. }
  886. else
  887. {
  888. $aParameters['allowed_values'] = 'null';
  889. }
  890. $aParameters['depends_on'] = $sDependencies;
  891. }
  892. elseif ($sAttType == 'AttributeExternalKey')
  893. {
  894. $aParameters['targetclass'] = $this->GetPropString($oField, 'target_class', '');
  895. // deprecated: $aParameters['jointype'] = 'null';
  896. if ($sOql = $oField->GetChildText('filter'))
  897. {
  898. $sEscapedOql = self::QuoteForPHP($sOql);
  899. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  900. }
  901. else
  902. {
  903. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  904. }
  905. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  906. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  907. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  908. $aParameters['depends_on'] = $sDependencies;
  909. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  910. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  911. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  912. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'select');
  913. }
  914. elseif ($sAttType == 'AttributeObjectKey')
  915. {
  916. $aParameters['class_attcode'] = $this->GetMandatoryPropString($oField, 'class_attcode');
  917. $aParameters['allowed_values'] = 'null';
  918. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  919. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  920. $aParameters['depends_on'] = $sDependencies;
  921. }
  922. elseif ($sAttType == 'AttributeHierarchicalKey')
  923. {
  924. if ($sOql = $oField->GetChildText('filter'))
  925. {
  926. $sEscapedOql = self::QuoteForPHP($sOql);
  927. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  928. }
  929. else
  930. {
  931. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  932. }
  933. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  934. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  935. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  936. $aParameters['depends_on'] = $sDependencies;
  937. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  938. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  939. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  940. }
  941. elseif ($sAttType == 'AttributeExternalField')
  942. {
  943. $aParameters['allowed_values'] = 'null';
  944. $aParameters['extkey_attcode'] = $this->GetMandatoryPropString($oField, 'extkey_attcode', '');
  945. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode', '');
  946. }
  947. elseif ($sAttType == 'AttributeURL')
  948. {
  949. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  950. $aParameters['allowed_values'] = 'null';
  951. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  952. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  953. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  954. $aParameters['depends_on'] = $sDependencies;
  955. }
  956. elseif ($sAttType == 'AttributeEnum')
  957. {
  958. $oValues = $oField->GetUniqueElement('values');
  959. $oValueNodes = $oValues->getElementsByTagName('value');
  960. $aValues = array();
  961. foreach($oValueNodes as $oValue)
  962. {
  963. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  964. $aValues[] = $oValue->textContent;
  965. }
  966. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  967. $sValues = '"'.implode(',', $aValues).'"';
  968. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  969. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  970. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql', '');
  971. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  972. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  973. $aParameters['depends_on'] = $sDependencies;
  974. }
  975. elseif ($sAttType == 'AttributeBlob')
  976. {
  977. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  978. $aParameters['depends_on'] = $sDependencies;
  979. }
  980. elseif ($sAttType == 'AttributeStopWatch')
  981. {
  982. $oStates = $oField->GetUniqueElement('states');
  983. $oStateNodes = $oStates->getElementsByTagName('state');
  984. $aStates = array();
  985. foreach($oStateNodes as $oState)
  986. {
  987. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  988. }
  989. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  990. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  991. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', ''); // Blank (different than DefaultWorkingTimeComputer)
  992. $oThresholds = $oField->GetUniqueElement('thresholds');
  993. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  994. $aThresholds = array();
  995. foreach($oThresholdNodes as $oThreshold)
  996. {
  997. $iPercent = (int)$oThreshold->getAttribute('id');
  998. $oHighlight = $oThreshold->GetUniqueElement('highlight', false);
  999. $sHighlight = '';
  1000. if($oHighlight)
  1001. {
  1002. $sCode = $oHighlight->GetChildText('code');
  1003. $sPersistent = $this->GetPropBoolean($oHighlight, 'persistent', false);
  1004. $sHighlight = "'highlight' => array('code' => '$sCode', 'persistent' => $sPersistent), ";
  1005. }
  1006. $oActions = $oThreshold->GetUniqueElement('actions');
  1007. $oActionNodes = $oActions->getElementsByTagName('action');
  1008. $aActions = array();
  1009. foreach($oActionNodes as $oAction)
  1010. {
  1011. $oParams = $oAction->GetOptionalElement('params');
  1012. $aActionParams = array();
  1013. if ($oParams)
  1014. {
  1015. $oParamNodes = $oParams->getElementsByTagName('param');
  1016. foreach($oParamNodes as $oParam)
  1017. {
  1018. $sParamType = $oParam->getAttribute('xsi:type');
  1019. if ($sParamType == '')
  1020. {
  1021. $sParamType = 'string';
  1022. }
  1023. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  1024. }
  1025. }
  1026. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  1027. $sVerb = $this->GetPropString($oAction, 'verb');
  1028. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  1029. }
  1030. $sActions = 'array('.implode(', ', $aActions).')';
  1031. $aThresholds[] = $iPercent." => array('percent' => $iPercent, $sHighlight 'actions' => $sActions)";
  1032. }
  1033. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  1034. }
  1035. elseif ($sAttType == 'AttributeSubItem')
  1036. {
  1037. $aParameters['target_attcode'] = $this->GetMandatoryPropString($oField, 'target_attcode');
  1038. $aParameters['item_code'] = $this->GetMandatoryPropString($oField, 'item_code');
  1039. }
  1040. elseif ($sAttType == 'AttributeRedundancySettings')
  1041. {
  1042. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  1043. $aParameters['relation_code'] = $this->GetMandatoryPropString($oField, 'relation_code');
  1044. $aParameters['from_class'] = $this->GetMandatoryPropString($oField, 'from_class');
  1045. $aParameters['neighbour_id'] = $this->GetMandatoryPropString($oField, 'neighbour_id');
  1046. $aParameters['enabled'] = $this->GetMandatoryPropBoolean($oField, 'enabled');
  1047. $aParameters['enabled_mode'] = $this->GetMandatoryPropString($oField, 'enabled_mode');
  1048. $aParameters['min_up'] = $this->GetMandatoryPropNumber($oField, 'min_up');
  1049. $aParameters['min_up_mode'] = $this->GetMandatoryPropString($oField, 'min_up_mode');
  1050. $aParameters['min_up_type'] = $this->GetMandatoryPropString($oField, 'min_up_type');
  1051. }
  1052. else
  1053. {
  1054. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  1055. $aParameters['sql'] = $this->GetMandatoryPropString($oField, 'sql');
  1056. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  1057. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  1058. $aParameters['depends_on'] = $sDependencies;
  1059. }
  1060. // Optional parameters (more for historical reasons)
  1061. // Added if present...
  1062. //
  1063. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  1064. $aParameters['width'] = $this->GetPropString($oField, 'width');
  1065. $aParameters['height'] = $this->GetPropString($oField, 'height');
  1066. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  1067. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  1068. $aParameters['always_load_in_tables'] = $this->GetPropBoolean($oField, 'always_load_in_tables', false);
  1069. $sTrackingLevel = $oField->GetChildText('tracking_level');
  1070. if (!is_null($sTrackingLevel))
  1071. {
  1072. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sAttType, $sTrackingLevel);
  1073. }
  1074. $aParams = array();
  1075. foreach($aParameters as $sKey => $sValue)
  1076. {
  1077. if (!is_null($sValue))
  1078. {
  1079. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  1080. }
  1081. }
  1082. $sParams = implode(', ', $aParams);
  1083. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  1084. }
  1085. catch(Exception $e)
  1086. {
  1087. throw new DOMFormatException("Field: '$sAttCode', (type: $sAttType), ".$e->getMessage());
  1088. }
  1089. }
  1090. // Lifecycle
  1091. //
  1092. $sLifecycle = '';
  1093. $sHighlightScale = '';
  1094. if ($oLifecycle)
  1095. {
  1096. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  1097. $sLifecycle .= "\t\t//\n";
  1098. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  1099. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  1100. {
  1101. $sStimulus = $oStimulus->getAttribute('id');
  1102. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  1103. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  1104. }
  1105. $oHighlightScale = $oLifecycle->GetUniqueElement('highlight_scale', false);
  1106. if ($oHighlightScale)
  1107. {
  1108. $sHighlightScale = "\t\t// Higlight Scale\n";
  1109. $sHighlightScale .= " MetaModel::Init_DefineHighlightScale( array(\n";
  1110. $this->CompileFiles($oHighlightScale, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  1111. foreach ($oHighlightScale->getElementsByTagName('item') as $oItem)
  1112. {
  1113. $sItemCode = $oItem->getAttribute('id');
  1114. $fRank = (float)$oItem->GetChildText('rank');
  1115. $sColor = $oItem->GetChildText('color');
  1116. if (($sIcon = $oItem->GetChildText('icon')) && (strlen($sIcon) > 0))
  1117. {
  1118. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  1119. $sIcon = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  1120. }
  1121. else
  1122. {
  1123. $sIcon = "''";
  1124. }
  1125. switch($sColor)
  1126. {
  1127. // Known PHP constants: keep the literal value as-is
  1128. case 'HILIGHT_CLASS_CRITICAL':
  1129. case 'HIGHLIGHT_CLASS_CRITICAL':
  1130. $sColor = 'HILIGHT_CLASS_CRITICAL';
  1131. break;
  1132. case 'HILIGHT_CLASS_OK':
  1133. case 'HIGHLIGHT_CLASS_OK':
  1134. $sColor = 'HILIGHT_CLASS_OK';
  1135. break;
  1136. case 'HIGHLIGHT_CLASS_WARNING':
  1137. case 'HILIGHT_CLASS_WARNING':
  1138. $sColor = 'HILIGHT_CLASS_WARNING';
  1139. break;
  1140. case 'HIGHLIGHT_CLASS_NONE':
  1141. case 'HILIGHT_CLASS_NONE':
  1142. $sColor = 'HILIGHT_CLASS_NONE';
  1143. break;
  1144. default:
  1145. // Future extension, specify your own color??
  1146. $sColor = "'".addslashes($sColor)."'";
  1147. }
  1148. $sHighlightScale .= " '$sItemCode' => array('rank' => $fRank, 'color' => $sColor, 'icon' => $sIcon),\n";
  1149. }
  1150. $sHighlightScale .= " ));\n";
  1151. }
  1152. $oStates = $oLifecycle->GetUniqueElement('states');
  1153. $aStatesDependencies = array();
  1154. $aStates = array();
  1155. foreach ($oStates->getElementsByTagName('state') as $oState)
  1156. {
  1157. $aStatesDependencies[$oState->getAttribute('id')] = $oState->GetChildText('inherit_flags_from', '');
  1158. $aStates[$oState->getAttribute('id')] = $oState;
  1159. }
  1160. $aStatesOrder = array();
  1161. while (count($aStatesOrder) < count($aStatesDependencies))
  1162. {
  1163. $iResolved = 0;
  1164. foreach($aStatesDependencies as $sState => $sInheritFrom)
  1165. {
  1166. if (is_null($sInheritFrom))
  1167. {
  1168. // Already recorded as resolved
  1169. continue;
  1170. }
  1171. elseif ($sInheritFrom == '')
  1172. {
  1173. // Resolved
  1174. $aStatesOrder[$sState] = $sInheritFrom;
  1175. $aStatesDependencies[$sState] = null;
  1176. $iResolved++;
  1177. }
  1178. elseif (isset($aStatesOrder[$sInheritFrom]))
  1179. {
  1180. // Resolved
  1181. $aStatesOrder[$sState] = $sInheritFrom;
  1182. $aStatesDependencies[$sState] = null;
  1183. $iResolved++;
  1184. }
  1185. }
  1186. if ($iResolved == 0)
  1187. {
  1188. // No change on this loop -> there are unmet dependencies
  1189. $aRemainingDeps = array();
  1190. foreach($aStatesDependencies as $sState => $sParentState)
  1191. {
  1192. if (strlen($sParentState) > 0)
  1193. {
  1194. $aRemainingDeps[] = $sState.' ('.$sParentState.')';
  1195. }
  1196. }
  1197. throw new DOMFormatException("Could not solve inheritance for states: ".implode(', ', $aRemainingDeps));
  1198. }
  1199. }
  1200. foreach ($aStatesOrder as $sState => $foo)
  1201. {
  1202. $oState = $aStates[$sState];
  1203. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  1204. if ($oInitialStatePath)
  1205. {
  1206. $aInitialStatePath = array();
  1207. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  1208. {
  1209. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  1210. }
  1211. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  1212. }
  1213. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  1214. $sLifecycle .= " \"".$sState."\",\n";
  1215. $sLifecycle .= " array(\n";
  1216. $sAttributeInherit = $oState->GetChildText('inherit_flags_from', '');
  1217. $sLifecycle .= " \"attribute_inherit\" => '$sAttributeInherit',\n";
  1218. $oHighlight = $oState->GetUniqueElement('highlight', false);
  1219. if ($oHighlight)
  1220. {
  1221. $sCode = $oHighlight->GetChildText('code', '');
  1222. if ($sCode != '')
  1223. {
  1224. $sLifecycle .= " 'highlight' => array('code' => '$sCode'),\n";
  1225. }
  1226. }
  1227. $sLifecycle .= " \"attribute_list\" => array(\n";
  1228. $oFlags = $oState->GetUniqueElement('flags');
  1229. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  1230. {
  1231. $sFlags = $this->FlagsToPHP($oAttributeNode);
  1232. if (strlen($sFlags) > 0)
  1233. {
  1234. $sAttCode = $oAttributeNode->GetAttribute('id');
  1235. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  1236. }
  1237. }
  1238. $sLifecycle .= " ),\n";
  1239. if (!is_null($oInitialStatePath))
  1240. {
  1241. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  1242. }
  1243. $sLifecycle .= " )\n";
  1244. $sLifecycle .= " );\n";
  1245. $oTransitions = $oState->GetUniqueElement('transitions');
  1246. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  1247. {
  1248. $sStimulus = $oTransition->getAttribute('id');
  1249. $sTargetState = $oTransition->GetChildText('target');
  1250. $oActions = $oTransition->GetUniqueElement('actions');
  1251. $aVerbs = array();
  1252. foreach ($oActions->getElementsByTagName('action') as $oAction)
  1253. {
  1254. $sVerb = $oAction->GetChildText('verb');
  1255. $oParams = $oAction->GetOptionalElement('params');
  1256. $aActionParams = array();
  1257. if ($oParams)
  1258. {
  1259. $oParamNodes = $oParams->getElementsByTagName('param');
  1260. foreach($oParamNodes as $oParam)
  1261. {
  1262. $sParamType = $oParam->getAttribute('xsi:type');
  1263. if ($sParamType == '')
  1264. {
  1265. $sParamType = 'string';
  1266. }
  1267. $aActionParams[] = "array('type' => '$sParamType', 'value' => ".self::QuoteForPHP($oParam->textContent).")";
  1268. }
  1269. }
  1270. else
  1271. {
  1272. // Old (pre 2.1.0) format, when no parameter is specified, assume 1 parameter: reference sStimulusCode
  1273. $aActionParams[] = "array('type' => 'reference', 'value' => 'sStimulusCode')";
  1274. }
  1275. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  1276. $aVerbs[] = "array('verb' => '$sVerb', 'params' => $sActionParams)";
  1277. }
  1278. $sActions = implode(', ', $aVerbs);
  1279. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  1280. }
  1281. }
  1282. }
  1283. // ZLists
  1284. //
  1285. $aListRef = array(
  1286. 'details' => 'details',
  1287. 'standard_search' => 'search',
  1288. 'list' => 'list'
  1289. );
  1290. $oPresentation = $oClass->GetUniqueElement('presentation');
  1291. $sZlists = '';
  1292. foreach ($aListRef as $sListCode => $sListTag)
  1293. {
  1294. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  1295. if ($oListNode)
  1296. {
  1297. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  1298. $this->ArrayOfItemsToZList($aAttributes);
  1299. $sZAttributes = var_export($aAttributes, true);
  1300. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  1301. }
  1302. }
  1303. // Methods
  1304. $sMethods = "";
  1305. $oMethods = $oClass->GetUniqueElement('methods');
  1306. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  1307. {
  1308. $sMethodCode = $oMethod->GetChildText('code');
  1309. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  1310. {
  1311. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  1312. }
  1313. else
  1314. {
  1315. $sMethods .= "\n\n".$sMethodCode."\n";
  1316. }
  1317. }
  1318. // Relations
  1319. //
  1320. $oRelations = $oClass->GetOptionalElement('relations');
  1321. if ($oRelations)
  1322. {
  1323. $aRelations = array();
  1324. foreach($oRelations->childNodes as $oRelation)
  1325. {
  1326. if ($oRelation->tagName != 'relation') continue;
  1327. $sRelationId = $oRelation->getAttribute('id');
  1328. $this->aRelations[$sRelationId] = array('id' => $sRelationId);
  1329. $oNeighbours = $oRelation->GetUniqueElement('neighbours');
  1330. foreach($oNeighbours->childNodes as $oNeighbour)
  1331. {
  1332. if ($oNeighbour->tagName != 'neighbour') continue;
  1333. $sNeighbourId = $oNeighbour->getAttribute('id');
  1334. $sDirection = $oNeighbour->GetChildText('direction', 'both');
  1335. $sAttribute = $oNeighbour->GetChildText('attribute');
  1336. $sQueryDown = $oNeighbour->GetChildText('query_down');
  1337. $sQueryUp = $oNeighbour->GetChildText('query_up');
  1338. if (($sQueryDown == '') && ($sAttribute == ''))
  1339. {
  1340. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': either a query or an attribute must be specified");
  1341. }
  1342. if (($sQueryDown != '') && ($sAttribute != ''))
  1343. {
  1344. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': both a query and and attribute have been specified... which one should be used?");
  1345. }
  1346. if ($sDirection == 'both')
  1347. {
  1348. if (($sAttribute == '') && ($sQueryUp == ''))
  1349. {
  1350. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': missing the query_up specification");
  1351. }
  1352. }
  1353. elseif ($sDirection == 'down')
  1354. {
  1355. // Ok
  1356. }
  1357. else
  1358. {
  1359. throw new DOMFormatException("Relation '$sRelationId/$sNeighbourId': unknown direction ($sDirection), expecting 'both' or 'down'");
  1360. }
  1361. $aRelations[$sRelationId][$sNeighbourId] = array(
  1362. '_legacy_' => false,
  1363. 'sDirection' => $sDirection,
  1364. 'sDefinedInClass' => $sClass,
  1365. 'sNeighbour' => $sNeighbourId,
  1366. 'sQueryDown' => $sQueryDown,
  1367. 'sQueryUp' => $sQueryUp,
  1368. 'sAttribute' => $sAttribute,
  1369. );
  1370. }
  1371. }
  1372. $sMethods .= "\tpublic static function GetRelationQueriesEx(\$sRelCode)\n";
  1373. $sMethods .= "\t{\n";
  1374. $sMethods .= "\t\tswitch (\$sRelCode)\n";
  1375. $sMethods .= "\t\t{\n";
  1376. foreach ($aRelations as $sRelationId => $aRelationData)
  1377. {
  1378. $sMethods .= "\t\tcase '$sRelationId':\n";
  1379. $sMethods .= "\t\t\t\$aRels = array(\n";
  1380. foreach ($aRelationData as $sNeighbourId => $aData)
  1381. {
  1382. //$sData = str_replace("\n", "\n\t\t\t\t", var_export($aData, true));
  1383. $sData = var_export($aData, true);
  1384. $sMethods .= "\t\t\t\t'$sNeighbourId' => $sData,\n";
  1385. }
  1386. $sMethods .= "\t\t\t);\n";
  1387. $sMethods .= "\t\t\treturn array_merge(\$aRels, parent::GetRelationQueriesEx(\$sRelCode));\n\n";
  1388. }
  1389. $sMethods .= "\t\tdefault:\n";
  1390. $sMethods .= "\t\t\treturn parent::GetRelationQueriesEx(\$sRelCode);\n";
  1391. $sMethods .= "\t\t}\n";
  1392. $sMethods .= "\t}\n";
  1393. }
  1394. // Let's make the whole class declaration
  1395. //
  1396. $sPHP = "\n\n$sCodeComment\n";
  1397. $sParentClass = $oClass->GetChildText('php_parent');
  1398. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  1399. if ($oPhpParent)
  1400. {
  1401. $sParentClass = $oPhpParent->GetChildText('name', '');
  1402. if ($sParentClass == '')
  1403. {
  1404. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', missing required tag 'name' under 'php_parent'.");
  1405. }
  1406. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  1407. if ($sIncludeFile != '')
  1408. {
  1409. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  1410. }
  1411. //TODO fix this !!!
  1412. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  1413. // if (!file_exists($sFullPath))
  1414. // {
  1415. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  1416. // }
  1417. }
  1418. else
  1419. {
  1420. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  1421. }
  1422. if ($oProperties->GetChildText('abstract') == 'true')
  1423. {
  1424. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  1425. }
  1426. else
  1427. {
  1428. $sPHP .= 'class '.$oClass->getAttribute('id');
  1429. }
  1430. $sPHP .= " extends $sParentClass\n";
  1431. $sPHP .=
  1432. <<<EOF
  1433. {
  1434. public static function Init()
  1435. {
  1436. \$aParams = array
  1437. (
  1438. $sClassParams
  1439. );
  1440. MetaModel::Init_Params(\$aParams);
  1441. MetaModel::Init_InheritAttributes();
  1442. $sAttributes
  1443. $sLifecycle
  1444. $sHighlightScale
  1445. $sZlists
  1446. }
  1447. $sMethods
  1448. }
  1449. EOF;
  1450. return $sPHP;
  1451. }// function CompileClass()
  1452. protected function CompileMenu($oMenu, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  1453. {
  1454. $this->CompileFiles($oMenu, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, $sModuleRelativeDir);
  1455. $sMenuId = $oMenu->getAttribute("id");
  1456. $sMenuClass = $oMenu->getAttribute("xsi:type");
  1457. $sParent = $oMenu->GetChildText('parent', null);
  1458. if ($sParent)
  1459. {
  1460. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  1461. }
  1462. else
  1463. {
  1464. $sParentSpec = '-1';
  1465. }
  1466. $fRank = (float) $oMenu->GetChildText('rank');
  1467. switch($sMenuClass)
  1468. {
  1469. case 'WebPageMenuNode':
  1470. $sUrl = $oMenu->GetChildText('url');
  1471. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  1472. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  1473. break;
  1474. case 'DashboardMenuNode':
  1475. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  1476. if ($sTemplateFile != '')
  1477. {
  1478. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1479. }
  1480. else
  1481. {
  1482. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  1483. if ($oDashboardDefinition == null)
  1484. {
  1485. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  1486. }
  1487. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  1488. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  1489. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  1490. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1491. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1492. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  1493. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1494. $oXMLDoc->appendChild($oRootNode);
  1495. foreach($oDashboardDefinition->childNodes as $oNode)
  1496. {
  1497. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  1498. $oRootNode->appendChild($oDefNode);
  1499. }
  1500. $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  1501. }
  1502. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1503. break;
  1504. case 'ShortcutContainerMenuNode':
  1505. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1506. break;
  1507. case 'OQLMenuNode':
  1508. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1509. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1510. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch);";
  1511. break;
  1512. case 'NewObjectMenuNode':
  1513. $sClass = $oMenu->GetChildText('class');
  1514. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1515. break;
  1516. case 'SearchMenuNode':
  1517. $sClass = $oMenu->GetChildText('class');
  1518. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1519. break;
  1520. case 'TemplateMenuNode':
  1521. $sTemplateFile = $oMenu->GetChildText('template_file');
  1522. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1523. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1524. {
  1525. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1526. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1527. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1528. if ($sEnableStimulus != null)
  1529. {
  1530. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1531. }
  1532. else
  1533. {
  1534. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1535. }
  1536. }
  1537. else
  1538. {
  1539. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1540. }
  1541. break;
  1542. case 'MenuGroup':
  1543. default:
  1544. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1545. {
  1546. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1547. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1548. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1549. if ($sEnableStimulus != null)
  1550. {
  1551. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1552. }
  1553. else
  1554. {
  1555. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1556. }
  1557. }
  1558. else
  1559. {
  1560. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1561. }
  1562. }
  1563. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1564. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1565. {
  1566. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1567. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1568. }
  1569. return $aPHPMenu;
  1570. } // function CompileMenu
  1571. /**
  1572. * Helper to compute the grant, taking any existing grant into account
  1573. */
  1574. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1575. {
  1576. if (isset($aGrants[$sKey]))
  1577. {
  1578. if (!$bGrant)
  1579. {
  1580. $aGrants[$sKey] = false;
  1581. }
  1582. }
  1583. else
  1584. {
  1585. $aGrants[$sKey] = $bGrant;
  1586. }
  1587. }
  1588. protected function CompileUserRights($oUserRightsNode)
  1589. {
  1590. static $aActionsInShort = array(
  1591. 'read' => 'r',
  1592. 'bulk read' => 'br',
  1593. 'write' => 'w',
  1594. 'bulk write' => 'bw',
  1595. 'delete' => 'd',
  1596. 'bulk delete' => 'bd',
  1597. );
  1598. // Preliminary : create an index so that links will be taken into account implicitely
  1599. $aLinkToClasses = array();
  1600. $oClasses = $this->oFactory->ListAllClasses();
  1601. foreach($oClasses as $oClass)
  1602. {
  1603. $bIsLink = false;
  1604. $oProperties = $oClass->GetOptionalElement('properties');
  1605. if ($oProperties)
  1606. {
  1607. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1608. }
  1609. if ($bIsLink)
  1610. {
  1611. foreach($this->oFactory->ListFields($oClass) as $oField)
  1612. {
  1613. $sAttType = $oField->getAttribute('xsi:type');
  1614. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1615. {
  1616. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1617. if (($sOnTargetDel == 'DEL_AUTO') || ($sOnTargetDel == 'DEL_SILENT'))
  1618. {
  1619. $sTargetClass = $oField->GetChildText('target_class');
  1620. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. }
  1626. // Groups
  1627. //
  1628. $aGroupClasses = array();
  1629. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1630. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1631. {
  1632. $sGroupId = $oGroup->getAttribute("id");
  1633. $aClasses = array();
  1634. $oClasses = $oGroup->GetUniqueElement('classes');
  1635. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1636. {
  1637. $sClass = $oClass->getAttribute("id");
  1638. $aClasses[] = $sClass;
  1639. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1640. //if ($bSubclasses)...
  1641. }
  1642. $aGroupClasses[$sGroupId] = $aClasses;
  1643. }
  1644. // Profiles and grants
  1645. //
  1646. $aProfiles = array();
  1647. // Hardcode the administrator profile
  1648. $aProfiles[1] = array(
  1649. 'name' => 'Administrator',
  1650. 'description' => 'Has the rights on everything (bypassing any control)'
  1651. );
  1652. $aGrants = array();
  1653. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1654. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1655. {
  1656. $iProfile = $oProfile->getAttribute("id");
  1657. $sName = $oProfile->GetChildText('name');
  1658. $sDescription = $oProfile->GetChildText('description');
  1659. $oGroups = $oProfile->GetUniqueElement('groups');
  1660. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1661. {
  1662. $sGroupId = $oGroup->getAttribute("id");
  1663. $aActions = array();
  1664. $oActions = $oGroup->GetUniqueElement('actions');
  1665. foreach($oActions->getElementsByTagName('action') as $oAction)
  1666. {
  1667. $sAction = $oAction->getAttribute("id");
  1668. if (strpos($sAction, 'action:') === 0)
  1669. {
  1670. $sType = 'action';
  1671. $sActionCode = substr($sAction, strlen('action:'));
  1672. $sActionCode = $aActionsInShort[$sActionCode];
  1673. }
  1674. else
  1675. {
  1676. $sType = 'stimulus';
  1677. $sActionCode = substr($sAction, strlen('stimulus:'));
  1678. }
  1679. $sGrant = $oAction->GetText();
  1680. $bGrant = ($sGrant == 'allow');
  1681. if ($sGroupId == '*')
  1682. {
  1683. $aGrantClasses = array('*');
  1684. }
  1685. else
  1686. {
  1687. $aGrantClasses = $aGroupClasses[$sGroupId];
  1688. }
  1689. foreach ($aGrantClasses as $sClass)
  1690. {
  1691. if ($sType == 'stimulus')
  1692. {
  1693. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sActionCode, $bGrant);
  1694. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1695. }
  1696. else
  1697. {
  1698. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sActionCode, $bGrant);
  1699. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sActionCode, $bGrant); // subclasses inherit this grant
  1700. }
  1701. }
  1702. }
  1703. }
  1704. $aProfiles[$iProfile] = array(
  1705. 'name' => $sName,
  1706. 'description' => $sDescription
  1707. );
  1708. }
  1709. $sProfiles = var_export($aProfiles, true);
  1710. $sGrants = var_export($aGrants, true);
  1711. $sLinkToClasses = var_export($aLinkToClasses, true);
  1712. $sPHP =
  1713. <<<EOF
  1714. //
  1715. // List of constant profiles
  1716. // - used by the class URP_Profiles at setup (create/update/delete records)
  1717. // - used by the addon UserRightsProfile to determine user rights
  1718. //
  1719. class ProfilesConfig
  1720. {
  1721. protected static \$aPROFILES = $sProfiles;
  1722. protected static \$aGRANTS = $sGrants;
  1723. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1724. // Now replaced by MetaModel::GetLinkClasses (working with 1.x)
  1725. // This function could be deprecated
  1726. public static function GetLinkClasses()
  1727. {
  1728. return self::\$aLINKTOCLASSES;
  1729. }
  1730. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1731. {
  1732. \$bLegacyBehavior = MetaModel::GetConfig()->Get('user_rights_legacy');
  1733. // Search for a grant, stoping if any deny is encountered (allowance implies the verification of all paths)
  1734. \$bAllow = null;
  1735. // 1 - The class itself
  1736. //
  1737. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1738. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1739. {
  1740. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1741. if (\$bLegacyBehavior) return \$bAllow;
  1742. if (!\$bAllow) return false;
  1743. }
  1744. // 2 - The parent classes, up to the root class
  1745. //
  1746. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1747. {
  1748. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1749. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1750. {
  1751. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1752. if (\$bLegacyBehavior) return \$bAllow;
  1753. if (!\$bAllow) return false;
  1754. }
  1755. }
  1756. // 3 - The related classes (if the current is an N-N link with DEL_AUTO/DEL_SILENT)
  1757. //
  1758. \$bGrant = self::GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction);
  1759. if (!is_null(\$bGrant))
  1760. {
  1761. \$bAllow = \$bGrant;
  1762. if (\$bLegacyBehavior) return \$bAllow;
  1763. if (!\$bAllow) return false;
  1764. }
  1765. // 4 - All
  1766. //
  1767. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1768. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1769. {
  1770. \$bAllow = self::\$aGRANTS[\$sGrantKey];
  1771. if (\$bLegacyBehavior) return \$bAllow;
  1772. if (!\$bAllow) return false;
  1773. }
  1774. // null or true
  1775. return \$bAllow;
  1776. }
  1777. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1778. {
  1779. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1780. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1781. {
  1782. return self::\$aGRANTS[\$sGrantKey];
  1783. }
  1784. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1785. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1786. {
  1787. return self::\$aGRANTS[\$sGrantKey];
  1788. }
  1789. return null;
  1790. }
  1791. // returns an array of id => array of column => php value(so-called "real value")
  1792. public static function GetProfilesValues()
  1793. {
  1794. return self::\$aPROFILES;
  1795. }
  1796. // Propagate the rights on classes onto the links themselves (the external keys must have DEL_AUTO or DEL_SILENT
  1797. //
  1798. protected static function GetLinkActionGrant(\$iProfileId, \$sClass, \$sAction)
  1799. {
  1800. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1801. {
  1802. // Get the grant for the remote classes. The resulting grant is:
  1803. // - One YES => YES
  1804. // - 100% undefined => undefined
  1805. // - otherwise => NO
  1806. //
  1807. // Having write allowed on the remote class implies write + delete on the N-N link class
  1808. if (\$sAction == 'd')
  1809. {
  1810. \$sRemoteAction = 'w';
  1811. }
  1812. elseif (\$sAction == 'bd')
  1813. {
  1814. \$sRemoteAction = 'bw';
  1815. }
  1816. else
  1817. {
  1818. \$sRemoteAction = \$sAction;
  1819. }
  1820. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1821. {
  1822. \$bUndefined = true;
  1823. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1824. if (\$bGrant === true)
  1825. {
  1826. return true;
  1827. }
  1828. if (\$bGrant === false)
  1829. {
  1830. \$bUndefined = false;
  1831. }
  1832. }
  1833. if (!\$bUndefined)
  1834. {
  1835. return false;
  1836. }
  1837. }
  1838. return null;
  1839. }
  1840. }
  1841. EOF;
  1842. return $sPHP;
  1843. } // function CompileUserRights
  1844. protected function CompileDictionary($oDictionaryNode, $sTempTargetDir, $sFinalTargetDir)
  1845. {
  1846. $sLang = $oDictionaryNode->getAttribute('id');
  1847. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1848. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1849. $aEntriesPHP = array();
  1850. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1851. foreach($oEntries->getElementsByTagName('entry') as $oEntry)
  1852. {
  1853. $sStringCode = $oEntry->getAttribute('id');
  1854. $sValue = $oEntry->GetText();
  1855. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP($sValue, true).",";
  1856. }
  1857. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1858. $sEscEnglishLanguageDesc = self::QuoteForPHP($sEnglishLanguageDesc);
  1859. $sEscLocalizedLanguageDesc = self::QuoteForPHP($sLocalizedLanguageDesc);
  1860. $sPHPDict =
  1861. <<<EOF
  1862. <?php
  1863. //
  1864. // Dictionary built by the compiler for the language "$sLang"
  1865. //
  1866. Dict::Add('$sLang', $sEscEnglishLanguageDesc, $sEscLocalizedLanguageDesc, array(
  1867. $sEntriesPHP
  1868. ));
  1869. EOF;
  1870. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1871. $sDictFile = $sTempTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1872. file_put_contents($sDictFile, $sPHPDict);
  1873. }
  1874. // Transform the file references into the corresponding filename (and create the file in the relevant directory)
  1875. //
  1876. protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath)
  1877. {
  1878. $oFileRefs = $oNode->GetNodes(".//fileref");
  1879. foreach ($oFileRefs as $oFileRef)
  1880. {
  1881. $sFileId = $oFileRef->getAttribute('ref');
  1882. if ($sFileId !== '')
  1883. {
  1884. $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id='$sFileId']");
  1885. if ($oNodes->length == 0)
  1886. {
  1887. throw new DOMFormatException('Could not find the file with ref '.$sFileId);
  1888. }
  1889. $sName = $oNodes->item(0)->GetChildText('name');
  1890. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  1891. $aPathInfo = pathinfo($sName);
  1892. $sFile = $sFileId.'.'.$aPathInfo['extension'];
  1893. $sFilePath = $sTempTargetDir.'/images/'.$sFile;
  1894. @mkdir($sTempTargetDir.'/images');
  1895. file_put_contents($sFilePath, $sData);
  1896. if (!file_exists($sFilePath))
  1897. {
  1898. throw new Exception('Could not write icon file '.$sFilePath);
  1899. }
  1900. $oParentNode = $oFileRef->parentNode;
  1901. $oParentNode->removeChild($oFileRef);
  1902. $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile);
  1903. $oParentNode->appendChild($oTextNode);
  1904. }
  1905. }
  1906. }
  1907. protected function CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $sNodeName, $sTargetFile)
  1908. {
  1909. if (($sIcon = $oBrandingNode->GetChildText($sNodeName)) && (strlen($sIcon) > 0))
  1910. {
  1911. if (substr($sIcon, 0, 8) == 'branding')
  1912. {
  1913. $sSourceFile = $sTempTargetDir.'/'.$sIcon;
  1914. }
  1915. else
  1916. {
  1917. $sSourceFile = APPROOT.$sIcon;
  1918. }
  1919. $sTargetFile = $sTempTargetDir.'/branding/'.$sTargetFile.'.png';
  1920. if (!file_exists($sSourceFile))
  1921. {
  1922. throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)");
  1923. }
  1924. // 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)
  1925. copy($sSourceFile, $sTargetFile);
  1926. }
  1927. }
  1928. protected function CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir)
  1929. {
  1930. if ($oBrandingNode)
  1931. {
  1932. // Transform file refs into files in the images folder
  1933. SetupUtils::builddir($sTempTargetDir.'/branding');
  1934. $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding');
  1935. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'main_logo', 'main-logo');
  1936. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'login_logo', 'login-logo');
  1937. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'portal_logo', 'portal-logo');
  1938. // Cleanup the images directory (eventually made by CompileFiles)
  1939. if (file_exists($sTempTargetDir.'/branding/images'))
  1940. {
  1941. SetupUtils::rrmdir($sTempTargetDir.'/branding/images');
  1942. }
  1943. }
  1944. }
  1945. protected function CompilePortals($oPortalsNode, $sTempTargetDir, $sFinalTargetDir)
  1946. {
  1947. if ($oPortalsNode)
  1948. {
  1949. // Create some static PHP data in <env-xxx>/core/main.php
  1950. $oPortals = $oPortalsNode->GetNodes('portal');
  1951. $aPortalsConfig = array();
  1952. foreach($oPortals as $oPortal)
  1953. {
  1954. $sPortalId = $oPortal->getAttribute('id');
  1955. $aPortalsConfig[$sPortalId] = array();
  1956. $aPortalsConfig[$sPortalId]['rank'] = (float)$oPortal->GetChildText('rank', 0);
  1957. $aPortalsConfig[$sPortalId]['handler'] = $oPortal->GetChildText('handler', 'PortalDispatcher');
  1958. $aPortalsConfig[$sPortalId]['url'] = $oPortal->GetChildText('url', 'portal/index.php');
  1959. $oAllow = $oPortal->GetOptionalElement('allow');
  1960. $aPortalsConfig[$sPortalId]['allow'] = array();
  1961. if ($oAllow)
  1962. {
  1963. foreach($oAllow->GetNodes('profile') as $oProfile)
  1964. {
  1965. $aPortalsConfig[$sPortalId]['allow'][] = $oProfile->getAttribute('id');
  1966. }
  1967. }
  1968. $oDeny = $oPortal->GetOptionalElement('deny');
  1969. $aPortalsConfig[$sPortalId]['deny'] = array();
  1970. if ($oDeny)
  1971. {
  1972. foreach($oDeny->GetNodes('profile') as $oProfile)
  1973. {
  1974. $aPortalsConfig[$sPortalId]['deny'][] = $oProfile->getAttribute('id');
  1975. }
  1976. }
  1977. }
  1978. uasort($aPortalsConfig, array(get_class($this), 'SortOnRank'));
  1979. $this->sMainPHPCode .= "\n";
  1980. $this->sMainPHPCode .= "/**\n";
  1981. $this->sMainPHPCode .= " * Portal(s) definition(s) extracted from the XML definition at compile time\n";
  1982. $this->sMainPHPCode .= " */\n";
  1983. $this->sMainPHPCode .= "class PortalDispatcherData\n";
  1984. $this->sMainPHPCode .= "{\n";
  1985. $this->sMainPHPCode .= "\tprotected static \$aData = ".var_export($aPortalsConfig, true).";\n\n";
  1986. $this->sMainPHPCode .= "\tpublic static function GetData(\$sPortalId = null)\n";
  1987. $this->sMainPHPCode .= "\t{\n";
  1988. $this->sMainPHPCode .= "\t\tif (\$sPortalId === null) return self::\$aData;\n";
  1989. $this->sMainPHPCode .= "\t\tif (!array_key_exists(\$sPortalId, self::\$aData)) return array();\n";
  1990. $this->sMainPHPCode .= "\t\treturn self::\$aData[\$sPortalId];\n";
  1991. $this->sMainPHPCode .= "\t}\n";
  1992. $this->sMainPHPCode .= "}\n";
  1993. }
  1994. }
  1995. public static function SortOnRank($aConf1, $aConf2)
  1996. {
  1997. return ($aConf1['rank'] < $aConf2['rank']) ? -1 : 1;
  1998. }
  1999. protected function CompileParameters($oParametersNode, $sTempTargetDir, $sFinalTargetDir)
  2000. {
  2001. if ($oParametersNode)
  2002. {
  2003. // Create some static PHP data in <env-xxx>/core/main.php
  2004. $oParameters = $oParametersNode->GetNodes('parameters');
  2005. $aParametersConfig = array();
  2006. foreach($oParameters as $oParams)
  2007. {
  2008. $sModuleId = $oParams->getAttribute('id');
  2009. $oParamsReader = new MFParameters($oParams);
  2010. $aParametersConfig[$sModuleId] = $oParamsReader->GetAll();
  2011. }
  2012. $this->sMainPHPCode .= "\n";
  2013. $this->sMainPHPCode .= "/**\n";
  2014. $this->sMainPHPCode .= " * Modules parameters extracted from the XML definition at compile time\n";
  2015. $this->sMainPHPCode .= " */\n";
  2016. $this->sMainPHPCode .= "class ModulesXMLParameters\n";
  2017. $this->sMainPHPCode .= "{\n";
  2018. $this->sMainPHPCode .= "\tprotected static \$aData = ".var_export($aParametersConfig, true).";\n\n";
  2019. $this->sMainPHPCode .= "\tpublic static function GetData(\$sModuleId = null)\n";
  2020. $this->sMainPHPCode .= "\t{\n";
  2021. $this->sMainPHPCode .= "\t\tif (\$sModuleId === null) return self::\$aData;\n";
  2022. $this->sMainPHPCode .= "\t\tif (!array_key_exists(\$sModuleId, self::\$aData)) return array();\n";
  2023. $this->sMainPHPCode .= "\t\treturn self::\$aData[\$sModuleId];\n";
  2024. $this->sMainPHPCode .= "\t}\n";
  2025. $this->sMainPHPCode .= "}\n";
  2026. }
  2027. }
  2028. protected function LoadSnippets()
  2029. {
  2030. $oSnippets = $this->oFactory->GetNodes('/itop_design/snippets/snippet');
  2031. foreach($oSnippets as $oSnippet)
  2032. {
  2033. $sSnippetId = $oSnippet->getAttribute('id');
  2034. $sPlacement = $oSnippet->GetChildText('placement', null);
  2035. if ($sPlacement == 'core')
  2036. {
  2037. $sModuleId = '_core_';
  2038. }
  2039. else if ($sPlacement == 'module')
  2040. {
  2041. $sModuleId = $oSnippet->GetChildText('module', null);
  2042. if ($sModuleId == null)
  2043. {
  2044. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId' with placement=module. Missing '<module>' tag.");
  2045. }
  2046. }
  2047. else if ($sPlacement === 'null')
  2048. {
  2049. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Missing <placement> tag.");
  2050. }
  2051. else
  2052. {
  2053. throw new DOMFormatException("Invalid definition for snippet id='$sSnippetId'. Incorrect value '$sPlacement' for <placement> tag. The allowed values are either 'core' or 'module'.");
  2054. }
  2055. if (!array_key_exists($sModuleId, $this->aSnippets))
  2056. {
  2057. $this->aSnippets[$sModuleId] = array('before' => array(), 'after' => array());
  2058. }
  2059. $fOrder = (float) $oSnippet->GetChildText('rank', 0);
  2060. $sContent = $oSnippet->GetChildText('content', '');
  2061. if ($fOrder < 0)
  2062. {
  2063. $this->aSnippets[$sModuleId]['before'][] = array(
  2064. 'rank' => $fOrder,
  2065. 'content' => $sContent,
  2066. 'snippet_id' => $sSnippetId,
  2067. );
  2068. }
  2069. else
  2070. {
  2071. $this->aSnippets[$sModuleId]['after'][] = array(
  2072. 'rank' => $fOrder,
  2073. 'content' => $sContent,
  2074. 'snippet_id' => $sSnippetId,
  2075. );
  2076. }
  2077. }
  2078. foreach($this->aSnippets as $sModuleId => $void)
  2079. {
  2080. uasort($this->aSnippets[$sModuleId]['before'], array(get_class($this), 'SortOnRank'));
  2081. }
  2082. }
  2083. }
  2084. ?>