applicationinstaller.class.inc.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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))
  339. {
  340. if (!mkdir($sTargetPath))
  341. {
  342. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  343. }
  344. else
  345. {
  346. // adjust the rights if and only if the directory was just created
  347. // owner:rwx user/group:rx
  348. chmod($sTargetPath, 0755);
  349. }
  350. }
  351. $oFactory = new ModelFactory($sSourcePath);
  352. $aModules = $oFactory->FindModules();
  353. foreach($aModules as $foo => $oModule)
  354. {
  355. $sModule = $oModule->GetName();
  356. if (in_array($sModule, $aSelectedModules))
  357. {
  358. $oFactory->LoadModule($oModule);
  359. }
  360. }
  361. if (strlen($sWorkspaceDir) > 0)
  362. {
  363. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspaceDir);
  364. if (file_exists($oWorkspace->GetWorkspacePath()))
  365. {
  366. $oFactory->LoadModule($oWorkspace);
  367. }
  368. }
  369. //$oFactory->Dump();
  370. if ($oFactory->HasLoadErrors())
  371. {
  372. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  373. {
  374. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  375. foreach($aErrors as $oXmlError)
  376. {
  377. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  378. }
  379. }
  380. throw new Exception("The data model could not be compiled. Please check the setup error log");
  381. }
  382. else
  383. {
  384. $oMFCompiler = new MFCompiler($oFactory, $sSourcePath);
  385. $oMFCompiler->Compile($sTargetPath);
  386. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  387. }
  388. }
  389. protected static function DoUpdateDBSchema($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  390. {
  391. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  392. $oConfig = new Config();
  393. $aParamValues = array(
  394. 'db_server' => $sDBServer,
  395. 'db_user' => $sDBUser,
  396. 'db_pwd' => $sDBPwd,
  397. 'db_name' => $sDBName,
  398. 'db_prefix' => $sDBPrefix,
  399. );
  400. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  401. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  402. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  403. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  404. {
  405. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  406. }
  407. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  408. }
  409. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  410. {
  411. SetupPage::log_info('After Database Creation');
  412. $oConfig = new Config();
  413. $aParamValues = array(
  414. 'db_server' => $sDBServer,
  415. 'db_user' => $sDBUser,
  416. 'db_pwd' => $sDBPwd,
  417. 'db_name' => $sDBName,
  418. 'db_prefix' => $sDBPrefix,
  419. );
  420. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  421. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  422. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  423. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  424. // Perform here additional DB setup... profiles, etc...
  425. //
  426. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), $sModulesDir);
  427. foreach($aAvailableModules as $sModuleId => $aModule)
  428. {
  429. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  430. isset($aAvailableModules[$sModuleId]['installer']) )
  431. {
  432. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  433. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  434. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  435. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  436. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  437. }
  438. }
  439. // Constant classes (e.g. User profiles)
  440. //
  441. foreach (MetaModel::GetClasses() as $sClass)
  442. {
  443. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  444. if ($aPredefinedObjects != null)
  445. {
  446. // Temporary... until this get really encapsulated as the default and transparent behavior
  447. $oMyChange = MetaModel::NewObject("CMDBChange");
  448. $oMyChange->Set("date", time());
  449. $sUserString = CMDBChange::GetCurrentUserName();
  450. $oMyChange->Set("userinfo", $sUserString);
  451. $iChangeId = $oMyChange->DBInsert();
  452. // Create/Delete/Update objects of this class,
  453. // according to the given constant values
  454. //
  455. $aDBIds = array();
  456. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  457. while ($oObj = $oAll->Fetch())
  458. {
  459. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  460. {
  461. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  462. foreach ($aObjValues as $sAttCode => $value)
  463. {
  464. $oObj->Set($sAttCode, $value);
  465. }
  466. $oObj->DBUpdateTracked($oMyChange);
  467. $aDBIds[$oObj->GetKey()] = true;
  468. }
  469. else
  470. {
  471. $oObj->DBDeleteTracked($oMyChange);
  472. }
  473. }
  474. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  475. {
  476. if (!array_key_exists($iRefId, $aDBIds))
  477. {
  478. $oNewObj = MetaModel::NewObject($sClass);
  479. $oNewObj->SetKey($iRefId);
  480. foreach ($aObjValues as $sAttCode => $value)
  481. {
  482. $oNewObj->Set($sAttCode, $value);
  483. }
  484. $oNewObj->DBInsertTracked($oMyChange);
  485. }
  486. }
  487. }
  488. }
  489. if (!$oProductionEnv->RecordInstallation($oConfig, $aSelectedModules, $sModulesDir))
  490. {
  491. throw new Exception("Failed to record the installation information");
  492. }
  493. if($sMode == 'install')
  494. {
  495. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  496. {
  497. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  498. }
  499. else
  500. {
  501. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  502. }
  503. }
  504. }
  505. /**
  506. * Helper function to create and administrator account for iTop
  507. * @return boolean true on success, false otherwise
  508. */
  509. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  510. {
  511. SetupPage::log_info('CreateAdminAccount');
  512. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  513. {
  514. return true;
  515. }
  516. else
  517. {
  518. return false;
  519. }
  520. }
  521. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '')
  522. {
  523. $aParamValues = array(
  524. 'db_server' => $sDBServer,
  525. 'db_user' => $sDBUser,
  526. 'db_pwd' => $sDBPwd,
  527. 'db_name' => $sDBName,
  528. 'new_db_name' => $sDBName,
  529. 'db_prefix' => $sDBPrefix,
  530. );
  531. $oConfig = new Config();
  532. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  533. //Load the MetaModel if needed (asynchronous mode)
  534. if (!self::$bMetaModelStarted)
  535. {
  536. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  537. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  538. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  539. }
  540. $oDataLoader = new XMLDataLoader();
  541. $oChange = MetaModel::NewObject("CMDBChange");
  542. $oChange->Set("date", time());
  543. $oChange->Set("userinfo", "Initialization");
  544. $iChangeId = $oChange->DBInsert();
  545. SetupPage::log_info("starting data load session");
  546. $oDataLoader->StartSession($oChange);
  547. $aFiles = array();
  548. $oProductionEnv = new RunTimeEnvironment();
  549. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $sModulesDir);
  550. foreach($aAvailableModules as $sModuleId => $aModule)
  551. {
  552. if (($sModuleId != ROOT_MODULE))
  553. {
  554. if (in_array($sModuleId, $aSelectedModules))
  555. {
  556. $aFiles = array_merge(
  557. $aFiles,
  558. $aAvailableModules[$sModuleId]['data.struct'],
  559. $aAvailableModules[$sModuleId]['data.sample']
  560. );
  561. }
  562. }
  563. }
  564. foreach($aFiles as $sFileRelativePath)
  565. {
  566. $sFileName = APPROOT.$sFileRelativePath;
  567. SetupPage::log_info("Loading file: $sFileName");
  568. if (empty($sFileName) || !file_exists($sFileName))
  569. {
  570. throw(new Exception("File $sFileName does not exist"));
  571. }
  572. $oDataLoader->LoadFile($sFileName);
  573. $sResult = sprintf("loading of %s done.", basename($sFileName));
  574. SetupPage::log_info($sResult);
  575. }
  576. $oDataLoader->EndSession();
  577. SetupPage::log_info("ending data load session");
  578. }
  579. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment = '')
  580. {
  581. $aParamValues = array(
  582. 'db_server' => $sDBServer,
  583. 'db_user' => $sDBUser,
  584. 'db_pwd' => $sDBPwd,
  585. 'db_name' => $sDBName,
  586. 'new_db_name' => $sDBName,
  587. 'db_prefix' => $sDBPrefix,
  588. 'application_path' => $sUrl,
  589. 'mode' => $sMode,
  590. 'language' => $sLanguage,
  591. 'selected_modules' => implode(',', $aSelectedModules),
  592. );
  593. $oConfig = new Config();
  594. // Migration: force utf8_unicode_ci as the collation to make the global search
  595. // NON case sensitive
  596. $oConfig->SetDBCollation('utf8_unicode_ci');
  597. // Final config update: add the modules
  598. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  599. // Make sure the root configuration directory exists
  600. if (!file_exists(APPCONF))
  601. {
  602. mkdir(APPCONF);
  603. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  604. SetupPage::log_info("Created configuration directory: ".APPCONF);
  605. }
  606. // Write the final configuration file
  607. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  608. $sConfigDir = dirname($sConfigFile);
  609. @mkdir($sConfigDir);
  610. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  611. $oConfig->WriteToFile($sConfigFile);
  612. // try to make the final config file read-only
  613. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  614. }
  615. }