compiler.class.inc.php 80 KB

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