applicationinstaller.class.inc.php 23 KB

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