applicationinstaller.class.inc.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php
  2. // Copyright (C) 2012 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. require_once(APPROOT.'setup/parameters.class.inc.php');
  17. require_once(APPROOT.'setup/xmldataloader.class.inc.php');
  18. require_once(APPROOT.'setup/backup.class.inc.php');
  19. /**
  20. * The base class for the installation process.
  21. * The installation process is split into a sequence of unitary steps
  22. * for performance reasons (i.e; timeout, memory usage) and also in order
  23. * to provide some feedback about the progress of the installation.
  24. *
  25. * This class can be used for a step by step interactive installation
  26. * while displaying a progress bar, or in an unattended manner
  27. * (for example from the command line), to run all the steps
  28. * in one go.
  29. * @author Erwan Taloc <erwan.taloc@combodo.com>
  30. * @author Romain Quetiez <romain.quetiez@combodo.com>
  31. * @author Denis Flaven <denis.flaven@combodo.com>
  32. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  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. do
  57. {
  58. if($sStep != '')
  59. {
  60. echo "$sStepLabel\n";
  61. echo "Executing '$sStep'\n";
  62. }
  63. else
  64. {
  65. echo "Starting the installation...\n";
  66. }
  67. $aRes = $this->ExecuteStep($sStep);
  68. $sStep = $aRes['next-step'];
  69. $sStepLabel = $aRes['next-step-label'];
  70. switch($aRes['status'])
  71. {
  72. case self::OK;
  73. echo "Ok. ".$aRes['percentage-completed']." % done.\n";
  74. break;
  75. case self::ERROR:
  76. echo "Error: ".$aRes['message']."\n";
  77. break;
  78. case self::WARNING:
  79. echo "Warning: ".$aRes['message']."\n";
  80. echo $aRes['percentage-completed']." % done.\n";
  81. break;
  82. case self::INFO:
  83. echo "Info: ".$aRes['message']."\n";
  84. echo $aRes['percentage-completed']." % done.\n";
  85. break;
  86. }
  87. }
  88. while(($aRes['status'] != self::ERROR) && ($aRes['next-step'] != ''));
  89. return ($aRes['status'] == self::OK);
  90. }
  91. /**
  92. * Executes the next step of the installation and reports about the progress
  93. * and the next step to perform
  94. * @param string $sStep The identifier of the step to execute
  95. * @return hash An array of (status => , message => , percentage-completed => , next-step => , next-step-label => )
  96. */
  97. public function ExecuteStep($sStep = '')
  98. {
  99. try
  100. {
  101. switch($sStep)
  102. {
  103. case '':
  104. $aResult = array(
  105. 'status' => self::OK,
  106. 'message' => '',
  107. 'percentage-completed' => 0,
  108. 'next-step' => 'copy',
  109. 'next-step-label' => 'Copying data model files',
  110. );
  111. break;
  112. case 'copy':
  113. $aPreinstall = $this->oParams->Get('preinstall');
  114. $aCopies = $aPreinstall['copies'];
  115. $sReport = self::DoCopy($aCopies);
  116. $aResult = array(
  117. 'status' => self::OK,
  118. 'message' => $sReport,
  119. );
  120. if (isset($aPreinstall['backup']))
  121. {
  122. $aResult['next-step'] = 'backup';
  123. $aResult['next-step-label'] = 'Backuping the database';
  124. $aResult['percentage-completed'] = 20;
  125. }
  126. else
  127. {
  128. $aResult['next-step'] = 'compile';
  129. $aResult['next-step-label'] = 'Compiling the data model';
  130. $aResult['percentage-completed'] = 20;
  131. }
  132. break;
  133. case 'backup':
  134. $aPreinstall = $this->oParams->Get('preinstall');
  135. // __DB__-%Y-%m-%d.zip
  136. $sDestination = $aPreinstall['backup']['destination'];
  137. $sSourceConfigFile = $aPreinstall['backup']['configuration_file'];
  138. $aDBParams = $this->oParams->Get('database');
  139. self::DoBackup($aDBParams['server'], $aDBParams['user'], $aDBParams['pwd'], $aDBParams['name'], $aDBParams['prefix'], $sDestination, $sSourceConfigFile);
  140. $aResult = array(
  141. 'status' => self::OK,
  142. 'message' => "Created backup",
  143. 'next-step' => 'compile',
  144. 'next-step-label' => 'Compiling the data model',
  145. 'percentage-completed' => 20,
  146. );
  147. break;
  148. case 'compile':
  149. $aSelectedModules = $this->oParams->Get('selected_modules');
  150. $sSourceDir = $this->oParams->Get('source_dir', 'datamodel');
  151. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  152. if ($sTargetEnvironment == '')
  153. {
  154. $sTargetEnvironment = 'production';
  155. }
  156. $sTargetDir = 'env-'.$sTargetEnvironment;
  157. $sWorkspaceDir = $this->oParams->Get('workspace_dir', 'workspace');
  158. self::DoCompile($aSelectedModules, $sSourceDir, $sTargetDir, $sWorkspaceDir);
  159. $aResult = array(
  160. 'status' => self::OK,
  161. 'message' => '',
  162. 'next-step' => 'db-schema',
  163. 'next-step-label' => 'Updating database schema',
  164. 'percentage-completed' => 40,
  165. );
  166. break;
  167. case 'db-schema':
  168. $sMode = $this->oParams->Get('mode');
  169. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  170. if ($sTargetEnvironment == '')
  171. {
  172. $sTargetEnvironment = 'production';
  173. }
  174. $sTargetDir = 'env-'.$sTargetEnvironment;
  175. $aDBParams = $this->oParams->Get('database');
  176. $sDBServer = $aDBParams['server'];
  177. $sDBUser = $aDBParams['user'];
  178. $sDBPwd = $aDBParams['pwd'];
  179. $sDBName = $aDBParams['name'];
  180. $sDBPrefix = $aDBParams['prefix'];
  181. self::DoUpdateDBSchema($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment);
  182. $aResult = array(
  183. 'status' => self::OK,
  184. 'message' => '',
  185. 'next-step' => 'after-db-create',
  186. 'next-step-label' => 'Creating Profiles',
  187. 'percentage-completed' => 60,
  188. );
  189. break;
  190. case 'after-db-create':
  191. $sMode = $this->oParams->Get('mode');
  192. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  193. if ($sTargetEnvironment == '')
  194. {
  195. $sTargetEnvironment = 'production';
  196. }
  197. $sTargetDir = 'env-'.$sTargetEnvironment;
  198. $aDBParams = $this->oParams->Get('database');
  199. $sDBServer = $aDBParams['server'];
  200. $sDBUser = $aDBParams['user'];
  201. $sDBPwd = $aDBParams['pwd'];
  202. $sDBName = $aDBParams['name'];
  203. $sDBPrefix = $aDBParams['prefix'];
  204. $aAdminParams = $this->oParams->Get('admin_account');
  205. $sAdminUser = $aAdminParams['user'];
  206. $sAdminPwd = $aAdminParams['pwd'];
  207. $sAdminLanguage = $aAdminParams['language'];
  208. $sLanguage = $this->oParams->Get('language');
  209. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  210. self::AfterDBCreate($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment);
  211. $aResult = array(
  212. 'status' => self::OK,
  213. 'message' => '',
  214. 'next-step' => 'sample-data',
  215. 'next-step-label' => 'Loading Sample Data',
  216. 'percentage-completed' => 80,
  217. );
  218. $bLoadData = ($this->oParams->Get('sample_data', 0) == 1);
  219. if (!$bLoadData)
  220. {
  221. $aResult['next-step'] = 'create-config';
  222. $aResult['next-step-label'] = 'Creating the Configuration File';
  223. }
  224. break;
  225. case 'sample-data':
  226. $aSelectedModules = $this->oParams->Get('selected_modules');
  227. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  228. $sTargetDir = 'env-'.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment);
  229. $aDBParams = $this->oParams->Get('database');
  230. $sDBServer = $aDBParams['server'];
  231. $sDBUser = $aDBParams['user'];
  232. $sDBPwd = $aDBParams['pwd'];
  233. $sDBName = $aDBParams['name'];
  234. $sDBPrefix = $aDBParams['prefix'];
  235. $aFiles = $this->oParams->Get('files', array());
  236. self::DoLoadFiles($aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment);
  237. $aResult = array(
  238. 'status' => self::INFO,
  239. 'message' => 'All data loaded',
  240. 'next-step' => 'create-config',
  241. 'next-step-label' => 'Creating the Configuration File',
  242. 'percentage-completed' => 99,
  243. );
  244. break;
  245. case 'create-config':
  246. $sMode = $this->oParams->Get('mode');
  247. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  248. if ($sTargetEnvironment == '')
  249. {
  250. $sTargetEnvironment = 'production';
  251. }
  252. $sTargetDir = 'env-'.$sTargetEnvironment;
  253. $aDBParams = $this->oParams->Get('database');
  254. $sDBServer = $aDBParams['server'];
  255. $sDBUser = $aDBParams['user'];
  256. $sDBPwd = $aDBParams['pwd'];
  257. $sDBName = $aDBParams['name'];
  258. $sDBPrefix = $aDBParams['prefix'];
  259. $sUrl = $this->oParams->Get('url', '');
  260. $sLanguage = $this->oParams->Get('language', '');
  261. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  262. self::DoCreateConfig($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment);
  263. $aResult = array(
  264. 'status' => self::INFO,
  265. 'message' => 'Configuration file created',
  266. 'next-step' => '',
  267. 'next-step-label' => 'Completed',
  268. 'percentage-completed' => 100,
  269. );
  270. break;
  271. default:
  272. $aResult = array(
  273. 'status' => self::ERROR,
  274. 'message' => '',
  275. 'next-step' => '',
  276. 'next-step-label' => "Unknown setup step '$sStep'.",
  277. 'percentage-completed' => 100,
  278. );
  279. }
  280. }
  281. catch(Exception $e)
  282. {
  283. $aResult = array(
  284. 'status' => self::ERROR,
  285. 'message' => $e->getMessage(),
  286. 'next-step' => '',
  287. 'next-step-label' => '',
  288. 'percentage-completed' => 100,
  289. );
  290. }
  291. return $aResult;
  292. }
  293. protected static function DoCopy($aCopies)
  294. {
  295. $aReports = array();
  296. foreach ($aCopies as $aCopy)
  297. {
  298. $sSource = $aCopy['source'];
  299. $sDestination = APPROOT.$aCopy['destination'];
  300. SetupUtils::builddir($sDestination);
  301. SetupUtils::tidydir($sDestination);
  302. SetupUtils::copydir($sSource, $sDestination);
  303. $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)";
  304. }
  305. if (count($aReports) > 0)
  306. {
  307. $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports);
  308. }
  309. else
  310. {
  311. $sReport = "No file copy";
  312. }
  313. return $sReport;
  314. }
  315. protected static function DoBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sBackupFile, $sSourceConfigFile)
  316. {
  317. $oBackup = new DBBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix);
  318. $sZipFile = $oBackup->MakeName($sBackupFile);
  319. $oBackup->CreateZip($sZipFile, $sSourceConfigFile);
  320. }
  321. protected static function DoCompile($aSelectedModules, $sSourceDir, $sTargetDir, $sWorkspaceDir = '')
  322. {
  323. SetupPage::log_info("Compiling data model.");
  324. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  325. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  326. require_once(APPROOT.'setup/compiler.class.inc.php');
  327. if (empty($sSourceDir) || empty($sTargetDir))
  328. {
  329. throw new Exception("missing parameter source_dir and/or target_dir");
  330. }
  331. $sSourcePath = APPROOT.$sSourceDir;
  332. $sTargetPath = APPROOT.$sTargetDir;
  333. if (!is_dir($sSourcePath))
  334. {
  335. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  336. }
  337. if (!is_dir($sTargetPath) && !mkdir($sTargetPath))
  338. {
  339. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  340. }
  341. // owner:rwx user/group:rx
  342. chmod($sTargetPath, 0755);
  343. $oFactory = new ModelFactory($sSourcePath);
  344. $aModules = $oFactory->FindModules();
  345. foreach($aModules as $foo => $oModule)
  346. {
  347. $sModule = $oModule->GetName();
  348. if (in_array($sModule, $aSelectedModules))
  349. {
  350. $oFactory->LoadModule($oModule);
  351. }
  352. }
  353. if (strlen($sWorkspaceDir) > 0)
  354. {
  355. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspaceDir);
  356. if (file_exists($oWorkspace->GetWorkspacePath()))
  357. {
  358. $oFactory->LoadModule($oWorkspace);
  359. }
  360. }
  361. //$oFactory->Dump();
  362. if ($oFactory->HasLoadErrors())
  363. {
  364. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  365. {
  366. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  367. foreach($aErrors as $oXmlError)
  368. {
  369. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  370. }
  371. }
  372. throw new Exception("The data model could not be compiled. Please check the setup error log");
  373. }
  374. else
  375. {
  376. $oMFCompiler = new MFCompiler($oFactory, $sSourcePath);
  377. $oMFCompiler->Compile($sTargetPath);
  378. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  379. }
  380. }
  381. protected static function DoUpdateDBSchema($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  382. {
  383. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  384. $oConfig = new Config();
  385. $aParamValues = array(
  386. 'db_server' => $sDBServer,
  387. 'db_user' => $sDBUser,
  388. 'db_pwd' => $sDBPwd,
  389. 'db_name' => $sDBName,
  390. 'db_prefix' => $sDBPrefix,
  391. );
  392. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  393. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  394. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  395. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  396. {
  397. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  398. }
  399. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  400. }
  401. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  402. {
  403. SetupPage::log_info('After Database Creation');
  404. $oConfig = new Config();
  405. $aParamValues = array(
  406. 'db_server' => $sDBServer,
  407. 'db_user' => $sDBUser,
  408. 'db_pwd' => $sDBPwd,
  409. 'db_name' => $sDBName,
  410. 'db_prefix' => $sDBPrefix,
  411. );
  412. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  413. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  414. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  415. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  416. // Perform here additional DB setup... profiles, etc...
  417. //
  418. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), $sModulesDir);
  419. foreach($aAvailableModules as $sModuleId => $aModule)
  420. {
  421. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  422. isset($aAvailableModules[$sModuleId]['installer']) )
  423. {
  424. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  425. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  426. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  427. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  428. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  429. }
  430. }
  431. // Constant classes (e.g. User profiles)
  432. //
  433. foreach (MetaModel::GetClasses() as $sClass)
  434. {
  435. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  436. if ($aPredefinedObjects != null)
  437. {
  438. // Temporary... until this get really encapsulated as the default and transparent behavior
  439. $oMyChange = MetaModel::NewObject("CMDBChange");
  440. $oMyChange->Set("date", time());
  441. $sUserString = CMDBChange::GetCurrentUserName();
  442. $oMyChange->Set("userinfo", $sUserString);
  443. $iChangeId = $oMyChange->DBInsert();
  444. // Create/Delete/Update objects of this class,
  445. // according to the given constant values
  446. //
  447. $aDBIds = array();
  448. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  449. while ($oObj = $oAll->Fetch())
  450. {
  451. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  452. {
  453. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  454. foreach ($aObjValues as $sAttCode => $value)
  455. {
  456. $oObj->Set($sAttCode, $value);
  457. }
  458. $oObj->DBUpdateTracked($oMyChange);
  459. $aDBIds[$oObj->GetKey()] = true;
  460. }
  461. else
  462. {
  463. $oObj->DBDeleteTracked($oMyChange);
  464. }
  465. }
  466. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  467. {
  468. if (!array_key_exists($iRefId, $aDBIds))
  469. {
  470. $oNewObj = MetaModel::NewObject($sClass);
  471. $oNewObj->SetKey($iRefId);
  472. foreach ($aObjValues as $sAttCode => $value)
  473. {
  474. $oNewObj->Set($sAttCode, $value);
  475. }
  476. $oNewObj->DBInsertTracked($oMyChange);
  477. }
  478. }
  479. }
  480. }
  481. if (!$oProductionEnv->RecordInstallation($oConfig, $aSelectedModules, $sModulesDir))
  482. {
  483. throw new Exception("Failed to record the installation information");
  484. }
  485. if($sMode == 'install')
  486. {
  487. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  488. {
  489. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  490. }
  491. else
  492. {
  493. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  494. }
  495. }
  496. }
  497. /**
  498. * Helper function to create and administrator account for iTop
  499. * @return boolean true on success, false otherwise
  500. */
  501. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  502. {
  503. SetupPage::log_info('CreateAdminAccount');
  504. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  505. {
  506. return true;
  507. }
  508. else
  509. {
  510. return false;
  511. }
  512. }
  513. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  514. {
  515. $aParamValues = array(
  516. 'db_server' => $sDBServer,
  517. 'db_user' => $sDBUser,
  518. 'db_pwd' => $sDBPwd,
  519. 'db_name' => $sDBName,
  520. 'new_db_name' => $sDBName,
  521. 'db_prefix' => $sDBPrefix,
  522. );
  523. $oConfig = new Config();
  524. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  525. //Load the MetaModel if needed (asynchronous mode)
  526. if (!self::$bMetaModelStarted)
  527. {
  528. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  529. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  530. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  531. }
  532. $oDataLoader = new XMLDataLoader();
  533. $oChange = MetaModel::NewObject("CMDBChange");
  534. $oChange->Set("date", time());
  535. $oChange->Set("userinfo", "Initialization");
  536. $iChangeId = $oChange->DBInsert();
  537. SetupPage::log_info("starting data load session");
  538. $oDataLoader->StartSession($oChange);
  539. $aFiles = array();
  540. $oProductionEnv = new RunTimeEnvironment();
  541. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $sModulesDir);
  542. foreach($aAvailableModules as $sModuleId => $aModule)
  543. {
  544. if (($sModuleId != ROOT_MODULE))
  545. {
  546. if (in_array($sModuleId, $aSelectedModules))
  547. {
  548. $aFiles = array_merge(
  549. $aFiles,
  550. $aAvailableModules[$sModuleId]['data.struct'],
  551. $aAvailableModules[$sModuleId]['data.sample']
  552. );
  553. }
  554. }
  555. }
  556. foreach($aFiles as $sFileRelativePath)
  557. {
  558. $sFileName = APPROOT.$sFileRelativePath;
  559. SetupPage::log_info("Loading file: $sFileName");
  560. if (empty($sFileName) || !file_exists($sFileName))
  561. {
  562. throw(new Exception("File $sFileName does not exist"));
  563. }
  564. $oDataLoader->LoadFile($sFileName);
  565. $sResult = sprintf("loading of %s done.", basename($sFileName));
  566. SetupPage::log_info($sResult);
  567. }
  568. $oDataLoader->EndSession();
  569. SetupPage::log_info("ending data load session");
  570. }
  571. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  572. {
  573. $aParamValues = array(
  574. 'db_server' => $sDBServer,
  575. 'db_user' => $sDBUser,
  576. 'db_pwd' => $sDBPwd,
  577. 'db_name' => $sDBName,
  578. 'new_db_name' => $sDBName,
  579. 'db_prefix' => $sDBPrefix,
  580. 'application_path' => $sUrl,
  581. 'mode' => $sMode,
  582. 'language' => $sLanguage,
  583. 'selected_modules' => implode(',', $aSelectedModules),
  584. );
  585. $oConfig = new Config();
  586. // Migration: force utf8_unicode_ci as the collation to make the global search
  587. // NON case sensitive
  588. $oConfig->SetDBCollation('utf8_unicode_ci');
  589. // Final config update: add the modules
  590. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  591. // Make sure the root configuration directory exists
  592. if (!file_exists(APPCONF))
  593. {
  594. mkdir(APPCONF);
  595. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  596. SetupPage::log_info("Created configuration directory: ".APPCONF);
  597. }
  598. // Write the final configuration file
  599. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  600. $sConfigDir = dirname($sConfigFile);
  601. @mkdir($sConfigDir);
  602. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  603. $oConfig->WriteToFile($sConfigFile);
  604. // try to make the final config file read-only
  605. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  606. }
  607. }