compiler.class.inc.php 80 KB

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