applicationinstaller.class.inc.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. <?php
  2. // Copyright (C) 2010-2012 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-2012 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.zip
  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. $sWorkspaceDir = $this->oParams->Get('workspace_dir', 'workspace');
  180. $bUseSymbolicLinks = false;
  181. $aMiscOptions = $this->oParams->Get('options', array());
  182. if (isset($aMiscOptions['symlinks']) && $aMiscOptions['symlinks'] )
  183. {
  184. if (function_exists('symlink'))
  185. {
  186. $bUseSymbolicLinks = true;
  187. SetupPage::log_info("Using symbolic links instead of copying data model files (for developers only!)");
  188. }
  189. else
  190. {
  191. SetupPage::log_info("Symbolic links (function symlinks) does not seem to be supported on this platform (OS/PHP version).");
  192. }
  193. }
  194. self::DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sWorkspaceDir, $bUseSymbolicLinks);
  195. $aResult = array(
  196. 'status' => self::OK,
  197. 'message' => '',
  198. 'next-step' => 'db-schema',
  199. 'next-step-label' => 'Updating database schema',
  200. 'percentage-completed' => 40,
  201. );
  202. break;
  203. case 'db-schema':
  204. $sMode = $this->oParams->Get('mode');
  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, $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' => 'sample-data',
  256. 'next-step-label' => 'Loading sample data',
  257. 'percentage-completed' => 80,
  258. );
  259. $bLoadData = ($this->oParams->Get('sample_data', 0) == 1);
  260. if (!$bLoadData)
  261. {
  262. $aResult['next-step'] = 'create-config';
  263. $aResult['next-step-label'] = 'Creating the configuration File';
  264. }
  265. break;
  266. case 'sample-data':
  267. $aSelectedModules = $this->oParams->Get('selected_modules');
  268. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  269. $sTargetDir = 'env-'.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment);
  270. $aDBParams = $this->oParams->Get('database');
  271. $sDBServer = $aDBParams['server'];
  272. $sDBUser = $aDBParams['user'];
  273. $sDBPwd = $aDBParams['pwd'];
  274. $sDBName = $aDBParams['name'];
  275. $sDBPrefix = $aDBParams['prefix'];
  276. $aFiles = $this->oParams->Get('files', array());
  277. $bOldAddon = $this->oParams->Get('old_addon', false);
  278. self::DoLoadFiles($aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment, $bOldAddon);
  279. $aResult = array(
  280. 'status' => self::INFO,
  281. 'message' => 'All data loaded',
  282. 'next-step' => 'create-config',
  283. 'next-step-label' => 'Creating the configuration File',
  284. 'percentage-completed' => 99,
  285. );
  286. break;
  287. case 'create-config':
  288. $sMode = $this->oParams->Get('mode');
  289. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  290. if ($sTargetEnvironment == '')
  291. {
  292. $sTargetEnvironment = 'production';
  293. }
  294. $sTargetDir = 'env-'.$sTargetEnvironment;
  295. $aDBParams = $this->oParams->Get('database');
  296. $sDBServer = $aDBParams['server'];
  297. $sDBUser = $aDBParams['user'];
  298. $sDBPwd = $aDBParams['pwd'];
  299. $sDBName = $aDBParams['name'];
  300. $sDBPrefix = $aDBParams['prefix'];
  301. $sUrl = $this->oParams->Get('url', '');
  302. $sLanguage = $this->oParams->Get('language', '');
  303. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  304. $bOldAddon = $this->oParams->Get('old_addon', false);
  305. $sSourceDir = $this->oParams->Get('source_dir', '');
  306. $sPreviousConfigFile = $this->oParams->Get('previous_configuration_file', '');
  307. self::DoCreateConfig($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile);
  308. $aResult = array(
  309. 'status' => self::INFO,
  310. 'message' => 'Configuration file created',
  311. 'next-step' => '',
  312. 'next-step-label' => 'Completed',
  313. 'percentage-completed' => 100,
  314. );
  315. break;
  316. default:
  317. $aResult = array(
  318. 'status' => self::ERROR,
  319. 'message' => '',
  320. 'next-step' => '',
  321. 'next-step-label' => "Unknown setup step '$sStep'.",
  322. 'percentage-completed' => 100,
  323. );
  324. }
  325. }
  326. catch(Exception $e)
  327. {
  328. $aResult = array(
  329. 'status' => self::ERROR,
  330. 'message' => $e->getMessage(),
  331. 'next-step' => '',
  332. 'next-step-label' => '',
  333. 'percentage-completed' => 100,
  334. );
  335. SetupPage::log_error('An exception occurred: '.$e->getMessage());
  336. SetupPage::log("Stack trace:\n".$e->getTraceAsString());
  337. }
  338. return $aResult;
  339. }
  340. protected static function DoCopy($aCopies)
  341. {
  342. $aReports = array();
  343. foreach ($aCopies as $aCopy)
  344. {
  345. $sSource = $aCopy['source'];
  346. $sDestination = APPROOT.$aCopy['destination'];
  347. SetupUtils::builddir($sDestination);
  348. SetupUtils::tidydir($sDestination);
  349. SetupUtils::copydir($sSource, $sDestination);
  350. $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)";
  351. }
  352. if (count($aReports) > 0)
  353. {
  354. $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports);
  355. }
  356. else
  357. {
  358. $sReport = "No file copy";
  359. }
  360. return $sReport;
  361. }
  362. protected static function DoBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sBackupFile, $sSourceConfigFile)
  363. {
  364. $oBackup = new DBBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix);
  365. $sZipFile = $oBackup->MakeName($sBackupFile);
  366. $oBackup->CreateZip($sZipFile, $sSourceConfigFile);
  367. }
  368. protected static function DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sWorkspaceDir = '', $bUseSymbolicLinks = false)
  369. {
  370. SetupPage::log_info("Compiling data model.");
  371. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  372. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  373. require_once(APPROOT.'setup/compiler.class.inc.php');
  374. if (empty($sSourceDir) || empty($sTargetDir))
  375. {
  376. throw new Exception("missing parameter source_dir and/or target_dir");
  377. }
  378. $sSourcePath = APPROOT.$sSourceDir;
  379. $aDirsToScan = array($sSourcePath);
  380. $sExtensionsPath = APPROOT.$sExtensionDir;
  381. if (is_dir($sExtensionsPath))
  382. {
  383. // if the extensions dir exists, scan it for additional modules as well
  384. $aDirsToScan[] = $sExtensionsPath;
  385. }
  386. $sTargetPath = APPROOT.$sTargetDir;
  387. if (!is_dir($sSourcePath))
  388. {
  389. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  390. }
  391. if (!is_dir($sTargetPath))
  392. {
  393. if (!mkdir($sTargetPath))
  394. {
  395. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  396. }
  397. else
  398. {
  399. // adjust the rights if and only if the directory was just created
  400. // owner:rwx user/group:rx
  401. chmod($sTargetPath, 0755);
  402. }
  403. }
  404. else if (substr($sTargetPath, 0, strlen(APPROOT)) == APPROOT)
  405. {
  406. // If the directory is under the root folder - as expected - let's clean-it before compiling
  407. SetupUtils::tidydir($sTargetPath);
  408. }
  409. $oFactory = new ModelFactory($aDirsToScan);
  410. $aModules = $oFactory->FindModules();
  411. foreach($aModules as $foo => $oModule)
  412. {
  413. $sModule = $oModule->GetName();
  414. if (in_array($sModule, $aSelectedModules))
  415. {
  416. $oFactory->LoadModule($oModule);
  417. }
  418. }
  419. if (strlen($sWorkspaceDir) > 0)
  420. {
  421. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspaceDir);
  422. if (file_exists($oWorkspace->GetWorkspacePath()))
  423. {
  424. $oFactory->LoadModule($oWorkspace);
  425. }
  426. }
  427. //$oFactory->Dump();
  428. if ($oFactory->HasLoadErrors())
  429. {
  430. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  431. {
  432. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  433. foreach($aErrors as $oXmlError)
  434. {
  435. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  436. }
  437. }
  438. throw new Exception("The data model could not be compiled. Please check the setup error log");
  439. }
  440. else
  441. {
  442. $oMFCompiler = new MFCompiler($oFactory);
  443. $oMFCompiler->Compile($sTargetPath, null, $bUseSymbolicLinks);
  444. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  445. }
  446. // Special case to patch a ugly patch in itop-config-mgmt
  447. $sFileToPatch = $sTargetPath.'/itop-config-mgmt-1.0.0/model.itop-config-mgmt.php';
  448. if (file_exists($sFileToPatch))
  449. {
  450. $sContent = file_get_contents($sFileToPatch);
  451. $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);
  452. file_put_contents($sFileToPatch, $sContent);
  453. }
  454. }
  455. protected static function DoUpdateDBSchema($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  456. {
  457. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  458. $oConfig = new Config();
  459. $aParamValues = array(
  460. 'db_server' => $sDBServer,
  461. 'db_user' => $sDBUser,
  462. 'db_pwd' => $sDBPwd,
  463. 'db_name' => $sDBName,
  464. 'db_prefix' => $sDBPrefix,
  465. );
  466. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  467. if ($bOldAddon)
  468. {
  469. // Old version of the add-on for backward compatibility with pre-2.0 data models
  470. $oConfig->SetAddons(array(
  471. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  472. ));
  473. }
  474. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  475. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  476. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  477. {
  478. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  479. }
  480. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  481. }
  482. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sDataModelVersion, $sSourceDir)
  483. {
  484. SetupPage::log_info('After Database Creation');
  485. $oConfig = new Config();
  486. $aParamValues = array(
  487. 'db_server' => $sDBServer,
  488. 'db_user' => $sDBUser,
  489. 'db_pwd' => $sDBPwd,
  490. 'db_name' => $sDBName,
  491. 'db_prefix' => $sDBPrefix,
  492. );
  493. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  494. if ($bOldAddon)
  495. {
  496. // Old version of the add-on for backward compatibility with pre-2.0 data models
  497. $oConfig->SetAddons(array(
  498. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  499. ));
  500. }
  501. $oConfig->Set('source_dir', $sSourceDir); // Needed by RecordInstallation below
  502. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  503. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  504. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  505. // Perform here additional DB setup... profiles, etc...
  506. //
  507. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  508. foreach($aAvailableModules as $sModuleId => $aModule)
  509. {
  510. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  511. isset($aAvailableModules[$sModuleId]['installer']) )
  512. {
  513. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  514. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  515. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  516. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  517. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  518. }
  519. }
  520. // Constant classes (e.g. User profiles)
  521. //
  522. foreach (MetaModel::GetClasses() as $sClass)
  523. {
  524. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  525. if ($aPredefinedObjects != null)
  526. {
  527. SetupPage::log_info("$sClass::GetPredefinedObjects() returned ".count($aPredefinedObjects)." elements.");
  528. // Create/Delete/Update objects of this class,
  529. // according to the given constant values
  530. //
  531. $aDBIds = array();
  532. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  533. while ($oObj = $oAll->Fetch())
  534. {
  535. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  536. {
  537. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  538. foreach ($aObjValues as $sAttCode => $value)
  539. {
  540. $oObj->Set($sAttCode, $value);
  541. }
  542. $oObj->DBUpdate();
  543. $aDBIds[$oObj->GetKey()] = true;
  544. }
  545. else
  546. {
  547. $oObj->DBDelete();
  548. }
  549. }
  550. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  551. {
  552. if (!array_key_exists($iRefId, $aDBIds))
  553. {
  554. $oNewObj = MetaModel::NewObject($sClass);
  555. $oNewObj->SetKey($iRefId);
  556. foreach ($aObjValues as $sAttCode => $value)
  557. {
  558. $oNewObj->Set($sAttCode, $value);
  559. }
  560. $oNewObj->DBInsert();
  561. }
  562. }
  563. }
  564. }
  565. if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModules, $sModulesDir))
  566. {
  567. throw new Exception("Failed to record the installation information");
  568. }
  569. if($sMode == 'install')
  570. {
  571. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  572. {
  573. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  574. }
  575. else
  576. {
  577. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  578. }
  579. }
  580. }
  581. /**
  582. * Helper function to create and administrator account for iTop
  583. * @return boolean true on success, false otherwise
  584. */
  585. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  586. {
  587. SetupPage::log_info('CreateAdminAccount');
  588. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  589. {
  590. return true;
  591. }
  592. else
  593. {
  594. return false;
  595. }
  596. }
  597. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  598. {
  599. $aParamValues = array(
  600. 'db_server' => $sDBServer,
  601. 'db_user' => $sDBUser,
  602. 'db_pwd' => $sDBPwd,
  603. 'db_name' => $sDBName,
  604. 'new_db_name' => $sDBName,
  605. 'db_prefix' => $sDBPrefix,
  606. );
  607. $oConfig = new Config();
  608. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  609. if ($bOldAddon)
  610. {
  611. // Old version of the add-on for backward compatibility with pre-2.0 data models
  612. $oConfig->SetAddons(array(
  613. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  614. ));
  615. }
  616. //Load the MetaModel if needed (asynchronous mode)
  617. if (!self::$bMetaModelStarted)
  618. {
  619. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  620. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  621. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  622. }
  623. $oDataLoader = new XMLDataLoader();
  624. CMDBObject::SetTrackInfo("Initialization");
  625. $oMyChange = CMDBObject::GetCurrentChange();
  626. SetupPage::log_info("starting data load session");
  627. $oDataLoader->StartSession($oMyChange);
  628. $aFiles = array();
  629. $oProductionEnv = new RunTimeEnvironment();
  630. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, APPROOT.$sModulesDir);
  631. foreach($aAvailableModules as $sModuleId => $aModule)
  632. {
  633. if (($sModuleId != ROOT_MODULE))
  634. {
  635. if (in_array($sModuleId, $aSelectedModules))
  636. {
  637. $aFiles = array_merge(
  638. $aFiles,
  639. $aAvailableModules[$sModuleId]['data.struct'],
  640. $aAvailableModules[$sModuleId]['data.sample']
  641. );
  642. }
  643. }
  644. }
  645. foreach($aFiles as $sFileRelativePath)
  646. {
  647. $sFileName = APPROOT.$sFileRelativePath;
  648. SetupPage::log_info("Loading file: $sFileName");
  649. if (empty($sFileName) || !file_exists($sFileName))
  650. {
  651. throw(new Exception("File $sFileName does not exist"));
  652. }
  653. $oDataLoader->LoadFile($sFileName);
  654. $sResult = sprintf("loading of %s done.", basename($sFileName));
  655. SetupPage::log_info($sResult);
  656. }
  657. $oDataLoader->EndSession();
  658. SetupPage::log_info("ending data load session");
  659. }
  660. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile)
  661. {
  662. $aParamValues = array(
  663. 'db_server' => $sDBServer,
  664. 'db_user' => $sDBUser,
  665. 'db_pwd' => $sDBPwd,
  666. 'db_name' => $sDBName,
  667. 'new_db_name' => $sDBName,
  668. 'db_prefix' => $sDBPrefix,
  669. 'application_path' => $sUrl,
  670. 'language' => $sLanguage,
  671. 'selected_modules' => implode(',', $aSelectedModules),
  672. );
  673. $bPreserveModuleSettings = false;
  674. if ($sMode == 'upgrade')
  675. {
  676. try
  677. {
  678. $oOldConfig = new Config($sPreviousConfigFile);
  679. $oConfig = clone($oOldConfig);
  680. $bPreserveModuleSettings = true;
  681. }
  682. catch(Exception $e)
  683. {
  684. // In case the previous configuration is corrupted... start with a blank new one
  685. $oConfig = new Config();
  686. }
  687. }
  688. else
  689. {
  690. $oConfig = new Config();
  691. }
  692. // Migration: force utf8_unicode_ci as the collation to make the global search
  693. // NON case sensitive
  694. $oConfig->SetDBCollation('utf8_unicode_ci');
  695. // Final config update: add the modules
  696. $oConfig->UpdateFromParams($aParamValues, $sModulesDir, $bPreserveModuleSettings);
  697. if ($bOldAddon)
  698. {
  699. // Old version of the add-on for backward compatibility with pre-2.0 data models
  700. $oConfig->SetAddons(array(
  701. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  702. ));
  703. }
  704. $oConfig->Set('source_dir', $sSourceDir);
  705. // Make sure the root configuration directory exists
  706. if (!file_exists(APPCONF))
  707. {
  708. mkdir(APPCONF);
  709. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  710. SetupPage::log_info("Created configuration directory: ".APPCONF);
  711. }
  712. // Write the final configuration file
  713. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  714. $sConfigDir = dirname($sConfigFile);
  715. @mkdir($sConfigDir);
  716. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  717. $oConfig->WriteToFile($sConfigFile);
  718. // try to make the final config file read-only
  719. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  720. // Ready to go !!
  721. require_once(APPROOT.'core/dict.class.inc.php');
  722. MetaModel::ResetCache();
  723. }
  724. }