compiler.class.inc.php 79 KB

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