compiler.class.inc.php 77 KB

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