compiler.class.inc.php 74 KB

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