function index() { global $db; global $config; global $dbname; $tables = $db->queryColumn('show tables'); $sql = null; $table = _get('table'); $where = _get('where', array()); if ($table) { $sql = build_table_sql($table, $where); $pkey = get_pkey($table); } if (empty($sql)) { $sql = _get('sql'); if (preg_match('/from\\s+`?(\\w+)`?/i', $sql, $matches)) { $table = $matches[1]; $pkey = get_pkey($table); } } if (empty($sql) || is_read($sql)) { $err = null; try { $table_data = $sql ? $db->queryAll($sql, $where) : []; } catch (PdoException $e) { $err = $e->errorInfo; } $fkt = $config['foreignkeys']; $dbname = $dbname; $data = compact('tables', 'table_data', 'table', 'sql', 'pkey', 'dbname', 'err', 'fkt', 'rowCount', 'where'); render(__DIR__ . '/view/index.html', $data, LAYOUT); } else { exec_sql(); } }
function test_query_execution_time($sql, $debug = false, $output = false) { $start = microtime(true); $q = exec_sql($sql); $time = microtime(true) - $start; if ($debug) { $debug = "{$sql}<br/>{$time}<br/><br/>"; if ($output) { print $debug; } else { log_query($debug); } } return $q; }
function setup() { /** ######################################################################################### **/ /** CONNECTION TO THE MYSQL's SERVER **/ /** ######################################################################################### **/ $link = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD); if (mysqli_connect_errno()) { echo "F**K ! A wild error appeared : " . mysqli_connect_error(); } /** ######################################################################################### **/ /** CREATING AND SELECTING THE DATABASE **/ /** ######################################################################################### **/ exec_sql($link, "CREATE DATABASE IF NOT EXISTS " . DATABASE_NAME); mysqli_select_db($link, DATABASE_NAME); /** ######################################################################################### **/ /** CREATING THE TABLE **/ /** ######################################################################################### **/ $query = "CREATE TABLE IF NOT EXISTS PLAYERS(ID int(11) NOT NULL AUTO_INCREMENT,NAME varchar(50) NOT NULL,\n\t\t\tACTIVE BOOL NOT NULL DEFAULT '0',\n\t\t\tCOLORS varchar(50) DEFAULT NULL,\n\t\t\tPOSITION int(11) DEFAULT 0,\n\t\t\tGAMES int(11) DEFAULT 0,\n\t\t\tSCORES int(11) DEFAULT 0,\n\t\t\tGOLD int(11) DEFAULT 0,\n\t\t\tWAVES int(11) DEFAULT 0,\n\t\t\tKILLS int(11) DEFAULT 0,\n\t\t\tTOWERS int(11) DEFAULT 0,\n\t\t\tSHOOTS int(11) DEFAULT 0,\n\t\t\tBEST_SCORES int(11) DEFAULT 0,\n\t\t\tBEST_GOLD int(11) DEFAULT 0,\n\t\t\tBEST_WAVES int(11) DEFAULT 0,\n\t\t\tBEST_KILLS int(11) DEFAULT 0,\n\t\t\tBEST_TOWERS int(11) DEFAULT 0,\n\t\t\tBEST_SHOOTS int(11) DEFAULT 0,\n\t\t\tCURRENT_SCORES TEXT,\n\t\t\tCURRENT_GOLD TEXT,\n\t\t\tCURRENT_WAVES TEXT,\n\t\t\tCURRENT_KILLS TEXT,\n\t\t\tCURRENT_TOWERS TEXT,\n\t\t\tCURRENT_SHOOTS TEXT,\n\t\t\tprimary key (ID));"; exec_sql($link, $query); /** ######################################################################################### **/ /** CLOSING THE CONNECTION **/ /** ######################################################################################### **/ mysqli_close($link); }
function check_all($install = NULL) { $db_server = get_input("db_server"); $db_port = get_input("db_port"); $db_username = get_input("db_username"); $db_password = get_input("db_password"); $db_schema = get_input("db_schema"); $adm_username = get_secure_input("adm_username"); $adm_email = get_secure_input("adm_email"); $adm_realname = get_secure_input("adm_realname"); $adm_password = get_secure_input("adm_password"); $adm_confirmpassword = get_secure_input("adm_confirmpassword"); $hide_index = get_secure_input("hide_index"); $gzip_compression = get_secure_input("gzip_compression"); // Main program $success = true; $errors = array(); $warnings = array(); // curl if (!in_array('curl', get_loaded_extensions())) { $warnings[] = 'CURL is not enabled. Some modules might require it'; } // database $result = check_db($db_server, $db_port, $db_username, $db_password, $db_schema); if (!$result['success']) { $success = FALSE; } if ($result['error_message'] != '') { $errors[] = $result['error_message']; } if ($result['warning_message'] != '') { $warnings[] = $result['warning_message']; } // writable if (!is_writable('../assets/caches')) { $success = FALSE; $errors[] = "Asset cache directory (assets/caches) is not writable"; } if (!is_writable('../application/config/database.php')) { $success = FALSE; $errors[] = "application/config/database.php is not writable"; } if (!is_writable('../application/config/routes.php')) { $success = FALSE; $errors[] = "application/config/routes.php is not writable"; } if (!is_writable('../application/config/config.php')) { $success = FALSE; $errors[] = "application/config/config.php is not writable"; } if (!is_writable('../assets/grocery_crud/js/jquery_plugins/config/jquery.ckeditor.config.js')) { $success = FALSE; $errors[] = 'assets/grocery_crud/js/jquery_plugins/config/jquery.ckeditor.config.js is not writable'; } if (!is_writable('./')) { $success = FALSE; $errors[] = 'install directory is not writable'; } if ($hide_index !== "") { if (!is_writable('../')) { $success = FALSE; $errors[] = "No-CMS directory is not writeable, we can't make .htaccess there"; } if (!is_mod_rewrite_active()) { $success = FALSE; $errors[] = "mod_rewrite is not enabled"; } } // admin password if ($adm_password == "") { $success = FALSE; $errors[] = "Admin's password is empty"; } if ($adm_password != $adm_confirmpassword) { $success = FALSE; $errors[] = "Admin's password confirmation doesn't match"; } // if not installed, than just return the warnings, errors and success if (!isset($install)) { $data = array("success" => $success, "errors" => $errors, "warnings" => $warnings); return $data; } else { // installation if (!$success) { // redirect if not success return false; } else { // perform installation // connection $db_connection = mysql_connect($db_server . ':' . $db_port, $db_username, $db_password); $db_exists = mysql_select_db($db_schema, $db_connection); if (!$db_exists) { $query = 'CREATE DATABASE ' . $db_schema . ' DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;'; exec_sql($query, $db_connection); mysql_select_db($db_schema, $db_connection); } // database.sql $sql = file_get_contents('./resources/database.sql'); $sql = replace($sql, array('@adm_username', '@adm_email', '@adm_password', '@adm_realname'), array($adm_username, $adm_email, md5($adm_password), $adm_realname)); $queries = explode('/*split*/', $sql); foreach ($queries as $query) { exec_sql($query, $db_connection); } // database.php $str = file_get_contents('./resources/database.php'); $str = replace($str, array('@db_server', '@db_port', '@db_username', '@db_password', '@db_schema'), array($db_server, $db_port, $db_username, $db_password, $db_schema)); file_put_contents('../application/config/database.php', $str); @chmod('../application/config/database.php', 0555); // routes.php $str = file_get_contents('./resources/routes.php'); file_put_contents('../application/config/routes.php', $str); @chmod('../application/config/routes.php', 0555); // jquery.ckeditor.config.js $str = file_get_contents('./resources/jquery.ckeditor.config.js'); $base_path = get_base_url(); $str = replace($str, array('@base_path'), array($base_path)); file_put_contents('../assets/grocery_crud/js/jquery_plugins/config/jquery.ckeditor.config.js', $str); @chmod('../assets/grocery_crud/js/jquery_plugins/config/jquery.ckeditor.config.js', 0555); // config.php $key_config = array(); $replace_config = array(); if ($gzip_compression != "") { $key_config[] = '@gzip'; $replace_config[] = 'TRUE'; } else { $key_config[] = '@gzip'; $replace_config[] = 'FALSE'; } if ($hide_index !== "") { $key_config[] = '@index_page'; $replace_config[] = ''; } else { $key_config[] = '@index_page'; $replace_config[] = 'index.php'; } $str = file_get_contents('./resources/config.php'); $str = replace($str, $key_config, $replace_config); file_put_contents('../application/config/config.php', $str); @chmod('../application/config/config.php', 0555); // .htaccess if ($hide_index !== "") { $str = file_get_contents('./resources/htaccess'); $str = replace($str, array('@base_path'), array($base_path)); file_put_contents('../.htaccess', $str); @chmod('../.htaccess', 0555); } else { file_put_contents('../.htaccess', ''); @chmod('../.htaccess', 0555); } // put htaccess in install directory file_put_contents('.htaccess', 'Deny from all'); @chmod('.htaccess', 0555); return true; } } }
} else { define('ON_SAE', 0); } $c = $config['db']; if (!ON_SAE) { $c['dbname'] = ''; } Pdb::setConfig($c); $histories = array(); $sqls = explode(';', file_get_contents('install.sql')); foreach ($sqls as $sql) { exec_sql($sql); } $sqls = explode(';', file_get_contents('default_data.sql')); foreach ($sqls as $sql) { exec_sql($sql); } function dd($str) { echo "<p>{$str}</p>\n"; } function exec_sql($sql = '') { if (ON_SAE && preg_match('/USE|CREATE\\sDATABASE/', $sql)) { return; } Pdb::exec($sql); $GLOBALS['histories'][] = $sql; } ?> <p>install ok</p>
#!/usr/bin/php <?php set_include_path('../site'); include_once 'include/database.php'; unset($config['database']['log_sql']); exec_sql("DELETE FROM users WHERE date_verified IS NULL AND " . "DATEDIFF( NOW(), date_registered ) >= 7");
function update_where($table, $fields, $where) { global $dbh; $sets = array(); foreach (array_keys($fields) as $field) { if (isset($fields[$field])) { array_push($sets, sprintf("%s='%s'", $field, mysql_real_escape_string($fields[$field], $dbh))); } else { array_push($sets, sprintf("%s=NULL", $field)); } } $sql = "UPDATE {$table} SET " . join(', ', $sets) . " WHERE {$where}"; exec_sql($sql); }
function add_categories_sql($title, $firstname, $name, $desc, $age, $price, $categories, $stock) { $title = protect_sql($title, "none"); $firstname = protect_sql($firstname, "none"); $name = protect_sql($name, "none"); $desc = protect_sql($desc, "none"); $age = protect_sql($age, "intval"); $price = protect_sql($price, "intval"); $tab = array(); foreach ($categories as $value) { if ($value >= 1 && $value <= 3) { $tab['pool'] = $value; $tab['pool'] = protect_sql($tab['pool'], "intval"); } else { if ($value >= 4 && $value <= 5) { $tab['year'] = $value; $tab['year'] = protect_sql($tab['year'], "intval"); } else { if ($value >= 6 && $value <= 7) { $tab['gender'] = $value; $tab['gender'] = protect_sql($tab['gender'], "intval"); } } } } $stock = protect_sql($stock, "intval"); $sql = 'INSERT INTO articles VALUES ("", "' . $title . '", "' . $firstname . '", "' . $name . '", "' . $desc . '", ' . $age . ', ' . $price . ', ' . $tab['pool'] . ', ' . $tab['year'] . ', ' . $tab['gender'] . ', ' . $stock . ')'; if (exec_sql($sql)) { return 1; } else { return 0; } }
function clean($table) { /** ######################################################################################### **/ /** CONNECTION TO THE MYSQL's SERVER **/ /** ######################################################################################### **/ $link = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, DATABASE_NAME); /** ######################################################################################### **/ /** CLEANING THE TABLE **/ /** ######################################################################################### **/ $query = "DELETE FROM " . $table . ";"; exec_sql($link, $query); /** ######################################################################################### **/ /** CLOSING THE CONNECTION **/ /** ######################################################################################### **/ mysqli_close($link); }
$code = substr(filter_input(INPUT_POST, 'code', FILTER_UNSAFE_RAW), 0, 15 * 1024); if (!$code || !$lang) { die("arg error"); } if (!in_array($lang, $support_lang)) { $lang = 'php'; } $db = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME); if ($db->connect_error) { die("Fail to connect db"); } # 查询IP的上次提交时间,限制1分钟提交一次代码. $sql = "SELECT count(`ip`) FROM " . TB_LOGIN . " WHERE `ip`=? "; if (exec_sql($db, $sql, $ip) != 0) { $sql = "SELECT TIMESTAMPDIFF(SECOND,`last`,now()) AS ltime FROM " . TB_LOGIN . " WHERE `ip`=?"; if ($time_limit && ($dif = exec_sql($db, $sql, $ip)) <= 60) { die("Retry 1 minute later."); } } $sql = "INSERT INTO " . TB_LOGIN . " SET `ip`=? ON DUPLICATE KEY UPDATE `last`=now(),`n`=`n`+1 "; $res = $db->prepare($sql); $res->bind_param("s", $ip); $res->execute(); # 代码存入数据库 $uuid = uuid4(); $file = gen_path($uuid); #insert code $sql = "INSERT INTO " . TB_CODE . "(`num`,`op`,`src`,`img`,`lang`) VALUES(?,?,?,?,?)"; $res = $db->prepare($sql); $res->bind_param("sssss", $uuid, $ip, $code, $file, $lang); $res->execute();
function process_tinyadm() { global $db; @session_start(); remove_magic_quotes(); if (!isset($_SESSION['user'])) { $_SESSION['user'] = ''; } if (!isset($_SESSION['password'])) { $_SESSION['password'] = ''; } if (!isset($_SESSION['database'])) { $_SESSION['database'] = ''; } if (!isset($_SESSION['table'])) { $_SESSION['table'] = ''; } if (!isset($_SESSION['last_sql'])) { $_SESSION['last_sql'] = ''; } if (!isset($_SESSION['sql_history'])) { $_SESSION['sql_history'] = array(); } $act = get_var('act'); if ($act == 'login') { setcookie('tinymy_user', get_var('user'), time() + 5184000); // 2 months $_SESSION['user'] = addslashes(get_var('user')); $_SESSION['password'] = addslashes(get_var('password')); } $db = new sqldb($_SESSION['user'], $_SESSION['password'], $_SESSION['database']); if (!$db->is_connected()) { return draw_login_form(); } if ($act == 'login') { // switch to default databas if (get_cookie('tinymy_database')) { $_SESSION['database'] = get_cookie('tinymy_database'); } } switch ($act) { case 'sel_db': $_SESSION['database'] = get_var('d'); $_SESSION['table'] = ''; setcookie('tinymy_database', get_var('d'), time() + 5184000); // 2 months redirect_self(); exit; case 'use_history': $idx = (int) get_var('idx'); if (isset($_SESSION['sql_history'][$idx])) { $_SESSION['database'] = $_SESSION['sql_history'][$idx]['db']; $_SESSION['last_sql'] = $_SESSION['sql_history'][$idx]['sql']; } redirect_self(); exit; case 'sel_table': $_SESSION['table'] = get_var('table'); break; case 'do_export': ob_end_clean(); // we need to pass through the following output from export immediately, without caching do_export(); break; case 'logout': session_unset(); session_destroy(); redirect_self(); exit; case 'exec_sql': history_add(get_var('sql')); } ob_start(); // menu needs to be created after the possible sql has executed echo '<div id="content">'; if ($act != 'export' && $act != 'do_export') { draw_sqlarea(); } switch ($act) { case 'history': draw_history(); break; case 'export': draw_export(); break; case 'sel_db': break; case 'sel_table': case 'show_structure': h('<p style="margin-bottom: 8px;"><a href="?act=show_contents">Show contents of %s</a></p>', $_SESSION['table']); exec_sql_internal(sprintf('desc `%s`', mysqli_escape_string($db->conn_id, $_SESSION['table']))); exec_sql_singlerow(sprintf('show create table `%s`', mysqli_escape_string($db->conn_id, $_SESSION['table']))); break; case 'show_contents': h('<p style="margin-bottom: 8px;"><a href="?act=show_structure">Show structure of %s</a></p>', $_SESSION['table']); $res = mysqli_query($db->conn_id, sprintf("select count(*) from `%s`", mysqli_escape_string($db->conn_id, $_SESSION['table']))); if (!$res) { $db->error(); // } else { list($reccount) = mysqli_fetch_row($res); pager($reccount); exec_sql_internal(sprintf('select * from `%s` %s', mysqli_escape_string($db->conn_id, $_SESSION['table']), pager_limits())); } case 'exec_sql': exec_sql(); // in case the query changed the database, switch to it $cur_database = $db->get_current_database(); if ($cur_database != $_SESSION['database']) { $_SESSION['database'] = $cur_database; setcookie('tinymy_database', $cur_database, time() + 5184000); // 2 months } break; } echo '</div>'; // content $content = ob_get_contents(); ob_end_clean(); // menu needs to be created after all the sql has executed draw_db_menu(); echo $content; }
function cache_bus_pos($bus, $reversed) { $sql = "select * from `busnow` where `line` = '{$bus}' and `reversed` = {$reversed}"; $row = query_sql_row($sql); $timestamp = time(); if ($row && $GLOBALS['CACHE']) { //return $timestamp-$row['timestamp']; if ($timestamp - $row['timestamp'] < $GLOBALS['CACHE_TIME']) { $bus_pos = json_decode($row['position'], true); $count = $row['count'] + 1; $sql = "update `busnow` set `count`={$count} where `line`='{$bus}' and `reversed`= {$reversed}"; exec_sql($sql); } else { $bus_info = get_bus_info($bus, $reversed); $bus_pos = __get_bus_pos($bus_info['info'], $reversed); $tmp = a2j_encode($bus_pos); $count = $row['count'] + 1; $sql = "update `busnow` set `position` = '{$tmp}',`timestamp`='{$timestamp}',`count`={$count} where `line`='{$bus}' and `reversed`= {$reversed}"; exec_sql($sql); } } else { $bus_info = get_bus_info($bus, $reversed); $bus_pos = __get_bus_pos($bus_info['info'], $reversed); if ($GLOBALS['CACHE']) { $tmp = a2j_encode($bus_pos); $count = $row['count'] + 1; // 再次检查是否有数据 $sql = "select * from `busnow` where `line` = '{$bus}' and `reversed` = {$reversed}"; $row = query_sql_row($sql); if (!$row) { $sql = "insert into `busnow`(`line`, `reversed`,`position`,`timestamp`,`count`)values('{$bus}', {$reversed}, '{$tmp}', '{$timestamp}', 1)"; exec_sql($sql); } } } return $bus_pos; }