compiler.class.inc.php 70 KB

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