$Date: 2005-10-10 14:08:54 +0100 (Mon, 10 Oct 2005) $ | > $Revision: 23 $ | > $Author: matt $ +--------------------------------------------------------------------------- | | > mySQL Admin Stuff | > Module written by Matt Mecham | > Date started: 21st October 2002 | | > Module Version Number: 1.0.0 | > Music listen to when coding this: Martin Grech - Open Heart Zoo | > Talk about useless information! +-------------------------------------------------------------------------- */ if ( ! defined( 'IN_ACP' ) ) { print "

Неверный вход

У Вас нет доступа к директиве этого файла. Если Вы проводили обновления, убедитесь, что не забыли обновить 'admin.php'."; exit(); } @set_time_limit(1200); class ad_sql_module { var $base_url; var $mysql_version = ""; var $true_version = ""; var $str_gzip_header = "\x1f\x8b\x08\x00\x00\x00\x00\x00"; /** * Section title name * * @var string */ var $perm_main = "admin"; /** * Section title name * * @var string */ var $perm_child = "sql"; /*-------------------------------------------------------------------------*/ // Auto run module /*-------------------------------------------------------------------------*/ function auto_run() { //----------------------------------------- // Kill globals - globals bad, Homer good. //----------------------------------------- $tmp_in = array_merge( $_GET, $_POST, $_COOKIE ); foreach ( $tmp_in as $k => $v ) { unset($$k); } //----------------------------------------- // Make sure we're a root admin, or else! //----------------------------------------- if ($this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group']) { $this->ipsclass->admin->error("Извините, но эти функции только для администраторской группы"); } //----------------------------------------- // Get the mySQL version. //----------------------------------------- $this->ipsclass->DB->sql_get_version(); $this->true_version = $this->ipsclass->DB->true_version; $this->mysql_version = $this->ipsclass->DB->mysql_version; switch($this->ipsclass->input['code']) { case 'dotool': $this->run_tool(); break; case 'runtime': $this->view_sql("SHOW STATUS"); break; case 'system': $this->view_sql("SHOW VARIABLES"); break; case 'processes': $this->view_sql("SHOW PROCESSLIST"); break; case 'runsql': $q = $_POST['query'] == "" ? urldecode($_GET['query']) : $_POST['query']; $this->view_sql(trim(stripslashes($q))); break; case 'backup': $this->show_backup_form(); break; case 'safebackup': $this->sbup_splash(); break; case 'dosafebackup': $this->do_safe_backup(); break; case 'export_tbl': $this->do_safe_backup(trim(urldecode(stripslashes($_GET['tbl'])))); break; //----------------------------------------- default: $this->list_index(); break; } } //----------------------------------------- // Back up baby, back up //----------------------------------------- function do_safe_backup($tbl_name="") { if ($tbl_name == "") { // Auto all tables $skip = intval($this->ipsclass->input['skip']); $create_tbl = intval($this->ipsclass->input['create_tbl']); $enable_gzip = intval($this->ipsclass->input['enable_gzip']); $filename = 'ibf_dbbackup'; } else { // Man. click export $skip = 0; $create_tbl = 0; $enable_gzip = 1; $filename = $tbl_name; } $output = ""; @header("Pragma: no-cache"); $do_gzip = 0; if( $enable_gzip ) { $phpver = phpversion(); if($phpver >= "4.0") { if(extension_loaded("zlib")) { $do_gzip = 1; } } } if( $do_gzip != 0 ) { @ob_start(); @ob_implicit_flush(0); header("Content-Type: text/x-delimtext; name=\"$filename.sql.gz\""); header("Content-disposition: attachment; filename=$filename.sql.gz"); } else { header("Content-Type: text/x-delimtext; name=\"$filename.sql\""); header("Content-disposition: attachment; filename=$filename.sql"); } //----------------------------------------- // Get tables to work on //----------------------------------------- if ($tbl_name == "") { $tmp_tbl = $this->ipsclass->DB->get_table_names(); foreach($tmp_tbl as $tbl) { // Ensure that we're only peeking at IBF tables if ( preg_match( "/^".$this->ipsclass->vars['sql_tbl_prefix']."/", $tbl ) ) { // We've started our headers, so print as we go to stop // poss memory problems $this->get_table_sql($tbl, $create_tbl, $skip); } } } else { $this->get_table_sql($tbl_name, $create_tbl, $skip); } //----------------------------------------- // GZIP? //----------------------------------------- if($do_gzip) { $size = ob_get_length(); $crc = crc32(ob_get_contents()); $contents = gzcompress(ob_get_contents()); ob_end_clean(); echo $this->str_gzip_header .substr($contents, 0, strlen($contents) - 4) .$this->gzip_four_chars($crc) .$this->gzip_four_chars($size); } exit(); } //----------------------------------------- // Internal handler to return content from table //----------------------------------------- function get_table_sql($tbl, $create_tbl, $skip=0) { if ($create_tbl) { // Generate table structure if ( $this->ipsclass->input['addticks'] ) { $this->ipsclass->DB->query("SHOW CREATE TABLE `".$this->ipsclass->vars['sql_database'].".".$tbl."`"); } else { $this->ipsclass->DB->query("SHOW CREATE TABLE ".$this->ipsclass->vars['sql_database'].".".$tbl); } $ctable = $this->ipsclass->DB->fetch_row(); echo $this->sql_strip_ticks($ctable['Создать таблицу']).";\n"; } // Are we skipping? Woohoo, where's me rope?! if ($skip == 1) { if ($tbl == $this->ipsclass->vars['sql_tbl_prefix'].'admin_sessions' OR $tbl == $this->ipsclass->vars['sql_tbl_prefix'].'sessions' OR $tbl == $this->ipsclass->vars['sql_tbl_prefix'].'reg_anti_spam' OR $tbl == $this->ipsclass->vars['sql_tbl_prefix'].'search_results' ) { return $ret; } } // Get the data $this->ipsclass->DB->query("SELECT * FROM $tbl"); // Check to make sure rows are in this // table, if not return. $row_count = $this->ipsclass->DB->get_num_rows(); if ($row_count < 1) { return TRUE; } //----------------------------------------- // Get col names //----------------------------------------- $f_list = ""; $fields = $this->ipsclass->DB->get_result_fields(); $cnt = count($fields); for( $i = 0; $i < $cnt; $i++ ) { $f_list .= $fields[$i]->name . ", "; } $f_list = preg_replace( "/, $/", "", $f_list ); while ( $row = $this->ipsclass->DB->fetch_row() ) { //----------------------------------------- // Get col data //----------------------------------------- $d_list = ""; for( $i = 0; $i < $cnt; $i++ ) { if ( ! isset($row[ $fields[$i]->name ]) ) { $d_list .= "NULL,"; } elseif ( $row[ $fields[$i]->name ] != '' ) { $d_list .= "'".$this->sql_add_slashes($row[ $fields[$i]->name ]). "',"; } else { $d_list .= "'',"; } } $d_list = preg_replace( "/,$/", "", $d_list ); echo "INSERT INTO $tbl ($f_list) VALUES($d_list);\n"; } return TRUE; } //----------------------------------------- // sql_strip_ticks from field names //----------------------------------------- function sql_strip_ticks($data) { return str_replace( "`", "", $data ); } //----------------------------------------- // Add slashes to single quotes to stop sql breaks //----------------------------------------- function sql_add_slashes($data) { $data = str_replace('\\', '\\\\', $data); $data = str_replace('\'', '\\\'', $data); $data = str_replace("\r", '\r' , $data); $data = str_replace("\n", '\n' , $data); return $data; } //----------------------------------------- // Almost there! //----------------------------------------- function sbup_splash() { $this->ipsclass->admin->page_detail = "В этой секции, Вы можете произвести резервную копию Вашей базы данных."; $this->ipsclass->admin->page_title = "mySQL ".$this->true_version." Back Up"; // Check for mySQL version.. // Might change at some point.. if ( $this->mysql_version < 3232 ) { $this->ipsclass->admin->error("Извините, но версия mySQL ниже, чем 3.23.21 и Вы не сможете осуществить резервное копирование"); } $this->ipsclass->adskin->td_header[] = array( " " , "100%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Простое копирование" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "Резервное копирование базы mySQL

После того, как Вы нажмёте на ссылку ниже, необходимо будет подождать, пока Ваш браузер не загрузит следующую страницу. Время загрузки может затянуться на несколько минут, в зависимости от размера копируемой базы данных.

ipsclass->input['addticks']}&skip={$this->ipsclass->input['skip']}&enable_gzip={$this->ipsclass->input['enable_gzip']}'>Нажмите сюда для начала резервного копирования" ) ); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); $this->ipsclass->admin->output(); } function show_backup_form() { $this->ipsclass->admin->page_detail = "Эта секция позволит Вам сделать резервное копирование базы данных форума.

Простое копирование
Эта функция компилирует файл-копию базы, с дальнейшими подсказками на страницах. Это полезно, если Ваш хостер использует безопасный режим PHP, но может использоваться только с небольшими базами данных. "; $this->ipsclass->admin->page_title = "mySQL ".$this->true_version." резервная копия"; // Check for mySQL version.. // Might change at some point.. if ( $this->mysql_version < 3232 ) { $this->ipsclass->admin->error("Извините, но версия mySQL ниже, чем 3.23.21 и Вы не сможете осуществить резервное копирование"); } $this->ipsclass->adskin->td_header[] = array( " " , "60%" ); $this->ipsclass->adskin->td_header[] = array( " " , "40%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'act' , 'sql' ), 2 => array( 'code' , 'safebackup'), 4 => array( 'section', $this->ipsclass->section_code ), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Просто копирование" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "Добавить команду 'CREATE TABLE'?
Добавить обратные кавычки в названиях таблиц?
(включите это, если у Вас выскакивает ошибка mySQL) ", $this->ipsclass->adskin->form_yes_no( 'create_tbl', 1), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "Пропустить не существенные данные?
Такие данные, как ibf_sessions, ibf_admin_sessions, ibf_search_results, ibf_reg_anti_spam, не будут добавлены.", $this->ipsclass->adskin->form_yes_no( 'skip', 1), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "Сжать в GZIP?
Если GZIP включён, то размер файла-копии будет сжат на более меньший размер.", $this->ipsclass->adskin->form_yes_no( 'enable_gzip', 1), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Начать резервное копирование"); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); $this->ipsclass->admin->output(); } //----------------------------------------- // Run mySQL queries //----------------------------------------- function view_sql($sql) { $limit = 50; $start = intval($this->ipsclass->input['st']) == "" ? 0 : intval($this->ipsclass->input['st']); $pages = ""; $this->ipsclass->admin->page_detail = "Эта секция для управления вашей базой данных mySQL.$extra"; $this->ipsclass->admin->page_title = "mySQL ".$this->true_version." (управление)"; $map = array( 'processes' => "SQL Процессы", 'runtime' => "Информация SQL Runtime", 'system' => "Переменные SQL", ); if ($map[ $this->ipsclass->input['code'] ] != "") { $tbl_title = $map[ $this->ipsclass->input['code'] ]; $man_query = 0; } else { $tbl_title = "Самостоятельный запрос"; $man_query = 1; } //----------------------------------------- if ($man_query == 1) { $this->ipsclass->adskin->td_header[] = array( " " , "100%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'act' , 'sql' ), 2 => array( 'code' , 'runsql'), 4 => array( 'section', $this->ipsclass->section_code ), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Запуск запроса" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "
".$this->ipsclass->adskin->form_textarea("query", $sql )."
" ) ); $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Запуск нового запроса"); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); // Check for drop, create and flush if ( preg_match( "/^DROP|CREATE|FLUSH/i", trim($sql) ) ) { $this->ipsclass->admin->error = "Извините, в целях Вашей безопасности этот запрос не разрешен"; } } //----------------------------------------- $this->ipsclass->DB->return_die = 1; $this->ipsclass->DB->query($sql,1); // Check for errors.. if ( $this->ipsclass->DB->error != "") { $this->ipsclass->adskin->td_header[] = array( " " , "100%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Ошибка SQL" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array($this->ipsclass->DB->error) ); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); $this->ipsclass->admin->output(); // End output and script } if ( preg_match( "/^INSERT|UPDATE|DELETE|ALTER/i", trim($sql) ) ) { // We can't show any info, and if we're here, there isn't // an error, so we're good to go. $this->ipsclass->adskin->td_header[] = array( " " , "100%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "SQL запрос успешно завершен" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("Query: $sql
Выполнено успешно!") ); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); $this->ipsclass->admin->output(); // End output and script } else if ( preg_match( "/^SELECT/i", $sql ) ) { // Sort out the pages and stuff // auto limit if need be if ( ! preg_match( "/LIMIT[ 0-9,]+$/i", $sql ) ) { $rows_returned = $this->ipsclass->DB->get_num_rows(); if ($rows_returned > $limit) { // Get tbl name //$tbl_name = preg_replace( "/(".$this->ipsclass->vars['sql_tbl_prefix']."\S+?)([\s\.,]|$)/i", "\\1", $sql ); // Set up pages. $links = $this->ipsclass->build_pagelinks( array( 'TOTAL_POSS' => $rows_returned, 'PER_PAGE' => $limit, 'CUR_ST_VAL' => $start, 'L_SINGLE' => "Одна страница", 'L_MULTI' => "Страницы: ", 'BASE_URL' => $this->ipsclass->base_url."&{$this->ipsclass->form_code}&code=runsql&query=".urlencode($sql), ) ); $sql .= " LIMIT $start, $limit"; // Re-run with limit $this->ipsclass->DB->query($sql, 1); /// bypass table swapping } } } $fields = $this->ipsclass->DB->get_result_fields(); $cnt = count($fields); // Print the headers - we don't what or how many so... for( $i = 0; $i < $cnt; $i++ ) { $this->ipsclass->adskin->td_header[] = array( $fields[$i]->name , "*" ); } $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Результат: ".$tbl_title ); if ($links != "") { $pages = $this->ipsclass->adskin->add_td_basic( $links, 'left', 'tdrow2' ); $this->ipsclass->html .= $pages; } while( $r = $this->ipsclass->DB->fetch_row() ) { // Grab the rows - we don't what or how many so... $rows = array(); for( $i = 0; $i < $cnt; $i++ ) { if ($man_query == 1) { // Limit output if ( strlen($r[ $fields[$i]->name ]) > 200 ) { $r[ $fields[$i]->name ] = substr($r[ $fields[$i]->name ], 0, 200) .'...'; } } $rows[] = wordwrap( htmlspecialchars(nl2br($r[ $fields[$i]->name ])) , 50, "
", 1 ); } $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( $rows ); } $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); //----------------------------------------- $this->ipsclass->admin->output(); } //----------------------------------------- // I'm A TOOL! //----------------------------------------- function run_tool() { $this->ipsclass->admin->page_detail = "Эта секция позволит вам администрировать вашу базу данных.$extra"; $this->ipsclass->admin->page_title = "mySQL ".$this->true_version." Утилита"; //----------------------------------------- // have we got some there tables me laddo? //----------------------------------------- $tables = array(); foreach ($this->ipsclass->input as $key => $value) { if ( preg_match( "/^tbl_(\S+)$/", $key, $match ) ) { if ($this->ipsclass->input[$match[0]]) { $tables[] = $match[1]; } } } if ( count($tables) < 1 ) { $this->ipsclass->admin->error("Вы должны выбрать какую-нибудь таблицу, чтобы запустить этот запрос иначе ничего не выйдет"); } //----------------------------------------- // What tool is one running? // optimize analyze check repair //----------------------------------------- if (strtoupper($this->ipsclass->input['tool']) == 'DROP' || strtoupper($this->ipsclass->input['tool']) == 'CREATE' || strtoupper($this->ipsclass->input['tool']) == 'FLUSH') { $this->ipsclass->admin->error("Вы не можете делать этого, извините"); } foreach($tables as $table) { $this->ipsclass->DB->query(strtoupper($this->ipsclass->input['tool'])." TABLE $table"); $fields = $this->ipsclass->DB->get_result_fields(); $data = $this->ipsclass->DB->fetch_row(); $cnt = count($fields); // Print the headers - we don't what or how many so... for( $i = 0; $i < $cnt; $i++ ) { $this->ipsclass->adskin->td_header[] = array( $fields[$i]->name , "*" ); } $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Результат: ".$this->ipsclass->input['tool']." ".$table ); // Grab the rows - we don't what or how many so... $rows = array(); for( $i = 0; $i < $cnt; $i++ ) { $rows[] = $data[ $fields[$i]->name ]; } $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( $rows ); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); } //----------------------------------------- $this->ipsclass->admin->output(); } //----------------------------------------- // SHOW ALL TABLES AND STUFF! // 5 hours ago this seemed like a damned good idea. //----------------------------------------- function list_index() { $form_array = array(); if ( $this->mysql_version < 3232 ) { $extra = "
Примечание: версия вашей mySQL ограниченная и возможно некоторые функции были удалены"; } $this->ipsclass->admin->page_detail = "Эта секция позволит вам администрировать вашу базу данных.$extra"; $this->ipsclass->admin->page_title = "SQL ".$this->true_version." Утилита"; //----------------------------------------- // Show advanced stuff for mySQL > 3.23.03 //----------------------------------------- $idx_size = 0; $tbl_size = 0; $this->ipsclass->html .= " "; $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'act' , 'sql' ), 2 => array( 'code' , 'dotool'), 4 => array( 'section', $this->ipsclass->section_code ), ) , "theForm" ); if ( $this->mysql_version >= 3230 ) { $this->ipsclass->adskin->td_header[] = array( "Таблица" , "20%" ); $this->ipsclass->adskin->td_header[] = array( "Рядов" , "10%" ); $this->ipsclass->adskin->td_header[] = array( "Экспорт" , "10%" ); $this->ipsclass->adskin->td_header[] = array( '' , "10%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Таблицы Invision Power Board" ); $this->ipsclass->DB->query("SHOW TABLE STATUS FROM `".$this->ipsclass->vars['sql_database']."`"); while ( $r = $this->ipsclass->DB->fetch_row() ) { // Check to ensure it's a table for this install... if ( ! preg_match( "/^".$this->ipsclass->vars['sql_tbl_prefix']."/", $r['Name'] ) ) { continue; } $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "{$r['Name']}", "
{$r['Rows']}
", "
Экспорт
", "
", ) ); } } else { // display a basic information table $this->ipsclass->adskin->td_header[] = array( "Таблица" , "60%" ); $this->ipsclass->adskin->td_header[] = array( "Ячейки" , "30%" ); $this->ipsclass->adskin->td_header[] = array( '' , "10%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Таблицы Invision Power Board" ); $tables = $this->ipsclass->DB->get_table_names(); foreach($tables as $tbl) { // Ensure that we're only peeking at IBF tables if ( ! preg_match( "/^".$this->ipsclass->vars['sql_tbl_prefix']."/", $tbl ) ) { continue; } $this->ipsclass->DB->query("SELECT COUNT(*) AS Rows FROM $tbl"); $cnt = $this->ipsclass->DB->fetch_row(); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "$tbl", "
{$cnt['Рядов']}
", "
", ) ); } } //----------------------------------------- // Add in the bottom stuff //----------------------------------------- if ( $this->mysql_version < 3232 ) { $this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic( " ", "center", "tdrow2" ); } else { $this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic( " ", "center", "tdrow2" ); } $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); //----------------------------------------- $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'act' , 'sql' ), 2 => array( 'code' , 'runsql'), 4 => array( 'section', $this->ipsclass->section_code ), ) ); $this->ipsclass->adskin->td_header[] = array( "{none}" , "30%" ); $this->ipsclass->adskin->td_header[] = array( "{none}" , "70%" ); $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Запуск запроса" ); $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "Самостоятельный запрос
Только для опытных пользователей", $this->ipsclass->adskin->form_textarea("query", "" ), ) ); $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Запуск запроса"); $this->ipsclass->html .= $this->ipsclass->adskin->end_table(); //----------------------------------------- $this->ipsclass->admin->output(); } function gzip_four_chars($val) { for ($i = 0; $i < 4; $i ++) { $return .= chr($val % 256); $val = floor($val / 256); } return $return; } } ?>