compiler.class.inc.php 77 KB

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