compiler.class.inc.php 74 KB

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