applicationinstaller.class.inc.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. // disabled - $sReport = self::DoCopy($aCopies);
  116. $sReport = "copy disabled...";
  117. $aResult = array(
  118. 'status' => self::OK,
  119. 'message' => $sReport,
  120. );
  121. if (isset($aPreinstall['backup']))
  122. {
  123. $aResult['next-step'] = 'backup';
  124. $aResult['next-step-label'] = 'Backuping the database';
  125. $aResult['percentage-completed'] = 20;
  126. }
  127. else
  128. {
  129. $aResult['next-step'] = 'compile';
  130. $aResult['next-step-label'] = 'Compiling the data model';
  131. $aResult['percentage-completed'] = 20;
  132. }
  133. break;
  134. case 'backup':
  135. $aPreinstall = $this->oParams->Get('preinstall');
  136. // __DB__-%Y-%m-%d.zip
  137. $sDestination = $aPreinstall['backup']['destination'];
  138. $sSourceConfigFile = $aPreinstall['backup']['configuration_file'];
  139. $aDBParams = $this->oParams->Get('database');
  140. self::DoBackup($aDBParams['server'], $aDBParams['user'], $aDBParams['pwd'], $aDBParams['name'], $aDBParams['prefix'], $sDestination, $sSourceConfigFile);
  141. $aResult = array(
  142. 'status' => self::OK,
  143. 'message' => "Created backup",
  144. 'next-step' => 'compile',
  145. 'next-step-label' => 'Compiling the data model',
  146. 'percentage-completed' => 20,
  147. );
  148. break;
  149. case 'compile':
  150. $aSelectedModules = $this->oParams->Get('selected_modules');
  151. $sSourceDir = $this->oParams->Get('source_dir', 'datamodel');
  152. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  153. if ($sTargetEnvironment == '')
  154. {
  155. $sTargetEnvironment = 'production';
  156. }
  157. $sTargetDir = 'env-'.$sTargetEnvironment;
  158. $sWorkspaceDir = $this->oParams->Get('workspace_dir', 'workspace');
  159. self::DoCompile($aSelectedModules, $sSourceDir, $sTargetDir, $sWorkspaceDir);
  160. $aResult = array(
  161. 'status' => self::OK,
  162. 'message' => '',
  163. 'next-step' => 'db-schema',
  164. 'next-step-label' => 'Updating database schema',
  165. 'percentage-completed' => 40,
  166. );
  167. break;
  168. case 'db-schema':
  169. $sMode = $this->oParams->Get('mode');
  170. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  171. if ($sTargetEnvironment == '')
  172. {
  173. $sTargetEnvironment = 'production';
  174. }
  175. $sTargetDir = 'env-'.$sTargetEnvironment;
  176. $aDBParams = $this->oParams->Get('database');
  177. $sDBServer = $aDBParams['server'];
  178. $sDBUser = $aDBParams['user'];
  179. $sDBPwd = $aDBParams['pwd'];
  180. $sDBName = $aDBParams['name'];
  181. $sDBPrefix = $aDBParams['prefix'];
  182. self::DoUpdateDBSchema($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment);
  183. $aResult = array(
  184. 'status' => self::OK,
  185. 'message' => '',
  186. 'next-step' => 'after-db-create',
  187. 'next-step-label' => 'Creating Profiles',
  188. 'percentage-completed' => 60,
  189. );
  190. break;
  191. case 'after-db-create':
  192. $sMode = $this->oParams->Get('mode');
  193. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  194. if ($sTargetEnvironment == '')
  195. {
  196. $sTargetEnvironment = 'production';
  197. }
  198. $sTargetDir = 'env-'.$sTargetEnvironment;
  199. $aDBParams = $this->oParams->Get('database');
  200. $sDBServer = $aDBParams['server'];
  201. $sDBUser = $aDBParams['user'];
  202. $sDBPwd = $aDBParams['pwd'];
  203. $sDBName = $aDBParams['name'];
  204. $sDBPrefix = $aDBParams['prefix'];
  205. $aAdminParams = $this->oParams->Get('admin_account');
  206. $sAdminUser = $aAdminParams['user'];
  207. $sAdminPwd = $aAdminParams['pwd'];
  208. $sAdminLanguage = $aAdminParams['language'];
  209. $sLanguage = $this->oParams->Get('language');
  210. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  211. self::AfterDBCreate($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment);
  212. $aResult = array(
  213. 'status' => self::OK,
  214. 'message' => '',
  215. 'next-step' => 'sample-data',
  216. 'next-step-label' => 'Loading Sample Data',
  217. 'percentage-completed' => 80,
  218. );
  219. $bLoadData = ($this->oParams->Get('sample_data', 0) == 1);
  220. if (!$bLoadData)
  221. {
  222. $aResult['next-step'] = 'create-config';
  223. $aResult['next-step-label'] = 'Creating the Configuration File';
  224. }
  225. break;
  226. case 'sample-data':
  227. $aSelectedModules = $this->oParams->Get('selected_modules');
  228. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  229. $sTargetDir = 'env-'.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment);
  230. $aDBParams = $this->oParams->Get('database');
  231. $sDBServer = $aDBParams['server'];
  232. $sDBUser = $aDBParams['user'];
  233. $sDBPwd = $aDBParams['pwd'];
  234. $sDBName = $aDBParams['name'];
  235. $sDBPrefix = $aDBParams['prefix'];
  236. $aFiles = $this->oParams->Get('files', array());
  237. self::DoLoadFiles($aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment);
  238. $aResult = array(
  239. 'status' => self::INFO,
  240. 'message' => 'All data loaded',
  241. 'next-step' => 'create-config',
  242. 'next-step-label' => 'Creating the Configuration File',
  243. 'percentage-completed' => 99,
  244. );
  245. break;
  246. case 'create-config':
  247. $sMode = $this->oParams->Get('mode');
  248. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  249. if ($sTargetEnvironment == '')
  250. {
  251. $sTargetEnvironment = 'production';
  252. }
  253. $sTargetDir = 'env-'.$sTargetEnvironment;
  254. $aDBParams = $this->oParams->Get('database');
  255. $sDBServer = $aDBParams['server'];
  256. $sDBUser = $aDBParams['user'];
  257. $sDBPwd = $aDBParams['pwd'];
  258. $sDBName = $aDBParams['name'];
  259. $sDBPrefix = $aDBParams['prefix'];
  260. $sUrl = $this->oParams->Get('url', '');
  261. $sLanguage = $this->oParams->Get('language', '');
  262. $aSelectedModules = $this->oParams->Get('selected_modules', array());
  263. self::DoCreateConfig($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment);
  264. $aResult = array(
  265. 'status' => self::INFO,
  266. 'message' => 'Configuration file created',
  267. 'next-step' => '',
  268. 'next-step-label' => 'Completed',
  269. 'percentage-completed' => 100,
  270. );
  271. break;
  272. default:
  273. $aResult = array(
  274. 'status' => self::ERROR,
  275. 'message' => '',
  276. 'next-step' => '',
  277. 'next-step-label' => "Unknown setup step '$sStep'.",
  278. 'percentage-completed' => 100,
  279. );
  280. }
  281. }
  282. catch(Exception $e)
  283. {
  284. $aResult = array(
  285. 'status' => self::ERROR,
  286. 'message' => $e->getMessage(),
  287. 'next-step' => '',
  288. 'next-step-label' => '',
  289. 'percentage-completed' => 100,
  290. );
  291. }
  292. return $aResult;
  293. }
  294. protected static function DoCopy($aCopies)
  295. {
  296. $aReports = array();
  297. foreach ($aCopies as $aCopy)
  298. {
  299. $sSource = $aCopy['source'];
  300. $sDestination = APPROOT.$aCopy['destination'];
  301. SetupUtils::builddir($sDestination);
  302. SetupUtils::tidydir($sDestination);
  303. SetupUtils::copydir($sSource, $sDestination);
  304. $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)";
  305. }
  306. if (count($aReports) > 0)
  307. {
  308. $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports);
  309. }
  310. else
  311. {
  312. $sReport = "No file copy";
  313. }
  314. return $sReport;
  315. }
  316. protected static function DoBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sBackupFile, $sSourceConfigFile)
  317. {
  318. $oBackup = new DBBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix);
  319. $sZipFile = $oBackup->MakeName($sBackupFile);
  320. $oBackup->CreateZip($sZipFile, $sSourceConfigFile);
  321. }
  322. protected static function DoCompile($aSelectedModules, $sSourceDir, $sTargetDir, $sWorkspaceDir = '')
  323. {
  324. SetupPage::log_info("Compiling data model.");
  325. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  326. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  327. require_once(APPROOT.'setup/compiler.class.inc.php');
  328. if (empty($sSourceDir) || empty($sTargetDir))
  329. {
  330. throw new Exception("missing parameter source_dir and/or target_dir");
  331. }
  332. $sSourcePath = APPROOT.$sSourceDir;
  333. $sTargetPath = APPROOT.$sTargetDir;
  334. if (!is_dir($sSourcePath))
  335. {
  336. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  337. }
  338. if (!is_dir($sTargetPath) && !mkdir($sTargetPath))
  339. {
  340. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  341. }
  342. // owner:rwx user/group:rx
  343. chmod($sTargetPath, 0755);
  344. $oFactory = new ModelFactory($sSourcePath);
  345. $aModules = $oFactory->FindModules();
  346. foreach($aModules as $foo => $oModule)
  347. {
  348. $sModule = $oModule->GetName();
  349. if (in_array($sModule, $aSelectedModules))
  350. {
  351. $oFactory->LoadModule($oModule);
  352. }
  353. }
  354. if (strlen($sWorkspaceDir) > 0)
  355. {
  356. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspaceDir);
  357. if (file_exists($oWorkspace->GetWorkspacePath()))
  358. {
  359. $oFactory->LoadModule($oWorkspace);
  360. }
  361. }
  362. //$oFactory->Dump();
  363. if ($oFactory->HasLoadErrors())
  364. {
  365. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  366. {
  367. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  368. foreach($aErrors as $oXmlError)
  369. {
  370. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  371. }
  372. }
  373. throw new Exception("The data model could not be compiled. Please check the setup error log");
  374. }
  375. else
  376. {
  377. $oMFCompiler = new MFCompiler($oFactory, $sSourcePath);
  378. $oMFCompiler->Compile($sTargetPath);
  379. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  380. }
  381. }
  382. protected static function DoUpdateDBSchema($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  383. {
  384. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  385. $oConfig = new Config();
  386. $aParamValues = array(
  387. 'db_server' => $sDBServer,
  388. 'db_user' => $sDBUser,
  389. 'db_pwd' => $sDBPwd,
  390. 'db_name' => $sDBName,
  391. 'db_prefix' => $sDBPrefix,
  392. );
  393. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  394. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  395. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  396. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  397. {
  398. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  399. }
  400. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  401. }
  402. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  403. {
  404. SetupPage::log_info('After Database Creation');
  405. $oConfig = new Config();
  406. $aParamValues = array(
  407. 'db_server' => $sDBServer,
  408. 'db_user' => $sDBUser,
  409. 'db_pwd' => $sDBPwd,
  410. 'db_name' => $sDBName,
  411. 'db_prefix' => $sDBPrefix,
  412. );
  413. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  414. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  415. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  416. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  417. // Perform here additional DB setup... profiles, etc...
  418. //
  419. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), $sModulesDir);
  420. foreach($aAvailableModules as $sModuleId => $aModule)
  421. {
  422. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  423. isset($aAvailableModules[$sModuleId]['installer']) )
  424. {
  425. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  426. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  427. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  428. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  429. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  430. }
  431. }
  432. // Constant classes (e.g. User profiles)
  433. //
  434. foreach (MetaModel::GetClasses() as $sClass)
  435. {
  436. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  437. if ($aPredefinedObjects != null)
  438. {
  439. // Temporary... until this get really encapsulated as the default and transparent behavior
  440. $oMyChange = MetaModel::NewObject("CMDBChange");
  441. $oMyChange->Set("date", time());
  442. $sUserString = CMDBChange::GetCurrentUserName();
  443. $oMyChange->Set("userinfo", $sUserString);
  444. $iChangeId = $oMyChange->DBInsert();
  445. // Create/Delete/Update objects of this class,
  446. // according to the given constant values
  447. //
  448. $aDBIds = array();
  449. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  450. while ($oObj = $oAll->Fetch())
  451. {
  452. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  453. {
  454. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  455. foreach ($aObjValues as $sAttCode => $value)
  456. {
  457. $oObj->Set($sAttCode, $value);
  458. }
  459. $oObj->DBUpdateTracked($oMyChange);
  460. $aDBIds[$oObj->GetKey()] = true;
  461. }
  462. else
  463. {
  464. $oObj->DBDeleteTracked($oMyChange);
  465. }
  466. }
  467. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  468. {
  469. if (!array_key_exists($iRefId, $aDBIds))
  470. {
  471. $oNewObj = MetaModel::NewObject($sClass);
  472. $oNewObj->SetKey($iRefId);
  473. foreach ($aObjValues as $sAttCode => $value)
  474. {
  475. $oNewObj->Set($sAttCode, $value);
  476. }
  477. $oNewObj->DBInsertTracked($oMyChange);
  478. }
  479. }
  480. }
  481. }
  482. if (!$oProductionEnv->RecordInstallation($oConfig, $aSelectedModules, $sModulesDir))
  483. {
  484. throw new Exception("Failed to record the installation information");
  485. }
  486. if($sMode == 'install')
  487. {
  488. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  489. {
  490. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  491. }
  492. else
  493. {
  494. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  495. }
  496. }
  497. }
  498. /**
  499. * Helper function to create and administrator account for iTop
  500. * @return boolean true on success, false otherwise
  501. */
  502. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  503. {
  504. SetupPage::log_info('CreateAdminAccount');
  505. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  506. {
  507. return true;
  508. }
  509. else
  510. {
  511. return false;
  512. }
  513. }
  514. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  515. {
  516. $aParamValues = array(
  517. 'db_server' => $sDBServer,
  518. 'db_user' => $sDBUser,
  519. 'db_pwd' => $sDBPwd,
  520. 'db_name' => $sDBName,
  521. 'new_db_name' => $sDBName,
  522. 'db_prefix' => $sDBPrefix,
  523. );
  524. $oConfig = new Config();
  525. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  526. //Load the MetaModel if needed (asynchronous mode)
  527. if (!self::$bMetaModelStarted)
  528. {
  529. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  530. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  531. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  532. }
  533. $oDataLoader = new XMLDataLoader();
  534. $oChange = MetaModel::NewObject("CMDBChange");
  535. $oChange->Set("date", time());
  536. $oChange->Set("userinfo", "Initialization");
  537. $iChangeId = $oChange->DBInsert();
  538. SetupPage::log_info("starting data load session");
  539. $oDataLoader->StartSession($oChange);
  540. $aFiles = array();
  541. $oProductionEnv = new RunTimeEnvironment();
  542. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $sModulesDir);
  543. foreach($aAvailableModules as $sModuleId => $aModule)
  544. {
  545. if (($sModuleId != ROOT_MODULE))
  546. {
  547. if (in_array($sModuleId, $aSelectedModules))
  548. {
  549. $aFiles = array_merge(
  550. $aFiles,
  551. $aAvailableModules[$sModuleId]['data.struct'],
  552. $aAvailableModules[$sModuleId]['data.sample']
  553. );
  554. }
  555. }
  556. }
  557. foreach($aFiles as $sFileRelativePath)
  558. {
  559. $sFileName = APPROOT.$sFileRelativePath;
  560. SetupPage::log_info("Loading file: $sFileName");
  561. if (empty($sFileName) || !file_exists($sFileName))
  562. {
  563. throw(new Exception("File $sFileName does not exist"));
  564. }
  565. $oDataLoader->LoadFile($sFileName);
  566. $sResult = sprintf("loading of %s done.", basename($sFileName));
  567. SetupPage::log_info($sResult);
  568. }
  569. $oDataLoader->EndSession();
  570. SetupPage::log_info("ending data load session");
  571. }
  572. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  573. {
  574. $aParamValues = array(
  575. 'db_server' => $sDBServer,
  576. 'db_user' => $sDBUser,
  577. 'db_pwd' => $sDBPwd,
  578. 'db_name' => $sDBName,
  579. 'new_db_name' => $sDBName,
  580. 'db_prefix' => $sDBPrefix,
  581. 'application_path' => $sUrl,
  582. 'mode' => $sMode,
  583. 'language' => $sLanguage,
  584. 'selected_modules' => implode(',', $aSelectedModules),
  585. );
  586. $oConfig = new Config();
  587. // Migration: force utf8_unicode_ci as the collation to make the global search
  588. // NON case sensitive
  589. $oConfig->SetDBCollation('utf8_unicode_ci');
  590. // Final config update: add the modules
  591. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  592. // Make sure the root configuration directory exists
  593. if (!file_exists(APPCONF))
  594. {
  595. mkdir(APPCONF);
  596. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  597. SetupPage::log_info("Created configuration directory: ".APPCONF);
  598. }
  599. // Write the final configuration file
  600. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  601. $sConfigDir = dirname($sConfigFile);
  602. @mkdir($sConfigDir);
  603. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  604. $oConfig->WriteToFile($sConfigFile);
  605. // try to make the final config file read-only
  606. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  607. }
  608. }