compiler.class.inc.php 80 KB

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