compiler.class.inc.php 77 KB

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