compiler.class.inc.php 72 KB

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