function restore() { global $config, $lang; if (!isset($_POST['file'])) { $_POST['file'] = $_GET['file']; } @set_error_handler("SXD_errorHandler", E_ALL ^ E_NOTICE); $buttons = ""; echo tpl_page(tpl_process($lang['dumper_18']), $buttons); $this->SET['last_action'] = 1; $this->SET['last_db_restore'] = DBNAMES; $file = isset($_POST['file']) ? $_POST['file'] : ''; $file = str_replace("\\", "/", $file); $file = str_replace("..", "", $file); $file = str_replace("/", "", $file); if (stripos($file, "php") !== false) { die("Hacking attempt!"); } $db = $this->SET['last_db_restore']; if (!$db) { echo tpl_l($lang['dumper_19'], C_ERROR); exit; } echo tpl_l("{$lang['dumper_20']} `{$db}`."); mysql_select_db($db) or trigger_error($lang['dumper_4'] . mysql_error(), E_USER_ERROR); // Определение формата файла if (preg_match("/^(.+?)\\.sql(\\.(bz2|gz))?\$/", $file, $matches)) { if (isset($matches[3]) && $matches[3] == 'bz2') { $this->SET['comp_method'] = 2; } elseif (isset($matches[2]) && $matches[3] == 'gz') { $this->SET['comp_method'] = 1; } else { $this->SET['comp_method'] = 0; } $this->SET['comp_level'] = ''; if (!file_exists(PATH . "/{$file}")) { echo tpl_l($lang['dumper_21'], C_ERROR); exit; } echo tpl_l("{$lang['dumper_22']} `{$file}`."); $file = $matches[1]; } else { echo tpl_l($lang['dumper_21'], C_ERROR); exit; } echo tpl_l(str_repeat("-", 60)); $fp = $this->fn_open($file, "r"); $this->file_cache = $sql = $table = $insert = ''; $is_skd = $query_len = $execute = $q = $t = $i = $aff_rows = 0; $limit = 300; $index = 4; $tabs = 0; $cache = ''; $info = array(); $convert = false; // Установка кодировки соединения if ($this->mysql_version > 40101 && (CHARSET != 'auto' || $this->forced_charset)) { // Кодировка по умолчанию, если в дампе не указана кодировка mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error($lang['dumper_6'] . mysql_error(), E_USER_ERROR); echo tpl_l("{$lang['dumper_7']} `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } else { $last_charset = ''; } $last_showed = ''; while (($str = $this->fn_read_str($fp)) !== false) { if (empty($str) || preg_match("/^(#|--)/", $str)) { if (!$is_skd && preg_match("/^#SKD101\\|/", $str)) { $info = explode("|", $str); echo tpl_s(0, $t / $info[4]); $is_skd = 1; } continue; } $query_len += strlen($str); if (!$insert && preg_match("/^(INSERT INTO `?([^` ]+)`? .*?VALUES)(.*)\$/i", $str, $m)) { if ($table != $m[2]) { $table = $m[2]; $tabs++; $cache .= tpl_l("Таблица `{$table}`."); $last_showed = $table; $i = 0; if ($is_skd) { echo tpl_s(100, $t / $info[4]); } } $insert = $m[1] . ' '; $sql .= $m[3]; $index++; $info[$index] = isset($info[$index]) ? $info[$index] : 0; $limit = round($info[$index] / 20); $limit = $limit < 300 ? 300 : $limit; if ($info[$index] > $limit) { echo $cache; $cache = ''; echo tpl_s(0 / $info[$index], $t / $info[4]); } } else { $sql .= $str; if ($insert) { $i++; $t++; if ($is_skd && $info[$index] > $limit && $t % $limit == 0) { echo tpl_s($i / $info[$index], $t / $info[4]); } } } if (!$insert && preg_match("/^CREATE TABLE (IF NOT EXISTS )?`?([^` ]+)`?/i", $str, $m) && $table != $m[2]) { $table = $m[2]; $insert = ''; $tabs++; $is_create = true; $i = 0; } if ($sql) { if (preg_match("/;\$/", $str)) { $sql = rtrim($insert . $sql, ";"); if (empty($insert)) { if ($this->mysql_version < 40101) { $sql = preg_replace("/ENGINE\\s?=/", "TYPE=", $sql); } elseif (preg_match("/CREATE TABLE/i", $sql)) { // Выставляем кодировку соединения if (preg_match("/(CHARACTER SET|CHARSET)[=\\s]+(\\w+)/i", $sql, $charset)) { if (!$this->forced_charset && $charset[2] != $last_charset) { if (CHARSET == 'auto') { if ($config['charset'] == "utf-8" and $charset[2] == "cp1251") { $convert = true; $charset[2] = "utf8"; $this->restore_charset = "utf8"; } mysql_query("SET NAMES '" . $charset[2] . "'") or trigger_error("{$lang['dumper_6']}{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("{$lang['dumper_7']} `" . $charset[2] . "`.", C_WARNING); $last_charset = $charset[2]; } else { $cache .= tpl_l($lang['dumper_8'], C_ERROR); $cache .= tpl_l($lang['dumper_9'] . ' `' . $table . '` -> ' . $charset[2] . ' (' . $lang['dumper_10'] . ' ' . $this->restore_charset . ')', C_ERROR); } } // Меняем кодировку если указано форсировать кодировку if ($this->forced_charset or $convert) { $sql = preg_replace("/(\\/\\*!\\d+\\s)?((COLLATE)[=\\s]+)\\w+(\\s+\\*\\/)?/i", '', $sql); $sql = preg_replace("/((CHARACTER SET|CHARSET)[=\\s]+)\\w+/i", "\\1" . $this->restore_charset . $this->restore_collate, $sql); } } elseif (CHARSET == 'auto') { // Вставляем кодировку для таблиц, если она не указана и установлена auto кодировка $sql .= ' DEFAULT CHARSET=' . $this->restore_charset . $this->restore_collate; if ($this->restore_charset != $last_charset) { mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error("{$lang['dumper_6']}{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("{$lang['dumper_7']} `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } } } if ($last_showed != $table) { $cache .= tpl_l("{$lang['dumper_9']} `{$table}`."); $last_showed = $table; } } elseif ($this->mysql_version > 40101 && empty($last_charset)) { // Устанавливаем кодировку на случай если отсутствует CREATE TABLE mysql_query("SET {$this->restore_charset} '" . $this->restore_charset . "'") or trigger_error("{$lang['dumper_6']}{$sql}<BR>" . mysql_error(), E_USER_ERROR); echo tpl_l("{$lang['dumper_7']} `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } $insert = ''; $execute = 1; } if ($query_len >= 65536 && preg_match("/,\$/", $str)) { $sql = rtrim($insert . $sql, ","); $execute = 1; } if ($execute) { $q++; if ($convert) { $sql = iconv('WINDOWS-1251', 'UTF-8//IGNORE', $sql); } mysql_query($sql) or trigger_error($lang['dumper_23'] . mysql_error(), E_USER_ERROR); if (preg_match("/^insert/i", $sql)) { $aff_rows += mysql_affected_rows(); } $sql = ''; $query_len = 0; $execute = 0; } } } echo $cache; echo tpl_s(1, 1); echo tpl_l(str_repeat("-", 60)); echo tpl_l($lang['dumper_24'], C_RESULT); if (isset($info[3])) { echo tpl_l("{$lang['dumper_25']} {$info[3]}", C_RESULT); } echo tpl_l("{$lang['dumper_26']} {$q}", C_RESULT); echo tpl_l("{$lang['dumper_27']} {$tabs}", C_RESULT); echo tpl_l("{$lang['dumper_28']} {$aff_rows}", C_RESULT); $this->tabs = $tabs; $this->records = $aff_rows; $this->size = filesize(PATH . $this->filename); $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; $this->fn_close($fp); }
function restore() { if (!isset($_POST)) { $this->main(); } set_error_handler("SXD_errorHandler"); $buttons = "<INPUT ID=back TYPE=button VALUE='Back' DISABLED onClick=\"history.back();\">"; echo tpl_page(tpl_process("Restoring database backup"), $buttons); $this->SET['last_action'] = 1; $this->SET['last_db_restore'] = isset($_POST['db_restore']) ? $_POST['db_restore'] : ''; $file = isset($_POST['file']) ? $_POST['file'] : ''; $this->fn_save(); $db = $this->SET['last_db_restore']; if (!$db) { echo tpl_l("ERROR! No database!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Đang kết nối cơ sở dữ liệu `{$db}`."); mysql_select_db($db) or trigger_error("Unable to select database. .<BR>" . mysql_error(), E_USER_ERROR); // Definition file format if (preg_match("/^(.+?)\\.sql(\\.(bz2|gz))?\$/", $file, $matches)) { if (isset($matches[3]) && $matches[3] == 'bz2') { $this->SET['comp_method'] = 2; } elseif (isset($matches[2]) && $matches[3] == 'gz') { $this->SET['comp_method'] = 1; } else { $this->SET['comp_method'] = 0; } $this->SET['comp_level'] = ''; if (!file_exists(PATH . "/{$file}")) { echo tpl_l("ERROR! File Not Found! !", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Reading File`{$file}`."); $file = $matches[1]; } else { echo tpl_l("ERROR! No file selected(", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l(str_repeat("-", 60)); $fp = $this->fn_open($file, "r"); $this->file_cache = $sql = $table = $insert = ''; $is_skd = $query_len = $execute = $q = $t = $i = $aff_rows = 0; $limit = 300; $index = 4; $tabs = 0; $cache = ''; $info = array(); // Setting coding connections if ($this->mysql_version > 40101 && (CHARSET != 'auto' || $this->forced_charset)) { // Encryption by default if the dump was not encoded mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error("Cannot set the encoding for the connection.<BR>" . mysql_error(), E_USER_ERROR); echo tpl_l("Using encoding `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } else { $last_charset = ''; } $last_showed = ''; while (($str = $this->fn_read_str($fp)) !== false) { if (empty($str) || preg_match("/^(#|--)/", $str)) { if (!$is_skd && preg_match("/^#SKD101\\|/", $str)) { $info = explode("|", $str); echo tpl_s(0, $t / $info[4]); $is_skd = 1; } continue; } $query_len += strlen($str); if (!$insert && preg_match("/^(INSERT INTO `?([^` ]+)`? .*?VALUES)(.*)\$/i", $str, $m)) { if ($table != $m[2]) { $table = $m[2]; $tabs++; $cache .= tpl_l("Table `{$table}`."); $last_showed = $table; $i = 0; if ($is_skd) { echo tpl_s(100, $t / $info[4]); } } $insert = $m[1] . ' '; $sql .= $m[3]; $index++; $info[$index] = isset($info[$index]) ? $info[$index] : 0; $limit = round($info[$index] / 20); $limit = $limit < 300 ? 300 : $limit; if ($info[$index] > $limit) { echo $cache; $cache = ''; echo tpl_s(0 / $info[$index], $t / $info[4]); } } else { $sql .= $str; if ($insert) { $i++; $t++; if ($is_skd && $info[$index] > $limit && $t % $limit == 0) { echo tpl_s($i / $info[$index], $t / $info[4]); } } } if (!$insert && preg_match("/^CREATE TABLE (IF NOT EXISTS )?`?([^` ]+)`?/i", $str, $m) && $table != $m[2]) { $table = $m[2]; $insert = ''; $tabs++; $is_create = true; $i = 0; } if ($sql) { if (preg_match("/;\$/", $str)) { $sql = rtrim($insert . $sql, ";"); if (empty($insert)) { if ($this->mysql_version < 40101) { $sql = preg_replace("/ENGINE\\s?=/", "TYPE=", $sql); } elseif (preg_match("/CREATE TABLE/i", $sql)) { // Bill encoding connections if (preg_match("/(CHARACTER SET|CHARSET)[=\\s]+(\\w+)/i", $sql, $charset)) { if (!$this->forced_charset && $charset[2] != $last_charset) { if (CHARSET == 'auto') { mysql_query("SET NAMES '" . $charset[2] . "'") or trigger_error("Cannot set the encoding for the connection.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("Using encoding `" . $charset[2] . "`.", C_WARNING); $last_charset = $charset[2]; } else { $cache .= tpl_l('Encoding connections, and the table does not match :', C_ERROR); $cache .= tpl_l('Table `' . $table . '` -> ' . $charset[2] . ' (Connection ' . $this->restore_charset . ')', C_ERROR); } } // Changing encoding if the rush encoding if ($this->forced_charset) { $sql = preg_replace("/(\\/\\*!\\d+\\s)?((COLLATE)[=\\s]+)\\w+(\\s+\\*\\/)?/i", '', $sql); $sql = preg_replace("/((CHARACTER SET|CHARSET)[=\\s]+)\\w+/i", "\\1" . $this->restore_charset . $this->restore_collate, $sql); } } elseif (CHARSET == 'auto') { // Run encoding table if it is not specified and installed auto encoding $sql .= ' DEFAULT CHARSET=' . $this->restore_charset . $this->restore_collate; if ($this->restore_charset != $last_charset) { mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error("Cannot set the encoding for the connection.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("Using encoding `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } } } if ($last_showed != $table) { $cache .= tpl_l("Table `{$table}`."); $last_showed = $table; } } elseif ($this->mysql_version > 40101 && empty($last_charset)) { // Install encoding for the absence CREATE TABLE mysql_query("SET {$this->restore_charset} '" . $this->restore_charset . "'") or trigger_error("Cannot set the encoding for the connection.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); echo tpl_l("Using encoding `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } $insert = ''; $execute = 1; } if ($query_len >= 65536 && preg_match("/,\$/", $str)) { $sql = rtrim($insert . $sql, ","); $execute = 1; } if ($execute) { $q++; mysql_query($sql) or trigger_error("Bad request.<BR>" . mysql_error(), E_USER_ERROR); if (preg_match("/^insert/i", $sql)) { $aff_rows += mysql_affected_rows(); } $sql = ''; $query_len = 0; $execute = 0; } } } echo $cache; echo tpl_s(1, 1); echo tpl_l(str_repeat("-", 60)); echo tpl_l("DB restored from a backup.", C_RESULT); if (isset($info[3])) { echo tpl_l("Established copies: {$info[3]}", C_RESULT); } echo tpl_l("Queries to DB: {$q}", C_RESULT); echo tpl_l("Tables set up: {$tabs}", C_RESULT); echo tpl_l("Lines added: {$aff_rows}", C_RESULT); $this->tabs = $tabs; $this->records = $aff_rows; $this->size = filesize(PATH . $this->filename); $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; echo "<SCRIPT>document.getElementById('back').disabled = 0;</SCRIPT>"; // Data Transfer for global statistics if (GS) { echo "<SCRIPT>document.getElementById('GS').src = 'http://sypex.net/gs.php?r={$this->tabs},{$this->records},{$this->size},{$this->comp},108';</SCRIPT>"; } $this->fn_close($fp); }
function restore() { if (!isset($_POST)) { $this->main(); } set_error_handler("SXD_errorHandler"); $buttons = "<INPUT ID=back TYPE=button VALUE='Вернуться' DISABLED onClick=\"history.back();\">"; echo tpl_page(tpl_process("Восстановление БД из резервной копии"), $buttons); $this->SET['last_action'] = 1; $this->SET['last_db_restore'] = isset($_POST['db_restore']) ? $_POST['db_restore'] : ''; $file = isset($_POST['file']) ? $_POST['file'] : ''; $this->fn_save(); $db = $this->SET['last_db_restore']; if (!$db) { echo tpl_l("ОШИБКА! Не указана база данных!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Подключение к БД `{$db}`."); mysql_select_db($db) or trigger_error("Не удается выбрать базу данных.<BR>" . mysql_error(), E_USER_ERROR); // Определение формата файла if (preg_match("/^(.+?)\\.sql(\\.(bz2|gz))?\$/", $file, $matches)) { if (isset($matches[3]) && $matches[3] == 'bz2') { $this->SET['comp_method'] = 2; } elseif (isset($matches[2]) && $matches[3] == 'gz') { $this->SET['comp_method'] = 1; } else { $this->SET['comp_method'] = 0; } $this->SET['comp_level'] = ''; if (!file_exists(PATH . "/{$file}")) { echo tpl_l("ОШИБКА! Файл не найден!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Чтение файла `{$file}`."); $file = $matches[1]; } else { echo tpl_l("ОШИБКА! Не выбран файл!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l(str_repeat("-", 60)); $fp = $this->fn_open($file, "r"); $this->file_cache = $sql = $table = $insert = ''; $is_skd = $query_len = $execute = $q = $t = $i = $aff_rows = 0; $limit = 300; $index = 4; $tabs = 0; $cache = ''; $info = array(); // Установка кодировки соединения if ($this->mysql_version > 40101 && (CHARSET != 'auto' || $this->forced_charset)) { // Кодировка по умолчанию, если в дампе не указана кодировка mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error("Неудается изменить кодировку соединения.<BR>" . mysql_error(), E_USER_ERROR); echo tpl_l("Установлена кодировка соединения `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } else { $last_charset = ''; } $last_showed = ''; while (($str = $this->fn_read_str($fp)) !== false) { if (empty($str) || preg_match("/^(#|--)/", $str)) { if (!$is_skd && preg_match("/^#SKD101\\|/", $str)) { $info = explode("|", $str); echo tpl_s(0, $t / $info[4]); $is_skd = 1; } continue; } $query_len += strlen($str); if (!$insert && preg_match("/^(INSERT INTO `?([^` ]+)`? .*?VALUES)(.*)\$/i", $str, $m)) { if ($table != $m[2]) { $table = $m[2]; $tabs++; $cache .= tpl_l("Таблица `{$table}`."); $last_showed = $table; $i = 0; if ($is_skd) { echo tpl_s(100, $t / $info[4]); } } $insert = $m[1] . ' '; $sql .= $m[3]; $index++; $info[$index] = isset($info[$index]) ? $info[$index] : 0; $limit = round($info[$index] / 20); $limit = $limit < 300 ? 300 : $limit; if ($info[$index] > $limit) { echo $cache; $cache = ''; echo tpl_s(0 / $info[$index], $t / $info[4]); } } else { $sql .= $str; if ($insert) { $i++; $t++; if ($is_skd && $info[$index] > $limit && $t % $limit == 0) { echo tpl_s($i / $info[$index], $t / $info[4]); } } } if (!$insert && preg_match("/^CREATE TABLE (IF NOT EXISTS )?`?([^` ]+)`?/i", $str, $m) && $table != $m[2]) { $table = $m[2]; $insert = ''; $tabs++; $is_create = true; $i = 0; } if ($sql) { if (preg_match("/;\$/", $str)) { $sql = rtrim($insert . $sql, ";"); if (empty($insert)) { if ($this->mysql_version < 40101) { $sql = preg_replace("/ENGINE\\s?=/", "TYPE=", $sql); } elseif (preg_match("/CREATE TABLE/i", $sql)) { // Выставляем кодировку соединения if (preg_match("/(CHARACTER SET|CHARSET)[=\\s]+(\\w+)/i", $sql, $charset)) { if (!$this->forced_charset && $charset[2] != $last_charset) { if (CHARSET == 'auto') { mysql_query("SET NAMES '" . $charset[2] . "'") or trigger_error("Неудается изменить кодировку соединения.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("Установлена кодировка соединения `" . $charset[2] . "`.", C_WARNING); $last_charset = $charset[2]; } else { $cache .= tpl_l('Кодировка соединения и таблицы не совпадает:', C_ERROR); $cache .= tpl_l('Таблица `' . $table . '` -> ' . $charset[2] . ' (соединение ' . $this->restore_charset . ')', C_ERROR); } } // Меняем кодировку если указано форсировать кодировку if ($this->forced_charset) { $sql = preg_replace("/(\\/\\*!\\d+\\s)?((COLLATE)[=\\s]+)\\w+(\\s+\\*\\/)?/i", '', $sql); $sql = preg_replace("/((CHARACTER SET|CHARSET)[=\\s]+)\\w+/i", "\\1" . $this->restore_charset . $this->restore_collate, $sql); } } elseif (CHARSET == 'auto') { // Вставляем кодировку для таблиц, если она не указана и установлена auto кодировка $sql .= ' DEFAULT CHARSET=' . $this->restore_charset . $this->restore_collate; if ($this->restore_charset != $last_charset) { mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error("Неудается изменить кодировку соединения.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); $cache .= tpl_l("Установлена кодировка соединения `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } } } if ($last_showed != $table) { $cache .= tpl_l("Таблица `{$table}`."); $last_showed = $table; } } elseif ($this->mysql_version > 40101 && empty($last_charset)) { // Устанавливаем кодировку на случай если отсутствует CREATE TABLE mysql_query("SET {$this->restore_charset} '" . $this->restore_charset . "'") or trigger_error("Неудается изменить кодировку соединения.<BR>{$sql}<BR>" . mysql_error(), E_USER_ERROR); echo tpl_l("Установлена кодировка соединения `" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } $insert = ''; $execute = 1; } if ($query_len >= 65536 && preg_match("/,\$/", $str)) { $sql = rtrim($insert . $sql, ","); $execute = 1; } if ($execute) { $q++; mysql_query($sql) or trigger_error("Неправильный запрос.<BR>" . mysql_error(), E_USER_ERROR); if (preg_match("/^insert/i", $sql)) { $aff_rows += mysql_affected_rows(); } $sql = ''; $query_len = 0; $execute = 0; } } } echo $cache; echo tpl_s(1, 1); echo tpl_l(str_repeat("-", 60)); echo tpl_l("БД восстановлена из резервной копии.", C_RESULT); if (isset($info[3])) { echo tpl_l("Дата создания копии: {$info[3]}", C_RESULT); } echo tpl_l("Запросов к БД: {$q}", C_RESULT); echo tpl_l("Таблиц создано: {$tabs}", C_RESULT); echo tpl_l("Строк добавлено: {$aff_rows}", C_RESULT); $this->tabs = $tabs; $this->records = $aff_rows; $this->size = filesize(PATH . $this->filename); $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; echo "<SCRIPT>document.getElementById('back').disabled = 0;</SCRIPT>"; // Передача данных для глобальной статистики if (GS) { echo "<SCRIPT>document.getElementById('GS').src = 'http://sypex.net/gs.php?r={$this->tabs},{$this->records},{$this->size},{$this->comp},108';</SCRIPT>"; } $this->fn_close($fp); }
function restore() { if (!isset($_POST)) { $this->main(); } set_error_handler("SXD_errorHandler"); $buttons = "<INPUT ID=back TYPE=button VALUE='Вернуться' DISABLED onClick=\"history.back();\">"; echo tpl_page(tpl_process("Восстановление БД из резервной копии"), $buttons); $this->SET['last_action'] = 1; $this->SET['last_db_restore'] = isset($_POST['db_restore']) ? $_POST['db_restore'] : ''; $file = isset($_POST['file']) ? $_POST['file'] : ''; $this->fn_save(); $db = $this->SET['last_db_restore']; if (!$db) { echo tpl_l("ОШИБКА! Не указана база данных!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Подключение к БД `{$db}`."); mysql_select_db($db) or trigger_error("Не удается выбрать базу данных.<BR>" . mysql_error(), E_USER_ERROR); preg_match("/^(\\d+)\\.(\\d+)\\.(\\d+)/", mysql_get_server_info(), $m); $this->mysql_version = sprintf("%d%02d%02d", $m[1], $m[2], $m[3]); // Определение формата файла if (preg_match("/^(.+?)\\.sql(\\.(bz2|gz))?\$/", $file, $matches)) { if (isset($matches[3]) && $matches[3] == 'bz2') { $this->SET['comp_method'] = 2; } elseif (isset($matches[2]) && $matches[3] == 'gz') { $this->SET['comp_method'] = 1; } else { $this->SET['comp_method'] = 0; } $this->SET['comp_level'] = ''; if (!file_exists(PATH . "/{$file}")) { echo tpl_l("ОШИБКА! Файл не найден!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l("Чтение файла `{$file}`."); $file = $matches[1]; } else { echo tpl_l("ОШИБКА! Не выбран файл!", C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l(str_repeat("-", 60)); $fp = $this->fn_open($file, "r"); $this->file_cache = $sql = $table = $insert = ''; $is_skd = $query_len = $execute = $q = $t = $i = $aff_rows = 0; $limit = 300; $index = 4; $tabs = 0; $cache = ''; $info = array(); while (($str = $this->fn_read_str($fp)) !== false) { if (empty($str) || preg_match("/^(#|--)/", $str)) { if (!$is_skd && preg_match("/^#SKD101\\|/", $str)) { $info = explode("|", $str); echo tpl_s(0, $t / $info[4]); $is_skd = 1; } continue; } $query_len += strlen($str); if (!$insert && preg_match("/^(INSERT INTO `?([^` ]+)`? .*?VALUES)(.*)\$/i", $str, $m)) { if ($table != $m[2]) { $table = $m[2]; $tabs++; echo tpl_l("Таблица `{$table}`."); $i = 0; if ($is_skd) { echo tpl_s(100, $t / $info[4]); } } $insert = $m[1] . ' '; $sql .= $m[3]; $index++; $info[$index] = isset($info[$index]) ? $info[$index] : 0; $limit = round($info[$index] / 20); $limit = $limit < 300 ? 300 : $limit; if ($info[$index] > $limit) { echo $cache; $cache = ''; echo tpl_s(0 / $info[$index], $t / $info[4]); } } else { $sql .= $str; if ($insert) { $i++; $t++; if ($is_skd && $info[$index] > $limit && $t % $limit == 0) { echo tpl_s($i / $info[$index], $t / $info[4]); } } } if (!$insert && preg_match("/^CREATE TABLE (IF NOT EXISTS )?`?([^` ]+)`?/i", $str, $m) && $table != $m[2]) { $table = $m[2]; $insert = ''; $tabs++; $cache .= tpl_l("Таблица `{$table}`."); $i = 0; } if ($sql) { if (preg_match("/;\$/", $str)) { $sql = rtrim($insert . $sql, ";"); if (empty($insert)) { if ($this->mysql_version < 40101) { $sql = preg_replace("/ENGINE\\s?=/", "TYPE=", $sql); } } $insert = ''; $execute = 1; } if ($query_len >= 65536 && preg_match("/,\$/", $str)) { $sql = rtrim($insert . $sql, ","); $execute = 1; } if ($execute) { $q++; mysql_query($sql) or trigger_error("Неправильный запрос.<BR>" . mysql_error(), E_USER_ERROR); if (preg_match("/^insert/i", $sql)) { $aff_rows += mysql_affected_rows(); } $sql = ''; $query_len = 0; $execute = 0; } } } echo $cache; echo tpl_s(1, 1); echo tpl_l(str_repeat("-", 60)); echo tpl_l("БД восстановлена из резервной копии.", C_RESULT); if (isset($info[3])) { echo tpl_l("Дата создания копии: {$info[3]}", C_RESULT); } echo tpl_l("Запросов к БД: {$q}", C_RESULT); echo tpl_l("Таблиц создано: {$tabs}", C_RESULT); echo tpl_l("Строк добавлено: {$aff_rows}", C_RESULT); $this->tabs = $tabs; $this->records = $aff_rows; $this->size = filesize(PATH . $this->filename); $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; echo "<SCRIPT>document.getElementById('back').disabled = 0;</SCRIPT>"; // Передача данных для глобальной статистики if (GS) { echo "<SCRIPT>document.getElementById('GS').src = 'http://sypex.net/gs.php?r={$this->tabs},{$this->records},{$this->size},{$this->comp},107';</SCRIPT>"; } $this->fn_close($fp); }
function backup($filter, $pack, $pack_rate) { $this->SET['tables_exclude'] = isset($filter) ? $filter : ''; $this->SET['comp_method'] = isset($pack) ? intval($pack) : 0; $this->SET['comp_level'] = isset($pack_rate) ? intval($pack_rate) : 0; $db = DB_NAME; $tables = array(); $result = mysql_query("SHOW TABLES"); $all = 0; while ($row = mysql_fetch_array($result)) { $status = 0; if (!empty($tbls)) { foreach ($tbls as $table) { $exclude = preg_match("/^\\^/", $table) ? true : false; if (!$exclude) { if (preg_match("/^{$table}\$/i", $row[0])) { $status = 1; } $all = 1; } if ($exclude && preg_match("/{$table}\$/i", $row[0])) { $status = -1; } } } else { $status = 1; } if ($status >= $all) { $tables[] = $row[0]; } } $tabs = count($tables); // Определение размеров таблиц $result = mysql_query("SHOW TABLE STATUS"); $tabinfo = array(); $tabinfo[0] = 0; $info = ''; while ($item = mysql_fetch_assoc($result)) { if (in_array($item['Name'], $tables)) { $item['Rows'] = empty($item['Rows']) ? 0 : $item['Rows']; $tabinfo[0] += $item['Rows']; $tabinfo[$item['Name']] = $item['Rows']; $this->size += $item['Data_length']; $tabsize[$item['Name']] = 1 + round(LIMIT * 1048576 / ($item['Avg_row_length'] + 1)); if ($item['Rows']) { $info .= "|" . $item['Rows']; } } } $show = 10 + $tabinfo[0] / 50; $info = $tabinfo[0] . $info; $name = $db . '_' . date("Y-m-d_H-i"); $fp = $this->fn_open($name, "w"); $this->fn_write($fp, "#SKD101|{$db}|{$tabs}|" . date("Y.m.d H:i:s") . "|{$info}\n\n"); $t = 0; $result = mysql_query("SET SQL_QUOTE_SHOW_CREATE = 1"); foreach ($tables as $table) { $this->tables_list[] = $table . "[" . fn_int($tabinfo[$table]) . "]"; // Создание таблицы $result = mysql_query("SHOW CREATE TABLE {$table}"); $tab = mysql_fetch_array($result); $tab = preg_replace('/(default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP|DEFAULT CHARSET=\\w+|COLLATE=\\w+|character set \\w+|collate \\w+)/i', '/*!40101 \\1 */', $tab); $this->fn_write($fp, "DROP TABLE IF EXISTS {$table};\n{$tab[1]};\n\n"); // Опредеделяем типы столбцов $NumericColumn = array(); $result = mysql_query("SHOW COLUMNS FROM {$table}"); $field = 0; while ($col = mysql_fetch_row($result)) { $NumericColumn[$field++] = preg_match("/^(\\w*int|year)/", $col[1]) ? 1 : 0; } $fields = $field; $from = 0; $limit = $tabsize[$table]; $limit2 = round($limit / 3); if ($tabinfo[$table] > 0) { if ($tabinfo[$table] > $limit2) { echo tpl_s(0, $t / $tabinfo[0]); } $i = 0; $this->fn_write($fp, "INSERT INTO `{$table}` VALUES"); while (($result = mysql_query("SELECT * FROM {$table} LIMIT {$from}, {$limit}")) && ($total = mysql_num_rows($result))) { while ($row = mysql_fetch_row($result)) { $i++; $t++; for ($k = 0; $k < $fields; $k++) { if ($NumericColumn[$k]) { $row[$k] = isset($row[$k]) ? $row[$k] : "NULL"; } else { $row[$k] = isset($row[$k]) ? "'" . mysql_escape_string($row[$k]) . "'" : "NULL"; } } $this->fn_write($fp, ($i == 1 ? "" : ",") . "\n(" . implode(", ", $row) . ")"); if ($i % $limit2 == 0) { echo tpl_s($i / $tabinfo[$table], $t / $tabinfo[0]); } } mysql_free_result($result); if ($total < $limit) { break; } $from += $limit; } $this->fn_write($fp, ";\n\n"); } } $this->tabs = $tabs; $this->records = $tabinfo[0]; $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; $this->fn_close($fp); $this->table_size = round($this->size / 1048576, 2); $this->file_size = round(filesize(PATH . $this->filename) / 1048576, 2); $this->tables_count = $tabs; $this->rows_count = fn_int($tabinfo[0]); }
function restore() { $TEXT_DUMPER_BACK = TEXT_DUMPER_BACK; $TEXT_DUMPER_NAME_ERROR = TEXT_DUMPER_NAME_ERROR; $TEXT_DUMPER_CONNECT = TEXT_DUMPER_CONNECT; $TEXT_DUMPER_CONNECT_ERROR = TEXT_DUMPER_CONNECT_ERROR; $TEXT_DUMPER_CREATE_FILE = TEXT_DUMPER_CREATE_FILE; $TEXT_DUMPER_CHARSET_ERROR = TEXT_DUMPER_CHARSET_ERROR; $TEXT_DUMPER_CHARSET = TEXT_DUMPER_CHARSET; $TEXT_DUMPER_CHARSET_COLLATION = TEXT_DUMPER_CHARSET_COLLATION; $TEXT_DUMPER_TABLE = TEXT_DUMPER_TABLE; $TEXT_DUMPER_CONNECT1 = TEXT_DUMPER_CONNECT1; $TEXT_DUMPER_PROCESS = TEXT_DUMPER_PROCESS; $TEXT_DUMPER_TABLES_COUNT = TEXT_DUMPER_TABLES_COUNT; $TEXT_DUMPER_STRING_COUNT = TEXT_DUMPER_STRING_COUNT; $TEXT_DUMPER_RESTORE = TEXT_DUMPER_RESTORE; $TEXT_DUMPER_FILE_ERROR = TEXT_DUMPER_FILE_ERROR; $TEXT_DUMPER_FILE_READ = TEXT_DUMPER_FILE_READ; $TEXT_DUMPER_FILE_ERROR1 = TEXT_DUMPER_FILE_ERROR1; $TEXT_DUMPER_QUERY_ERROR = TEXT_DUMPER_QUERY_ERROR; $TEXT_DUMPER_RESTORED = TEXT_DUMPER_RESTORED; $TEXT_DUMPER_DATE = TEXT_DUMPER_DATE; $TEXT_DUMPER_QUERY_COUNT = TEXT_DUMPER_QUERY_COUNT; $TEXT_DUMPER_TABLES_CREATED = TEXT_DUMPER_TABLES_CREATED; $TEXT_DUMPER_STRINGS_CREATED = TEXT_DUMPER_STRINGS_CREATED; $TEXT_DUMPER_MAX = TEXT_DUMPER_MAX; $TEXT_DUMPER_MED = TEXT_DUMPER_MED; $TEXT_DUMPER_MIN = TEXT_DUMPER_MIN; $TEXT_DUMPER_NO = TEXT_DUMPER_NO; if (!isset($_REQUEST)) { $this->main(); } set_error_handler("SXD_errorHandler"); $buttons = "<span class=button><button id=back type=button value='" . TEXT_DUMPER_BACK . "' disabled onclick=\"history.back();\">" . TEXT_DUMPER_BACK . "</button></span>"; echo tpl_page(tpl_process($TEXT_DUMPER_RESTORE), $buttons); $this->SET['last_action'] = 1; $this->SET['last_db_restore'] = isset($_REQUEST['db_restore']) ? $_REQUEST['db_restore'] : ''; $file = isset($_POST['file']) ? $_POST['file'] : ''; $this->fn_save(); $db = $this->SET['last_db_restore']; if (!$db) { echo tpl_l($TEXT_DUMPER_NAME_ERROR, C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l($TEXT_DUMPER_CONNECT . "`{$db}`."); mysql_select_db($db) or trigger_error($TEXT_DUMPER_CONNECT_ERROR . "<br />" . mysql_error(), E_USER_ERROR); // Определение формата файла if (preg_match("/^(.+?)\\.sql(\\.(bz2|gz))?\$/", $file, $matches)) { if (isset($matches[3]) && $matches[3] == 'bz2') { $this->SET['comp_method'] = 2; } elseif (isset($matches[2]) && $matches[3] == 'gz') { $this->SET['comp_method'] = 1; } else { $this->SET['comp_method'] = 0; } $this->SET['comp_level'] = ''; if (!file_exists(PATH . "/{$file}")) { echo tpl_l($TEXT_DUMPER_FILE_ERROR, C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l($TEXT_DUMPER_FILE_READ . "`{$file}`."); $file = $matches[1]; } else { echo tpl_l($TEXT_DUMPER_FILE_ERROR1, C_ERROR); echo tpl_enableBack(); exit; } echo tpl_l(str_repeat("-", 60)); $fp = $this->fn_open($file, "r"); $this->file_cache = $sql = $table = $insert = ''; $is_skd = $query_len = $execute = $q = $t = $i = $aff_rows = 0; $limit = 300; $index = 4; $tabs = 0; $cache = ''; $info = array(); // Установка кодировки соединения if ($this->mysql_version > 40101 && (CHARSET != 'auto' || $this->forced_charset)) { // Кодировка по умолчанию, если в дампе не указана кодировка mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error($TEXT_DUMPER_CHARSET_ERROR . "<br />" . mysql_error(), E_USER_ERROR); echo tpl_l($TEXT_DUMPER_CHARSET . "`" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } else { $last_charset = ''; } $last_showed = ''; while (($str = $this->fn_read_str($fp)) !== false) { if (empty($str) || preg_match("/^(#|--)/", $str)) { if (!$is_skd && preg_match("/^#SKD101\\|/", $str)) { $info = explode("|", $str); echo tpl_s(0, $t / $info[4]); $is_skd = 1; } continue; } $query_len += strlen($str); if (!$insert && preg_match("/^(INSERT INTO `?([^` ]+)`? .*?VALUES)(.*)\$/i", $str, $m)) { if ($table != $m[2]) { $table = $m[2]; $tabs++; $cache .= tpl_l("Таблица `{$table}`."); $last_showed = $table; $i = 0; if ($is_skd) { echo tpl_s(100, $t / $info[4]); } } $insert = $m[1] . ' '; $sql .= $m[3]; $index++; $info[$index] = isset($info[$index]) ? $info[$index] : 0; $limit = round($info[$index] / 20); $limit = $limit < 300 ? 300 : $limit; if ($info[$index] > $limit) { echo $cache; $cache = ''; echo tpl_s(0 / $info[$index], $t / $info[4]); } } else { $sql .= $str; if ($insert) { $i++; $t++; if ($is_skd && $info[$index] > $limit && $t % $limit == 0) { echo tpl_s($i / $info[$index], $t / $info[4]); } } } if (!$insert && preg_match("/^CREATE table (IF NOT EXISTS )?`?([^` ]+)`?/i", $str, $m) && $table != $m[2]) { $table = $m[2]; $insert = ''; $tabs++; $is_create = true; $i = 0; } if ($sql) { if (preg_match("/;\$/", $str)) { $sql = rtrim($insert . $sql, ";"); if (empty($insert)) { if ($this->mysql_version < 40101) { $sql = preg_replace("/ENGINE\\s?=/", "type=", $sql); } elseif (preg_match("/CREATE table/i", $sql)) { // Выставляем кодировку соединения if (preg_match("/(CHARACTER SET|CHARSET)[=\\s]+(\\w+)/i", $sql, $charset)) { if (!$this->forced_charset && $charset[2] != $last_charset) { if (CHARSET == 'auto') { mysql_query("SET NAMES '" . $charset[2] . "'") or trigger_error($TEXT_DUMPER_CHARSET_ERROR . "<br />{$sql}<br />" . mysql_error(), E_USER_ERROR); $cache .= tpl_l($TEXT_DUMPER_CHARSET . "`" . $charset[2] . "`.", C_WARNING); $last_charset = $charset[2]; } else { $cache .= tpl_l($TEXT_DUMPER_CHARSET_COLLATION, C_ERROR); $cache .= tpl_l($TEXT_DUMPER_TABLE . '`' . $table . '` -> ' . $charset[2] . ' (' . $TEXT_DUMPER_CONNECT1 . $this->restore_charset . ')', C_ERROR); } } // Меняем кодировку если указано форсировать кодировку if ($this->forced_charset) { $sql = preg_replace("/(\\/\\*!\\d+\\s)?((COLLATE)[=\\s]+)\\w+(\\s+\\*\\/)?/i", '', $sql); $sql = preg_replace("/((CHARACTER SET|CHARSET)[=\\s]+)\\w+/i", "\\1" . $this->restore_charset . $this->restore_collate, $sql); } } elseif (CHARSET == 'auto') { // Вставляем кодировку для таблиц, если она не указана и установлена auto кодировка $sql .= ' DEFAULT CHARSET=' . $this->restore_charset . $this->restore_collate; if ($this->restore_charset != $last_charset) { mysql_query("SET NAMES '" . $this->restore_charset . "'") or trigger_error($TEXT_DUMPER_CHARSET_ERROR . "<br />{$sql}<br />" . mysql_error(), E_USER_ERROR); $cache .= tpl_l($TEXT_DUMPER_CHARSET . "`" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } } } if ($last_showed != $table) { $cache .= tpl_l($TEXT_DUMPER_TABLE . "`{$table}`."); $last_showed = $table; } } elseif ($this->mysql_version > 40101 && empty($last_charset)) { // Устанавливаем кодировку на случай если отсутствует CREATE table mysql_query("SET {$this->restore_charset} '" . $this->restore_charset . "'") or trigger_error(TEXT_DUMPER_CHARSET_ERROR . "<br />{$sql}<br />" . mysql_error(), E_USER_ERROR); echo tpl_l($TEXT_DUMPER_CHARSET . "`" . $this->restore_charset . "`.", C_WARNING); $last_charset = $this->restore_charset; } $insert = ''; $execute = 1; } if ($query_len >= 65536 && preg_match("/,\$/", $str)) { $sql = rtrim($insert . $sql, ","); $execute = 1; } if ($execute) { $q++; mysql_query($sql) or trigger_error(TEXT_DUMPER_QUERY_ERROR . "<br />" . mysql_error(), E_USER_ERROR); if (preg_match("/^insert/i", $sql)) { $aff_rows += mysql_affected_rows(); } $sql = ''; $query_len = 0; $execute = 0; } } } echo $cache; echo tpl_s(1, 1); echo tpl_l(str_repeat("-", 60)); echo tpl_l($TEXT_DUMPER_RESTORED, C_RESULT); if (isset($info[3])) { echo tpl_l($TEXT_DUMPER_DATE . "{$info[3]}", C_RESULT); } echo tpl_l($TEXT_DUMPER_QUERY_COUNT . "{$q}", C_RESULT); echo tpl_l($TEXT_DUMPER_TABLES_CREATED . "{$tabs}", C_RESULT); echo tpl_l(TEXT_DUMPER_STRINGS_CREATED . "{$aff_rows}", C_RESULT); $this->tabs = $tabs; $this->records = $aff_rows; $this->size = filesize(PATH . $this->filename); $this->comp = $this->SET['comp_method'] * 10 + $this->SET['comp_level']; echo "<script>document.getElementById('back').disabled = 0;</script>"; // Передача данных для глобальной статистики if (GS) { echo "<script>document.getElementById('GS').src = 'http://sypex.net/gs.php?r={$this->tabs},{$this->records},{$this->size},{$this->comp},108';</script>"; } $this->fn_close($fp); }