compiler.class.inc.php 74 KB

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