applicationinstaller.class.inc.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. <?php
  2. // Copyright (C) 2010-2016 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-2016 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, $sTargetEnvironment, $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' => 'load-data',
  257. 'next-step-label' => 'Loading data',
  258. 'percentage-completed' => 80,
  259. );
  260. break;
  261. case 'load-data':
  262. $aSelectedModules = $this->oParams->Get('selected_modules');
  263. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  264. $sTargetDir = 'env-'.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment);
  265. $aDBParams = $this->oParams->Get('database');
  266. $sDBServer = $aDBParams['server'];
  267. $sDBUser = $aDBParams['user'];
  268. $sDBPwd = $aDBParams['pwd'];
  269. $sDBName = $aDBParams['name'];
  270. $sDBPrefix = $aDBParams['prefix'];
  271. $aFiles = $this->oParams->Get('files', array());
  272. $bOldAddon = $this->oParams->Get('old_addon', false);
  273. $bSampleData = ($this->oParams->Get('sample_data', 0) == 1);
  274. self::DoLoadFiles($aSelectedModules, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment, $bOldAddon, $bSampleData);
  275. $aResult = array(
  276. 'status' => self::INFO,
  277. 'message' => 'All data loaded',
  278. 'next-step' => 'create-config',
  279. 'next-step-label' => 'Creating the configuration File',
  280. 'percentage-completed' => 99,
  281. );
  282. break;
  283. case 'create-config':
  284. $sMode = $this->oParams->Get('mode');
  285. $sTargetEnvironment = $this->oParams->Get('target_env', '');
  286. if ($sTargetEnvironment == '')
  287. {
  288. $sTargetEnvironment = 'production';
  289. }
  290. $sTargetDir = 'env-'.$sTargetEnvironment;
  291. $aDBParams = $this->oParams->Get('database');
  292. $sDBServer = $aDBParams['server'];
  293. $sDBUser = $aDBParams['user'];
  294. $sDBPwd = $aDBParams['pwd'];
  295. $sDBName = $aDBParams['name'];
  296. $sDBPrefix = $aDBParams['prefix'];
  297. $sUrl = $this->oParams->Get('url', '');
  298. $sGraphvizPath = $this->oParams->Get('graphviz_path', '');
  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. $sDataModelVersion = $this->oParams->Get('datamodel_version', '0.0.0');
  305. self::DoCreateConfig($sMode, $sTargetDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile, $sDataModelVersion, $sGraphvizPath);
  306. $aResult = array(
  307. 'status' => self::INFO,
  308. 'message' => 'Configuration file created',
  309. 'next-step' => '',
  310. 'next-step-label' => 'Completed',
  311. 'percentage-completed' => 100,
  312. );
  313. break;
  314. default:
  315. $aResult = array(
  316. 'status' => self::ERROR,
  317. 'message' => '',
  318. 'next-step' => '',
  319. 'next-step-label' => "Unknown setup step '$sStep'.",
  320. 'percentage-completed' => 100,
  321. );
  322. }
  323. }
  324. catch(Exception $e)
  325. {
  326. $aResult = array(
  327. 'status' => self::ERROR,
  328. 'message' => $e->getMessage(),
  329. 'next-step' => '',
  330. 'next-step-label' => '',
  331. 'percentage-completed' => 100,
  332. );
  333. SetupPage::log_error('An exception occurred: '.$e->getMessage().' at line '.$e->getLine().' in file '.$e->getFile());
  334. $idx = 0;
  335. // Log the call stack, but not the parameters since they may contain passwords or other sensitive data
  336. SetupPage::log("Call stack:");
  337. foreach($e->getTrace() as $aTrace)
  338. {
  339. $sLine = empty($aTrace['line']) ? "" : $aTrace['line'];
  340. $sFile = empty($aTrace['file']) ? "" : $aTrace['file'];
  341. $sClass = empty($aTrace['class']) ? "" : $aTrace['class'];
  342. $sType = empty($aTrace['type']) ? "" : $aTrace['type'];
  343. $sFunction = empty($aTrace['function']) ? "" : $aTrace['function'];
  344. $sVerb = empty($sClass) ? $sFunction : "$sClass{$sType}$sFunction";
  345. SetupPage::log("#$idx $sFile($sLine): $sVerb(...)");
  346. $idx++;
  347. }
  348. }
  349. return $aResult;
  350. }
  351. protected static function DoCopy($aCopies)
  352. {
  353. $aReports = array();
  354. foreach ($aCopies as $aCopy)
  355. {
  356. $sSource = $aCopy['source'];
  357. $sDestination = APPROOT.$aCopy['destination'];
  358. SetupUtils::builddir($sDestination);
  359. SetupUtils::tidydir($sDestination);
  360. SetupUtils::copydir($sSource, $sDestination);
  361. $aReports[] = "'{$aCopy['source']}' to '{$aCopy['destination']}' (OK)";
  362. }
  363. if (count($aReports) > 0)
  364. {
  365. $sReport = "Copies: ".count($aReports).': '.implode('; ', $aReports);
  366. }
  367. else
  368. {
  369. $sReport = "No file copy";
  370. }
  371. return $sReport;
  372. }
  373. protected static function DoBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sBackupFile, $sSourceConfigFile)
  374. {
  375. $oBackup = new SetupDBBackup($sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix);
  376. $sZipFile = $oBackup->MakeName($sBackupFile);
  377. $oBackup->CreateZip($sZipFile, $sSourceConfigFile);
  378. }
  379. protected static function DoCompile($aSelectedModules, $sSourceDir, $sExtensionDir, $sTargetDir, $sEnvironment, $bUseSymbolicLinks = false)
  380. {
  381. SetupPage::log_info("Compiling data model.");
  382. require_once(APPROOT.'setup/modulediscovery.class.inc.php');
  383. require_once(APPROOT.'setup/modelfactory.class.inc.php');
  384. require_once(APPROOT.'setup/compiler.class.inc.php');
  385. if (empty($sSourceDir) || empty($sTargetDir))
  386. {
  387. throw new Exception("missing parameter source_dir and/or target_dir");
  388. }
  389. $sSourcePath = APPROOT.$sSourceDir;
  390. $aDirsToScan = array($sSourcePath);
  391. $sExtensionsPath = APPROOT.$sExtensionDir;
  392. if (is_dir($sExtensionsPath))
  393. {
  394. // if the extensions dir exists, scan it for additional modules as well
  395. $aDirsToScan[] = $sExtensionsPath;
  396. }
  397. $sExtraPath = APPROOT.'/data/'.$sEnvironment.'-modules/';
  398. if (is_dir($sExtraPath))
  399. {
  400. // if the extra dir exists, scan it for additional modules as well
  401. $aDirsToScan[] = $sExtraPath;
  402. }
  403. $sTargetPath = APPROOT.$sTargetDir;
  404. if (!is_dir($sSourcePath))
  405. {
  406. throw new Exception("Failed to find the source directory '$sSourcePath', please check the rights of the web server");
  407. }
  408. if (!is_dir($sTargetPath))
  409. {
  410. if (!mkdir($sTargetPath))
  411. {
  412. throw new Exception("Failed to create directory '$sTargetPath', please check the rights of the web server");
  413. }
  414. else
  415. {
  416. // adjust the rights if and only if the directory was just created
  417. // owner:rwx user/group:rx
  418. chmod($sTargetPath, 0755);
  419. }
  420. }
  421. else if (substr($sTargetPath, 0, strlen(APPROOT)) == APPROOT)
  422. {
  423. // If the directory is under the root folder - as expected - let's clean-it before compiling
  424. SetupUtils::tidydir($sTargetPath);
  425. }
  426. $oFactory = new ModelFactory($aDirsToScan);
  427. $sDeltaFile = APPROOT.'core/datamodel.core.xml';
  428. if (file_exists($sDeltaFile))
  429. {
  430. $oCoreModule = new MFCoreModule('core', 'Core Module', $sDeltaFile);
  431. $oFactory->LoadModule($oCoreModule);
  432. }
  433. $sDeltaFile = APPROOT.'application/datamodel.application.xml';
  434. if (file_exists($sDeltaFile))
  435. {
  436. $oApplicationModule = new MFCoreModule('application', 'Application Module', $sDeltaFile);
  437. $oFactory->LoadModule($oApplicationModule);
  438. }
  439. $aModules = $oFactory->FindModules();
  440. foreach($aModules as $foo => $oModule)
  441. {
  442. $sModule = $oModule->GetName();
  443. if (in_array($sModule, $aSelectedModules))
  444. {
  445. $oFactory->LoadModule($oModule);
  446. }
  447. }
  448. $sDeltaFile = APPROOT.'data/'.$sEnvironment.'.delta.xml';
  449. if (file_exists($sDeltaFile))
  450. {
  451. $oDelta = new MFDeltaModule($sDeltaFile);
  452. $oFactory->LoadModule($oDelta);
  453. }
  454. //$oFactory->Dump();
  455. if ($oFactory->HasLoadErrors())
  456. {
  457. foreach($oFactory->GetLoadErrors() as $sModuleId => $aErrors)
  458. {
  459. SetupPage::log_error("Data model source file (xml) could not be loaded - found errors in module: $sModuleId");
  460. foreach($aErrors as $oXmlError)
  461. {
  462. SetupPage::log_error("Load error: File: ".$oXmlError->file." Line:".$oXmlError->line." Message:".$oXmlError->message);
  463. }
  464. }
  465. throw new Exception("The data model could not be compiled. Please check the setup error log");
  466. }
  467. else
  468. {
  469. $oMFCompiler = new MFCompiler($oFactory);
  470. $oMFCompiler->Compile($sTargetPath, null, $bUseSymbolicLinks);
  471. //$aCompilerLog = $oMFCompiler->GetLog();
  472. //SetupPage::log_info(implode("\n", $aCompilerLog));
  473. SetupPage::log_info("Data model successfully compiled to '$sTargetPath'.");
  474. $sCacheDir = APPROOT.'/data/cache-'.$sEnvironment.'/';
  475. Setuputils::builddir($sCacheDir);
  476. Setuputils::tidydir($sCacheDir);
  477. }
  478. // Special case to patch a ugly patch in itop-config-mgmt
  479. $sFileToPatch = $sTargetPath.'/itop-config-mgmt-1.0.0/model.itop-config-mgmt.php';
  480. if (file_exists($sFileToPatch))
  481. {
  482. $sContent = file_get_contents($sFileToPatch);
  483. $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);
  484. file_put_contents($sFileToPatch, $sContent);
  485. }
  486. }
  487. protected static function DoUpdateDBSchema($sMode, $aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false)
  488. {
  489. SetupPage::log_info("Update Database Schema for environment '$sTargetEnvironment'.");
  490. $oConfig = new Config();
  491. $aParamValues = array(
  492. 'mode' => $sMode,
  493. 'db_server' => $sDBServer,
  494. 'db_user' => $sDBUser,
  495. 'db_pwd' => $sDBPwd,
  496. 'db_name' => $sDBName,
  497. 'db_prefix' => $sDBPrefix,
  498. );
  499. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  500. if ($bOldAddon)
  501. {
  502. // Old version of the add-on for backward compatibility with pre-2.0 data models
  503. $oConfig->SetAddons(array(
  504. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  505. ));
  506. }
  507. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  508. $oProductionEnv->InitDataModel($oConfig, true); // load data model only
  509. // Migrate application data format
  510. //
  511. // priv_internalUser caused troubles because MySQL transforms table names to lower case under Windows
  512. // This becomes an issue when moving your installation data to/from Windows
  513. // Starting 2.0, all table names must be lowercase
  514. if ($sMode != 'install')
  515. {
  516. SetupPage::log_info("Renaming '{$sDBPrefix}priv_internalUser' into '{$sDBPrefix}priv_internaluser' (lowercase)");
  517. // This command will have no effect under Windows...
  518. // and it has been written in two steps so as to make it work under windows!
  519. CMDBSource::SelectDB($sDBName);
  520. try
  521. {
  522. $sRepair = "RENAME TABLE `{$sDBPrefix}priv_internalUser` TO `{$sDBPrefix}priv_internaluser_other`, `{$sDBPrefix}priv_internaluser_other` TO `{$sDBPrefix}priv_internaluser`";
  523. CMDBSource::Query($sRepair);
  524. }
  525. catch (Exception $e)
  526. {
  527. SetupPage::log_info("Renaming '{$sDBPrefix}priv_internalUser' failed (already done in a previous upgrade?)");
  528. }
  529. // let's remove the records in priv_change which have no counterpart in priv_changeop
  530. SetupPage::log_info("Cleanup of '{$sDBPrefix}priv_change' to remove orphan records");
  531. CMDBSource::SelectDB($sDBName);
  532. try
  533. {
  534. $sTotalCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change`";
  535. $iTotalCount = (int)CMDBSource::QueryToScalar($sTotalCount);
  536. SetupPage::log_info("There is a total of $iTotalCount records in {$sDBPrefix}priv_change.");
  537. $sOrphanCount = "SELECT COUNT(c.id) FROM `{$sDBPrefix}priv_change` AS c left join `{$sDBPrefix}priv_changeop` AS o ON c.id = o.changeid WHERE o.id IS NULL";
  538. $iOrphanCount = (int)CMDBSource::QueryToScalar($sOrphanCount);
  539. SetupPage::log_info("There are $iOrphanCount useless records in {$sDBPrefix}priv_change (".sprintf('%.2f', ((100.0*$iOrphanCount)/$iTotalCount))."%)");
  540. if ($iOrphanCount > 0)
  541. {
  542. SetupPage::log_info("Removing the orphan records...");
  543. $sCleanup = "DELETE FROM `{$sDBPrefix}priv_change` USING `{$sDBPrefix}priv_change` LEFT JOIN `{$sDBPrefix}priv_changeop` ON `{$sDBPrefix}priv_change`.id = `{$sDBPrefix}priv_changeop`.changeid WHERE `{$sDBPrefix}priv_changeop`.id IS NULL;";
  544. CMDBSource::Query($sCleanup);
  545. SetupPage::log_info("Cleanup completed successfully.");
  546. }
  547. else
  548. {
  549. SetupPage::log_info("Ok, nothing to cleanup.");
  550. }
  551. }
  552. catch (Exception $e)
  553. {
  554. SetupPage::log_info("Cleanup of orphan records in `{$sDBPrefix}priv_change` failed: ".$e->getMessage());
  555. }
  556. }
  557. // Module specific actions (migrate the data)
  558. //
  559. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  560. foreach($aAvailableModules as $sModuleId => $aModule)
  561. {
  562. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  563. isset($aAvailableModules[$sModuleId]['installer']) )
  564. {
  565. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  566. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::BeforeDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  567. $aCallSpec = array($sModuleInstallerClass, 'BeforeDatabaseCreation');
  568. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  569. }
  570. }
  571. if(!$oProductionEnv->CreateDatabaseStructure(MetaModel::GetConfig(), $sMode))
  572. {
  573. throw new Exception("Failed to create/upgrade the database structure for environment '$sTargetEnvironment'");
  574. }
  575. // priv_change now has an 'origin' field to distinguish between the various input sources
  576. // Let's initialize the field with 'interactive' for all records were it's null
  577. // Then check if some records should hold a different value, based on a pattern matching in the userinfo field
  578. CMDBSource::SelectDB($sDBName);
  579. try
  580. {
  581. $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_change` WHERE `origin` IS NULL";
  582. $iCount = (int)CMDBSource::QueryToScalar($sCount);
  583. if ($iCount > 0)
  584. {
  585. SetupPage::log_info("Initializing '{$sDBPrefix}priv_change.origin' ($iCount records to update)");
  586. // By default all uninitialized values are considered as 'interactive'
  587. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'interactive' WHERE `origin` IS NULL";
  588. CMDBSource::Query($sInit);
  589. // CSV Import was identified by the comment at the end
  590. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'csv-import.php' WHERE `userinfo` LIKE '%Web Service (CSV)'";
  591. CMDBSource::Query($sInit);
  592. // CSV Import was identified by the comment at the end
  593. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'csv-interactive' WHERE `userinfo` LIKE '%(CSV)' AND origin = 'interactive'";
  594. CMDBSource::Query($sInit);
  595. // Syncho data sources were identified by the comment at the end
  596. // Unfortunately the comment is localized, so we have to search for all possible patterns
  597. $sCurrentLanguage = Dict::GetUserLanguage();
  598. foreach(Dict::GetLanguages() as $sLangCode => $aLang)
  599. {
  600. Dict::SetUserLanguage($sLangCode);
  601. $sSuffix = CMDBSource::Quote('%'.Dict::S('Core:SyncDataExchangeComment'));
  602. $aSuffixes[$sSuffix] = true;
  603. }
  604. Dict::SetUserLanguage($sCurrentLanguage);
  605. $sCondition = "`userinfo` LIKE ".implode(" OR `userinfo` LIKE ", array_keys($aSuffixes));
  606. $sInit = "UPDATE `{$sDBPrefix}priv_change` SET `origin` = 'synchro-data-source' WHERE ($sCondition)";
  607. CMDBSource::Query($sInit);
  608. SetupPage::log_info("Initialization of '{$sDBPrefix}priv_change.origin' completed.");
  609. }
  610. else
  611. {
  612. SetupPage::log_info("'{$sDBPrefix}priv_change.origin' already initialized, nothing to do.");
  613. }
  614. }
  615. catch (Exception $e)
  616. {
  617. SetupPage::log_error("Initializing '{$sDBPrefix}priv_change.origin' failed: ".$e->getMessage());
  618. }
  619. // priv_async_task now has a 'status' field to distinguish between the various statuses rather than just relying on the date columns
  620. // Let's initialize the field with 'planned' or 'error' for all records were it's null
  621. CMDBSource::SelectDB($sDBName);
  622. try
  623. {
  624. $sCount = "SELECT COUNT(*) FROM `{$sDBPrefix}priv_async_task` WHERE `status` IS NULL";
  625. $iCount = (int)CMDBSource::QueryToScalar($sCount);
  626. if ($iCount > 0)
  627. {
  628. SetupPage::log_info("Initializing '{$sDBPrefix}priv_async_task.status' ($iCount records to update)");
  629. $sInit = "UPDATE `{$sDBPrefix}priv_async_task` SET `status` = 'planned' WHERE (`status` IS NULL) AND (`started` IS NULL)";
  630. CMDBSource::Query($sInit);
  631. $sInit = "UPDATE `{$sDBPrefix}priv_async_task` SET `status` = 'error' WHERE (`status` IS NULL) AND (`started` IS NOT NULL)";
  632. CMDBSource::Query($sInit);
  633. SetupPage::log_info("Initialization of '{$sDBPrefix}priv_async_task.status' completed.");
  634. }
  635. else
  636. {
  637. SetupPage::log_info("'{$sDBPrefix}priv_async_task.status' already initialized, nothing to do.");
  638. }
  639. }
  640. catch (Exception $e)
  641. {
  642. SetupPage::log_error("Initializing '{$sDBPrefix}priv_async_task.status' failed: ".$e->getMessage());
  643. }
  644. SetupPage::log_info("Database Schema Successfully Updated for environment '$sTargetEnvironment'.");
  645. }
  646. protected static function AfterDBCreate($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sAdminUser, $sAdminPwd, $sAdminLanguage, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sDataModelVersion, $sSourceDir)
  647. {
  648. SetupPage::log_info('After Database Creation');
  649. $oConfig = new Config();
  650. $aParamValues = array(
  651. 'mode' => $sMode,
  652. 'db_server' => $sDBServer,
  653. 'db_user' => $sDBUser,
  654. 'db_pwd' => $sDBPwd,
  655. 'db_name' => $sDBName,
  656. 'db_prefix' => $sDBPrefix,
  657. );
  658. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  659. if ($bOldAddon)
  660. {
  661. // Old version of the add-on for backward compatibility with pre-2.0 data models
  662. $oConfig->SetAddons(array(
  663. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  664. ));
  665. }
  666. $oConfig->Set('source_dir', $sSourceDir); // Needed by RecordInstallation below
  667. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  668. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  669. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  670. // Perform here additional DB setup... profiles, etc...
  671. //
  672. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  673. foreach($aAvailableModules as $sModuleId => $aModule)
  674. {
  675. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  676. isset($aAvailableModules[$sModuleId]['installer']) )
  677. {
  678. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  679. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseCreation(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  680. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  681. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseCreation');
  682. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  683. }
  684. }
  685. $oProductionEnv->UpdatePredefinedObjects();
  686. if($sMode == 'install')
  687. {
  688. if (!self::CreateAdminAccount(MetaModel::GetConfig(), $sAdminUser, $sAdminPwd, $sAdminLanguage))
  689. {
  690. throw(new Exception("Failed to create the administrator account '$sAdminUser'"));
  691. }
  692. else
  693. {
  694. SetupPage::log_info("Administrator account '$sAdminUser' created.");
  695. }
  696. }
  697. // Perform final setup tasks here
  698. //
  699. foreach($aAvailableModules as $sModuleId => $aModule)
  700. {
  701. if (($sModuleId != ROOT_MODULE) && in_array($sModuleId, $aSelectedModules) &&
  702. isset($aAvailableModules[$sModuleId]['installer']) )
  703. {
  704. $sModuleInstallerClass = $aAvailableModules[$sModuleId]['installer'];
  705. SetupPage::log_info("Calling Module Handler: $sModuleInstallerClass::AfterDatabaseSetup(oConfig, {$aModule['version_db']}, {$aModule['version_code']})");
  706. // The validity of the sModuleInstallerClass has been established in BuildConfig()
  707. $aCallSpec = array($sModuleInstallerClass, 'AfterDatabaseSetup');
  708. call_user_func_array($aCallSpec, array(MetaModel::GetConfig(), $aModule['version_db'], $aModule['version_code']));
  709. }
  710. }
  711. }
  712. /**
  713. * Helper function to create and administrator account for iTop
  714. * @return boolean true on success, false otherwise
  715. */
  716. protected static function CreateAdminAccount(Config $oConfig, $sAdminUser, $sAdminPwd, $sLanguage)
  717. {
  718. SetupPage::log_info('CreateAdminAccount');
  719. if (UserRights::CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage))
  720. {
  721. return true;
  722. }
  723. else
  724. {
  725. return false;
  726. }
  727. }
  728. protected static function DoLoadFiles($aSelectedModules, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sTargetEnvironment = '', $bOldAddon = false, $bSampleData = false)
  729. {
  730. $aParamValues = array(
  731. 'db_server' => $sDBServer,
  732. 'db_user' => $sDBUser,
  733. 'db_pwd' => $sDBPwd,
  734. 'db_name' => $sDBName,
  735. 'new_db_name' => $sDBName,
  736. 'db_prefix' => $sDBPrefix,
  737. );
  738. $oConfig = new Config();
  739. $oConfig->UpdateFromParams($aParamValues, $sModulesDir);
  740. if ($bOldAddon)
  741. {
  742. // Old version of the add-on for backward compatibility with pre-2.0 data models
  743. $oConfig->SetAddons(array(
  744. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  745. ));
  746. }
  747. //Load the MetaModel if needed (asynchronous mode)
  748. if (!self::$bMetaModelStarted)
  749. {
  750. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  751. $oProductionEnv->InitDataModel($oConfig, false); // load data model and connect to the database
  752. self::$bMetaModelStarted = true; // No need to reload the final MetaModel in case the installer runs synchronously
  753. }
  754. $oDataLoader = new XMLDataLoader();
  755. CMDBObject::SetTrackInfo("Initialization");
  756. $oMyChange = CMDBObject::GetCurrentChange();
  757. SetupPage::log_info("starting data load session");
  758. $oDataLoader->StartSession($oMyChange);
  759. $aFiles = array();
  760. $aPreviouslyLoadedFiles = array();
  761. $oProductionEnv = new RunTimeEnvironment();
  762. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, APPROOT.$sModulesDir);
  763. foreach($aAvailableModules as $sModuleId => $aModule)
  764. {
  765. if (($sModuleId != ROOT_MODULE))
  766. {
  767. // Load data only for selected AND newly installed modules
  768. if (in_array($sModuleId, $aSelectedModules))
  769. {
  770. if ($aModule['version_db'] != '')
  771. {
  772. // Simulate the load of the previously loaded XML files to get the mapping of the keys
  773. if ($bSampleData)
  774. {
  775. $aPreviouslyLoadedFiles = array_merge(
  776. $aPreviouslyLoadedFiles,
  777. $aAvailableModules[$sModuleId]['data.struct'],
  778. $aAvailableModules[$sModuleId]['data.sample']
  779. );
  780. }
  781. else
  782. {
  783. // Load only structural data
  784. $aPreviouslyLoadedFiles = array_merge(
  785. $aPreviouslyLoadedFiles,
  786. $aAvailableModules[$sModuleId]['data.struct']
  787. );
  788. }
  789. }
  790. else
  791. {
  792. if ($bSampleData)
  793. {
  794. $aFiles = array_merge(
  795. $aFiles,
  796. $aAvailableModules[$sModuleId]['data.struct'],
  797. $aAvailableModules[$sModuleId]['data.sample']
  798. );
  799. }
  800. else
  801. {
  802. // Load only structural data
  803. $aFiles = array_merge(
  804. $aFiles,
  805. $aAvailableModules[$sModuleId]['data.struct']
  806. );
  807. }
  808. }
  809. }
  810. }
  811. }
  812. // Simulate the load of the previously loaded files, in order to initialize
  813. // the mapping between the identifiers in the XML and the actual identifiers
  814. // in the current database
  815. foreach($aPreviouslyLoadedFiles as $sFileRelativePath)
  816. {
  817. $sFileName = APPROOT.$sFileRelativePath;
  818. SetupPage::log_info("Loading file: $sFileName (just to get the keys mapping)");
  819. if (empty($sFileName) || !file_exists($sFileName))
  820. {
  821. throw(new Exception("File $sFileName does not exist"));
  822. }
  823. $oDataLoader->LoadFile($sFileName, true);
  824. $sResult = sprintf("loading of %s done.", basename($sFileName));
  825. SetupPage::log_info($sResult);
  826. }
  827. foreach($aFiles as $sFileRelativePath)
  828. {
  829. $sFileName = APPROOT.$sFileRelativePath;
  830. SetupPage::log_info("Loading file: $sFileName");
  831. if (empty($sFileName) || !file_exists($sFileName))
  832. {
  833. throw(new Exception("File $sFileName does not exist"));
  834. }
  835. $oDataLoader->LoadFile($sFileName);
  836. $sResult = sprintf("loading of %s done.", basename($sFileName));
  837. SetupPage::log_info($sResult);
  838. }
  839. $oDataLoader->EndSession();
  840. SetupPage::log_info("ending data load session");
  841. }
  842. protected static function DoCreateConfig($sMode, $sModulesDir, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sUrl, $sLanguage, $aSelectedModules, $sTargetEnvironment, $bOldAddon, $sSourceDir, $sPreviousConfigFile, $sDataModelVersion, $sGraphvizPath)
  843. {
  844. $aParamValues = array(
  845. 'mode' => $sMode,
  846. 'db_server' => $sDBServer,
  847. 'db_user' => $sDBUser,
  848. 'db_pwd' => $sDBPwd,
  849. 'db_name' => $sDBName,
  850. 'new_db_name' => $sDBName,
  851. 'db_prefix' => $sDBPrefix,
  852. 'application_path' => $sUrl,
  853. 'language' => $sLanguage,
  854. 'graphviz_path' => $sGraphvizPath,
  855. 'selected_modules' => implode(',', $aSelectedModules),
  856. );
  857. $bPreserveModuleSettings = false;
  858. if ($sMode == 'upgrade')
  859. {
  860. try
  861. {
  862. $oOldConfig = new Config($sPreviousConfigFile);
  863. $oConfig = clone($oOldConfig);
  864. $bPreserveModuleSettings = true;
  865. }
  866. catch(Exception $e)
  867. {
  868. // In case the previous configuration is corrupted... start with a blank new one
  869. $oConfig = new Config();
  870. }
  871. }
  872. else
  873. {
  874. $oConfig = new Config();
  875. // To preserve backward compatibility while upgrading to 2.0.3 (when tracking_level_linked_set_default has been introduced)
  876. // the default value on upgrade differs from the default value at first install
  877. $oConfig->Set('tracking_level_linked_set_default', LINKSET_TRACKING_NONE, 'first_install');
  878. }
  879. // Migration: force utf8_unicode_ci as the collation to make the global search
  880. // NON case sensitive
  881. $oConfig->SetDBCollation('utf8_unicode_ci');
  882. // Final config update: add the modules
  883. $oConfig->UpdateFromParams($aParamValues, $sModulesDir, $bPreserveModuleSettings);
  884. if ($bOldAddon)
  885. {
  886. // Old version of the add-on for backward compatibility with pre-2.0 data models
  887. $oConfig->SetAddons(array(
  888. 'user rights' => 'addons/userrights/userrightsprofile.db.class.inc.php',
  889. ));
  890. }
  891. $oConfig->Set('source_dir', $sSourceDir);
  892. // Have it work fine even if the DB has been set in read-only mode for the users
  893. $iPrevAccessMode = $oConfig->Get('access_mode');
  894. $oConfig->Set('access_mode', ACCESS_FULL);
  895. // Record which modules are installed...
  896. $oProductionEnv = new RunTimeEnvironment($sTargetEnvironment);
  897. $oProductionEnv->InitDataModel($oConfig, true); // load data model and connect to the database
  898. $aAvailableModules = $oProductionEnv->AnalyzeInstallation(MetaModel::GetConfig(), APPROOT.$sModulesDir);
  899. if (!$oProductionEnv->RecordInstallation($oConfig, $sDataModelVersion, $aSelectedModules, $sModulesDir))
  900. {
  901. throw new Exception("Failed to record the installation information");
  902. }
  903. // Restore the previous access mode
  904. $oConfig->Set('access_mode', $iPrevAccessMode);
  905. // Make sure the root configuration directory exists
  906. if (!file_exists(APPCONF))
  907. {
  908. mkdir(APPCONF);
  909. chmod(APPCONF, 0770); // RWX for owner and group, nothing for others
  910. SetupPage::log_info("Created configuration directory: ".APPCONF);
  911. }
  912. // Write the final configuration file
  913. $sConfigFile = APPCONF.(($sTargetEnvironment == '') ? 'production' : $sTargetEnvironment).'/'.ITOP_CONFIG_FILE;
  914. $sConfigDir = dirname($sConfigFile);
  915. @mkdir($sConfigDir);
  916. @chmod($sConfigDir, 0770); // RWX for owner and group, nothing for others
  917. $oConfig->WriteToFile($sConfigFile);
  918. // try to make the final config file read-only
  919. @chmod($sConfigFile, 0444); // Read-only for owner and group, nothing for others
  920. // Ready to go !!
  921. require_once(APPROOT.'core/dict.class.inc.php');
  922. MetaModel::ResetCache();
  923. }
  924. }
  925. class SetupDBBackup extends DBBackup
  926. {
  927. protected function LogInfo($sMsg)
  928. {
  929. SetupPage::log('Info - '.$sMsg);
  930. }
  931. protected function LogError($sMsg)
  932. {
  933. SetupPage::log('Error - '.$sMsg);
  934. }
  935. }