compiler.class.inc.php 74 KB

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