compiler.class.inc.php 80 KB

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