compiler.class.inc.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. <?php
  2. // Copyright (C) 2011-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once(APPROOT.'setup/setuputils.class.inc.php');
  19. class DOMFormatException extends Exception
  20. {
  21. }
  22. /**
  23. * Compiler class
  24. */
  25. class MFCompiler
  26. {
  27. protected $oFactory;
  28. protected $aRootClasses;
  29. protected $aLog;
  30. public function __construct($oModelFactory)
  31. {
  32. $this->oFactory = $oModelFactory;
  33. $this->aLog = array();
  34. }
  35. protected function Log($sText)
  36. {
  37. $this->aLog[] = $sText;
  38. }
  39. protected function DumpLog($oPage)
  40. {
  41. foreach ($this->aLog as $sText)
  42. {
  43. $oPage->p($sText);
  44. }
  45. }
  46. public function GetLog()
  47. {
  48. return $this->aLog;
  49. }
  50. public function Compile($sTargetDir, $oP = null, $bUseSymbolicLinks = false)
  51. {
  52. $sFinalTargetDir = $sTargetDir;
  53. if ($bUseSymbolicLinks)
  54. {
  55. // Skip the creation of a temporary dictionary, not compatible with symbolic links
  56. $sTempTargetDir = $sFinalTargetDir;
  57. }
  58. else
  59. {
  60. // Create a temporary directory
  61. // Once the compilation is 100% successful, then move the results into the target directory
  62. $sTempTargetDir = tempnam(SetupUtils::GetTmpDir(), 'itop-');
  63. unlink($sTempTargetDir); // I need a directory, not a file...
  64. SetupUtils::builddir($sTempTargetDir); // Here is the directory
  65. }
  66. try
  67. {
  68. $this->DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks);
  69. }
  70. catch (Exception $e)
  71. {
  72. if ($sTempTargetDir != $sFinalTargetDir)
  73. {
  74. // Cleanup the temporary directory
  75. SetupUtils::rrmdir($sTempTargetDir);
  76. }
  77. throw $e;
  78. }
  79. if ($sTempTargetDir != $sFinalTargetDir)
  80. {
  81. // Move the results to the target directory
  82. SetupUtils::movedir($sTempTargetDir, $sFinalTargetDir);
  83. }
  84. }
  85. protected function DoCompile($sTempTargetDir, $sFinalTargetDir, $oP = null, $bUseSymbolicLinks = false)
  86. {
  87. $aAllClasses = array(); // flat list of classes
  88. // Determine the target modules for the MENUS
  89. //
  90. $aMenuNodes = array();
  91. $aMenusByModule = array();
  92. foreach ($this->oFactory->ListActiveChildNodes('menus', 'menu') as $oMenuNode)
  93. {
  94. $sMenuId = $oMenuNode->getAttribute('id');
  95. $aMenuNodes[$sMenuId] = $oMenuNode;
  96. $sModuleMenu = $oMenuNode->getAttribute('_created_in');
  97. $aMenusByModule[$sModuleMenu][] = $sMenuId;
  98. }
  99. // Determine the target module (exactly one!) for USER RIGHTS
  100. //
  101. $sUserRightsModule = '';
  102. $oUserRightsNode = $this->oFactory->GetNodes('user_rights')->item(0);
  103. if ($oUserRightsNode)
  104. {
  105. $sUserRightsModule = $oUserRightsNode->getAttribute('_created_in');
  106. $this->Log("User Rights module found: $sUserRightsModule");
  107. }
  108. // List root classes
  109. //
  110. $this->aRootClasses = array();
  111. foreach ($this->oFactory->ListRootClasses() as $oClass)
  112. {
  113. $this->Log("Root class (with child classes): ".$oClass->getAttribute('id'));
  114. $this->aRootClasses[$oClass->getAttribute('id')] = $oClass;
  115. }
  116. // Compile, module by module
  117. //
  118. $aModules = $this->oFactory->GetLoadedModules();
  119. foreach($aModules as $foo => $oModule)
  120. {
  121. $sModuleName = $oModule->GetName();
  122. $sModuleVersion = $oModule->GetVersion();
  123. $sModuleRootDir = $oModule->GetRootDir();
  124. if ($sModuleRootDir != '')
  125. {
  126. $sModuleRootDir = realpath($sModuleRootDir);
  127. $sRelativeDir = basename($sModuleRootDir);
  128. // Push the other module files
  129. SetupUtils::copydir($sModuleRootDir, $sTempTargetDir.'/'.$sRelativeDir, $bUseSymbolicLinks);
  130. }
  131. $sCompiledCode = '';
  132. $oConstants = $this->oFactory->ListConstants($sModuleName);
  133. if ($oConstants->length > 0)
  134. {
  135. foreach($oConstants as $oConstant)
  136. {
  137. $sCompiledCode .= $this->CompileConstant($oConstant)."\n";
  138. }
  139. }
  140. $oClasses = $this->oFactory->ListClasses($sModuleName);
  141. $iClassCount = $oClasses->length;
  142. if ($iClassCount == 0)
  143. {
  144. $this->Log("Found module without classes declared: $sModuleName");
  145. }
  146. else
  147. {
  148. foreach($oClasses as $oClass)
  149. {
  150. $sClass = $oClass->getAttribute("id");
  151. $aAllClasses[] = $sClass;
  152. try
  153. {
  154. $sCompiledCode .= $this->CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir, $oP);
  155. }
  156. catch (DOMFormatException $e)
  157. {
  158. throw new Exception("Failed to process class '$sClass', from '$sModuleRootDir': ".$e->getMessage());
  159. }
  160. }
  161. }
  162. if (!array_key_exists($sModuleName, $aMenusByModule))
  163. {
  164. $this->Log("Found module without menus declared: $sModuleName");
  165. }
  166. else
  167. {
  168. $sCompiledCode .=
  169. <<<EOF
  170. //
  171. // Menus
  172. //
  173. global \$__comp_menus__; // ensure that the global variable is indeed global !
  174. EOF;
  175. // Preliminary: determine parent menus not defined within the current module
  176. $aMenusToLoad = array();
  177. $aParentMenus = array();
  178. foreach($aMenusByModule[$sModuleName] as $sMenuId)
  179. {
  180. $oMenuNode = $aMenuNodes[$sMenuId];
  181. if ($sParent = $oMenuNode->GetChildText('parent', null))
  182. {
  183. $aMenusToLoad[] = $sParent;
  184. $aParentMenus[] = $sParent;
  185. }
  186. // Note: the order matters: the parents must be defined BEFORE
  187. $aMenusToLoad[] = $sMenuId;
  188. }
  189. $aMenusToLoad = array_unique($aMenusToLoad);
  190. foreach($aMenusToLoad as $sMenuId)
  191. {
  192. $oMenuNode = $aMenuNodes[$sMenuId];
  193. if ($oMenuNode->getAttribute("xsi:type") == 'MenuGroup')
  194. {
  195. // Note: this algorithm is wrong
  196. // 1 - the module may appear empty in the current module, while children are defined in other modules
  197. // 2 - check recursively that child nodes are not empty themselves
  198. // Future algorithm:
  199. // a- browse the modules and build the menu tree
  200. // b- browse the tree and blacklist empty menus
  201. // c- before compiling, discard if blacklisted
  202. if (!in_array($oMenuNode->getAttribute("id"), $aParentMenus))
  203. {
  204. // Discard empty menu groups
  205. continue;
  206. }
  207. }
  208. try
  209. {
  210. $sCompiledCode .= $this->CompileMenu($oMenuNode, $sTempTargetDir, $sFinalTargetDir, $sRelativeDir, $oP);
  211. }
  212. catch (DOMFormatException $e)
  213. {
  214. throw new Exception("Failed to process menu '$sMenuId', from '$sModuleRootDir': ".$e->getMessage());
  215. }
  216. }
  217. }
  218. // User rights
  219. //
  220. if ($sModuleName == $sUserRightsModule)
  221. {
  222. $sCompiledCode .= $this->CompileUserRights($oUserRightsNode);
  223. }
  224. // Create (overwrite if existing) the compiled file
  225. //
  226. if (strlen($sCompiledCode) > 0)
  227. {
  228. // We have compiled something: write the result file
  229. //
  230. $sResultFile = $sTempTargetDir.'/'.$sRelativeDir.'/model.'.$sModuleName.'.php';
  231. if (is_file($sResultFile))
  232. {
  233. $this->Log("Updating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  234. }
  235. else
  236. {
  237. $sResultDir = dirname($sResultFile);
  238. if (!is_dir($sResultDir))
  239. {
  240. $this->Log("Creating directory $sResultDir");
  241. mkdir($sResultDir, 0777, true);
  242. }
  243. $this->Log("Creating $sResultFile for module $sModuleName in version $sModuleVersion ($iClassCount classes)");
  244. }
  245. // Compile the module into a single file
  246. //
  247. $sId = $sModuleName;
  248. $sCurrDate = date(DATE_ISO8601);
  249. $sAuthor = 'iTop compiler';
  250. $sLicence = 'http://opensource.org/licenses/AGPL-3.0';
  251. $sFileHeader =
  252. <<<EOF
  253. <?php
  254. //
  255. // File generated by ... on the $sCurrDate
  256. // Please do not edit manually
  257. //
  258. /**
  259. * Classes and menus for $sModuleName (version $sModuleVersion)
  260. *
  261. * @author $sAuthor
  262. * @license $sLicence
  263. */
  264. EOF;
  265. $ret = file_put_contents($sResultFile, $sFileHeader.$sCompiledCode);
  266. if ($ret === false)
  267. {
  268. $iLen = strlen($sFileHeader.$sCompiledCode);
  269. $fFree = @disk_free_space(dirname($sResultFile));
  270. $aErr = error_get_last();
  271. throw new Exception("Failed to write '$sResultFile'. Last error: '{$aErr['message']}', content to write: $iLen bytes, available free space on disk: $fFree.");
  272. }
  273. }
  274. else
  275. {
  276. $this->Log("Compilation of module $sModuleName in version $sModuleVersion produced not code at all. No file written.");
  277. }
  278. } // foreach module
  279. // Compile the dictionaries -out of the modules
  280. //
  281. $sDictDir = $sTempTargetDir.'/dictionaries';
  282. if (!is_dir($sDictDir))
  283. {
  284. $this->Log("Creating directory $sDictDir");
  285. mkdir($sDictDir, 0777, true);
  286. }
  287. $oDictionaries = $this->oFactory->ListActiveChildNodes('dictionaries', 'dictionary');
  288. foreach($oDictionaries as $oDictionaryNode)
  289. {
  290. $this->CompileDictionary($oDictionaryNode, $sTempTargetDir, $sFinalTargetDir);
  291. }
  292. // Compile the branding
  293. //
  294. $oBrandingNode = $this->oFactory->GetNodes('branding')->item(0);
  295. $this->CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir);
  296. } // DoCompile()
  297. /**
  298. * Helper to form a valid ZList from the array built by GetNodeAsArrayOfItems()
  299. */
  300. protected function ArrayOfItemsToZList(&$aItems)
  301. {
  302. $aTransformed = array();
  303. foreach ($aItems as $key => $value)
  304. {
  305. if (is_null($value))
  306. {
  307. $aTransformed[] = $key;
  308. }
  309. else
  310. {
  311. if (is_array($value))
  312. {
  313. $this->ArrayOfItemsToZList($value);
  314. }
  315. $aTransformed[$key] = $value;
  316. }
  317. }
  318. $aItems = $aTransformed;
  319. }
  320. /**
  321. * Helper to format the flags for an attribute, in a given state
  322. * @param object $oAttNode DOM node containing the information to build the flags
  323. * Returns string PHP flags, based on the OPT_ATT_ constants, or empty (meaning 0, can be omitted)
  324. */
  325. protected function FlagsToPHP($oAttNode)
  326. {
  327. static $aNodeAttributeToFlag = array(
  328. 'mandatory' => 'OPT_ATT_MANDATORY',
  329. 'read_only' => 'OPT_ATT_READONLY',
  330. 'must_prompt' => 'OPT_ATT_MUSTPROMPT',
  331. 'must_change' => 'OPT_ATT_MUSTCHANGE',
  332. 'hidden' => 'OPT_ATT_HIDDEN',
  333. );
  334. $aFlags = array();
  335. foreach ($aNodeAttributeToFlag as $sNodeAttribute => $sFlag)
  336. {
  337. $bFlag = ($oAttNode->GetOptionalElement($sNodeAttribute) != null);
  338. if ($bFlag)
  339. {
  340. $aFlags[] = $sFlag;
  341. }
  342. }
  343. $sRes = implode(' | ', $aFlags);
  344. return $sRes;
  345. }
  346. /**
  347. * Helper to format the tracking level for linkset (direct or indirect attributes)
  348. * @param string $sTrackingLevel Value set from within the XML
  349. * Returns string PHP flag
  350. */
  351. protected function TrackingLevelToPHP($sAttType, $sTrackingLevel)
  352. {
  353. static $aXmlToPHP_Links = array(
  354. 'none' => 'LINKSET_TRACKING_NONE',
  355. 'list' => 'LINKSET_TRACKING_LIST',
  356. 'details' => 'LINKSET_TRACKING_DETAILS',
  357. 'all' => 'LINKSET_TRACKING_ALL',
  358. );
  359. static $aXmlToPHP_Others = array(
  360. 'none' => 'ATTRIBUTE_TRACKING_NONE',
  361. 'all' => 'ATTRIBUTE_TRACKING_ALL',
  362. );
  363. switch ($sAttType)
  364. {
  365. case 'AttributeLinkedSetIndirect':
  366. case 'AttributeLinkedSet':
  367. $aXmlToPHP = $aXmlToPHP_Links;
  368. break;
  369. default:
  370. $aXmlToPHP = $aXmlToPHP_Others;
  371. }
  372. if (!array_key_exists($sTrackingLevel, $aXmlToPHP))
  373. {
  374. throw new DOMFormatException("Tracking level: unknown value '$sTrackingLevel', expecting a value in {".implode(', ', array_keys($aXmlToPHP))."}");
  375. }
  376. return $aXmlToPHP[$sTrackingLevel];
  377. }
  378. /**
  379. * Helper to format the edit-mode for direct linkset
  380. * @param string $sEditMode Value set from within the XML
  381. * Returns string PHP flag
  382. */
  383. protected function EditModeToPHP($sEditMode)
  384. {
  385. static $aXmlToPHP = array(
  386. 'none' => 'LINKSET_EDITMODE_NONE',
  387. 'add_only' => 'LINKSET_EDITMODE_ADDONLY',
  388. 'actions' => 'LINKSET_EDITMODE_ACTIONS',
  389. 'in_place' => 'LINKSET_EDITMODE_INPLACE',
  390. 'add_remove' => 'LINKSET_EDITMODE_ADDREMOVE',
  391. );
  392. if (!array_key_exists($sEditMode, $aXmlToPHP))
  393. {
  394. throw new DOMFormatException("Edit mode: unknown value '$sEditMode'");
  395. }
  396. return $aXmlToPHP[$sEditMode];
  397. }
  398. /**
  399. * Format a path (file or url) as an absolute path or relative to the module or the app
  400. */
  401. protected function PathToPHP($sPath, $sModuleRelativeDir, $bIsUrl = false)
  402. {
  403. if ($sPath == '')
  404. {
  405. $sPHP = "''";
  406. }
  407. elseif (substr($sPath, 0, 2) == '$$')
  408. {
  409. // Absolute
  410. $sPHP = self::QuoteForPHP(substr($sPath, 2));
  411. }
  412. elseif (substr($sPath, 0, 1) == '$')
  413. {
  414. // Relative to the application
  415. if ($bIsUrl)
  416. {
  417. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP(substr($sPath, 1));
  418. }
  419. else
  420. {
  421. $sPHP = "APPROOT.".self::QuoteForPHP(substr($sPath, 1));
  422. }
  423. }
  424. else
  425. {
  426. // Relative to the module
  427. if ($bIsUrl)
  428. {
  429. $sPHP = "utils::GetAbsoluteUrlAppRoot().".self::QuoteForPHP($sModuleRelativeDir.''.$sPath);
  430. }
  431. else
  432. {
  433. $sPHP = "dirname(__FILE__).'/$sPath'";
  434. }
  435. }
  436. return $sPHP;
  437. }
  438. protected function GetPropString($oNode, $sTag, $sDefault = null)
  439. {
  440. $val = $oNode->GetChildText($sTag);
  441. if (is_null($val))
  442. {
  443. if (is_null($sDefault))
  444. {
  445. return null;
  446. }
  447. else
  448. {
  449. $val = $sDefault;
  450. }
  451. }
  452. return "'".$val."'";
  453. }
  454. protected function GetPropBoolean($oNode, $sTag, $bDefault = null)
  455. {
  456. $val = $oNode->GetChildText($sTag);
  457. if (is_null($val))
  458. {
  459. if (is_null($bDefault))
  460. {
  461. return null;
  462. }
  463. else
  464. {
  465. return $bDefault ? 'true' : 'false';
  466. }
  467. }
  468. return $val == 'true' ? 'true' : 'false';
  469. }
  470. protected function GetPropNumber($oNode, $sTag, $nDefault = null)
  471. {
  472. $val = $oNode->GetChildText($sTag);
  473. if (is_null($val))
  474. {
  475. if (is_null($nDefault))
  476. {
  477. return null;
  478. }
  479. else
  480. {
  481. $val = $nDefault;
  482. }
  483. }
  484. return (string)$val;
  485. }
  486. /**
  487. * Adds quotes and escape characters
  488. */
  489. protected function QuoteForPHP($sStr, $bSimpleQuotes = false)
  490. {
  491. if ($bSimpleQuotes)
  492. {
  493. $sEscaped = str_replace(array('\\', "'"), array('\\\\', "\\'"), $sStr);
  494. $sRet = "'$sEscaped'";
  495. }
  496. else
  497. {
  498. $sEscaped = str_replace(array('\\', '"', "\n"), array('\\\\', '\\"', '\\n'), $sStr);
  499. $sRet = '"'.$sEscaped.'"';
  500. }
  501. return $sRet;
  502. }
  503. protected function CompileConstant($oConstant)
  504. {
  505. $sName = $oConstant->getAttribute('id');
  506. $sType = $oConstant->getAttribute('xsi:type');
  507. $sText = $oConstant->GetText(null);
  508. switch ($sType)
  509. {
  510. case 'integer':
  511. if (is_null($sText))
  512. {
  513. // No data given => null
  514. $sScalar = 'null';
  515. }
  516. else
  517. {
  518. $sScalar = (string)(int)$sText;
  519. }
  520. break;
  521. case 'float':
  522. if (is_null($sText))
  523. {
  524. // No data given => null
  525. $sScalar = 'null';
  526. }
  527. else
  528. {
  529. $sScalar = (string)(float)$sText;
  530. }
  531. break;
  532. case 'bool':
  533. if (is_null($sText))
  534. {
  535. // No data given => null
  536. $sScalar = 'null';
  537. }
  538. else
  539. {
  540. $sScalar = ($sText == 'true') ? 'true' : 'false';
  541. }
  542. break;
  543. case 'string':
  544. default:
  545. $sScalar = $this->QuoteForPHP($sText, true);
  546. }
  547. $sPHPDefine = "define('$sName', $sScalar);";
  548. return $sPHPDefine;
  549. }
  550. protected function CompileClass($oClass, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  551. {
  552. $sClass = $oClass->getAttribute('id');
  553. $oProperties = $oClass->GetUniqueElement('properties');
  554. // Class caracteristics
  555. //
  556. $aClassParams = array();
  557. $aClassParams['category'] = $this->GetPropString($oProperties, 'category', '');
  558. $aClassParams['key_type'] = "'autoincrement'";
  559. if ((bool) $this->GetPropNumber($oProperties, 'is_link', 0))
  560. {
  561. $aClassParams['is_link'] = 'true';
  562. }
  563. if ($oNaming = $oProperties->GetOptionalElement('naming'))
  564. {
  565. $oNameAttributes = $oNaming->GetUniqueElement('attributes');
  566. $oAttributes = $oNameAttributes->getElementsByTagName('attribute');
  567. $aNameAttCodes = array();
  568. foreach($oAttributes as $oAttribute)
  569. {
  570. $aNameAttCodes[] = $oAttribute->getAttribute('id');
  571. }
  572. if (count($aNameAttCodes) > 1)
  573. {
  574. // New style...
  575. $sNameAttCode = "array('".implode("', '", $aNameAttCodes)."')";
  576. }
  577. elseif (count($aNameAttCodes) == 1)
  578. {
  579. // New style...
  580. $sNameAttCode = "'$aNameAttCodes[0]'";
  581. }
  582. else
  583. {
  584. $sNameAttCode = "''";
  585. }
  586. }
  587. else
  588. {
  589. $sNameAttCode = "''";
  590. }
  591. $aClassParams['name_attcode'] = $sNameAttCode;
  592. $oLifecycle = $oClass->GetOptionalElement('lifecycle');
  593. if ($oLifecycle)
  594. {
  595. $sStateAttCode = $oLifecycle->GetChildText('attribute');
  596. }
  597. else
  598. {
  599. $sStateAttCode = "";
  600. }
  601. $aClassParams['state_attcode'] = "'$sStateAttCode'";
  602. if ($oReconciliation = $oProperties->GetOptionalElement('reconciliation'))
  603. {
  604. $oReconcAttributes = $oReconciliation->getElementsByTagName('attribute');
  605. $aReconcAttCodes = array();
  606. foreach($oReconcAttributes as $oAttribute)
  607. {
  608. $aReconcAttCodes[] = $oAttribute->getAttribute('id');
  609. }
  610. $sReconcKeys = "array('".implode("', '", $aReconcAttCodes)."')";
  611. }
  612. else
  613. {
  614. $sReconcKeys = "array()";
  615. }
  616. $aClassParams['reconc_keys'] = $sReconcKeys;
  617. $aClassParams['db_table'] = $this->GetPropString($oProperties, 'db_table', '');
  618. $aClassParams['db_key_field'] = $this->GetPropString($oProperties, 'db_key_field', 'id');
  619. if (array_key_exists($sClass, $this->aRootClasses))
  620. {
  621. $sDefaultFinalClass = 'finalclass';
  622. }
  623. else
  624. {
  625. $sDefaultFinalClass = '';
  626. }
  627. $aClassParams['db_finalclass_field'] = $this->GetPropString($oProperties, 'db_final_class_field', $sDefaultFinalClass);
  628. if (($sDisplayTemplate = $oProperties->GetChildText('display_template')) && (strlen($sDisplayTemplate) > 0))
  629. {
  630. $sDisplayTemplate = $sModuleRelativeDir.'/'.$sDisplayTemplate;
  631. $aClassParams['display_template'] = "utils::GetAbsoluteUrlModulesRoot().'$sDisplayTemplate'";
  632. }
  633. $this->CompileFiles($oProperties, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, '');
  634. if (($sIcon = $oProperties->GetChildText('icon')) && (strlen($sIcon) > 0))
  635. {
  636. $sIcon = $sModuleRelativeDir.'/'.$sIcon;
  637. $aClassParams['icon'] = "utils::GetAbsoluteUrlModulesRoot().'$sIcon'";
  638. }
  639. $oOrder = $oProperties->GetOptionalElement('order');
  640. if ($oOrder)
  641. {
  642. $oColumnsNode = $oOrder->GetUniqueElement('columns');
  643. $oColumns = $oColumnsNode->getElementsByTagName('column');
  644. $aSortColumns = array();
  645. foreach($oColumns as $oColumn)
  646. {
  647. $aSortColumns[] = "'".$oColumn->getAttribute('id')."' => ".(($oColumn->getAttribute('ascending') == 'true') ? 'true' : 'false');
  648. }
  649. if (count($aSortColumns) > 0)
  650. {
  651. $aClassParams['order_by_default'] = "array(".implode(", ", $aSortColumns).")";
  652. }
  653. }
  654. if ($oIndexes = $oProperties->GetOptionalElement('indexes'))
  655. {
  656. $aIndexes = array();
  657. foreach($oIndexes->getElementsByTagName('index') as $oIndex)
  658. {
  659. $sIndexId = $oIndex->getAttribute('id');
  660. $oAttributes = $oIndex->GetUniqueElement('attributes');
  661. foreach($oAttributes->getElementsByTagName('attribute') as $oAttribute)
  662. {
  663. $aIndexes[$sIndexId][] = $oAttribute->getAttribute('id');
  664. }
  665. }
  666. $aClassParams['indexes'] = var_export($aIndexes, true);
  667. }
  668. // Finalize class params declaration
  669. //
  670. $aClassParamsPHP = array();
  671. foreach($aClassParams as $sKey => $sPHPValue)
  672. {
  673. $aClassParamsPHP[] = " '$sKey' => $sPHPValue,";
  674. }
  675. $sClassParams = implode("\n", $aClassParamsPHP);
  676. // Comment on top of the class declaration
  677. //
  678. $sCodeComment = $oProperties->GetChildText('comment');
  679. // Fields
  680. //
  681. $sAttributes = '';
  682. foreach($this->oFactory->ListFields($oClass) as $oField)
  683. {
  684. // $oField
  685. $sAttCode = $oField->getAttribute('id');
  686. $sAttType = $oField->getAttribute('xsi:type');
  687. $aDependencies = array();
  688. $oDependencies = $oField->GetOptionalElement('dependencies');
  689. if (!is_null($oDependencies))
  690. {
  691. $oDepNodes = $oDependencies->getElementsByTagName('attribute');
  692. foreach($oDepNodes as $oDepAttribute)
  693. {
  694. $aDependencies[] = "'".$oDepAttribute->getAttribute('id')."'";
  695. }
  696. }
  697. $sDependencies = 'array('.implode(', ', $aDependencies).')';
  698. $aParameters = array();
  699. if ($sAttType == 'AttributeLinkedSetIndirect')
  700. {
  701. $aParameters['linked_class'] = $this->GetPropString($oField, 'linked_class', '');
  702. $aParameters['ext_key_to_me'] = $this->GetPropString($oField, 'ext_key_to_me', '');
  703. $aParameters['ext_key_to_remote'] = $this->GetPropString($oField, 'ext_key_to_remote', '');
  704. $aParameters['allowed_values'] = 'null';
  705. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  706. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  707. $aParameters['duplicates'] = $this->GetPropBoolean($oField, 'duplicates', false);
  708. $aParameters['depends_on'] = $sDependencies;
  709. }
  710. elseif ($sAttType == 'AttributeLinkedSet')
  711. {
  712. $aParameters['linked_class'] = $this->GetPropString($oField, 'linked_class', '');
  713. $aParameters['ext_key_to_me'] = $this->GetPropString($oField, 'ext_key_to_me', '');
  714. $aParameters['count_min'] = $this->GetPropNumber($oField, 'count_min', 0);
  715. $aParameters['count_max'] = $this->GetPropNumber($oField, 'count_max', 0);
  716. $sEditMode = $oField->GetChildText('edit_mode');
  717. if (!is_null($sEditMode))
  718. {
  719. $aParameters['edit_mode'] = $this->EditModeToPHP($sEditMode);
  720. }
  721. if ($sOql = $oField->GetChildText('filter'))
  722. {
  723. $sEscapedOql = self::QuoteForPHP($sOql);
  724. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)";
  725. }
  726. else
  727. {
  728. $aParameters['allowed_values'] = 'null';
  729. }
  730. $aParameters['depends_on'] = $sDependencies;
  731. }
  732. elseif ($sAttType == 'AttributeExternalKey')
  733. {
  734. $aParameters['targetclass'] = $this->GetPropString($oField, 'target_class', '');
  735. // deprecated: $aParameters['jointype'] = 'null';
  736. if ($sOql = $oField->GetChildText('filter'))
  737. {
  738. $sEscapedOql = self::QuoteForPHP($sOql);
  739. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  740. }
  741. else
  742. {
  743. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  744. }
  745. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  746. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  747. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  748. $aParameters['depends_on'] = $sDependencies;
  749. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  750. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  751. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  752. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'select');
  753. }
  754. elseif ($sAttType == 'AttributeHierarchicalKey')
  755. {
  756. if ($sOql = $oField->GetChildText('filter'))
  757. {
  758. $sEscapedOql = self::QuoteForPHP($sOql);
  759. $aParameters['allowed_values'] = "new ValueSetObjects($sEscapedOql)"; // or "new ValueSetObjects('SELECT xxxx')"
  760. }
  761. else
  762. {
  763. $aParameters['allowed_values'] = 'null'; // or "new ValueSetObjects('SELECT xxxx')"
  764. }
  765. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  766. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  767. $aParameters['on_target_delete'] = $oField->GetChildText('on_target_delete');
  768. $aParameters['depends_on'] = $sDependencies;
  769. $aParameters['max_combo_length'] = $this->GetPropNumber($oField, 'max_combo_length');
  770. $aParameters['min_autocomplete_chars'] = $this->GetPropNumber($oField, 'min_autocomplete_chars');
  771. $aParameters['allow_target_creation'] = $this->GetPropBoolean($oField, 'allow_target_creation');
  772. }
  773. elseif ($sAttType == 'AttributeExternalField')
  774. {
  775. $aParameters['allowed_values'] = 'null';
  776. $aParameters['extkey_attcode'] = $this->GetPropString($oField, 'extkey_attcode', '');
  777. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode', '');
  778. }
  779. elseif ($sAttType == 'AttributeURL')
  780. {
  781. $aParameters['target'] = $this->GetPropString($oField, 'target', '');
  782. $aParameters['allowed_values'] = 'null';
  783. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  784. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  785. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  786. $aParameters['depends_on'] = $sDependencies;
  787. }
  788. elseif ($sAttType == 'AttributeEnum')
  789. {
  790. $oValues = $oField->GetUniqueElement('values');
  791. $oValueNodes = $oValues->getElementsByTagName('value');
  792. $aValues = array();
  793. foreach($oValueNodes as $oValue)
  794. {
  795. // new style... $aValues[] = self::QuoteForPHP($oValue->textContent);
  796. $aValues[] = $oValue->textContent;
  797. }
  798. // new style... $sValues = 'array('.implode(', ', $aValues).')';
  799. $sValues = '"'.implode(',', $aValues).'"';
  800. $aParameters['allowed_values'] = "new ValueSetEnum($sValues)";
  801. $aParameters['display_style'] = $this->GetPropString($oField, 'display_style', 'list');
  802. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  803. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  804. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  805. $aParameters['depends_on'] = $sDependencies;
  806. }
  807. elseif ($sAttType == 'AttributeBlob')
  808. {
  809. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  810. $aParameters['depends_on'] = $sDependencies;
  811. }
  812. elseif ($sAttType == 'AttributeStopWatch')
  813. {
  814. $oStates = $oField->GetUniqueElement('states');
  815. $oStateNodes = $oStates->getElementsByTagName('state');
  816. $aStates = array();
  817. foreach($oStateNodes as $oState)
  818. {
  819. $aStates[] = '"'.$oState->GetAttribute('id').'"';
  820. }
  821. $aParameters['states'] = 'array('.implode(', ', $aStates).')';
  822. $aParameters['goal_computing'] = $this->GetPropString($oField, 'goal', 'DefaultMetricComputer'); // Optional, no deadline by default
  823. $aParameters['working_time_computing'] = $this->GetPropString($oField, 'working_time', ''); // Blank (different than DefaultWorkingTimeComputer)
  824. $oThresholds = $oField->GetUniqueElement('thresholds');
  825. $oThresholdNodes = $oThresholds->getElementsByTagName('threshold');
  826. $aThresholds = array();
  827. foreach($oThresholdNodes as $oThreshold)
  828. {
  829. $iPercent = $this->GetPropNumber($oThreshold, 'percent');
  830. $oActions = $oThreshold->GetUniqueElement('actions');
  831. $oActionNodes = $oActions->getElementsByTagName('action');
  832. $aActions = array();
  833. foreach($oActionNodes as $oAction)
  834. {
  835. $oParams = $oAction->GetOptionalElement('params');
  836. $aActionParams = array();
  837. if ($oParams)
  838. {
  839. $oParamNodes = $oParams->getElementsByTagName('param');
  840. foreach($oParamNodes as $oParam)
  841. {
  842. $aActionParams[] = self::QuoteForPHP($oParam->textContent);
  843. }
  844. }
  845. $sActionParams = 'array('.implode(', ', $aActionParams).')';
  846. $sVerb = $this->GetPropString($oAction, 'verb');
  847. $aActions[] = "array('verb' => $sVerb, 'params' => $sActionParams)";
  848. }
  849. $sActions = 'array('.implode(', ', $aActions).')';
  850. $aThresholds[] = $iPercent." => array('percent' => $iPercent, 'actions' => $sActions)";
  851. }
  852. $aParameters['thresholds'] = 'array('.implode(', ', $aThresholds).')';
  853. }
  854. elseif ($sAttType == 'AttributeSubItem')
  855. {
  856. $aParameters['target_attcode'] = $this->GetPropString($oField, 'target_attcode');
  857. $aParameters['item_code'] = $this->GetPropString($oField, 'item_code');
  858. }
  859. else
  860. {
  861. $aParameters['allowed_values'] = 'null'; // or "new ValueSetEnum('SELECT xxxx')"
  862. $aParameters['sql'] = $this->GetPropString($oField, 'sql', '');
  863. $aParameters['default_value'] = $this->GetPropString($oField, 'default_value', '');
  864. $aParameters['is_null_allowed'] = $this->GetPropBoolean($oField, 'is_null_allowed', false);
  865. $aParameters['depends_on'] = $sDependencies;
  866. }
  867. // Optional parameters (more for historical reasons)
  868. // Added if present...
  869. //
  870. $aParameters['validation_pattern'] = $this->GetPropString($oField, 'validation_pattern');
  871. $aParameters['width'] = $this->GetPropNumber($oField, 'width');
  872. $aParameters['height'] = $this->GetPropNumber($oField, 'height');
  873. $aParameters['digits'] = $this->GetPropNumber($oField, 'digits');
  874. $aParameters['decimals'] = $this->GetPropNumber($oField, 'decimals');
  875. $aParameters['always_load_in_tables'] = $this->GetPropBoolean($oField, 'always_load_in_tables', false);
  876. $sTrackingLevel = $oField->GetChildText('tracking_level');
  877. if (!is_null($sTrackingLevel))
  878. {
  879. $aParameters['tracking_level'] = $this->TrackingLevelToPHP($sAttType, $sTrackingLevel);
  880. }
  881. $aParams = array();
  882. foreach($aParameters as $sKey => $sValue)
  883. {
  884. if (!is_null($sValue))
  885. {
  886. $aParams[] = '"'.$sKey.'"=>'.$sValue;
  887. }
  888. }
  889. $sParams = implode(', ', $aParams);
  890. $sAttributes .= " MetaModel::Init_AddAttribute(new $sAttType(\"$sAttCode\", array($sParams)));\n";
  891. }
  892. // Lifecycle
  893. //
  894. $sLifecycle = '';
  895. if ($oLifecycle)
  896. {
  897. $sLifecycle .= "\t\t// Lifecycle (status attribute: $sStateAttCode)\n";
  898. $sLifecycle .= "\t\t//\n";
  899. $oStimuli = $oLifecycle->GetUniqueElement('stimuli');
  900. foreach ($oStimuli->getElementsByTagName('stimulus') as $oStimulus)
  901. {
  902. $sStimulus = $oStimulus->getAttribute('id');
  903. $sStimulusClass = $oStimulus->getAttribute('xsi:type');
  904. $sLifecycle .= " MetaModel::Init_DefineStimulus(new ".$sStimulusClass."(\"".$sStimulus."\", array()));\n";
  905. }
  906. $oStates = $oLifecycle->GetUniqueElement('states');
  907. foreach ($oStates->getElementsByTagName('state') as $oState)
  908. {
  909. $sState = $oState->getAttribute('id');
  910. $oInitialStatePath = $oState->GetOptionalElement('initial_state_path');
  911. if ($oInitialStatePath)
  912. {
  913. $aInitialStatePath = array();
  914. foreach ($oInitialStatePath->getElementsByTagName('state_ref') as $oIntermediateState)
  915. {
  916. $aInitialStatePath[] = "'".$oIntermediateState->GetText()."'";
  917. }
  918. $sInitialStatePath = 'Array('.implode(', ', $aInitialStatePath).')';
  919. }
  920. $sLifecycle .= " MetaModel::Init_DefineState(\n";
  921. $sLifecycle .= " \"".$sState."\",\n";
  922. $sLifecycle .= " array(\n";
  923. $sLifecycle .= " \"attribute_inherit\" => '',\n";
  924. $sLifecycle .= " \"attribute_list\" => array(\n";
  925. $oFlags = $oState->GetUniqueElement('flags');
  926. foreach ($oFlags->getElementsByTagName('attribute') as $oAttributeNode)
  927. {
  928. $sFlags = $this->FlagsToPHP($oAttributeNode);
  929. if (strlen($sFlags) > 0)
  930. {
  931. $sAttCode = $oAttributeNode->GetAttribute('id');
  932. $sLifecycle .= " '$sAttCode' => $sFlags,\n";
  933. }
  934. }
  935. $sLifecycle .= " ),\n";
  936. if (!is_null($oInitialStatePath))
  937. {
  938. $sLifecycle .= " \"initial_state_path\" => $sInitialStatePath,\n";
  939. }
  940. $sLifecycle .= " )\n";
  941. $sLifecycle .= " );\n";
  942. $oTransitions = $oState->GetUniqueElement('transitions');
  943. foreach ($oTransitions->getElementsByTagName('transition') as $oTransition)
  944. {
  945. $sStimulus = $oTransition->GetChildText('stimulus');
  946. $sTargetState = $oTransition->GetChildText('target');
  947. $oActions = $oTransition->GetUniqueElement('actions');
  948. $aVerbs = array();
  949. foreach ($oActions->getElementsByTagName('action') as $oAction)
  950. {
  951. $sVerb = $oAction->GetChildText('verb');
  952. $aVerbs[] = "'$sVerb'";
  953. }
  954. $sActions = implode(', ', $aVerbs);
  955. $sLifecycle .= " MetaModel::Init_DefineTransition(\"$sState\", \"$sStimulus\", array(\"target_state\"=>\"$sTargetState\", \"actions\"=>array($sActions), \"user_restriction\"=>null));\n";
  956. }
  957. }
  958. }
  959. // ZLists
  960. //
  961. $aListRef = array(
  962. 'details' => 'details',
  963. 'standard_search' => 'search',
  964. 'list' => 'list'
  965. );
  966. $oPresentation = $oClass->GetUniqueElement('presentation');
  967. $sZlists = '';
  968. foreach ($aListRef as $sListCode => $sListTag)
  969. {
  970. $oListNode = $oPresentation->GetOptionalElement($sListTag);
  971. if ($oListNode)
  972. {
  973. $aAttributes = $oListNode->GetNodeAsArrayOfItems();
  974. $this->ArrayOfItemsToZList($aAttributes);
  975. $sZAttributes = var_export($aAttributes, true);
  976. $sZlists .= " MetaModel::Init_SetZListItems('$sListCode', $sZAttributes);\n";
  977. }
  978. }
  979. // Methods
  980. $sMethods = "";
  981. $oMethods = $oClass->GetUniqueElement('methods');
  982. foreach($oMethods->getElementsByTagName('method') as $oMethod)
  983. {
  984. $sMethodCode = $oMethod->GetChildText('code');
  985. if ($sMethodComment = $oMethod->GetChildText('comment', null))
  986. {
  987. $sMethods .= "\n\t$sMethodComment\n".$sMethodCode."\n";
  988. }
  989. else
  990. {
  991. $sMethods .= "\n\n".$sMethodCode."\n";
  992. }
  993. }
  994. // Let's make the whole class declaration
  995. //
  996. $sPHP = "\n\n$sCodeComment\n";
  997. $sParentClass = $oClass->GetChildText('php_parent');
  998. $oPhpParent = $oClass->GetUniqueElement('php_parent', false);
  999. if ($oPhpParent)
  1000. {
  1001. $sParentClass = $oPhpParent->GetChildText('name', '');
  1002. if ($sParentClass == '')
  1003. {
  1004. throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', missing required tag 'name' under 'php_parent'.");
  1005. }
  1006. $sIncludeFile = $oPhpParent->GetChildText('file', '');
  1007. if ($sIncludeFile != '')
  1008. {
  1009. $sPHP .= "\nrequire_once('$sIncludeFile'); // Implementation of the class $sParentClass\n";
  1010. }
  1011. //TODO fix this !!!
  1012. // $sFullPath = $this->sSourceDir.'/'.$sModuleRelativeDir.'/'.$sIncludeFile;
  1013. // if (!file_exists($sFullPath))
  1014. // {
  1015. // throw new Exception("Failed to process class '".$oClass->getAttribute('id')."', from '$sModuleRelativeDir'. The required include file: '$sFullPath' does not exist.");
  1016. // }
  1017. }
  1018. else
  1019. {
  1020. $sParentClass = $oClass->GetChildText('parent', 'DBObject');
  1021. }
  1022. if ($oProperties->GetChildText('abstract') == 'true')
  1023. {
  1024. $sPHP .= 'abstract class '.$oClass->getAttribute('id');
  1025. }
  1026. else
  1027. {
  1028. $sPHP .= 'class '.$oClass->getAttribute('id');
  1029. }
  1030. $sPHP .= " extends $sParentClass\n";
  1031. $sPHP .=
  1032. <<<EOF
  1033. {
  1034. public static function Init()
  1035. {
  1036. \$aParams = array
  1037. (
  1038. $sClassParams
  1039. );
  1040. MetaModel::Init_Params(\$aParams);
  1041. MetaModel::Init_InheritAttributes();
  1042. $sAttributes
  1043. $sLifecycle
  1044. $sZlists
  1045. }
  1046. $sMethods
  1047. }
  1048. EOF;
  1049. return $sPHP;
  1050. }// function CompileClass()
  1051. protected function CompileMenu($oMenu, $sTempTargetDir, $sFinalTargetDir, $sModuleRelativeDir, $oP)
  1052. {
  1053. $this->CompileFiles($oMenu, $sTempTargetDir.'/'.$sModuleRelativeDir, $sFinalTargetDir.'/'.$sModuleRelativeDir, $sModuleRelativeDir);
  1054. $sMenuId = $oMenu->getAttribute("id");
  1055. $sMenuClass = $oMenu->getAttribute("xsi:type");
  1056. $sParent = $oMenu->GetChildText('parent', null);
  1057. if ($sParent)
  1058. {
  1059. $sParentSpec = "\$__comp_menus__['$sParent']->GetIndex()";
  1060. }
  1061. else
  1062. {
  1063. $sParentSpec = '-1';
  1064. }
  1065. $fRank = (float) $oMenu->GetChildText('rank');
  1066. switch($sMenuClass)
  1067. {
  1068. case 'WebPageMenuNode':
  1069. $sUrl = $oMenu->GetChildText('url');
  1070. $sUrlSpec = $this->PathToPHP($sUrl, $sModuleRelativeDir, true /* Url */);
  1071. $sNewMenu = "new WebPageMenuNode('$sMenuId', $sUrlSpec, $sParentSpec, $fRank);";
  1072. break;
  1073. case 'DashboardMenuNode':
  1074. $sTemplateFile = $oMenu->GetChildText('definition_file', '');
  1075. if ($sTemplateFile != '')
  1076. {
  1077. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1078. }
  1079. else
  1080. {
  1081. $oDashboardDefinition = $oMenu->GetOptionalElement('definition');
  1082. if ($oDashboardDefinition == null)
  1083. {
  1084. throw(new DOMFormatException('Missing definition for Dashboard menu "'.$sMenuId.'" expecting either a tag "definition_file" or "definition".'));
  1085. }
  1086. $sFileName = strtolower(str_replace(array(':', '/', '\\', '*'), '_', $sMenuId)).'_dashboard_menu.xml';
  1087. $sTemplateSpec = $this->PathToPHP($sFileName, $sModuleRelativeDir);
  1088. $oXMLDoc = new DOMDocument('1.0', 'UTF-8');
  1089. $oXMLDoc->formatOutput = true; // indent (must be loaded with option LIBXML_NOBLANKS)
  1090. $oXMLDoc->preserveWhiteSpace = true; // otherwise the formatOutput option would have no effect
  1091. $oRootNode = $oXMLDoc->createElement('dashboard'); // make sure that the document is not empty
  1092. $oRootNode->setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance");
  1093. $oXMLDoc->appendChild($oRootNode);
  1094. foreach($oDashboardDefinition->childNodes as $oNode)
  1095. {
  1096. $oDefNode = $oXMLDoc->importNode($oNode, true); // layout, cells, etc Nodes and below
  1097. $oRootNode->appendChild($oDefNode);
  1098. }
  1099. $oXMLDoc->save($sTempTargetDir.'/'.$sModuleRelativeDir.'/'.$sFileName);
  1100. }
  1101. $sNewMenu = "new DashboardMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1102. break;
  1103. case 'ShortcutContainerMenuNode':
  1104. $sNewMenu = "new ShortcutContainerMenuNode('$sMenuId', $sParentSpec, $fRank);";
  1105. break;
  1106. case 'OQLMenuNode':
  1107. $sOQL = self::QuoteForPHP($oMenu->GetChildText('oql'));
  1108. $bSearch = ($oMenu->GetChildText('do_search') == '1') ? 'true' : 'false';
  1109. $sNewMenu = "new OQLMenuNode('$sMenuId', $sOQL, $sParentSpec, $fRank, $bSearch);";
  1110. break;
  1111. case 'NewObjectMenuNode':
  1112. $sClass = $oMenu->GetChildText('class');
  1113. $sNewMenu = "new NewObjectMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1114. break;
  1115. case 'SearchMenuNode':
  1116. $sClass = $oMenu->GetChildText('class');
  1117. $sNewMenu = "new SearchMenuNode('$sMenuId', '$sClass', $sParentSpec, $fRank);";
  1118. break;
  1119. case 'TemplateMenuNode':
  1120. $sTemplateFile = $oMenu->GetChildText('template_file');
  1121. $sTemplateSpec = $this->PathToPHP($sTemplateFile, $sModuleRelativeDir);
  1122. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1123. {
  1124. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1125. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1126. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1127. if ($sEnableStimulus != null)
  1128. {
  1129. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1130. }
  1131. else
  1132. {
  1133. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1134. }
  1135. }
  1136. else
  1137. {
  1138. $sNewMenu = "new TemplateMenuNode('$sMenuId', $sTemplateSpec, $sParentSpec, $fRank);";
  1139. }
  1140. break;
  1141. case 'MenuGroup':
  1142. default:
  1143. if ($sEnableClass = $oMenu->GetChildText('enable_class'))
  1144. {
  1145. $sEnableAction = $oMenu->GetChildText('enable_action', 'null');
  1146. $sEnablePermission = $oMenu->GetChildText('enable_permission', 'UR_ALLOWED_YES');
  1147. $sEnableStimulus = $oMenu->GetChildText('enable_stimulus');
  1148. if ($sEnableStimulus != null)
  1149. {
  1150. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission, '$sEnableStimulus');";
  1151. }
  1152. else
  1153. {
  1154. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank, '$sEnableClass', $sEnableAction, $sEnablePermission);";
  1155. }
  1156. }
  1157. else
  1158. {
  1159. $sNewMenu = "new $sMenuClass('$sMenuId', $fRank);";
  1160. }
  1161. }
  1162. $sIndent = '';
  1163. $aPHPMenu = array("\$__comp_menus__['$sMenuId'] = $sNewMenu");
  1164. if ($sAutoReload = $oMenu->GetChildText('auto_reload'))
  1165. {
  1166. $sAutoReload = self::QuoteForPHP($sAutoReload);
  1167. $aPHPMenu[] = "\$__comp_menus__['$sMenuId']->SetParameters(array('auto_reload' => $sAutoReload));";
  1168. }
  1169. $sAdminOnly = $oMenu->GetChildText('enable_admin_only');
  1170. if ($sAdminOnly && ($sAdminOnly == '1'))
  1171. {
  1172. $sPHP = $sIndent."if (UserRights::IsAdministrator())\n";
  1173. $sPHP .= $sIndent."{\n";
  1174. foreach($aPHPMenu as $sPHPLine)
  1175. {
  1176. $sPHP .= $sIndent." $sPHPLine\n";
  1177. }
  1178. $sPHP .= $sIndent."}\n";
  1179. }
  1180. else
  1181. {
  1182. $sPHP = '';
  1183. foreach($aPHPMenu as $sPHPLine)
  1184. {
  1185. $sPHP .= $sIndent.$sPHPLine."\n";
  1186. }
  1187. }
  1188. return $sPHP;
  1189. } // function CompileMenu
  1190. /**
  1191. * Helper to compute the grant, taking any existing grant into account
  1192. */
  1193. protected function CumulateGrant(&$aGrants, $sKey, $bGrant)
  1194. {
  1195. if (isset($aGrants[$sKey]))
  1196. {
  1197. if (!$bGrant)
  1198. {
  1199. $aGrants[$sKey] = false;
  1200. }
  1201. }
  1202. else
  1203. {
  1204. $aGrants[$sKey] = $bGrant;
  1205. }
  1206. }
  1207. protected function CompileUserRights($oUserRightsNode)
  1208. {
  1209. static $aActionsInShort = array(
  1210. 'read' => 'r',
  1211. 'bulk read' => 'br',
  1212. 'write' => 'w',
  1213. 'bulk write' => 'bw',
  1214. 'delete' => 'd',
  1215. 'bulk delete' => 'bd',
  1216. );
  1217. // Preliminary : create an index so that links will be taken into account implicitely
  1218. $aLinkToClasses = array();
  1219. $oClasses = $this->oFactory->ListAllClasses();
  1220. foreach($oClasses as $oClass)
  1221. {
  1222. $bIsLink = false;
  1223. $oProperties = $oClass->GetOptionalElement('properties');
  1224. if ($oProperties)
  1225. {
  1226. $bIsLink = (bool) $this->GetPropNumber($oProperties, 'is_link', 0);
  1227. }
  1228. if ($bIsLink)
  1229. {
  1230. foreach($this->oFactory->ListFields($oClass) as $oField)
  1231. {
  1232. $sAttType = $oField->getAttribute('xsi:type');
  1233. if (($sAttType == 'AttributeExternalKey') || ($sAttType == 'AttributeHierarchicalKey'))
  1234. {
  1235. $sOnTargetDel = $oField->GetChildText('on_target_delete');
  1236. if ($sOnTargetDel == 'DEL_AUTO')
  1237. {
  1238. $sTargetClass = $oField->GetChildText('target_class');
  1239. $aLinkToClasses[$oClass->getAttribute('id')][] = $sTargetClass;
  1240. }
  1241. }
  1242. }
  1243. }
  1244. }
  1245. // Groups
  1246. //
  1247. $aGroupClasses = array();
  1248. $oGroups = $oUserRightsNode->GetUniqueElement('groups');
  1249. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1250. {
  1251. $sGroupId = $oGroup->getAttribute("id");
  1252. $aClasses = array();
  1253. $oClasses = $oGroup->GetUniqueElement('classes');
  1254. foreach($oClasses->getElementsByTagName('class') as $oClass)
  1255. {
  1256. $sClass = $oClass->getAttribute("id");
  1257. $aClasses[] = $sClass;
  1258. //$bSubclasses = $this->GetPropBoolean($oClass, 'subclasses', true);
  1259. //if ($bSubclasses)...
  1260. }
  1261. $aGroupClasses[$sGroupId] = $aClasses;
  1262. }
  1263. // Profiles and grants
  1264. //
  1265. $aProfiles = array();
  1266. // Hardcode the administrator profile
  1267. $aProfiles[1] = array(
  1268. 'name' => 'Administrator',
  1269. 'description' => 'Has the rights on everything (bypassing any control)'
  1270. );
  1271. $aGrants = array();
  1272. $oProfiles = $oUserRightsNode->GetUniqueElement('profiles');
  1273. foreach($oProfiles->getElementsByTagName('profile') as $oProfile)
  1274. {
  1275. $iProfile = $oProfile->getAttribute("id");
  1276. $sName = $oProfile->GetChildText('name');
  1277. $sDescription = $oProfile->GetChildText('description');
  1278. $oGroups = $oProfile->GetUniqueElement('groups');
  1279. foreach($oGroups->getElementsByTagName('group') as $oGroup)
  1280. {
  1281. $sGroupId = $oGroup->getAttribute("id");
  1282. $aActions = array();
  1283. $oActions = $oGroup->GetUniqueElement('actions');
  1284. foreach($oActions->getElementsByTagName('action') as $oAction)
  1285. {
  1286. $sAction = $oAction->getAttribute("id");
  1287. $sType = $oAction->getAttribute("xsi:type");
  1288. $sGrant = $oAction->GetText();
  1289. $bGrant = ($sGrant == 'allow');
  1290. if ($sGroupId == '*')
  1291. {
  1292. $aGrantClasses = array('*');
  1293. }
  1294. else
  1295. {
  1296. $aGrantClasses = $aGroupClasses[$sGroupId];
  1297. }
  1298. foreach ($aGrantClasses as $sClass)
  1299. {
  1300. if ($sType == 'stimulus')
  1301. {
  1302. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_s_'.$sAction, $bGrant);
  1303. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_s_'.$sAction, $bGrant); // subclasses inherit this grant
  1304. }
  1305. else
  1306. {
  1307. $sAction = $aActionsInShort[$sType];
  1308. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'_'.$sAction, $bGrant);
  1309. $this->CumulateGrant($aGrants, $iProfile.'_'.$sClass.'+_'.$sAction, $bGrant); // subclasses inherit this grant
  1310. }
  1311. }
  1312. }
  1313. }
  1314. $aProfiles[$iProfile] = array(
  1315. 'name' => $sName,
  1316. 'description' => $sDescription
  1317. );
  1318. }
  1319. $sProfiles = var_export($aProfiles, true);
  1320. $sGrants = var_export($aGrants, true);
  1321. $sLinkToClasses = var_export($aLinkToClasses, true);
  1322. $sPHP =
  1323. <<<EOF
  1324. //
  1325. // List of constant profiles
  1326. // - used by the class URP_Profiles at setup (create/update/delete records)
  1327. // - used by the addon UserRightsProfile to determine user rights
  1328. //
  1329. class ProfilesConfig
  1330. {
  1331. protected static \$aPROFILES = $sProfiles;
  1332. protected static \$aGRANTS = $sGrants;
  1333. protected static \$aLINKTOCLASSES = $sLinkToClasses;
  1334. // Now replaced by MetaModel::GetLinkClasses (working with 1.x)
  1335. // This function could be deprecated
  1336. public static function GetLinkClasses()
  1337. {
  1338. return self::\$aLINKTOCLASSES;
  1339. }
  1340. public static function GetProfileActionGrant(\$iProfileId, \$sClass, \$sAction)
  1341. {
  1342. // Search for a grant, starting from the most explicit declaration,
  1343. // then searching for less and less explicit declaration
  1344. // 1 - The class itself
  1345. //
  1346. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_'.\$sAction;
  1347. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1348. {
  1349. return self::\$aGRANTS[\$sGrantKey];
  1350. }
  1351. // 2 - The parent classes, up to the root class
  1352. //
  1353. foreach (MetaModel::EnumParentClasses(\$sClass, ENUM_PARENT_CLASSES_EXCLUDELEAF, false /*bRootFirst*/) as \$sParent)
  1354. {
  1355. \$sGrantKey = \$iProfileId.'_'.\$sParent.'+_'.\$sAction;
  1356. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1357. {
  1358. return self::\$aGRANTS[\$sGrantKey];
  1359. }
  1360. }
  1361. // 3 - The related classes (if the current is an N-N link with AUTO_DEL)
  1362. //
  1363. if (array_key_exists(\$sClass, self::\$aLINKTOCLASSES))
  1364. {
  1365. // Get the grant for the remote classes. The resulting grant is:
  1366. // - One YES => YES
  1367. // - 100% undefined => undefined
  1368. // - otherwise => NO
  1369. //
  1370. // Having write allowed on the remote class implies write + delete on the N-N link class
  1371. if (\$sAction == 'd')
  1372. {
  1373. \$sRemoteAction = 'w';
  1374. }
  1375. elseif (\$sAction == 'bd')
  1376. {
  1377. \$sRemoteAction = 'bw';
  1378. }
  1379. else
  1380. {
  1381. \$sRemoteAction = \$sAction;
  1382. }
  1383. foreach (self::\$aLINKTOCLASSES[\$sClass] as \$sRemoteClass)
  1384. {
  1385. \$bUndefined = true;
  1386. \$bGrant = self::GetProfileActionGrant(\$iProfileId, \$sRemoteClass, \$sAction);
  1387. if (\$bGrant === true)
  1388. {
  1389. return true;
  1390. }
  1391. if (\$bGrant === false)
  1392. {
  1393. \$bUndefined = false;
  1394. }
  1395. }
  1396. if (!\$bUndefined)
  1397. {
  1398. return false;
  1399. }
  1400. }
  1401. // 4 - All
  1402. //
  1403. \$sGrantKey = \$iProfileId.'_*_'.\$sAction;
  1404. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1405. {
  1406. return self::\$aGRANTS[\$sGrantKey];
  1407. }
  1408. // Still undefined for this class
  1409. return null;
  1410. }
  1411. public static function GetProfileStimulusGrant(\$iProfileId, \$sClass, \$sStimulus)
  1412. {
  1413. \$sGrantKey = \$iProfileId.'_'.\$sClass.'_s_'.\$sStimulus;
  1414. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1415. {
  1416. return self::\$aGRANTS[\$sGrantKey];
  1417. }
  1418. \$sGrantKey = \$iProfileId.'_*_s_'.\$sStimulus;
  1419. if (isset(self::\$aGRANTS[\$sGrantKey]))
  1420. {
  1421. return self::\$aGRANTS[\$sGrantKey];
  1422. }
  1423. return null;
  1424. }
  1425. // returns an array of id => array of column => php value(so-called "real value")
  1426. public static function GetProfilesValues()
  1427. {
  1428. return self::\$aPROFILES;
  1429. }
  1430. }
  1431. EOF;
  1432. return $sPHP;
  1433. } // function CompileUserRights
  1434. protected function CompileDictionary($oDictionaryNode, $sTempTargetDir, $sFinalTargetDir)
  1435. {
  1436. $sLang = $oDictionaryNode->getAttribute('id');
  1437. $sEnglishLanguageDesc = $oDictionaryNode->GetChildText('english_description');
  1438. $sLocalizedLanguageDesc = $oDictionaryNode->GetChildText('localized_description');
  1439. $aEntriesPHP = array();
  1440. $oEntries = $oDictionaryNode->GetUniqueElement('entries');
  1441. foreach($oEntries->getElementsByTagName('entry') as $oEntry)
  1442. {
  1443. $sStringCode = $oEntry->getAttribute('id');
  1444. $sValue = $oEntry->GetText();
  1445. $aEntriesPHP[] = "\t'$sStringCode' => ".self::QuoteForPHP($sValue, true).",";
  1446. }
  1447. $sEntriesPHP = implode("\n", $aEntriesPHP);
  1448. $sEscEnglishLanguageDesc = self::QuoteForPHP($sEnglishLanguageDesc);
  1449. $sEscLocalizedLanguageDesc = self::QuoteForPHP($sLocalizedLanguageDesc);
  1450. $sPHPDict =
  1451. <<<EOF
  1452. <?php
  1453. //
  1454. // Dictionary built by the compiler for the language "$sLang"
  1455. //
  1456. Dict::Add('$sLang', $sEscEnglishLanguageDesc, $sEscLocalizedLanguageDesc, array(
  1457. $sEntriesPHP
  1458. ));
  1459. EOF;
  1460. $sSafeLang = str_replace(' ', '-', strtolower(trim($sLang)));
  1461. $sDictFile = $sTempTargetDir.'/dictionaries/'.$sSafeLang.'.dict.php';
  1462. file_put_contents($sDictFile, $sPHPDict);
  1463. }
  1464. // Transform the file references into the corresponding filename (and create the file in the relevant directory)
  1465. //
  1466. protected function CompileFiles($oNode, $sTempTargetDir, $sFinalTargetDir, $sRelativePath)
  1467. {
  1468. $oFileRefs = $oNode->GetNodes(".//fileref");
  1469. foreach ($oFileRefs as $oFileRef)
  1470. {
  1471. $sFileId = $oFileRef->getAttribute('ref');
  1472. if ($sFileId !== '')
  1473. {
  1474. $oNodes = $this->oFactory->GetNodes("/itop_design/files/file[@id='$sFileId']");
  1475. if ($oNodes->length == 0)
  1476. {
  1477. throw new DOMFormatException('Could not find the file with ref '.$sFileId);
  1478. }
  1479. $sName = $oNodes->item(0)->GetChildText('name');
  1480. $sData = base64_decode($oNodes->item(0)->GetChildText('data'));
  1481. $aPathInfo = pathinfo($sName);
  1482. $sFile = $sFileId.'.'.$aPathInfo['extension'];
  1483. $sFilePath = $sTempTargetDir.'/images/'.$sFile;
  1484. @mkdir($sTempTargetDir.'/images');
  1485. file_put_contents($sFilePath, $sData);
  1486. if (!file_exists($sFilePath))
  1487. {
  1488. throw new Exception('Could not write icon file '.$sFilePath);
  1489. }
  1490. $oParentNode = $oFileRef->parentNode;
  1491. $oParentNode->removeChild($oFileRef);
  1492. $oTextNode = $oParentNode->ownerDocument->createTextNode($sRelativePath.'/images/'.$sFile);
  1493. $oParentNode->appendChild($oTextNode);
  1494. }
  1495. }
  1496. }
  1497. protected function CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, $sNodeName, $sTargetFile)
  1498. {
  1499. if (($sIcon = $oBrandingNode->GetChildText($sNodeName)) && (strlen($sIcon) > 0))
  1500. {
  1501. if (substr($sIcon, 0, 8) == 'branding')
  1502. {
  1503. $sSourceFile = $sTempTargetDir.'/'.$sIcon;
  1504. }
  1505. else
  1506. {
  1507. $sSourceFile = APPROOT.$sIcon;
  1508. }
  1509. $sTargetFile = $sTempTargetDir.'/branding/'.$sTargetFile.'.png';
  1510. if (!file_exists($sSourceFile))
  1511. {
  1512. throw new Exception("Branding $sNodeName: could not find the file $sIcon ($sSourceFile)");
  1513. }
  1514. // Note: rename makes sense only when the file given as a file ref, otherwise it may be an item of the application (thus it must be kept there)
  1515. copy($sSourceFile, $sTargetFile);
  1516. }
  1517. }
  1518. protected function CompileBranding($oBrandingNode, $sTempTargetDir, $sFinalTargetDir)
  1519. {
  1520. if ($oBrandingNode)
  1521. {
  1522. // Transform file refs into files in the images folder
  1523. SetupUtils::builddir($sTempTargetDir.'/branding');
  1524. $this->CompileFiles($oBrandingNode, $sTempTargetDir.'/branding', $sFinalTargetDir.'/branding', 'branding');
  1525. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'main_logo', 'main-logo');
  1526. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'login_logo', 'login-logo');
  1527. $this->CompileLogo($oBrandingNode, $sTempTargetDir, $sFinalTargetDir, 'portal_logo', 'portal-logo');
  1528. // Cleanup the images directory (made by CompileFiles)
  1529. SetupUtils::rrmdir($sTempTargetDir.'/branding/images');
  1530. }
  1531. }
  1532. }
  1533. ?>