applicationinstaller.class.inc.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 = "Copying...";
  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'] = 'Performing a backup of 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. $aDirsToScan = array($sSourcePath);
  360. $sExtensionsPath = APPROOT.$sExtensionDir;
  361. if (is_dir($sExtensionsPath))
  362. {
  363. // if the extensions dir exists, scan it for additional modules as well
  364. $aDirsToScan[] = $sExtensionsPath;
  365. }
  366. $sTargetPath = APPROOT.$sTargetDir;
  367. if (!is_dir($sSourcePath))
  368. {
  369. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  370. }
  371. if (!is_dir($sTargetPath))
  372. {
  373. if (!mkdir($sTargetPath))
  374. {
  375. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  376. }
  377. else
  378. {
  379. // adjust the rights if and only if the directory was just created
  380. // owner:rwx user/group:rx
  381. chmod($sTargetPath, 0755);
  382. }
  383. }
  384. $oFactory = new ModelFactory($aDirsToScan);
  385. $aModules = $oFactory->FindModules();
  386. foreach($aModules as $foo => $oModule)
  387. {
  388. $sModule = $oModule->GetName();
  389. if (in_array($sModule, $aSelectedModules))
  390. {
  391. $oFactory->LoadModule($oModule);
  392. }
  393. }
  394. if (strlen($sWorkspaceDir) > 0)
  395. {
  396. $oWorkspace = new MFWorkspace(APPROOT.$sWorkspaceDir);
  397. if (file_exists($oWorkspace->GetWorkspacePath()))
  398. {
  399. $oFactory->LoadModule($oWorkspace);
  400. }
  401. }
  402. //$oFactory->Dump();
  403. if ($oFactory->HasLoadErrors())
  404. {
  405. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  406. {
  407. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  408. foreach($aErrors as $oXmlError)
  409. {
  410. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  411. }
  412. }
  413. throw new Exception("The data model could not be compiled. Please check the setup error log");
  414. }
  415. else
  416. {
  417. $oMFCompiler = new MFCompiler($oFactory);
  418. $oMFCompiler->Compile($sTargetPath, null, $bUseSymbolicLinks);
  419. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  420. }
  421. // Special case to patch a ugly patch in itop-config-mgmt
  422. $sFileToPatch = $sTargetPath.'/itop-config-mgmt-1.0.0/model.itop-config-mgmt.php';
  423. if (file_exists($sFileToPatch))
  424. {
  425. $sContent = file_get_contents($sFileToPatch);
  426. $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);
  427. file_put_contents($sFileToPatch, $sContent);
  428. }
  429. }
  430. protected static function DoUpdateDBSchema($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  431. {
  432. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  433. $oConfig = new Config();
  434. $aParamValues = array(
  435. 'db_server' => $sDBServer,
  436. 'db_user' => $sDBUser,
  437. 'db_pwd' => $sDBPwd,
  438. 'db_name' => $sDBName,
  439. 'db_prefix' => $sDBPrefix,
  440. );
  441. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  442. if ($bOldAddon)
  443. {
  444. // Old version of the add-on for backward compatibility with pre-2.0 data models
  445. $oConfig->SetAddons(array(
  446. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  447. ));
  448. }
  449. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  450. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  451. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  452. {
  453. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  454. }
  455. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  456. }
  457. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sDataModelVersion, $sSourceDir)
  458. {
  459. SetupPage::log_info('After Database Creation');
  460. $oConfig = new Config();
  461. $aParamValues = array(
  462. 'db_server' => $sDBServer,
  463. 'db_user' => $sDBUser,
  464. 'db_pwd' => $sDBPwd,
  465. 'db_name' => $sDBName,
  466. 'db_prefix' => $sDBPrefix,
  467. );
  468. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  469. if ($bOldAddon)
  470. {
  471. // Old version of the add-on for backward compatibility with pre-2.0 data models
  472. $oConfig->SetAddons(array(
  473. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  474. ));
  475. }
  476. $oConfig->Set('source_dir', $sSourceDir); // Needed by RecordInstallation below
  477. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  478. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  479. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  480. // Perform here additional DB setup... profiles, etc...
  481. //
  482. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  483. foreach($aAvailableModules as $sModuleId => $aModule)
  484. {
  485. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  486. isset($aAvailableModules[$sModuleId]['installer']) )
  487. {
  488. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  489. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  490. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  491. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  492. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  493. }
  494. }
  495. // Constant classes (e.g. User profiles)
  496. //
  497. foreach (MetaModel::GetClasses() as $sClass)
  498. {
  499. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  500. if ($aPredefinedObjects != null)
  501. {
  502. SetupPage::log_info("$sClass::GetPredefinedObjects() returned ".count($aPredefinedObjects)." elements.");
  503. // Create/Delete/Update objects of this class,
  504. // according to the given constant values
  505. //
  506. $aDBIds = array();
  507. $oAll = new DBObjectSet(new DBObjectSearch($sClass));
  508. while ($oObj = $oAll->Fetch())
  509. {
  510. if (array_key_exists($oObj->GetKey(), $aPredefinedObjects))
  511. {
  512. $aObjValues = $aPredefinedObjects[$oObj->GetKey()];
  513. foreach ($aObjValues as $sAttCode => $value)
  514. {
  515. $oObj->Set($sAttCode, $value);
  516. }
  517. $oObj->DBUpdate();
  518. $aDBIds[$oObj->GetKey()] = true;
  519. }
  520. else
  521. {
  522. $oObj->DBDelete();
  523. }
  524. }
  525. foreach ($aPredefinedObjects as $iRefId => $aObjValues)
  526. {
  527. if (!array_key_exists($iRefId, $aDBIds))
  528. {
  529. $oNewObj = MetaModel::NewObject($sClass);
  530. $oNewObj->SetKey($iRefId);
  531. foreach ($aObjValues as $sAttCode => $value)
  532. {
  533. $oNewObj->Set($sAttCode, $value);
  534. }
  535. $oNewObj->DBInsert();
  536. }
  537. }
  538. }
  539. }
  540. if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModules, $sModulesDir))
  541. {
  542. throw new Exception("Failed to record the installation information");
  543. }
  544. if($sMode == 'install')
  545. {
  546. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  547. {
  548. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  549. }
  550. else
  551. {
  552. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  553. }
  554. }
  555. }
  556. /**
  557. * Helper function to create and administrator account for iTop
  558. * @return boolean true on success, false otherwise
  559. */
  560. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  561. {
  562. SetupPage::log_info('CreateAdminAccount');
  563. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  564. {
  565. return true;
  566. }
  567. else
  568. {
  569. return false;
  570. }
  571. }
  572. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  573. {
  574. $aParamValues = array(
  575. 'db_server' => $sDBServer,
  576. 'db_user' => $sDBUser,
  577. 'db_pwd' => $sDBPwd,
  578. 'db_name' => $sDBName,
  579. 'new_db_name' => $sDBName,
  580. 'db_prefix' => $sDBPrefix,
  581. );
  582. $oConfig = new Config();
  583. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  584. if ($bOldAddon)
  585. {
  586. // Old version of the add-on for backward compatibility with pre-2.0 data models
  587. $oConfig->SetAddons(array(
  588. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  589. ));
  590. }
  591. //Load the MetaModel if needed (asynchronous mode)
  592. if (!self::$bMetaModelStarted)
  593. {
  594. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  595. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  596. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  597. }
  598. $oDataLoader = new XMLDataLoader();
  599. CMDBObject::SetTrackInfo("Initialization");
  600. $oMyChange = CMDBObject::GetCurrentChange();
  601. SetupPage::log_info("starting data load session");
  602. $oDataLoader->StartSession($oMyChange);
  603. $aFiles = array();
  604. $oProductionEnv = new RunTimeEnvironment();
  605. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, APPROOT.$sModulesDir);
  606. foreach($aAvailableModules as $sModuleId => $aModule)
  607. {
  608. if (($sModuleId != ROOT_MODULE))
  609. {
  610. if (in_array($sModuleId, $aSelectedModules))
  611. {
  612. $aFiles = array_merge(
  613. $aFiles,
  614. $aAvailableModules[$sModuleId]['data.struct'],
  615. $aAvailableModules[$sModuleId]['data.sample']
  616. );
  617. }
  618. }
  619. }
  620. foreach($aFiles as $sFileRelativePath)
  621. {
  622. $sFileName = APPROOT.$sFileRelativePath;
  623. SetupPage::log_info("Loading file: $sFileName");
  624. if (empty($sFileName) || !file_exists($sFileName))
  625. {
  626. throw(new Exception("File $sFileName does not exist"));
  627. }
  628. $oDataLoader->LoadFile($sFileName);
  629. $sResult = sprintf("loading of %s done.", basename($sFileName));
  630. SetupPage::log_info($sResult);
  631. }
  632. $oDataLoader->EndSession();
  633. SetupPage::log_info("ending data load session");
  634. }
  635. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile)
  636. {
  637. $aParamValues = array(
  638. 'db_server' => $sDBServer,
  639. 'db_user' => $sDBUser,
  640. 'db_pwd' => $sDBPwd,
  641. 'db_name' => $sDBName,
  642. 'new_db_name' => $sDBName,
  643. 'db_prefix' => $sDBPrefix,
  644. 'application_path' => $sUrl,
  645. 'language' => $sLanguage,
  646. 'selected_modules' => implode(',', $aSelectedModules),
  647. );
  648. $bPreserveModuleSettings = false;
  649. if ($sMode == 'upgrade')
  650. {
  651. try
  652. {
  653. $oOldConfig = new Config($sPreviousConfigFile);
  654. $oConfig = clone($oOldConfig);
  655. $bPreserveModuleSettings = true;
  656. }
  657. catch(Exception $e)
  658. {
  659. // In case the previous configuration is corrupted... start with a blank new one
  660. $oConfig = new Config();
  661. }
  662. }
  663. else
  664. {
  665. $oConfig = new Config();
  666. }
  667. // Migration: force utf8_unicode_ci as the collation to make the global search
  668. // NON case sensitive
  669. $oConfig->SetDBCollation('utf8_unicode_ci');
  670. // Final config update: add the modules
  671. $oConfig->UpdateFromParams($aParamValues, $sModulesDir, $bPreserveModuleSettings);
  672. if ($bOldAddon)
  673. {
  674. // Old version of the add-on for backward compatibility with pre-2.0 data models
  675. $oConfig->SetAddons(array(
  676. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  677. ));
  678. }
  679. $oConfig->Set('source_dir', $sSourceDir);
  680. // Make sure the root configuration directory exists
  681. if (!file_exists(APPCONF))
  682. {
  683. mkdir(APPCONF);
  684. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  685. SetupPage::log_info("Created configuration directory: ".APPCONF);
  686. }
  687. // Write the final configuration file
  688. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  689. $sConfigDir = dirname($sConfigFile);
  690. @mkdir($sConfigDir);
  691. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  692. $oConfig->WriteToFile($sConfigFile);
  693. // try to make the final config file read-only
  694. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  695. // Ready to go !!
  696. require_once(APPROOT.'core/dict.class.inc.php');
  697. MetaModel::ResetCache($sTargetEnvironment);
  698. }
  699. }