applicationinstaller.class.inc.php 28 KB

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