applicationinstaller.class.inc.php 25 KB

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