setuputils.class.inc.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. <?php
  2. // Copyright (C) 2012 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * The standardized result of any pass/fail check performed by the setup
  18. * @author Erwan Taloc <erwan.taloc@combodo.com>
  19. * @author Romain Quetiez <romain.quetiez@combodo.com>
  20. * @author Denis Flaven <denis.flaven@combodo.com>
  21. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  22. */
  23. class CheckResult
  24. {
  25. // Severity levels
  26. const ERROR = 0;
  27. const WARNING = 1;
  28. const INFO = 2;
  29. public $iSeverity;
  30. public $sLabel;
  31. public $sDescription;
  32. public function __construct($iSeverity, $sLabel, $sDescription = '')
  33. {
  34. $this->iSeverity = $iSeverity;
  35. $this->sLabel = $sLabel;
  36. $this->sDescription = $sDescription;
  37. }
  38. }
  39. /**
  40. * Namespace for storing all the functions/utilities needed by both
  41. * the setup wizard and the installation process
  42. * @author Erwan Taloc <erwan.taloc@combodo.com>
  43. * @author Romain Quetiez <romain.quetiez@combodo.com>
  44. * @author Denis Flaven <denis.flaven@combodo.com>
  45. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  46. */
  47. class SetupUtils
  48. {
  49. const PHP_MIN_VERSION = '5.2.0';
  50. const MYSQL_MIN_VERSION = '5.0.0';
  51. const MIN_MEMORY_LIMIT = 33554432; // = 32*1024*1024 Beware: Computations are not allowed in defining constants
  52. const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048;
  53. /**
  54. * Check the version of PHP, the needed PHP extension and a number
  55. * of configuration parameters (memory_limit, max_upload_file_size, etc...)
  56. * @param SetupPage $oP The page used only for its 'log' method
  57. * @return array An array of CheckResults objects
  58. */
  59. static function CheckPHPVersion()
  60. {
  61. $aResult = array();
  62. SetupPage::log('Info - CheckPHPVersion');
  63. if (version_compare(phpversion(), self::PHP_MIN_VERSION, '>='))
  64. {
  65. $aResult[] = new CheckResult(CheckResult::INFO, "The current PHP Version (".phpversion().") is greater than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")");
  66. }
  67. else
  68. {
  69. $aResult[] = new CheckResult(CheckResult::ERROR, "Error: The current PHP Version (".phpversion().") is lower than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")");
  70. }
  71. $aMandatoryExtensions = array('mysqli', 'iconv', 'simplexml', 'soap', 'hash', 'json', 'session', 'pcre', 'dom');
  72. $aOptionalExtensions = array('mcrypt' => 'Strong encryption will not be used.',
  73. 'ldap' => 'LDAP authentication will be disabled.');
  74. asort($aMandatoryExtensions); // Sort the list to look clean !
  75. ksort($aOptionalExtensions); // Sort the list to look clean !
  76. $aExtensionsOk = array();
  77. $aMissingExtensions = array();
  78. $aMissingExtensionsLinks = array();
  79. // First check the mandatory extensions
  80. foreach($aMandatoryExtensions as $sExtension)
  81. {
  82. if (extension_loaded($sExtension))
  83. {
  84. $aExtensionsOk[] = $sExtension;
  85. }
  86. else
  87. {
  88. $aMissingExtensions[] = $sExtension;
  89. $aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\" target=\"_blank\">$sExtension</a>";
  90. }
  91. }
  92. if (count($aExtensionsOk) > 0)
  93. {
  94. $aResult[] = new CheckResult(CheckResult::INFO, "Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  95. }
  96. if (count($aMissingExtensions) > 0)
  97. {
  98. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
  99. }
  100. // Next check the optional extensions
  101. $aExtensionsOk = array();
  102. $aMissingExtensions = array();
  103. foreach($aOptionalExtensions as $sExtension => $sMessage)
  104. {
  105. if (extension_loaded($sExtension))
  106. {
  107. $aExtensionsOk[] = $sExtension;
  108. }
  109. else
  110. {
  111. $aMissingExtensions[$sExtension] = $sMessage;
  112. }
  113. }
  114. if (count($aExtensionsOk) > 0)
  115. {
  116. $aResult[] = new CheckResult(CheckResult::INFO, "Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  117. }
  118. if (count($aMissingExtensions) > 0)
  119. {
  120. foreach($aMissingExtensions as $sExtension => $sMessage)
  121. {
  122. $aResult[] = new CheckResult(CheckResult::WARNING, "Missing optional PHP extension: $sExtension. ".$sMessage);
  123. }
  124. }
  125. // Check some ini settings here
  126. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  127. {
  128. $sPhpIniFile = php_ini_loaded_file();
  129. // Other included/scanned files
  130. if ($sFileList = php_ini_scanned_files())
  131. {
  132. if (strlen($sFileList) > 0)
  133. {
  134. $aFiles = explode(',', $sFileList);
  135. foreach ($aFiles as $sFile)
  136. {
  137. $sPhpIniFile .= ', '.trim($sFile);
  138. }
  139. }
  140. }
  141. SetupPage::log("Info - php.ini file(s): '$sPhpIniFile'");
  142. }
  143. else
  144. {
  145. $sPhpIniFile = 'php.ini';
  146. }
  147. if (!ini_get('file_uploads'))
  148. {
  149. $aResult[] = new CheckResult(CheckResult::ERROR, "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  150. }
  151. $sUploadTmpDir = self::GetUploadTmpDir();
  152. if (empty($sUploadTmpDir))
  153. {
  154. $sUploadTmpDir = '/tmp';
  155. $aResult[] = new CheckResult(CheckResult::WARNING, "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  156. }
  157. // check that the upload directory is indeed writable from PHP
  158. if (!empty($sUploadTmpDir))
  159. {
  160. if (!file_exists($sUploadTmpDir))
  161. {
  162. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  163. }
  164. else if (!is_writable($sUploadTmpDir))
  165. {
  166. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  167. }
  168. else
  169. {
  170. SetupPage::log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  171. }
  172. }
  173. if (!ini_get('upload_max_filesize'))
  174. {
  175. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').").");
  176. }
  177. $iMaxFileUploads = ini_get('max_file_uploads');
  178. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  179. {
  180. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  181. }
  182. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  183. $iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size'));
  184. if ($iMaxPostSize <= $iMaxUploadSize)
  185. {
  186. $aResult[] = new CheckResult(CheckResult::WARNING, "post_max_size (".ini_get('post_max_size').") in php.ini should be bigger than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximun size.");
  187. }
  188. SetupPage::log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  189. SetupPage::log("Info - post_max_size: ".ini_get('post_max_size'));
  190. SetupPage::log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  191. // Check some more ini settings here, needed for file upload
  192. if (function_exists('get_magic_quotes_gpc'))
  193. {
  194. if (@get_magic_quotes_gpc())
  195. {
  196. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_gpc' is set to On. Please turn it Off in php.ini before continuing.");
  197. }
  198. }
  199. if (function_exists('magic_quotes_runtime'))
  200. {
  201. if (@magic_quotes_runtime())
  202. {
  203. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_runtime' is set to On. Please turn it Off in php.ini before continuing.");
  204. }
  205. }
  206. $sMemoryLimit = trim(ini_get('memory_limit'));
  207. if (empty($sMemoryLimit))
  208. {
  209. // On some PHP installations, memory_limit does not exist as a PHP setting!
  210. // (encountered on a 5.2.0 under Windows)
  211. // In that case, ini_set will not work, let's keep track of this and proceed anyway
  212. $aResult[] = new CheckResult(CheckResult::WARNING, "No memory limit has been defined in this instance of PHP");
  213. }
  214. else
  215. {
  216. // Check that the limit will allow us to load the data
  217. //
  218. $iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
  219. if ($iMemoryLimit < self::MIN_MEMORY_LIMIT)
  220. {
  221. $aResult[] = new CheckResult(CheckResult::ERROR, "memory_limit ($iMemoryLimit) is too small, the minimum value to run the application is ".self::MIN_MEMORY_LIMIT.".");
  222. }
  223. else
  224. {
  225. SetupPage::log("Info - memory_limit is $iMemoryLimit, ok.");
  226. }
  227. }
  228. // Special case for APC
  229. if (extension_loaded('apc'))
  230. {
  231. $sAPCVersion = phpversion('apc');
  232. $aResult[] = new CheckResult(CheckResult::INFO, "APC detected (version $sAPCVersion). The APC cache will be used to speed-up ".ITOP_APPLICATION.".");
  233. }
  234. // Special case Suhosin extension
  235. if (extension_loaded('suhosin'))
  236. {
  237. $sSuhosinVersion = phpversion('suhosin');
  238. $aOk[] = "Suhosin extension detected (version $sSuhosinVersion).";
  239. $iGetMaxValueLength = ini_get('suhosin.get.max_value_length');
  240. if ($iGetMaxValueLength < self::SUHOSIN_GET_MAX_VALUE_LENGTH)
  241. {
  242. $aResult[] = new CheckResult(CheckResult::WARNING, "suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value recommended to run the application is ".self::SUHOSIN_GET_MAX_VALUE_LENGTH.".");
  243. }
  244. else
  245. {
  246. SetupPage::log("Info - suhosin.get.max_value_length = $iGetMaxValueLength, ok.");
  247. }
  248. }
  249. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  250. {
  251. $sPhpIniFile = php_ini_loaded_file();
  252. // Other included/scanned files
  253. if ($sFileList = php_ini_scanned_files())
  254. {
  255. if (strlen($sFileList) > 0)
  256. {
  257. $aFiles = explode(',', $sFileList);
  258. foreach ($aFiles as $sFile)
  259. {
  260. $sPhpIniFile .= ', '.trim($sFile);
  261. }
  262. }
  263. }
  264. $aResult[] = new CheckResult(CheckResult::INFO, "Loaded php.ini files: $sPhpIniFile");
  265. }
  266. return $aResult;
  267. }
  268. /**
  269. * Check that the backup could be executed
  270. * @param Page $oP The page used only for its 'log' method
  271. * @return array An array of CheckResults objects
  272. */
  273. static function CheckBackupPrerequisites($sDestDir)
  274. {
  275. $aResult = array();
  276. SetupPage::log('Info - CheckBackupPrerequisites');
  277. // zip extension
  278. //
  279. if (!extension_loaded('zip'))
  280. {
  281. $sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.zip.php\" target=\"_blank\">zip</a>";
  282. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: zip", $sMissingExtensionLink);
  283. }
  284. // availability of exec()
  285. //
  286. $aDisabled = explode(', ', ini_get('disable_functions'));
  287. SetupPage::log('Info - PHP functions disabled: '.implode(', ', $aDisabled));
  288. if (in_array('exec', $aDisabled))
  289. {
  290. $aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
  291. }
  292. // availability of mysqldump
  293. $sMySQLBinDir = utils::ReadParam('mysql_bindir', '', true);
  294. if (empty($sMySQLBinDir))
  295. {
  296. $sMySQLDump = 'mysqldump';
  297. }
  298. else
  299. {
  300. SetupPage::log('Info - Found mysql_bindir: '.$sMySQLBinDir);
  301. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  302. }
  303. $sCommand = "$sMySQLDump -V 2>&1";
  304. $aOutput = array();
  305. $iRetCode = 0;
  306. exec($sCommand, $aOutput, $iRetCode);
  307. if ($iRetCode == 0)
  308. {
  309. $aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: ".$aOutput[0]);
  310. }
  311. elseif ($iRetCode == 1)
  312. {
  313. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.");
  314. }
  315. else
  316. {
  317. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path");
  318. }
  319. foreach($aOutput as $sLine)
  320. {
  321. SetupPage::log('Info - mysqldump -V said: '.$sLine);
  322. }
  323. // check disk space
  324. // to do... evaluate how we can correlate the DB size with the size of the dump (and the zip!)
  325. // E.g. 2,28 Mb after a full install, giving a zip of 26 Kb (data = 26 Kb)
  326. // Example of query (DB without a suffix)
  327. //$sDBSize = "SELECT SUM(ROUND(DATA_LENGTH/1024/1024, 2)) AS size_mb FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = `$sDBName`";
  328. return $aResult;
  329. }
  330. /**
  331. * Helper function to retrieve the system's temporary directory
  332. * Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
  333. * @return string Path to the system's temp directory
  334. */
  335. static function GetTmpDir()
  336. {
  337. // try to figure out what is the temporary directory
  338. // prior to PHP 5.2.1 the function sys_get_temp_dir
  339. // did not exist
  340. if ( !function_exists('sys_get_temp_dir'))
  341. {
  342. if( $temp=getenv('TMP') ) return realpath($temp);
  343. if( $temp=getenv('TEMP') ) return realpath($temp);
  344. if( $temp=getenv('TMPDIR') ) return realpath($temp);
  345. $temp=tempnam(__FILE__,'');
  346. if (file_exists($temp))
  347. {
  348. unlink($temp);
  349. return realpath(dirname($temp));
  350. }
  351. return null;
  352. }
  353. else
  354. {
  355. return realpath(sys_get_temp_dir());
  356. }
  357. }
  358. /**
  359. * Helper function to retrieve the directory where files are to be uploaded
  360. * @return string Path to the temp directory used for uploading files
  361. */
  362. static function GetUploadTmpDir()
  363. {
  364. $sPath = ini_get('upload_tmp_dir');
  365. if (empty($sPath))
  366. {
  367. $sPath = self::GetTmpDir();
  368. }
  369. return $sPath;
  370. }
  371. /**
  372. * Helper to recursively remove a directory
  373. */
  374. public static function rrmdir($dir)
  375. {
  376. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  377. {
  378. throw new Exception("Attempting to delete directory: '$dir'");
  379. }
  380. self::tidydir($dir);
  381. rmdir($dir);
  382. }
  383. /**
  384. * Helper to recursively cleanup a directory
  385. */
  386. public static function tidydir($dir)
  387. {
  388. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  389. {
  390. throw new Exception("Attempting to delete directory: '$dir'");
  391. }
  392. foreach(glob($dir . '/*') as $file)
  393. {
  394. if(is_dir($file))
  395. {
  396. self::tidydir($file);
  397. rmdir($file);
  398. }
  399. else
  400. {
  401. unlink($file);
  402. }
  403. }
  404. }
  405. /**
  406. * Helper to build the full path of a new directory
  407. */
  408. public static function builddir($dir)
  409. {
  410. $parent = dirname($dir);
  411. if(!is_dir($parent))
  412. {
  413. self::builddir($parent);
  414. }
  415. if (!is_dir($dir))
  416. {
  417. mkdir($dir);
  418. }
  419. }
  420. /**
  421. * Helper to copy a directory to a target directory, skipping .SVN files (for developer's comfort!)
  422. * Returns true if successfull
  423. */
  424. public static function copydir($sSource, $sDest, $bUseSymbolicLinks = false)
  425. {
  426. if (is_dir($sSource))
  427. {
  428. if (!is_dir($sDest))
  429. {
  430. mkdir($sDest);
  431. }
  432. $aFiles = scandir($sSource);
  433. if(sizeof($aFiles) > 0 )
  434. {
  435. foreach($aFiles as $sFile)
  436. {
  437. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  438. {
  439. // Skip
  440. continue;
  441. }
  442. if (is_dir($sSource.'/'.$sFile))
  443. {
  444. // Recurse
  445. self::copydir($sSource.'/'.$sFile, $sDest.'/'.$sFile, $bUseSymbolicLinks);
  446. }
  447. else
  448. {
  449. if ($bUseSymbolicLinks)
  450. {
  451. if (function_exists('symlink'))
  452. {
  453. symlink($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  454. }
  455. else
  456. {
  457. throw(new Exception("Error, cannot *copy* '$sSource/$sFile' to '$sDest/$sFile' using symbolic links, 'symlink' is not supported on this system."));
  458. }
  459. }
  460. else
  461. {
  462. copy($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  463. }
  464. }
  465. }
  466. }
  467. return true;
  468. }
  469. elseif (is_file($sSource))
  470. {
  471. if ($bUseSymbolicLinks)
  472. {
  473. if (function_exists('symlink'))
  474. {
  475. return symlink($sSource, $sDest);
  476. }
  477. else
  478. {
  479. throw(new Exception("Error, cannot *copy* '$sSource' to '$sDest' using symbolic links, 'symlink' is not supported on this system."));
  480. }
  481. }
  482. else
  483. {
  484. return copy($sSource, $sDest);
  485. }
  486. }
  487. else
  488. {
  489. return false;
  490. }
  491. }
  492. static function GetPreviousInstance($sDir)
  493. {
  494. $bFound = false;
  495. $sSourceDir = '';
  496. $sSourceEnvironement = '';
  497. $sConfigFile = '';
  498. $aResult = array(
  499. 'found' => false,
  500. );
  501. if (file_exists($sDir.'/config-itop.php'))
  502. {
  503. $sSourceDir = $sDir;
  504. $sSourceEnvironment = '';
  505. $sConfigFile = $sDir.'/config-itop.php';
  506. $aResult['found'] = true;
  507. }
  508. else if (file_exists($sDir.'/conf/production/config-itop.php'))
  509. {
  510. $sSourceDir = $sDir;
  511. $sSourceEnvironment = 'production';
  512. $sConfigFile = $sDir.'/conf/production/config-itop.php';
  513. $aResult['found'] = true;
  514. }
  515. if ($aResult['found'])
  516. {
  517. $oPrevConf = new Config($sConfigFile);
  518. $aResult = array(
  519. 'found' => true,
  520. 'source_dir' => $sSourceDir,
  521. 'source_environment' => $sSourceEnvironment,
  522. 'configuration_file' => $sConfigFile,
  523. 'db_server' => $oPrevConf->GetDBHost(),
  524. 'db_user' => $oPrevConf->GetDBUser(),
  525. 'db_pwd' => $oPrevConf->GetDBPwd(),
  526. 'db_name' => $oPrevConf->GetDBName(),
  527. 'db_prefix' => $oPrevConf->GetDBSubname(),
  528. );
  529. }
  530. return $aResult;
  531. }
  532. static function CheckDiskSpace($sDir)
  533. {
  534. while(($f = @disk_free_space($sDir)) == false)
  535. {
  536. if ($sDir == dirname($sDir)) break;
  537. if ($sDir == '.') break;
  538. $sDir = dirname($sDir);
  539. }
  540. return $f;
  541. }
  542. static function HumanReadableSize($fBytes)
  543. {
  544. $aSizes = array('bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Hb');
  545. $index = 0;
  546. while (($fBytes > 1000) && ($index < count($aSizes)))
  547. {
  548. $index++;
  549. $fBytes = $fBytes / 1000;
  550. }
  551. return sprintf('%.2f %s', $fBytes, $aSizes[$index]);
  552. }
  553. static function DisplayDBParameters($oPage, $bAllowDBCreation, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sNewDBName = '')
  554. {
  555. $oPage->add('<tr><td colspan="2">');
  556. $oPage->add('<fieldset><legend>Database Server Connection</legend>');
  557. $oPage->add('<table>');
  558. $oPage->add('<tr><td>Server Name:</td><td><input id="db_server" type="text" name="db_server" value="'.htmlentities($sDBServer, ENT_QUOTES, 'UTF-8').'" size="15"/></td><td>E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"</td></tr>');
  559. $oPage->add('<tr><td>Login:</td><td><input id="db_user" type="text" name="db_user" value="'.htmlentities($sDBUser, ENT_QUOTES, 'UTF-8').'" size="15"/></td><td rowspan="2" style="vertical-align:top">The account must have the following privileges on the database: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, CREATE VIEW, SUPER, TRIGGER</td></tr>');
  560. $oPage->add('<tr><td>Password:</td><td><input id="db_pwd" type="password" name="db_pwd" value="'.htmlentities($sDBPwd, ENT_QUOTES, 'UTF-8').'" size="15"/></td></tr>');
  561. $oPage->add('</table>');
  562. $oPage->add('</fieldset>');
  563. $oPage->add('</td></tr>');
  564. $oPage->add('<tr><td colspan="2"><span id="db_info"></span></td></tr>');
  565. $oPage->add('<tr><td colspan="2">');
  566. $oPage->add('<fieldset><legend>Database</legend>');
  567. $oPage->add('<table>');
  568. if ($bAllowDBCreation)
  569. {
  570. $oPage->add('<tr><td><input type="radio" id="existing_db" name="create_db" value="no"/><label for="existing_db">&nbsp;Use the existing database:</label></td>');
  571. $oPage->add('<td id="db_name_container"><input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span></td></tr>');
  572. $oPage->add('<tr><td><input type="radio" id="create_db" name="create_db" value="yes"/><label for="create_db">&nbsp;Create a new database:</label></td>');
  573. $oPage->add('<td><input id="db_new_name" type="text" name="db_new_name" value="'.htmlentities($sNewDBName, ENT_QUOTES, 'UTF-8').'" size="15" maxlength="32"/><span style="width:20px;" id="v_db_new_name"></span></td></tr>');
  574. $oPage->add('<tr><td>Use a prefix for the tables:</td><td><input id="db_prefix" type="text" name="db_prefix" value="'.htmlentities($sDBPrefix, ENT_QUOTES, 'UTF-8').'" size="15" maxlength="32"/><span style="width:20px;" id="v_db_prefix"></span></td></tr>');
  575. }
  576. else
  577. {
  578. $oPage->add('<tr><td>Database Name:</td><td id="db_name_container"><input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span></td></tr>');
  579. $oPage->add('<tr><td>Use a prefix for the tables:</td><td><input id="db_prefix" type="text" name="db_prefix" value="'.htmlentities($sDBPrefix, ENT_QUOTES, 'UTF-8').'" size="15"/><span style="width:20px;" id="v_db_prefix"></span></td></tr>');
  580. }
  581. $oPage->add('</table>');
  582. $oPage->add('</fieldset>');
  583. $oPage->add('<tr><td colspan="2"><span id="table_info">&nbsp;</span></td></tr>');
  584. $oPage->add('</td></tr>');
  585. $oPage->add_script(
  586. <<<EOF
  587. var iCheckDBTimer = null;
  588. var oXHRCheckDB = null;
  589. function CheckDBConnection()
  590. {
  591. // Don't call the server too often...
  592. if (iCheckDBTimer !== null)
  593. {
  594. clearTimeout(iCheckDBTimer);
  595. iCheckDBTimer = null;
  596. }
  597. iCheckDBTimer = setTimeout(DoCheckDBConnection, 500);
  598. }
  599. function DoCheckDBConnection()
  600. {
  601. iCheckDBTimer = null;
  602. var oParams = {
  603. 'db_server': $("#db_server").val(),
  604. 'db_user': $("#db_user").val(),
  605. 'db_pwd': $("#db_pwd").val(),
  606. 'db_name': $("#db_name").val()
  607. }
  608. if (oXHRCheckDB !== null)
  609. {
  610. oXHRCheckDB.abort();
  611. oXHRCheckDB = null;
  612. }
  613. oXHRCheckDB = WizardAsyncAction("check_db", oParams);
  614. }
  615. function ValidateField(sFieldId, bUsed)
  616. {
  617. var sValue = new String($("#"+sFieldId).val());
  618. var bMandatory = false;
  619. if (bUsed)
  620. {
  621. if (sFieldId == 'db_name')
  622. {
  623. bUsed = ($("#existing_db").attr("checked") == "checked");
  624. bMandatory = true;
  625. }
  626. if (sFieldId == 'db_new_name')
  627. {
  628. bUsed = ($("#create_db").attr("checked") == "checked");
  629. bMandatory = true;
  630. }
  631. }
  632. if (!bUsed)
  633. {
  634. $("#v_"+sFieldId).html("");
  635. return true;
  636. }
  637. else
  638. {
  639. if (sValue != "")
  640. {
  641. if (sValue.match(/^[A-Za-z][A-Za-z0-9_]*$/))
  642. {
  643. var bCollision = false;
  644. if (sFieldId == 'db_new_name')
  645. {
  646. // check that the "new name" does not correspond to an existing database
  647. var sNewName = $('#db_new_name').val();
  648. $('#db_name option').each( function() {
  649. if ($(this).attr('value') == sNewName)
  650. {
  651. bCollision = true;
  652. }
  653. });
  654. }
  655. if (bCollision)
  656. {
  657. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="A database with the same name already exists"/>');
  658. return false;
  659. }
  660. else
  661. {
  662. $("#v_"+sFieldId).html("");
  663. return true;
  664. }
  665. }
  666. else
  667. {
  668. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="Only the characters [A-Za-z0-9_] are allowed"/>');
  669. return false;
  670. }
  671. }
  672. else if (bMandatory)
  673. {
  674. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="This field cannot be empty"/>');
  675. return false;
  676. }
  677. else
  678. {
  679. $("#v_"+sFieldId).html("");
  680. return true;
  681. }
  682. }
  683. }
  684. EOF
  685. );
  686. $oPage->add_ready_script(
  687. <<<EOF
  688. DoCheckDBConnection(); // Validate the initial values immediately
  689. $("#db_server").bind("keyup change", function() { CheckDBConnection(); });
  690. $("#db_user").bind("keyup change", function() { CheckDBConnection(); });
  691. $("#db_pwd").bind("keyup change", function() { CheckDBConnection(); });
  692. $("#db_new_name").bind("click keyup change", function() { $("#create_db").attr("checked", "checked"); WizardUpdateButtons(); });
  693. $("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });
  694. $("#db_prefix").bind("keyup change", function() { WizardUpdateButtons(); });
  695. $("#existing_db").bind("click change", function() { WizardUpdateButtons(); });
  696. $("#create_db").bind("click change", function() { WizardUpdateButtons(); });
  697. EOF
  698. );
  699. }
  700. /**
  701. * Helper function check the connection to the database, verify a few conditions (minimum version, etc...) and (if connected)
  702. * enumerate the existing databases (if possible)
  703. * @return mixed false if the connection failed or array('checks' => Array of CheckResult, 'databases' => Array of database names (as strings) or null if not allowed)
  704. */
  705. static function CheckServerConnection($sDBServer, $sDBUser, $sDBPwd)
  706. {
  707. $aResult = array('checks' => array(), 'databases' => null);
  708. try
  709. {
  710. $oDBSource = new CMDBSource;
  711. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  712. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Connection to '$sDBServer' as '$sDBUser' successful.");
  713. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  714. $sDBVersion = $oDBSource->GetDBVersion();
  715. if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>='))
  716. {
  717. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")");
  718. // Check some server variables
  719. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  720. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  721. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  722. {
  723. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is big enough compared to upload_max_filesize ($iMaxUploadSize).");
  724. }
  725. else if($iMaxAllowedPacket < $iMaxUploadSize)
  726. {
  727. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
  728. }
  729. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  730. if ($iMaxConnections < 5)
  731. {
  732. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  733. }
  734. else
  735. {
  736. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_connections is set to $iMaxConnections.");
  737. }
  738. }
  739. else
  740. {
  741. $aResult['checks'][] = new CheckResult(CheckResult::ERROR, "Error: Current MySQL version is ($sDBVersion), minimum required version (".self::MYSQL_MIN_VERSION.")");
  742. }
  743. try
  744. {
  745. $aResult['databases'] = $oDBSource->ListDB();
  746. }
  747. catch(Exception $e)
  748. {
  749. $aResult['databases'] = null;
  750. }
  751. }
  752. catch(Exception $e)
  753. {
  754. return false;
  755. }
  756. return $aResult;
  757. }
  758. static public function AsyncCheckDB($oPage, $aParameters)
  759. {
  760. $sDBServer = $aParameters['db_server'];
  761. $sDBUser = $aParameters['db_user'];
  762. $sDBPwd = $aParameters['db_pwd'];
  763. $sDBName = $aParameters['db_name'];
  764. $oPage->add_ready_script('oXHRCheckDB = null;');
  765. $checks = SetupUtils::CheckServerConnection($sDBServer, $sDBUser, $sDBPwd);
  766. if ($checks === false)
  767. {
  768. // Connection failed, disable the "Next" button
  769. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  770. $oPage->add_ready_script('$("#db_info").html("No connection to the database...");');
  771. }
  772. else
  773. {
  774. $aErrors = array();
  775. $aWarnings = array();
  776. foreach($checks['checks'] as $oCheck)
  777. {
  778. if ($oCheck->iSeverity == CheckResult::ERROR)
  779. {
  780. $aErrors[] = $oCheck->sLabel;
  781. }
  782. else if ($oCheck->iSeverity == CheckResult::WARNING)
  783. {
  784. $aWarnings[] = $oCheck->sLabel;
  785. }
  786. }
  787. if (count($aErrors) > 0)
  788. {
  789. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  790. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_error.png"/>&nbsp;<b>Error:</b> '.htmlentities(implode('<br/>', $aErrors), ENT_QUOTES, 'UTF-8').'\');');
  791. }
  792. else if (count($aWarnings) > 0)
  793. {
  794. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  795. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/error.png"/>&nbsp;<b>Warning:</b> '.htmlentities(implode('<br/>', $aWarnings), ENT_QUOTES, 'UTF-8').'\');');
  796. }
  797. else
  798. {
  799. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  800. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_ok.png"/>&nbsp;Database server connection Ok.\');');
  801. }
  802. if ($checks['databases'] == null)
  803. {
  804. $sDBNameInput = '<input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span>';
  805. $oPage->add_ready_script('$("#table_info").html(\'<img src="../images/error.png"/>&nbsp;Not enough rights to enumerate the databases\');');
  806. }
  807. else
  808. {
  809. $sDBNameInput = '<select id="db_name" name="db_name">';
  810. foreach($checks['databases'] as $sDatabaseName)
  811. {
  812. if ($sDatabaseName != 'information_schema')
  813. {
  814. $sEncodedName = htmlentities($sDatabaseName, ENT_QUOTES, 'UTF-8');
  815. $sSelected = ($sDatabaseName == $sDBName) ? ' selected ' : '';
  816. $sDBNameInput .= '<option value="'.$sEncodedName.'"'.$sSelected.'>'.$sEncodedName.'</option>';
  817. }
  818. }
  819. $sDBNameInput .= '</select>';
  820. }
  821. $oPage->add_ready_script('$("#db_name_container").html("'.addslashes($sDBNameInput).'");');
  822. $oPage->add_ready_script('$("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });');
  823. }
  824. $oPage->add_ready_script('WizardUpdateButtons();');
  825. }
  826. /**
  827. * Helper function to get the available languages from the given directory
  828. * @param $sDir Path to the dictionary
  829. * @return an array of language code => description
  830. */
  831. static public function GetAvailableLanguages($sDir)
  832. {
  833. require_once(APPROOT.'/core/coreexception.class.inc.php');
  834. require_once(APPROOT.'/core/dict.class.inc.php');
  835. $aFiles = scandir($sDir);
  836. foreach($aFiles as $sFile)
  837. {
  838. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  839. {
  840. // Skip
  841. continue;
  842. }
  843. $sFilePath = $sDir.'/'.$sFile;
  844. if (is_file($sFilePath) && preg_match('/^.+\.dict.*\.php$/i', $sFilePath, $aMatches))
  845. {
  846. require_once($sFilePath);
  847. }
  848. }
  849. return Dict::GetLanguages();
  850. }
  851. static public function GetLanguageSelect($sSourceDir, $sInputName, $sDefaultLanguageCode)
  852. {
  853. $sHtml = '<select id="'.$sInputName.'" name="'.$sInputName.'">';
  854. $sSourceDir = APPROOT.'dictionaries/';
  855. $aLanguages = SetupUtils::GetAvailableLanguages($sSourceDir);
  856. foreach($aLanguages as $sCode => $aInfo)
  857. {
  858. $sSelected = ($sCode == $sDefaultLanguageCode) ? ' selected ' : '';
  859. $sHtml .= '<option value="'.$sCode.'"'.$sSelected.'>'.htmlentities($aInfo['description'], ENT_QUOTES, 'UTF-8').' ('.htmlentities($aInfo['localized_description'], ENT_QUOTES, 'UTF-8').')</option>';
  860. }
  861. $sHtml .= '</select></td></tr>';
  862. return $sHtml;
  863. }
  864. public static function AnalyzeInstallation($oWizard)
  865. {
  866. require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
  867. $oConfig = new Config();
  868. $aParamValues = array(
  869. 'db_server' => $oWizard->GetParameter('db_server', ''),
  870. 'db_user' => $oWizard->GetParameter('db_user', ''),
  871. 'db_pwd' => $oWizard->GetParameter('db_pwd', ''),
  872. 'db_name' => $oWizard->GetParameter('db_name', ''),
  873. 'db_prefix' => $oWizard->GetParameter('db_prefix', ''),
  874. 'source_dir' => APPROOT.'datamodel',
  875. );
  876. $oConfig->UpdateFromParams($aParamValues, 'datamodel');
  877. $oProductionEnv = new RunTimeEnvironment();
  878. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, 'datamodel');
  879. return $aAvailableModules;
  880. }
  881. /**
  882. * Checks if the content of a directory matches the given manifest
  883. * @param string $sBaseDir Path to the root directory of iTop
  884. * @param string $sSourceDir Relative path to the directory to check under $sBaseDir
  885. * @param Array $aDOMManifest Array of array('path' => relative_path 'size'=> iSize, 'md5' => sHexMD5)
  886. * @param Hash $aResult Used for recursion
  887. * @return hash Hash array ('added' => array(), 'removed' => array(), 'modified' => array())
  888. */
  889. public static function CheckDirAgainstManifest($sBaseDir, $sSourceDir, $aManifest, $aExcludeNames = array('.svn'), $aResult = null)
  890. {
  891. if ($aResult === null)
  892. {
  893. $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
  894. }
  895. if (substr($sSourceDir, 0, 1) == '/')
  896. {
  897. $sSourceDir = substr($sSourceDir, 1);
  898. }
  899. // Manifest limited to all the files supposed to be located in this directory
  900. $aDirManifest = array();
  901. foreach($aManifest as $aFileInfo)
  902. {
  903. $sDir = dirname($aFileInfo['path']);
  904. if ($sDir == '.')
  905. {
  906. // Hmm... the file seems located at the root of iTop
  907. $sDir = '';
  908. }
  909. if ($sDir == $sSourceDir)
  910. {
  911. $aDirManifest[basename($aFileInfo['path'])] = $aFileInfo;
  912. }
  913. }
  914. // Read the content of the directory
  915. foreach(glob($sBaseDir.'/'.$sSourceDir .'/*') as $sFilePath)
  916. {
  917. $sFile = basename($sFilePath);
  918. if (in_array(basename($sFile), $aExcludeNames)) continue;
  919. if(is_dir($sFilePath))
  920. {
  921. $aResult = self::CheckDirAgainstManifest($sBaseDir, $sSourceDir.'/'.$sFile, $aManifest, $aExcludeNames, $aResult);
  922. }
  923. else
  924. {
  925. if (!array_key_exists($sFile, $aDirManifest))
  926. {
  927. //echo "New file ".$sFile." in $sSourceDir\n";
  928. $aResult['added'][$sSourceDir.'/'.$sFile] = true;
  929. }
  930. else
  931. {
  932. $aStats = stat($sFilePath);
  933. if ($aStats['size'] != $aDirManifest[$sFile]['size'])
  934. {
  935. // Different sizes
  936. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Different sizes. Original size: '.$aDirManifest[$sFile]['size'].' bytes, actual file size on disk: '.$aStats['size'].' bytes.';
  937. }
  938. else
  939. {
  940. // Same size, compare the md5 signature
  941. $sMD5 = md5_file($sFilePath);
  942. if ($sMD5 != $aDirManifest[$sFile]['md5'])
  943. {
  944. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Content modified (MD5 checksums differ).';
  945. }
  946. //else
  947. //{
  948. // echo $sSourceDir.'/'.$sFile." unmodified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n";
  949. //}
  950. }
  951. //echo "Removing ".$sFile." from aDirManifest\n";
  952. unset($aDirManifest[$sFile]);
  953. }
  954. }
  955. }
  956. // What remains in the array are files that were deleted
  957. foreach($aDirManifest as $sDeletedFile => $void)
  958. {
  959. $aResult['removed'][$sSourceDir.'/'.$sDeletedFile] = true;
  960. }
  961. return $aResult;
  962. }
  963. public static function CheckDataModelFiles($sManifestFile, $sBaseDir)
  964. {
  965. $oXML = simplexml_load_file($sManifestFile);
  966. $aManifest = array();
  967. foreach($oXML as $oFileInfo)
  968. {
  969. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  970. }
  971. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'modules', $aManifest);
  972. // echo "<pre>Comparison of ".dirname($sBaseDir)."/modules:\n".print_r($aResults, true)."</pre>";
  973. return $aResults;
  974. }
  975. public static function CheckPortalFiles($sManifestFile, $sBaseDir)
  976. {
  977. $oXML = simplexml_load_file($sManifestFile);
  978. $aManifest = array();
  979. foreach($oXML as $oFileInfo)
  980. {
  981. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  982. }
  983. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest);
  984. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  985. return $aResults;
  986. }
  987. public static function CheckApplicationFiles($sManifestFile, $sBaseDir)
  988. {
  989. $oXML = simplexml_load_file($sManifestFile);
  990. $aManifest = array();
  991. foreach($oXML as $oFileInfo)
  992. {
  993. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  994. }
  995. $aResults = array('added' => array(), 'removed' => array(), 'modified' => array());
  996. foreach(array('addons', 'core', 'dictionaries', 'js', 'application', 'css', 'pages', 'synchro', 'webservices') as $sDir)
  997. {
  998. $aTmp = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest);
  999. $aResults['added'] = array_merge($aResults['added'], $aTmp['added']);
  1000. $aResults['modified'] = array_merge($aResults['modified'], $aTmp['modified']);
  1001. $aResults['removed'] = array_merge($aResults['removed'], $aTmp['removed']);
  1002. }
  1003. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  1004. return $aResults;
  1005. }
  1006. }