compiler.class.inc.php 48 KB

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