compiler.class.inc.php 71 KB

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