setuputils.class.inc.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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)
  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);
  446. }
  447. else
  448. {
  449. copy($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  450. }
  451. }
  452. }
  453. return true;
  454. }
  455. elseif (is_file($sSource))
  456. {
  457. return copy($sSource, $sDest);
  458. }
  459. else
  460. {
  461. return false;
  462. }
  463. }
  464. static function GetPreviousInstance($sDir)
  465. {
  466. $bFound = false;
  467. $sSourceDir = '';
  468. $sSourceEnvironement = '';
  469. $sConfigFile = '';
  470. $aResult = array(
  471. 'found' => false,
  472. );
  473. if (file_exists($sDir.'/config-itop.php'))
  474. {
  475. $sSourceDir = $sDir;
  476. $sSourceEnvironment = '';
  477. $sConfigFile = $sDir.'/config-itop.php';
  478. $aResult['found'] = true;
  479. }
  480. else if (file_exists($sDir.'/conf/production/config-itop.php'))
  481. {
  482. $sSourceDir = $sDir;
  483. $sSourceEnvironment = 'production';
  484. $sConfigFile = $sDir.'/conf/production/config-itop.php';
  485. $aResult['found'] = true;
  486. }
  487. if ($aResult['found'])
  488. {
  489. $oPrevConf = new Config($sConfigFile);
  490. $aResult = array(
  491. 'found' => true,
  492. 'source_dir' => $sSourceDir,
  493. 'source_environment' => $sSourceEnvironment,
  494. 'configuration_file' => $sConfigFile,
  495. 'db_server' => $oPrevConf->GetDBHost(),
  496. 'db_user' => $oPrevConf->GetDBUser(),
  497. 'db_pwd' => $oPrevConf->GetDBPwd(),
  498. 'db_name' => $oPrevConf->GetDBName(),
  499. 'db_prefix' => $oPrevConf->GetDBSubname(),
  500. );
  501. }
  502. return $aResult;
  503. }
  504. static function CheckDiskSpace($sDir)
  505. {
  506. while(($f = @disk_free_space($sDir)) == false)
  507. {
  508. if ($sDir == dirname($sDir)) break;
  509. if ($sDir == '.') break;
  510. $sDir = dirname($sDir);
  511. }
  512. return $f;
  513. }
  514. static function HumanReadableSize($fBytes)
  515. {
  516. $aSizes = array('bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Hb');
  517. $index = 0;
  518. while (($fBytes > 1000) && ($index < count($aSizes)))
  519. {
  520. $index++;
  521. $fBytes = $fBytes / 1000;
  522. }
  523. return sprintf('%.2f %s', $fBytes, $aSizes[$index]);
  524. }
  525. static function DisplayDBParameters($oPage, $bAllowDBCreation, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sNewDBName = '')
  526. {
  527. $oPage->add('<tr><td colspan="2">');
  528. $oPage->add('<fieldset><legend>Database Server Connection</legend>');
  529. $oPage->add('<table>');
  530. $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>');
  531. $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>');
  532. $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>');
  533. $oPage->add('</table>');
  534. $oPage->add('</fieldset>');
  535. $oPage->add('</td></tr>');
  536. $oPage->add('<tr><td colspan="2"><span id="db_info"></span></td></tr>');
  537. $oPage->add('<tr><td colspan="2">');
  538. $oPage->add('<fieldset><legend>Database</legend>');
  539. $oPage->add('<table>');
  540. if ($bAllowDBCreation)
  541. {
  542. $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>');
  543. $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>');
  544. $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>');
  545. $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>');
  546. $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>');
  547. }
  548. else
  549. {
  550. $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>');
  551. $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>');
  552. }
  553. $oPage->add('</table>');
  554. $oPage->add('</fieldset>');
  555. $oPage->add('<tr><td colspan="2"><span id="table_info">&nbsp;</span></td></tr>');
  556. $oPage->add('</td></tr>');
  557. $oPage->add_script(
  558. <<<EOF
  559. var iCheckDBTimer = null;
  560. var oXHRCheckDB = null;
  561. function CheckDBConnection()
  562. {
  563. // Don't call the server too often...
  564. if (iCheckDBTimer !== null)
  565. {
  566. clearTimeout(iCheckDBTimer);
  567. iCheckDBTimer = null;
  568. }
  569. iCheckDBTimer = setTimeout(DoCheckDBConnection, 500);
  570. }
  571. function DoCheckDBConnection()
  572. {
  573. iCheckDBTimer = null;
  574. var oParams = {
  575. 'db_server': $("#db_server").val(),
  576. 'db_user': $("#db_user").val(),
  577. 'db_pwd': $("#db_pwd").val(),
  578. 'db_name': $("#db_name").val()
  579. }
  580. if (oXHRCheckDB !== null)
  581. {
  582. oXHRCheckDB.abort();
  583. oXHRCheckDB = null;
  584. }
  585. oXHRCheckDB = WizardAsyncAction("check_db", oParams);
  586. }
  587. function ValidateField(sFieldId, bUsed)
  588. {
  589. var sValue = new String($("#"+sFieldId).val());
  590. var bMandatory = false;
  591. if (bUsed)
  592. {
  593. if (sFieldId == 'db_name')
  594. {
  595. bUsed = ($("#existing_db").attr("checked") == "checked");
  596. bMandatory = true;
  597. }
  598. if (sFieldId == 'db_new_name')
  599. {
  600. bUsed = ($("#create_db").attr("checked") == "checked");
  601. bMandatory = true;
  602. }
  603. }
  604. if (!bUsed)
  605. {
  606. $("#v_"+sFieldId).html("");
  607. return true;
  608. }
  609. else
  610. {
  611. if (sValue != "")
  612. {
  613. if (sValue.match(/^[A-Za-z][A-Za-z0-9_]*$/))
  614. {
  615. $("#v_"+sFieldId).html("");
  616. return true;
  617. }
  618. else
  619. {
  620. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="Only the characters [A-Za-z0-9_] are allowed"/>');
  621. return false;
  622. }
  623. }
  624. else if (bMandatory)
  625. {
  626. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="This field cannot be empty"/>');
  627. return false;
  628. }
  629. else
  630. {
  631. $("#v_"+sFieldId).html("");
  632. return true;
  633. }
  634. }
  635. }
  636. EOF
  637. );
  638. $oPage->add_ready_script(
  639. <<<EOF
  640. DoCheckDBConnection(); // Validate the initial values immediately
  641. $("#db_server").bind("keyup change", function() { CheckDBConnection(); });
  642. $("#db_user").bind("keyup change", function() { CheckDBConnection(); });
  643. $("#db_pwd").bind("keyup change", function() { CheckDBConnection(); });
  644. $("#db_new_name").bind("click", function() { $("#create_db").attr("checked", "checked"); });
  645. $("#db_new_name").bind("keyup change", function() { WizardUpdateButtons(); });
  646. $("#db_name").bind("keyup change", function() { WizardUpdateButtons(); });
  647. $("#db_prefix").bind("keyup change", function() { WizardUpdateButtons(); });
  648. $("#db_name").bind("click", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });
  649. $("#existing_db").bind("click change", function() { WizardUpdateButtons(); });
  650. $("#create_db").bind("click change", function() { WizardUpdateButtons(); });
  651. EOF
  652. );
  653. }
  654. /**
  655. * Helper function check the connection to the database, verify a few conditions (minimum version, etc...) and (if connected)
  656. * enumerate the existing databases (if possible)
  657. * @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)
  658. */
  659. static function CheckServerConnection($sDBServer, $sDBUser, $sDBPwd)
  660. {
  661. $aResult = array('checks' => array(), 'databases' => null);
  662. try
  663. {
  664. $oDBSource = new CMDBSource;
  665. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  666. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Connection to '$sDBServer' as '$sDBUser' successful.");
  667. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  668. $sDBVersion = $oDBSource->GetDBVersion();
  669. if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>='))
  670. {
  671. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")");
  672. // Check some server variables
  673. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  674. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  675. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  676. {
  677. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is big enough compared to upload_max_filesize ($iMaxUploadSize).");
  678. }
  679. else if($iMaxAllowedPacket < $iMaxUploadSize)
  680. {
  681. $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).".");
  682. }
  683. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  684. if ($iMaxConnections < 5)
  685. {
  686. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  687. }
  688. else
  689. {
  690. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_connections is set to $iMaxConnections.");
  691. }
  692. }
  693. else
  694. {
  695. $aResult['checks'][] = new CheckResult(CheckResult::ERROR, "Error: Current MySQL version is ($sDBVersion), minimum required version (".self::MYSQL_MIN_VERSION.")");
  696. }
  697. try
  698. {
  699. $aResult['databases'] = $oDBSource->ListDB();
  700. }
  701. catch(Exception $e)
  702. {
  703. $aResult['databases'] = null;
  704. }
  705. }
  706. catch(Exception $e)
  707. {
  708. return false;
  709. }
  710. return $aResult;
  711. }
  712. static public function AsyncCheckDB($oPage, $aParameters)
  713. {
  714. $sDBServer = $aParameters['db_server'];
  715. $sDBUser = $aParameters['db_user'];
  716. $sDBPwd = $aParameters['db_pwd'];
  717. $sDBName = $aParameters['db_name'];
  718. $oPage->add_ready_script('oXHRCheckDB = null;');
  719. $checks = SetupUtils::CheckServerConnection($sDBServer, $sDBUser, $sDBPwd);
  720. if ($checks === false)
  721. {
  722. // Connection failed, disable the "Next" button
  723. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  724. $oPage->add_ready_script('$("#db_info").html("No connection to the database...");');
  725. }
  726. else
  727. {
  728. $aErrors = array();
  729. $aWarnings = array();
  730. foreach($checks['checks'] as $oCheck)
  731. {
  732. if ($oCheck->iSeverity == CheckResult::ERROR)
  733. {
  734. $aErrors[] = $oCheck->sLabel;
  735. }
  736. else if ($oCheck->iSeverity == CheckResult::WARNING)
  737. {
  738. $aWarnings[] = $oCheck->sLabel;
  739. }
  740. }
  741. if (count($aErrors) > 0)
  742. {
  743. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  744. $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').'\');');
  745. }
  746. else if (count($aWarnings) > 0)
  747. {
  748. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  749. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/error.png"/>&nbsp;<b>Warning:</b> '.htmlentities(implode('<br/>', $aWarnings), ENT_QUOTES, 'UTF-8').'\');');
  750. }
  751. else
  752. {
  753. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  754. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_ok.png"/>&nbsp;Database server connection Ok.\');');
  755. }
  756. if ($checks['databases'] == null)
  757. {
  758. $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>';
  759. $oPage->add_ready_script('$("#table_info").html(\'<img src="../images/error.png"/>&nbsp;Not enough rights to enumerate the databases\');');
  760. }
  761. else
  762. {
  763. $sDBNameInput = '<select id="db_name" name="db_name">';
  764. foreach($checks['databases'] as $sDatabaseName)
  765. {
  766. if ($sDatabaseName != 'information_schema')
  767. {
  768. $sEncodedName = htmlentities($sDatabaseName, ENT_QUOTES, 'UTF-8');
  769. $sSelected = ($sDatabaseName == $sDBName) ? ' selected ' : '';
  770. $sDBNameInput .= '<option value="'.$sEncodedName.'"'.$sSelected.'>'.$sEncodedName.'</option>';
  771. }
  772. }
  773. $sDBNameInput .= '</select>';
  774. }
  775. $oPage->add_ready_script('$("#db_name_container").html("'.addslashes($sDBNameInput).'");');
  776. $oPage->add_ready_script('$("#db_name").bind("click", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });');
  777. $oPage->add_ready_script('$("#db_name").bind("keyup change", function() { WizardUpdateButtons(); });');
  778. }
  779. $oPage->add_ready_script('WizardUpdateButtons();');
  780. }
  781. /**
  782. * Helper function to get the available languages from the given directory
  783. * @param $sDir Path to the dictionary
  784. * @return an array of language code => description
  785. */
  786. static public function GetAvailableLanguages($sDir)
  787. {
  788. require_once(APPROOT.'/core/coreexception.class.inc.php');
  789. require_once(APPROOT.'/core/dict.class.inc.php');
  790. $aFiles = scandir($sDir);
  791. foreach($aFiles as $sFile)
  792. {
  793. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  794. {
  795. // Skip
  796. continue;
  797. }
  798. $sFilePath = $sDir.'/'.$sFile;
  799. if (is_file($sFilePath) && preg_match('/^.+\.dict.*\.php$/i', $sFilePath, $aMatches))
  800. {
  801. require_once($sFilePath);
  802. }
  803. }
  804. return Dict::GetLanguages();
  805. }
  806. static public function GetLanguageSelect($sSourceDir, $sInputName, $sDefaultLanguageCode)
  807. {
  808. $sHtml = '<select id="'.$sInputName.'" name="'.$sInputName.'">';
  809. $sSourceDir = APPROOT.'dictionaries/';
  810. $aLanguages = SetupUtils::GetAvailableLanguages($sSourceDir);
  811. foreach($aLanguages as $sCode => $aInfo)
  812. {
  813. $sSelected = ($sCode == $sDefaultLanguageCode) ? ' selected ' : '';
  814. $sHtml .= '<option value="'.$sCode.'"'.$sSelected.'>'.htmlentities($aInfo['description'], ENT_QUOTES, 'UTF-8').' ('.htmlentities($aInfo['localized_description'], ENT_QUOTES, 'UTF-8').')</option>';
  815. }
  816. $sHtml .= '</select></td></tr>';
  817. return $sHtml;
  818. }
  819. }