/**
  * sqlAddslashes test
  */
 public function testAddSlashes()
 {
     $string = "\\'test''\\''\\'\r\t\n";
     $this->assertEquals("\\\\\\\\\\'test\\'\\'\\\\\\\\\\'\\'\\\\\\\\\\'\\r\\t\\n", PMA_sqlAddSlashes($string, true, true, true));
     $this->assertEquals("\\\\\\\\''test''''\\\\\\\\''''\\\\\\\\''\\r\\t\\n", PMA_sqlAddSlashes($string, true, true, false));
     $this->assertEquals("\\\\\\\\\\'test\\'\\'\\\\\\\\\\'\\'\\\\\\\\\\'\r\t\n", PMA_sqlAddSlashes($string, true, false, true));
     $this->assertEquals("\\\\\\\\''test''''\\\\\\\\''''\\\\\\\\''\r\t\n", PMA_sqlAddSlashes($string, true, false, false));
     $this->assertEquals("\\\\\\'test\\'\\'\\\\\\'\\'\\\\\\'\\r\\t\\n", PMA_sqlAddSlashes($string, false, true, true));
     $this->assertEquals("\\\\''test''''\\\\''''\\\\''\\r\\t\\n", PMA_sqlAddSlashes($string, false, true, false));
     $this->assertEquals("\\\\\\'test\\'\\'\\\\\\'\\'\\\\\\'\r\t\n", PMA_sqlAddSlashes($string, false, false, true));
     $this->assertEquals("\\\\''test''''\\\\''''\\\\''\r\t\n", PMA_sqlAddSlashes($string, false, false, false));
 }
Example #2
0
 /**
  * Save recent tables into phpMyAdmin database.
  *
  * @return true|PMA_Message
  */
 public function saveToDb()
 {
     $username = $GLOBALS['cfg']['Server']['user'];
     $sql_query = " REPLACE INTO " . $this->pma_table . " (`username`, `tables`)" . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes(json_encode($this->tables)) . "')";
     $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
     if (!$success) {
         $message = PMA_Message::error(__('Could not save recent table'));
         $message->addMessage('<br /><br />');
         $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
         return $message;
     }
     return true;
 }
Example #3
0
/**
 * Composes the query necessary to create an event from an HTTP request.
 *
 * @return  string  The CREATE EVENT query.
 */
function PMA_EVN_getQueryFromRequest()
{
    global $_REQUEST, $errors, $event_status, $event_type, $event_interval;
    $query = 'CREATE ';
    if (!empty($_REQUEST['item_definer'])) {
        if (strpos($_REQUEST['item_definer'], '@') !== false) {
            $arr = explode('@', $_REQUEST['item_definer']);
            $query .= 'DEFINER=' . PMA_backquote($arr[0]);
            $query .= '@' . PMA_backquote($arr[1]) . ' ';
        } else {
            $errors[] = __('The definer must be in the "username@hostname" format');
        }
    }
    $query .= 'EVENT ';
    if (!empty($_REQUEST['item_name'])) {
        $query .= PMA_backquote($_REQUEST['item_name']) . ' ';
    } else {
        $errors[] = __('You must provide an event name');
    }
    $query .= 'ON SCHEDULE ';
    if (!empty($_REQUEST['item_type']) && in_array($_REQUEST['item_type'], $event_type)) {
        if ($_REQUEST['item_type'] == 'RECURRING') {
            if (!empty($_REQUEST['item_interval_value']) && !empty($_REQUEST['item_interval_field']) && in_array($_REQUEST['item_interval_field'], $event_interval)) {
                $query .= 'EVERY ' . intval($_REQUEST['item_interval_value']) . ' ';
                $query .= $_REQUEST['item_interval_field'] . ' ';
            } else {
                $errors[] = __('You must provide a valid interval value for the event.');
            }
            if (!empty($_REQUEST['item_starts'])) {
                $query .= "STARTS '" . PMA_sqlAddSlashes($_REQUEST['item_starts']) . "' ";
            }
            if (!empty($_REQUEST['item_ends'])) {
                $query .= "ENDS '" . PMA_sqlAddSlashes($_REQUEST['item_ends']) . "' ";
            }
        } else {
            if (!empty($_REQUEST['item_execute_at'])) {
                $query .= "AT '" . PMA_sqlAddSlashes($_REQUEST['item_execute_at']) . "' ";
            } else {
                $errors[] = __('You must provide a valid execution time for the event.');
            }
        }
    } else {
        $errors[] = __('You must provide a valid type for the event.');
    }
    $query .= 'ON COMPLETION ';
    if (empty($_REQUEST['item_preserve'])) {
        $query .= 'NOT ';
    }
    $query .= 'PRESERVE ';
    if (!empty($_REQUEST['item_status'])) {
        foreach ($event_status['display'] as $key => $value) {
            if ($value == $_REQUEST['item_status']) {
                $query .= $event_status['query'][$key] . ' ';
                break;
            }
        }
    }
    $query .= 'DO ';
    if (!empty($_REQUEST['item_definition'])) {
        $query .= $_REQUEST['item_definition'];
    } else {
        $errors[] = __('You must provide an event definition.');
    }
    return $query;
}
Example #4
0
}
$tables_selected = array();
if (empty($_REQUEST['table_select']) || !is_array($_REQUEST['table_select'])) {
    unset($_REQUEST['submit_search']);
} elseif (!isset($_REQUEST['selectall']) && !isset($_REQUEST['unselectall'])) {
    $tables_selected = array_intersect($_REQUEST['table_select'], $tables_names_only);
}
if (isset($_REQUEST['selectall'])) {
    $tables_selected = $tables_names_only;
} elseif (isset($_REQUEST['unselectall'])) {
    $tables_selected = array();
}
if (empty($_REQUEST['field_str']) || !is_string($_REQUEST['field_str'])) {
    unset($field_str);
} else {
    $field_str = PMA_sqlAddSlashes($_REQUEST['field_str'], true);
}
/**
 * Displays top links if we are not in an Ajax request
 */
$sub_part = '';
if ($GLOBALS['is_ajax_request'] != true) {
    include 'libraries/db_info.inc.php';
    echo '<div id="searchresults">';
}
/**
 * 1. Main search form has been submitted
 */
if (isset($_REQUEST['submit_search'])) {
    /**
     * Builds the SQL search query
Example #5
0
 /**
  * Save this table's UI preferences into phpMyAdmin database.
  *
  * @return true|PMA_Message
  */
 protected function saveUiPrefsToDb()
 {
     $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "." . PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
     $username = $GLOBALS['cfg']['Server']['user'];
     $sql_query = " REPLACE INTO " . $pma_table . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name) . "', '" . PMA_sqlAddSlashes($this->name) . "', '" . PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
     $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
     if (!$success) {
         $message = PMA_Message::error(__('Could not save table UI preferences'));
         $message->addMessage('<br /><br />');
         $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
         return $message;
     }
     // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
     $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
     $rows_count = PMA_DBI_fetch_value($sql_query);
     $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
     if ($rows_count > $max_rows) {
         $num_rows_to_delete = $rows_count - $max_rows;
         $sql_query = ' DELETE FROM ' . $pma_table . ' ORDER BY last_update ASC' . ' LIMIT ' . $num_rows_to_delete;
         $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
         if (!$success) {
             $message = PMA_Message::error(sprintf(__('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'), PMA_showDocu('cfg_Servers_MaxTableUiprefs')));
             $message->addMessage('<br /><br />');
             $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
             print_r($message);
             return $message;
         }
     }
     return true;
 }
Example #6
0
 /**
  * The "Table_Stats" constructor
  *
  * @param string  $tableName      The table name
  * @param integer $fontSize       The font size
  * @param integer $pageNumber     The current page number (from the
  *                                $cfg['Servers'][$i]['table_coords'] table)
  * @param integer &$sameWideWidth The max. with among tables
  * @param boolean $showKeys       Whether to display keys or not
  * @param boolean $showInfo       Whether to display table position or not
  *
  * @global object    The current PDF document
  * @global array     The relations settings
  * @global string    The current db name
  *
  * @return void
  *
  * @see PMA_Schema_PDF, Table_Stats::Table_Stats_setWidth,
  *     Table_Stats::Table_Stats_setHeight
  */
 function __construct($tableName, $fontSize, $pageNumber, &$sameWideWidth, $showKeys = false, $showInfo = false)
 {
     global $pdf, $cfgRelation, $db;
     $this->_tableName = $tableName;
     $sql = 'DESCRIBE ' . PMA_backquote($tableName);
     $result = PMA_DBI_try_query($sql, null, PMA_DBI_QUERY_STORE);
     if (!$result || !PMA_DBI_num_rows($result)) {
         $pdf->Error(sprintf(__('The %s table doesn\'t exist!'), $tableName));
     }
     // load fields
     //check to see if it will load all fields or only the foreign keys
     if ($showKeys) {
         $indexes = PMA_Index::getFromTable($this->_tableName, $db);
         $all_columns = array();
         foreach ($indexes as $index) {
             $all_columns = array_merge($all_columns, array_flip(array_keys($index->getColumns())));
         }
         $this->fields = array_keys($all_columns);
     } else {
         while ($row = PMA_DBI_fetch_row($result)) {
             $this->fields[] = $row[0];
         }
     }
     $this->_showInfo = $showInfo;
     $this->_setHeight();
     /*
      * setWidth must me after setHeight, because title
      * can include table height which changes table width
      */
     $this->_setWidth($fontSize);
     if ($sameWideWidth < $this->width) {
         $sameWideWidth = $this->width;
     }
     $sql = 'SELECT x, y FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'' . ' AND   table_name = \'' . PMA_sqlAddSlashes($tableName) . '\'' . ' AND   pdf_page_number = ' . $pageNumber;
     $result = PMA_query_as_controluser($sql, false, PMA_DBI_QUERY_STORE);
     if (!$result || !PMA_DBI_num_rows($result)) {
         $pdf->Error(sprintf(__('Please configure the coordinates for table %s'), $tableName));
     }
     list($this->x, $this->y) = PMA_DBI_fetch_row($result);
     $this->x = (double) $this->x;
     $this->y = (double) $this->y;
     /*
      * displayfield
      */
     $this->displayfield = PMA_getDisplayField($db, $tableName);
     /*
      * index
      */
     $result = PMA_DBI_query('SHOW INDEX FROM ' . PMA_backquote($tableName) . ';', null, PMA_DBI_QUERY_STORE);
     if (PMA_DBI_num_rows($result) > 0) {
         while ($row = PMA_DBI_fetch_assoc($result)) {
             if ($row['Key_name'] == 'PRIMARY') {
                 $this->primary[] = $row['Column_name'];
             }
         }
     }
 }
/**
 * returns collation of given db
 *
 * @uses    PMA_DBI_fetch_value()
 * @uses    PMA_DBI_select_db()
 * @uses    PMA_sqlAddSlashes()
 * @uses    $GLOBALS['db']
 * @param   string  $db     name of db
 * @return  string  collation of $db
 */
function PMA_getDbCollation($db)
{
    if ($db == 'information_schema') {
        // We don't have to check the collation of the virtual
        // information_schema database: We know it!
        return 'utf8_general_ci';
    }
    if (!$GLOBALS['cfg']['Server']['DisableIS']) {
        // this is slow with thousands of databases
        return PMA_DBI_fetch_value('SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = \'' . PMA_sqlAddSlashes($db) . '\' LIMIT 1;');
    } else {
        PMA_DBI_select_db($db);
        $return = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'collation_database\'', 0, 1);
        if ($db !== $GLOBALS['db']) {
            PMA_DBI_select_db($GLOBALS['db']);
        }
        return $return;
    }
}
Example #8
0
        $retval = $pmatable->setUiProp(PMA_Table::PROP_COLUMN_VISIB, $col_visib, $_REQUEST['table_create_time']);
        if (gettype($retval) != 'boolean') {
            PMA_ajaxResponse($retval->getString(), false);
        }
    }

    PMA_ajaxResponse(null, ($retval == true));
}

// Default to browse if no query set and we have table
// (needed for browsing from DefaultTabTable)
if (empty($sql_query) && strlen($table) && strlen($db)) {
    include_once 'libraries/bookmark.lib.php';
    $book_sql_query = PMA_Bookmark_get(
        $db,
        '\'' . PMA_sqlAddSlashes($table) . '\'',
        'label',
        false,
        true
    );

    if (! empty($book_sql_query)) {
        $GLOBALS['using_bookmark_message'] = PMA_message::notice(__('Using bookmark "%s" as default browse query.'));
        $GLOBALS['using_bookmark_message']->addParam($table);
        $GLOBALS['using_bookmark_message']->addMessage(PMA_showDocu('faq6_22'));
        $sql_query = $book_sql_query;
    } else {
        $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
    }
    unset($book_sql_query);
 /**
  * Outputs the content of a table in SQL format
  *
  * @param string  $db         database name
  * @param string  $table      table name
  * @param string  $crlf       the end of line sequence
  * @param string  $error_url  the url to go back in case of error
  * @param string  $sql_query  SQL query for obtaining data
  * @return  bool        Whether it succeeded
  *
  * @access  public
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $sql_backquotes;
     global $current_row;
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_backquote($table) : '\'' . $table . '\'';
     // Do not export data for a VIEW
     // (For a VIEW, this is called only when exporting a single VIEW)
     if (PMA_Table::isView($db, $table)) {
         $head = PMA_possibleCRLF() . PMA_exportComment() . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name) . PMA_exportComment(__('Data') . ': ' . __('None')) . PMA_exportComment() . PMA_possibleCRLF();
         if (!PMA_exportOutputHandler($head)) {
             return false;
         }
         return true;
     }
     // analyze the query to get the true column names, not the aliases
     // (this fixes an undefined index, also if Complete inserts
     //  are used, we did not get the true column name in case of aliases)
     $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
     $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     // a possible error: the table has crashed
     $tmp_error = PMA_DBI_getError();
     if ($tmp_error) {
         return PMA_exportOutputHandler(PMA_exportComment(__('Error reading data:') . ' (' . $tmp_error . ')'));
     }
     if ($result != false) {
         $fields_cnt = PMA_DBI_num_fields($result);
         // Get field information
         $fields_meta = PMA_DBI_get_fields_meta($result);
         $field_flags = array();
         for ($j = 0; $j < $fields_cnt; $j++) {
             $field_flags[$j] = PMA_DBI_field_flags($result, $j);
         }
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
                 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
             } else {
                 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
             }
         }
         if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
             // update
             $schema_insert = 'UPDATE ';
             if (isset($GLOBALS['sql_ignore'])) {
                 $schema_insert .= 'IGNORE ';
             }
             // avoid EOL blank
             $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
         } else {
             // insert or replace
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
                 $sql_command = 'REPLACE';
             } else {
                 $sql_command = 'INSERT';
             }
             // delayed inserts?
             if (isset($GLOBALS['sql_delayed'])) {
                 $insert_delayed = ' DELAYED';
             } else {
                 $insert_delayed = '';
             }
             // insert ignore?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
                 $insert_delayed .= ' IGNORE';
             }
             // scheme for inserting fields
             if ($GLOBALS['sql_insert_syntax'] == 'complete' || $GLOBALS['sql_insert_syntax'] == 'both') {
                 $fields = implode(', ', $field_set);
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' (' . $fields . ') VALUES';
             } else {
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' VALUES';
             }
         }
         $search = array("", "\n", "\r", "");
         //\x08\\x09, not required
         $replace = array('\\0', '\\n', '\\r', '\\Z');
         $current_row = 0;
         $query_size = 0;
         if (($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             if ($current_row == 0) {
                 $head = PMA_possibleCRLF() . PMA_exportComment() . PMA_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name) . PMA_exportComment() . $crlf;
                 if (!PMA_exportOutputHandler($head)) {
                     return false;
                 }
             }
             $current_row++;
             for ($j = 0; $j < $fields_cnt; $j++) {
                 // NULL
                 if (!isset($row[$j]) || is_null($row[$j])) {
                     $values[] = 'NULL';
                     // a number
                     // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
                 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                     $values[] = $row[$j];
                     // a true BLOB
                     // - mysqldump only generates hex data when the --hex-blob
                     //   option is used, for fields having the binary attribute
                     //   no hex is generated
                     // - a TEXT field returns type blob but a real blob
                     //   returns also the 'binary' flag
                 } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob && isset($GLOBALS['sql_hex_for_blob'])) {
                     // empty blobs need to be different, but '0' is also empty :-(
                     if (empty($row[$j]) && $row[$j] != '0') {
                         $values[] = '\'\'';
                     } else {
                         $values[] = '0x' . bin2hex($row[$j]);
                     }
                     // detection of 'bit' works only on mysqli extension
                 } elseif ($fields_meta[$j]->type == 'bit') {
                     $values[] = "b'" . PMA_sqlAddSlashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length)) . "'";
                     // something else -> treat as a string
                 } else {
                     $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddSlashes($row[$j])) . '\'';
                 }
                 // end if
             }
             // end for
             // should we make update?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
                 $insert_line = $schema_insert;
                 for ($i = 0; $i < $fields_cnt; $i++) {
                     if (0 == $i) {
                         $insert_line .= ' ';
                     }
                     if ($i > 0) {
                         // avoid EOL blank
                         $insert_line .= ',';
                     }
                     $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                 }
                 list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
                 $insert_line .= ' WHERE ' . $tmp_unique_condition;
                 unset($tmp_unique_condition, $tmp_clause_is_unique);
             } else {
                 // Extended inserts case
                 if ($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') {
                     if ($current_row == 1) {
                         $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                     } else {
                         $insert_line = '(' . implode(', ', $values) . ')';
                         if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
                             if (!PMA_exportOutputHandler(';' . $crlf)) {
                                 return false;
                             }
                             $query_size = 0;
                             $current_row = 1;
                             $insert_line = $schema_insert . $insert_line;
                         }
                     }
                     $query_size += strlen($insert_line);
                 } else {
                     $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                 }
             }
             unset($values);
             if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
                 return false;
             }
         }
         // end while
         if ($current_row > 0) {
             if (!PMA_exportOutputHandler(';' . $crlf)) {
                 return false;
             }
         }
     }
     // end if ($result != false)
     PMA_DBI_free_result($result);
     return true;
 }
Example #10
0
    $disp     = PMA_getDisplayField($db, $table);
    if ($disp) {
        if ($display_field != $disp) {
            $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
                       . ' SET display_field = \'' . PMA_sqlAddSlashes($display_field) . '\''
                       . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\''
                       . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
        } else {
            $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
                       . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\''
                       . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
        }
    } elseif ($display_field != '') {
        $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
                   . '(db_name, table_name, display_field) '
                   . ' VALUES('
                   . '\'' . PMA_sqlAddSlashes($db) . '\','
                   . '\'' . PMA_sqlAddSlashes($table) . '\','
                   . '\'' . PMA_sqlAddSlashes($display_field) . '\')';
    }

    if (isset($upd_query)) {
        $upd_rs    = PMA_query_as_controluser($upd_query);
    }
} // end if

header("Content-Type: text/xml; charset=utf-8");
header("Cache-Control: no-cache");
die("<root act='save_pos' return=__('Modifications have been saved')></root>");
?>
Example #11
0
}
$sql .= ' INFILE \'' . PMA_sqlAddSlashes($import_file) . '\'';
if (isset($ldi_replace)) {
    $sql .= ' REPLACE';
} elseif (isset($ldi_ignore)) {
    $sql .= ' IGNORE';
}
$sql .= ' INTO TABLE ' . PMA_backquote($table);
if (strlen($ldi_terminated) > 0) {
    $sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\'';
}
if (strlen($ldi_enclosed) > 0) {
    $sql .= ' ENCLOSED BY \'' . PMA_sqlAddSlashes($ldi_enclosed) . '\'';
}
if (strlen($ldi_escaped) > 0) {
    $sql .= ' ESCAPED BY \'' . PMA_sqlAddSlashes($ldi_escaped) . '\'';
}
if (strlen($ldi_new_line) > 0) {
    if ($ldi_new_line == 'auto') {
        $ldi_new_line = PMA_whichCrlf() == "\n" ? '\\n' : '\\r\\n';
    }
    $sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\'';
}
if ($skip_queries > 0) {
    $sql .= ' IGNORE ' . $skip_queries . ' LINES';
    $skip_queries = 0;
}
if (strlen($ldi_columns) > 0) {
    $sql .= ' (';
    $tmp = preg_split('/,( ?)/', $ldi_columns);
    $cnt_tmp = count($tmp);
Example #12
0
        echo '</div>';
    }
    // end if
}
// end if (!$is_information_schema)
// not sure about displaying the PDF dialog in case db is information_schema
if ($cfgRelation['pdfwork'] && $num_tables > 0) {
    ?>
    <!-- Work on PDF Pages -->

    <?php 
    // We only show this if we find something in the new pdf_pages table
    $test_query = '
         SELECT *
           FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages']) . '
          WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'';
    $test_rs = PMA_query_as_controluser($test_query, null, PMA_DBI_QUERY_STORE);
    /*
     * Export Relational Schema View
     */
    echo '<div class="operations_full_width"><fieldset><a href="schema_edit.php?' . $url_query . '">';
    if ($cfg['PropertiesIconic']) {
        echo PMA_getImage('b_edit.png');
    }
    echo __('Edit or export relational schema') . '</a></fieldset></div>';
}
// end if
/**
 * Displays the footer
 */
require 'libraries/footer.inc.php';
Example #13
0
    /**
     * Analyzes a given SQL statement and saves tracking data.
     *
     * @param string $query a SQL query
     *
     * @static
     *
     * @return void
     */
    static public function handleQuery($query)
    {
        // If query is marked as untouchable, leave
        if (strstr($query, "/*NOTRACK*/")) {
            return;
        }

        if (! (substr($query, -1) == ';')) {
            $query = $query . ";\n";
        }
        // Get some information about query
        $result = self::parseQuery($query);

        // Get database name
        $dbname = trim($GLOBALS['db'], '`');
        // $dbname can be empty, for example when coming from Synchronize
        // and this is a query for the remote server
        if (empty($dbname)) {
            return;
        }

        // If we found a valid statement
        if (isset($result['identifier'])) {
            $version = self::getVersion($dbname, $result['tablename'], $result['identifier']);

            // If version not exists and auto-creation is enabled
            if (self::$version_auto_create == true
                && self::isTracked($dbname, $result['tablename']) == false
                && $version == -1
            ) {
                // Create the version

                switch ($result['identifier']) {
                case 'CREATE TABLE':
                    self::createVersion($dbname, $result['tablename'], '1');
                    break;
                case 'CREATE VIEW':
                    self::createVersion($dbname, $result['tablename'], '1', '', true);
                    break;
                case 'CREATE DATABASE':
                    self::createDatabaseVersion($dbname, '1', $query);
                    break;
                } // end switch
            }

            // If version exists
            if (self::isTracked($dbname, $result['tablename']) && $version != -1) {
                if ($result['type'] == 'DDL') {
                    $save_to = 'schema_sql';
                } elseif ($result['type'] == 'DML') {
                    $save_to = 'data_sql';
                } else {
                    $save_to = '';
                }
                $date  = date('Y-m-d H:i:s');

                // Cut off `dbname`. from query
                $query = preg_replace('/`' . $dbname . '`\s?\./', '', $query);

                // Add log information
                $query = self::getLogComment() . $query ;

                // Mark it as untouchable
                $sql_query = " /*NOTRACK*/\n" .
                " UPDATE " . self::$pma_table .
                " SET " . PMA_backquote($save_to) ." = CONCAT( " . PMA_backquote($save_to) . ",'\n"
                . PMA_sqlAddSlashes($query) . "') ," . " `date_updated` = '" . $date . "' ";

                // If table was renamed we have to change the tablename attribute in pma_tracking too
                if ($result['identifier'] == 'RENAME TABLE') {
                    $sql_query .= ', `table_name` = \'' . PMA_sqlAddSlashes($result['tablename_after_rename']) . '\' ';
                }

                // Save the tracking information only for
                //     1. the database
                //     2. the table / view
                //     3. the statements
                // we want to track
                $sql_query .=
                " WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" .
                " AND `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
                " AND `table_name` = '" . PMA_sqlAddSlashes($result['tablename']) . "' " .
                " AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";

                $result = PMA_query_as_controluser($sql_query);
            }
        }
    }
Example #14
0
 $db_info_result = PMA_DBI_query('SHOW OPEN TABLES FROM ' . PMA_backquote($db) . ';');
 // Blending out tables in use
 if ($db_info_result && PMA_DBI_num_rows($db_info_result) > 0) {
     while ($tmp = PMA_DBI_fetch_row($db_info_result)) {
         // if in use memorize tablename
         if (preg_match('@in_use=[1-9]+@i', $tmp[1])) {
             $sot_cache[$tmp[0]] = true;
         }
     }
     PMA_DBI_free_result($db_info_result);
     if (isset($sot_cache)) {
         $db_info_result = PMA_DBI_query('SHOW TABLES FROM ' . PMA_backquote($db) . $tbl_group_sql . ';', null, PMA_DBI_QUERY_STORE);
         if ($db_info_result && PMA_DBI_num_rows($db_info_result) > 0) {
             while ($tmp = PMA_DBI_fetch_row($db_info_result)) {
                 if (!isset($sot_cache[$tmp[0]])) {
                     $sts_result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddSlashes($tmp[0], true) . '\';');
                     $sts_tmp = PMA_DBI_fetch_assoc($sts_result);
                     PMA_DBI_free_result($sts_result);
                     unset($sts_result);
                     if (!isset($sts_tmp['Type']) && isset($sts_tmp['Engine'])) {
                         $sts_tmp['Type'] =& $sts_tmp['Engine'];
                     }
                     if (!empty($tbl_group) && $cfg['ShowTooltipAliasTB'] && !preg_match('@' . preg_quote($tbl_group, '@') . '@i', $sts_tmp['Comment'])) {
                         continue;
                     }
                     if ($cfg['ShowTooltip']) {
                         PMA_fillTooltip($tooltip_truename, $tooltip_aliasname, $sts_tmp);
                     }
                     $tables[$sts_tmp['Name']] = $sts_tmp;
                 } else {
                     // table in use
Example #15
0
$go_sql = false;
$executed_queries = 0;
$run_query = true;
$charset_conversion = false;
$reset_charset = false;
$bookmark_created = false;
// Bookmark Support: get a query back from bookmark if required
if (!empty($id_bookmark)) {
    $id_bookmark = (int) $id_bookmark;
    include_once './libraries/bookmark.lib.php';
    switch ($action_bookmark) {
        case 0:
            // bookmarked query that have to be run
            $import_text = PMA_Bookmark_get($db, $id_bookmark, 'id', isset($action_bookmark_all));
            if (isset($bookmark_variable) && !empty($bookmark_variable)) {
                $import_text = preg_replace('|/\\*(.*)\\[VARIABLE\\](.*)\\*/|imsU', '${1}' . PMA_sqlAddSlashes($bookmark_variable) . '${2}', $import_text);
            }
            // refresh left frame on changes in table or db structure
            if (preg_match('/^(CREATE|ALTER|DROP)\\s+(VIEW|TABLE|DATABASE|SCHEMA)\\s+/i', $import_text)) {
                $GLOBALS['reload'] = true;
            }
            break;
        case 1:
            // bookmarked query that have to be displayed
            $import_text = PMA_Bookmark_get($db, $id_bookmark);
            if ($GLOBALS['is_ajax_request'] == true) {
                $extra_data['sql_query'] = $import_text;
                $extra_data['action_bookmark'] = $action_bookmark;
                $message = PMA_Message::success(__('Showing bookmark'));
                PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
            } else {
Example #16
0
                      (db_name, table_name, column_name, comment)
                 VALUES (
                        \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
                        \'' . PMA_sqlAddSlashes(trim($tab)) . '\',
                        \'' . PMA_sqlAddSlashes(trim($inf[0])) . '\',
                        \'' . PMA_sqlAddSlashes(trim($inf[1])) . '\')';
            PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]), true);
        }
        // end inf[1] exists
        if (!empty($inf[2]) && strlen(trim($inf[2])) > 0) {
            $for = explode('->', $inf[2]);
            $qry = '
                 INSERT INTO
                        ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
                      (master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)
                 VALUES (
                        \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
                        \'' . PMA_sqlAddSlashes(trim($tab)) . '\',
                        \'' . PMA_sqlAddSlashes(trim($inf[0])) . '\',
                        \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
                        \'' . PMA_sqlAddSlashes(trim($for[0])) . '\',
                        \'' . PMA_sqlAddSlashes(trim($for[1])) . '\')';
            PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]) . '(' . htmlspecialchars($inf[2]) . ')', true);
        }
        // end inf[2] exists
    }
    // End lines loop
}
// End import
// Commit any possible data in buffers
PMA_importRunQuery();
Example #17
0
 */
require_once './libraries/pmd_common.php';
$cfgRelation = PMA_getRelationsParam();
if (!$cfgRelation['designerwork']) {
    PMD_err_sav();
}
foreach ($t_x as $key => $value) {
    $KEY = empty($IS_AJAX) ? urldecode($key) : $key;
    // table name decode (post PDF exp/imp)
    list($DB, $TAB) = explode(".", $KEY);
    PMA_query_as_controluser('DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
                      WHERE `db_name` = \'' . PMA_sqlAddSlashes($DB) . '\'
                        AND `table_name` = \'' . PMA_sqlAddSlashes($TAB) . '\'', true, PMA_DBI_QUERY_STORE);
    PMA_query_as_controluser('INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
                         (db_name, table_name, x, y, v, h)
                  VALUES (' . '\'' . PMA_sqlAddSlashes($DB) . '\', ' . '\'' . PMA_sqlAddSlashes($TAB) . '\', ' . '\'' . PMA_sqlAddSlashes($t_x[$key]) . '\', ' . '\'' . PMA_sqlAddSlashes($t_y[$key]) . '\', ' . '\'' . PMA_sqlAddSlashes($t_v[$key]) . '\', ' . '\'' . PMA_sqlAddSlashes($t_h[$key]) . '\'' . ')', true, PMA_DBI_QUERY_STORE);
}
//----------------------------------------------------------------------------
function PMD_err_sav()
{
    global $die_save_pos;
    // if this file included
    if (!empty($die_save_pos)) {
        header("Content-Type: text/xml; charset=utf-8");
        header("Cache-Control: no-cache");
        die('<root act="save_pos" return="' . __('Error saving coordinates for Designer.') . '"></root>');
    }
}
if (!empty($die_save_pos)) {
    header("Content-Type: text/xml; charset=utf-8");
    header("Cache-Control: no-cache");
Example #18
0
     //  i n s e r t
     if ($is_insert) {
         // no need to add column into the valuelist
         if (strlen($cur_value)) {
             $query_values[] = $cur_value;
             // first inserted row so prepare the list of fields
             if (empty($value_sets)) {
                 $query_fields[] = PMA_backquote($me_fields_name[$key]);
             }
         }
         //  u p d a t e
     } elseif (!empty($me_fields_null_prev[$key]) && !isset($me_fields_null[$key])) {
         // field had the null checkbox before the update
         // field no longer has the null checkbox
         $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
     } elseif (empty($me_funcs[$key]) && isset($me_fields_prev[$key]) && "'" . PMA_sqlAddSlashes($me_fields_prev[$key]) . "'" == $val) {
         // No change for this column and no MySQL function is used -> next column
         continue;
     } elseif (!empty($val)) {
         // avoid setting a field to NULL when it's already NULL
         // (field had the null checkbox before the update
         //  field still has the null checkbox)
         if (empty($me_fields_null_prev[$key]) || empty($me_fields_null[$key])) {
             $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
         }
     }
 }
 // end foreach ($me_fields as $key => $val)
 if (count($query_values) > 0) {
     if ($is_insert) {
         $value_sets[] = implode(', ', $query_values);
Example #19
0
/**
 * Create a PDF page
 *
 * @param string $newpage     name of the new PDF page
 * @param array  $cfgRelation
 * @param string $db          database name
 *
 * @return string   $pdf_page_number
 */
function PMA_REL_create_page($newpage, $cfgRelation, $db)
{
    if (!isset($newpage) || $newpage == '') {
        $newpage = __('no description');
    }
    $ins_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages']) . ' (db_name, page_descr)' . ' VALUES (\'' . PMA_sqlAddSlashes($db) . '\', \'' . PMA_sqlAddSlashes($newpage) . '\')';
    PMA_query_as_controluser($ins_query, false);
    return PMA_DBI_insert_id(isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : '');
}
Example #20
0
/**
 * purges SQL history
 *
 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
 * given user
 *
 * @uses    $cfg['QueryHistoryMax']
 * @uses    $cfg['QueryHistoryDB']
 * @uses    $GLOBALS['controllink']
 * @uses    PMA_backquote()
 * @uses    PMA_sqlAddSlashes()
 * @uses    PMA_query_as_cu()
 * @uses    PMA_DBI_fetch_value()
 * @param   string   $username  the username
 * @access  public
 */
function PMA_purgeHistory($username)
{
    $cfgRelation = PMA_getRelationsParam();
    if (!$GLOBALS['cfg']['QueryHistoryDB'] || !$cfgRelation['historywork']) {
        return;
    }
    if (!$cfgRelation['historywork']) {
        return;
    }
    $search_query = '
         SELECT `timevalue`
           FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
          WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
       ORDER BY `timevalue` DESC
          LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
    if ($max_time = PMA_DBI_fetch_value($search_query, 0, 0, $GLOBALS['controllink'])) {
        PMA_query_as_cu('
             DELETE FROM
                    ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
              WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
                AND `timevalue` <= \'' . $max_time . '\'');
    }
}
Example #21
0
 /**
  * returns collation of given db
  *
  * @uses    PMA_MYSQL_INT_VERSION
  * @uses    PMA_DBI_fetch_value()
  * @uses    PMA_DBI_select_db()
  * @uses    PMA_sqlAddSlashes()
  * @uses    $GLOBALS['db']
  * @param   string  $db     name of db
  * @return  string  collation of $db
  */
 function PMA_getDbCollation($db)
 {
     if (PMA_MYSQL_INT_VERSION >= 50000 && $db == 'information_schema') {
         // We don't have to check the collation of the virtual
         // information_schema database: We know it!
         return 'utf8_general_ci';
     }
     if (PMA_MYSQL_INT_VERSION >= 50006) {
         // Since MySQL 5.0.6, we don't have to parse SHOW CREATE DATABASE anymore.
         return PMA_DBI_fetch_value('SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = \'' . PMA_sqlAddSlashes($db) . '\' LIMIT 1;');
     } elseif (PMA_MYSQL_INT_VERSION >= 40101) {
         // MySQL 4.1.0 does not support seperate charset settings
         // for databases.
         PMA_DBI_select_db($db);
         // the query does not work if this string is in double quotes
         // and MySQL is running in ANSI mode
         $return = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'collation_database\'', 0, 1);
         if ($db !== $GLOBALS['db']) {
             PMA_DBI_select_db($GLOBALS['db']);
         }
         return $return;
     }
     return '';
 }
Example #22
0
/**
 * Set a SQL history entry
 *
 * @param   string   the name of the db
 * @param   string   the name of the table
 * @param   string   the username
 * @param   string   the sql query
 *
 * @global  array    the list of relations settings
 * @global  array    global phpMyAdmin configuration
 *
 * @return  boolean  true
 *
 * @access  public
 */
function PMA_purgeHistory($username)
{
    global $cfgRelation, $cfg;
    $purge_query = '
         SELECT timevalue
           FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
          WHERE username = \'' . PMA_sqlAddSlashes($username) . '\'
       ORDER BY timevalue DESC LIMIT ' . $cfg['QueryHistoryMax'] . ', 1';
    $purge_rs = PMA_query_as_cu($purge_query);
    $i = 0;
    $row = PMA_DBI_fetch_row($purge_rs);
    PMA_DBI_free_result($purge_rs);
    if (is_array($row) && isset($row[0]) && $row[0] > 0) {
        $maxtime = $row[0];
        // quotes added around $maxtime to prevent a difficult to
        // reproduce problem
        $remove_rs = PMA_query_as_cu('
             DELETE FROM 
                    ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
              WHERE timevalue <= \'' . $maxtime . '\'');
    }
    return true;
}
Example #23
0
/**
 * PMA_populateTargetTables() inserts data into uncommon tables after they have been created
 *
 * @param string $src_db                 name of source database
 * @param string $trg_db                 name of target database
 * @param mixed  $src_link               connection established with source server
 * @param mixed  $trg_link               connection established with target server
 * @param array  $uncommon_tables        uncommon table names (table names that are present in source but not in target db)
 * @param int    $table_index            index of table in matching_table_array
 * @param array  $uncommon_tables_fields field names of the uncommon table
 * @param bool   $display
 *
 * @todo This turns NULL values into '' (empty string)
 */
function PMA_populateTargetTables($src_db, $trg_db, $src_link, $trg_link, $uncommon_tables, $table_index, $uncommon_tables_fields, $display)
{
    $display = false;
    // todo: maybe display some of the queries if they are not too numerous
    $unbuffered_result = PMA_DBI_try_query('SELECT * FROM ' . PMA_backquote($src_db) . '.' . PMA_backquote($uncommon_tables[$table_index]), $src_link, PMA_DBI_QUERY_UNBUFFERED);
    if (false !== $unbuffered_result) {
        $insert_query = 'INSERT INTO ' . PMA_backquote($trg_db) . '.' . PMA_backquote($uncommon_tables[$table_index]) . ' VALUES';
        while ($one_row = PMA_DBI_fetch_row($unbuffered_result)) {
            $insert_query .= '(';
            $key_of_last_value = count($one_row) - 1;
            foreach ($one_row as $key => $value) {
                $insert_query .= "'" . PMA_sqlAddSlashes($value) . "'";
                if ($key < $key_of_last_value) {
                    $insert_query .= ",";
                }
            }
            $insert_query .= '),';
        }
        $insert_query = substr($insert_query, 0, -1);
        $insert_query .= ';';
        if ($display == true) {
            PMA_displayQuery($insert_query);
        }
        PMA_DBI_try_query($insert_query, $trg_link, 0);
    }
}
Example #24
0
 /**
  * update X and Y coordinates for a table
  *
  * @param string $db          The database name
  * @param array  $cfgRelation relation settings
  *
  * @return void
  * @access private
  */
 private function _editCoordinates($db, $cfgRelation)
 {
     for ($i = 0; $i < $this->c_table_rows; $i++) {
         $arrvalue = 'c_table_' . $i;
         global ${$arrvalue};
         $arrvalue = ${$arrvalue};
         if (!isset($arrvalue['x']) || $arrvalue['x'] == '') {
             $arrvalue['x'] = 0;
         }
         if (!isset($arrvalue['y']) || $arrvalue['y'] == '') {
             $arrvalue['y'] = 0;
         }
         if (isset($arrvalue['name']) && $arrvalue['name'] != '--') {
             $test_query = 'SELECT * FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'' . ' AND   table_name = \'' . PMA_sqlAddSlashes($arrvalue['name']) . '\'' . ' AND   pdf_page_number = \'' . PMA_sqlAddSlashes($this->chosenPage) . '\'';
             $test_rs = PMA_query_as_controluser($test_query, false, PMA_DBI_QUERY_STORE);
             //echo $test_query;
             if ($test_rs && PMA_DBI_num_rows($test_rs) > 0) {
                 if (isset($arrvalue['delete']) && $arrvalue['delete'] == 'y') {
                     $ch_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'' . ' AND   table_name = \'' . PMA_sqlAddSlashes($arrvalue['name']) . '\'' . ' AND   pdf_page_number = \'' . PMA_sqlAddSlashes($this->chosenPage) . '\'';
                 } else {
                     $ch_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' ' . 'SET x = ' . $arrvalue['x'] . ', y= ' . $arrvalue['y'] . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'' . ' AND   table_name = \'' . PMA_sqlAddSlashes($arrvalue['name']) . '\'' . ' AND   pdf_page_number = \'' . PMA_sqlAddSlashes($this->chosenPage) . '\'';
                 }
             } else {
                 $ch_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' ' . '(db_name, table_name, pdf_page_number, x, y) ' . 'VALUES (\'' . PMA_sqlAddSlashes($db) . '\', \'' . PMA_sqlAddSlashes($arrvalue['name']) . '\', \'' . PMA_sqlAddSlashes($this->chosenPage) . '\',' . $arrvalue['x'] . ',' . $arrvalue['y'] . ')';
             }
             //echo $ch_query;
             PMA_query_as_controluser($ch_query, false);
         }
         // end if
     }
     // end for
 }
Example #25
0
/**
 * Handles requests for executing a routine
 */
function PMA_RTN_handleExecute()
{
    global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $cfg;
    /**
     * Handle all user requests other than the default of listing routines
     */
    if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) {
        // Build the queries
        $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false);
        if ($routine !== false) {
            $queries = array();
            $end_query = array();
            $args = array();
            for ($i = 0; $i < $routine['item_num_params']; $i++) {
                if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) {
                    $value = $_REQUEST['params'][$routine['item_param_name'][$i]];
                    if (is_array($value)) {
                        // is SET type
                        $value = implode(',', $value);
                    }
                    $value = PMA_sqlAddSlashes($value);
                    if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $cfg['Functions'])) {
                        $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n";
                    } else {
                        $queries[] = "SET @p{$i}='{$value}';\n";
                    }
                    $args[] = "@p{$i}";
                } else {
                    $args[] = "@p{$i}";
                }
                if ($routine['item_type'] == 'PROCEDURE') {
                    if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') {
                        $end_query[] = "@p{$i} AS " . PMA_backquote($routine['item_param_name'][$i]);
                    }
                }
            }
            if ($routine['item_type'] == 'PROCEDURE') {
                $queries[] = "CALL " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n";
                if (count($end_query)) {
                    $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
                }
            } else {
                $queries[] = "SELECT " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_backquote($routine['item_name']) . ";\n";
            }
            // Execute the queries
            $affected = 0;
            $result = null;
            $outcome = true;
            foreach ($queries as $query) {
                $resource = PMA_DBI_try_query($query);
                if ($resource === false) {
                    $outcome = false;
                    break;
                }
                while (true) {
                    if (!PMA_DBI_more_results()) {
                        break;
                    }
                    PMA_DBI_next_result();
                }
                if (substr($query, 0, 6) == 'SELECT') {
                    $result = $resource;
                } else {
                    if (substr($query, 0, 4) == 'CALL') {
                        $result = $resource ? $resource : $result;
                        $affected = PMA_DBI_affected_rows() - PMA_DBI_num_rows($resource);
                    }
                }
            }
            // Generate output
            if ($outcome) {
                $message = __('Your SQL query has been executed successfully');
                if ($routine['item_type'] == 'PROCEDURE') {
                    $message .= '<br />';
                    $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected);
                }
                $message = PMA_message::success($message);
                // Pass the SQL queries through the "pretty printer"
                $output = '<code class="sql" style="margin-bottom: 1em;">';
                $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries)));
                $output .= '</code>';
                // Display results
                if ($result) {
                    $output .= "<fieldset><legend>";
                    $output .= sprintf(__('Execution results of routine %s'), PMA_backquote(htmlspecialchars($routine['item_name'])));
                    $output .= "</legend>";
                    $output .= "<table><tr>";
                    foreach (PMA_DBI_get_fields_meta($result) as $key => $field) {
                        $output .= "<th>";
                        $output .= htmlspecialchars($field->name);
                        $output .= "</th>";
                    }
                    $output .= "</tr>";
                    // Stored routines can only ever return ONE ROW.
                    $data = PMA_DBI_fetch_single_row($result);
                    foreach ($data as $key => $value) {
                        if ($value === null) {
                            $value = '<i>NULL</i>';
                        } else {
                            $value = htmlspecialchars($value);
                        }
                        $output .= "<td class='odd'>" . $value . "</td>";
                    }
                    $output .= "</table></fieldset>";
                } else {
                    $notice = __('MySQL returned an empty result set (i.e. zero rows).');
                    $output .= PMA_message::notice($notice)->getDisplay();
                }
            } else {
                $output = '';
                $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), $query) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null));
            }
            // Print/send output
            if ($GLOBALS['is_ajax_request']) {
                $extra_data = array('dialog' => false);
                PMA_ajaxResponse($message->getDisplay() . $output, $message->isSuccess(), $extra_data);
            } else {
                echo $message->getDisplay() . $output;
                if ($message->isError()) {
                    // At least one query has failed, so shouldn't
                    // execute any more queries, so we quit.
                    exit;
                }
                unset($_POST);
                // Now deliberately fall through to displaying the routines list
            }
        } else {
            $message = __('Error in processing request') . ' : ';
            $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db)));
            $message = PMA_message::error($message);
            if ($GLOBALS['is_ajax_request']) {
                PMA_ajaxResponse($message, $message->isSuccess());
            } else {
                echo $message->getDisplay();
                unset($_POST);
            }
        }
    } else {
        if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) {
            /**
             * Display the execute form for a routine.
             */
            $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true);
            if ($routine !== false) {
                $form = PMA_RTN_getExecuteForm($routine);
                if ($GLOBALS['is_ajax_request'] == true) {
                    $extra_data = array();
                    $extra_data['dialog'] = true;
                    $extra_data['title'] = __("Execute routine") . " ";
                    $extra_data['title'] .= PMA_backquote(htmlentities($_GET['item_name'], ENT_QUOTES));
                    PMA_ajaxResponse($form, true, $extra_data);
                } else {
                    echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
                    echo $form;
                    include './libraries/footer.inc.php';
                    // exit;
                }
            } else {
                if ($GLOBALS['is_ajax_request'] == true) {
                    $message = __('Error in processing request') . ' : ';
                    $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db)));
                    $message = PMA_message::error($message);
                    PMA_ajaxResponse($message, false);
                }
            }
        }
    }
}
/**
 * sets BLOBStreaming variables to a list of specified arguments
 * @access  public
 * @uses    PMA_DBI_query()
 * @returns boolean - success of variables setup
*/
function PMA_BS_SetVariables($bs_variables)
{
    // if no variables exist in array, return false
    if (empty($bs_variables) || count($bs_variables) == 0) {
        return FALSE;
    }
    // set BS variables to those specified in array
    foreach ($bs_variables as $key => $val) {
        if (!is_null($val) && strlen($val) > 0) {
            // set BS variable to specified value
            $query = "SET GLOBAL {$key}=" . PMA_sqlAddSlashes($val);
            $result = PMA_DBI_query($query);
            // if query fails execution, return false
            if (!$result) {
                return FALSE;
            }
        }
    }
    // end if (!is_null($val) && strlen($val) > 0)
    // return true on success
    return TRUE;
}
Example #27
0
/**
 * Checks if the current user has a specific privilege and returns true if the
 * user indeed has that privilege or false if (s)he doesn't. This function must
 * only be used for features that are available since MySQL 5, because it
 * relies on the INFORMATION_SCHEMA database to be present.
 *
 * Example:   PMA_currentUserHasPrivilege('CREATE ROUTINE', 'mydb');
 *            // Checks if the currently logged in user has the global
 *            // 'CREATE ROUTINE' privilege or, if not, checks if the
 *            // user has this privilege on database 'mydb'.
 *
 * @param string $priv The privilege to check
 * @param mixed  $db   null, to only check global privileges
 *                     string, db name where to also check for privileges
 * @param mixed  $tbl  null, to only check global/db privileges
 *                     string, table name where to also check for privileges
 *
 * @return bool
 */
function PMA_currentUserHasPrivilege($priv, $db = null, $tbl = null)
{
    // Get the username for the current user in the format
    // required to use in the information schema database.
    $user = PMA_DBI_fetch_value("SELECT CURRENT_USER();");
    if ($user === false) {
        return false;
    }
    $user = explode('@', $user);
    $username = "******";
    $username .= str_replace("'", "''", $user[0]);
    $username .= "''@''";
    $username .= str_replace("'", "''", $user[1]);
    $username .= "''";
    // Prepage the query
    $query = "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.`%s` " . "WHERE GRANTEE='%s' AND PRIVILEGE_TYPE='%s'";
    // Check global privileges first.
    if (PMA_DBI_fetch_value(sprintf($query, 'USER_PRIVILEGES', $username, $priv))) {
        return true;
    }
    // If a database name was provided and user does not have the
    // required global privilege, try database-wise permissions.
    if ($db !== null) {
        // need to escape wildcards in db and table names, see bug #3518484
        $db = str_replace(array('%', '_'), array('\\%', '\\_'), $db);
        $query .= " AND TABLE_SCHEMA='%s'";
        if (PMA_DBI_fetch_value(sprintf($query, 'SCHEMA_PRIVILEGES', $username, $priv, PMA_sqlAddSlashes($db)))) {
            return true;
        }
    } else {
        // There was no database name provided and the user
        // does not have the correct global privilege.
        return false;
    }
    // If a table name was also provided and we still didn't
    // find any valid privileges, try table-wise privileges.
    if ($tbl !== null) {
        // need to escape wildcards in db and table names, see bug #3518484
        $tbl = str_replace(array('%', '_'), array('\\%', '\\_'), $tbl);
        $query .= " AND TABLE_NAME='%s'";
        if ($retval = PMA_DBI_fetch_value(sprintf($query, 'TABLE_PRIVILEGES', $username, $priv, PMA_sqlAddSlashes($db), PMA_sqlAddSlashes($tbl)))) {
            return true;
        }
    }
    // If we reached this point, the user does not
    // have even valid table-wise privileges.
    return false;
}
/**
 * Cleanup database related relation stuff
 *
 * @param string $db
 */
function PMA_relationsCleanupDatabase($db)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['commwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['bookmarkwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['bookmark']) . ' WHERE dbase  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['displaywork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['pdfwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_coords']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['designerwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['designer_coords']) . ' WHERE db_name  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
    if ($cfgRelation['relwork']) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' WHERE master_db  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' WHERE foreign_db  = \'' . PMA_sqlAddSlashes($db) . '\'';
        PMA_query_as_controluser($remove_query);
    }
}
/**
 * Returns all the grants for a certain user on a certain host
 * Used in the export privileges for all users section
 *
 * @param string $user User name
 * @param string $host Host name
 *
 * @return string containing all the grants text
 */
function PMA_getGrants($user, $host)
{
    $grants = PMA_DBI_fetch_result("SHOW GRANTS FOR '" . PMA_sqlAddSlashes($user) . "'@'" . PMA_sqlAddSlashes($host) . "'");
    $response = '';
    foreach ($grants as $one_grant) {
        $response .= $one_grant . ";\n\n";
    }
    return $response;
} // end of the 'PMA_getGrants()' function
Example #30
0
/**
 * Displays the privileges form table
 *
 * @param string  $db     the database
 * @param string  $table  the table
 * @param boolean $submit wheather to display the submit button or not
 *
 * @global  array      $cfg         the phpMyAdmin configuration
 * @global  ressource  $user_link   the database connection
 *
 * @return  void
 */
function PMA_displayPrivTable($db = '*', $table = '*', $submit = true)
{
    global $random_n;
    if ($db == '*') {
        $table = '*';
    }
    if (isset($GLOBALS['username'])) {
        $username = $GLOBALS['username'];
        $hostname = $GLOBALS['hostname'];
        if ($db == '*') {
            $sql_query = "SELECT * FROM `mysql`.`user`" . " WHERE `User` = '" . PMA_sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA_sqlAddSlashes($hostname) . "';";
        } elseif ($table == '*') {
            $sql_query = "SELECT * FROM `mysql`.`db`" . " WHERE `User` = '" . PMA_sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA_sqlAddSlashes($hostname) . "'" . " AND '" . PMA_unescape_mysql_wildcards($db) . "'" . " LIKE `Db`;";
        } else {
            $sql_query = "SELECT `Table_priv`" . " FROM `mysql`.`tables_priv`" . " WHERE `User` = '" . PMA_sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA_sqlAddSlashes($hostname) . "'" . " AND `Db` = '" . PMA_unescape_mysql_wildcards($db) . "'" . " AND `Table_name` = '" . PMA_sqlAddSlashes($table) . "';";
        }
        $row = PMA_DBI_fetch_single_row($sql_query);
    }
    if (empty($row)) {
        if ($table == '*') {
            if ($db == '*') {
                $sql_query = 'SHOW COLUMNS FROM `mysql`.`user`;';
            } elseif ($table == '*') {
                $sql_query = 'SHOW COLUMNS FROM `mysql`.`db`;';
            }
            $res = PMA_DBI_query($sql_query);
            while ($row1 = PMA_DBI_fetch_row($res)) {
                if (substr($row1[0], 0, 4) == 'max_') {
                    $row[$row1[0]] = 0;
                } else {
                    $row[$row1[0]] = 'N';
                }
            }
            PMA_DBI_free_result($res);
        } else {
            $row = array('Table_priv' => '');
        }
    }
    if (isset($row['Table_priv'])) {
        $row1 = PMA_DBI_fetch_single_row('SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';', 'ASSOC', $GLOBALS['userlink']);
        // note: in MySQL 5.0.3 we get "Create View', 'Show view';
        // the View for Create is spelled with uppercase V
        // the view for Show is spelled with lowercase v
        // and there is a space between the words
        $av_grants = explode('\',\'', substr($row1['Type'], strpos($row1['Type'], '(') + 2, strpos($row1['Type'], ')') - strpos($row1['Type'], '(') - 3));
        unset($row1);
        $users_grants = explode(',', $row['Table_priv']);
        foreach ($av_grants as $current_grant) {
            $row[$current_grant . '_priv'] = in_array($current_grant, $users_grants) ? 'Y' : 'N';
        }
        unset($row['Table_priv'], $current_grant, $av_grants, $users_grants);
        // get collumns
        $res = PMA_DBI_try_query('SHOW COLUMNS FROM ' . PMA_backquote(PMA_unescape_mysql_wildcards($db)) . '.' . PMA_backquote($table) . ';');
        $columns = array();
        if ($res) {
            while ($row1 = PMA_DBI_fetch_row($res)) {
                $columns[$row1[0]] = array('Select' => false, 'Insert' => false, 'Update' => false, 'References' => false);
            }
            PMA_DBI_free_result($res);
        }
        unset($res, $row1);
    }
    // t a b l e - s p e c i f i c    p r i v i l e g e s
    if (!empty($columns)) {
        $res = PMA_DBI_query('SELECT `Column_name`, `Column_priv`' . ' FROM `mysql`.`columns_priv`' . ' WHERE `User`' . ' = \'' . PMA_sqlAddSlashes($username) . "'" . ' AND `Host`' . ' = \'' . PMA_sqlAddSlashes($hostname) . "'" . ' AND `Db`' . ' = \'' . PMA_sqlAddSlashes(PMA_unescape_mysql_wildcards($db)) . "'" . ' AND `Table_name`' . ' = \'' . PMA_sqlAddSlashes($table) . '\';');
        while ($row1 = PMA_DBI_fetch_row($res)) {
            $row1[1] = explode(',', $row1[1]);
            foreach ($row1[1] as $current) {
                $columns[$row1[0]][$current] = true;
            }
        }
        PMA_DBI_free_result($res);
        unset($res, $row1, $current);
        echo '<input type="hidden" name="grant_count" value="' . count($row) . '" />' . "\n" . '<input type="hidden" name="column_count" value="' . count($columns) . '" />' . "\n" . '<fieldset id="fieldset_user_priv">' . "\n" . '    <legend>' . __('Table-specific privileges') . PMA_showHint(__('Note: MySQL privilege names are expressed in English')) . '</legend>' . "\n";
        // privs that are attached to a specific column
        PMA_display_column_privs($columns, $row, 'Select_priv', 'SELECT', 'select', __('Allows reading data.'), 'Select');
        PMA_display_column_privs($columns, $row, 'Insert_priv', 'INSERT', 'insert', __('Allows inserting and replacing data.'), 'Insert');
        PMA_display_column_privs($columns, $row, 'Update_priv', 'UPDATE', 'update', __('Allows changing data.'), 'Update');
        PMA_display_column_privs($columns, $row, 'References_priv', 'REFERENCES', 'references', __('Has no effect in this MySQL version.'), 'References');
        // privs that are not attached to a specific column
        echo '    <div class="item">' . "\n";
        foreach ($row as $current_grant => $current_grant_value) {
            if (in_array(substr($current_grant, 0, strlen($current_grant) - 5), array('Select', 'Insert', 'Update', 'References'))) {
                continue;
            }
            // make a substitution to match the messages variables;
            // also we must substitute the grant we get, because we can't generate
            // a form variable containing blanks (those would get changed to
            // an underscore when receiving the POST)
            if ($current_grant == 'Create View_priv') {
                $tmp_current_grant = 'CreateView_priv';
                $current_grant = 'Create_view_priv';
            } elseif ($current_grant == 'Show view_priv') {
                $tmp_current_grant = 'ShowView_priv';
                $current_grant = 'Show_view_priv';
            } else {
                $tmp_current_grant = $current_grant;
            }
            echo '        <div class="item">' . "\n" . '            <input type="checkbox"' . (empty($GLOBALS['checkall']) ? '' : ' checked="checked"') . ' name="' . $current_grant . '" id="checkbox_' . $current_grant . '" value="Y" ' . ($current_grant_value == 'Y' ? 'checked="checked" ' : '') . 'title="';
            echo (isset($GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5)]) ? $GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5)] : $GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5) . 'Tbl']) . '"/>' . "\n";
            echo '            <label for="checkbox_' . $current_grant . '"><tt><dfn title="' . (isset($GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5)]) ? $GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5)] : $GLOBALS['strPrivDesc' . substr($tmp_current_grant, 0, strlen($tmp_current_grant) - 5) . 'Tbl']) . '">' . strtoupper(substr($current_grant, 0, strlen($current_grant) - 5)) . '</dfn></tt></label>' . "\n" . '        </div>' . "\n";
        }
        // end foreach ()
        echo '    </div>' . "\n";
        // for Safari 2.0.2
        echo '    <div class="clearfloat"></div>' . "\n";
    } else {
        // g l o b a l    o r    d b - s p e c i f i c
        //
        $privTable_names = array(0 => __('Data'), 1 => __('Structure'), 2 => __('Administration'));
        // d a t a
        $privTable[0] = array(array('Select', 'SELECT', __('Allows reading data.')), array('Insert', 'INSERT', __('Allows inserting and replacing data.')), array('Update', 'UPDATE', __('Allows changing data.')), array('Delete', 'DELETE', __('Allows deleting data.')));
        if ($db == '*') {
            $privTable[0][] = array('File', 'FILE', __('Allows importing data from and exporting data into files.'));
        }
        // s t r u c t u r e
        $privTable[1] = array(array('Create', 'CREATE', $table == '*' ? __('Allows creating new databases and tables.') : __('Allows creating new tables.')), array('Alter', 'ALTER', __('Allows altering the structure of existing tables.')), array('Index', 'INDEX', __('Allows creating and dropping indexes.')), array('Drop', 'DROP', $table == '*' ? __('Allows dropping databases and tables.') : __('Allows dropping tables.')), array('Create_tmp_table', 'CREATE TEMPORARY TABLES', __('Allows creating temporary tables.')), array('Show_view', 'SHOW VIEW', __('Allows performing SHOW CREATE VIEW queries.')), array('Create_routine', 'CREATE ROUTINE', __('Allows creating stored routines.')), array('Alter_routine', 'ALTER ROUTINE', __('Allows altering and dropping stored routines.')), array('Execute', 'EXECUTE', __('Allows executing stored routines.')));
        // this one is for a db-specific priv: Create_view_priv
        if (isset($row['Create_view_priv'])) {
            $privTable[1][] = array('Create_view', 'CREATE VIEW', __('Allows creating new views.'));
        }
        // this one is for a table-specific priv: Create View_priv
        if (isset($row['Create View_priv'])) {
            $privTable[1][] = array('Create View', 'CREATE VIEW', __('Allows creating new views.'));
        }
        if (isset($row['Event_priv'])) {
            // MySQL 5.1.6
            $privTable[1][] = array('Event', 'EVENT', __('Allows to set up events for the event scheduler'));
            $privTable[1][] = array('Trigger', 'TRIGGER', __('Allows creating and dropping triggers'));
        }
        // a d m i n i s t r a t i o n
        $privTable[2] = array(array('Grant', 'GRANT', __('Allows adding users and privileges without reloading the privilege tables.')));
        if ($db == '*') {
            $privTable[2][] = array('Super', 'SUPER', __('Allows connecting, even if maximum number of connections is reached; required for most administrative operations like setting global variables or killing threads of other users.'));
            $privTable[2][] = array('Process', 'PROCESS', __('Allows viewing processes of all users'));
            $privTable[2][] = array('Reload', 'RELOAD', __('Allows reloading server settings and flushing the server\'s caches.'));
            $privTable[2][] = array('Shutdown', 'SHUTDOWN', __('Allows shutting down the server.'));
            $privTable[2][] = array('Show_db', 'SHOW DATABASES', __('Gives access to the complete list of databases.'));
        }
        $privTable[2][] = array('Lock_tables', 'LOCK TABLES', __('Allows locking tables for the current thread.'));
        $privTable[2][] = array('References', 'REFERENCES', __('Has no effect in this MySQL version.'));
        if ($db == '*') {
            $privTable[2][] = array('Repl_client', 'REPLICATION CLIENT', __('Allows the user to ask where the slaves / masters are.'));
            $privTable[2][] = array('Repl_slave', 'REPLICATION SLAVE', __('Needed for the replication slaves.'));
            $privTable[2][] = array('Create_user', 'CREATE USER', __('Allows creating, dropping and renaming user accounts.'));
        }
        echo '<input type="hidden" name="grant_count" value="' . (count($privTable[0]) + count($privTable[1]) + count($privTable[2]) - (isset($row['Grant_priv']) ? 1 : 0)) . '" />' . "\n" . '<fieldset id="fieldset_user_global_rights">' . "\n" . '    <legend>' . "\n" . '        ' . ($db == '*' ? __('Global privileges') : ($table == '*' ? __('Database-specific privileges') : __('Table-specific privileges'))) . "\n" . '        (<a href="server_privileges.php?' . $GLOBALS['url_query'] . '&amp;checkall=1" onclick="setCheckboxes(\'addUsersForm_' . $random_n . '\', true); return false;">' . __('Check All') . '</a> /' . "\n" . '        <a href="server_privileges.php?' . $GLOBALS['url_query'] . '" onclick="setCheckboxes(\'addUsersForm_' . $random_n . '\', false); return false;">' . __('Uncheck All') . '</a>)' . "\n" . '    </legend>' . "\n" . '    <p><small><i>' . __('Note: MySQL privilege names are expressed in English') . '</i></small></p>' . "\n";
        // Output the Global privilege tables with checkboxes
        foreach ($privTable as $i => $table) {
            echo '    <fieldset>' . "\n" . '        <legend>' . __($privTable_names[$i]) . '</legend>' . "\n";
            foreach ($table as $priv) {
                echo '        <div class="item">' . "\n" . '            <input type="checkbox"' . ' name="' . $priv[0] . '_priv" id="checkbox_' . $priv[0] . '_priv"' . ' value="Y" title="' . $priv[2] . '"' . (!empty($GLOBALS['checkall']) || $row[$priv[0] . '_priv'] == 'Y' ? ' checked="checked"' : '') . '/>' . "\n" . '            <label for="checkbox_' . $priv[0] . '_priv"><tt><dfn title="' . $priv[2] . '">' . $priv[1] . '</dfn></tt></label>' . "\n" . '        </div>' . "\n";
            }
            echo '    </fieldset>' . "\n";
        }
        // The "Resource limits" box is not displayed for db-specific privs
        if ($db == '*') {
            echo '    <fieldset>' . "\n" . '        <legend>' . __('Resource limits') . '</legend>' . "\n" . '        <p><small><i>' . __('Note: Setting these options to 0 (zero) removes the limit.') . '</i></small></p>' . "\n" . '        <div class="item">' . "\n" . '            <label for="text_max_questions"><tt><dfn title="' . __('Limits the number of queries the user may send to the server per hour.') . '">MAX QUERIES PER HOUR</dfn></tt></label>' . "\n" . '            <input type="text" name="max_questions" id="text_max_questions" value="' . $row['max_questions'] . '" size="11" maxlength="11" title="' . __('Limits the number of queries the user may send to the server per hour.') . '" />' . "\n" . '        </div>' . "\n" . '        <div class="item">' . "\n" . '            <label for="text_max_updates"><tt><dfn title="' . __('Limits the number of commands that change any table or database the user may execute per hour.') . '">MAX UPDATES PER HOUR</dfn></tt></label>' . "\n" . '            <input type="text" name="max_updates" id="text_max_updates" value="' . $row['max_updates'] . '" size="11" maxlength="11" title="' . __('Limits the number of commands that change any table or database the user may execute per hour.') . '" />' . "\n" . '        </div>' . "\n" . '        <div class="item">' . "\n" . '            <label for="text_max_connections"><tt><dfn title="' . __('Limits the number of new connections the user may open per hour.') . '">MAX CONNECTIONS PER HOUR</dfn></tt></label>' . "\n" . '            <input type="text" name="max_connections" id="text_max_connections" value="' . $row['max_connections'] . '" size="11" maxlength="11" title="' . __('Limits the number of new connections the user may open per hour.') . '" />' . "\n" . '        </div>' . "\n" . '        <div class="item">' . "\n" . '            <label for="text_max_user_connections"><tt><dfn title="' . __('Limits the number of simultaneous connections the user may have.') . '">MAX USER_CONNECTIONS</dfn></tt></label>' . "\n" . '            <input type="text" name="max_user_connections" id="text_max_user_connections" value="' . $row['max_user_connections'] . '" size="11" maxlength="11" title="' . __('Limits the number of simultaneous connections the user may have.') . '" />' . "\n" . '        </div>' . "\n" . '    </fieldset>' . "\n";
        }
        // for Safari 2.0.2
        echo '    <div class="clearfloat"></div>' . "\n";
    }
    echo '</fieldset>' . "\n";
    if ($submit) {
        echo '<fieldset id="fieldset_user_privtable_footer" class="tblFooters">' . "\n" . '    <input type="submit" name="update_privs" value="' . __('Go') . '" />' . "\n" . '</fieldset>' . "\n";
    }
}