applicationinstaller.class.inc.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once(APPROOT.'setup/parameters.class.inc.php');
  19. require_once(APPROOT.'setup/xmldataloader.class.inc.php');
  20. require_once(APPROOT.'setup/backup.class.inc.php');
  21. /**
  22. * The base class for the installation process.
  23. * The installation process is split into a sequence of unitary steps
  24. * for performance reasons (i.e; timeout, memory usage) and also in order
  25. * to provide some feedback about the progress of the installation.
  26. *
  27. * This class can be used for a step by step interactive installation
  28. * while displaying a progress bar, or in an unattended manner
  29. * (for example from the command line), to run all the steps
  30. * in one go.
  31. * @copyright Copyright (C) 2010-2017 Combodo SARL
  32. * @license http://opensource.org/licenses/AGPL-3.0
  33. */
  34. class ApplicationInstaller
  35. {
  36. const OK = 1;
  37. const ERROR = 2;
  38. const WARNING = 3;
  39. const INFO = 4;
  40. protected $oParams;
  41. protected static $bMetaModelStarted = false;
  42. public function __construct($oParams)
  43. {
  44. $this->oParams = $oParams;
  45. }
  46. /**
  47. * Runs all the installation steps in one go and directly outputs
  48. * some information about the progress and the success of the various
  49. * sequential steps.
  50. * @return boolean True if the installation was successful, false otherwise
  51. */
  52. public function ExecuteAllSteps()
  53. {
  54. $sStep = '';
  55. $sStepLabel = '';
  56. $iOverallStatus = self::OK;
  57. do
  58. {
  59. if($sStep != '')
  60. {
  61. echo "$sStepLabel\n";
  62. echo "Executing '$sStep'\n";
  63. }
  64. else
  65. {
  66. echo "Starting the installation...\n";
  67. }
  68. $aRes = $this->ExecuteStep($sStep);
  69. $sStep = $aRes['next-step'];
  70. $sStepLabel = $aRes['next-step-label'];
  71. switch($aRes['status'])
  72. {
  73. case self::OK;
  74. echo "Ok. ".$aRes['percentage-completed']." % done.\n";
  75. break;
  76. case self::ERROR:
  77. $iOverallStatus = self::ERROR;
  78. echo "Error: ".$aRes['message']."\n";
  79. break;
  80. case self::WARNING:
  81. $iOverallStatus = self::WARNING;
  82. echo "Warning: ".$aRes['message']."\n";
  83. echo $aRes['percentage-completed']." % done.\n";
  84. break;
  85. case self::INFO:
  86. echo "Info: ".$aRes['message']."\n";
  87. echo $aRes['percentage-completed']." % done.\n";
  88. break;
  89. }
  90. }
  91. while(($aRes['status'] != self::ERROR) && ($aRes['next-step'] != ''));
  92. return ($iOverallStatus == self::OK);
  93. }
  94. /**
  95. * Executes the next step of the installation and reports about the progress
  96. * and the next step to perform
  97. * @param string $sStep The identifier of the step to execute
  98. * @return hash An array of (status => , message => , percentage-completed => , next-step => , next-step-label => )
  99. */
  100. public function ExecuteStep($sStep = '')
  101. {
  102. try
  103. {
  104. switch($sStep)
  105. {
  106. case '':
  107. $aResult = array(
  108. 'status' => self::OK,
  109. 'message' => '',
  110. 'percentage-completed' => 0,
  111. 'next-step' => 'copy',
  112. 'next-step-label' => 'Copying data model files',
  113. );
  114. // Log the parameters...
  115. $oDoc = new DOMDocument('1.0', 'UTF-8');
  116. $oDoc->preserveWhiteSpace = false;
  117. $oDoc->formatOutput = true;
  118. $this->oParams->ToXML($oDoc, null, 'installation');
  119. $sXML = $oDoc->saveXML();
  120. $sSafeXml = preg_replace("|<pwd>([^<]*)</pwd>|", "<pwd>**removed**</pwd>", $sXML);
  121. SetupPage::log_info("======= Installation starts =======\nParameters:\n$sSafeXml\n");
  122. // Save the response file as a stand-alone file as well
  123. $sFileName = 'install-'.date('Y-m-d');
  124. $index = 0;
  125. while(file_exists(APPROOT.'log/'.$sFileName.'.xml'))
  126. {
  127. $index++;
  128. $sFileName = 'install-'.date('Y-m-d').'-'.$index;
  129. }
  130. file_put_contents(APPROOT.'log/'.$sFileName.'.xml', $sSafeXml);
  131. break;
  132. case 'copy':
  133. $aPreinstall = $this->oParams->Get('preinstall');
  134. $aCopies = $aPreinstall['copies'];
  135. $sReport = self::DoCopy($aCopies);
  136. $sReport = "Copying...";
  137. $aResult = array(
  138. 'status' => self::OK,
  139. 'message' => $sReport,
  140. );
  141. if (isset($aPreinstall['backup']))
  142. {
  143. $aResult['next-step'] = 'backup';
  144. $aResult['next-step-label'] = 'Performing a backup of the database';
  145. $aResult['percentage-completed'] = 20;
  146. }
  147. else
  148. {
  149. $aResult['next-step'] = 'compile';
  150. $aResult['next-step-label'] = 'Compiling the data model';
  151. $aResult['percentage-completed'] = 20;
  152. }
  153. break;
  154. case 'backup':
  155. $aPreinstall = $this->oParams->Get('preinstall');
  156. // __DB__-%Y-%m-%d
  157. $sDestination = $aPreinstall['backup']['destination'];
  158. $sSourceConfigFile = $aPreinstall['backup']['configuration_file'];
  159. $aDBParams = $this->oParams->Get('database');
  160. self::DoBackup($aDBParams['server'], $aDBParams['user'], $aDBParams['pwd'], $aDBParams['name'], $aDBParams['prefix'], $sDestination, $sSourceConfigFile);
  161. $aResult = array(
  162. 'status' => self::OK,
  163. 'message' => "Created backup",
  164. 'next-step' => 'compile',
  165. 'next-step-label' => 'Compiling the data model',
  166. 'percentage-completed' => 20,
  167. );
  168. break;
  169. case 'compile':
  170. $aSelectedModules = $this->oParams->Get('selected_modules');
  171. $sSourceDir = $this->oParams->Get('source_dir', 'datamodels/latest');
  172. $sExtensionDir = $this->oParams->Get('extensions_dir', 'extensions');
  173. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  174. if ($sTargetEnvironment == '')
  175. {
  176. $sTargetEnvironment = 'production';
  177. }
  178. $sTargetDir = 'env-'.$sTargetEnvironment;
  179. $bUseSymbolicLinks = false;
  180. $aMiscOptions = $this->oParams->Get('options', array());
  181. if (isset($aMiscOptions['symlinks']) && $aMiscOptions['symlinks'] )
  182. {
  183. if (function_exists('symlink'))
  184. {
  185. $bUseSymbolicLinks = true;
  186. SetupPage::log_info("Using symbolic links instead of copying data model files (for developers only!)");
  187. }
  188. else
  189. {
  190. SetupPage::log_info("Symbolic links (function symlinks) does not seem to be supported on this platform (OS/PHP version).");
  191. }
  192. }
  193. self::DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sTargetEnvironment, $bUseSymbolicLinks);
  194. $aResult = array(
  195. 'status' => self::OK,
  196. 'message' => '',
  197. 'next-step' => 'db-schema',
  198. 'next-step-label' => 'Updating database schema',
  199. 'percentage-completed' => 40,
  200. );
  201. break;
  202. case 'db-schema':
  203. $sMode = $this->oParams->Get('mode');
  204. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  205. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  206. if ($sTargetEnvironment == '')
  207. {
  208. $sTargetEnvironment = 'production';
  209. }
  210. $sTargetDir = 'env-'.$sTargetEnvironment;
  211. $aDBParams = $this->oParams->Get('database');
  212. $sDBServer = $aDBParams['server'];
  213. $sDBUser = $aDBParams['user'];
  214. $sDBPwd = $aDBParams['pwd'];
  215. $sDBName = $aDBParams['name'];
  216. $sDBPrefix = $aDBParams['prefix'];
  217. $bOldAddon = $this->oParams->Get('old_addon', false);
  218. self::DoUpdateDBSchema($sMode, $aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment, $bOldAddon);
  219. $aResult = array(
  220. 'status' => self::OK,
  221. 'message' => '',
  222. 'next-step' => 'after-db-create',
  223. 'next-step-label' => 'Creating profiles',
  224. 'percentage-completed' => 60,
  225. );
  226. break;
  227. case 'after-db-create':
  228. $sMode = $this->oParams->Get('mode');
  229. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  230. if ($sTargetEnvironment == '')
  231. {
  232. $sTargetEnvironment = 'production';
  233. }
  234. $sTargetDir = 'env-'.$sTargetEnvironment;
  235. $aDBParams = $this->oParams->Get('database');
  236. $sDBServer = $aDBParams['server'];
  237. $sDBUser = $aDBParams['user'];
  238. $sDBPwd = $aDBParams['pwd'];
  239. $sDBName = $aDBParams['name'];
  240. $sDBPrefix = $aDBParams['prefix'];
  241. $aAdminParams = $this->oParams->Get('admin_account');
  242. $sAdminUser = $aAdminParams['user'];
  243. $sAdminPwd = $aAdminParams['pwd'];
  244. $sAdminLanguage = $aAdminParams['language'];
  245. $sLanguage = $this->oParams->Get('language');
  246. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  247. $sDataModelVersion = $this->oParams->Get('datamodel_version', '0.0.0');
  248. $bOldAddon = $this->oParams->Get('old_addon', false);
  249. $sSourceDir = $this->oParams->Get('source_dir', '');
  250. self::AfterDBCreate($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser,
  251. $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sDataModelVersion, $sSourceDir);
  252. $aResult = array(
  253. 'status' => self::OK,
  254. 'message' => '',
  255. 'next-step' => 'load-data',
  256. 'next-step-label' => 'Loading data',
  257. 'percentage-completed' => 80,
  258. );
  259. break;
  260. case 'load-data':
  261. $aSelectedModules = $this->oParams->Get('selected_modules');
  262. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  263. $sTargetDir = 'env-'.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment);
  264. $aDBParams = $this->oParams->Get('database');
  265. $sDBServer = $aDBParams['server'];
  266. $sDBUser = $aDBParams['user'];
  267. $sDBPwd = $aDBParams['pwd'];
  268. $sDBName = $aDBParams['name'];
  269. $sDBPrefix = $aDBParams['prefix'];
  270. $bOldAddon = $this->oParams->Get('old_addon', false);
  271. $bSampleData = ($this->oParams->Get('sample_data', 0) == 1);
  272. self::DoLoadFiles($aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment, $bOldAddon, $bSampleData);
  273. $aResult = array(
  274. 'status' => self::INFO,
  275. 'message' => 'All data loaded',
  276. 'next-step' => 'create-config',
  277. 'next-step-label' => 'Creating the configuration File',
  278. 'percentage-completed' => 99,
  279. );
  280. break;
  281. case 'create-config':
  282. $sMode = $this->oParams->Get('mode');
  283. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  284. if ($sTargetEnvironment == '')
  285. {
  286. $sTargetEnvironment = 'production';
  287. }
  288. $sTargetDir = 'env-'.$sTargetEnvironment;
  289. $aDBParams = $this->oParams->Get('database');
  290. $sDBServer = $aDBParams['server'];
  291. $sDBUser = $aDBParams['user'];
  292. $sDBPwd = $aDBParams['pwd'];
  293. $sDBName = $aDBParams['name'];
  294. $sDBPrefix = $aDBParams['prefix'];
  295. $sUrl = $this->oParams->Get('url', '');
  296. $sGraphvizPath = $this->oParams->Get('graphviz_path', '');
  297. $sLanguage = $this->oParams->Get('language', '');
  298. $aSelectedModuleCodes = $this->oParams->Get('selected_modules', array());
  299. $aSelectedExtensionCodes = $this->oParams->Get('selected_extensions', array());
  300. $bOldAddon = $this->oParams->Get('old_addon', false);
  301. $sSourceDir = $this->oParams->Get('source_dir', '');
  302. $sPreviousConfigFile = $this->oParams->Get('previous_configuration_file', '');
  303. $sDataModelVersion = $this->oParams->Get('datamodel_version', '0.0.0');
  304. self::DoCreateConfig($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModuleCodes, $aSelectedExtensionCodes, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile, $sDataModelVersion, $sGraphvizPath);
  305. $aResult = array(
  306. 'status' => self::INFO,
  307. 'message' => 'Configuration file created',
  308. 'next-step' => '',
  309. 'next-step-label' => 'Completed',
  310. 'percentage-completed' => 100,
  311. );
  312. break;
  313. default:
  314. $aResult = array(
  315. 'status' => self::ERROR,
  316. 'message' => '',
  317. 'next-step' => '',
  318. 'next-step-label' => "Unknown setup step '$sStep'.",
  319. 'percentage-completed' => 100,
  320. );
  321. }
  322. }
  323. catch(Exception $e)
  324. {
  325. $aResult = array(
  326. 'status' => self::ERROR,
  327. 'message' => $e->getMessage(),
  328. 'next-step' => '',
  329. 'next-step-label' => '',
  330. 'percentage-completed' => 100,
  331. );
  332. SetupPage::log_error('An exception occurred: '.$e->getMessage().' at line '.$e->getLine().' in file '.$e->getFile());
  333. $idx = 0;
  334. // Log the call stack, but not the parameters since they may contain passwords or other sensitive data
  335. SetupPage::log("Call stack:");
  336. foreach($e->getTrace() as $aTrace)
  337. {
  338. $sLine = empty($aTrace['line']) ? "" : $aTrace['line'];
  339. $sFile = empty($aTrace['file']) ? "" : $aTrace['file'];
  340. $sClass = empty($aTrace['class']) ? "" : $aTrace['class'];
  341. $sType = empty($aTrace['type']) ? "" : $aTrace['type'];
  342. $sFunction = empty($aTrace['function']) ? "" : $aTrace['function'];
  343. $sVerb = empty($sClass) ? $sFunction : "$sClass{$sType}$sFunction";
  344. SetupPage::log("#$idx $sFile($sLine): $sVerb(...)");
  345. $idx++;
  346. }
  347. }
  348. return $aResult;
  349. }
  350. protected static function DoCopy($aCopies)
  351. {
  352. $aReports = array();
  353. foreach ($aCopies as $aCopy)
  354. {
  355. $sSource = $aCopy['source'];
  356. $sDestination = APPROOT.$aCopy['destination'];
  357. SetupUtils::builddir($sDestination);
  358. SetupUtils::tidydir($sDestination);
  359. SetupUtils::copydir($sSource, $sDestination);
  360. $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)";
  361. }
  362. if (count($aReports) > 0)
  363. {
  364. $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports);
  365. }
  366. else
  367. {
  368. $sReport = "No file copy";
  369. }
  370. return $sReport;
  371. }
  372. protected static function DoBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sBackupFileFormat, $sSourceConfigFile)
  373. {
  374. $oBackup = new SetupDBBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix);
  375. $sTargetFile = $oBackup->MakeName($sBackupFileFormat);
  376. $oBackup->CreateCompressedBackup($sTargetFile, $sSourceConfigFile);
  377. }
  378. protected static function DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sEnvironment, $bUseSymbolicLinks = false)
  379. {
  380. SetupPage::log_info("Compiling data model.");
  381. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  382. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  383. require_once(APPROOT.'setup/compiler.class.inc.php');
  384. if (empty($sSourceDir) || empty($sTargetDir))
  385. {
  386. throw new Exception("missing parameter source_dir and/or target_dir");
  387. }
  388. $sSourcePath = APPROOT.$sSourceDir;
  389. $aDirsToScan = array($sSourcePath);
  390. $sExtensionsPath = APPROOT.$sExtensionDir;
  391. if (is_dir($sExtensionsPath))
  392. {
  393. // if the extensions dir exists, scan it for additional modules as well
  394. $aDirsToScan[] = $sExtensionsPath;
  395. }
  396. $sExtraPath = APPROOT.'/data/'.$sEnvironment.'-modules/';
  397. if (is_dir($sExtraPath))
  398. {
  399. // if the extra dir exists, scan it for additional modules as well
  400. $aDirsToScan[] = $sExtraPath;
  401. }
  402. $sTargetPath = APPROOT.$sTargetDir;
  403. if (!is_dir($sSourcePath))
  404. {
  405. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  406. }
  407. if (!is_dir($sTargetPath))
  408. {
  409. if (!mkdir($sTargetPath))
  410. {
  411. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  412. }
  413. else
  414. {
  415. // adjust the rights if and only if the directory was just created
  416. // owner:rwx user/group:rx
  417. chmod($sTargetPath, 0755);
  418. }
  419. }
  420. else if (substr($sTargetPath, 0, strlen(APPROOT)) == APPROOT)
  421. {
  422. // If the directory is under the root folder - as expected - let's clean-it before compiling
  423. SetupUtils::tidydir($sTargetPath);
  424. }
  425. $oFactory = new ModelFactory($aDirsToScan);
  426. $oDictModule = new MFDictModule('dictionaries', 'iTop Dictionaries', APPROOT.'dictionaries');
  427. $oFactory->LoadModule($oDictModule);
  428. $sDeltaFile = APPROOT.'core/datamodel.core.xml';
  429. if (file_exists($sDeltaFile))
  430. {
  431. $oCoreModule = new MFCoreModule('core', 'Core Module', $sDeltaFile);
  432. $oFactory->LoadModule($oCoreModule);
  433. }
  434. $sDeltaFile = APPROOT.'application/datamodel.application.xml';
  435. if (file_exists($sDeltaFile))
  436. {
  437. $oApplicationModule = new MFCoreModule('application', 'Application Module', $sDeltaFile);
  438. $oFactory->LoadModule($oApplicationModule);
  439. }
  440. $aModules = $oFactory->FindModules();
  441. foreach($aModules as $oModule)
  442. {
  443. $sModule = $oModule->GetName();
  444. if (in_array($sModule, $aSelectedModules))
  445. {
  446. $oFactory->LoadModule($oModule);
  447. }
  448. }
  449. // Dump the "reference" model, just before loading any actual delta
  450. $oFactory->SaveToFile(APPROOT.'data/datamodel-'.$sEnvironment.'.xml');
  451. $sDeltaFile = APPROOT.'data/'.$sEnvironment.'.delta.xml';
  452. if (file_exists($sDeltaFile))
  453. {
  454. $oDelta = new MFDeltaModule($sDeltaFile);
  455. $oFactory->LoadModule($oDelta);
  456. $oFactory->SaveToFile(APPROOT.'data/datamodel-'.$sEnvironment.'-with-delta.xml');
  457. }
  458. //$oFactory->Dump();
  459. if ($oFactory->HasLoadErrors())
  460. {
  461. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  462. {
  463. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  464. foreach($aErrors as $oXmlError)
  465. {
  466. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  467. }
  468. }
  469. throw new Exception("The data model could not be compiled. Please check the setup error log");
  470. }
  471. else
  472. {
  473. $oMFCompiler = new MFCompiler($oFactory);
  474. $oMFCompiler->Compile($sTargetPath, null, $bUseSymbolicLinks);
  475. //$aCompilerLog = $oMFCompiler->GetLog();
  476. //SetupPage::log_info(implode("\n", $aCompilerLog));
  477. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  478. $sCacheDir = APPROOT.'/data/cache-'.$sEnvironment.'/';
  479. SetupUtils::builddir($sCacheDir);
  480. SetupUtils::tidydir($sCacheDir);
  481. }
  482. // Special case to patch a ugly patch in itop-config-mgmt
  483. $sFileToPatch = $sTargetPath.'/itop-config-mgmt-1.0.0/model.itop-config-mgmt.php';
  484. if (file_exists($sFileToPatch))
  485. {
  486. $sContent = file_get_contents($sFileToPatch);
  487. $sContent = str_replace("require_once(APPROOT.'modules/itop-welcome-itil/model.itop-welcome-itil.php');", "//\n// The line below is no longer needed in iTop 2.0 -- patched by the setup program\n// require_once(APPROOT.'modules/itop-welcome-itil/model.itop-welcome-itil.php');", $sContent);
  488. file_put_contents($sFileToPatch, $sContent);
  489. }
  490. // Set an "Instance UUID" identifying this machine based on a file located in the data directory
  491. $sInstanceUUIDFile = APPROOT.'data/instance.txt';
  492. SetupUtils::builddir(APPROOT.'data');
  493. if (!file_exists($sInstanceUUIDFile))
  494. {
  495. $sIntanceUUID = utils::CreateUUID('filesystem');
  496. file_put_contents($sInstanceUUIDFile, $sIntanceUUID);
  497. }
  498. }
  499. protected static function DoUpdateDBSchema($sMode, $aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  500. {
  501. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  502. $oConfig = new Config();
  503. $aParamValues = array(
  504. 'mode' => $sMode,
  505. 'db_server' => $sDBServer,
  506. 'db_user' => $sDBUser,
  507. 'db_pwd' => $sDBPwd,
  508. 'db_name' => $sDBName,
  509. 'db_prefix' => $sDBPrefix,
  510. );
  511. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  512. if ($bOldAddon)
  513. {
  514. // Old version of the add-on for backward compatibility with pre-2.0 data models
  515. $oConfig->SetAddons(array(
  516. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  517. ));
  518. }
  519. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  520. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  521. // Migrate application data format
  522. //
  523. // priv_internalUser caused troubles because MySQL transforms table names to lower case under Windows
  524. // This becomes an issue when moving your installation data to/from Windows
  525. // Starting 2.0, all table names must be lowercase
  526. if ($sMode != 'install')
  527. {
  528. SetupPage::log_info("Renaming '{$sDBPrefix}priv_internalUser' into '{$sDBPrefix}priv_internaluser' (lowercase)");
  529. // This command will have no effect under Windows...
  530. // and it has been written in two steps so as to make it work under windows!
  531. CMDBSource::SelectDB($sDBName);
  532. try
  533. {
  534. $sRepair = "RENAME TABLE `{$sDBPrefix}priv_internalUser` TO `{$sDBPrefix}priv_internaluser_other`, `{$sDBPrefix}priv_internaluser_other` TO `{$sDBPrefix}priv_internaluser`";
  535. CMDBSource::Query($sRepair);
  536. }
  537. catch (Exception $e)
  538. {
  539. SetupPage::log_info("Renaming '{$sDBPrefix}priv_internalUser' failed (already done in a previous upgrade?)");
  540. }
  541. // let's remove the records in priv_change which have no counterpart in priv_changeop
  542. SetupPage::log_info("Cleanup of '{$sDBPrefix}priv_change' to remove orphan records");
  543. CMDBSource::SelectDB($sDBName);
  544. try
  545. {
  546. $sTotalCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change`";
  547. $iTotalCount = (int)CMDBSource::QueryToScalar($sTotalCount);
  548. SetupPage::log_info("There is a total of $iTotalCount records in {$sDBPrefix}priv_change.");
  549. $sOrphanCount = "SELECT COUNT(c.id) FROM `{$sDBPrefix}priv_change` AS c left join `{$sDBPrefix}priv_changeop` AS o ON c.id = o.changeid WHERE o.id IS NULL";
  550. $iOrphanCount = (int)CMDBSource::QueryToScalar($sOrphanCount);
  551. SetupPage::log_info("There are $iOrphanCount useless records in {$sDBPrefix}priv_change (".sprintf('%.2f', ((100.0*$iOrphanCount)/$iTotalCount))."%)");
  552. if ($iOrphanCount > 0)
  553. {
  554. SetupPage::log_info("Removing the orphan records...");
  555. $sCleanup = "DELETE FROM `{$sDBPrefix}priv_change` USING `{$sDBPrefix}priv_change` LEFT JOIN `{$sDBPrefix}priv_changeop` ON `{$sDBPrefix}priv_change`.id = `{$sDBPrefix}priv_changeop`.changeid WHERE `{$sDBPrefix}priv_changeop`.id IS NULL;";
  556. CMDBSource::Query($sCleanup);
  557. SetupPage::log_info("Cleanup completed successfully.");
  558. }
  559. else
  560. {
  561. SetupPage::log_info("Ok, nothing to cleanup.");
  562. }
  563. }
  564. catch (Exception $e)
  565. {
  566. SetupPage::log_info("Cleanup of orphan records in `{$sDBPrefix}priv_change` failed: ".$e->getMessage());
  567. }
  568. }
  569. // Module specific actions (migrate the data)
  570. //
  571. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  572. foreach($aAvailableModules as $sModuleId => $aModule)
  573. {
  574. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  575. isset($aAvailableModules[$sModuleId]['installer']) )
  576. {
  577. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  578. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::BeforeDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  579. $aCallSpec = array($sModuleInstallerClass, 'BeforeDatabaseCreation');
  580. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  581. }
  582. }
  583. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  584. {
  585. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  586. }
  587. // Set a DBProperty with a unique ID to identify this instance of iTop
  588. $sUUID = DBProperty::GetProperty('database_uuid', '');
  589. if ($sUUID === '')
  590. {
  591. $sUUID = utils::CreateUUID('database');
  592. DBProperty::SetProperty('database_uuid', $sUUID, 'Installation/upgrade of '.ITOP_APPLICATION, 'Unique ID of this '.ITOP_APPLICATION.' Database');
  593. }
  594. // priv_change now has an 'origin' field to distinguish between the various input sources
  595. // Let's initialize the field with 'interactive' for all records were it's null
  596. // Then check if some records should hold a different value, based on a pattern matching in the userinfo field
  597. CMDBSource::SelectDB($sDBName);
  598. try
  599. {
  600. $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change` WHERE `origin` IS NULL";
  601. $iCount = (int)CMDBSource::QueryToScalar($sCount);
  602. if ($iCount > 0)
  603. {
  604. SetupPage::log_info("Initializing '{$sDBPrefix}priv_change.origin' ($iCount records to update)");
  605. // By default all uninitialized values are considered as 'interactive'
  606. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'interactive' WHERE `origin` IS NULL";
  607. CMDBSource::Query($sInit);
  608. // CSV Import was identified by the comment at the end
  609. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'csv-import.php' WHERE `userinfo` LIKE '%Web Service (CSV)'";
  610. CMDBSource::Query($sInit);
  611. // CSV Import was identified by the comment at the end
  612. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'csv-interactive' WHERE `userinfo` LIKE '%(CSV)' AND origin = 'interactive'";
  613. CMDBSource::Query($sInit);
  614. // Syncho data sources were identified by the comment at the end
  615. // Unfortunately the comment is localized, so we have to search for all possible patterns
  616. $sCurrentLanguage = Dict::GetUserLanguage();
  617. $aSuffixes = array();
  618. foreach(array_keys(Dict::GetLanguages()) as $sLangCode)
  619. {
  620. Dict::SetUserLanguage($sLangCode);
  621. $sSuffix = CMDBSource::Quote('%'.Dict::S('Core:SyncDataExchangeComment'));
  622. $aSuffixes[$sSuffix] = true;
  623. }
  624. Dict::SetUserLanguage($sCurrentLanguage);
  625. $sCondition = "`userinfo` LIKE ".implode(" OR `userinfo` LIKE ", array_keys($aSuffixes));
  626. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'synchro-data-source' WHERE ($sCondition)";
  627. CMDBSource::Query($sInit);
  628. SetupPage::log_info("Initialization of '{$sDBPrefix}priv_change.origin' completed.");
  629. }
  630. else
  631. {
  632. SetupPage::log_info("'{$sDBPrefix}priv_change.origin' already initialized, nothing to do.");
  633. }
  634. }
  635. catch (Exception $e)
  636. {
  637. SetupPage::log_error("Initializing '{$sDBPrefix}priv_change.origin' failed: ".$e->getMessage());
  638. }
  639. // priv_async_task now has a 'status' field to distinguish between the various statuses rather than just relying on the date columns
  640. // Let's initialize the field with 'planned' or 'error' for all records were it's null
  641. CMDBSource::SelectDB($sDBName);
  642. try
  643. {
  644. $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_async_task` WHERE `status` IS NULL";
  645. $iCount = (int)CMDBSource::QueryToScalar($sCount);
  646. if ($iCount > 0)
  647. {
  648. SetupPage::log_info("Initializing '{$sDBPrefix}priv_async_task.status' ($iCount records to update)");
  649. $sInit = "UPDATE `{$sDBPrefix}priv_async_task` SET `status` = 'planned' WHERE (`status` IS NULL) AND (`started` IS NULL)";
  650. CMDBSource::Query($sInit);
  651. $sInit = "UPDATE `{$sDBPrefix}priv_async_task` SET `status` = 'error' WHERE (`status` IS NULL) AND (`started` IS NOT NULL)";
  652. CMDBSource::Query($sInit);
  653. SetupPage::log_info("Initialization of '{$sDBPrefix}priv_async_task.status' completed.");
  654. }
  655. else
  656. {
  657. SetupPage::log_info("'{$sDBPrefix}priv_async_task.status' already initialized, nothing to do.");
  658. }
  659. }
  660. catch (Exception $e)
  661. {
  662. SetupPage::log_error("Initializing '{$sDBPrefix}priv_async_task.status' failed: ".$e->getMessage());
  663. }
  664. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  665. }
  666. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sDataModelVersion, $sSourceDir)
  667. {
  668. SetupPage::log_info('After Database Creation');
  669. $oConfig = new Config();
  670. $aParamValues = array(
  671. 'mode' => $sMode,
  672. 'db_server' => $sDBServer,
  673. 'db_user' => $sDBUser,
  674. 'db_pwd' => $sDBPwd,
  675. 'db_name' => $sDBName,
  676. 'db_prefix' => $sDBPrefix,
  677. );
  678. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  679. if ($bOldAddon)
  680. {
  681. // Old version of the add-on for backward compatibility with pre-2.0 data models
  682. $oConfig->SetAddons(array(
  683. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  684. ));
  685. }
  686. $oConfig->Set('source_dir', $sSourceDir); // Needed by RecordInstallation below
  687. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  688. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  689. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  690. // Perform here additional DB setup... profiles, etc...
  691. //
  692. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  693. foreach($aAvailableModules as $sModuleId => $aModule)
  694. {
  695. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  696. isset($aAvailableModules[$sModuleId]['installer']) )
  697. {
  698. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  699. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  700. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  701. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  702. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  703. }
  704. }
  705. $oProductionEnv->UpdatePredefinedObjects();
  706. if($sMode == 'install')
  707. {
  708. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  709. {
  710. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  711. }
  712. else
  713. {
  714. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  715. }
  716. }
  717. // Perform final setup tasks here
  718. //
  719. foreach($aAvailableModules as $sModuleId => $aModule)
  720. {
  721. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  722. isset($aAvailableModules[$sModuleId]['installer']) )
  723. {
  724. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  725. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseSetup(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  726. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  727. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseSetup');
  728. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  729. }
  730. }
  731. }
  732. /**
  733. * Helper function to create and administrator account for iTop
  734. * @return boolean true on success, false otherwise
  735. */
  736. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  737. {
  738. SetupPage::log_info('CreateAdminAccount');
  739. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  740. {
  741. return true;
  742. }
  743. else
  744. {
  745. return false;
  746. }
  747. }
  748. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = 'production', $bOldAddon = false, $bSampleData = false)
  749. {
  750. $aParamValues = array(
  751. 'db_server' => $sDBServer,
  752. 'db_user' => $sDBUser,
  753. 'db_pwd' => $sDBPwd,
  754. 'db_name' => $sDBName,
  755. 'new_db_name' => $sDBName,
  756. 'db_prefix' => $sDBPrefix,
  757. );
  758. $oConfig = new Config();
  759. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  760. if ($bOldAddon)
  761. {
  762. // Old version of the add-on for backward compatibility with pre-2.0 data models
  763. $oConfig->SetAddons(array(
  764. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  765. ));
  766. }
  767. //Load the MetaModel if needed (asynchronous mode)
  768. if (!self::$bMetaModelStarted)
  769. {
  770. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  771. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  772. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  773. }
  774. $oDataLoader = new XMLDataLoader();
  775. CMDBObject::SetTrackInfo("Initialization");
  776. $oMyChange = CMDBObject::GetCurrentChange();
  777. SetupPage::log_info("starting data load session");
  778. $oDataLoader->StartSession($oMyChange);
  779. $aFiles = array();
  780. $aPreviouslyLoadedFiles = array();
  781. $oProductionEnv = new RunTimeEnvironment();
  782. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, APPROOT.$sModulesDir);
  783. foreach($aAvailableModules as $sModuleId => $aModule)
  784. {
  785. if (($sModuleId != ROOT_MODULE))
  786. {
  787. $sRelativePath = 'env-'.$sTargetEnvironment.'/'.basename($aModule['root_dir']);
  788. // Load data only for selected AND newly installed modules
  789. if (in_array($sModuleId, $aSelectedModules))
  790. {
  791. if ($aModule['version_db'] != '')
  792. {
  793. // Simulate the load of the previously loaded XML files to get the mapping of the keys
  794. if ($bSampleData)
  795. {
  796. $aPreviouslyLoadedFiles = static::MergeWithRelativeDir($aPreviouslyLoadedFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.struct']);
  797. $aPreviouslyLoadedFiles = static::MergeWithRelativeDir($aPreviouslyLoadedFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.sample']);
  798. }
  799. else
  800. {
  801. // Load only structural data
  802. $aPreviouslyLoadedFiles = static::MergeWithRelativeDir($aPreviouslyLoadedFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.struct']);
  803. }
  804. }
  805. else
  806. {
  807. if ($bSampleData)
  808. {
  809. $aFiles = static::MergeWithRelativeDir($aFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.struct']);
  810. $aFiles = static::MergeWithRelativeDir($aFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.sample']);
  811. }
  812. else
  813. {
  814. // Load only structural data
  815. $aFiles = static::MergeWithRelativeDir($aFiles, $sRelativePath, $aAvailableModules[$sModuleId]['data.struct']);
  816. }
  817. }
  818. }
  819. }
  820. }
  821. // Simulate the load of the previously loaded files, in order to initialize
  822. // the mapping between the identifiers in the XML and the actual identifiers
  823. // in the current database
  824. foreach($aPreviouslyLoadedFiles as $sFileRelativePath)
  825. {
  826. $sFileName = APPROOT.$sFileRelativePath;
  827. SetupPage::log_info("Loading file: $sFileName (just to get the keys mapping)");
  828. if (empty($sFileName) || !file_exists($sFileName))
  829. {
  830. throw(new Exception("File $sFileName does not exist"));
  831. }
  832. $oDataLoader->LoadFile($sFileName, true);
  833. $sResult = sprintf("loading of %s done.", basename($sFileName));
  834. SetupPage::log_info($sResult);
  835. }
  836. foreach($aFiles as $sFileRelativePath)
  837. {
  838. $sFileName = APPROOT.$sFileRelativePath;
  839. SetupPage::log_info("Loading file: $sFileName");
  840. if (empty($sFileName) || !file_exists($sFileName))
  841. {
  842. throw(new Exception("File $sFileName does not exist"));
  843. }
  844. $oDataLoader->LoadFile($sFileName);
  845. $sResult = sprintf("loading of %s done.", basename($sFileName));
  846. SetupPage::log_info($sResult);
  847. }
  848. $oDataLoader->EndSession();
  849. SetupPage::log_info("ending data load session");
  850. // Perform after dbload setup tasks here
  851. //
  852. foreach($aAvailableModules as $sModuleId => $aModule)
  853. {
  854. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  855. isset($aAvailableModules[$sModuleId]['installer']) )
  856. {
  857. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  858. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDataLoad(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  859. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  860. $aCallSpec = array($sModuleInstallerClass, 'AfterDataLoad');
  861. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  862. }
  863. }
  864. }
  865. /**
  866. * Merge two arrays of file names, adding the relative path to the files provided in the array to merge
  867. * @param string[] $aSourceArray
  868. * @param string $sBaseDir
  869. * @param string[] $aFilesToMerge
  870. * @return string[]
  871. */
  872. protected static function MergeWithRelativeDir($aSourceArray, $sBaseDir, $aFilesToMerge)
  873. {
  874. $aToMerge = array();
  875. foreach($aFilesToMerge as $sFile)
  876. {
  877. $aToMerge[] = $sBaseDir.'/'.$sFile;
  878. }
  879. return array_merge($aSourceArray, $aToMerge);
  880. }
  881. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModuleCodes, $aSelectedExtensionCodes, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile, $sDataModelVersion, $sGraphvizPath)
  882. {
  883. $aParamValues = array(
  884. 'mode' => $sMode,
  885. 'db_server' => $sDBServer,
  886. 'db_user' => $sDBUser,
  887. 'db_pwd' => $sDBPwd,
  888. 'db_name' => $sDBName,
  889. 'new_db_name' => $sDBName,
  890. 'db_prefix' => $sDBPrefix,
  891. 'application_path' => $sUrl,
  892. 'language' => $sLanguage,
  893. 'graphviz_path' => $sGraphvizPath,
  894. 'selected_modules' => implode(',', $aSelectedModuleCodes)
  895. );
  896. $bPreserveModuleSettings = false;
  897. if ($sMode == 'upgrade')
  898. {
  899. try
  900. {
  901. $oOldConfig = new Config($sPreviousConfigFile);
  902. $oConfig = clone($oOldConfig);
  903. $bPreserveModuleSettings = true;
  904. }
  905. catch(Exception $e)
  906. {
  907. // In case the previous configuration is corrupted... start with a blank new one
  908. $oConfig = new Config();
  909. }
  910. }
  911. else
  912. {
  913. $oConfig = new Config();
  914. // To preserve backward compatibility while upgrading to 2.0.3 (when tracking_level_linked_set_default has been introduced)
  915. // the default value on upgrade differs from the default value at first install
  916. $oConfig->Set('tracking_level_linked_set_default', LINKSET_TRACKING_NONE, 'first_install');
  917. }
  918. // Final config update: add the modules
  919. $oConfig->UpdateFromParams($aParamValues, $sModulesDir, $bPreserveModuleSettings);
  920. if ($bOldAddon)
  921. {
  922. // Old version of the add-on for backward compatibility with pre-2.0 data models
  923. $oConfig->SetAddons(array(
  924. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  925. ));
  926. }
  927. $oConfig->Set('source_dir', $sSourceDir);
  928. // Record which modules are installed...
  929. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  930. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  931. if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModuleCodes, $aSelectedExtensionCodes))
  932. {
  933. throw new Exception("Failed to record the installation information");
  934. }
  935. // Make sure the root configuration directory exists
  936. if (!file_exists(APPCONF))
  937. {
  938. mkdir(APPCONF);
  939. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  940. SetupPage::log_info("Created configuration directory: ".APPCONF);
  941. }
  942. // Write the final configuration file
  943. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  944. $sConfigDir = dirname($sConfigFile);
  945. @mkdir($sConfigDir);
  946. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  947. $oConfig->WriteToFile($sConfigFile);
  948. // try to make the final config file read-only
  949. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  950. // Ready to go !!
  951. require_once(APPROOT.'core/dict.class.inc.php');
  952. MetaModel::ResetCache();
  953. }
  954. }
  955. class SetupDBBackup extends DBBackup
  956. {
  957. protected function LogInfo($sMsg)
  958. {
  959. SetupPage::log('Info - '.$sMsg);
  960. }
  961. protected function LogError($sMsg)
  962. {
  963. SetupPage::log('Error - '.$sMsg);
  964. }
  965. }