applicationinstaller.class.inc.php 26 KB

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