compiler.class.inc.php 77 KB

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