PageRenderTime 67ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/other/install.php

https://github.com/smf-portal/SMF2.1
PHP | 2588 lines | 2071 code | 308 blank | 209 comment | 369 complexity | f96e529e5dd28aa0c8b991b220282873 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2012 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. $GLOBALS['current_smf_version'] = '2.1 Alpha 1';
  13. $GLOBALS['db_script_version'] = '2-1';
  14. $GLOBALS['required_php_version'] = '5.1.0';
  15. // Don't have PHP support, do you?
  16. // ><html dir="ltr"><head><title>Error!</title></head><body>Sorry, this installer requires PHP!<div style="display: none;">
  17. // Database info.
  18. $databases = array(
  19. 'mysql' => array(
  20. 'name' => 'MySQL',
  21. 'version' => '4.0.18',
  22. 'version_check' => 'return min(mysql_get_server_info(), mysql_get_client_info());',
  23. 'supported' => function_exists('mysql_connect'),
  24. 'default_user' => 'mysql.default_user',
  25. 'default_password' => 'mysql.default_password',
  26. 'default_host' => 'mysql.default_host',
  27. 'default_port' => 'mysql.default_port',
  28. 'utf8_support' => true,
  29. 'utf8_version' => '4.1.0',
  30. 'utf8_version_check' => 'return mysql_get_server_info();',
  31. 'utf8_default' => true,
  32. 'utf8_required' => false,
  33. 'alter_support' => true,
  34. 'validate_prefix' => create_function('&$value', '
  35. $value = preg_replace(\'~[^A-Za-z0-9_\$]~\', \'\', $value);
  36. return true;
  37. '),
  38. ),
  39. 'postgresql' => array(
  40. 'name' => 'PostgreSQL',
  41. 'version' => '8.0',
  42. 'function_check' => 'pg_connect',
  43. 'version_check' => '$request = pg_query(\'SELECT version()\'); list ($version) = pg_fetch_row($request); list($pgl, $version) = explode(" ", $version); return $version;',
  44. 'supported' => function_exists('pg_connect'),
  45. 'always_has_db' => true,
  46. 'utf8_default' => true,
  47. 'utf8_required' => true,
  48. 'utf8_support' => true,
  49. 'utf8_version' => '8.0',
  50. 'utf8_version_check' => '$request = pg_query(\'SELECT version()\'); list ($version) = pg_fetch_row($request); list($pgl, $version) = explode(" ", $version); return $version;',
  51. 'validate_prefix' => create_function('&$value', '
  52. $value = preg_replace(\'~[^A-Za-z0-9_\$]~\', \'\', $value);
  53. // Is it reserved?
  54. if ($value == \'pg_\')
  55. return $txt[\'error_db_prefix_reserved\'];
  56. // Is the prefix numeric?
  57. if (preg_match(\'~^\d~\', $value))
  58. return $txt[\'error_db_prefix_numeric\'];
  59. return true;
  60. '),
  61. ),
  62. 'sqlite' => array(
  63. 'name' => 'SQLite',
  64. 'version' => '1',
  65. 'function_check' => 'sqlite_open',
  66. 'version_check' => 'return 1;',
  67. 'supported' => function_exists('sqlite_open'),
  68. 'always_has_db' => true,
  69. 'utf8_default' => true,
  70. 'utf8_required' => true,
  71. 'utf8_support' => false,
  72. 'validate_prefix' => create_function('&$value', '
  73. global $incontext, $txt;
  74. $value = preg_replace(\'~[^A-Za-z0-9_\$]~\', \'\', $value);
  75. // Is it reserved?
  76. if ($value == \'sqlite_\')
  77. return $txt[\'error_db_prefix_reserved\'];
  78. // Is the prefix numeric?
  79. if (preg_match(\'~^\d~\', $value))
  80. return $txt[\'error_db_prefix_numeric\'];
  81. return true;
  82. '),
  83. ),
  84. );
  85. // Initialize everything and load the language files.
  86. initialize_inputs();
  87. load_lang_file();
  88. // This is what we are.
  89. $installurl = $_SERVER['PHP_SELF'];
  90. // This is where SMF is.
  91. $smfsite = 'http://www.simplemachines.org/smf';
  92. // All the steps in detail.
  93. // Number,Name,Function,Progress Weight.
  94. $incontext['steps'] = array(
  95. 0 => array(1, $txt['install_step_welcome'], 'Welcome', 0),
  96. 1 => array(2, $txt['install_step_writable'], 'CheckFilesWritable', 10),
  97. 2 => array(3, $txt['install_step_databaseset'], 'DatabaseSettings', 15),
  98. 3 => array(4, $txt['install_step_forum'], 'ForumSettings', 40),
  99. 4 => array(5, $txt['install_step_databasechange'], 'DatabasePopulation', 15),
  100. 5 => array(6, $txt['install_step_admin'], 'AdminAccount', 20),
  101. 6 => array(7, $txt['install_step_delete'], 'DeleteInstall', 0),
  102. );
  103. // Default title...
  104. $incontext['page_title'] = $txt['smf_installer'];
  105. // What step are we on?
  106. $incontext['current_step'] = isset($_GET['step']) ? (int) $_GET['step'] : 0;
  107. // Loop through all the steps doing each one as required.
  108. $incontext['overall_percent'] = 0;
  109. foreach ($incontext['steps'] as $num => $step)
  110. {
  111. if ($num >= $incontext['current_step'])
  112. {
  113. // The current weight of this step in terms of overall progress.
  114. $incontext['step_weight'] = $step[3];
  115. // Make sure we reset the skip button.
  116. $incontext['skip'] = false;
  117. // Call the step and if it returns false that means pause!
  118. if (function_exists($step[2]) && $step[2]() === false)
  119. break;
  120. elseif (function_exists($step[2]))
  121. $incontext['current_step']++;
  122. // No warnings pass on.
  123. $incontext['warning'] = '';
  124. }
  125. $incontext['overall_percent'] += $step[3];
  126. }
  127. // Actually do the template stuff.
  128. installExit();
  129. function initialize_inputs()
  130. {
  131. global $databases, $incontext;
  132. // Just so people using older versions of PHP aren't left in the cold.
  133. if (!isset($_SERVER['PHP_SELF']))
  134. $_SERVER['PHP_SELF'] = isset($GLOBALS['HTTP_SERVER_VARS']['PHP_SELF']) ? $GLOBALS['HTTP_SERVER_VARS']['PHP_SELF'] : 'install.php';
  135. // Turn off magic quotes runtime and enable error reporting.
  136. if (function_exists('set_magic_quotes_runtime'))
  137. @set_magic_quotes_runtime(0);
  138. error_reporting(E_ALL);
  139. // Fun. Low PHP version...
  140. if (!isset($_GET))
  141. {
  142. $GLOBALS['_GET']['step'] = 0;
  143. return;
  144. }
  145. if (!isset($_GET['obgz']))
  146. {
  147. ob_start();
  148. if (ini_get('session.save_handler') == 'user')
  149. @ini_set('session.save_handler', 'files');
  150. if (function_exists('session_start'))
  151. @session_start();
  152. }
  153. else
  154. {
  155. ob_start('ob_gzhandler');
  156. if (ini_get('session.save_handler') == 'user')
  157. @ini_set('session.save_handler', 'files');
  158. session_start();
  159. if (!headers_sent())
  160. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  161. <html xmlns="http://www.w3.org/1999/xhtml">
  162. <head>
  163. <title>', htmlspecialchars($_GET['pass_string']), '</title>
  164. </head>
  165. <body style="background-color: #d4d4d4; margin-top: 16%; text-align: center; font-size: 16pt;">
  166. <strong>', htmlspecialchars($_GET['pass_string']), '</strong>
  167. </body>
  168. </html>';
  169. exit;
  170. }
  171. // Are we calling the backup css file?
  172. if (isset($_GET['infile_css']))
  173. {
  174. header('Content-Type: text/css');
  175. template_css();
  176. exit;
  177. }
  178. // Anybody home?
  179. if (!isset($_GET['xml']))
  180. {
  181. $incontext['remote_files_available'] = false;
  182. $test = @fsockopen('www.simplemachines.org', 80, $errno, $errstr, 1);
  183. if ($test)
  184. $incontext['remote_files_available'] = true;
  185. @fclose($test);
  186. }
  187. // Add slashes, as long as they aren't already being added.
  188. if (!function_exists('get_magic_quotes_gpc') || @get_magic_quotes_gpc() == 0)
  189. foreach ($_POST as $k => $v)
  190. if (strpos($k, 'password') === false)
  191. $_POST[$k] = addslashes($v);
  192. // This is really quite simple; if ?delete is on the URL, delete the installer...
  193. if (isset($_GET['delete']))
  194. {
  195. if (isset($_SESSION['installer_temp_ftp']))
  196. {
  197. $ftp = new ftp_connection($_SESSION['installer_temp_ftp']['server'], $_SESSION['installer_temp_ftp']['port'], $_SESSION['installer_temp_ftp']['username'], $_SESSION['installer_temp_ftp']['password']);
  198. $ftp->chdir($_SESSION['installer_temp_ftp']['path']);
  199. $ftp->unlink('install.php');
  200. $ftp->unlink('webinstall.php');
  201. foreach ($databases as $key => $dummy)
  202. $ftp->unlink('install_' . $GLOBALS['db_script_version'] . '_' . $key . '.sql');
  203. $ftp->close();
  204. unset($_SESSION['installer_temp_ftp']);
  205. }
  206. else
  207. {
  208. @unlink(__FILE__);
  209. @unlink(dirname(__FILE__) . '/webinstall.php');
  210. foreach ($databases as $key => $dummy)
  211. @unlink(dirname(__FILE__) . '/install_' . $GLOBALS['db_script_version'] . '_' . $key . '.sql');
  212. }
  213. // Now just redirect to a blank.png...
  214. header('Location: http://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']) . dirname($_SERVER['PHP_SELF']) . '/Themes/default/images/blank.png');
  215. exit;
  216. }
  217. // PHP 5 might cry if we don't do this now.
  218. if (function_exists('date_default_timezone_set'))
  219. {
  220. $server_offset = @mktime(0, 0, 0, 1, 1, 1970);
  221. date_default_timezone_set('Etc/GMT' . ($server_offset > 0 ? '+' : '') . ($server_offset / 3600));
  222. }
  223. // Force an integer step, defaulting to 0.
  224. $_GET['step'] = (int) @$_GET['step'];
  225. }
  226. // Load the list of language files, and the current language file.
  227. function load_lang_file()
  228. {
  229. global $txt, $incontext;
  230. $incontext['detected_languages'] = array();
  231. // Make sure the languages directory actually exists.
  232. if (file_exists(dirname(__FILE__) . '/Themes/default/languages'))
  233. {
  234. // Find all the "Install" language files in the directory.
  235. $dir = dir(dirname(__FILE__) . '/Themes/default/languages');
  236. while ($entry = $dir->read())
  237. {
  238. if (substr($entry, 0, 8) == 'Install.' && substr($entry, -4) == '.php')
  239. $incontext['detected_languages'][$entry] = ucfirst(substr($entry, 8, strlen($entry) - 12));
  240. }
  241. $dir->close();
  242. }
  243. // Didn't find any, show an error message!
  244. if (empty($incontext['detected_languages']))
  245. {
  246. // Let's not cache this message, eh?
  247. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  248. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  249. header('Cache-Control: no-cache');
  250. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  251. <html xmlns="http://www.w3.org/1999/xhtml">
  252. <head>
  253. <title>SMF Installer: Error!</title>
  254. </head>
  255. <body style="font-family: sans-serif;"><div style="width: 600px;">
  256. <h1 style="font-size: 14pt;">A critical error has occurred.</h1>
  257. <p>This installer was unable to find the installer\'s language file or files. They should be found under:</p>
  258. <div style="margin: 1ex; font-family: monospace; font-weight: bold;">', dirname($_SERVER['PHP_SELF']) != '/' ? dirname($_SERVER['PHP_SELF']) : '', '/Themes/default/languages</div>
  259. <p>In some cases, FTP clients do not properly upload files with this many folders. Please double check to make sure you <span style="font-weight: 600;">have uploaded all the files in the distribution</span>.</p>
  260. <p>If that doesn\'t help, please make sure this install.php file is in the same place as the Themes folder.</p>
  261. <p>If you continue to get this error message, feel free to <a href="http://support.simplemachines.org/">look to us for support</a>.</p>
  262. </div></body>
  263. </html>';
  264. die;
  265. }
  266. // Override the language file?
  267. if (isset($_GET['lang_file']))
  268. $_SESSION['installer_temp_lang'] = $_GET['lang_file'];
  269. elseif (isset($GLOBALS['HTTP_GET_VARS']['lang_file']))
  270. $_SESSION['installer_temp_lang'] = $GLOBALS['HTTP_GET_VARS']['lang_file'];
  271. // Make sure it exists, if it doesn't reset it.
  272. if (!isset($_SESSION['installer_temp_lang']) || preg_match('~[^\\w_\\-.]~', $_SESSION['installer_temp_lang']) === 1 || !file_exists(dirname(__FILE__) . '/Themes/default/languages/' . $_SESSION['installer_temp_lang']))
  273. {
  274. // Use the first one...
  275. list ($_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
  276. // If we have english and some other language, use the other language. We Americans hate english :P.
  277. if ($_SESSION['installer_temp_lang'] == 'Install.english.php' && count($incontext['detected_languages']) > 1)
  278. list (, $_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
  279. }
  280. // And now include the actual language file itself.
  281. require_once(dirname(__FILE__) . '/Themes/default/languages/' . $_SESSION['installer_temp_lang']);
  282. }
  283. // This handy function loads some settings and the like.
  284. function load_database()
  285. {
  286. global $db_prefix, $db_connection, $db_character_set, $sourcedir, $language;
  287. global $smcFunc, $mbname, $scripturl, $boardurl, $modSettings, $db_type, $db_name, $db_user;
  288. if (empty($sourcedir))
  289. $sourcedir = dirname(__FILE__) . '/Sources';
  290. // Need this to check whether we need the database password.
  291. require(dirname(__FILE__) . '/Settings.php');
  292. if (!defined('SMF'))
  293. define('SMF', 1);
  294. if (empty($smcFunc))
  295. $smcFunc = array();
  296. $modSettings['disableQueryCheck'] = true;
  297. // Connect the database.
  298. if (!$db_connection)
  299. {
  300. require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
  301. if (version_compare(PHP_VERSION, '5', '<'))
  302. require_once($sourcedir . '/Subs-Compat.php');
  303. if (!$db_connection)
  304. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('persist' => $db_persist));
  305. }
  306. }
  307. // This is called upon exiting the installer, for template etc.
  308. function installExit($fallThrough = false)
  309. {
  310. global $incontext, $installurl, $txt;
  311. // Send character set.
  312. header('Content-Type: text/html; charset=' . (isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'ISO-8859-1'));
  313. // We usually dump our templates out.
  314. if (!$fallThrough)
  315. {
  316. // The top install bit.
  317. template_install_above();
  318. // Call the template.
  319. if (isset($incontext['sub_template']))
  320. {
  321. $incontext['form_url'] = $installurl . '?step=' . $incontext['current_step'];
  322. call_user_func('template_' . $incontext['sub_template']);
  323. }
  324. // @todo REMOVE THIS!!
  325. else
  326. {
  327. if (function_exists('doStep' . $_GET['step']))
  328. call_user_func('doStep' . $_GET['step']);
  329. }
  330. // Show the footer.
  331. template_install_below();
  332. }
  333. // Bang - gone!
  334. die();
  335. }
  336. function Welcome()
  337. {
  338. global $incontext, $txt, $databases, $installurl;
  339. $incontext['page_title'] = $txt['install_welcome'];
  340. $incontext['sub_template'] = 'welcome_message';
  341. // Done the submission?
  342. if (isset($_POST['contbutt']))
  343. return true;
  344. // Check the PHP version.
  345. if ((!function_exists('version_compare') || version_compare($GLOBALS['required_php_version'], PHP_VERSION, '>')))
  346. {
  347. $incontext['warning'] = $txt['error_php_too_low'];
  348. }
  349. // See if we think they have already installed it?
  350. if (is_readable(dirname(__FILE__) . '/Settings.php'))
  351. {
  352. $probably_installed = 0;
  353. foreach (file(dirname(__FILE__) . '/Settings.php') as $line)
  354. {
  355. if (preg_match('~^\$db_passwd\s=\s\'([^\']+)\';$~', $line))
  356. $probably_installed++;
  357. if (preg_match('~^\$boardurl\s=\s\'([^\']+)\';~', $line) && !preg_match('~^\$boardurl\s=\s\'http://127\.0\.0\.1/smf\';~', $line))
  358. $probably_installed++;
  359. }
  360. if ($probably_installed == 2)
  361. $incontext['warning'] = $txt['error_already_installed'];
  362. }
  363. // Is some database support even compiled in?
  364. $incontext['supported_databases'] = array();
  365. foreach ($databases as $key => $db)
  366. {
  367. if ($db['supported'])
  368. {
  369. if (!file_exists(dirname(__FILE__) . '/install_' . $GLOBALS['db_script_version'] . '_' . $key . '.sql'))
  370. {
  371. $databases[$key]['supported'] = false;
  372. $notFoundSQLFile = true;
  373. $txt['error_db_script_missing'] = sprintf($txt['error_db_script_missing'], 'install_' . $GLOBALS['db_script_version'] . '_' . $key . '.sql');
  374. }
  375. else
  376. {
  377. $db_type = $key;
  378. $incontext['supported_databases'][] = $db;
  379. }
  380. }
  381. }
  382. if (empty($incontext['supported_databases']))
  383. $error = empty($notFoundSQLFile) ? 'error_db_missing' : 'error_db_script_missing';
  384. // How about session support? Some crazy sysadmin remove it?
  385. elseif (!function_exists('session_start'))
  386. $error = 'error_session_missing';
  387. // Make sure they uploaded all the files.
  388. elseif (!file_exists(dirname(__FILE__) . '/index.php'))
  389. $error = 'error_missing_files';
  390. // Very simple check on the session.save_path for Windows.
  391. // @todo Move this down later if they don't use database-driven sessions?
  392. elseif (@ini_get('session.save_path') == '/tmp' && substr(__FILE__, 1, 2) == ':\\')
  393. $error = 'error_session_save_path';
  394. // Since each of the three messages would look the same, anyway...
  395. if (isset($error))
  396. $incontext['error'] = $txt[$error];
  397. // Mod_security blocks everything that smells funny. Let SMF handle security.
  398. if (!fixModSecurity() && !isset($_GET['overmodsecurity']))
  399. $incontext['error'] = $txt['error_mod_security'] . '<br /><br /><a href="' . $installurl . '?overmodsecurity=true">' . $txt['error_message_click'] . '</a> ' . $txt['error_message_bad_try_again'];
  400. return false;
  401. }
  402. function CheckFilesWritable()
  403. {
  404. global $txt, $incontext;
  405. $incontext['page_title'] = $txt['ftp_checking_writable'];
  406. $incontext['sub_template'] = 'chmod_files';
  407. $writable_files = array(
  408. 'attachments',
  409. 'avatars',
  410. 'cache',
  411. 'Packages',
  412. 'Packages/installed.list',
  413. 'Smileys',
  414. 'Themes',
  415. 'agreement.txt',
  416. 'Settings.php',
  417. 'Settings_bak.php'
  418. );
  419. foreach ($incontext['detected_languages'] as $lang => $temp)
  420. $extra_files[] = 'Themes/default/languages/' . $lang;
  421. // With mod_security installed, we could attempt to fix it with .htaccess.
  422. if (function_exists('apache_get_modules') && in_array('mod_security', apache_get_modules()))
  423. $writable_files[] = file_exists(dirname(__FILE__) . '/.htaccess') ? '.htaccess' : '.';
  424. $failed_files = array();
  425. // On linux, it's easy - just use is_writable!
  426. if (substr(__FILE__, 1, 2) != ':\\')
  427. {
  428. foreach ($writable_files as $file)
  429. {
  430. if (!is_writable(dirname(__FILE__) . '/' . $file))
  431. {
  432. @chmod(dirname(__FILE__) . '/' . $file, 0755);
  433. // Well, 755 hopefully worked... if not, try 777.
  434. if (!is_writable(dirname(__FILE__) . '/' . $file) && !@chmod(dirname(__FILE__) . '/' . $file, 0777))
  435. $failed_files[] = $file;
  436. }
  437. }
  438. foreach ($extra_files as $file)
  439. @chmod(dirname(__FILE__) . (empty($file) ? '' : '/' . $file), 0777);
  440. }
  441. // Windows is trickier. Let's try opening for r+...
  442. else
  443. {
  444. foreach ($writable_files as $file)
  445. {
  446. // Folders can't be opened for write... but the index.php in them can ;)
  447. if (is_dir(dirname(__FILE__) . '/' . $file))
  448. $file .= '/index.php';
  449. // Funny enough, chmod actually does do something on windows - it removes the read only attribute.
  450. @chmod(dirname(__FILE__) . '/' . $file, 0777);
  451. $fp = @fopen(dirname(__FILE__) . '/' . $file, 'r+');
  452. // Hmm, okay, try just for write in that case...
  453. if (!is_resource($fp))
  454. $fp = @fopen(dirname(__FILE__) . '/' . $file, 'w');
  455. if (!is_resource($fp))
  456. $failed_files[] = $file;
  457. @fclose($fp);
  458. }
  459. foreach ($extra_files as $file)
  460. @chmod(dirname(__FILE__) . (empty($file) ? '' : '/' . $file), 0777);
  461. }
  462. $failure = count($failed_files) >= 1;
  463. if (!isset($_SERVER))
  464. return !$failure;
  465. // Put the list into context.
  466. $incontext['failed_files'] = $failed_files;
  467. // It's not going to be possible to use FTP on windows to solve the problem...
  468. if ($failure && substr(__FILE__, 1, 2) == ':\\')
  469. {
  470. $incontext['error'] = $txt['error_windows_chmod'] . '
  471. <ul style="margin: 2.5ex; font-family: monospace;">
  472. <li>' . implode('</li>
  473. <li>', $failed_files) . '</li>
  474. </ul>';
  475. return false;
  476. }
  477. // We're going to have to use... FTP!
  478. elseif ($failure)
  479. {
  480. // Load any session data we might have...
  481. if (!isset($_POST['ftp_username']) && isset($_SESSION['installer_temp_ftp']))
  482. {
  483. $_POST['ftp_server'] = $_SESSION['installer_temp_ftp']['server'];
  484. $_POST['ftp_port'] = $_SESSION['installer_temp_ftp']['port'];
  485. $_POST['ftp_username'] = $_SESSION['installer_temp_ftp']['username'];
  486. $_POST['ftp_password'] = $_SESSION['installer_temp_ftp']['password'];
  487. $_POST['ftp_path'] = $_SESSION['installer_temp_ftp']['path'];
  488. }
  489. $incontext['ftp_errors'] = array();
  490. if (isset($_POST['ftp_username']))
  491. {
  492. $ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
  493. if ($ftp->error === false)
  494. {
  495. // Try it without /home/abc just in case they messed up.
  496. if (!$ftp->chdir($_POST['ftp_path']))
  497. {
  498. $incontext['ftp_errors'][] = $ftp->last_message;
  499. $ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
  500. }
  501. }
  502. }
  503. if (!isset($ftp) || $ftp->error !== false)
  504. {
  505. if (!isset($ftp))
  506. $ftp = new ftp_connection(null);
  507. // Save the error so we can mess with listing...
  508. elseif ($ftp->error !== false && empty($incontext['ftp_errors']) && !empty($ftp->last_message))
  509. $incontext['ftp_errors'][] = $ftp->last_message;
  510. list ($username, $detect_path, $found_path) = $ftp->detect_path(dirname(__FILE__));
  511. if (empty($_POST['ftp_path']) && $found_path)
  512. $_POST['ftp_path'] = $detect_path;
  513. if (!isset($_POST['ftp_username']))
  514. $_POST['ftp_username'] = $username;
  515. // Set the username etc, into context.
  516. $incontext['ftp'] = array(
  517. 'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : 'localhost',
  518. 'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : '21',
  519. 'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : '',
  520. 'path' => isset($_POST['ftp_path']) ? $_POST['ftp_path'] : '/',
  521. 'path_msg' => !empty($found_path) ? $txt['ftp_path_found_info'] : $txt['ftp_path_info'],
  522. );
  523. return false;
  524. }
  525. else
  526. {
  527. $_SESSION['installer_temp_ftp'] = array(
  528. 'server' => $_POST['ftp_server'],
  529. 'port' => $_POST['ftp_port'],
  530. 'username' => $_POST['ftp_username'],
  531. 'password' => $_POST['ftp_password'],
  532. 'path' => $_POST['ftp_path']
  533. );
  534. $failed_files_updated = array();
  535. foreach ($failed_files as $file)
  536. {
  537. if (!is_writable(dirname(__FILE__) . '/' . $file))
  538. $ftp->chmod($file, 0755);
  539. if (!is_writable(dirname(__FILE__) . '/' . $file))
  540. $ftp->chmod($file, 0777);
  541. if (!is_writable(dirname(__FILE__) . '/' . $file))
  542. {
  543. $failed_files_updated[] = $file;
  544. $incontext['ftp_errors'][] = rtrim($ftp->last_message) . ' -> ' . $file . "\n";
  545. }
  546. }
  547. $ftp->close();
  548. // Are there any errors left?
  549. if (count($failed_files_updated) >= 1)
  550. {
  551. // Guess there are...
  552. $incontext['failed_files'] = $failed_files_updated;
  553. // Set the username etc, into context.
  554. $incontext['ftp'] = $_SESSION['installer_temp_ftp'] += array(
  555. 'path_msg' => $txt['ftp_path_info'],
  556. );
  557. return false;
  558. }
  559. }
  560. }
  561. return true;
  562. }
  563. function DatabaseSettings()
  564. {
  565. global $txt, $databases, $incontext, $smcFunc, $sourcedir;
  566. $incontext['sub_template'] = 'database_settings';
  567. $incontext['page_title'] = $txt['db_settings'];
  568. $incontext['continue'] = 1;
  569. // Set up the defaults.
  570. $incontext['db']['server'] = 'localhost';
  571. $incontext['db']['user'] = '';
  572. $incontext['db']['name'] = '';
  573. $incontext['db']['pass'] = '';
  574. $incontext['db']['type'] = '';
  575. $incontext['supported_databases'] = array();
  576. $foundOne = false;
  577. foreach ($databases as $key => $db)
  578. {
  579. // Override with the defaults for this DB if appropriate.
  580. if ($db['supported'])
  581. {
  582. $incontext['supported_databases'][$key] = $db;
  583. if (!$foundOne)
  584. {
  585. if (isset($db['default_host']))
  586. $incontext['db']['server'] = ini_get($db['default_host']) or $incontext['db']['server'] = 'localhost';
  587. if (isset($db['default_user']))
  588. {
  589. $incontext['db']['user'] = ini_get($db['default_user']);
  590. $incontext['db']['name'] = ini_get($db['default_user']);
  591. }
  592. if (isset($db['default_password']))
  593. $incontext['db']['pass'] = ini_get($db['default_password']);
  594. if (isset($db['default_port']))
  595. $db_port = ini_get($db['default_port']);
  596. $incontext['db']['type'] = $key;
  597. $foundOne = true;
  598. }
  599. }
  600. }
  601. // Override for repost.
  602. if (isset($_POST['db_user']))
  603. {
  604. $incontext['db']['user'] = $_POST['db_user'];
  605. $incontext['db']['name'] = $_POST['db_type'] == 'sqlite' && isset($_POST['db_filename']) ? $_POST['db_filename'] : $_POST['db_name'];
  606. $incontext['db']['server'] = $_POST['db_server'];
  607. $incontext['db']['prefix'] = $_POST['db_prefix'];
  608. }
  609. else
  610. {
  611. $incontext['db']['prefix'] = 'smf_';
  612. // Should we use a non standard port?
  613. if (!empty($db_port))
  614. $incontext['db']['server'] .= ':' . $db_port;
  615. }
  616. // Are we submitting?
  617. if (isset($_POST['db_type']))
  618. {
  619. if (isset($_POST['db_filename']))
  620. {
  621. // You better enter enter a database name for SQLite.
  622. if (trim($_POST['db_filename']) == '')
  623. {
  624. $incontext['error'] = $txt['error_db_filename'];
  625. return false;
  626. }
  627. // Duplicate name in the same dir? Can't do that with SQLite. Weird things happen.
  628. if (file_exists($_POST['db_filename'] . (substr($_POST['db_filename'], -3) != '.db' ? '.db' : '')))
  629. {
  630. $incontext['error'] = $txt['error_db_filename_exists'];
  631. return false;
  632. }
  633. }
  634. // What type are they trying?
  635. $db_type = preg_replace('~[^A-Za-z0-9]~', '', $_POST['db_type']);
  636. $db_prefix = $_POST['db_prefix'];
  637. // Validate the prefix.
  638. $valid_prefix = $databases[$db_type]['validate_prefix']($db_prefix);
  639. if ($valid_prefix !== true)
  640. {
  641. $incontext['error'] = $valid_prefix;
  642. return false;
  643. }
  644. // Take care of these variables...
  645. $vars = array(
  646. 'db_type' => $db_type,
  647. 'db_name' => $_POST['db_type'] == 'sqlite' && isset($_POST['db_filename']) ? $_POST['db_filename'] : $_POST['db_name'],
  648. 'db_user' => $_POST['db_user'],
  649. 'db_passwd' => isset($_POST['db_passwd']) ? $_POST['db_passwd'] : '',
  650. 'db_server' => $_POST['db_server'],
  651. 'db_prefix' => $db_prefix,
  652. // The cookiename is special; we want it to be the same if it ever needs to be reinstalled with the same info.
  653. 'cookiename' => 'SMFCookie' . abs(crc32($_POST['db_name'] . preg_replace('~[^A-Za-z0-9_$]~', '', $_POST['db_prefix'])) % 1000),
  654. );
  655. // God I hope it saved!
  656. if (!updateSettingsFile($vars) && substr(__FILE__, 1, 2) == ':\\')
  657. {
  658. $incontext['error'] = $txt['error_windows_chmod'];
  659. return false;
  660. }
  661. // Make sure it works.
  662. require(dirname(__FILE__) . '/Settings.php');
  663. if (empty($sourcedir))
  664. $sourcedir = dirname(__FILE__) . '/Sources';
  665. // Better find the database file!
  666. if (!file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
  667. {
  668. $incontext['error'] = sprintf($txt['error_db_file'], 'Subs-Db-' . $db_type . '.php');
  669. return false;
  670. }
  671. // Now include it for database functions!
  672. define('SMF', 1);
  673. $modSettings['disableQueryCheck'] = true;
  674. if (empty($smcFunc))
  675. $smcFunc = array();
  676. require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
  677. // What - running PHP4? The shame!
  678. if (version_compare(PHP_VERSION, '5', '<'))
  679. require_once($sourcedir . '/Subs-Compat.php');
  680. // Attempt a connection.
  681. $needsDB = !empty($databases[$db_type]['always_has_db']);
  682. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('non_fatal' => true, 'dont_select_db' => !$needsDB));
  683. // No dice? Let's try adding the prefix they specified, just in case they misread the instructions ;)
  684. if ($db_connection == null)
  685. {
  686. $db_error = @$smcFunc['db_error']();
  687. $db_connection = smf_db_initiate($db_server, $db_name, $_POST['db_prefix'] . $db_user, $db_passwd, $db_prefix, array('non_fatal' => true, 'dont_select_db' => !$needsDB));
  688. if ($db_connection != null)
  689. {
  690. $db_user = $_POST['db_prefix'] . $db_user;
  691. updateSettingsFile(array('db_user' => $db_user));
  692. }
  693. }
  694. // Still no connection? Big fat error message :P.
  695. if (!$db_connection)
  696. {
  697. $incontext['error'] = $txt['error_db_connect'] . '<div style="margin: 2.5ex; font-family: monospace;"><strong>' . $db_error . '</strong></div>';
  698. return false;
  699. }
  700. // Do they meet the install requirements?
  701. // @todo Old client, new server?
  702. if (version_compare($databases[$db_type]['version'], preg_replace('~^\D*|\-.+?$~', '', eval($databases[$db_type]['version_check']))) > 0)
  703. {
  704. $incontext['error'] = $txt['error_db_too_low'];
  705. return false;
  706. }
  707. // Let's try that database on for size... assuming we haven't already lost the opportunity.
  708. if ($db_name != '' && !$needsDB)
  709. {
  710. $smcFunc['db_query']('', "
  711. CREATE DATABASE IF NOT EXISTS `$db_name`",
  712. array(
  713. 'security_override' => true,
  714. 'db_error_skip' => true,
  715. ),
  716. $db_connection
  717. );
  718. // Okay, let's try the prefix if it didn't work...
  719. if (!$smcFunc['db_select_db']($db_name, $db_connection) && $db_name != '')
  720. {
  721. $smcFunc['db_query']('', "
  722. CREATE DATABASE IF NOT EXISTS `$_POST[db_prefix]$db_name`",
  723. array(
  724. 'security_override' => true,
  725. 'db_error_skip' => true,
  726. ),
  727. $db_connection
  728. );
  729. if ($smcFunc['db_select_db']($_POST['db_prefix'] . $db_name, $db_connection))
  730. {
  731. $db_name = $_POST['db_prefix'] . $db_name;
  732. updateSettingsFile(array('db_name' => $db_name));
  733. }
  734. }
  735. // Okay, now let's try to connect...
  736. if (!$smcFunc['db_select_db']($db_name, $db_connection))
  737. {
  738. $incontext['error'] = sprintf($txt['error_db_database'], $db_name);
  739. return false;
  740. }
  741. }
  742. return true;
  743. }
  744. return false;
  745. }
  746. // Let's start with basic forum type settings.
  747. function ForumSettings()
  748. {
  749. global $txt, $incontext, $databases, $smcFunc, $db_connection, $db_type;
  750. $incontext['sub_template'] = 'forum_settings';
  751. $incontext['page_title'] = $txt['install_settings'];
  752. // Let's see if we got the database type correct.
  753. if (isset($_POST['db_type'], $databases[$_POST['db_type']]))
  754. $db_type = $_POST['db_type'];
  755. // Else we'd better be able to get the connection.
  756. else
  757. load_database();
  758. $db_type = isset($_POST['db_type']) ? $_POST['db_type'] : $db_type;
  759. // What host and port are we on?
  760. $host = empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
  761. // Now, to put what we've learned together... and add a path.
  762. $incontext['detected_url'] = 'http' . (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 's' : '') . '://' . $host . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
  763. // Check if the database sessions will even work.
  764. $incontext['test_dbsession'] = ini_get('session.auto_start') != 1;
  765. $incontext['utf8_default'] = $databases[$db_type]['utf8_default'];
  766. $incontext['utf8_required'] = $databases[$db_type]['utf8_required'];
  767. $incontext['continue'] = 1;
  768. // Submitting?
  769. if (isset($_POST['boardurl']))
  770. {
  771. if (substr($_POST['boardurl'], -10) == '/index.php')
  772. $_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
  773. elseif (substr($_POST['boardurl'], -1) == '/')
  774. $_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
  775. if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
  776. $_POST['boardurl'] = 'http://' . $_POST['boardurl'];
  777. // Save these variables.
  778. $vars = array(
  779. 'boardurl' => $_POST['boardurl'],
  780. 'boarddir' => addslashes(dirname(__FILE__)),
  781. 'sourcedir' => addslashes(dirname(__FILE__)) . '/Sources',
  782. 'cachedir' => addslashes(dirname(__FILE__)) . '/cache',
  783. 'mbname' => strtr($_POST['mbname'], array('\"' => '"')),
  784. 'language' => substr($_SESSION['installer_temp_lang'], 8, -4),
  785. );
  786. // Must save!
  787. if (!updateSettingsFile($vars) && substr(__FILE__, 1, 2) == ':\\')
  788. {
  789. $incontext['error'] = $txt['error_windows_chmod'];
  790. return false;
  791. }
  792. // Make sure it works.
  793. require(dirname(__FILE__) . '/Settings.php');
  794. // UTF-8 requires a setting to override the language charset.
  795. if ((!empty($databases[$db_type]['utf8_support']) && !empty($databases[$db_type]['utf8_required'])) || (empty($databases[$db_type]['utf8_required']) && !empty($databases[$db_type]['utf8_support']) && isset($_POST['utf8'])))
  796. {
  797. if (!empty($databases[$db_type]['utf8_version_check']) && version_compare($databases[$db_type]['utf8_version'], preg_replace('~\-.+?$~', '', eval($databases[$db_type]['utf8_version_check'])), '>'))
  798. {
  799. $incontext['error'] = sprintf($txt['error_utf8_version'], $databases[$db_type]['utf8_version']);
  800. return false;
  801. }
  802. else
  803. // Set the character set here.
  804. updateSettingsFile(array('db_character_set' => 'utf8'));
  805. }
  806. // Good, skip on.
  807. return true;
  808. }
  809. return false;
  810. }
  811. // Step one: Do the SQL thang.
  812. function DatabasePopulation()
  813. {
  814. global $db_character_set, $txt, $db_connection, $smcFunc, $databases, $modSettings, $db_type, $sourcedir, $db_prefix, $incontext, $db_name, $boardurl;
  815. $incontext['sub_template'] = 'populate_database';
  816. $incontext['page_title'] = $txt['db_populate'];
  817. $incontext['continue'] = 1;
  818. // Already done?
  819. if (isset($_POST['pop_done']))
  820. return true;
  821. // Reload settings.
  822. require(dirname(__FILE__) . '/Settings.php');
  823. load_database();
  824. // Before running any of the queries, let's make sure another version isn't already installed.
  825. $result = $smcFunc['db_query']('', '
  826. SELECT variable, value
  827. FROM {db_prefix}settings',
  828. array(
  829. 'db_error_skip' => true,
  830. )
  831. );
  832. $modSettings = array();
  833. if ($result !== false)
  834. {
  835. while ($row = $smcFunc['db_fetch_assoc']($result))
  836. $modSettings[$row['variable']] = $row['value'];
  837. $smcFunc['db_free_result']($result);
  838. // Do they match? If so, this is just a refresh so charge on!
  839. if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] != $GLOBALS['current_smf_version'])
  840. {
  841. $incontext['error'] = $txt['error_versions_do_not_match'];
  842. return false;
  843. }
  844. }
  845. $modSettings['disableQueryCheck'] = true;
  846. // If doing UTF8, select it. PostgreSQL requires passing it as a string...
  847. if (!empty($db_character_set) && $db_character_set == 'utf8' && !empty($databases[$db_type]['utf8_support']))
  848. $smcFunc['db_query']('', '
  849. SET NAMES {'. ($db_type == 'postgresql' ? 'string' : 'raw') . ':utf8}',
  850. array(
  851. 'db_error_skip' => true,
  852. 'utf8' => 'utf8',
  853. )
  854. );
  855. $replaces = array(
  856. '{$db_prefix}' => $db_prefix,
  857. '{$boarddir}' => $smcFunc['db_escape_string'](dirname(__FILE__)),
  858. '{$boardurl}' => $boardurl,
  859. '{$enableCompressedOutput}' => isset($_POST['compress']) ? '1' : '0',
  860. '{$databaseSession_enable}' => isset($_POST['dbsession']) ? '1' : '0',
  861. '{$smf_version}' => $GLOBALS['current_smf_version'],
  862. '{$current_time}' => time(),
  863. '{$sched_task_offset}' => 82800 + mt_rand(0, 86399),
  864. );
  865. foreach ($txt as $key => $value)
  866. {
  867. if (substr($key, 0, 8) == 'default_')
  868. $replaces['{$' . $key . '}'] = $smcFunc['db_escape_string']($value);
  869. }
  870. $replaces['{$default_reserved_names}'] = strtr($replaces['{$default_reserved_names}'], array('\\\\n' => '\\n'));
  871. // If the UTF-8 setting was enabled, add it to the table definitions.
  872. if (empty($databases[$db_type]['utf8_required']) && isset($_POST['utf8']) && !empty($databases[$db_type]['utf8_support']))
  873. $replaces[') ENGINE=MyISAM;'] = ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;';
  874. // Read in the SQL. Turn this on and that off... internationalize... etc.
  875. $sql_lines = explode("\n", strtr(implode(' ', file(dirname(__FILE__) . '/install_' . $GLOBALS['db_script_version'] . '_' . $db_type . '.sql')), $replaces));
  876. // Execute the SQL.
  877. $current_statement = '';
  878. $exists = array();
  879. $incontext['failures'] = array();
  880. $incontext['sql_results'] = array(
  881. 'tables' => 0,
  882. 'inserts' => 0,
  883. 'table_dups' => 0,
  884. 'insert_dups' => 0,
  885. );
  886. foreach ($sql_lines as $count => $line)
  887. {
  888. // No comments allowed!
  889. if (substr(trim($line), 0, 1) != '#')
  890. $current_statement .= "\n" . rtrim($line);
  891. // Is this the end of the query string?
  892. if (empty($current_statement) || (preg_match('~;[\s]*$~s', $line) == 0 && $count != count($sql_lines)))
  893. continue;
  894. // Does this table already exist? If so, don't insert more data into it!
  895. if (preg_match('~^\s*INSERT INTO ([^\s\n\r]+?)~', $current_statement, $match) != 0 && in_array($match[1], $exists))
  896. {
  897. $incontext['sql_results']['insert_dups']++;
  898. $current_statement = '';
  899. continue;
  900. }
  901. if ($smcFunc['db_query']('', $current_statement, array('security_override' => true, 'db_error_skip' => true), $db_connection) === false)
  902. {
  903. // Error 1050: Table already exists!
  904. // @todo Needs to be made better!
  905. if (($db_type != 'mysql' || mysql_errno($db_connection) === 1050) && preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
  906. {
  907. $exists[] = $match[1];
  908. $incontext['sql_results']['table_dups']++;
  909. }
  910. // Don't error on duplicate indexes (or duplicate operators in PostgreSQL.)
  911. elseif (!preg_match('~^\s*CREATE( UNIQUE)? INDEX ([^\n\r]+?)~', $current_statement, $match) && !($db_type == 'postgresql' && preg_match('~^\s*CREATE OPERATOR (^\n\r]+?)~', $current_statement, $match)))
  912. {
  913. $incontext['failures'][$count] = $smcFunc['db_error']();
  914. }
  915. }
  916. else
  917. {
  918. if (preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
  919. $incontext['sql_results']['tables']++;
  920. else
  921. {
  922. preg_match_all('~\)[,;]~', $current_statement, $matches);
  923. if (!empty($matches[0]))
  924. $incontext['sql_results']['inserts'] += count($matches[0]);
  925. else
  926. $incontext['sql_results']['inserts']++;
  927. }
  928. }
  929. $current_statement = '';
  930. }
  931. // Sort out the context for the SQL.
  932. foreach ($incontext['sql_results'] as $key => $number)
  933. {
  934. if ($number == 0)
  935. unset($incontext['sql_results'][$key]);
  936. else
  937. $incontext['sql_results'][$key] = sprintf($txt['db_populate_' . $key], $number);
  938. }
  939. // Make sure UTF will be used globally.
  940. if ((!empty($databases[$db_type]['utf8_support']) && !empty($databases[$db_type]['utf8_required'])) || (empty($databases[$db_type]['utf8_required']) && !empty($databases[$db_type]['utf8_support']) && isset($_POST['utf8'])))
  941. $smcFunc['db_insert']('replace',
  942. $db_prefix . 'settings',
  943. array(
  944. 'variable' => 'string-255', 'value' => 'string-65534',
  945. ),
  946. array(
  947. 'global_character_set', 'UTF-8',
  948. ),
  949. array('variable')
  950. );
  951. // Maybe we can auto-detect better cookie settings?
  952. preg_match('~^http[s]?://([^\.]+?)([^/]*?)(/.*)?$~', $boardurl, $matches);
  953. if (!empty($matches))
  954. {
  955. // Default = both off.
  956. $localCookies = false;
  957. $globalCookies = false;
  958. // Okay... let's see. Using a subdomain other than www.? (not a perfect check.)
  959. if ($matches[2] != '' && (strpos(substr($matches[2], 1), '.') === false || in_array($matches[1], array('forum', 'board', 'community', 'forums', 'support', 'chat', 'help', 'talk', 'boards', 'www'))))
  960. $globalCookies = true;
  961. // If there's a / in the middle of the path, or it starts with ~... we want local.
  962. if (isset($matches[3]) && strlen($matches[3]) > 3 && (substr($matches[3], 0, 2) == '/~' || strpos(substr($matches[3], 1), '/') !== false))
  963. $localCookies = true;
  964. if ($globalCookies)
  965. $rows[] = array('globalCookies', '1');
  966. if ($localCookies)
  967. $rows[] = array('localCookies', '1');
  968. if (!empty($rows))
  969. {
  970. $smcFunc['db_insert']('replace',
  971. $db_prefix . 'settings',
  972. array('variable' => 'string-255', 'value' => 'string-65534'),
  973. $rows,
  974. array('variable')
  975. );
  976. }
  977. }
  978. // Are we allowing stat collection?
  979. if (isset($_POST['stats']) && strpos($_POST['boardurl'], 'http://localhost') !== 0)
  980. {
  981. // Attempt to register the site etc.
  982. $fp = @fsockopen("www.simplemachines.org", 80, $errno, $errstr);
  983. if ($fp)
  984. {
  985. $out = "GET /smf/stats/register_stats.php?site=" . base64_encode($_POST['boardurl']) . " HTTP/1.1\r\n";
  986. $out .= "Host: www.simplemachines.org\r\n";
  987. $out .= "Connection: Close\r\n\r\n";
  988. fwrite($fp, $out);
  989. $return_data = '';
  990. while (!feof($fp))
  991. $return_data .= fgets($fp, 128);
  992. fclose($fp);
  993. // Get the unique site ID.
  994. preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
  995. if (!empty($ID[1]))
  996. $smcFunc['db_insert']('',
  997. $db_prefix . 'settings',
  998. array(
  999. 'variable' => 'string-255', 'value' => 'string-65534',
  1000. ),
  1001. array(
  1002. 'allow_sm_stats', $ID[1],
  1003. ),
  1004. array('variable')
  1005. );
  1006. }
  1007. }
  1008. // As of PHP 5.1, setting a timezone is required.
  1009. if (!isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
  1010. {
  1011. $server_offset = mktime(0, 0, 0, 1, 1, 1970);
  1012. $timezone_id = 'Etc/GMT' . ($server_offset > 0 ? '+' : '') . ($server_offset / 3600);
  1013. if (date_default_timezone_set($timezone_id))
  1014. $smcFunc['db_insert']('',
  1015. $db_prefix . 'settings',
  1016. array(
  1017. 'variable' => 'string-255', 'value' => 'string-65534',
  1018. ),
  1019. array(
  1020. 'default_timezone', $timezone_id,
  1021. ),
  1022. array('variable')
  1023. );
  1024. }
  1025. // Let's optimize those new tables.
  1026. db_extend();
  1027. $tables = $smcFunc['db_list_tables']($db_name, $db_prefix . '%');
  1028. foreach ($tables as $table)
  1029. {
  1030. $smcFunc['db_optimize_table']($table) != -1 or $db_messed = true;
  1031. // Optimizing one sqlite table, optimizes them all
  1032. if($db_type == 'sqlite')
  1033. break;
  1034. if (!empty($db_messed))
  1035. {
  1036. $incontext['failures'][-1] = $smcFunc['db_error']();
  1037. break;
  1038. }
  1039. }
  1040. // Check for the ALTER privilege.
  1041. if (!empty($databases[$db_type]['alter_support']) && $smcFunc['db_query']('', "ALTER TABLE {$db_prefix}boards ORDER BY id_board", array('security_override' => true, 'db_error_skip' => true)) === false)
  1042. {
  1043. $incontext['error'] = $txt['error_db_alter_priv'];
  1044. return false;
  1045. }
  1046. if (!empty($exists))
  1047. {
  1048. $incontext['page_title'] = $txt['user_refresh_install'];
  1049. $incontext['was_refresh'] = true;
  1050. }
  1051. return false;
  1052. }
  1053. // Ask for the administrator login information.
  1054. function AdminAccount()
  1055. {
  1056. global $txt, $db_type, $db_connection, $databases, $smcFunc, $incontext, $db_prefix, $db_passwd, $sourcedir;
  1057. $incontext['sub_template'] = 'admin_account';
  1058. $incontext['page_title'] = $txt['user_settings'];
  1059. $incontext['continue'] = 1;
  1060. // Skipping?
  1061. if (!empty($_POST['skip']))
  1062. return true;
  1063. // Need this to check whether we need the database password.
  1064. require(dirname(__FILE__) . '/Settings.php');
  1065. load_database();
  1066. // Define the sha1 function, if it doesn't exist.
  1067. if (!function_exists('sha1') || version_compare(PHP_VERSION, '5', '<'))
  1068. require_once($sourcedir . '/Subs-Compat.php');
  1069. if (!isset($_POST['username']))
  1070. $_POST['username'] = '';
  1071. if (!isset($_POST['email']))
  1072. $_POST['email'] = '';
  1073. $incontext['username'] = htmlspecialchars(stripslashes($_POST['username']));
  1074. $incontext['email'] = htmlspecialchars(stripslashes($_POST['email']));
  1075. $incontext['require_db_confirm'] = empty($db_type) || $db_type != 'sqlite';
  1076. // Only allow skipping if we think they already have an account setup.
  1077. $request = $smcFunc['db_query']('', '
  1078. SELECT id_member
  1079. FROM {db_prefix}members
  1080. WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
  1081. LIMIT 1',
  1082. array(
  1083. 'db_error_skip' => true,
  1084. 'admin_group' => 1,
  1085. )
  1086. );
  1087. if ($smcFunc['db_num_rows']($request) != 0)
  1088. $incontext['skip'] = 1;
  1089. $smcFunc['db_free_result']($request);
  1090. // Trying to create an account?
  1091. if (isset($_POST['password1']) && !empty($_POST['contbutt']))
  1092. {
  1093. // Wrong password?
  1094. if ($incontext['require_db_confirm'] && $_POST['password3'] != $db_passwd)
  1095. {
  1096. $incontext['error'] = $txt['error_db_connect'];
  1097. return false;
  1098. }
  1099. // Not matching passwords?
  1100. if ($_POST['password1'] != $_POST['password2'])
  1101. {
  1102. $incontext['error'] = $txt['error_user_settings_again_match'];
  1103. return false;
  1104. }
  1105. // No password?
  1106. if (strlen($_POST['password1']) < 4)
  1107. {
  1108. $incontext['error'] = $txt['error_user_settings_no_password'];
  1109. return false;
  1110. }
  1111. if (!file_exists($sourcedir . '/Subs.php'))
  1112. {
  1113. $incontext['error'] = $txt['error_subs_missing'];
  1114. return false;
  1115. }
  1116. // Update the main contact email?
  1117. if (!empty($_POST['email']) && (empty($webmaster_email) || $webmaster_email == 'noreply@myserver.com'))
  1118. updateSettingsFile(array('webmaster_email' => $_POST['email']));
  1119. // Work out whether we're going to have dodgy characters and remove them.
  1120. $invalid_characters = preg_match('~[<>&"\'=\\\]~', $_POST['username']) != 0;
  1121. $_POST['username'] = preg_replace('~[<>&"\'=\\\]~', '', $_POST['username']);
  1122. $result = $smcFunc['db_query']('', '
  1123. SELECT id_member, password_salt
  1124. FROM {db_prefix}members
  1125. WHERE member_name = {string:username} OR email_address = {string:email}
  1126. LIMIT 1',
  1127. array(
  1128. 'username' => stripslashes($_POST['username']),
  1129. 'email' => stripslashes($_POST['email']),
  1130. 'db_error_skip' => true,
  1131. )
  1132. );
  1133. if ($smcFunc['db_num_rows']($result) != 0)
  1134. {
  1135. list ($incontext['member_id'], $incontext['member_salt']) = $smcFunc['db_fetch_row']($result);
  1136. $smcFunc['db_free_result']($result);
  1137. $incontext['account_existed'] = $txt['error_user_settings_taken'];
  1138. }
  1139. elseif ($_POST['username'] == '' || strlen($_POST['username']) > 25)
  1140. {
  1141. // Try the previous step again.
  1142. $incontext['error'] = $_POST['username'] == '' ? $txt['error_username_left_empty'] : $txt['error_username_too_long'];
  1143. return false;
  1144. }
  1145. elseif ($invalid_characters || $_POST['username'] == '_' || $_POST['username'] == '|' || strpos($_POST['username'], '[code') !== false || strpos($_POST['username'], '[/code') !== false)
  1146. {
  1147. // Try the previous step again.
  1148. $incontext['error'] = $txt['error_invalid_characters_username'];
  1149. return false;
  1150. }
  1151. elseif (empty($_POST['email']) || preg_match('~^[0-9A-Za-z=_+\-/][0-9A-Za-z=_\'+\-/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$~', stripslashes($_POST['email'])) === 0 || strlen(stripslashes($_POST['email'])) > 255)
  1152. {
  1153. // One step back, this time fill out a proper email address.
  1154. $incontext['error'] = sprintf($txt['error_valid_email_needed'], $_POST['username']);
  1155. return false;
  1156. }
  1157. elseif ($_POST['username'] != '')
  1158. {
  1159. $incontext['member_salt'] = substr(md5(mt_rand()), 0, 4);
  1160. // Format the username properly.
  1161. $_POST['username'] = preg_replace('~[\t\n\r\x0B\0\xA0]+~', ' ', $_POST['username']);
  1162. $ip = isset($_SERVER['REMOTE_ADDR']) ? substr($_SERVER['REMOTE_ADDR'], 0, 255) : '';
  1163. $request = $smcFunc['db_insert']('',
  1164. $db_prefix . 'members',
  1165. array(
  1166. 'member_name' => 'string-25', 'real_name' => 'string-25', 'passwd' => 'string', 'email_address' => 'string',
  1167. 'id_group' => 'int', 'posts' => 'int', 'date_registered' => 'int', 'hide_email' => 'int',
  1168. 'password_salt' => 'string', 'lngfile' => 'string', 'personal_text' => 'string', 'avatar' => 'string',
  1169. 'member_ip' => 'string', 'member_ip2' => 'string', 'buddy_list' => 'string', 'pm_ignore_list' => 'string',
  1170. 'message_labels' => 'string', 'website_title' => 'string', 'website_url' => 'string', 'location' => 'string',
  1171. 'aim' => 'string', 'icq' => 'string', 'msn' => 'string', 'signature' => 'string', 'usertitle' => 'string', 'secret_question' => 'string',
  1172. 'additional_groups' => 'string', 'ignore_boards' => 'string', 'openid_uri' => 'string',
  1173. ),
  1174. array(
  1175. stripslashes($_POST['username']), stripslashes($_POST['username']), sha1(strtolower(stripslashes($_POST['username'])) . stripslashes($_POST['password1'])), stripslashes($_POST['email']),
  1176. 1, 0, time(), 0,
  1177. $incontext['member_salt'], '', '', '',
  1178. $ip, $ip, '', '',
  1179. '', '', '', '',
  1180. '', '', '', '', '', '',
  1181. '', '', '',
  1182. ),
  1183. array('id_member')
  1184. );
  1185. // Awww, crud!
  1186. if ($request === false)
  1187. {
  1188. $incontext['error'] = $txt['error_user_settings_query'] . '<br />
  1189. <div style="margin: 2ex;">' . nl2br(htmlspecialchars($smcFunc['db_error']($db_connection))) . '</div>';
  1190. return false;
  1191. }
  1192. $incontext['member_id'] = $smcFunc['db_insert_id']("{$db_prefix}members", 'id_member');
  1193. }
  1194. // If we're here we're good.
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. // Final step, clean up and a complete message!
  1200. function DeleteInstall()
  1201. {
  1202. global $txt, $db_prefix, $db_connection, $HTTP_SESSION_VARS, $cookiename, $incontext;
  1203. global $smcFunc, $db_character_set, $mbname, $context, $scripturl, $boardurl;
  1204. global $current_smf_version, $databases, $sourcedir, $forum_version, $modSettings, $user_info, $language, $db_type;
  1205. $incontext['page_title'] = $txt['congratulations'];
  1206. $incontext['sub_template'] = 'delete_install';
  1207. $incontext['continue'] = 0;
  1208. require(dirname(__FILE__) . '/Settings.php');
  1209. load_database();
  1210. chdir(dirname(__FILE__));
  1211. require_once($sourcedir . '/Errors.php');
  1212. require_once($sourcedir . '/Logging.php');
  1213. require_once($sourcedir . '/Subs.php');
  1214. require_once($sourcedir . '/Load.php');
  1215. require_once($sourcedir . '/Security.php');
  1216. require_once($sourcedir . '/Subs-Auth.php');
  1217. // Bring a warning over.
  1218. if (!empty($incontext['account_existed']))
  1219. $incontext['warning'] = $incontext['account_existed'];
  1220. if (!empty($db_character_set) && !empty($databases[$db_type]['utf8_support']))
  1221. $smcFunc['db_query']('', '
  1222. SET NAMES {raw:db_character_set}',
  1223. array(
  1224. 'db_character_set' => $db_character_set,
  1225. 'db_error_skip' => true,
  1226. )
  1227. );
  1228. // As track stats is by default enabled let's add some activity.
  1229. $smcFunc['db_insert']('ignore',
  1230. '{db_prefix}log_activity',
  1231. array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'),
  1232. array(strftime('%Y-%m-%d', time()), 1, 1, (!empty($incontext['member_id']) ? 1 : 0)),
  1233. array('date')
  1234. );
  1235. // We're going to want our lovely $modSettings now.
  1236. $request = $smcFunc['db_query']('', '
  1237. SELECT variable, value
  1238. FROM {db_prefix}settings',
  1239. array(
  1240. 'db_error_skip' => true,
  1241. )
  1242. );
  1243. // Only proceed if we can load the data.
  1244. if ($request)
  1245. {
  1246. while ($row = $smcFunc['db_fetch_row']($request))
  1247. $modSettings[$row[0]] = $row[1];
  1248. $smcFunc['db_free_result']($request);
  1249. }
  1250. // Automatically log them in ;)
  1251. if (isset($incontext['member_id']) && isset($incontext['member_salt']))
  1252. setLoginCookie(3153600 * 60, $incontext['member_id'], sha1(sha1(strtolower($_POST['username']) . $_POST['password1']) . $incontext['member_salt']));
  1253. $result = $smcFunc['db_query']('', '
  1254. SELECT value
  1255. FROM {db_prefix}settings
  1256. WHERE variable = {string:db_sessions}',
  1257. array(
  1258. 'db_sessions' => 'databaseSession_enable',
  1259. 'db_error_skip' => true,
  1260. )
  1261. );
  1262. if ($smcFunc['db_num_rows']($result) != 0)
  1263. list ($db_sessions) = $smcFunc['db_fetch_row']($result);
  1264. $smcFunc['db_free_result']($result);
  1265. if (empty($db_sessions))
  1266. $_SESSION['admin_time'] = time();
  1267. else
  1268. {
  1269. $_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211);
  1270. $smcFunc['db_insert']('replace',
  1271. '{db_prefix}sessions',
  1272. array(
  1273. 'session_id' => 'string', 'last_update' => 'int', 'data' => 'string',
  1274. ),
  1275. array(
  1276. session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';',
  1277. ),
  1278. array('session_id')
  1279. );
  1280. }
  1281. updateStats('member');
  1282. updateStats('message');
  1283. updateStats('topic');
  1284. // This function is needed to do the updat…

Large files files are truncated, but you can click here to view the full file