compiler.class.inc.php 69 KB

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