<?php
//===============================================/
// select verb for ubiquity
// by mitcho (Michael Yoshitaka Erlewine)
// code at mitcho.com
// http://mitcho.com/code/select/
// license: MPL
//===============================================/

//==USAGE========================================/
// 1. Configure the database config below.
// 2. Put this file on your server.
// 3. Go to this script on your server.
//    You should get a success message.
// 4. Subscribe to the verbs on mitcho.com/code/select/
//    if you haven't already.
// 5. Select the URL to the script (including "http://..."),
//    enter ubiquity and run `setup-select this` on the URL.
//===============================================/

$version '1.0'// this is the "API version"

//==DATABASE CONFIG==============================/
$mysqlhost 'YOUR SERVER HERE'// e.g. localhost
$mysqluser 'YOUR DB USER HERE';
$mysqlpass 'YOUR DB PASS HERE';
$mysqldb   'YOUR DATABASE NAME HERE';
//===============================================/

header("Cache-control: private");

$db = @mysql_connect($mysqlhost$mysqluser$mysqlpass); //connect to server.

if (!$db) {
    echo 
"<p style='color:red'><code>select</code> could not connect to the database.";
}

if (!@
mysql_select_db($mysqldb)) { // set database.
    
echo "<p style='color:red'><code>select</code> could not select the database <code>$mysqldb</code>.</p>";
}

if (isset(
$_REQUEST['task'])) {
    switch(
$_REQUEST['task']) {
        case 
'version':
            echo 
$version;
            break;
        case 
'list-tables':
            
$first true;
            
$query_results mysql_query("show tables");
            echo 
"[";
            while (
$table mysql_fetch_array($query_results)) {
                echo (
$first?'':', ')."'$table[0]'";
                
$first false;
            }
            echo 
"]";
            break;
        case 
'list-columns':
            
$first true;
            
$query_results mysql_query("show columns from ".mysql_real_escape_string($_REQUEST['table']));
            echo 
"[";
            while (
$table mysql_fetch_array($query_results)) {
                echo (
$first?'':', ')."'$table[0]'";
                
$first false;
            }
            echo 
"]";
            break;
        case 
'select':
        case 
'show':
            if (!empty(
$_REQUEST['select']))
                
$query stripslashes('select SQL_CALC_FOUND_ROWS '.$_REQUEST['select']);
            if (!empty(
$_REQUEST['show']))
                
$query 'show '.$_REQUEST['show'];
            if (!isset(
$query))
                
$query 'show tables';
            
prepareQuery(&$query);
    
            if (!(
$result_query = @mysql_query($query))) {
                echo 
"<p style='color:red;'>ERROR ".mysql_errno().": ".mysql_error()."</p>";
                exit;
            }
    
            
displayResults($result_query);
            break;
    }
} else {
    echo 
"select.php successfully installed and connected to $mysqlhost (".mysql_get_host_info().")";
}

//==QUERY PREP==================================/
function prepareQuery($query){
    
// make sure there's a limit to these things
    
if (stristr($query,'select ') !== false and stristr($query,'limit') === false)
        
$query .= ' limit 50';
        
    
// make sure we only are executing one statement; protect against attacks.
    
$i 0;
    
$quot false;
    
$dblquot false;
    
$escape false;
    while (
$i strlen($query)) {
        
$beginescape $escape;
        
$focus substr($query,$i,1);
        if (
$focus == '\\')
            
$escape = !$escape;
        if (!
$escape and !$quot and $focus == '"')
            
$dblquot = !$dblquot;
        if (!
$escape and !$dblquot and $focus == "'")
            
$quot = !$quot;
        if (!
$quot and !$dblquot and $focus == ';') {
            echo 
"<p style='color:red'>You can only execute one statement at a time.</p>";
            exit;
        }
        if (
$beginescape)
            
$escape false;
        if (isset(
$_REQUEST['testfilter']))
            echo 
"$focus$quot$dblquot$escape --- ";

        
$i++;
    }
}

//===============================================/


//==DISPLAY=====================================/

function displayResults($result_query) {

    
// if there was only one value found, and we want to paste it, just return it.
    
if (mysql_num_rows($result_query) == and mysql_num_fields($result_query) == and isset($_REQUEST['paste'])) {
        
$row mysql_fetch_array($result_query);
        echo 
"$row[0]";
        return;
    }

    echo 
"<table><tr>";
    while(
$col = @mysql_fetch_field($result_query))
        echo 
"<th style='text-align:left;font-weight:bold;'>".htmlentities($col->name)."</th>"// "<abbr title='{$col->table}'>".htmlentities($col->name)."</abbr>"
    
echo "</tr>";
    
    while(
$row = @mysql_fetch_row($result_query)) {
        echo 
"<tr>";
        foreach (
$row as $val) {
            echo 
"<td>".htmlentities($val)."</td>";
        }
        echo 
"</tr>";
    }
    echo 
"</table>";
    
    
$count_query mysql_query('select found_rows() as rows');
    
$count mysql_fetch_array($count_query);
    if (
$count[0] >= $rows and !isset($_REQUEST['paste'])) // there are some cases (show's, etc.) where the count is wrong, so we ignore those.
        
echo "<p>$count[0] row".(($count[0] == 1)?"":'s')." found</p>";
}
//===============================================/

?>