Beispiel #1
0
function plogger_stats_count_total_comments()
{
    $query = "SELECT COUNT(*) AS `n` FROM `" . PLOGGER_TABLE_PREFIX . "comments` WHERE approved = 1";
    $result = run_query($query);
    $num_comments = mysqli_result($result, 0, 'n');
    echo $num_comments . ' ';
    echo $num_comments == 1 ? plog_tr('comment') : plog_tr('comments');
}
function plogger_stats_count_total_comments()
{
    $query = "SELECT COUNT(*) AS \"n\" FROM \"" . PLOGGER_TABLE_PREFIX . "comments\" WHERE approved = 1";
    $result = run_query($query);
    $num_comments = $result->fetch()['n'];
    echo $num_comments . ' ';
    echo $num_comments == 1 ? plog_tr('comment') : plog_tr('comments');
}
function fetch_url($product)
{
    $sql = "SELECT link FROM product WHERE prod_name= '" . $product . "'";
    $result = run_query($sql);
    while ($row = mysqli_fetch_assoc($result)) {
        $url = $row['link'];
    }
    return $url;
}
Beispiel #4
0
function exec_query($conn, $query)
{
    $res = run_query($conn, $query);
    while ($row = mysql_fetch_assoc($res)) {
        $return[] = $row;
    }
    //   mysql_free_result($res);
    //   print_r($return);
    return $return;
}
function get_tag_by_id($tag_id)
{
    global $TABLE_PREFIX;
    $existing_tag = array();
    $tag_id = intval($tag_id);
    $query = 'SELECT `id`, `tag`, `urlified` FROM `' . $TABLE_PREFIX . 'tags` WHERE `id`=' . $tag_id;
    $result = run_query($query);
    $row = mysql_fetch_assoc($result);
    if (!is_array($row)) {
        return NULL;
    }
    return array('id' => $row['tag_id'], 'tag' => $row['tag'], 'urlified' => $row['urlified']);
}
Beispiel #6
0
function delete_bags($conn, $bags)
{
    if (!$bags) {
        return;
    }
    if (sizeof($bags) == 1) {
        $where = " id = {$bags[0]} ";
    } else {
        $where = " id in (" . implode(',', $bags) . ") ";
    }
    $query = "delete from bags where " . $where;
    print $query;
    run_query($conn, $query);
    print ".. DONE<br/>";
}
function process_report($report, $xml)
{
    $report = array();
    $sql = array();
    $query = array();
    $format = array();
    $result = array();
    foreach ($xml as $key => $value) {
        if ($key == 'title') {
            $title = $value;
        }
        if ($key == 'description') {
            $description = $value;
        }
        if ($key == 'query') {
            if (isset($value['_content'])) {
                $sql[$value['name']] = $value['_content'];
                $query[$value['name']] = $value['title'];
            } else {
                foreach ($value as $key_sql => $value_sql) {
                    $sql[$value_sql['name']] = $value_sql['_content'];
                    $query[$value_sql['name']] = $value_sql['title'];
                }
            }
        }
        if ($key == 'column') {
            $format = $value;
        }
    }
    require_once __ROOT__ . '/tpl/report_hdr.tpl';
    $timestamp = date('Ymdhis');
    $chartData = '';
    foreach ($sql as $sql_key => $sql_value) {
        $result = run_query($sql_value, $parms);
        if ($result) {
            foreach ($result as $key => $value) {
                if ($value) {
                    $html .= build_html($html, $chartData, $query, $sql_key, $value, $report_name, $title, $description, $parms, $format, $timestamp);
                }
            }
        }
    }
    echo $chartData;
    echo "</script>\n";
    echo $html;
    require_once __ROOT__ . '/tpl/report_ftr.tpl';
}
function generate_breadcrumb_admin($level, $id = 0)
{
    switch ($level) {
        case 'collections':
            $breadcrumbs = '<strong>' . plog_tr('Collections') . '</strong>';
            break;
        case 'albums':
            $collection = get_collection_by_id($id);
            $collection_name = SmartStripSlashes($collection['name']);
            $breadcrumbs = '<a href="' . $_SERVER['PHP_SELF'] . '">' . plog_tr('Collections') . '</a> &raquo; <strong>' . $collection_name . '</strong>';
            break;
        case 'pictures':
            $album = get_album_by_id($id);
            $album_link = SmartStripSlashes($album['name']);
            $collection_link = '<a href="' . $_SERVER['PHP_SELF'] . '?level=albums&amp;id=' . $album['parent_id'] . '">' . SmartStripSlashes($album['collection_name']) . '</a>';
            $breadcrumbs = '<a href="' . $_SERVER['PHP_SELF'] . '">' . plog_tr('Collections') . '</a> &raquo; ' . $collection_link . ' &raquo; ' . '<strong>' . $album_link . '</strong>';
            break;
        case 'comments':
            $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "pictures` WHERE `id`='" . $id . "'";
            $result = run_query($query);
            $row = mysql_fetch_assoc($result);
            $picture_link = '<strong>' . SmartStripSlashes(basename($row['path'])) . '</strong>';
            $album_id = $row['parent_album'];
            $collection_id = $row['parent_collection'];
            $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "albums` WHERE `id`='" . $album_id . "'";
            $result = run_query($query);
            $row = mysql_fetch_assoc($result);
            $album_link = '<a href="' . $_SERVER['PHP_SELF'] . '?level=pictures&amp;id=' . $album_id . '">' . SmartStripSlashes($row['name']) . '</a>';
            $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "collections` WHERE `id`='" . $collection_id . "'";
            $result = run_query($query);
            $row = mysql_fetch_assoc($result);
            $collection_link = '<a href="' . $_SERVER['PHP_SELF'] . '?level=albums&amp;id=' . $collection_id . '">' . SmartStripSlashes($row['name']) . '</a>';
            $breadcrumbs = '<a href="' . $_SERVER['PHP_SELF'] . '">' . plog_tr('Collections') . '</a> &raquo; ' . $collection_link . ' &raquo; ' . $album_link . ' &raquo; ' . $picture_link . ' - ' . '<strong>' . plog_tr('Comments') . ':</strong>';
            break;
        default:
            $breadcrumbs = '<strong>' . plog_tr('Collections') . '</strong>';
    }
    return "\n\t\t" . '<div id="breadcrumb_links">' . $breadcrumbs . '</div>';
}
function start_search($scope, array $q_items = null)
{
    switch ($scope) {
        case 'random':
            return random_search();
            break;
        case 'advanced-search':
            if (empty($q_items)) {
                return search_form(true);
            } else {
                return run_query($q_items);
            }
            break;
        case 'search':
        default:
            if (!empty($q_items)) {
                return run_query($q_items);
            } else {
                return search_form(false);
            }
    }
}
Beispiel #10
0
print "</ul>";
print "<hr/>";
print "<h2>Actors! <a href='actor_form.php'>(Add)</a></h2>";
$random_actors_query = "select * from Actor order by rand() limit 5";
$random_actors = run_query($random_actors_query, $db_connection);
print "<ul>";
while ($random_actor_row = mysql_fetch_array($random_actors, MYSQL_ASSOC)) {
    $actor_id = $random_actor_row['id'];
    $actor_tag = $random_actor_row['first'] . " " . $random_actor_row['last'] . " (" . $random_actor_row['dob'] . ")";
    $actor_link = "actor.php?actor_id={$actor_id}";
    print "<li><a href={$actor_link}>{$actor_tag}</a></li>";
}
print "</ul>";
print "<hr/>";
print "<h2>Directors! <a href='director_form.php'>(Add)</a></h2>";
$random_directors_query = "select * from Director order by rand() limit 5";
$random_directors = run_query($random_directors_query, $db_connection);
print "<ul>";
while ($random_director_row = mysql_fetch_array($random_directors, MYSQL_ASSOC)) {
    $director_id = $random_director_row['id'];
    $director_tag = $random_director_row['first'] . " " . $random_director_row['last'] . " (" . $random_director_row['dob'] . ")";
    $director_link = "director.php?director_id={$director_id}";
    print "<li><a href={$director_link}>{$director_tag}</a></li>";
}
print "</ul>";
print "<hr/>";
close_connection($db_connection);
print "</body>";
?>
</html>
Beispiel #11
0
function gr_add_album($parent, $name, $description)
{
    // Parent is the name of the collection
    $query = "SELECT * FROM \"" . PLOGGER_TABLE_PREFIX . "collections\" WHERE name = '" . $PLOGGER_DBH->quote($parent) . "'";
    $result = run_query($query);
    $row = $result->fetch();
    if (empty($name)) {
        $name = 'no name';
    }
    if (empty($description)) {
        $description = 'no description';
    }
    $parent_id = $row['id'];
    $result = add_album($name, $description, $parent_id);
    global $response;
    if (0 == $result['id']) {
        $response->set_key('status', GR_STAT_CREATE_ALBUM_FAILED);
        $response->set_key('status_text', 'Could not create album');
    } else {
        $response->set_key('status', GR_STAT_SUCCESS);
        $response->set_key('status_text', 'Album created');
    }
}
Beispiel #12
0
    $dob = sanitize_string($_GET["dob"], $db_connection);
    $dod = NULL;
    if ($_GET["dod"]) {
        $dod = sanitize_string($_GET["dod"], $db_connection);
    }
    $person_type = sanitize_string($_GET["person_type"], $db_connection);
    //print $person_type . "<br/>";
    if ($person_type == "actor") {
        $actor_base_query = "insert into Actor values (%d,'%s','%s','%s','%s','%s')";
        $actor_query = sprintf($actor_base_query, $id, $last, $first, $sex, $dob, $dod);
        //print $actor_query . "<br/>";
        run_query($actor_query, $db_connection);
    } else {
        if ($person_type == "director") {
            $director_base_query = "insert into Director values (%d,'%s','%s','%s','%s')";
            $director_query = sprintf($director_base_query, $id, $last, $first, $dob, $dod);
            //print $director_query . "<br/>";
            run_query($director_query, $db_connection);
        }
    }
    $max_person_update_query = sprintf("update MaxPersonID set id=%d where id=%d", $id, $old_max_person_id);
    //print $max_person_update_query . "<br/>";
    run_query($max_person_update_query, $db_connection);
    close_connection($db_connection);
    print "</body>";
    if ($person_type == "actor") {
        header("Location:actor.php?actor_id={$id}");
    } else {
        header("Location:director.php?director_id={$id}");
    }
}
Beispiel #13
0
function ss_get_mysql_stats($options)
{
    # Process connection options and connect to MySQL.
    global $debug, $mysql_user, $mysql_pass, $heartbeat, $cache_dir, $poll_time, $chk_options, $mysql_port, $mysql_ssl;
    # Connect to MySQL.
    $user = isset($options['user']) ? $options['user'] : $mysql_user;
    $pass = isset($options['pass']) ? $options['pass'] : $mysql_pass;
    $port = isset($options['port']) ? $options['port'] : $mysql_port;
    $heartbeat = isset($options['heartbeat']) ? $options['heartbeat'] : $heartbeat;
    # If there is a port, or if it's a non-standard port, we add ":$port" to the
    # hostname.
    $host_str = $options['host'] . (isset($options['port']) || $port != 3306 ? ":{$port}" : '');
    debug(array('connecting to', $host_str, $user, $pass));
    if (!extension_loaded('mysql')) {
        debug("The MySQL extension is not loaded");
        die("The MySQL extension is not loaded");
    }
    if ($mysql_ssl || isset($options['mysql_ssl']) && $options['mysql_ssl']) {
        $conn = mysql_connect($host_str, $user, $pass, true, MYSQL_CLIENT_SSL);
    } else {
        $conn = mysql_connect($host_str, $user, $pass);
    }
    if (!$conn) {
        die("MySQL: " . mysql_error());
    }
    $sanitized_host = str_replace(array(":", "/"), array("", "_"), $options['host']);
    $cache_file = "{$cache_dir}/{$sanitized_host}-mysql_cacti_stats.txt" . (isset($options['port']) || $port != 3306 ? ":{$port}" : '');
    debug("Cache file is {$cache_file}");
    # First, check the cache.
    $fp = null;
    if (!isset($options['nocache'])) {
        if ($fp = fopen($cache_file, 'a+')) {
            $locked = flock($fp, 1);
            # LOCK_SH
            if ($locked) {
                if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                    # The cache file is good to use.
                    debug("Using the cache file");
                    fclose($fp);
                    return $arr[0];
                } else {
                    debug("The cache file seems too small or stale");
                    # Escalate the lock to exclusive, so we can write to it.
                    if (flock($fp, 2)) {
                        # LOCK_EX
                        # We might have blocked while waiting for that LOCK_EX, and
                        # another process ran and updated it.  Let's see if we can just
                        # return the data now:
                        if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                            # The cache file is good to use.
                            debug("Using the cache file");
                            fclose($fp);
                            return $arr[0];
                        }
                        ftruncate($fp, 0);
                        # Now it's ready for writing later.
                    }
                }
            } else {
                debug("Couldn't lock the cache file, ignoring it.");
                $fp = null;
            }
        }
    } else {
        $fp = null;
        debug("Couldn't open the cache file");
    }
    # Set up variables.
    $status = array('relay_log_space' => null, 'binary_log_space' => null, 'current_transactions' => 0, 'locked_transactions' => 0, 'active_transactions' => 0, 'innodb_locked_tables' => 0, 'innodb_tables_in_use' => 0, 'innodb_lock_structs' => 0, 'innodb_lock_wait_secs' => 0, 'innodb_sem_waits' => 0, 'innodb_sem_wait_time_ms' => 0, 'State_closing_tables' => null, 'State_copying_to_tmp_table' => null, 'State_end' => null, 'State_freeing_items' => null, 'State_init' => null, 'State_locked' => null, 'State_login' => null, 'State_preparing' => null, 'State_reading_from_net' => null, 'State_sending_data' => null, 'State_sorting_result' => null, 'State_statistics' => null, 'State_updating' => null, 'State_writing_to_net' => null, 'State_none' => null, 'State_other' => null);
    # Get SHOW STATUS and convert the name-value array into a simple
    # associative array.
    $result = run_query("SHOW /*!50002 GLOBAL */ STATUS", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW VARIABLES and do the same thing, adding it to the $status array.
    $result = run_query("SHOW VARIABLES", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW SLAVE STATUS, and add it to the $status array.
    if ($chk_options['slave']) {
        $result = run_query("SHOW SLAVE STATUS", $conn);
        $slave_status_rows_gotten = 0;
        foreach ($result as $row) {
            $slave_status_rows_gotten++;
            # Must lowercase keys because different MySQL versions have different
            # lettercase.
            $row = array_change_key_case($row, CASE_LOWER);
            $status['relay_log_space'] = $row['relay_log_space'];
            $status['slave_lag'] = $row['seconds_behind_master'];
            # Check replication heartbeat, if present.
            if ($heartbeat) {
                $result2 = run_query("SELECT GREATEST(0, UNIX_TIMESTAMP() - UNIX_TIMESTAMP(ts) - 1)" . " AS delay FROM {$heartbeat} WHERE id = 1", $conn);
                $slave_delay_rows_gotten = 0;
                foreach ($result2 as $row2) {
                    $slave_delay_rows_gotten++;
                    if ($row2 && is_array($row2) && array_key_exists('delay', $row2)) {
                        $status['slave_lag'] = $row2['delay'];
                    } else {
                        debug("Couldn't get slave lag from {$heartbeat}");
                    }
                }
                if ($slave_delay_rows_gotten == 0) {
                    debug("Got nothing from heartbeat query");
                }
            }
            # Scale slave_running and slave_stopped relative to the slave lag.
            $status['slave_running'] = $row['slave_sql_running'] == 'Yes' ? $status['slave_lag'] : 0;
            $status['slave_stopped'] = $row['slave_sql_running'] == 'Yes' ? 0 : $status['slave_lag'];
        }
        if ($slave_status_rows_gotten == 0) {
            debug("Got nothing from SHOW SLAVE STATUS");
        }
    }
    # Get SHOW MASTER STATUS, and add it to the $status array.
    if ($chk_options['master'] && array_key_exists('log_bin', $status) && $status['log_bin'] == 'ON') {
        # See issue #8
        $binlogs = array(0);
        $result = run_query("SHOW MASTER LOGS", $conn);
        foreach ($result as $row) {
            $row = array_change_key_case($row, CASE_LOWER);
            # Older versions of MySQL may not have the File_size column in the
            # results of the command.  Zero-size files indicate the user is
            # deleting binlogs manually from disk (bad user! bad!).
            if (array_key_exists('file_size', $row) && $row['file_size'] > 0) {
                $binlogs[] = $row['file_size'];
            }
        }
        if (count($binlogs)) {
            $status['binary_log_space'] = to_int(array_sum($binlogs));
        }
    }
    # Get SHOW PROCESSLIST and aggregate it by state, then add it to the array
    # too.
    if ($chk_options['procs']) {
        $result = run_query('SHOW PROCESSLIST', $conn);
        foreach ($result as $row) {
            $state = $row['State'];
            if (is_null($state)) {
                $state = 'NULL';
            }
            if ($state == '') {
                $state = 'none';
            }
            $state = str_replace(' ', '_', strtolower($state));
            if (array_key_exists("State_{$state}", $status)) {
                increment($status, "State_{$state}", 1);
            } else {
                increment($status, "State_other", 1);
            }
        }
    }
    # Get SHOW INNODB STATUS and extract the desired metrics from it, then add
    # those to the array too.
    if ($chk_options['innodb'] && array_key_exists('have_innodb', $status) && $status['have_innodb'] == 'YES') {
        $result = run_query("SHOW /*!50000 ENGINE*/ INNODB STATUS", $conn);
        $istatus_text = $result[0]['Status'];
        $istatus_vals = get_innodb_array($istatus_text);
        # Get response time histogram from Percona Server if enabled.
        if ($chk_options['get_qrt'] && isset($status['have_response_time_distribution']) && $status['have_response_time_distribution'] == 'YES') {
            debug('Getting query time histogram');
            $i = 0;
            $result = run_query("SELECT `count`, total * 1000000 AS total " . "FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME " . "WHERE `time` <> 'TOO LONG'", $conn);
            foreach ($result as $row) {
                $count_key = sprintf("Query_time_count_%02d", $i);
                $total_key = sprintf("Query_time_total_%02d", $i);
                $status[$count_key] = $row['count'];
                $status[$total_key] = $row['total'];
                $i++;
            }
        } else {
            debug('Not getting time histogram because it is not enabled');
        }
        # Override values from InnoDB parsing with values from SHOW STATUS,
        # because InnoDB status might not have everything and the SHOW STATUS is
        # to be preferred where possible.
        $overrides = array('Innodb_buffer_pool_pages_data' => 'database_pages', 'Innodb_buffer_pool_pages_dirty' => 'modified_pages', 'Innodb_buffer_pool_pages_free' => 'free_pages', 'Innodb_buffer_pool_pages_total' => 'pool_size', 'Innodb_data_fsyncs' => 'file_fsyncs', 'Innodb_data_pending_reads' => 'pending_normal_aio_reads', 'Innodb_data_pending_writes' => 'pending_normal_aio_writes', 'Innodb_os_log_pending_fsyncs' => 'pending_log_flushes', 'Innodb_pages_created' => 'pages_created', 'Innodb_pages_read' => 'pages_read', 'Innodb_pages_written' => 'pages_written', 'Innodb_rows_deleted' => 'rows_deleted', 'Innodb_rows_inserted' => 'rows_inserted', 'Innodb_rows_read' => 'rows_read', 'Innodb_rows_updated' => 'rows_updated');
        # If the SHOW STATUS value exists, override...
        foreach ($overrides as $key => $val) {
            if (array_key_exists($key, $status)) {
                debug("Override {$key}");
                $istatus_vals[$val] = $status[$key];
            }
        }
        # Now copy the values into $status.
        foreach ($istatus_vals as $key => $val) {
            $status[$key] = $istatus_vals[$key];
        }
    }
    # Make table_open_cache backwards-compatible (issue 63).
    if (array_key_exists('table_open_cache', $status)) {
        $status['table_cache'] = $status['table_open_cache'];
    }
    # Compute how much of the key buffer is used and unflushed (issue 127).
    $status['Key_buf_bytes_used'] = big_sub($status['key_buffer_size'], big_multiply($status['Key_blocks_unused'], $status['key_cache_block_size']));
    $status['Key_buf_bytes_unflushed'] = big_multiply($status['Key_blocks_not_flushed'], $status['key_cache_block_size']);
    if (array_key_exists('unflushed_log', $status) && $status['unflushed_log']) {
        # TODO: I'm not sure what the deal is here; need to debug this.  But the
        # unflushed log bytes spikes a lot sometimes and it's impossible for it to
        # be more than the log buffer.
        debug("Unflushed log: {$status['unflushed_log']}");
        $status['unflushed_log'] = max($status['unflushed_log'], $status['innodb_log_buffer_size']);
    }
    # Define the variables to output.  I use shortened variable names so maybe
    # it'll all fit in 1024 bytes for Cactid and Spine's benefit.  This list must
    # come right after the word MAGIC_VARS_DEFINITIONS.  The Perl script parses
    # it and uses it as a Perl variable.
    $keys = array('Key_read_requests' => 'a0', 'Key_reads' => 'a1', 'Key_write_requests' => 'a2', 'Key_writes' => 'a3', 'history_list' => 'a4', 'innodb_transactions' => 'a5', 'read_views' => 'a6', 'current_transactions' => 'a7', 'locked_transactions' => 'a8', 'active_transactions' => 'a9', 'pool_size' => 'aa', 'free_pages' => 'ab', 'database_pages' => 'ac', 'modified_pages' => 'ad', 'pages_read' => 'ae', 'pages_created' => 'af', 'pages_written' => 'ag', 'file_fsyncs' => 'ah', 'file_reads' => 'ai', 'file_writes' => 'aj', 'log_writes' => 'ak', 'pending_aio_log_ios' => 'al', 'pending_aio_sync_ios' => 'am', 'pending_buf_pool_flushes' => 'an', 'pending_chkp_writes' => 'ao', 'pending_ibuf_aio_reads' => 'ap', 'pending_log_flushes' => 'aq', 'pending_log_writes' => 'ar', 'pending_normal_aio_reads' => 'as', 'pending_normal_aio_writes' => 'at', 'ibuf_inserts' => 'au', 'ibuf_merged' => 'av', 'ibuf_merges' => 'aw', 'spin_waits' => 'ax', 'spin_rounds' => 'ay', 'os_waits' => 'az', 'rows_inserted' => 'b0', 'rows_updated' => 'b1', 'rows_deleted' => 'b2', 'rows_read' => 'b3', 'Table_locks_waited' => 'b4', 'Table_locks_immediate' => 'b5', 'Slow_queries' => 'b6', 'Open_files' => 'b7', 'Open_tables' => 'b8', 'Opened_tables' => 'b9', 'innodb_open_files' => 'ba', 'open_files_limit' => 'bb', 'table_cache' => 'bc', 'Aborted_clients' => 'bd', 'Aborted_connects' => 'be', 'Max_used_connections' => 'bf', 'Slow_launch_threads' => 'bg', 'Threads_cached' => 'bh', 'Threads_connected' => 'bi', 'Threads_created' => 'bj', 'Threads_running' => 'bk', 'max_connections' => 'bl', 'thread_cache_size' => 'bm', 'Connections' => 'bn', 'slave_running' => 'bo', 'slave_stopped' => 'bp', 'Slave_retried_transactions' => 'bq', 'slave_lag' => 'br', 'Slave_open_temp_tables' => 'bs', 'Qcache_free_blocks' => 'bt', 'Qcache_free_memory' => 'bu', 'Qcache_hits' => 'bv', 'Qcache_inserts' => 'bw', 'Qcache_lowmem_prunes' => 'bx', 'Qcache_not_cached' => 'by', 'Qcache_queries_in_cache' => 'bz', 'Qcache_total_blocks' => 'c0', 'query_cache_size' => 'c1', 'Questions' => 'c2', 'Com_update' => 'c3', 'Com_insert' => 'c4', 'Com_select' => 'c5', 'Com_delete' => 'c6', 'Com_replace' => 'c7', 'Com_load' => 'c8', 'Com_update_multi' => 'c9', 'Com_insert_select' => 'ca', 'Com_delete_multi' => 'cb', 'Com_replace_select' => 'cc', 'Select_full_join' => 'cd', 'Select_full_range_join' => 'ce', 'Select_range' => 'cf', 'Select_range_check' => 'cg', 'Select_scan' => 'ch', 'Sort_merge_passes' => 'ci', 'Sort_range' => 'cj', 'Sort_rows' => 'ck', 'Sort_scan' => 'cl', 'Created_tmp_tables' => 'cm', 'Created_tmp_disk_tables' => 'cn', 'Created_tmp_files' => 'co', 'Bytes_sent' => 'cp', 'Bytes_received' => 'cq', 'innodb_log_buffer_size' => 'cr', 'unflushed_log' => 'cs', 'log_bytes_flushed' => 'ct', 'log_bytes_written' => 'cu', 'relay_log_space' => 'cv', 'binlog_cache_size' => 'cw', 'Binlog_cache_disk_use' => 'cx', 'Binlog_cache_use' => 'cy', 'binary_log_space' => 'cz', 'innodb_locked_tables' => 'd0', 'innodb_lock_structs' => 'd1', 'State_closing_tables' => 'd2', 'State_copying_to_tmp_table' => 'd3', 'State_end' => 'd4', 'State_freeing_items' => 'd5', 'State_init' => 'd6', 'State_locked' => 'd7', 'State_login' => 'd8', 'State_preparing' => 'd9', 'State_reading_from_net' => 'da', 'State_sending_data' => 'db', 'State_sorting_result' => 'dc', 'State_statistics' => 'dd', 'State_updating' => 'de', 'State_writing_to_net' => 'df', 'State_none' => 'dg', 'State_other' => 'dh', 'Handler_commit' => 'di', 'Handler_delete' => 'dj', 'Handler_discover' => 'dk', 'Handler_prepare' => 'dl', 'Handler_read_first' => 'dm', 'Handler_read_key' => 'dn', 'Handler_read_next' => 'do', 'Handler_read_prev' => 'dp', 'Handler_read_rnd' => 'dq', 'Handler_read_rnd_next' => 'dr', 'Handler_rollback' => 'ds', 'Handler_savepoint' => 'dt', 'Handler_savepoint_rollback' => 'du', 'Handler_update' => 'dv', 'Handler_write' => 'dw', 'innodb_tables_in_use' => 'dx', 'innodb_lock_wait_secs' => 'dy', 'hash_index_cells_total' => 'dz', 'hash_index_cells_used' => 'e0', 'total_mem_alloc' => 'e1', 'additional_pool_alloc' => 'e2', 'uncheckpointed_bytes' => 'e3', 'ibuf_used_cells' => 'e4', 'ibuf_free_cells' => 'e5', 'ibuf_cell_count' => 'e6', 'adaptive_hash_memory' => 'e7', 'page_hash_memory' => 'e8', 'dictionary_cache_memory' => 'e9', 'file_system_memory' => 'ea', 'lock_system_memory' => 'eb', 'recovery_system_memory' => 'ec', 'thread_hash_memory' => 'ed', 'innodb_sem_waits' => 'ee', 'innodb_sem_wait_time_ms' => 'ef', 'Key_buf_bytes_unflushed' => 'eg', 'Key_buf_bytes_used' => 'eh', 'key_buffer_size' => 'ei', 'Innodb_row_lock_time' => 'ej', 'Innodb_row_lock_waits' => 'ek', 'Query_time_count_00' => 'el', 'Query_time_count_01' => 'em', 'Query_time_count_02' => 'en', 'Query_time_count_03' => 'eo', 'Query_time_count_04' => 'ep', 'Query_time_count_05' => 'eq', 'Query_time_count_06' => 'er', 'Query_time_count_07' => 'es', 'Query_time_count_08' => 'et', 'Query_time_count_09' => 'eu', 'Query_time_count_10' => 'ev', 'Query_time_count_11' => 'ew', 'Query_time_count_12' => 'ex', 'Query_time_count_13' => 'ey', 'Query_time_total_00' => 'ez', 'Query_time_total_01' => 'fa', 'Query_time_total_02' => 'fb', 'Query_time_total_03' => 'fc', 'Query_time_total_04' => 'fd', 'Query_time_total_05' => 'fe', 'Query_time_total_06' => 'ff', 'Query_time_total_07' => 'fg', 'Query_time_total_08' => 'fh', 'Query_time_total_09' => 'fi', 'Query_time_total_10' => 'fj', 'Query_time_total_11' => 'fk', 'Query_time_total_12' => 'fl', 'Query_time_total_13' => 'fm');
    # Return the output.
    $output = array();
    foreach ($keys as $key => $short) {
        # If the value isn't defined, return -1 which is lower than (most graphs')
        # minimum value of 0, so it'll be regarded as a missing value.
        $val = isset($status[$key]) ? $status[$key] : -1;
        $output[] = "{$short}:{$val}";
    }
    $result = implode(' ', $output);
    if ($fp) {
        if (fwrite($fp, $result) === FALSE) {
            die("Can't write '{$cache_file}'");
        }
        fclose($fp);
    }
    return $result;
}
chdir(dirname(__FILE__));
function run_query($query)
{
    echo $query . ";\n";
    return true;
}
echo "\n\n-- ##### point_in_polygon.sql\n\n";
echo file_get_contents($basedir . 'mysql_feplus/point_in_polygon.sql');
echo "\n\n-- ##### feplus.sql\n\n";
echo file_get_contents($basedir . 'mysql_feplus/feplus.sql');
echo "\n\n-- ##### fedump.csv\n\n";
// make shape column hold text values
run_query("alter table feplus modify column shape TEXT");
// generate sql from data
$contents = file_get_contents($basedir . 'mysql_feplus/fedump.csv');
$lines = split("\n", $contents);
foreach ($lines as $line) {
    if ($line != '') {
        run_query("insert into feplus (s, m, e, h, l, area, shape, feregion, priority, dataset) values (" . $line . ")") or print mysql_error();
    }
}
// now convert text values to polygons
run_query("alter table feplus ADD COLUMN polyshape POLYGON AFTER shape") or print mysql_error();
run_query("update feplus SET polyshape = GeomFromText(shape)") or print mysql_error();
run_query("alter table feplus DROP COLUMN shape") or print mysql_error();
run_query("alter table feplus CHANGE polyshape shape POLYGON NOT NULL") or print mysql_error();
run_query("alter table feplus ADD SPATIAL INDEX(shape)") or print mysql_error();
echo "\n\n-- #### productIndexSchemaMysql.sql\n\n";
echo file_get_contents($basedir . 'productIndexSchemaMysql.sql');
#echo "\n\n-- #### productIndexOnEventUpdateMysql.sql\n\n";
#echo file_get_contents($basedir . 'productIndexOnEventUpdateMysql.sql');
 } else {
     if ($_REQUEST['destination_radio'] == 'new') {
         // Create the new album
         $result = add_album(mysql_real_escape_string($_REQUEST['new_album_name']), NULL, $_REQUEST['collections_menu']);
         if (!$result['errors']) {
             // No errors, add uploaded image to new album
             $album_id = $result['id'];
         } else {
             // Errors exist, let's find out what they are
             if (isset($result['output']) && $result['output'] == 'existing' && isset($result['id'])) {
                 // Album already exists so try insert images into the existing album
                 // and alert the user that their "new" album is already existing
                 $album_id = $result['id'];
                 // Get the collection name for display
                 $sql = "SELECT `name` FROM " . PLOGGER_TABLE_PREFIX . "collections WHERE id = " . intval($_REQUEST['collections_menu']);
                 $result = run_query($sql);
                 $row = mysql_fetch_assoc($result);
                 $output .= "\n\t" . '<p class="actions">' . sprintf(plog_tr('Album already exists. Uploading file to existing album %s in collection %s'), '<strong>' . $_REQUEST['new_album_name'] . '</strong>', '<strong>' . $row['name'] . '</strong>') . '</p>' . "\n";
             } else {
                 // Error has nothing to do with an existing album, show the returned error
                 $album_id = '';
                 $output .= "\n\t" . '<p class="errors">' . $result['errors'] . '</p>' . "\n";
             }
         }
     } else {
         // Use an existing album
         $album_id = $_REQUEST['albums_menu'];
     }
     if ($album_id) {
         $result = add_picture($album_id, $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'], $_REQUEST['caption'], $_REQUEST['description']);
         if (!$result['errors']) {
function add_photos($checked, $type, $dir)
{
    global $zipfile;
    if ($type == 'collections') {
        foreach ($checked as $cid) {
            $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "collections` WHERE `id`='" . intval($cid) . "'";
            $result = run_query($query);
            while ($row = mysql_fetch_assoc($result)) {
                $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "albums` WHERE `parent_id`='" . $row['id'] . "'";
                $newresult = run_query($query);
                $newchecked = array();
                while ($newrow = mysql_fetch_assoc($newresult)) {
                    $newchecked[] = $newrow['id'];
                }
                $newdir = $row['name'];
                $i = 1;
                while (is_dir($newdir)) {
                    $newdir = $row['name'] . '(' . $i++ . ')';
                }
                // $zipfile -> add_dir($dir . $newdir);
                add_photos($newchecked, 'collection', $dir . $newdir . '/');
            }
        }
    } else {
        if ($type == 'collection') {
            foreach ($checked as $aid) {
                $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "albums` WHERE `id`='" . intval($aid) . "'";
                $result = run_query($query);
                while ($row = mysql_fetch_assoc($result)) {
                    $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "pictures` WHERE `parent_album`='" . $row['id'] . "'";
                    $newresult = run_query($query);
                    $newchecked = array();
                    while ($newrow = mysql_fetch_assoc($newresult)) {
                        $newchecked[] = $newrow['id'];
                    }
                    $newdir = $row['name'];
                    $i = 1;
                    while (is_dir($newdir)) {
                        $newdir = $row['name'] . '(' . $i++ . ')';
                    }
                    // $zipfile -> add_dir($dir . $newdir);
                    add_photos($newchecked, 'album', $dir . $newdir . '/');
                }
            }
        } elseif ($type == 'album' || $type == 'search') {
            foreach ($checked as $pid) {
                $query = "SELECT * FROM `" . PLOGGER_TABLE_PREFIX . "pictures` WHERE `id`='" . intval($pid) . "'";
                $result = run_query($query);
                while ($row = mysql_fetch_assoc($result)) {
                    $file_contents = file_get_contents('plog-content/images/' . $row['path'], true);
                    $zipfile->add_file($file_contents, $row['path']);
                }
            }
        }
    }
    return;
}
Beispiel #17
0
<script language="PHP">
require "search-functions.php";

$mode = array_key_exists('v', $_GET)?$_GET['v']:"";
$query = array_key_exists('query', $_GET)?$_GET['query']:"";

$query_results = run_query($query);

switch ($mode)
{
  case "opensearch.xml":
    opensearch_description();
    break;
  case "json":
    opensearch_json_results($query, $query_results);
    break;
  case "xml":
    opensearch_xml_results($query, $query_results);
    break;
  default:
    invalid_format($query, $query_results);
    break;
}

function opensearch_description()
{
  global $config;
  global $translator;

  $shortname = $translator['search']." ".$config['PROJECT_NAME'];
  $link = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']);
Beispiel #18
0
<?php

include 'config.php';
include 'db-functions.php';
$connection = connect_to_db();
select_db();
$query = "INSERT INTO action (actionid, description)\n            VALUES (%s, %s)";
$query = sprintf($query, $_GET["actionid"], $_GET["description"]);
if (!run_query($query)) {
    // Unsuccessful query?
    $array = array("Status" => "Failure", "Message" => "Action could not be added.");
} else {
    $array = array("Status" => "Success", "Message" => "Action has been successfully added.");
}
echo json_encode($array);
close_db($connection);
<?php 
require_once "getquery.php";
$query = "SELECT * FROM ruleset as r GROUP BY r.id ORDER BY r.id ASC";
echo $json = to_json(run_query($query));
Beispiel #20
0
function get_picture_ids($album_id, $order = "alpha", $sort = "DESC")
{
    global $config;
    $query = "SELECT\r\n\t\t\t`p`.`id`\r\n\t\tFROM `" . TABLE_PREFIX . "pictures` AS `p`\r\n\t\t\tLEFT JOIN `" . TABLE_PREFIX . "albums` AS `a` ON `p`.`parent_album`=`a`.`id`\r\n\t\tWHERE `a`.`id`=" . intval($album_id);
    if ($order == "mod") {
        $query .= "\tORDER BY `p`.`date_submitted` ";
    } else {
        $query .= "\tORDER BY `p`.`caption` ";
    }
    if ($sort == "ASC") {
        $query .= " ASC ";
    } else {
        $query .= " DESC ";
    }
    $result = run_query($query);
    $pictures = array();
    while ($row = mysql_fetch_assoc($result)) {
        $pictures[$row["id"]] = $row;
    }
    return $pictures;
}
function plog_edit_album_form($album_id)
{
    global $thumbnail_config;
    $album_id = intval($album_id);
    $album = get_album_by_id($album_id);
    $auto_graphic = "../graphics/auto.gif";
    $output .= '<form class="edit" action="' . $_SERVER["PHP_SELF"] . '?level=albums&amp;id=' . $album["parent_id"] . '" method="post">';
    $images = '<option class="thumboption" value="0" style="padding-left: 100px; background-image: url(' . $auto_graphic . '); 
		background-repeat: no-repeat;">' . plog_tr('automatic') . '</option>';
    $sql = "SELECT id,caption,path FROM " . TABLE_PREFIX . "pictures p WHERE p.parent_album = '" . $album_id . "'";
    $result = run_query($sql);
    while ($row = mysql_fetch_assoc($result)) {
        $selected = $row["id"] == $album["thumbnail_id"] ? " selected" : "";
        $style = 'class="thumboption" style="padding-left: ' . ($thumbnail_config[THUMB_SMALL]["size"] + 5) . 'px; background-image: 
			url(' . generate_thumb(SmartStripSlashes($row["path"]), $row["id"]) . '); background-repeat: no-repeat;"';
        $images .= "<option {$style} value='" . $row["id"] . "'" . $selected . ">";
        $images .= !empty($row["caption"]) ? SmartStripSlashes($row["caption"]) : SmartStripSlashes(basename($row["path"]));
        $images .= "</option>\n";
    }
    $output .= '<label for="name" accesskey="n"><em>N</em>ame:</label><br/><input size="30" name="name" id="name" value="' . SmartStripSlashes($album['name']) . '"><br/>
				    <label for="description" accesskey="d"><em>D</em>escription:</label><br/><input size="80" name="description" id="description" value="' . SmartStripSlashes($album['description']) . '"><br/>
				    Thumbnail:<br/><select name="thumbnail_id" class="thumbselect" id="thumbselect" 
				    onchange="updateThumbPreview(this)">' . $images . '</select>
				    <script type="text/javascript">updateThumbPreview(document.getElementById(\'thumbselect\'));</script>';
    $output .= '<input type="hidden" name="pid" value="' . $album_id . '">
					<input type="hidden" name="action" value="update-album">
					<tr><td><button class="submit" type="submit">' . plog_tr('Update') . '</button>';
    $output .= '</form>';
    return $output;
}
Beispiel #22
0
<?php

include 'header.php';
include 'db_functions.php';
if ($_GET["create_review"]) {
    print "<body>";
    $db_connection = create_connection("localhost", "cs143", "");
    $name = sanitize_string($_GET["review_name"], $db_connection);
    $date = date('Y-m-d H:i:s');
    print $date . "<br/>";
    $mid = sanitize_string($_GET["movie_id"], $db_connection);
    $rating = sanitize_string($_GET["rating"], $db_connection);
    $comment = sanitize_string($_GET["comment"], $db_connection);
    $review_base_query = "insert into Review values ('%s', '%s', %d, %d, '%s')";
    $review_query = sprintf($review_base_query, $name, $date, $mid, $rating, $comment);
    print $review_query . "<br/>";
    run_query($review_query, $db_connection);
    close_connection($db_connection);
    print "</body>";
    header("Location: movie.php?movie_id={$mid}");
}
Beispiel #23
0
<?php

include 'config.php';
include 'db-functions.php';
$connection = connect_to_db();
select_db();
if (isset($_GET["notificationid"])) {
    $query = "SELECT * FROM notification WHERE notificationid = " . $_GET["notificationid"];
} else {
    $query = "SELECT * FROM notification";
}
$result = run_query($query);
// Pushes each entry of result into an array and converts it to JSON.
$array = array();
while ($row = mysql_fetch_assoc($result)) {
    array_push($array, $row);
}
echo json_encode($array);
close_db($connection);
Beispiel #24
0
function get_app_by_id()
{
    return run_query();
}
//ini_set('display_errors','On');
//error_reporting(E_ALL);
require "sphinxapi.php";
//phpinfo();
//exit();
function run_query()
{
    if ($_GET["search_str"] != "") {
        $tmp_var = do_query($_GET["search_str"]);
        echo json_encode($tmp_var);
    } else {
        echo json_encode(array("-1" => array("")));
    }
}
run_query();
function do_query($search_str)
{
    //$tmp_var = array(array('itemName' => "test1"), array('itemName' => "test2"), array('itemName' => "test3"));
    //echo implode(",",tmp_var);
    //echo json_encode($tmp_var);
    //return tmp_var;
    $q = "";
    $sql = "";
    $mode = SPH_MATCH_ALL;
    $host = "localhost";
    $port = 9312;
    $index = "*";
    $groupby = "";
    $groupsort = "@group desc";
    $filter = "group_id";
Beispiel #26
0
function ss_get_mysql_stats($options)
{
    # Process connection options.
    global $debug, $mysql_user, $mysql_pass, $cache_dir, $poll_time, $chk_options, $mysql_port, $mysql_ssl, $mysql_ssl_key, $mysql_ssl_cert, $mysql_ssl_ca, $mysql_connection_timeout, $heartbeat, $heartbeat_table, $heartbeat_server_id, $heartbeat_utc;
    $user = isset($options['user']) ? $options['user'] : $mysql_user;
    $pass = isset($options['pass']) ? $options['pass'] : $mysql_pass;
    $host = $options['host'];
    $port = isset($options['port']) ? $options['port'] : $mysql_port;
    $connection_timeout = isset($options['connection-timeout']) ? $options['connection-timeout'] : $mysql_connection_timeout;
    $heartbeat_server_id = isset($options['server-id']) ? $options['server-id'] : $heartbeat_server_id;
    $sanitized_host = str_replace(array(":", "/"), array("", "_"), $host);
    $cache_file = "{$cache_dir}/{$sanitized_host}-mysql_cacti_stats.txt" . ($port != 3306 ? ":{$port}" : '');
    debug("Cache file is {$cache_file}");
    # First, check the cache.
    $fp = null;
    if ($cache_dir && !array_key_exists('nocache', $options)) {
        if ($fp = fopen($cache_file, 'a+')) {
            $locked = flock($fp, 1);
            # LOCK_SH
            if ($locked) {
                if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                    # The cache file is good to use.
                    debug("Using the cache file");
                    fclose($fp);
                    return $arr[0];
                } else {
                    debug("The cache file seems too small or stale");
                    # Escalate the lock to exclusive, so we can write to it.
                    if (flock($fp, 2)) {
                        # LOCK_EX
                        # We might have blocked while waiting for that LOCK_EX, and
                        # another process ran and updated it.  Let's see if we can just
                        # return the data now:
                        if (filesize($cache_file) > 0 && filectime($cache_file) + $poll_time / 2 > time() && ($arr = file($cache_file))) {
                            # The cache file is good to use.
                            debug("Using the cache file");
                            fclose($fp);
                            return $arr[0];
                        }
                        ftruncate($fp, 0);
                        # Now it's ready for writing later.
                    }
                }
            } else {
                $fp = null;
                debug("Couldn't lock the cache file, ignoring it");
            }
        } else {
            $fp = null;
            debug("Couldn't open the cache file");
        }
    } else {
        debug("Caching is disabled.");
    }
    # Connect to MySQL.
    debug(array('Connecting to', $host, $port, $user, $pass));
    if (!extension_loaded('mysqli')) {
        debug("PHP MySQLi extension is not loaded");
        die("PHP MySQLi extension is not loaded");
    }
    if ($mysql_ssl) {
        $conn = mysqli_init();
        $conn->options(MYSQLI_OPT_CONNECT_TIMEOUT, $connection_timeout);
        mysqli_ssl_set($conn, $mysql_ssl_key, $mysql_ssl_cert, $mysql_ssl_ca, NULL, NULL);
        mysqli_real_connect($conn, $host, $user, $pass, NULL, $port);
    } else {
        $conn = mysqli_init();
        $conn->options(MYSQLI_OPT_CONNECT_TIMEOUT, $connection_timeout);
        mysqli_real_connect($conn, $host, $user, $pass, NULL, $port);
    }
    if (mysqli_connect_errno()) {
        debug("MySQL connection failed: " . mysqli_connect_error());
        die("ERROR: " . mysqli_connect_error());
    }
    # MySQL server version.
    # The form of this version number is main_version * 10000 + minor_version * 100 + sub_version
    # i.e. version 5.5.44 is 50544.
    $mysql_version = mysqli_get_server_version($conn);
    debug("MySQL server version is " . $mysql_version);
    # Set up variables.
    $status = array('relay_log_space' => null, 'binary_log_space' => null, 'current_transactions' => 0, 'locked_transactions' => 0, 'active_transactions' => 0, 'innodb_locked_tables' => 0, 'innodb_tables_in_use' => 0, 'innodb_lock_structs' => 0, 'innodb_lock_wait_secs' => 0, 'innodb_sem_waits' => 0, 'innodb_sem_wait_time_ms' => 0, 'State_closing_tables' => 0, 'State_copying_to_tmp_table' => 0, 'State_end' => 0, 'State_freeing_items' => 0, 'State_init' => 0, 'State_locked' => 0, 'State_login' => 0, 'State_preparing' => 0, 'State_reading_from_net' => 0, 'State_sending_data' => 0, 'State_sorting_result' => 0, 'State_statistics' => 0, 'State_updating' => 0, 'State_writing_to_net' => 0, 'State_none' => 0, 'State_other' => 0);
    # Get SHOW STATUS and convert the name-value array into a simple
    # associative array.
    $result = run_query("SHOW /*!50002 GLOBAL */ STATUS", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW VARIABLES and do the same thing, adding it to the $status array.
    $result = run_query("SHOW VARIABLES", $conn);
    foreach ($result as $row) {
        $status[$row[0]] = $row[1];
    }
    # Get SHOW SLAVE STATUS, and add it to the $status array.
    if ($chk_options['slave']) {
        # Leverage lock-free SHOW SLAVE STATUS if available
        $result = run_query("SHOW SLAVE STATUS NONBLOCKING", $conn);
        if (!$result) {
            $result = run_query("SHOW SLAVE STATUS NOLOCK", $conn);
            if (!$result) {
                $result = run_query("SHOW SLAVE STATUS", $conn);
            }
        }
        $slave_status_rows_gotten = 0;
        foreach ($result as $row) {
            $slave_status_rows_gotten++;
            # Must lowercase keys because different MySQL versions have different
            # lettercase.
            $row = array_change_key_case($row, CASE_LOWER);
            $status['relay_log_space'] = $row['relay_log_space'];
            $status['slave_lag'] = $row['seconds_behind_master'];
            # Check replication heartbeat, if present.
            if ($heartbeat) {
                if ($heartbeat_utc) {
                    $now_func = 'UNIX_TIMESTAMP(UTC_TIMESTAMP)';
                } else {
                    $now_func = 'UNIX_TIMESTAMP()';
                }
                $result2 = run_query("SELECT MAX({$now_func} - ROUND(UNIX_TIMESTAMP(ts)))" . " AS delay FROM {$heartbeat_table}" . " WHERE {$heartbeat_server_id} = 0 OR server_id = {$heartbeat_server_id}", $conn);
                $slave_delay_rows_gotten = 0;
                foreach ($result2 as $row2) {
                    $slave_delay_rows_gotten++;
                    if ($row2 && is_array($row2) && array_key_exists('delay', $row2)) {
                        $status['slave_lag'] = $row2['delay'];
                    } else {
                        debug("Couldn't get slave lag from {$heartbeat_table}");
                    }
                }
                if ($slave_delay_rows_gotten == 0) {
                    debug("Got nothing from heartbeat query");
                }
            }
            # Scale slave_running and slave_stopped relative to the slave lag.
            $status['slave_running'] = $row['slave_sql_running'] == 'Yes' ? $status['slave_lag'] : 0;
            $status['slave_stopped'] = $row['slave_sql_running'] == 'Yes' ? 0 : $status['slave_lag'];
        }
        if ($slave_status_rows_gotten == 0) {
            debug("Got nothing from SHOW SLAVE STATUS");
        }
    }
    # Get SHOW MASTER STATUS, and add it to the $status array.
    if ($chk_options['master'] && array_key_exists('log_bin', $status) && $status['log_bin'] == 'ON') {
        # See issue #8
        $binlogs = array(0);
        $result = run_query("SHOW MASTER LOGS", $conn);
        foreach ($result as $row) {
            $row = array_change_key_case($row, CASE_LOWER);
            # Older versions of MySQL may not have the File_size column in the
            # results of the command.  Zero-size files indicate the user is
            # deleting binlogs manually from disk (bad user! bad!).
            if (array_key_exists('file_size', $row) && $row['file_size'] > 0) {
                $binlogs[] = $row['file_size'];
            }
        }
        if (count($binlogs)) {
            $status['binary_log_space'] = to_int(array_sum($binlogs));
        }
    }
    # Get SHOW PROCESSLIST and aggregate it by state, then add it to the array
    # too.
    if ($chk_options['procs']) {
        $result = run_query('SHOW PROCESSLIST', $conn);
        foreach ($result as $row) {
            $state = $row['State'];
            if (is_null($state)) {
                $state = 'NULL';
            }
            if ($state == '') {
                $state = 'none';
            }
            # MySQL 5.5 replaces the 'Locked' state with a variety of "Waiting for
            # X lock" types of statuses.  Wrap these all back into "Locked" because
            # we don't really care about the type of locking it is.
            $state = preg_replace('/^(Table lock|Waiting for .*lock)$/', 'Locked', $state);
            $state = str_replace(' ', '_', strtolower($state));
            if (array_key_exists("State_{$state}", $status)) {
                increment($status, "State_{$state}", 1);
            } else {
                increment($status, "State_other", 1);
            }
        }
    }
    # Get SHOW ENGINES to be able to determine whether InnoDB is present.
    $engines = array();
    $result = run_query("SHOW ENGINES", $conn);
    foreach ($result as $row) {
        $engines[$row[0]] = $row[1];
    }
    # Get SHOW INNODB STATUS and extract the desired metrics from it, then add
    # those to the array too.
    if ($chk_options['innodb'] && array_key_exists('InnoDB', $engines) && $engines['InnoDB'] == 'YES' || $engines['InnoDB'] == 'DEFAULT') {
        $result = run_query("SHOW /*!50000 ENGINE*/ INNODB STATUS", $conn);
        $istatus_text = $result[0]['Status'];
        $istatus_vals = get_innodb_array($istatus_text, $mysql_version);
        # Get response time histogram from Percona Server or MariaDB if enabled.
        if ($chk_options['get_qrt'] && (isset($status['have_response_time_distribution']) && $status['have_response_time_distribution'] == 'YES' || isset($status['query_response_time_stats']) && $status['query_response_time_stats'] == 'ON')) {
            debug('Getting query time histogram');
            $i = 0;
            $result = run_query("SELECT `count`, ROUND(total * 1000000) AS total " . "FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME " . "WHERE `time` <> 'TOO LONG'", $conn);
            foreach ($result as $row) {
                if ($i > 13) {
                    # It's possible that the number of rows returned isn't 14.
                    # Don't add extra status counters.
                    break;
                }
                $count_key = sprintf("Query_time_count_%02d", $i);
                $total_key = sprintf("Query_time_total_%02d", $i);
                $status[$count_key] = $row['count'];
                $status[$total_key] = $row['total'];
                $i++;
            }
            # It's also possible that the number of rows returned is too few.
            # Don't leave any status counters unassigned; it will break graphs.
            while ($i <= 13) {
                $count_key = sprintf("Query_time_count_%02d", $i);
                $total_key = sprintf("Query_time_total_%02d", $i);
                $status[$count_key] = 0;
                $status[$total_key] = 0;
                $i++;
            }
        } else {
            debug('Not getting time histogram because it is not enabled');
        }
        # Override values from InnoDB parsing with values from SHOW STATUS,
        # because InnoDB status might not have everything and the SHOW STATUS is
        # to be preferred where possible.
        $overrides = array('Innodb_buffer_pool_pages_data' => 'database_pages', 'Innodb_buffer_pool_pages_dirty' => 'modified_pages', 'Innodb_buffer_pool_pages_free' => 'free_pages', 'Innodb_buffer_pool_pages_total' => 'pool_size', 'Innodb_data_fsyncs' => 'file_fsyncs', 'Innodb_data_pending_reads' => 'pending_normal_aio_reads', 'Innodb_data_pending_writes' => 'pending_normal_aio_writes', 'Innodb_os_log_pending_fsyncs' => 'pending_log_flushes', 'Innodb_pages_created' => 'pages_created', 'Innodb_pages_read' => 'pages_read', 'Innodb_pages_written' => 'pages_written', 'Innodb_rows_deleted' => 'rows_deleted', 'Innodb_rows_inserted' => 'rows_inserted', 'Innodb_rows_read' => 'rows_read', 'Innodb_rows_updated' => 'rows_updated', 'Innodb_buffer_pool_reads' => 'pool_reads', 'Innodb_buffer_pool_read_requests' => 'pool_read_requests');
        # If the SHOW STATUS value exists, override...
        foreach ($overrides as $key => $val) {
            if (array_key_exists($key, $status)) {
                debug("Override {$key}");
                $istatus_vals[$val] = $status[$key];
            }
        }
        # Now copy the values into $status.
        foreach ($istatus_vals as $key => $val) {
            $status[$key] = $istatus_vals[$key];
        }
    }
    # Make table_open_cache backwards-compatible (issue 63).
    if (array_key_exists('table_open_cache', $status)) {
        $status['table_cache'] = $status['table_open_cache'];
    }
    # Compute how much of the key buffer is used and unflushed (issue 127).
    $status['Key_buf_bytes_used'] = big_sub($status['key_buffer_size'], big_multiply($status['Key_blocks_unused'], $status['key_cache_block_size']));
    $status['Key_buf_bytes_unflushed'] = big_multiply($status['Key_blocks_not_flushed'], $status['key_cache_block_size']);
    if (array_key_exists('unflushed_log', $status) && $status['unflushed_log']) {
        # TODO: I'm not sure what the deal is here; need to debug this.  But the
        # unflushed log bytes spikes a lot sometimes and it's impossible for it to
        # be more than the log buffer.
        debug("Unflushed log: {$status['unflushed_log']}");
        $status['unflushed_log'] = max($status['unflushed_log'], $status['innodb_log_buffer_size']);
    }
    # Define the variables to output.  I use shortened variable names so maybe
    # it'll all fit in 1024 bytes for Cactid and Spine's benefit.  Strings must
    # have some non-hex characters (non a-f0-9) to avoid a Cacti bug.  This list
    # must come right after the word MAGIC_VARS_DEFINITIONS.  The Perl script
    # parses it and uses it as a Perl variable.
    $keys = array('Key_read_requests' => 'gg', 'Key_reads' => 'gh', 'Key_write_requests' => 'gi', 'Key_writes' => 'gj', 'history_list' => 'gk', 'innodb_transactions' => 'gl', 'read_views' => 'gm', 'current_transactions' => 'gn', 'locked_transactions' => 'go', 'active_transactions' => 'gp', 'pool_size' => 'gq', 'free_pages' => 'gr', 'database_pages' => 'gs', 'modified_pages' => 'gt', 'pages_read' => 'gu', 'pages_created' => 'gv', 'pages_written' => 'gw', 'file_fsyncs' => 'gx', 'file_reads' => 'gy', 'file_writes' => 'gz', 'log_writes' => 'hg', 'pending_aio_log_ios' => 'hh', 'pending_aio_sync_ios' => 'hi', 'pending_buf_pool_flushes' => 'hj', 'pending_chkp_writes' => 'hk', 'pending_ibuf_aio_reads' => 'hl', 'pending_log_flushes' => 'hm', 'pending_log_writes' => 'hn', 'pending_normal_aio_reads' => 'ho', 'pending_normal_aio_writes' => 'hp', 'ibuf_inserts' => 'hq', 'ibuf_merged' => 'hr', 'ibuf_merges' => 'hs', 'spin_waits' => 'ht', 'spin_rounds' => 'hu', 'os_waits' => 'hv', 'rows_inserted' => 'hw', 'rows_updated' => 'hx', 'rows_deleted' => 'hy', 'rows_read' => 'hz', 'Table_locks_waited' => 'ig', 'Table_locks_immediate' => 'ih', 'Slow_queries' => 'ii', 'Open_files' => 'ij', 'Open_tables' => 'ik', 'Opened_tables' => 'il', 'innodb_open_files' => 'im', 'open_files_limit' => 'in', 'table_cache' => 'io', 'Aborted_clients' => 'ip', 'Aborted_connects' => 'iq', 'Max_used_connections' => 'ir', 'Slow_launch_threads' => 'is', 'Threads_cached' => 'it', 'Threads_connected' => 'iu', 'Threads_created' => 'iv', 'Threads_running' => 'iw', 'max_connections' => 'ix', 'thread_cache_size' => 'iy', 'Connections' => 'iz', 'slave_running' => 'jg', 'slave_stopped' => 'jh', 'Slave_retried_transactions' => 'ji', 'slave_lag' => 'jj', 'Slave_open_temp_tables' => 'jk', 'Qcache_free_blocks' => 'jl', 'Qcache_free_memory' => 'jm', 'Qcache_hits' => 'jn', 'Qcache_inserts' => 'jo', 'Qcache_lowmem_prunes' => 'jp', 'Qcache_not_cached' => 'jq', 'Qcache_queries_in_cache' => 'jr', 'Qcache_total_blocks' => 'js', 'query_cache_size' => 'jt', 'Questions' => 'ju', 'Com_update' => 'jv', 'Com_insert' => 'jw', 'Com_select' => 'jx', 'Com_delete' => 'jy', 'Com_replace' => 'jz', 'Com_load' => 'kg', 'Com_update_multi' => 'kh', 'Com_insert_select' => 'ki', 'Com_delete_multi' => 'kj', 'Com_replace_select' => 'kk', 'Select_full_join' => 'kl', 'Select_full_range_join' => 'km', 'Select_range' => 'kn', 'Select_range_check' => 'ko', 'Select_scan' => 'kp', 'Sort_merge_passes' => 'kq', 'Sort_range' => 'kr', 'Sort_rows' => 'ks', 'Sort_scan' => 'kt', 'Created_tmp_tables' => 'ku', 'Created_tmp_disk_tables' => 'kv', 'Created_tmp_files' => 'kw', 'Bytes_sent' => 'kx', 'Bytes_received' => 'ky', 'innodb_log_buffer_size' => 'kz', 'unflushed_log' => 'lg', 'log_bytes_flushed' => 'lh', 'log_bytes_written' => 'li', 'relay_log_space' => 'lj', 'binlog_cache_size' => 'lk', 'Binlog_cache_disk_use' => 'll', 'Binlog_cache_use' => 'lm', 'binary_log_space' => 'ln', 'innodb_locked_tables' => 'lo', 'innodb_lock_structs' => 'lp', 'State_closing_tables' => 'lq', 'State_copying_to_tmp_table' => 'lr', 'State_end' => 'ls', 'State_freeing_items' => 'lt', 'State_init' => 'lu', 'State_locked' => 'lv', 'State_login' => 'lw', 'State_preparing' => 'lx', 'State_reading_from_net' => 'ly', 'State_sending_data' => 'lz', 'State_sorting_result' => 'mg', 'State_statistics' => 'mh', 'State_updating' => 'mi', 'State_writing_to_net' => 'mj', 'State_none' => 'mk', 'State_other' => 'ml', 'Handler_commit' => 'mm', 'Handler_delete' => 'mn', 'Handler_discover' => 'mo', 'Handler_prepare' => 'mp', 'Handler_read_first' => 'mq', 'Handler_read_key' => 'mr', 'Handler_read_next' => 'ms', 'Handler_read_prev' => 'mt', 'Handler_read_rnd' => 'mu', 'Handler_read_rnd_next' => 'mv', 'Handler_rollback' => 'mw', 'Handler_savepoint' => 'mx', 'Handler_savepoint_rollback' => 'my', 'Handler_update' => 'mz', 'Handler_write' => 'ng', 'innodb_tables_in_use' => 'nh', 'innodb_lock_wait_secs' => 'ni', 'hash_index_cells_total' => 'nj', 'hash_index_cells_used' => 'nk', 'total_mem_alloc' => 'nl', 'additional_pool_alloc' => 'nm', 'uncheckpointed_bytes' => 'nn', 'ibuf_used_cells' => 'no', 'ibuf_free_cells' => 'np', 'ibuf_cell_count' => 'nq', 'adaptive_hash_memory' => 'nr', 'page_hash_memory' => 'ns', 'dictionary_cache_memory' => 'nt', 'file_system_memory' => 'nu', 'lock_system_memory' => 'nv', 'recovery_system_memory' => 'nw', 'thread_hash_memory' => 'nx', 'innodb_sem_waits' => 'ny', 'innodb_sem_wait_time_ms' => 'nz', 'Key_buf_bytes_unflushed' => 'og', 'Key_buf_bytes_used' => 'oh', 'key_buffer_size' => 'oi', 'Innodb_row_lock_time' => 'oj', 'Innodb_row_lock_waits' => 'ok', 'Query_time_count_00' => 'ol', 'Query_time_count_01' => 'om', 'Query_time_count_02' => 'on', 'Query_time_count_03' => 'oo', 'Query_time_count_04' => 'op', 'Query_time_count_05' => 'oq', 'Query_time_count_06' => 'or', 'Query_time_count_07' => 'os', 'Query_time_count_08' => 'ot', 'Query_time_count_09' => 'ou', 'Query_time_count_10' => 'ov', 'Query_time_count_11' => 'ow', 'Query_time_count_12' => 'ox', 'Query_time_count_13' => 'oy', 'Query_time_total_00' => 'oz', 'Query_time_total_01' => 'pg', 'Query_time_total_02' => 'ph', 'Query_time_total_03' => 'pi', 'Query_time_total_04' => 'pj', 'Query_time_total_05' => 'pk', 'Query_time_total_06' => 'pl', 'Query_time_total_07' => 'pm', 'Query_time_total_08' => 'pn', 'Query_time_total_09' => 'po', 'Query_time_total_10' => 'pp', 'Query_time_total_11' => 'pq', 'Query_time_total_12' => 'pr', 'Query_time_total_13' => 'ps', 'wsrep_replicated_bytes' => 'pt', 'wsrep_received_bytes' => 'pu', 'wsrep_replicated' => 'pv', 'wsrep_received' => 'pw', 'wsrep_local_cert_failures' => 'px', 'wsrep_local_bf_aborts' => 'py', 'wsrep_local_send_queue' => 'pz', 'wsrep_local_recv_queue' => 'qg', 'wsrep_cluster_size' => 'qh', 'wsrep_cert_deps_distance' => 'qi', 'wsrep_apply_window' => 'qj', 'wsrep_commit_window' => 'qk', 'wsrep_flow_control_paused' => 'ql', 'wsrep_flow_control_sent' => 'qm', 'wsrep_flow_control_recv' => 'qn', 'pool_reads' => 'qo', 'pool_read_requests' => 'qp');
    # Return the output.
    $output = array();
    foreach ($keys as $key => $short) {
        # If the value isn't defined, return -1 which is lower than (most graphs')
        # minimum value of 0, so it'll be regarded as a missing value.
        $val = isset($status[$key]) ? $status[$key] : -1;
        $output[] = "{$short}:{$val}";
    }
    $result = implode(' ', $output);
    if ($fp) {
        if (fwrite($fp, $result) === FALSE) {
            die("Can't write '{$cache_file}'");
        }
        fclose($fp);
    }
    return $result;
}
Beispiel #27
0
<?php

require_once "getquery.php";
$handle = @fopen("regulations.txt", "r");
$query = "INSERT INTO banspecies (ruleset, species) VALUES ";
if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        $buffer = substr($buffer, 0, strlen($buffer) - 2);
        $ids = json_decode(to_json(run_query("\n            SELECT id FROM species WHERE name=\"{$buffer}\"\n        ")));
        $query .= "(1, " . $ids[0]->id . "),";
    }
}
echo $query;
run_query(substr($query, 0, strlen($query) - 1));
die("Done!");
Beispiel #28
0
function add_photos($checked, $type, $dir)
{
    global $zipfile;
    if ($type == "collections") {
        foreach ($checked as $cid) {
            $query = "SELECT * FROM `" . TABLE_PREFIX . "collections` WHERE `id`='" . intval($cid) . "'";
            $result = run_query($query);
            while ($row = mysql_fetch_assoc($result)) {
                $query = "SELECT * FROM `" . TABLE_PREFIX . "albums` WHERE `parent_id`='" . $row["id"] . "'";
                $newresult = run_query($query);
                $newchecked = array();
                while ($newrow = mysql_fetch_assoc($newresult)) {
                    $newchecked[] = $newrow["id"];
                }
                $newdir = $row["name"];
                $i = 1;
                while (is_dir($newdir)) {
                    $newdir = $row["name"] . " (" . $i++ . ")";
                }
                // $zipfile -> add_dir($dir . $newdir);
                add_photos($newchecked, "collection", $dir . $newdir . "/");
            }
        }
    } elseif ($type == "collection") {
        foreach ($checked as $aid) {
            $query = "SELECT * FROM `" . TABLE_PREFIX . "albums` WHERE `id`='" . intval($aid) . "'";
            $result = run_query($query);
            while ($row = mysql_fetch_assoc($result)) {
                $query = "SELECT * FROM `" . TABLE_PREFIX . "pictures` WHERE `parent_album`='" . $row["id"] . "'";
                $newresult = run_query($query);
                $newchecked = array();
                while ($newrow = mysql_fetch_assoc($newresult)) {
                    $newchecked[] = $newrow["id"];
                }
                $newdir = $row["name"];
                $i = 1;
                while (is_dir($newdir)) {
                    $newdir = $row["name"] . " (" . $i++ . ")";
                }
                // $zipfile -> add_dir($dir . $newdir);
                add_photos($newchecked, "album", $dir . $newdir . "/");
            }
        }
    } elseif ($type == "album" || $type == "search") {
        foreach ($checked as $pid) {
            $query = "SELECT * FROM `" . TABLE_PREFIX . "pictures` WHERE `id`='" . intval($pid) . "'";
            $result = run_query($query);
            while ($row = mysql_fetch_assoc($result)) {
                $file_contents = file_get_contents("images/" . $row["path"], true);
                $zipfile->add_file($file_contents, $row["path"]);
            }
        }
    }
    return;
}
Beispiel #29
0
 function db_create_form_processing($connection, $table)
 {
     $connection = $connection;
     $table = $table;
     $display = $table;
     $query = "";
     $form_is_empty = "";
     function empty_form_test()
     {
         $filled_form_fields_count = "";
         $form_is_empty = "";
         foreach ($_POST as $key => $value) {
             if (!empty($value)) {
                 $filled_form_fields_count += 1;
             }
         }
         if ($filled_form_fields_count > 1) {
             $form_is_empty = FALSE;
         } else {
             $form_is_empty = TRUE;
         }
         return $form_is_empty;
     }
     function construct_query($table)
     {
         $table = $table;
         $query = "";
         $fields = "";
         $columns = "";
         $values = "";
         // May want to re-factor global declaration.
         global $connection;
         if (!empty($_POST)) {
             /* //Debugging
             			//echo "POST Debugging: <br/>";
             			//print_r($_POST);
             			//Debugging */
             $fields = $_POST;
             unset($fields['submit']);
             // Query Format Validation
             /*
             function format_validation($fields) {
             	// Notice: global $connection; being used. May want to re-factor.
             	function primary_validation($fields) {
             		global $connection;
             		//  Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z. 
             		foreach ($fields as $key => $value) {
             			// String test not working.
             			if (is_string($value)) {
             				$value = mysqli_real_escape_string($connection, $value);
             			}
             		}
             		return $fields;
             	}
             	
             	//function secondary_validation($fields) {
             	//	global $connection;
             	//}
             	
             	$fields = primary_validation($fields);
             	//secondary_validation($fields);
             	return $fields;
             }						
             
             $fields = format_validation($fields); 
             */
             // Query Creation Prep
             function input_count($fields)
             {
                 $fields = $fields;
                 $input_count = "";
                 foreach ($fields as $key => $value) {
                     if (!empty($value)) {
                         ++$input_count;
                     }
                 }
                 return $input_count;
             }
             $input_count = input_count($fields);
             // Query Creation
             // mysqli_real_escape_string formats values with special characters so they can be stored in the database and not alter the format of the SQL query statement.
             foreach ($fields as $key => $value) {
                 if (!empty($value) && $input_count > 1) {
                     $value = mysqli_real_escape_string($connection, $value);
                     $columns .= $key . ", ";
                     $values .= "'" . $value . "'" . ", ";
                     --$input_count;
                 } elseif (!empty($value) && $input_count == 1) {
                     $value = mysqli_real_escape_string($connection, $value);
                     $columns .= $key;
                     $values .= "'" . $value . "'";
                 }
             }
             $query = "INSERT INTO ";
             $query .= "{$table} (";
             $query .= "{$columns}) ";
             $query .= "VALUES (";
             $query .= "{$values})";
             //Debugging
             //echo "<br/><br/>Query Debugging: <br/>" . $query . "</br>";
             //Debugging
         } else {
             $query = "";
         }
         return $query;
     }
     function run_query($connection, $query, $display, $form_is_empty)
     {
         $connection = $connection;
         $query = $query;
         $display = $display;
         $form_is_empty = $form_is_empty;
         function db_interfacing($connection, $query, $form_is_empty)
         {
             $connection = $connection;
             $query = $query;
             $form_is_empty = $form_is_empty;
             function send_query($connection, $query, $empty_form_test)
             {
                 $connection = $connection;
                 $form_is_empty = $empty_form_test;
                 $query = $query;
                 if ($form_is_empty == FALSE) {
                     $result = mysqli_query($connection, $query);
                     return $result;
                 }
             }
             $result = send_query($connection, $query, $form_is_empty);
             return $result;
         }
         function report($result, $display, $form_is_empty)
         {
             //$result = $result;
             //$display = $display;
             //$form_is_empty = $form_is_empty;
             if ($result) {
                 echo "Successfully added {$display}.";
                 redirect_to("submission.php?display=personnel", 0);
             } elseif (!empty($_POST) && ($form_is_empty = TRUE)) {
                 echo "Please enter data and click 'Add'.";
             }
         }
         $result = db_interfacing($connection, $query, $form_is_empty);
         report($result, $display, $form_is_empty);
     }
     $form_is_empty = empty_form_test();
     $query = construct_query($table);
     run_query($connection, $query, $display, $form_is_empty);
 }
Beispiel #30
0
    return $ret;
}
require_once "./config.php";
printf("\n");
if (!($conn = new mysqli("myapp", DB_USER, DB_PASSWORD, DB_SCHEMA)) || mysqli_connect_errno()) {
    die(sprintf("Please check the *config.json used and config.php, failed to connect: [%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}
$queries = array();
printf("Creating a test table. Statements should be send to the master...\n");
run_query($conn, "DROP TABLE IF EXISTS test");
run_query($conn, "CREATE TABLE test(id INT)");
run_query($conn, "INSERT INTO test(id) VALUES (1)");
printf("Dumping list of connections. Should be only one, the master connection...\n");
foreach ($queries as $thread_id => $details) {
    printf("\t... Connection %d has run\n", $thread_id);
    foreach ($details as $query) {
        printf("\t\t... %s\n", $query);
    }
}
printf("Running a SELECT, it should be send to the slaves...\n");
run_query($conn, "SELECT 1 FROM DUAL");
printf("Dropping the test table. Statement should be send to the master...\n");
run_query($conn, "DROP TABLE IF EXISTS test");
printf("Dumping list of connections. Should be two: master and slave...\n");
foreach ($queries as $thread_id => $details) {
    printf("\t... Connection %d has run\n", $thread_id);
    foreach ($details as $query) {
        printf("\t\t... %s\n", $query);
    }
}
printf("\n");