Exemplo n.º 1
0
 /**
  * checks if MySQL server supports partitioning
  *
  * @static
  * @staticvar boolean $have_partitioning
  * @staticvar boolean $already_checked
  * @access  public
  * @return boolean
  */
 public static function havePartitioning()
 {
     static $have_partitioning = false;
     static $already_checked = false;
     if (!$already_checked) {
         if (PMA_MYSQL_INT_VERSION >= 50100) {
             if (PMA_MYSQL_INT_VERSION < 50600) {
                 if (PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'have_partitioning';")) {
                     $have_partitioning = true;
                 }
             } else {
                 // see http://dev.mysql.com/doc/refman/5.6/en/partitioning.html
                 $plugins = PMA_DBI_fetch_result("SHOW PLUGINS");
                 foreach ($plugins as $value) {
                     if ($value['Name'] == 'partition') {
                         $have_partitioning = true;
                         break;
                     }
                 }
             }
             $already_checked = true;
         }
     }
     return $have_partitioning;
 }
Exemplo n.º 2
0
/**
 * Creates a fieldset for adding a new event, if the user has the privileges.
 *
 * @return   string    HTML code with containing the fotter fieldset
 */
function PMA_EVN_getFooterLinks()
{
    global $db, $url_query;
    /**
     * For events, we show the usual 'Add event' form and also
     * a form for toggling the state of the event scheduler
     */
    // Init options for the event scheduler toggle functionality
    $es_state = PMA_DBI_fetch_value("SHOW GLOBAL VARIABLES LIKE 'event_scheduler'", 0, 1);
    $es_state = strtolower($es_state);
    $options = array(0 => array('label' => __('OFF'), 'value' => "SET GLOBAL event_scheduler=\"OFF\"", 'selected' => $es_state != 'on'), 1 => array('label' => __('ON'), 'value' => "SET GLOBAL event_scheduler=\"ON\"", 'selected' => $es_state == 'on'));
    // Generate output
    $retval = "<!-- FOOTER LINKS START -->\n";
    $retval .= "<div class='doubleFieldset'>\n";
    // show the usual footer
    $retval .= PMA_RTE_getFooterLinks('CREATE_EVENT', 'EVENT', 'EVENT');
    $retval .= "    <fieldset class='right'>\n";
    $retval .= "        <legend>\n";
    $retval .= "            " . __('Event scheduler status') . "\n";
    $retval .= "        </legend>\n";
    $retval .= "        <div class='wrap'>\n";
    // show the toggle button
    $retval .= PMA_toggleButton("sql.php?{$url_query}&amp;goto=db_events.php" . urlencode("?db={$db}"), 'sql_query', $options, 'PMA_slidingMessage(data.sql_query);');
    $retval .= "        </div>\n";
    $retval .= "    </fieldset>\n";
    $retval .= "    <div style='clear: both;'></div>\n";
    $retval .= "</div>";
    $retval .= "<!-- FOOTER LINKS END -->\n";
    return $retval;
}
Exemplo n.º 3
0
 /**
  * checks if MySQL server supports partitioning
  *
  * @static
  * @staticvar boolean $have_partitioning
  * @staticvar boolean $already_checked
  * @access  public
  * @uses    PMA_DBI_fetch_result()
  * @return  boolean
  */
 public static function havePartitioning()
 {
     static $have_partitioning = false;
     static $already_checked = false;
     if (!$already_checked) {
         $have_partitioning = PMA_MYSQL_INT_VERSION >= 50100 && PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'have_partitioning';");
         $already_checked = true;
     }
     return $have_partitioning;
 }
Exemplo n.º 4
0
 /**
  * Returns the comment associated with node
  * This method should be overridden by specific type of nodes
  *
  * @return string
  */
 public function getComment()
 {
     $db = PMA_Util::sqlAddSlashes($this->realParent()->real_name);
     $event = PMA_Util::sqlAddSlashes($this->real_name);
     $query = "SELECT `EVENT_COMMENT` ";
     $query .= "FROM `INFORMATION_SCHEMA`.`EVENTS` ";
     $query .= "WHERE `EVENT_SCHEMA`='{$db}' ";
     $query .= "AND `EVENT_NAME`='{$event}' ";
     return PMA_DBI_fetch_value($query);
 }
Exemplo n.º 5
0
 /**
  * Returns the comment associated with node
  * This method should be overridden by specific type of nodes
  *
  * @return string
  */
 public function getComment()
 {
     $db = PMA_Util::sqlAddSlashes($this->realParent()->real_name);
     $routine = PMA_Util::sqlAddSlashes($this->real_name);
     $query = "SELECT `ROUTINE_COMMENT` ";
     $query .= "FROM `INFORMATION_SCHEMA`.`ROUTINES` ";
     $query .= "WHERE `ROUTINE_SCHEMA`='{$db}' ";
     $query .= "AND `ROUTINE_NAME`='{$routine}' ";
     $query .= "AND `ROUTINE_TYPE`='FUNCTION' ";
     return PMA_DBI_fetch_value($query);
 }
Exemplo n.º 6
0
 /**
  * Returns the comment associated with node
  * This method should be overridden by specific type of nodes
  *
  * @return string
  */
 public function getComment()
 {
     $db = PMA_Util::sqlAddSlashes($this->realParent()->realParent()->real_name);
     $table = PMA_Util::sqlAddSlashes($this->realParent()->real_name);
     $column = PMA_Util::sqlAddSlashes($this->real_name);
     $query = "SELECT `COLUMN_COMMENT` ";
     $query .= "FROM `INFORMATION_SCHEMA`.`COLUMNS` ";
     $query .= "WHERE `TABLE_SCHEMA`='{$db}' ";
     $query .= "AND `TABLE_NAME`='{$table}' ";
     $query .= "AND `COLUMN_NAME`='{$column}' ";
     return PMA_DBI_fetch_value($query);
 }
Exemplo n.º 7
0
 /**
  * Returns the number of children of type $type present inside this container
  * This method is overridden by the Node_Database and Node_Table classes
  *
  * @param string $type         The type of item we are looking for
  *                             ('columns' or 'indexes')
  * @param string $searchClause A string used to filter the results of the query
  *
  * @return int
  */
 public function getPresence($type = '', $searchClause = '')
 {
     $retval = 0;
     $db = $this->realParent()->real_name;
     $table = $this->real_name;
     switch ($type) {
         case 'columns':
             if (!$GLOBALS['cfg']['Servers'][$GLOBALS['server']]['DisableIS']) {
                 $db = PMA_Util::sqlAddSlashes($db);
                 $table = PMA_Util::sqlAddSlashes($table);
                 $query = "SELECT COUNT(*) ";
                 $query .= "FROM `INFORMATION_SCHEMA`.`COLUMNS` ";
                 $query .= "WHERE `TABLE_NAME`='{$table}' ";
                 $query .= "AND `TABLE_SCHEMA`='{$db}'";
                 $retval = (int) PMA_DBI_fetch_value($query);
             } else {
                 $db = PMA_Util::backquote($db);
                 $table = PMA_Util::backquote($table);
                 $query = "SHOW COLUMNS FROM {$table} FROM {$db}";
                 $retval = (int) PMA_DBI_num_rows(PMA_DBI_try_query($query));
             }
             break;
         case 'indexes':
             $db = PMA_Util::backquote($db);
             $table = PMA_Util::backquote($table);
             $query = "SHOW INDEXES FROM {$table} FROM {$db}";
             $retval = (int) PMA_DBI_num_rows(PMA_DBI_try_query($query));
             break;
         case 'triggers':
             if (!$GLOBALS['cfg']['Servers'][$GLOBALS['server']]['DisableIS']) {
                 $db = PMA_Util::sqlAddSlashes($db);
                 $table = PMA_Util::sqlAddSlashes($table);
                 $query = "SELECT COUNT(*) ";
                 $query .= "FROM `INFORMATION_SCHEMA`.`TRIGGERS` ";
                 $query .= "WHERE `EVENT_OBJECT_SCHEMA`='{$db}' ";
                 $query .= "AND `EVENT_OBJECT_TABLE`='{$table}'";
                 $retval = (int) PMA_DBI_fetch_value($query);
             } else {
                 $db = PMA_Util::backquote($db);
                 $table = PMA_Util::sqlAddSlashes($table);
                 $query = "SHOW TRIGGERS FROM {$db} WHERE `Table` = '{$table}'";
                 $retval = (int) PMA_DBI_num_rows(PMA_DBI_try_query($query));
             }
             break;
         default:
             break;
     }
     return $retval;
 }
/**
 * Saves user preferences
 *
 * @param array $config_array configuration array
 *
 * @return true|PMA_Message
 */
function PMA_saveUserprefs(array $config_array)
{
    $cfgRelation = PMA_getRelationsParam();
    $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : $GLOBALS['cfg']['ServerDefault'];
    $cache_key = 'server_' . $server;
    if (!$cfgRelation['userconfigwork']) {
        // no pmadb table, use session storage
        $_SESSION['userconfig'] = array('db' => $config_array, 'ts' => time());
        if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
            unset($_SESSION['cache'][$cache_key]['userprefs']);
        }
        return true;
    }
    // save configuration to pmadb
    $query_table = PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['userconfig']);
    $query = '
        SELECT `username`
        FROM ' . $query_table . '
          WHERE `username` = \'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\'';
    $has_config = PMA_DBI_fetch_value($query, 0, 0, $GLOBALS['controllink']);
    $config_data = json_encode($config_array);
    if ($has_config) {
        $query = '
            UPDATE ' . $query_table . '
            SET `config_data` = \'' . PMA_Util::sqlAddSlashes($config_data) . '\'
            WHERE `username` = \'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\'';
    } else {
        $query = '
            INSERT INTO ' . $query_table . ' (`username`, `config_data`)
            VALUES (\'' . PMA_Util::sqlAddSlashes($cfgRelation['user']) . '\',
                \'' . PMA_Util::sqlAddSlashes($config_data) . '\')';
    }
    if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
        unset($_SESSION['cache'][$cache_key]['userprefs']);
    }
    if (!PMA_DBI_try_query($query, $GLOBALS['controllink'])) {
        $message = PMA_Message::error(__('Could not save configuration'));
        $message->addMessage('<br /><br />');
        $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
        return $message;
    }
    return true;
}
Exemplo n.º 9
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;
 }
Exemplo n.º 10
0
/**
 * Displays operations that are available on results.
 *
 * @param   array   the display mode
 * @param   array   the analyzed query
 *
 * @uses    $_SESSION['tmp_user_values']['pos']
 * @uses    $_SESSION['tmp_user_values']['display_text']
 * @global  string   $db                the database name
 * @global  string   $table             the table name
 * @global  string   $sql_query         the current SQL query
 * @global  integer  $unlim_num_rows    the total number of rows returned by the
 *                                      SQL query without any programmatically
 *                                      appended "LIMIT" clause
 *
 * @access  private
 *
 * @see     PMA_showMessage(), PMA_setDisplayMode(),
 *          PMA_displayTableNavigation(), PMA_displayTableHeaders(),
 *          PMA_displayTableBody(), PMA_displayResultsOperations()
 */
function PMA_displayResultsOperations($the_disp_mode, $analyzed_sql)
{
    global $db, $table, $sql_query, $unlim_num_rows;
    $header_shown = FALSE;
    $header = '<fieldset><legend>' . $GLOBALS['strQueryResultsOperations'] . '</legend>';
    if ($the_disp_mode[6] == '1' || $the_disp_mode[9] == '1') {
        // Displays "printable view" link if required
        if ($the_disp_mode[9] == '1') {
            if (!$header_shown) {
                echo $header;
                $header_shown = TRUE;
            }
            $_url_params = array('db' => $db, 'table' => $table, 'printview' => '1', 'sql_query' => $sql_query);
            $url_query = PMA_generate_common_url($_url_params);
            echo PMA_linkOrButton('sql.php' . $url_query, PMA_getIcon('b_print.png', $GLOBALS['strPrintView'], false, true), '', true, true, 'print_view') . "\n";
            if ($_SESSION['tmp_user_values']['display_text']) {
                $_url_params['display_text'] = 'F';
                echo PMA_linkOrButton('sql.php' . PMA_generate_common_url($_url_params), PMA_getIcon('b_print.png', $GLOBALS['strPrintViewFull'], false, true), '', true, true, 'print_view') . "\n";
                unset($_url_params['display_text']);
            }
        }
        // end displays "printable view"
    }
    // Export link
    // (the url_query has extra parameters that won't be used to export)
    // (the single_table parameter is used in display_export.lib.php
    //  to hide the SQL and the structure export dialogs)
    // If the parser found a PROCEDURE clause
    // (most probably PROCEDURE ANALYSE()) it makes no sense to
    // display the Export link).
    if (isset($analyzed_sql[0]) && $analyzed_sql[0]['querytype'] == 'SELECT' && !isset($printview) && !isset($analyzed_sql[0]['queryflags']['procedure'])) {
        if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name']) && !isset($analyzed_sql[0]['table_ref'][1]['table_true_name'])) {
            $_url_params['single_table'] = 'true';
        }
        if (!$header_shown) {
            echo $header;
            $header_shown = TRUE;
        }
        $_url_params['unlim_num_rows'] = $unlim_num_rows;
        /**
         * At this point we don't know the table name; this can happen
         * for example with a query like
         * SELECT bike_code FROM (SELECT bike_code FROM bikes) tmp
         * As a workaround we set in the table parameter the name of the
         * first table of this database, so that tbl_export.php and
         * the script it calls do not fail
         */
        if (empty($_url_params['table'])) {
            $_url_params['table'] = PMA_DBI_fetch_value("SHOW TABLES");
        }
        echo PMA_linkOrButton('tbl_export.php' . PMA_generate_common_url($_url_params), PMA_getIcon('b_tblexport.png', $GLOBALS['strExport'], false, true), '', true, true, '') . "\n";
    }
    // CREATE VIEW
    /**
     *
     * @todo detect privileges to create a view
     *       (but see 2006-01-19 note in display_create_table.lib.php,
     *        I think we cannot detect db-specific privileges reliably)
     * Note: we don't display a Create view link if we found a PROCEDURE clause
     */
    if (!$header_shown) {
        echo $header;
        $header_shown = TRUE;
    }
    if (!isset($analyzed_sql[0]['queryflags']['procedure'])) {
        echo PMA_linkOrButton('view_create.php' . $url_query, PMA_getIcon('b_views.png', 'CREATE VIEW', false, true), '', true, true, '') . "\n";
    }
    if ($header_shown) {
        echo '</fieldset><br />';
    }
}
Exemplo n.º 11
0
 */
if (strlen($db) && (!empty($db_rename) || !empty($db_copy))) {
    if (!empty($db_rename)) {
        $move = true;
    } else {
        $move = false;
    }
    if (!isset($newname) || !strlen($newname)) {
        $message = PMA_Message::error('strDatabaseEmpty');
    } else {
        $sql_query = '';
        // in case target db exists
        $_error = false;
        if ($move || isset($create_database_before_copying) && $create_database_before_copying) {
            // lower_case_table_names=1 `DB` becomes `db`
            $lower_case_table_names = PMA_DBI_fetch_value('SHOW VARIABLES LIKE "lower_case_table_names"', 0, 1);
            if ($lower_case_table_names === '1') {
                $newname = strtolower($newname);
            }
            $local_query = 'CREATE DATABASE ' . PMA_backquote($newname);
            if (isset($db_collation)) {
                $local_query .= ' DEFAULT' . PMA_generateCharsetQueryPart($db_collation);
            }
            $local_query .= ';';
            $sql_query = $local_query;
            PMA_DBI_query($local_query);
            // rebuild the database list because PMA_Table::moveCopy
            // checks in this list if the target db exists
            $GLOBALS['pma']->databases->build();
        }
        if (isset($GLOBALS['add_constraints'])) {
Exemplo n.º 12
0
 /**
  * Outputs export header. It is the first method to be called, so all
  * the required variables are initialized here.
  *
  * @return bool Whether it succeeded
  */
 public function exportHeader()
 {
     global $crlf, $cfg;
     global $mysql_charset_map;
     if (isset($GLOBALS['sql_compatibility'])) {
         $tmp_compat = $GLOBALS['sql_compatibility'];
         if ($tmp_compat == 'NONE') {
             $tmp_compat = '';
         }
         PMA_DBI_try_query('SET SQL_MODE="' . $tmp_compat . '"');
         unset($tmp_compat);
     }
     $head = $this->_exportComment('phpMyAdmin SQL Dump') . $this->_exportComment('version ' . PMA_VERSION) . $this->_exportComment('http://www.phpmyadmin.net') . $this->_exportComment();
     $host_string = __('Host') . ': ' . $cfg['Server']['host'];
     if (!empty($cfg['Server']['port'])) {
         $host_string .= ':' . $cfg['Server']['port'];
     }
     $head .= $this->_exportComment($host_string);
     $head .= $this->_exportComment(__('Generation Time') . ': ' . PMA_Util::localisedDate()) . $this->_exportComment(__('Server version') . ': ' . PMA_MYSQL_STR_VERSION) . $this->_exportComment(__('PHP Version') . ': ' . phpversion()) . $this->_possibleCRLF();
     if (isset($GLOBALS['sql_header_comment']) && !empty($GLOBALS['sql_header_comment'])) {
         // '\n' is not a newline (like "\n" would be), it's the characters
         // backslash and n, as explained on the export interface
         $lines = explode('\\n', $GLOBALS['sql_header_comment']);
         $head .= $this->_exportComment();
         foreach ($lines as $one_line) {
             $head .= $this->_exportComment($one_line);
         }
         $head .= $this->_exportComment();
     }
     if (isset($GLOBALS['sql_disable_fk'])) {
         $head .= 'SET FOREIGN_KEY_CHECKS=0;' . $crlf;
     }
     // We want exported AUTO_INCREMENT columns to have still same value,
     // do this only for recent MySQL exports
     if ((!isset($GLOBALS['sql_compatibility']) || $GLOBALS['sql_compatibility'] == 'NONE') && !PMA_DRIZZLE) {
         $head .= 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' . $crlf;
     }
     if (isset($GLOBALS['sql_use_transaction'])) {
         $head .= 'SET AUTOCOMMIT = 0;' . $crlf . 'START TRANSACTION;' . $crlf;
     }
     /* Change timezone if we should export timestamps in UTC */
     if (isset($GLOBALS['sql_utc_time']) && $GLOBALS['sql_utc_time']) {
         $head .= 'SET time_zone = "+00:00";' . $crlf;
         $GLOBALS['old_tz'] = PMA_DBI_fetch_value('SELECT @@session.time_zone');
         PMA_DBI_query('SET time_zone = "+00:00"');
     }
     $head .= $this->_possibleCRLF();
     if (!empty($GLOBALS['asfile']) && !PMA_DRIZZLE) {
         // we are saving as file, therefore we provide charset information
         // so that a utility like the mysql client can interpret
         // the file correctly
         if (isset($GLOBALS['charset_of_file']) && isset($mysql_charset_map[$GLOBALS['charset_of_file']])) {
             // we got a charset from the export dialog
             $set_names = $mysql_charset_map[$GLOBALS['charset_of_file']];
         } else {
             // by default we use the connection charset
             $set_names = $mysql_charset_map['utf-8'];
         }
         $head .= $crlf . '/*!40101 SET @OLD_CHARACTER_SET_CLIENT=' . '@@CHARACTER_SET_CLIENT */;' . $crlf . '/*!40101 SET @OLD_CHARACTER_SET_RESULTS=' . '@@CHARACTER_SET_RESULTS */;' . $crlf . '/*!40101 SET @OLD_COLLATION_CONNECTION=' . '@@COLLATION_CONNECTION */;' . $crlf . '/*!40101 SET NAMES ' . $set_names . ' */;' . $crlf . $crlf;
     }
     return PMA_exportOutputHandler($head);
 }
Exemplo n.º 13
0
 /**
  * returns InnoDB status
  *
  * @uses    htmlspecialchars()
  * @uses    PMA_DBI_fetch_value()
  * @return  string  result of SHOW INNODB STATUS inside pre tags
  */
 function getPageStatus()
 {
     return '<pre id="pre_innodb_status">' . "\n"
         . htmlspecialchars(PMA_DBI_fetch_value('SHOW INNODB STATUS;')) . "\n"
         . '</pre>' . "\n";
 }
/**
 * Gets the sql command from a bookmark
 *
 * @uses    PMA_backquote()
 * @uses    PMA_sqlAddslashes()
 * @uses    PMA_DBI_fetch_value()
 * @uses    PMA_Bookmark_getParams()
 * @global  resource  the controluser db connection handle
 *
 * @param   string    the current database name
 * @param   mixed     the id of the bookmark to get
 * @param   string    which field to look up the $id
 * @param   boolean  TRUE: get all bookmarks regardless of the owning user
 * @param   boolean   whether to ignore bookmarks with no user
 *
 * @return  string    the sql query
 *
 * @access  public
 */
function PMA_Bookmark_get($db, $id, $id_field = 'id', $action_bookmark_all = FALSE, $exact_user_match = FALSE)
{
    global $controllink;
    $cfgBookmark = PMA_Bookmark_getParams();
    if (empty($cfgBookmark)) {
        return '';
    }
    $query = 'SELECT query FROM ' . PMA_backquote($cfgBookmark['db']) . '.' . PMA_backquote($cfgBookmark['table']) . ' WHERE dbase = \'' . PMA_sqlAddslashes($db) . '\'';
    if (!$action_bookmark_all) {
        $query .= ' AND (user = \'' . PMA_sqlAddslashes($cfgBookmark['user']) . '\'';
        if (!$exact_user_match) {
            $query .= ' OR user = \'\'';
        }
        $query .= ')';
    }
    $query .= ' AND ' . PMA_backquote($id_field) . ' = ' . $id;
    return PMA_DBI_fetch_value($query, 0, 0, $controllink);
}
Exemplo n.º 15
0
            // if (mysql_error()) {
            // void.
            // I tried the case
            // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
            // UNION (SELECT `User`, `Host`, "%" AS "Db",
            // `Select_priv`
            // FROM `user`) ORDER BY `User`, `Host`, `Db`;
            // and although the generated count_query is wrong
            // the SELECT FOUND_ROWS() work! (maybe it gets the
            // count from the latest query that worked)
            //
            // another case where the count_query is wrong:
            // SELECT COUNT(*), f1 from t1 group by f1
            // and you click to sort on count(*)
            // }
            $unlim_num_rows = PMA_DBI_fetch_value('SELECT FOUND_ROWS()');
        } // end else "just browsing"

    } else { // not $is_select
         $unlim_num_rows         = 0;
    } // end rows total count

    // if a table or database gets dropped, check column comments.
    if (isset($purge) && $purge == '1') {
        /**
         * Cleanup relations.
         */
        include_once 'libraries/relation_cleanup.lib.php';

        if (strlen($table) && strlen($db)) {
            PMA_relationsCleanupTable($db, $table);
Exemplo n.º 16
0
 /**
  * Copies or renames table
  * @todo use RENAME for move operations
  *        - would work only if the databases are on the same filesystem,
  *          how can we check that? try the operation and
  *          catch an error?
  *        - for views, only if MYSQL > 50013
  *        - still have to handle pmadb synch.
  *
  * @author          Michal Cihar <*****@*****.**>
  */
 function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
 {
     global $err_url;
     // set export settings we need
     $GLOBALS['sql_backquotes'] = 1;
     $GLOBALS['asfile'] = 1;
     // Ensure the target is valid
     if (!$GLOBALS['PMA_List_Database']->exists($source_db, $target_db)) {
         /**
          * @todo exit really needed here? or just a return?
          */
         exit;
     }
     $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
     if (!isset($target_db) || !strlen($target_db)) {
         $target_db = $source_db;
     }
     // Doing a select_db could avoid some problems with replicated databases,
     // when moving table from replicated one to not replicated one
     PMA_DBI_select_db($target_db);
     $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
     // do not create the table if dataonly
     if ($what != 'dataonly') {
         require_once './libraries/export/sql.php';
         $no_constraints_comments = true;
         $GLOBALS['sql_constraints_query'] = '';
         $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url);
         unset($no_constraints_comments);
         $parsed_sql = PMA_SQP_parse($sql_structure);
         $analyzed_sql = PMA_SQP_analyze($parsed_sql);
         $i = 0;
         if (empty($analyzed_sql[0]['create_table_fields'])) {
             // this is not a CREATE TABLE, so find the first VIEW
             $target_for_view = PMA_backquote($target_db);
             while (true) {
                 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
                     break;
                 }
                 $i++;
             }
         }
         unset($analyzed_sql);
         $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
         if ('ANSI_QUOTES' == $server_sql_mode) {
             $table_delimiter = 'quote_double';
         } else {
             $table_delimiter = 'quote_backtick';
         }
         unset($server_sql_mode);
         /* nijel: Find table name in query and replace it */
         while ($parsed_sql[$i]['type'] != $table_delimiter) {
             $i++;
         }
         /* no need to PMA_backquote() */
         if (isset($target_for_view)) {
             // this a view definition; we just found the first db name
             // that follows DEFINER VIEW
             // so change it for the new db name
             $parsed_sql[$i]['data'] = $target_for_view;
             // then we have to find all references to the source db
             // and change them to the target db, ensuring we stay into
             // the $parsed_sql limits
             $last = $parsed_sql['len'] - 1;
             $backquoted_source_db = PMA_backquote($source_db);
             for (++$i; $i <= $last; $i++) {
                 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
                     $parsed_sql[$i]['data'] = $target_for_view;
                 }
             }
             unset($last, $backquoted_source_db);
         } else {
             $parsed_sql[$i]['data'] = $target;
         }
         /* Generate query back */
         $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
         // If table exists, and 'add drop table' is selected: Drop it!
         $drop_query = '';
         if (isset($GLOBALS['drop_if_exists']) && $GLOBALS['drop_if_exists'] == 'true') {
             if (PMA_Table::_isView($target_db, $target_table)) {
                 $drop_query = 'DROP VIEW';
             } else {
                 $drop_query = 'DROP TABLE';
             }
             $drop_query .= ' IF EXISTS ' . PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
             PMA_DBI_query($drop_query);
             $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
             // garvin: If an existing table gets deleted, maintain any
             // entries for the PMA_* tables
             $maintain_relations = true;
         }
         @PMA_DBI_query($sql_structure);
         $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
         if (($move || isset($GLOBALS['add_constraints'])) && !empty($GLOBALS['sql_constraints_query'])) {
             $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
             $i = 0;
             // find the first $table_delimiter, it must be the source table name
             while ($parsed_sql[$i]['type'] != $table_delimiter) {
                 $i++;
                 // maybe someday we should guard against going over limit
                 //if ($i == $parsed_sql['len']) {
                 //    break;
                 //}
             }
             // replace it by the target table name, no need to PMA_backquote()
             $parsed_sql[$i]['data'] = $target;
             // now we must remove all $table_delimiter that follow a CONSTRAINT
             // keyword, because a constraint name must be unique in a db
             $cnt = $parsed_sql['len'] - 1;
             for ($j = $i; $j < $cnt; $j++) {
                 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord' && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
                     if ($parsed_sql[$j + 1]['type'] == $table_delimiter) {
                         $parsed_sql[$j + 1]['data'] = '';
                     }
                 }
             }
             // Generate query back
             $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql, 'query_only');
             if ($mode == 'one_table') {
                 PMA_DBI_query($GLOBALS['sql_constraints_query']);
             }
             $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
             if ($mode == 'one_table') {
                 unset($GLOBALS['sql_constraints_query']);
             }
         }
     } else {
         $GLOBALS['sql_query'] = '';
     }
     // Copy the data unless this is a VIEW
     if (($what == 'data' || $what == 'dataonly') && !PMA_Table::_isView($target_db, $target_table)) {
         $sql_insert_data = 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
         PMA_DBI_query($sql_insert_data);
         $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
     }
     require_once './libraries/relation.lib.php';
     $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
     // Drops old table if the user has requested to move it
     if ($move) {
         // This could avoid some problems with replicated databases, when
         // moving table from replicated one to not replicated one
         PMA_DBI_select_db($source_db);
         if (PMA_Table::_isView($source_db, $source_table)) {
             $sql_drop_query = 'DROP VIEW';
         } else {
             $sql_drop_query = 'DROP TABLE';
         }
         $sql_drop_query .= ' ' . $source;
         PMA_DBI_query($sql_drop_query);
         // garvin: Move old entries from PMA-DBs to new table
         if ($GLOBALS['cfgRelation']['commwork']) {
             $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . ' SET     table_name = \'' . PMA_sqlAddslashes($target_table) . '\', ' . '        db_name    = \'' . PMA_sqlAddslashes($target_db) . '\'' . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($remove_query);
             unset($remove_query);
         }
         // garvin: updating bookmarks is not possible since only a single table is moved,
         // and not the whole DB.
         if ($GLOBALS['cfgRelation']['displaywork']) {
             $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . ' SET     db_name = \'' . PMA_sqlAddslashes($target_db) . '\', ' . '         table_name = \'' . PMA_sqlAddslashes($target_table) . '\'' . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($table_query);
             unset($table_query);
         }
         if ($GLOBALS['cfgRelation']['relwork']) {
             $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . ' SET     foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\',' . '         foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\'' . ' WHERE foreign_db  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($table_query);
             unset($table_query);
             $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation']) . ' SET     master_table = \'' . PMA_sqlAddslashes($target_table) . '\',' . '         master_db = \'' . PMA_sqlAddslashes($target_db) . '\'' . ' WHERE master_db  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($table_query);
             unset($table_query);
         }
         /**
          * @todo garvin: Can't get moving PDFs the right way. The page numbers
          * always get screwed up independently from duplication because the
          * numbers do not seem to be stored on a per-database basis. Would
          * the author of pdf support please have a look at it?
          */
         if ($GLOBALS['cfgRelation']['pdfwork']) {
             $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . ' SET     table_name = \'' . PMA_sqlAddslashes($target_table) . '\',' . '         db_name = \'' . PMA_sqlAddslashes($target_db) . '\'' . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($table_query);
             unset($table_query);
             /*
             $pdf_query = 'SELECT pdf_page_number '
                        . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
                        . ' WHERE db_name  = \'' . PMA_sqlAddslashes($target_db) . '\''
                        . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
             $pdf_rs = PMA_query_as_cu($pdf_query);
             
             while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
                 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
                                 . ' SET     db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
                                 . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\''
                                 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
                 $tb_rs    = PMA_query_as_cu($table_query);
                 unset($table_query);
                 unset($tb_rs);
             }
             */
         }
         if ($GLOBALS['cfgRelation']['designerwork']) {
             $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . ' SET     table_name = \'' . PMA_sqlAddslashes($target_table) . '\',' . '         db_name = \'' . PMA_sqlAddslashes($target_db) . '\'' . ' WHERE db_name  = \'' . PMA_sqlAddslashes($source_db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
             PMA_query_as_cu($table_query);
             unset($table_query);
         }
         $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
         // end if ($move)
     } else {
         // we are copying
         // garvin: Create new entries as duplicates from old PMA DBs
         if ($what != 'dataonly' && !isset($maintain_relations)) {
             if ($GLOBALS['cfgRelation']['commwork']) {
                 // Get all comments and MIME-Types for current table
                 $comments_copy_query = 'SELECT
                                             column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
                                         FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
                                         WHERE
                                             db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
                                             table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
                 $comments_copy_rs = PMA_query_as_cu($comments_copy_query);
                 // Write every comment as new copied entry. [MIME]
                 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
                     $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') ' . ' VALUES(' . '\'' . PMA_sqlAddslashes($target_db) . '\',' . '\'' . PMA_sqlAddslashes($target_table) . '\',' . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\'' . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\',' . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\',' . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\',' . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '') . ')';
                     PMA_query_as_cu($new_comment_query);
                 }
                 // end while
                 PMA_DBI_free_result($comments_copy_rs);
                 unset($comments_copy_rs);
             }
             // duplicating the bookmarks must not be done here, but
             // just once per db
             $get_fields = array('display_field');
             $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
             $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
             PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
             /**
              * @todo revise this code when we support cross-db relations
              */
             $get_fields = array('master_field', 'foreign_table', 'foreign_field');
             $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
             $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
             PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
             $get_fields = array('foreign_field', 'master_table', 'master_field');
             $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
             $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
             PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
             $get_fields = array('x', 'y', 'v', 'h');
             $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
             $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
             PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
             /**
             * @todo garvin: Can't get duplicating PDFs the right way. The
             * page numbers always get screwed up independently from
             * duplication because the numbers do not seem to be stored on a
             * per-database basis. Would the author of pdf support please
             * have a look at it?
             *
                             $get_fields = array('page_descr');
                             $where_fields = array('db_name' => $source_db);
                             $new_fields = array('db_name' => $target_db);
                             $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
             
                             if (isset($last_id) && $last_id >= 0) {
                $get_fields = array('x', 'y');
                $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
                $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
                PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
                             }
             */
         }
     }
 }
Exemplo n.º 17
0
 */
if (!empty($disp_message)) {
    if (!isset($disp_query)) {
        $disp_query = null;
    }
    PMA_showMessage($disp_message, $disp_query);
}
/**
 * Displays top menu links
 */
require_once './libraries/tbl_links.inc.php';
/**
 * Get the analysis of SHOW CREATE TABLE for this table
 * @todo should be handled by class Table
 */
$show_create_table = PMA_DBI_fetch_value('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), 0, 1);
$analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
unset($show_create_table);
/**
 * Get the list of the fields of the current table
 */
PMA_DBI_select_db($db);
$table_fields = PMA_DBI_fetch_result('SHOW FIELDS FROM ' . PMA_backquote($table) . ';', null, null, null, PMA_DBI_QUERY_STORE);
$rows = array();
if (isset($where_clause)) {
    // when in edit mode load all selected rows from table
    $insert_mode = false;
    if (is_array($where_clause)) {
        $where_clause_array = $where_clause;
    } else {
        $where_clause_array = array(0 => $where_clause);
Exemplo n.º 18
0
    // Use the verbose name of the server instead of the hostname
    // if a value is set
    $server_info = '';
    if (! empty($cfg['Server']['verbose'])) {
        $server_info .= htmlspecialchars($cfg['Server']['verbose']);
        if ($GLOBALS['cfg']['ShowServerInfo']) {
            $server_info .= ' (';
        }
    }
    if ($GLOBALS['cfg']['ShowServerInfo'] || empty($cfg['Server']['verbose'])) {
        $server_info .= PMA_DBI_get_host_info();
    }
    if (! empty($cfg['Server']['verbose']) && $GLOBALS['cfg']['ShowServerInfo']) {
        $server_info .= ')';
    }
    $mysql_cur_user_and_host = PMA_DBI_fetch_value('SELECT USER();');

    // should we add the port info here?
    $short_server_info = (!empty($GLOBALS['cfg']['Server']['verbose'])
                ? $GLOBALS['cfg']['Server']['verbose']
                : $GLOBALS['cfg']['Server']['host']);
}

echo '<div id="maincontainer">' . "\n";
echo '<div id="main_pane_left">';
if ($server > 0
    || (! $cfg['LeftDisplayServers'] && count($cfg['Servers']) > 1)
) {
    echo '<div class="group">';
    echo '<h2>' . __('General Settings') . '</h2>';
    echo '<ul>';
Exemplo n.º 19
0
/**
 * returns default server collation from show variables
 *
 * @uses    PMA_DBI_fetch_value()
 * @return  string  $server_collation
 */
function PMA_getServerCollation()
{
    return PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'collation_server\'', 0, 1);
}
Exemplo n.º 20
0
    }
    $num_fields  = count($fields_meta);
    $action      = 'tbl_alter.php';

    // Get more complete field information.
    // For now, this is done to obtain MySQL 4.1.2+ new TIMESTAMP options
    // and to know when there is an empty DEFAULT value.
    // Later, if the analyser returns more information, it
    // could be executed to replace the info given by SHOW FULL COLUMNS FROM.
    /**
     * @todo put this code into a require()
     * or maybe make it part of PMA_DBI_get_columns();
     */

    // We also need this to correctly learn if a TIMESTAMP is NOT NULL, since
    // SHOW FULL COLUMNS says NULL and SHOW CREATE TABLE says NOT NULL (tested
    // in MySQL 4.0.25).

    $show_create_table = PMA_DBI_fetch_value(
        'SHOW CREATE TABLE ' . $common_functions->backquote($db) . '.' . $common_functions->backquote($table),
        0, 1
    );
    $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
    unset($show_create_table);
    /**
     * Form for changing properties.
     */
    include 'libraries/tbl_properties.inc.php';
}
?>
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
         $result = PMA_DBI_query($a_query);
         if ($query_type == 'drop_db') {
             PMA_clearTransformations($selected[$i]);
         } elseif ($query_type == 'drop_tbl') {
             PMA_clearTransformations($db, $selected[$i]);
         } else {
             if ($query_type == 'drop_fld') {
                 PMA_clearTransformations($db, $table, $selected[$i]);
             }
         }
     }
     // end if
 }
 // end for
 if ($query_type == 'drop_tbl') {
     $default_fk_check_value = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'foreign_key_checks\';', 0, 1) == 'ON' ? 1 : 0;
     if (!empty($sql_query)) {
         $sql_query .= ';';
     } elseif (!empty($sql_query_views)) {
         $sql_query = $sql_query_views . ';';
         unset($sql_query_views);
     }
 }
 if ($use_sql) {
     include './sql.php';
 } elseif (!$run_parts) {
     PMA_DBI_select_db($db);
     // for disabling foreign key checks while dropping tables
     if (!isset($_REQUEST['fk_check']) && $query_type == 'drop_tbl') {
         PMA_DBI_query('SET FOREIGN_KEY_CHECKS = 0;');
     }
Exemplo n.º 23
0
/**
 * PMA_createTargetTables() Create the missing table $uncommon_table in target database
 *
 * @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        names of tables present in source but not in target
 * @param int    $table_index             index of table in $uncommon_tables array
 * @param array  &$uncommon_tables_fields field names of the uncommon table
 * @param bool   $display
 */
function PMA_createTargetTables($src_db, $trg_db, $src_link, $trg_link, &$uncommon_tables, $table_index, &$uncommon_tables_fields, $display)
{
    if (isset($uncommon_tables[$table_index])) {
        $fields_result = PMA_DBI_get_columns($src_db, $uncommon_tables[$table_index], null, true, $src_link);
        $fields = array();
        foreach ($fields_result as $each_field) {
            $field_name = $each_field['Field'];
            $fields[] = $field_name;
        }
        $uncommon_tables_fields[$table_index] = $fields;
        $Create_Query = PMA_DBI_fetch_value("SHOW CREATE TABLE " . PMA_backquote($src_db) . '.' . PMA_backquote($uncommon_tables[$table_index]), 0, 1, $src_link);
        // Replace the src table name with a `dbname`.`tablename`
        $Create_Table_Query = preg_replace('/' . preg_quote(PMA_backquote($uncommon_tables[$table_index]), '/') . '/', PMA_backquote($trg_db) . '.' . PMA_backquote($uncommon_tables[$table_index]), $Create_Query, $limit = 1);
        $is_fk_query = "SELECT * FROM  information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '" . $src_db . "'\n                        AND TABLE_NAME = '" . $uncommon_tables[$table_index] . "' AND TABLE_NAME <> REFERENCED_TABLE_NAME;";
        $is_fk_result = PMA_DBI_fetch_result($is_fk_query, null, null, $src_link);
        if (sizeof($is_fk_result) > 0) {
            for ($j = 0; $j < sizeof($is_fk_result); $j++) {
                if (in_array($is_fk_result[$j]['REFERENCED_TABLE_NAME'], $uncommon_tables)) {
                    $table_index = array_keys($uncommon_tables, $is_fk_result[$j]['REFERENCED_TABLE_NAME']);
                    PMA_createTargetTables($src_db, $trg_db, $trg_link, $src_link, $uncommon_tables, $table_index[0], $uncommon_tables_fields, $display);
                    unset($uncommon_tables[$table_index[0]]);
                }
            }
        }
        $Create_Table_Query .= ';';
        if ($display == true) {
            echo '<p>' . $Create_Table_Query . '</p>';
        }
        PMA_DBI_try_query($Create_Table_Query, $trg_link, 0);
    }
}
Exemplo n.º 24
0
/**
 * Gets foreign keys in preparation for a drop-down selector
 *
 * @param array  $foreigners     array of the foreign keys
 * @param string $field          the foreign field name
 * @param bool   $override_total whether to override the total
 * @param string $foreign_filter a possible filter
 * @param string $foreign_limit  a possible LIMIT clause
 *
 * @return  array    data about the foreign keys
 *
 * @access  public
 */
function PMA_getForeignData($foreigners, $field, $override_total, $foreign_filter, $foreign_limit)
{
    // we always show the foreign field in the drop-down; if a display
    // field is defined, we show it besides the foreign field
    $foreign_link = false;
    if ($foreigners && isset($foreigners[$field])) {
        $foreigner = $foreigners[$field];
        $foreign_db = $foreigner['foreign_db'];
        $foreign_table = $foreigner['foreign_table'];
        $foreign_field = $foreigner['foreign_field'];
        // Count number of rows in the foreign table. Currently we do
        // not use a drop-down if more than 200 rows in the foreign table,
        // for speed reasons and because we need a better interface for this.
        //
        // We could also do the SELECT anyway, with a LIMIT, and ensure that
        // the current value of the field is one of the choices.
        $the_total = PMA_Table::countRecords($foreign_db, $foreign_table);
        if ($override_total == true || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']) {
            // foreign_display can be false if no display field defined:
            $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
            $f_query_main = 'SELECT ' . PMA_backquote($foreign_field) . ($foreign_display == false ? '' : ', ' . PMA_backquote($foreign_display));
            $f_query_from = ' FROM ' . PMA_backquote($foreign_db) . '.' . PMA_backquote($foreign_table);
            $f_query_filter = empty($foreign_filter) ? '' : ' WHERE ' . PMA_backquote($foreign_field) . ' LIKE "%' . PMA_sqlAddSlashes($foreign_filter, true) . '%"' . ($foreign_display == false ? '' : ' OR ' . PMA_backquote($foreign_display) . ' LIKE "%' . PMA_sqlAddSlashes($foreign_filter, true) . '%"');
            $f_query_order = $foreign_display == false ? '' : ' ORDER BY ' . PMA_backquote($foreign_table) . '.' . PMA_backquote($foreign_display);
            $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
            if (!empty($foreign_filter)) {
                $res = PMA_DBI_query('SELECT COUNT(*)' . $f_query_from . $f_query_filter);
                if ($res) {
                    $the_total = PMA_DBI_fetch_value($res);
                    @PMA_DBI_free_result($res);
                } else {
                    $the_total = 0;
                }
            }
            $disp = PMA_DBI_query($f_query_main . $f_query_from . $f_query_filter . $f_query_order . $f_query_limit);
            if ($disp && PMA_DBI_num_rows($disp) > 0) {
                // If a resultset has been created, pre-cache it in the $disp_row array
                // This helps us from not needing to use mysql_data_seek by accessing a pre-cached
                // PHP array. Usually those resultsets are not that big, so a performance hit should
                // not be expected.
                $disp_row = array();
                while ($single_disp_row = @PMA_DBI_fetch_assoc($disp)) {
                    $disp_row[] = $single_disp_row;
                }
                @PMA_DBI_free_result($disp);
            }
        } else {
            $disp_row = null;
            $foreign_link = true;
        }
    }
    // end if $foreigners
    $foreignData['foreign_link'] = $foreign_link;
    $foreignData['the_total'] = isset($the_total) ? $the_total : null;
    $foreignData['foreign_display'] = isset($foreign_display) ? $foreign_display : null;
    $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
    $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
    return $foreignData;
}
Exemplo n.º 25
0
        return $sql;
    }
    // end of the "PMA_getSearchSqls()" function
    /**
     * Displays the results
     */
    $this_url_params = array('db' => $GLOBALS['db'], 'goto' => 'db_sql.php', 'pos' => 0, 'is_js_confirmed' => 0);
    // Displays search string
    echo '<br />' . "\n" . '<table class="data">' . "\n" . '<caption class="tblHeaders">' . "\n" . sprintf(__('Search results for "<i>%s</i>" %s:'), $searched, $option_str) . "\n" . '</caption>' . "\n";
    $num_search_result_total = 0;
    $odd_row = true;
    foreach ($tables_selected as $each_table) {
        // Gets the SQL statements
        $newsearchsqls = PMA_getSearchSqls($each_table, !empty($field_str) ? $field_str : '', $search_str, $search_option);
        // Executes the "COUNT" statement
        $res_cnt = PMA_DBI_fetch_value($newsearchsqls['select_count']);
        $num_search_result_total += $res_cnt;
        $sql_query .= $newsearchsqls['select_count'];
        echo '<tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">' . '<td>' . sprintf(_ngettext('%1$s match inside table <i>%2$s</i>', '%1$s matches inside table <i>%2$s</i>', $res_cnt), $res_cnt, htmlspecialchars($each_table)) . "</td>\n";
        if ($res_cnt > 0) {
            $this_url_params['sql_query'] = $newsearchsqls['select_fields'];
            $browse_result_path = 'sql.php' . PMA_generate_common_url($this_url_params);
            ?>
            <td> <a name="browse_search" href="<?php 
            echo $browse_result_path;
            ?>
" onclick="loadResult('<?php 
            echo $browse_result_path;
            ?>
 ',' <?php 
            echo $each_table;
/**
 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
 *
 * @param string   $db    db name
 * @param string   $which PROCEDURE | FUNCTION | EVENT | VIEW
 * @param string   $name  the procedure|function|event|view name
 * @param resource $link  mysql link
 *
 * @return string the definition
 */
function PMA_DBI_get_definition($db, $which, $name, $link = null)
{
    $common_functions = PMA_CommonFunctions::getInstance();
    $returned_field = array('PROCEDURE' => 'Create Procedure', 'FUNCTION' => 'Create Function', 'EVENT' => 'Create Event', 'VIEW' => 'Create View');
    $query = 'SHOW CREATE ' . $which . ' ' . $common_functions->backquote($db) . '.' . $common_functions->backquote($name);
    return PMA_DBI_fetch_value($query, 0, $returned_field[$which]);
}
Exemplo n.º 27
0
/**
 * Displays the fields used by the "new user" form as well as the
 * "change login information / copy user" form.
 *
 * @param string $mode are we creating a new user or are we just
 *                     changing  one? (allowed values: 'new', 'change')
 *
 * @global  array      $cfg     the phpMyAdmin configuration
 * @global  ressource  $user_link the database connection
 *
 * @return void
 */
function PMA_displayLoginInformationFields($mode = 'new')
{
    // Get user/host name lengths
    $fields_info = PMA_DBI_get_columns('mysql', 'user', null, true);
    $username_length = 16;
    $hostname_length = 41;
    foreach ($fields_info as $val) {
        if ($val['Field'] == 'User') {
            strtok($val['Type'], '()');
            $v = strtok('()');
            if (is_int($v)) {
                $username_length = $v;
            }
        } elseif ($val['Field'] == 'Host') {
            strtok($val['Type'], '()');
            $v = strtok('()');
            if (is_int($v)) {
                $hostname_length = $v;
            }
        }
    }
    unset($fields_info);

    if (isset($GLOBALS['username']) && strlen($GLOBALS['username']) === 0) {
        $GLOBALS['pred_username'] = '******';
    }
    echo '<fieldset id="fieldset_add_user_login">' . "\n"
       . '<legend>' . __('Login Information') . '</legend>' . "\n"
       . '<div class="item">' . "\n"
       . '<label for="select_pred_username">' . "\n"
       . '    ' . __('User name') . ':' . "\n"
       . '</label>' . "\n"
       . '<span class="options">' . "\n"
       . '    <select name="pred_username" id="select_pred_username" title="' . __('User name') . '"' . "\n"
       . '        onchange="if (this.value == \'any\') { username.value = \'\'; } else if (this.value == \'userdefined\') { username.focus(); username.select(); }">' . "\n"
       . '        <option value="any"' . ((isset($GLOBALS['pred_username']) && $GLOBALS['pred_username'] == 'any') ? ' selected="selected"' : '') . '>' . __('Any user') . '</option>' . "\n"
       . '        <option value="userdefined"' . ((! isset($GLOBALS['pred_username']) || $GLOBALS['pred_username'] == 'userdefined') ? ' selected="selected"' : '') . '>' . __('Use text field') . ':</option>' . "\n"
       . '    </select>' . "\n"
       . '</span>' . "\n"
       . '<input type="text" name="username" maxlength="'
       . $username_length . '" title="' . __('User name') . '"'
       . (empty($GLOBALS['username'])
           ? ''
           : ' value="' . htmlspecialchars(
               isset($GLOBALS['new_username'])
               ? $GLOBALS['new_username']
               : $GLOBALS['username']
           ) . '"'
       )
       . ' onchange="pred_username.value = \'userdefined\';" autofocus="autofocus" />' . "\n"
       . '</div>' . "\n"
       . '<div class="item">' . "\n"
       . '<label for="select_pred_hostname">' . "\n"
       . '    ' . __('Host') . ':' . "\n"
       . '</label>' . "\n"
       . '<span class="options">' . "\n"
       . '    <select name="pred_hostname" id="select_pred_hostname" title="' . __('Host') . '"' . "\n";
    $_current_user = PMA_DBI_fetch_value('SELECT USER();');
    if (! empty($_current_user)) {
        $thishost = str_replace("'", '', substr($_current_user, (strrpos($_current_user, '@') + 1)));
        if ($thishost == 'localhost' || $thishost == '127.0.0.1') {
            unset($thishost);
        }
    }
    echo '    onchange="if (this.value == \'any\') { hostname.value = \'%\'; } else if (this.value == \'localhost\') { hostname.value = \'localhost\'; } '
       . (empty($thishost) ? '' : 'else if (this.value == \'thishost\') { hostname.value = \'' . addslashes(htmlspecialchars($thishost)) . '\'; } ')
       . 'else if (this.value == \'hosttable\') { hostname.value = \'\'; } else if (this.value == \'userdefined\') { hostname.focus(); hostname.select(); }">' . "\n";
    unset($_current_user);

    // when we start editing a user, $GLOBALS['pred_hostname'] is not defined
    if (! isset($GLOBALS['pred_hostname']) && isset($GLOBALS['hostname'])) {
        switch (strtolower($GLOBALS['hostname'])) {
        case 'localhost':
        case '127.0.0.1':
            $GLOBALS['pred_hostname'] = 'localhost';
            break;
        case '%':
            $GLOBALS['pred_hostname'] = 'any';
            break;
        default:
            $GLOBALS['pred_hostname'] = 'userdefined';
            break;
        }
    }
    echo '        <option value="any"'
        . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'any')
            ? ' selected="selected"' : '') . '>' . __('Any host')
        . '</option>' . "\n"
       . '        <option value="localhost"'
        . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'localhost')
            ? ' selected="selected"' : '') . '>' . __('Local')
        . '</option>' . "\n";
    if (! empty($thishost)) {
        echo '        <option value="thishost"'
            . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'thishost')
                ? ' selected="selected"' : '') . '>' . __('This Host')
            . '</option>' . "\n";
    }
    unset($thishost);
    echo '        <option value="hosttable"'
        . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'hosttable')
            ? ' selected="selected"' : '') . '>' . __('Use Host Table')
        . '</option>' . "\n"
       . '        <option value="userdefined"'
        . ((isset($GLOBALS['pred_hostname']) && $GLOBALS['pred_hostname'] == 'userdefined')
            ? ' selected="selected"' : '')
        . '>' . __('Use text field') . ':</option>' . "\n"
       . '    </select>' . "\n"
       . '</span>' . "\n"
       . '<input type="text" name="hostname" maxlength="'
        . $hostname_length . '" value="'
        . htmlspecialchars(isset($GLOBALS['hostname']) ? $GLOBALS['hostname'] : '')
        . '" title="' . __('Host')
        . '" onchange="pred_hostname.value = \'userdefined\';" />' . "\n"
       . PMA_showHint(__('When Host table is used, this field is ignored and values stored in Host table are used instead.'))
       . '</div>' . "\n"
       . '<div class="item">' . "\n"
       . '<label for="select_pred_password">' . "\n"
       . '    ' . __('Password') . ':' . "\n"
       . '</label>' . "\n"
       . '<span class="options">' . "\n"
       . '    <select name="pred_password" id="select_pred_password" title="'
        . __('Password') . '"' . "\n"
       . '            onchange="if (this.value == \'none\') { pma_pw.value = \'\'; pma_pw2.value = \'\'; } else if (this.value == \'userdefined\') { pma_pw.focus(); pma_pw.select(); }">' . "\n"
       . ($mode == 'change' ? '            <option value="keep" selected="selected">' . __('Do not change the password') . '</option>' . "\n" : '')
       . '        <option value="none"';
    if (isset($GLOBALS['username']) && $mode != 'change') {
        echo '  selected="selected"';
    }
    echo '>' . __('No Password') . '</option>' . "\n"
       . '        <option value="userdefined"' . (isset($GLOBALS['username']) ? '' : ' selected="selected"') . '>' . __('Use text field') . ':</option>' . "\n"
       . '    </select>' . "\n"
       . '</span>' . "\n"
       . '<input type="password" id="text_pma_pw" name="pma_pw" title="' . __('Password') . '" onchange="pred_password.value = \'userdefined\';" />' . "\n"
       . '</div>' . "\n"
       . '<div class="item" id="div_element_before_generate_password">' . "\n"
       . '<label for="text_pma_pw2">' . "\n"
       . '    ' . __('Re-type') . ':' . "\n"
       . '</label>' . "\n"
       . '<span class="options">&nbsp;</span>' . "\n"
       . '<input type="password" name="pma_pw2" id="text_pma_pw2" title="' . __('Re-type') . '" onchange="pred_password.value = \'userdefined\';" />' . "\n"
       . '</div>' . "\n"
       // Generate password added here via jQuery
       . '</fieldset>' . "\n";
} // end of the 'PMA_displayUserAndHostFields()' function
/**
 * Get HTML snippet for display user properties
 *
 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
 * @param type    $url_dbname         url database name that urlencode() string
 * @param string  $username           username
 * @param string  $hostname           host name
 * @param string  $link_edit          standard link to edit privileges
 * @param string  $link_revoke        standard link to revoke
 * @param string  $dbname             database name
 * @param string  $tablename          table name
 *
 * @return string $html_output
 */
function PMA_getHtmlForDisplayUserProperties($dbname_is_wildcard, $url_dbname, $username, $hostname, $link_edit, $link_revoke, $dbname, $tablename)
{
    $html_output = PMA_getHtmlHeaderForDisplayUserProperties($dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename);
    $sql = "SELECT '1' FROM `mysql`.`user`" . " WHERE `User` = '" . PMA_Util::sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA_Util::sqlAddSlashes($hostname) . "';";
    $user_does_not_exists = (bool) (!PMA_DBI_fetch_value($sql));
    if ($user_does_not_exists) {
        $html_output .= PMA_Message::error(__('The selected user was not found in the privilege table.'))->getDisplay();
        $html_output .= PMA_getHtmlForDisplayLoginInformationFields();
        //exit;
    }
    $class = ' class="ajax"';
    $html_output .= '<form' . $class . ' name="usersForm" id="addUsersForm"' . ' action="server_privileges.php" method="post">' . "\n";
    $_params = array('username' => $username, 'hostname' => $hostname);
    if (strlen($dbname)) {
        $_params['dbname'] = $dbname;
        if (strlen($tablename)) {
            $_params['tablename'] = $tablename;
        }
    }
    $html_output .= PMA_generate_common_hidden_inputs($_params);
    $html_output .= PMA_getHtmlToDisplayPrivilegesTable(PMA_ifSetOr($dbname, '*', 'length'), PMA_ifSetOr($tablename, '*', 'length'));
    $html_output .= '</form>' . "\n";
    if (!strlen($tablename) && empty($dbname_is_wildcard)) {
        // no table name was given, display all table specific rights
        // but only if $dbname contains no wildcards
        $html_output .= '<form action="server_privileges.php" ' . 'id="db_or_table_specific_priv" method="post">' . "\n";
        list($html_rightsTable, $found_rows) = PMA_getTableForDisplayAllTableSpecificRights($username, $hostname, $link_edit, $link_revoke, $dbname);
        $html_output .= $html_rightsTable;
        if (!strlen($dbname)) {
            // no database name was given, display select db
            $html_output .= PMA_getHtmlForDisplaySelectDbInEditPrivs($found_rows);
        } else {
            $html_output .= PMA_displayTablesInEditPrivs($dbname, $found_rows);
        }
        $html_output .= '</fieldset>' . "\n";
        $html_output .= '<fieldset class="tblFooters">' . "\n" . '    <input type="submit" value="' . __('Go') . '" />' . '</fieldset>' . "\n" . '</form>' . "\n";
    }
    // Provide a line with links to the relevant database and table
    if (strlen($dbname) && empty($dbname_is_wildcard)) {
        $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);
    }
    if (!strlen($dbname) && !$user_does_not_exists) {
        //change login information
        $html_output .= PMA_getHtmlForChangePassword($username, $hostname);
        $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
    }
    return $html_output;
}
Exemplo n.º 29
0
function PMA_DBI_insert_id($link = null)
{
    if (empty($link)) {
        if (isset($GLOBALS['userlink'])) {
            $link = $GLOBALS['userlink'];
        } else {
            return false;
        }
    }
    //$insert_id = mysql_insert_id($link);
    // if the primary key is BIGINT we get an incorrect result
    // (sometimes negative, sometimes positive)
    // and in the present function we don't know if the PK is BIGINT
    // so better play safe and use LAST_INSERT_ID()
    //
    // by the way, no problem with mysqli_insert_id()
    return PMA_DBI_fetch_value('SELECT LAST_INSERT_ID();', 0, 0, $link);
}
Exemplo n.º 30
0
/**
 * returns the definition of a specific PROCEDURE, FUNCTION or EVENT
 *
 * @uses    PMA_DBI_fetch_value()
 * @param   string              $db     db name
 * @param   string              $which  PROCEDURE | FUNCTION | EVENT
 * @param   string              $name  the procedure|function|event name
 * @param   resource            $link   mysql link
 *
 * @return  string              the definition
 */
function PMA_DBI_get_definition($db, $which, $name, $link = null)
{
    $returned_field = array('PROCEDURE' => 'Create Procedure', 'FUNCTION' => 'Create Function', 'EVENT' => 'Create Event');
    $query = 'SHOW CREATE ' . $which . ' ' . PMA_backquote($db) . '.' . PMA_backquote($name);
    return PMA_DBI_fetch_value($query, 0, $returned_field[$which]);
}