function smf_db_backup_table($table, $backup_table)
{
    global $smcFunc, $db_prefix;
    $table = str_replace('{db_prefix}', $db_prefix, $table);
    // Do we need to drop it first?
    $tables = smf_db_list_tables(false, $backup_table);
    if (!empty($tables)) {
        $smcFunc['db_query']('', '
			DROP TABLE {raw:backup_table}', array('backup_table' => $backup_table));
    }
    //!!! Should we create backups of sequences as well?
    $smcFunc['db_query']('', '
		CREATE TABLE {raw:backup_table}
		(
			LIKE {raw:table}
			INCLUDING DEFAULTS
		)', array('backup_table' => $backup_table, 'table' => $table));
    $smcFunc['db_query']('', '
		INSERT INTO {raw:backup_table}
		SELECT * FROM {raw:table}', array('backup_table' => $backup_table, 'table' => $table));
}
Exemple #2
0
function DatabasePopulation()
{
    global $txt, $db_connection, $databases, $modSettings, $db_type, $db_prefix, $incontext, $db_name, $boardurl;
    $incontext['sub_template'] = 'populate_database';
    $incontext['page_title'] = $txt['db_populate'];
    $incontext['continue'] = 1;
    // Already done?
    if (isset($_POST['pop_done'])) {
        return true;
    }
    // Reload settings.
    require dirname(__FILE__) . '/Settings.php';
    load_database();
    // Before running any of the queries, let's make sure another version isn't already installed.
    $result = smf_db_query('
		SELECT variable, value
		FROM {db_prefix}settings', array('db_error_skip' => true));
    $modSettings = array();
    if ($result !== false) {
        while ($row = mysql_fetch_assoc($result)) {
            $modSettings[$row['variable']] = $row['value'];
        }
        mysql_free_result($result);
        // Do they match?  If so, this is just a refresh so charge on!
        if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] != $GLOBALS['current_smf_version']) {
            $incontext['error'] = $txt['error_versions_do_not_match'];
            return false;
        }
    }
    smf_db_query('
		SET NAMES utf8', array());
    $boardurl = $_POST['boardurl'];
    echo $boardurl;
    $replaces = array('{$db_prefix}' => $db_prefix, '{$boarddir}' => mysql_real_escape_string(dirname(__FILE__)), '{$boardurl}' => $boardurl, '{$enableCompressedOutput}' => isset($_POST['compress']) ? '1' : '0', '{$databaseSession_enable}' => isset($_POST['dbsession']) ? '1' : '0', '{$smf_version}' => $GLOBALS['current_smf_version'], '{$current_time}' => time(), '{$sched_task_offset}' => 82800 + mt_rand(0, 86399));
    foreach ($txt as $key => $value) {
        if (substr($key, 0, 8) == 'default_') {
            $replaces['{$' . $key . '}'] = mysql_real_escape_string($value);
        }
    }
    $replaces['{$default_reserved_names}'] = strtr($replaces['{$default_reserved_names}'], array('\\\\n' => '\\n'));
    $replaces[') ENGINE=MyISAM;'] = ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;';
    // Read in the SQL.  Turn this on and that off... internationalize... etc.
    $sql_lines = explode("\n", strtr(implode(' ', file(dirname(__FILE__) . '/install_' . $GLOBALS['db_script_version'] . '_' . $db_type . '.sql')), $replaces));
    // Execute the SQL.
    $current_statement = '';
    $exists = array();
    $incontext['failures'] = array();
    $incontext['sql_results'] = array('tables' => 0, 'inserts' => 0, 'table_dups' => 0, 'insert_dups' => 0);
    foreach ($sql_lines as $count => $line) {
        // No comments allowed!
        if (substr(trim($line), 0, 1) != '#') {
            $current_statement .= "\n" . rtrim($line);
        }
        // Is this the end of the query string?
        if (empty($current_statement) || preg_match('~;[\\s]*$~s', $line) == 0 && $count != count($sql_lines)) {
            continue;
        }
        // Does this table already exist?  If so, don't insert more data into it!
        if (preg_match('~^\\s*INSERT INTO ([^\\s\\n\\r]+?)~', $current_statement, $match) != 0 && in_array($match[1], $exists)) {
            $incontext['sql_results']['insert_dups']++;
            $current_statement = '';
            continue;
        }
        if (smf_db_query($current_statement, array('security_override' => true, 'db_error_skip' => true), $db_connection) === false) {
            // Error 1050: Table already exists!
            //!!! Needs to be made better!
            if (($db_type != 'mysql' || mysql_errno($db_connection) === 1050) && preg_match('~^\\s*CREATE TABLE ([^\\s\\n\\r]+?)~', $current_statement, $match) == 1) {
                $exists[] = $match[1];
                $incontext['sql_results']['table_dups']++;
            } 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))) {
                $incontext['failures'][$count] = mysql_error($db_connection);
            }
        } else {
            if (preg_match('~^\\s*CREATE TABLE ([^\\s\\n\\r]+?)~', $current_statement, $match) == 1) {
                $incontext['sql_results']['tables']++;
            } else {
                preg_match_all('~\\)[,;]~', $current_statement, $matches);
                if (!empty($matches[0])) {
                    $incontext['sql_results']['inserts'] += count($matches[0]);
                } else {
                    $incontext['sql_results']['inserts']++;
                }
            }
        }
        $current_statement = '';
    }
    // Sort out the context for the SQL.
    foreach ($incontext['sql_results'] as $key => $number) {
        if ($number == 0) {
            unset($incontext['sql_results'][$key]);
        } else {
            $incontext['sql_results'][$key] = sprintf($txt['db_populate_' . $key], $number);
        }
    }
    // Make sure UTF will be used globally.
    if (isset($_POST['utf8']) && !empty($databases[$db_type]['utf8_support'])) {
        smf_db_insert('replace', $db_prefix . 'settings', array('variable' => 'string-255', 'value' => 'string-65534'), array('global_character_set', 'UTF-8'), array('variable'));
    }
    // Maybe we can auto-detect better cookie settings?
    preg_match('~^http[s]?://([^\\.]+?)([^/]*?)(/.*)?$~', $boardurl, $matches);
    if (!empty($matches)) {
        // Default = both off.
        $localCookies = false;
        $globalCookies = false;
        // Okay... let's see.  Using a subdomain other than www.? (not a perfect check.)
        if ($matches[2] != '' && (strpos(substr($matches[2], 1), '.') === false || in_array($matches[1], array('forum', 'board', 'community', 'forums', 'support', 'chat', 'help', 'talk', 'boards', 'www')))) {
            $globalCookies = true;
        }
        // If there's a / in the middle of the path, or it starts with ~... we want local.
        if (isset($matches[3]) && strlen($matches[3]) > 3 && (substr($matches[3], 0, 2) == '/~' || strpos(substr($matches[3], 1), '/') !== false)) {
            $localCookies = true;
        }
        $rows = array();
        if ($globalCookies) {
            $rows[] = array('globalCookies', '1');
        }
        if ($localCookies) {
            $rows[] = array('localCookies', '1');
        }
        if (!empty($rows)) {
            smf_db_insert('replace', $db_prefix . 'settings', array('variable' => 'string-255', 'value' => 'string-65534'), $rows, array('variable'));
        }
    }
    // As of PHP 5.1, setting a timezone is required.
    if (!isset($modSettings['default_timezone'])) {
        $server_offset = mktime(0, 0, 0, 1, 1, 1970);
        $timezone_id = 'Etc/GMT' . ($server_offset > 0 ? '+' : '') . $server_offset / 3600;
        if (date_default_timezone_set($timezone_id)) {
            smf_db_insert('', $db_prefix . 'settings', array('variable' => 'string-255', 'value' => 'string-65534'), array('default_timezone', $timezone_id), array('variable'));
        }
    }
    // Let's optimize those new tables.
    db_extend();
    $tables = smf_db_list_tables($db_name, $db_prefix . '%');
    foreach ($tables as $table) {
        smf_db_optimize_table($table) != -1 or $db_messed = true;
        // Optimizing one sqlite table, optimizes them all
        if ($db_type == 'sqlite') {
            break;
        }
        if (!empty($db_messed)) {
            $incontext['failures'][-1] = mysql_error($db_connection);
            break;
        }
    }
    // Check for the ALTER privilege.
    if (!empty($databases[$db_type]['alter_support']) && smf_db_query("ALTER TABLE {$db_prefix}boards ORDER BY id_board", array('security_override' => true, 'db_error_skip' => true)) === false) {
        $incontext['error'] = $txt['error_db_alter_priv'];
        return false;
    }
    if (!empty($exists)) {
        $incontext['page_title'] = $txt['user_refresh_install'];
        $incontext['was_refresh'] = true;
    }
    return false;
}
Exemple #3
0
function scheduled_auto_optimize()
{
    global $modSettings, $db_prefix, $db_type;
    // By default do it now!
    $delay = false;
    // As a kind of hack, if the server load is too great delay, but only by a bit!
    if (!empty($modSettings['load_average']) && !empty($modSettings['loadavg_auto_opt']) && $modSettings['load_average'] >= $modSettings['loadavg_auto_opt']) {
        $delay = true;
    }
    // Otherwise are we restricting the number of people online for this?
    if (!empty($modSettings['autoOptMaxOnline'])) {
        $request = smf_db_query('
			SELECT COUNT(*)
			FROM {db_prefix}log_online', array());
        list($dont_do_it) = mysql_fetch_row($request);
        mysql_free_result($request);
        if ($dont_do_it > $modSettings['autoOptMaxOnline']) {
            $delay = true;
        }
    }
    // If we are gonna delay, do so now!
    if ($delay) {
        return false;
    }
    db_extend();
    // Get all the tables.
    $tables = smf_db_list_tables(false, $db_prefix . '%');
    // Actually do the optimisation.
    if ($db_type == 'sqlite') {
        smf_db_optimize_table($table[0]);
    } else {
        foreach ($tables as $table) {
            smf_db_optimize_table($table);
        }
    }
    // Return for the log...
    return true;
}
Exemple #4
0
function BackupDatabase()
{
    global $upcontext, $db_prefix, $command_line, $is_debug, $support_js, $file_steps, $smcFunc;
    $upcontext['sub_template'] = isset($_GET['xml']) ? 'backup_xml' : 'backup_database';
    $upcontext['page_title'] = 'Backup Database';
    // Done it already - js wise?
    if (!empty($_POST['backup_done'])) {
        return true;
    }
    // Some useful stuff here.
    db_extend();
    // Get all the table names.
    $filter = str_replace('_', '\\_', preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) != 0 ? $match[2] : $db_prefix) . '%';
    $db = preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) != 0 ? strtr($match[1], array('`' => '')) : false;
    $tables = smf_db_list_tables($db, $filter);
    $table_names = array();
    foreach ($tables as $table) {
        if (substr($table, 0, 7) !== 'backup_') {
            $table_names[] = $table;
        }
    }
    $upcontext['table_count'] = count($table_names);
    $upcontext['cur_table_num'] = $_GET['substep'];
    $upcontext['cur_table_name'] = str_replace($db_prefix, '', isset($table_names[$_GET['substep']]) ? $table_names[$_GET['substep']] : $table_names[0]);
    $upcontext['step_progress'] = (int) ($upcontext['cur_table_num'] / $upcontext['table_count'] * 100);
    // For non-java auto submit...
    $file_steps = $upcontext['table_count'];
    // What ones have we already done?
    foreach ($table_names as $id => $table) {
        if ($id < $_GET['substep']) {
            $upcontext['previous_tables'][] = $table;
        }
    }
    if ($command_line) {
        echo 'Backing Up Tables.';
    }
    // If we don't support javascript we backup here.
    if (!$support_js || isset($_GET['xml'])) {
        // Backup each table!
        for ($substep = $_GET['substep'], $n = count($table_names); $substep < $n; $substep++) {
            $upcontext['cur_table_name'] = str_replace($db_prefix, '', isset($table_names[$substep + 1]) ? $table_names[$substep + 1] : $table_names[$substep]);
            $upcontext['cur_table_num'] = $substep + 1;
            $upcontext['step_progress'] = (int) ($upcontext['cur_table_num'] / $upcontext['table_count'] * 100);
            // Do we need to pause?
            nextSubstep($substep);
            backupTable($table_names[$substep]);
            // If this is XML to keep it nice for the user do one table at a time anyway!
            if (isset($_GET['xml'])) {
                return upgradeExit();
            }
        }
        if ($is_debug && $command_line) {
            echo "\n" . ' Successful.\'' . "\n";
            flush();
        }
        $upcontext['step_progress'] = 100;
        $_GET['substep'] = 0;
        // Make sure we move on!
        return true;
    }
    // Either way next place to post will be database changes!
    $_GET['substep'] = 0;
    return false;
}
Exemple #5
0
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
{
    global $reservedTables, $db_prefix;
    // After stripping away the database name, this is what's left.
    $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
    // Get some aliases.
    $full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
    $table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
    // God no - dropping one of these = bad.
    if (in_array(strtolower($table_name), $reservedTables)) {
        return false;
    }
    // Does it exist?
    if (in_array($full_table_name, smf_db_list_tables())) {
        $query = 'DROP TABLE ' . $table_name;
        smf_db_query($query, array('security_override' => true));
        return true;
    }
    // Otherwise do 'nout.
    return false;
}
Exemple #6
0
function CreateMessageIndex()
{
    global $modSettings, $context, $db_prefix, $txt;
    // Scotty, we need more time...
    @set_time_limit(600);
    if (function_exists('apache_reset_timeout')) {
        @apache_reset_timeout();
    }
    $context[$context['admin_menu_name']]['current_subsection'] = 'method';
    $context['page_title'] = $txt['search_index_custom'];
    $messages_per_batch = 50;
    $index_properties = array(2 => array('column_definition' => 'small', 'step_size' => 1000000), 4 => array('column_definition' => 'medium', 'step_size' => 1000000, 'max_size' => 16777215), 5 => array('column_definition' => 'large', 'step_size' => 100000000, 'max_size' => 2000000000));
    if (isset($_REQUEST['resume']) && !empty($modSettings['search_custom_index_resume'])) {
        $context['index_settings'] = unserialize($modSettings['search_custom_index_resume']);
        $context['start'] = (int) $context['index_settings']['resume_at'];
        unset($context['index_settings']['resume_at']);
        $context['step'] = 1;
    } else {
        $context['index_settings'] = array('bytes_per_word' => isset($_REQUEST['bytes_per_word']) && isset($index_properties[$_REQUEST['bytes_per_word']]) ? (int) $_REQUEST['bytes_per_word'] : 2);
        $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
        $context['step'] = isset($_REQUEST['step']) ? (int) $_REQUEST['step'] : 0;
    }
    if ($context['step'] !== 0) {
        checkSession('request');
    }
    // Step 0: let the user determine how they like their index.
    if ($context['step'] === 0) {
        $context['sub_template'] = 'create_index';
    }
    // Step 1: insert all the words.
    if ($context['step'] === 1) {
        $context['sub_template'] = 'create_index_progress';
        if ($context['start'] === 0) {
            db_extend();
            $tables = smf_db_list_tables(false, $db_prefix . 'log_search_words');
            if (!empty($tables)) {
                smf_db_query('
					DROP TABLE {db_prefix}log_search_words', array());
            }
            smf_db_create_word_search($index_properties[$context['index_settings']['bytes_per_word']]['column_definition']);
            // Temporarily switch back to not using a search index.
            if (!empty($modSettings['search_index']) && $modSettings['search_index'] == 'custom') {
                updateSettings(array('search_index' => ''));
            }
            // Don't let simultanious processes be updating the search index.
            if (!empty($modSettings['search_custom_index_config'])) {
                updateSettings(array('search_custom_index_config' => ''));
            }
        }
        $num_messages = array('done' => 0, 'todo' => 0);
        $request = smf_db_query('
			SELECT id_msg >= {int:starting_id} AS todo, COUNT(*) AS num_messages
			FROM {db_prefix}messages
			GROUP BY todo', array('starting_id' => $context['start']));
        while ($row = mysql_fetch_assoc($request)) {
            $num_messages[empty($row['todo']) ? 'done' : 'todo'] = $row['num_messages'];
        }
        if (empty($num_messages['todo'])) {
            $context['step'] = 2;
            $context['percentage'] = 80;
            $context['start'] = 0;
        } else {
            // Number of seconds before the next step.
            $stop = time() + 3;
            while (time() < $stop) {
                $inserts = array();
                $request = smf_db_query('
					SELECT id_msg, body
					FROM {db_prefix}messages
					WHERE id_msg BETWEEN {int:starting_id} AND {int:ending_id}
					LIMIT {int:limit}', array('starting_id' => $context['start'], 'ending_id' => $context['start'] + $messages_per_batch - 1, 'limit' => $messages_per_batch));
                $forced_break = false;
                $number_processed = 0;
                while ($row = mysql_fetch_assoc($request)) {
                    // In theory it's possible for one of these to take friggin ages so add more timeout protection.
                    if ($stop < time()) {
                        $forced_break = true;
                        break;
                    }
                    $number_processed++;
                    foreach (text2words($row['body'], $context['index_settings']['bytes_per_word'], true) as $id_word) {
                        $inserts[] = array($id_word, $row['id_msg']);
                    }
                }
                $num_messages['done'] += $number_processed;
                $num_messages['todo'] -= $number_processed;
                mysql_free_result($request);
                $context['start'] += $forced_break ? $number_processed : $messages_per_batch;
                if (!empty($inserts)) {
                    smf_db_insert('ignore', '{db_prefix}log_search_words', array('id_word' => 'int', 'id_msg' => 'int'), $inserts, array('id_word', 'id_msg'));
                }
                if ($num_messages['todo'] === 0) {
                    $context['step'] = 2;
                    $context['start'] = 0;
                    break;
                } else {
                    updateSettings(array('search_custom_index_resume' => serialize(array_merge($context['index_settings'], array('resume_at' => $context['start'])))));
                }
            }
            // Since there are still two steps to go, 90% is the maximum here.
            $context['percentage'] = round($num_messages['done'] / ($num_messages['done'] + $num_messages['todo']), 3) * 80;
        }
    } elseif ($context['step'] === 2) {
        if ($context['index_settings']['bytes_per_word'] < 4) {
            $context['step'] = 3;
        } else {
            $stop_words = $context['start'] === 0 || empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
            $stop = time() + 3;
            $context['sub_template'] = 'create_index_progress';
            $max_messages = ceil(60 * $modSettings['totalMessages'] / 100);
            while (time() < $stop) {
                $request = smf_db_query('
					SELECT id_word, COUNT(id_word) AS num_words
					FROM {db_prefix}log_search_words
					WHERE id_word BETWEEN {int:starting_id} AND {int:ending_id}
					GROUP BY id_word
					HAVING COUNT(id_word) > {int:minimum_messages}', array('starting_id' => $context['start'], 'ending_id' => $context['start'] + $index_properties[$context['index_settings']['bytes_per_word']]['step_size'] - 1, 'minimum_messages' => $max_messages));
                while ($row = mysql_fetch_assoc($request)) {
                    $stop_words[] = $row['id_word'];
                }
                mysql_free_result($request);
                updateSettings(array('search_stopwords' => implode(',', $stop_words)));
                if (!empty($stop_words)) {
                    smf_db_query('
						DELETE FROM {db_prefix}log_search_words
						WHERE id_word in ({array_int:stop_words})', array('stop_words' => $stop_words));
                }
                $context['start'] += $index_properties[$context['index_settings']['bytes_per_word']]['step_size'];
                if ($context['start'] > $index_properties[$context['index_settings']['bytes_per_word']]['max_size']) {
                    $context['step'] = 3;
                    break;
                }
            }
            $context['percentage'] = 80 + round($context['start'] / $index_properties[$context['index_settings']['bytes_per_word']]['max_size'], 3) * 20;
        }
    }
    // Step 3: remove words not distinctive enough.
    if ($context['step'] === 3) {
        $context['sub_template'] = 'create_index_done';
        updateSettings(array('search_index' => 'custom', 'search_custom_index_config' => serialize($context['index_settings'])));
        smf_db_query('
			DELETE FROM {db_prefix}settings
			WHERE variable = {string:search_custom_index_resume}', array('search_custom_index_resume' => 'search_custom_index_resume'));
    }
}
Exemple #7
0
function DumpDatabase2()
{
    global $db_name, $scripturl, $context, $modSettings, $crlf, $smcFunc, $db_prefix;
    // Administrators only!
    if (!allowedTo('admin_forum')) {
        fatal_lang_error('no_dump_database', 'critical');
    }
    // You can't dump nothing!
    if (!isset($_REQUEST['struct']) && !isset($_REQUEST['data'])) {
        $_REQUEST['data'] = true;
    }
    checkSession('post');
    // We will need this, badly!
    db_extend();
    // Attempt to stop from dying...
    @set_time_limit(600);
    if (@ini_get('memory_limit') < 256) {
        @ini_set('memory_limit', '256M');
    }
    // Start saving the output... (don't do it otherwise for memory reasons.)
    if (isset($_REQUEST['compress']) && function_exists('gzencode')) {
        // Make sure we're gzipping output, but then say we're not in the header ^_^.
        if (empty($modSettings['enableCompressedOutput'])) {
            @ob_start('ob_gzhandler');
        } elseif (ob_get_length() != 0) {
            ob_end_clean();
            @ob_start('ob_gzhandler');
        }
        // Send faked headers so it will just save the compressed output as a gzip.
        header('Content-Type: application/x-gzip');
        header('Accept-Ranges: bytes');
        header('Content-Encoding: none');
        // Gecko browsers... don't like this. (Mozilla, Firefox, etc.)
        if (!$context['browser']['is_gecko']) {
            header('Content-Transfer-Encoding: binary');
        }
        // The file extension will include .gz...
        $extension = '.sql.gz';
    } else {
        // Get rid of the gzipping alreading being done.
        if (!empty($modSettings['enableCompressedOutput'])) {
            @ob_end_clean();
        } elseif (function_exists('ob_clean') && ob_get_length() != 0) {
            ob_clean();
        }
        // Tell the client to save this file, even though it's text.
        header('Content-Type: ' . ($context['browser']['is_ie'] || $context['browser']['is_opera'] ? 'application/octetstream' : 'application/octet-stream'));
        header('Content-Encoding: none');
        // This time the extension should just be .sql.
        $extension = '.sql';
    }
    // This should turn off the session URL parser.
    $scripturl = '';
    // If this database is flat file and has a handler function pass it to that.
    if (!empty($smcFunc['db_get_backup'])) {
        $smcFunc['db_get_backup']();
        exit;
    }
    // Send the proper headers to let them download this file.
    header('Content-Disposition: filename="' . $db_name . '-' . (empty($_REQUEST['struct']) ? 'data' : (empty($_REQUEST['data']) ? 'structure' : 'complete')) . '_' . strftime('%Y-%m-%d') . $extension . '"');
    header('Cache-Control: private');
    header('Connection: close');
    // This makes things simpler when using it so very very often.
    $crlf = "\r\n";
    // SQL Dump Header.
    echo '-- ==========================================================', $crlf, '--', $crlf, '-- Database dump of tables in `', $db_name, '`', $crlf, '-- ', timeformat(time(), false), $crlf, '--', $crlf, '-- ==========================================================', $crlf, $crlf;
    // Get all tables in the database....
    if (preg_match('~^`(.+?)`\\.(.+?)$~', $db_prefix, $match) != 0) {
        $db = strtr($match[1], array('`' => ''));
        $dbp = str_replace('_', '\\_', $match[2]);
    } else {
        $db = false;
        $dbp = $db_prefix;
    }
    // Dump each table.
    $tables = smf_db_list_tables(false, $db_prefix . '%');
    foreach ($tables as $tableName) {
        if (function_exists('apache_reset_timeout')) {
            @apache_reset_timeout();
        }
        // Are we dumping the structures?
        if (isset($_REQUEST['struct'])) {
            echo $crlf, '--', $crlf, '-- Table structure for table `', $tableName, '`', $crlf, '--', $crlf, $crlf, smf_db_table_sql($tableName), ';', $crlf;
        }
        // How about the data?
        if (!isset($_REQUEST['data']) || substr($tableName, -10) == 'log_errors') {
            continue;
        }
        // Are there any rows in this table?
        $get_rows = smf_db_insert_sql($tableName);
        // No rows to get - skip it.
        if (empty($get_rows)) {
            continue;
        }
        echo $crlf, '--', $crlf, '-- Dumping data in `', $tableName, '`', $crlf, '--', $crlf, $crlf, $get_rows, '-- --------------------------------------------------------', $crlf;
    }
    echo $crlf, '-- Done', $crlf;
    exit;
}
Exemple #8
0
function OptimizeTables()
{
    global $db_type, $db_name, $db_prefix, $txt, $context, $scripturl, $sourcedir, $smcFunc;
    isAllowedTo('admin_forum');
    checkSession('post');
    ignore_user_abort(true);
    db_extend();
    // Start with no tables optimized.
    $opttab = 0;
    $context['page_title'] = $txt['database_optimize'];
    $context['sub_template'] = 'optimize';
    // Only optimize the tables related to this smf install, not all the tables in the db
    $real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
    // Get a list of tables, as well as how many there are.
    $temp_tables = smf_db_list_tables(false, $real_prefix . '%');
    $tables = array();
    foreach ($temp_tables as $table) {
        $tables[] = array('table_name' => $table);
    }
    // If there aren't any tables then I believe that would mean the world has exploded...
    $context['num_tables'] = count($tables);
    if ($context['num_tables'] == 0) {
        fatal_error('You appear to be running SMF in a flat file mode... fantastic!', false);
    }
    // For each table....
    $context['optimized_tables'] = array();
    foreach ($tables as $table) {
        // Optimize the table!  We use backticks here because it might be a custom table.
        $data_freed = smf_db_optimize_table($table['table_name']);
        if ($data_freed > 0) {
            $context['optimized_tables'][] = array('name' => $table['table_name'], 'data_freed' => $data_freed);
        }
    }
    // Number of tables, etc....
    $txt['database_numb_tables'] = sprintf($txt['database_numb_tables'], $context['num_tables']);
    $context['num_tables_optimized'] = count($context['optimized_tables']);
    // Check that we don't auto optimise again too soon!
    require_once $sourcedir . '/ScheduledTasks.php';
    CalculateNextTrigger('auto_optimize', true);
}