/**
 * Functions creates dump of tables in $file.
 *
 * @param mixed $tables Array of tables
 * @param string $dir Directory for saving file with table names
 * @param string $file Dump file name  \
 * @param Logger $log
 * @return bool Boolean False on failure
 */
function fn_uc_backup_tables($tables, $dir, $file, $log)
{
    if (empty($tables)) {
        return array();
    }
    if (!is_array($tables)) {
        $tables = array($tables);
    }
    $new_license_data = fn_uc_get_new_license_data();
    if (!empty($new_license_data['new_license']) && !in_array(Registry::get('config.table_prefix') . 'settings', $tables)) {
        $tables[] = Registry::get('config.table_prefix') . 'settings';
    }
    $file_backuped_tables = "{$dir}/db_backup_tables.txt";
    $backuped_tables = is_file($file_backuped_tables) ? explode("\n", fn_get_contents($file_backuped_tables)) : array();
    foreach ($tables as $key => &$table) {
        $table = fn_check_db_prefix($table, Registry::get('config.table_prefix'));
        if (in_array($table, $backuped_tables)) {
            unset($tables[$key]);
        }
    }
    if (empty($tables)) {
        return $tables;
    }
    if (false === fn_uc_is_enough_disk_space($file, $tables)) {
        fn_set_notification('W', __('warning'), __('text_uc_no_enough_space_to_backup_database'));
        return false;
    }
    if (fn_uc_is_mysqldump_available(Registry::get('config.db_password'))) {
        $log->write('Using mysqldump', __FILE__, __LINE__);
        $command = 'mysqldump --compact --no-create-db --add-drop-table --default-character-set=utf8 --skip-comments --verbose --host=' . Registry::get('config.db_host') . ' --user='******'config.db_user') . ' --password=\'' . Registry::get('config.db_password') . '\' --databases ' . Registry::get('config.db_name') . ' --tables ' . implode(' ', $tables) . ' >> ' . $file;
        system($command, $retval);
        if (0 === $retval) {
            $backuped_tables = array_merge($backuped_tables, $tables);
            fn_put_contents($file_backuped_tables, implode("\n", $backuped_tables));
            return $tables;
        }
        $log->write('mysqldump has reported failure', __FILE__, __LINE__);
    }
    $rows_per_pass = 40;
    $max_row_size = 10000;
    $t_status = db_get_hash_array("SHOW TABLE STATUS", 'Name');
    $f = fopen($file, 'ab');
    if (!empty($f)) {
        foreach ($tables as &$table) {
            $log->write('Backing up table: ' . $table, __FILE__, __LINE__);
            fwrite($f, "\nDROP TABLE IF EXISTS " . str_replace('?:', Registry::get('config.table_prefix'), $table) . ";\n");
            if (empty($t_status[str_replace('?:', Registry::get('config.table_prefix'), $table)])) {
                // new table in upgrade, we need drop statement only
                continue;
            }
            $scheme = db_get_row("SHOW CREATE TABLE {$table}");
            fwrite($f, array_pop($scheme) . ";\n\n");
            $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
            // Define iterator
            if ($t_status[str_replace('?:', Registry::get('config.table_prefix'), $table)]['Avg_row_length'] < $max_row_size) {
                $it = $rows_per_pass;
            } else {
                $it = 1;
            }
            fn_echo(' .');
            for ($i = 0; $i < $total_rows; $i = $i + $it) {
                $table_data = db_get_array("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                foreach ($table_data as $_tdata) {
                    $_tdata = fn_add_slashes($_tdata, true);
                    $values = array();
                    foreach ($_tdata as $v) {
                        $values[] = $v !== null ? "'{$v}'" : 'NULL';
                    }
                    fwrite($f, "INSERT INTO " . str_replace('?:', Registry::get('config.table_prefix'), $table) . " (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES (" . implode(', ', $values) . ");\n");
                }
            }
            $backuped_tables[] = "{$table}";
        }
        fclose($f);
        @chmod($file, DEFAULT_FILE_PERMISSIONS);
        fn_put_contents($file_backuped_tables, implode("\n", $backuped_tables));
        return $tables;
    }
}
示例#2
0
/**
 * Fuctnions parses SQL file and import data from it
 *
 * @param string $file File for import
 * @param integer $buffer Buffer size for fread function
 * @param bool $show_status Show or do not show process by printing ' .'
 * @param integer $show_create_table 0 - Do not print the name of created table, 1 - Print name and get lang_var('create_table'), 2 - Print name without getting lang_var
 * @param bool $check_prefix Check table prefix and replace it with the installed in config.php
 * @param bool $track Use queries cache. Do not execute queries that already are executed.
 * @param bool $skip_errors Skip errors or not
 * @param bool $move_progress_bar Move COMET progress bar or not on show progress
 * @return bool false, if file is not accessible
 */
function db_import_sql_file($file, $buffer = 16384, $show_status = true, $show_create_table = 1, $check_prefix = false, $track = false, $skip_errors = false, $move_progress_bar = true)
{
    if (file_exists($file)) {
        $path = dirname($file);
        $file_name = fn_basename($file);
        $tmp_file = $path . "/{$file_name}.tmp";
        $executed_queries = array();
        if ($track && file_exists($tmp_file)) {
            $executed_queries = unserialize(fn_get_contents($tmp_file));
        }
        if ($skip_errors) {
            $_skip_errors = Registry::get('runtime.database.skip_errors');
            Registry::set('runtime.database.skip_errors', true);
        }
        $fd = fopen($file, 'r');
        if ($fd) {
            $ret = array();
            $rest = '';
            $fs = filesize($file);
            if ($show_status && $move_progress_bar) {
                fn_set_progress('step_scale', ceil($fs / $buffer));
            }
            while (!feof($fd)) {
                $str = $rest . fread($fd, $buffer);
                $rest = fn_parse_queries($ret, $str);
                if ($show_status) {
                    fn_set_progress('echo', '<br />' . __('importing_data'), $move_progress_bar);
                }
                if (!empty($ret)) {
                    foreach ($ret as $query) {
                        if (!in_array($query, $executed_queries)) {
                            if ($show_create_table && preg_match('/CREATE\\s+TABLE\\s+`?(\\w+)`?/i', $query, $matches)) {
                                if ($show_create_table == 1) {
                                    $_text = __('creating_table');
                                } elseif ($show_create_table == 2) {
                                    $_text = 'Creating table';
                                }
                                $table_name = $check_prefix ? fn_check_db_prefix($matches[1], Registry::get('config.table_prefix')) : $matches[1];
                                if ($show_status) {
                                    fn_set_progress('echo', '<br />' . $_text . ': <b>' . $table_name . '</b>', $move_progress_bar);
                                }
                            }
                            if ($check_prefix) {
                                $query = fn_check_db_prefix($query);
                            }
                            Database::query($query);
                            if ($track) {
                                $executed_queries[] = $query;
                                fn_put_contents($tmp_file, serialize($executed_queries));
                            }
                            if ($show_status) {
                                fn_echo(' .');
                            }
                        }
                    }
                    $ret = array();
                }
            }
            fclose($fd);
            return true;
        }
        if ($skip_errors) {
            Registry::set('runtime.database.skip_errors', $_skip_errors);
        }
    }
    return false;
}
示例#3
0
/**
 * Functions creates dump of tables in $file.
 *
 * @param mixed $tables Array of tables
 * @param string $file Dump file name
 * @return Boolean False on failure
 */
function fn_uc_backup_tables($tables, $file)
{
    $rows_per_pass = 40;
    $max_row_size = 10000;
    if (!empty($tables)) {
        if (!is_array($tables)) {
            $tables = array($tables);
        }
        $t_status = db_get_hash_array("SHOW TABLE STATUS", 'Name');
        $f = fopen($file, 'ab');
        if (!empty($f)) {
            foreach ($tables as &$table) {
                $table = fn_check_db_prefix($table);
                fwrite($f, "\nDROP TABLE IF EXISTS " . str_replace('?:', TABLE_PREFIX, $table) . ";\n");
                if (empty($t_status[str_replace('?:', TABLE_PREFIX, $table)])) {
                    // new table in upgrade, we need drop statement only
                    continue;
                }
                $scheme = db_get_row("SHOW CREATE TABLE {$table}");
                fwrite($f, array_pop($scheme) . ";\n\n");
                $total_rows = db_get_field("SELECT COUNT(*) FROM {$table}");
                // Define iterator
                if ($t_status[str_replace('?:', TABLE_PREFIX, $table)]['Avg_row_length'] < $max_row_size) {
                    $it = $rows_per_pass;
                } else {
                    $it = 1;
                }
                fn_echo(' .');
                for ($i = 0; $i < $total_rows; $i = $i + $it) {
                    $table_data = db_get_array("SELECT * FROM {$table} LIMIT {$i}, {$it}");
                    foreach ($table_data as $_tdata) {
                        $_tdata = fn_add_slashes($_tdata, true);
                        fwrite($f, "INSERT INTO " . str_replace('?:', TABLE_PREFIX, $table) . " (`" . implode('`, `', array_keys($_tdata)) . "`) VALUES ('" . implode('\', \'', array_values($_tdata)) . "');\n");
                    }
                }
            }
            fclose($f);
            @chmod($file, DEFAULT_FILE_PERMISSIONS);
            return $tables;
        }
    } else {
        return array();
    }
}