compiler.class.inc.php 70 KB

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