applicationinstaller.class.inc.php 21 KB

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