compiler.class.inc.php 75 KB

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