compiler.class.inc.php 76 KB

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