compiler.class.inc.php 76 KB

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