applicationinstaller.class.inc.php 26 KB

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