Beispiel #1
0
 public static function parse($_sql)
 {
     if (!is_array($_sql)) {
         $_sql = self::parsePMA($_sql);
     }
     $analyzedSql = PMA_SQP_analyze($_sql);
     return self::trim(@$analyzedSql[0]);
 }
Beispiel #2
0
/**
 * Dispatches between the versions of 'getTableContent' to use depending
 * on the php version
 *
 * @param   string      the database name
 * @param   string      the table name
 * @param   string      the end of line sequence
 * @param   string      the url to go back in case of error
 * @param   string      SQL query for obtaining data
 *
 * @return  bool        Whether it suceeded
 *
 * @global  boolean  whether to use backquotes to allow the use of special
 *                   characters in database, table and fields names or not
 * @global  integer  the number of records
 * @global  integer  the current record position
 *
 * @access  public
 *
 * @see     PMA_getTableContentFast(), PMA_getTableContentOld()
 *
 * @author  staybyte
 */
function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
{
    global $use_backquotes;
    global $rows_cnt;
    global $current_row;
    $formatted_table_name = isset($GLOBALS['use_backquotes']) ? PMA_backquote($table) : '\'' . $table . '\'';
    $head = $crlf . '#' . $crlf . '# ' . $GLOBALS['strDumpingData'] . ' ' . $formatted_table_name . $crlf . '#' . $crlf . $crlf;
    if (!PMA_exportOutputHandler($head)) {
        return FALSE;
    }
    $buffer = '';
    $result = PMA_mysql_query($sql_query) or PMA_mysqlDie('', $sql_query, '', $error_url);
    if ($result != FALSE) {
        $fields_cnt = mysql_num_fields($result);
        $rows_cnt = mysql_num_rows($result);
        // get the real types of the table's fields (in an array)
        // the key of the array is the backquoted field name
        $field_types = PMA_fieldTypes($db, $table, $use_backquotes);
        // 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));
        // Checks whether the field is an integer or not
        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'], $use_backquotes);
            } else {
                $field_set[$j] = PMA_backquote(PMA_mysql_field_name($result, $j), $use_backquotes);
            }
            $type = $field_types[$field_set[$j]];
            if ($type == 'tinyint' || $type == 'smallint' || $type == 'mediumint' || $type == 'int' || $type == 'bigint' || PMA_MYSQL_INT_VERSION < 40100 && $type == 'timestamp') {
                $field_num[$j] = TRUE;
            } else {
                $field_num[$j] = FALSE;
            }
            // blob
            if ($type == 'blob' || $type == 'mediumblob' || $type == 'longblob' || $type == 'tinyblob') {
                $field_blob[$j] = TRUE;
            } else {
                $field_blob[$j] = FALSE;
            }
        }
        // end for
        if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'update') {
            // update
            $schema_insert = 'UPDATE ' . PMA_backquote($table, $use_backquotes) . ' SET ';
            $fields_no = count($field_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['delayed'])) {
                $insert_delayed = ' DELAYED';
            } else {
                $insert_delayed = '';
            }
            // Sets the scheme
            if (isset($GLOBALS['showcolumns'])) {
                $fields = implode(', ', $field_set);
                $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $use_backquotes) . ' (' . $fields . ') VALUES (';
            } else {
                $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $use_backquotes) . ' VALUES (';
            }
        }
        $search = array("", "\n", "\r", "");
        //\x08\\x09, not required
        $replace = array('\\0', '\\n', '\\r', '\\Z');
        $current_row = 0;
        while ($row = PMA_mysql_fetch_row($result)) {
            $current_row++;
            for ($j = 0; $j < $fields_cnt; $j++) {
                if (!isset($row[$j])) {
                    $values[] = 'NULL';
                } else {
                    if ($row[$j] == '0' || $row[$j] != '') {
                        // a number
                        if ($field_num[$j]) {
                            $values[] = $row[$j];
                            // a not empty blob
                        } else {
                            if ($field_blob[$j] && !empty($row[$j])) {
                                $values[] = '0x' . bin2hex($row[$j]);
                                // a string
                            } else {
                                $values[] = "'" . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . "'";
                            }
                        }
                    } else {
                        $values[] = "''";
                    }
                }
                // 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_no; $i++) {
                    if ($i > 0) {
                        $insert_line .= ', ';
                    }
                    $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                }
            } else {
                // Extended inserts case
                if (isset($GLOBALS['extended_ins'])) {
                    if ($current_row == 1) {
                        $insert_line = $schema_insert . implode(', ', $values) . ')';
                    } else {
                        $insert_line = '(' . implode(', ', $values) . ')';
                    }
                } else {
                    $insert_line = $schema_insert . implode(', ', $values) . ')';
                }
            }
            unset($values);
            if (!PMA_exportOutputHandler($insert_line . (isset($GLOBALS['extended_ins']) && $current_row < $rows_cnt ? ',' : ';') . $crlf)) {
                return FALSE;
            }
        }
        // end while
    }
    // end if ($result != FALSE)
    mysql_free_result($result);
    return TRUE;
}
Beispiel #3
0
/**
 * Gets all Relations to foreign tables for a given table or
 * optionally a given column in a table
 *
 * @param string $db     the name of the db to check for
 * @param string $table  the name of the table to check for
 * @param string $column the name of the column to check for
 * @param string $source the source for foreign key information
 *
 * @return array    db,table,column
 *
 * @access  public
 */
function PMA_getForeigners($db, $table, $column = '', $source = 'both')
{
    $cfgRelation = PMA_getRelationsParam();
    $foreign = array();
    if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
        $rel_query = '
             SELECT `master_field`,
                    `foreign_db`,
                    `foreign_table`,
                    `foreign_field`
               FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . '
              WHERE `master_db`    = \'' . PMA_Util::sqlAddSlashes($db) . '\'
                AND `master_table` = \'' . PMA_Util::sqlAddSlashes($table) . '\' ';
        if (mb_strlen($column)) {
            $rel_query .= ' AND `master_field` = ' . '\'' . PMA_Util::sqlAddSlashes($column) . '\'';
        }
        $foreign = $GLOBALS['dbi']->fetchResult($rel_query, 'master_field', null, $GLOBALS['controllink']);
    }
    if (($source == 'both' || $source == 'foreign') && mb_strlen($table)) {
        $showCreateTableQuery = 'SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
        $show_create_table = $GLOBALS['dbi']->fetchValue($showCreateTableQuery, 0, 1);
        if ($show_create_table) {
            $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
            $foreign['foreign_keys_data'] = $analyzed_sql[0]['foreign_keys'];
        }
    }
    /**
     * Emulating relations for some information_schema and data_dictionary tables
     */
    $isInformationSchema = mb_strtolower($db) == 'information_schema';
    $is_data_dictionary = PMA_DRIZZLE && mb_strtolower($db) == 'data_dictionary';
    $isMysql = mb_strtolower($db) == 'mysql';
    if (($isInformationSchema || $is_data_dictionary || $isMysql) && ($source == 'internal' || $source == 'both')) {
        if ($isInformationSchema) {
            $relations_key = 'information_schema_relations';
            include_once './libraries/information_schema_relations.lib.php';
        } else {
            if ($is_data_dictionary) {
                $relations_key = 'data_dictionary_relations';
                include_once './libraries/data_dictionary_relations.lib.php';
            } else {
                $relations_key = 'mysql_relations';
                include_once './libraries/mysql_relations.lib.php';
            }
        }
        if (isset($GLOBALS[$relations_key][$table])) {
            foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
                if ((!mb_strlen($column) || $column == $field) && (!isset($foreign[$field]) || !mb_strlen($foreign[$field]))) {
                    $foreign[$field] = $relations;
                }
            }
        }
    }
    return $foreign;
}
<?php

/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 *
 * @package phpMyAdmin
 */
if (!defined('PHPMYADMIN')) {
    exit;
}
/**
 *
 */
$GLOBALS['unparsed_sql'] = $sql_query;
$parsed_sql = PMA_SQP_parse($sql_query);
$analyzed_sql = PMA_SQP_analyze($parsed_sql);
// for bug 780516: now that we use case insensitive preg_match
// or flags from the analyser, do not put back the reformatted query
// into $sql_query, to make this kind of query work without
// capitalizing keywords:
//
// CREATE TABLE SG_Persons (
//  id int(10) unsigned NOT NULL auto_increment,
//  first varchar(64) NOT NULL default '',
//  PRIMARY KEY  (`id`)
// )
// check for a real SELECT ... FROM
$is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
// If the query is a Select, extract the db and table names and modify
// $db and $table, to have correct page headers, links and left frame.
// db and table name may be enclosed with backquotes, db is optionnal,
Beispiel #5
0
/**
 * displays the message and the query
 * usually the message is the result of the query executed
 *
 * @param string  $message   the message to display
 * @param string  $sql_query the query to display
 * @param string  $type      the type (level) of the message
 * @param boolean $is_view   is this a message after a VIEW operation?
 *
 * @return  string
 *
 * @access  public
 */
function PMA_showMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
{
    /*
     * PMA_ajaxResponse uses this function to collect the string of HTML generated
     * for showing the message.  Use output buffering to collect it and return it
     * in a string.  In some special cases on sql.php, buffering has to be disabled
     * and hence we check with $GLOBALS['buffer_message']
     */
    if ($GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message'])) {
        ob_start();
    }
    global $cfg;
    if (null === $sql_query) {
        if (!empty($GLOBALS['display_query'])) {
            $sql_query = $GLOBALS['display_query'];
        } elseif ($cfg['SQP']['fmtType'] == 'none' && !empty($GLOBALS['unparsed_sql'])) {
            $sql_query = $GLOBALS['unparsed_sql'];
        } elseif (!empty($GLOBALS['sql_query'])) {
            $sql_query = $GLOBALS['sql_query'];
        } else {
            $sql_query = '';
        }
    }
    if (isset($GLOBALS['using_bookmark_message'])) {
        $GLOBALS['using_bookmark_message']->display();
        unset($GLOBALS['using_bookmark_message']);
    }
    // Corrects the tooltip text via JS if required
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (!$is_view && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
        $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
        $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
        echo "\n";
        echo '<script type="text/javascript">' . "\n";
        echo '//<![CDATA[' . "\n";
        echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
        echo '//]]>' . "\n";
        echo '</script>' . "\n";
    }
    // end if ... elseif
    // Checks if the table needs to be repaired after a TRUNCATE query.
    // @todo what about $GLOBALS['display_query']???
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (strlen($GLOBALS['table']) && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
        if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024 && !PMA_DRIZZLE) {
            PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
        }
    }
    unset($tbl_status);
    // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
    // check for it's presence before using it
    echo '<div id="result_query" align="' . (isset($GLOBALS['cell_align_left']) ? $GLOBALS['cell_align_left'] : '') . '">' . "\n";
    if ($message instanceof PMA_Message) {
        if (isset($GLOBALS['special_message'])) {
            $message->addMessage($GLOBALS['special_message']);
            unset($GLOBALS['special_message']);
        }
        $message->display();
        $type = $message->getLevel();
    } else {
        echo '<div class="' . $type . '">';
        echo PMA_sanitize($message);
        if (isset($GLOBALS['special_message'])) {
            echo PMA_sanitize($GLOBALS['special_message']);
            unset($GLOBALS['special_message']);
        }
        echo '</div>';
    }
    if ($cfg['ShowSQL'] == true && !empty($sql_query)) {
        // Html format the query to be displayed
        // If we want to show some sql code it is easiest to create it here
        /* SQL-Parser-Analyzer */
        if (!empty($GLOBALS['show_as_php'])) {
            $new_line = '\\n"<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
            $query_base = htmlspecialchars(addslashes($sql_query));
            $query_base = preg_replace('/((\\015\\012)|(\\015)|(\\012))/', $new_line, $query_base);
        } else {
            $query_base = $sql_query;
        }
        $query_too_big = false;
        if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
            // when the query is large (for example an INSERT of binary
            // data), the parser chokes; so avoid parsing the query
            $query_too_big = true;
            $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
        } elseif (!empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
            // (here, use "! empty" because when deleting a bookmark,
            // $GLOBALS['parsed_sql'] is set but empty
            $parsed_sql = $GLOBALS['parsed_sql'];
        } else {
            // Parse SQL if needed
            $parsed_sql = PMA_SQP_parse($query_base);
        }
        // Analyze it
        if (isset($parsed_sql) && !PMA_SQP_isError()) {
            $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
            // Same as below (append LIMIT), append the remembered ORDER BY
            if ($GLOBALS['cfg']['RememberSorting'] && isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_order_to_append'])) {
                $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_order_to_append'] . $analyzed_display_query[0]['limit_clause'] . ' ' . $analyzed_display_query[0]['section_after_limit'];
                // Need to reparse query
                $parsed_sql = PMA_SQP_parse($query_base);
                // update the $analyzed_display_query
                $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
                $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
            }
            // Here we append the LIMIT added for navigation, to
            // enable its display. Adding it higher in the code
            // to $sql_query would create a problem when
            // using the Refresh or Edit links.
            // Only append it on SELECTs.
            /**
             * @todo what would be the best to do when someone hits Refresh:
             * use the current LIMITs ?
             */
            if (isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_limit_to_append'])) {
                $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
                // Need to reparse query
                $parsed_sql = PMA_SQP_parse($query_base);
            }
        }
        if (!empty($GLOBALS['show_as_php'])) {
            $query_base = '$sql  = "' . $query_base;
        } elseif (!empty($GLOBALS['validatequery'])) {
            try {
                $query_base = PMA_validateSQL($query_base);
            } catch (Exception $e) {
                PMA_Message::error(__('Failed to connect to SQL validator!'))->display();
            }
        } elseif (isset($parsed_sql)) {
            $query_base = PMA_formatSql($parsed_sql, $query_base);
        }
        // Prepares links that may be displayed to edit/explain the query
        // (don't go to default pages, we must go to the page
        // where the query box is available)
        // Basic url query part
        $url_params = array();
        if (!isset($GLOBALS['db'])) {
            $GLOBALS['db'] = '';
        }
        if (strlen($GLOBALS['db'])) {
            $url_params['db'] = $GLOBALS['db'];
            if (strlen($GLOBALS['table'])) {
                $url_params['table'] = $GLOBALS['table'];
                $edit_link = 'tbl_sql.php';
            } else {
                $edit_link = 'db_sql.php';
            }
        } else {
            $edit_link = 'server_sql.php';
        }
        // Want to have the query explained
        // but only explain a SELECT (that has not been explained)
        /* SQL-Parser-Analyzer */
        $explain_link = '';
        $is_select = false;
        if (!empty($cfg['SQLQuery']['Explain']) && !$query_too_big) {
            $explain_params = $url_params;
            // Detect if we are validating as well
            // To preserve the validate uRL data
            if (!empty($GLOBALS['validatequery'])) {
                $explain_params['validatequery'] = 1;
            }
            if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
                $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
                $_message = __('Explain SQL');
                $is_select = true;
            } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
                $explain_params['sql_query'] = substr($sql_query, 8);
                $_message = __('Skip Explain SQL');
            }
            if (isset($explain_params['sql_query'])) {
                $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
                $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
            }
        }
        //show explain
        $url_params['sql_query'] = $sql_query;
        $url_params['show_query'] = 1;
        // even if the query is big and was truncated, offer the chance
        // to edit it (unless it's enormous, see PMA_linkOrButton() )
        if (!empty($cfg['SQLQuery']['Edit'])) {
            if ($cfg['EditInWindow'] == true) {
                $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
            } else {
                $onclick = '';
            }
            $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
            $edit_link = ' [' . PMA_linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick)) . ']';
        } else {
            $edit_link = '';
        }
        $url_qpart = PMA_generate_common_url($url_params);
        // Also we would like to get the SQL formed in some nice
        // php-code
        if (!empty($cfg['SQLQuery']['ShowAsPHP']) && !$query_too_big) {
            $php_params = $url_params;
            if (!empty($GLOBALS['show_as_php'])) {
                $_message = __('Without PHP Code');
            } else {
                $php_params['show_as_php'] = 1;
                $_message = __('Create PHP Code');
            }
            $php_link = 'import.php' . PMA_generate_common_url($php_params);
            $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
            if (isset($GLOBALS['show_as_php'])) {
                $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
                $php_link .= ' [' . PMA_linkOrButton($runquery_link, __('Submit Query')) . ']';
            }
        } else {
            $php_link = '';
        }
        //show as php
        // Refresh query
        if (!empty($cfg['SQLQuery']['Refresh']) && !isset($GLOBALS['show_as_php']) && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
            $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
            $refresh_link = ' [' . PMA_linkOrButton($refresh_link, __('Refresh')) . ']';
        } else {
            $refresh_link = '';
        }
        //refresh
        if (!empty($cfg['SQLValidator']['use']) && !empty($cfg['SQLQuery']['Validate'])) {
            $validate_params = $url_params;
            if (!empty($GLOBALS['validatequery'])) {
                $validate_message = __('Skip Validate SQL');
            } else {
                $validate_params['validatequery'] = 1;
                $validate_message = __('Validate SQL');
            }
            $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
            $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
        } else {
            $validate_link = '';
        }
        //validator
        if (!empty($GLOBALS['validatequery'])) {
            echo '<div class="sqlvalidate">';
        } else {
            echo '<code class="sql">';
        }
        if ($query_too_big) {
            echo $shortened_query_base;
        } else {
            echo $query_base;
        }
        //Clean up the end of the PHP
        if (!empty($GLOBALS['show_as_php'])) {
            echo '";';
        }
        if (!empty($GLOBALS['validatequery'])) {
            echo '</div>';
        } else {
            echo '</code>';
        }
        echo '<div class="tools">';
        // avoid displaying a Profiling checkbox that could
        // be checked, which would reexecute an INSERT, for example
        if (!empty($refresh_link)) {
            PMA_profilingCheckbox($sql_query);
        }
        // if needed, generate an invisible form that contains controls for the
        // Inline link; this way, the behavior of the Inline link does not
        // depend on the profiling support or on the refresh link
        if (empty($refresh_link) || !PMA_profilingSupported()) {
            echo '<form action="sql.php" method="post">';
            echo PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']);
            echo '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
            echo '</form>';
        }
        // in the tools div, only display the Inline link when not in ajax
        // mode because 1) it currently does not work and 2) we would
        // have two similar mechanisms on the page for the same goal
        if ($is_select || $GLOBALS['is_ajax_request'] === false && !$query_too_big) {
            // see in js/functions.js the jQuery code attached to id inline_edit
            // document.write conflicts with jQuery, hence used $().append()
            echo "<script type=\"text/javascript\">\n" . "//<![CDATA[\n" . "\$('.tools form').last().after('[<a href=\"#\" title=\"" . PMA_escapeJsString(__('Inline edit of this query')) . "\" class=\"inline_edit_sql\">" . PMA_escapeJsString(_pgettext('Inline edit query', 'Inline')) . "</a>]');\n" . "//]]>\n" . "</script>";
        }
        echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
        echo '</div>';
    }
    echo '</div>';
    if ($GLOBALS['is_ajax_request'] === false) {
        echo '<br class="clearfloat" />';
    }
    // If we are in an Ajax request, we have most probably been called in
    // PMA_ajaxResponse().  Hence, collect the buffer contents and return it
    // to PMA_ajaxResponse(), which will encode it for JSON.
    if ($GLOBALS['is_ajax_request'] == true && !isset($GLOBALS['buffer_message'])) {
        $buffer_contents = ob_get_contents();
        ob_end_clean();
        return $buffer_contents;
    }
    return null;
}
/**
 * Get Aliases from select query
 * Note: only useful for select query on single table.
 *
 * @param string $select_query The Select SQL Query
 * @param string $db           Current DB
 *
 * @return Array alias information from select query
 */
function PMA_SQP_getAliasesFromQuery($select_query, $db)
{
    if (empty($select_query) || empty($db)) {
        return array();
    }
    $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($select_query));
    $aliases = array($db => array('alias' => null, 'tables' => array()));
    foreach ($analyzed_sql[0]['table_ref'] as $table) {
        $t_db = !empty($table['db']) ? $table['db'] : $db;
        if (!isset($aliases[$t_db])) {
            $aliases[$t_db] = array('alias' => null, 'tables' => array());
        }
        $aliases[$t_db]['tables'][$table['table_true_name']] = array('alias' => !empty($table['table_alias']) ? $table['table_alias'] : null, 'columns' => array());
    }
    foreach ($analyzed_sql[0]['select_expr'] as $cols) {
        if (!empty($cols['alias'])) {
            $t_db = !empty($cols['db']) ? $cols['db'] : $db;
            if (!empty($cols['table_true_name'])) {
                $aliases[$t_db]['tables'][$cols['table_true_name']]['columns'][$cols['column']] = $cols['alias'];
            } else {
                foreach ($aliases[$t_db]['tables'] as $key => $table) {
                    $aliases[$t_db]['tables'][$key]['columns'][$cols['column']] = $cols['alias'];
                }
            }
        }
    }
    return $aliases;
}
/**
 * Displays HTML for changing one or more columns
 *
 * @param string $db       database name
 * @param string $table    table name
 * @param array  $selected the selected columns
 * @param string $action   target script to call
 *
 * @return boolean $regenerate true if error occurred
 *
 */
function PMA_displayHtmlForColumnChange($db, $table, $selected, $action)
{
    // $selected comes from multi_submits.inc.php
    if (empty($selected)) {
        $selected[] = $_REQUEST['field'];
        $selected_cnt = 1;
    } else {
        // from a multiple submit
        $selected_cnt = count($selected);
    }
    /**
     * @todo optimize in case of multiple fields to modify
     */
    $fields_meta = array();
    for ($i = 0; $i < $selected_cnt; $i++) {
        $fields_meta[] = $GLOBALS['dbi']->getColumns($db, $table, $selected[$i], true);
    }
    $num_fields = count($fields_meta);
    // set these globals because tbl_columns_definition_form.inc.php
    // verifies them
    // @todo: refactor tbl_columns_definition_form.inc.php so that it uses
    // function params
    $GLOBALS['action'] = 'tbl_structure.php';
    $GLOBALS['num_fields'] = $num_fields;
    // 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 $GLOBALS['dbi']->getColumns();
     */
    // 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 = $GLOBALS['dbi']->fetchValue('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::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_columns_definition_form.inc.php';
}
Beispiel #8
0
/**
 * Gets all Relations to foreign tables for a given table or
 * optionally a given column in a table
 *
 * @param string $db     the name of the db to check for
 * @param string $table  the name of the table to check for
 * @param string $column the name of the column to check for
 * @param string $source the source for foreign key information
 *
 * @return  array    db,table,column
 *
 * @access  public
 */
function PMA_getForeigners($db, $table, $column = '', $source = 'both')
{
    $cfgRelation = PMA_getRelationsParam();
    $foreign = array();
    if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
        $rel_query = '
             SELECT `master_field`,
                    `foreign_db`,
                    `foreign_table`,
                    `foreign_field`
               FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
              WHERE `master_db`    = \'' . PMA_sqlAddSlashes($db) . '\'
                AND `master_table` = \'' . PMA_sqlAddSlashes($table) . '\' ';
        if (strlen($column)) {
            $rel_query .= ' AND `master_field` = \'' . PMA_sqlAddSlashes($column) . '\'';
        }
        $foreign = PMA_DBI_fetch_result($rel_query, 'master_field', null, $GLOBALS['controllink']);
    }
    if (($source == 'both' || $source == 'foreign') && strlen($table)) {
        $show_create_table_query = 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table);
        $show_create_table = PMA_DBI_fetch_value($show_create_table_query, 0, 1);
        $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
        foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
            // The analyzer may return more than one column name in the
            // index list or the ref_index_list; if this happens,
            // the current logic just discards the whole index; having
            // more than one index field is currently unsupported (see FAQ 3.6)
            if (count($one_key['index_list']) == 1) {
                foreach ($one_key['index_list'] as $i => $field) {
                    // If a foreign key is defined in the 'internal' source (pmadb)
                    // and as a native foreign key, we won't get it twice
                    // if $source='both' because we use $field as key
                    // The parser looks for a CONSTRAINT clause just before
                    // the FOREIGN KEY clause. It finds it (as output from
                    // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
                    // versions like 3.23.58.
                    // In those cases, the FOREIGN KEY parsing will put numbers
                    // like -1, 0, 1... instead of the constraint number.
                    if (isset($one_key['constraint'])) {
                        $foreign[$field]['constraint'] = $one_key['constraint'];
                    }
                    if (isset($one_key['ref_db_name'])) {
                        $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
                    } else {
                        $foreign[$field]['foreign_db'] = $db;
                    }
                    $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
                    $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
                    if (isset($one_key['on_delete'])) {
                        $foreign[$field]['on_delete'] = $one_key['on_delete'];
                    }
                    if (isset($one_key['on_update'])) {
                        $foreign[$field]['on_update'] = $one_key['on_update'];
                    }
                }
            }
        }
    }
    /**
     * Emulating relations for some information_schema and data_dictionary tables
     */
    $is_information_schema = strtolower($db) == 'information_schema';
    $is_data_dictionary = PMA_DRIZZLE && strtolower($db) == 'data_dictionary';
    if (($is_information_schema || $is_data_dictionary) && ($source == 'internal' || $source == 'both')) {
        if ($is_information_schema) {
            $relations_key = 'information_schema_relations';
            include_once './libraries/information_schema_relations.lib.php';
        } else {
            $relations_key = 'data_dictionary_relations';
            include_once './libraries/data_dictionary_relations.lib.php';
        }
        if (isset($GLOBALS[$relations_key][$table])) {
            foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
                if ((!strlen($column) || $column == $field) && (!isset($foreign[$field]) || !strlen($foreign[$field]))) {
                    $foreign[$field] = $relations;
                }
            }
        }
    }
    return $foreign;
}
Beispiel #9
0
    /**
     * Displays a message at the top of the "main" (right) frame
     *
     * @param   string  the message to display
     *
     * @global  array   the configuration array
     *
     * @access  public
     */
    function PMA_showMessage($message)
    {
        global $cfg;
        // Sanitizes $message
        $message = PMA_sanitize($message);
        // Corrects the tooltip text via JS if required
        if (isset($GLOBALS['table']) && strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
            $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
            if ($result) {
                $tbl_status = PMA_DBI_fetch_assoc($result);
                $tooltip = empty($tbl_status['Comment']) ? '' : $tbl_status['Comment'] . ' ';
                $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
                PMA_DBI_free_result($result);
                $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
                echo "\n";
                ?>
<script type="text/javascript" language="javascript">
//<![CDATA[
window.parent.updateTableTitle('<?php 
                echo $uni_tbl;
                ?>
', '<?php 
                echo PMA_jsFormat($tooltip, false);
                ?>
');
//]]>
</script>
                <?php 
            }
            // end if
        }
        // end if ... elseif
        // Checks if the table needs to be repaired after a TRUNCATE query.
        if (isset($GLOBALS['table']) && isset($GLOBALS['sql_query']) && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
            if (!isset($tbl_status)) {
                $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
                if ($result) {
                    $tbl_status = PMA_DBI_fetch_assoc($result);
                    PMA_DBI_free_result($result);
                }
            }
            if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
                PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
            }
        }
        unset($tbl_status);
        ?>
<br />
<div align="<?php 
        echo $GLOBALS['cell_align_left'];
        ?>
">
        <?php 
        if (!empty($GLOBALS['show_error_header'])) {
            ?>
    <div class="error">
        <h1><?php 
            echo $GLOBALS['strError'];
            ?>
</h1>
            <?php 
        }
        echo $message;
        if (isset($GLOBALS['special_message'])) {
            echo PMA_sanitize($GLOBALS['special_message']);
            unset($GLOBALS['special_message']);
        }
        if (!empty($GLOBALS['show_error_header'])) {
            echo '</div>';
        }
        if ($cfg['ShowSQL'] == true && (!empty($GLOBALS['sql_query']) || !empty($GLOBALS['display_query']))) {
            $local_query = !empty($GLOBALS['display_query']) ? $GLOBALS['display_query'] : ($cfg['SQP']['fmtType'] == 'none' && isset($GLOBALS['unparsed_sql']) && $GLOBALS['unparsed_sql'] != '' ? $GLOBALS['unparsed_sql'] : $GLOBALS['sql_query']);
            // Basic url query part
            $url_qpart = '?' . PMA_generate_common_url(isset($GLOBALS['db']) ? $GLOBALS['db'] : '', isset($GLOBALS['table']) ? $GLOBALS['table'] : '');
            // Html format the query to be displayed
            // The nl2br function isn't used because its result isn't a valid
            // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
            // If we want to show some sql code it is easiest to create it here
            /* SQL-Parser-Analyzer */
            if (!empty($GLOBALS['show_as_php'])) {
                $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
            }
            if (isset($new_line)) {
                /* SQL-Parser-Analyzer */
                $query_base = PMA_sqlAddslashes(htmlspecialchars($local_query), false, false, true);
                /* SQL-Parser-Analyzer */
                $query_base = preg_replace("@((\r\n)|(\r)|(\n))+@", $new_line, $query_base);
            } else {
                $query_base = $local_query;
            }
            // Parse SQL if needed
            if (isset($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
                $parsed_sql = $GLOBALS['parsed_sql'];
            } else {
                // when the query is large (for example an INSERT of binary
                // data), the parser chokes; so avoid parsing the query
                if (strlen($query_base) < 1000) {
                    $parsed_sql = PMA_SQP_parse($query_base);
                }
            }
            // Analyze it
            if (isset($parsed_sql)) {
                $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
            }
            // Here we append the LIMIT added for navigation, to
            // enable its display. Adding it higher in the code
            // to $local_query would create a problem when
            // using the Refresh or Edit links.
            // Only append it on SELECTs.
            // FIXME: what would be the best to do when someone
            // hits Refresh: use the current LIMITs ?
            if (isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_limit_to_append'])) {
                $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
                // Need to reparse query
                $parsed_sql = PMA_SQP_parse($query_base);
            }
            if (!empty($GLOBALS['show_as_php'])) {
                $query_base = '$sql  = \'' . $query_base;
            } elseif (!empty($GLOBALS['validatequery'])) {
                $query_base = PMA_validateSQL($query_base);
            } else {
                if (isset($parsed_sql)) {
                    $query_base = PMA_formatSql($parsed_sql, $query_base);
                }
            }
            // Prepares links that may be displayed to edit/explain the query
            // (don't go to default pages, we must go to the page
            // where the query box is available)
            // (also, I don't see why we should check the goto variable)
            //if (!isset($GLOBALS['goto'])) {
            //$edit_target = (isset($GLOBALS['table'])) ? $cfg['DefaultTabTable'] : $cfg['DefaultTabDatabase'];
            $edit_target = isset($GLOBALS['db']) ? isset($GLOBALS['table']) ? 'tbl_properties.php' : 'db_details.php' : 'server_sql.php';
            //} elseif ($GLOBALS['goto'] != 'main.php') {
            //    $edit_target = $GLOBALS['goto'];
            //} else {
            //    $edit_target = '';
            //}
            if (isset($cfg['SQLQuery']['Edit']) && $cfg['SQLQuery']['Edit'] == true && !empty($edit_target)) {
                if ($cfg['EditInWindow'] == true) {
                    $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($local_query, false) . '\'); return false;';
                } else {
                    $onclick = '';
                }
                $edit_link = $edit_target . $url_qpart . '&amp;sql_query=' . urlencode($local_query) . '&amp;show_query=1#querybox';
                $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
            } else {
                $edit_link = '';
            }
            // Want to have the query explained (Mike Beck 2002-05-22)
            // but only explain a SELECT (that has not been explained)
            /* SQL-Parser-Analyzer */
            if (isset($cfg['SQLQuery']['Explain']) && $cfg['SQLQuery']['Explain'] == true) {
                // Detect if we are validating as well
                // To preserve the validate uRL data
                if (!empty($GLOBALS['validatequery'])) {
                    $explain_link_validate = '&amp;validatequery=1';
                } else {
                    $explain_link_validate = '';
                }
                $explain_link = 'import.php' . $url_qpart . $explain_link_validate . '&amp;sql_query=';
                if (preg_match('@^SELECT[[:space:]]+@i', $local_query)) {
                    $explain_link .= urlencode('EXPLAIN ' . $local_query);
                    $message = $GLOBALS['strExplain'];
                } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $local_query)) {
                    $explain_link .= urlencode(substr($local_query, 8));
                    $message = $GLOBALS['strNoExplain'];
                } else {
                    $explain_link = '';
                }
                if (!empty($explain_link)) {
                    $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
                }
            } else {
                $explain_link = '';
            }
            //show explain
            // Also we would like to get the SQL formed in some nice
            // php-code (Mike Beck 2002-05-22)
            if (isset($cfg['SQLQuery']['ShowAsPHP']) && $cfg['SQLQuery']['ShowAsPHP'] == true) {
                $php_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query) . '&amp;show_as_php=';
                if (!empty($GLOBALS['show_as_php'])) {
                    $php_link .= '0';
                    $message = $GLOBALS['strNoPhp'];
                } else {
                    $php_link .= '1';
                    $message = $GLOBALS['strPhp'];
                }
                $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
                if (isset($GLOBALS['show_as_php']) && $GLOBALS['show_as_php'] == '1') {
                    $runquery_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query);
                    $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
                }
            } else {
                $php_link = '';
            }
            //show as php
            // Refresh query
            if (isset($cfg['SQLQuery']['Refresh']) && $cfg['SQLQuery']['Refresh'] && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $local_query)) {
                $refresh_link = 'import.php' . $url_qpart . '&amp;show_query=1' . (isset($_GET['pos']) ? '&amp;pos=' . $_GET['pos'] : '') . '&amp;sql_query=' . urlencode($local_query);
                $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
            } else {
                $refresh_link = '';
            }
            //show as php
            if (isset($cfg['SQLValidator']['use']) && $cfg['SQLValidator']['use'] == true && isset($cfg['SQLQuery']['Validate']) && $cfg['SQLQuery']['Validate'] == true) {
                $validate_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query) . '&amp;validatequery=';
                if (!empty($GLOBALS['validatequery'])) {
                    $validate_link .= '0';
                    $validate_message = $GLOBALS['strNoValidateSQL'];
                } else {
                    $validate_link .= '1';
                    $validate_message = $GLOBALS['strValidateSQL'];
                }
                $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
            } else {
                $validate_link = '';
            }
            //validator
            unset($local_query);
            // Displays the message
            echo '<fieldset class="">' . "\n";
            echo '    <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
            echo '    ' . $query_base;
            //Clean up the end of the PHP
            if (!empty($GLOBALS['show_as_php'])) {
                echo '\';';
            }
            echo '</fieldset>' . "\n";
            if (!empty($edit_target)) {
                echo '<fieldset class="tblFooters">';
                echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
                echo '</fieldset>';
            }
        }
        ?>
</div><br />
        <?php 
    }
/**
 * Returns a modified sql query with only the label column
 * and spatial column(wrapped with 'ASTEXT()' function).
 *
 * @param string $sql_query             original sql query
 * @param array  $visualizationSettings settings for the visualization
 *
 * @return the modified sql query.
 */
function PMA_GIS_modifyQuery($sql_query, $visualizationSettings)
{
    $modified_query = 'SELECT ';
    $analyzed_query = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
    // If select clause is not *
    if (trim($analyzed_query[0]['select_expr_clause']) != '*') {
        // If label column is chosen add it to the query
        if (isset($visualizationSettings['labelColumn']) && $visualizationSettings['labelColumn'] != '') {
            // Check to see whether an alias has been used on the label column
            $is_label_alias = false;
            foreach ($analyzed_query[0]['select_expr'] as $select) {
                if ($select['alias'] == $visualizationSettings['labelColumn']) {
                    $modified_query .= sanitize($select) . ' AS `' . $select['alias'] . '`, ';
                    $is_label_alias = true;
                    break;
                }
            }
            // If no alias have been used on the label column
            if (!$is_label_alias) {
                foreach ($analyzed_query[0]['select_expr'] as $select) {
                    if ($select['column'] == $visualizationSettings['labelColumn']) {
                        $modified_query .= sanitize($select) . ', ';
                    }
                }
            }
        }
        // Check to see whether an alias has been used on the spatial column
        $is_spatial_alias = false;
        foreach ($analyzed_query[0]['select_expr'] as $select) {
            if ($select['alias'] == $visualizationSettings['spatialColumn']) {
                $sanitized = sanitize($select);
                $modified_query .= 'ASTEXT(' . $sanitized . ') AS `' . $select['alias'] . '`, ';
                // Get the SRID
                $modified_query .= 'SRID(' . $sanitized . ') AS `srid` ';
                $is_spatial_alias = true;
                break;
            }
        }
        // If no alias have been used on the spatial column
        if (!$is_spatial_alias) {
            foreach ($analyzed_query[0]['select_expr'] as $select) {
                if ($select['column'] == $visualizationSettings['spatialColumn']) {
                    $sanitized = sanitize($select);
                    $modified_query .= 'ASTEXT(' . $sanitized . ') AS `' . $select['column'] . '`, ';
                    // Get the SRID
                    $modified_query .= 'SRID(' . $sanitized . ') AS `srid` ';
                }
            }
        }
        // If select cluase is *
    } else {
        // If label column is chosen add it to the query
        if (isset($visualizationSettings['labelColumn']) && $visualizationSettings['labelColumn'] != '') {
            $modified_query .= '`' . $visualizationSettings['labelColumn'] . '`, ';
        }
        // Wrap the spatial column with 'ASTEXT()' function and add it
        $modified_query .= 'ASTEXT(`' . $visualizationSettings['spatialColumn'] . '`) AS `' . $visualizationSettings['spatialColumn'] . '`, ';
        // Get the SRID
        $modified_query .= 'SRID(`' . $visualizationSettings['spatialColumn'] . '`) AS `srid` ';
    }
    // Append the rest of the query
    $from_pos = stripos($sql_query, 'FROM');
    $modified_query .= substr($sql_query, $from_pos);
    return $modified_query;
}
Beispiel #11
0
/**
 * Function to append the limit clause
 *
 * @param String $full_sql_query full sql query
 * @param array  $analyzed_sql   analyzed sql query
 * @param String $display_query  display query
 *
 * @return array
 */
function PMA_appendLimitClause($full_sql_query, $analyzed_sql, $display_query)
{
    $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmpval']['pos'] . ', ' . $_SESSION['tmpval']['max_rows'] . " ";
    $full_sql_query = PMA_getSqlWithLimitClause($full_sql_query, $analyzed_sql, $sql_limit_to_append);
    /**
     * @todo pretty printing of this modified query
     */
    if ($display_query) {
        // if the analysis of the original query revealed that we found
        // a section_after_limit, we now have to analyze $display_query
        // to display it correctly
        if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
            $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
            $display_query = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
        }
    }
    return array($sql_limit_to_append, $full_sql_query, isset($analyzed_display_query) ? $analyzed_display_query : null, isset($display_query) ? $display_query : null);
}
Beispiel #12
0
/**
 * Set a single comment to a certain value.
 *
 * @param   string   the name of the db
 * @param   string   the name of the table (may be empty in case of a db comment)
 * @param   string   the name of the column
 * @param   string   the value of the column
 * @param   string   (optional) if a column is renamed, this is the name of the former key which will get deleted
 * @param   string   whether we set pmadb comments, native comments or both
 *
 * @return  boolean  true, if comment-query was made.
 *
 * @global  array    the list of relations settings
 *
 * @access  public
 */
function PMA_setComment($db, $table, $col, $comment, $removekey = '', $mode = 'auto')
{
    global $cfgRelation;
    if ($mode == 'auto') {
        if (PMA_MYSQL_INT_VERSION >= 40100) {
            $mode = 'native';
        } else {
            $mode = 'pmadb';
        }
    }
    // native mode is only for column comments so we need a table name
    if ($mode == 'native' && !empty($table)) {
        $fields = PMA_DBI_get_fields($db, $table);
        // Get more complete field information
        // For now, this is done just for MySQL 4.1.2+ new TIMESTAMP options
        // but later, if the analyser returns more information, it
        // could be executed for any MySQL version and replace
        // the info given by SHOW FULL FIELDS FROM.
        // TODO: put this code into a require()
        // or maybe make it part of PMA_DBI_get_fields();
        if (PMA_MYSQL_INT_VERSION >= 40102) {
            $show_create_table_query = 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table);
            $show_create_table_res = PMA_DBI_query($show_create_table_query);
            list(, $show_create_table) = PMA_DBI_fetch_row($show_create_table_res);
            PMA_DBI_free_result($show_create_table_res);
            unset($show_create_table_res, $show_create_table_query);
            $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
        }
        // TODO: get directly the information of $col
        foreach ($fields as $key => $field) {
            $tmp_col = $field['Field'];
            $types[$tmp_col] = $field['Type'];
            $collations[$tmp_col] = $field['Collation'];
            $nulls[$tmp_col] = $field['Null'];
            $defaults[$tmp_col] = $field['Default'];
            $extras[$tmp_col] = $field['Extra'];
            if (PMA_MYSQL_INT_VERSION >= 40102 && isset($analyzed_sql[0]['create_table_fields'][$tmp_col]['on_update_current_timestamp'])) {
                $extras[$tmp_col] = 'ON UPDATE CURRENT_TIMESTAMP';
            }
            if (PMA_MYSQL_INT_VERSION >= 40102 && isset($analyzed_sql[0]['create_table_fields'][$tmp_col]['default_current_timestamp'])) {
                $default_current_timestamps[$tmp_col] = TRUE;
            } else {
                $default_current_timestamps[$tmp_col] = FALSE;
            }
            if ($tmp_col == $col) {
                break;
            }
        }
        if ($nulls[$col] == 'YES') {
            $nulls[$col] = '';
        } else {
            $nulls[$col] = 'NOT NULL';
        }
        $query = 'ALTER TABLE ' . PMA_backquote($table) . ' CHANGE ' . PMA_generateAlterTable($col, $col, $types[$col], $collations[$col], $nulls[$col], $defaults[$col], $default_current_timestamps[$col], $extras[$col], $comment);
        PMA_DBI_try_query($query, NULL, PMA_DBI_QUERY_STORE);
        return TRUE;
    }
    // $mode == 'pmadb' section:
    $cols = array('db_name' => 'db_name    ', 'table_name' => 'table_name ', 'column_name' => 'column_name');
    if ($removekey != '' and $removekey != $col) {
        $remove_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['column_info']) . ' WHERE ' . $cols['db_name'] . ' = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND   ' . $cols['table_name'] . ' = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND   ' . $cols['column_name'] . ' = \'' . PMA_sqlAddslashes($removekey) . '\'';
        PMA_query_as_cu($remove_query);
        unset($remove_query);
    }
    $test_qry = 'SELECT ' . PMA_backquote('comment') . ', mimetype, transformation, transformation_options FROM ' . PMA_backquote($cfgRelation['column_info']) . ' WHERE ' . $cols['db_name'] . ' = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND   ' . $cols['table_name'] . ' = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND   ' . $cols['column_name'] . ' = \'' . PMA_sqlAddslashes($col) . '\'';
    $test_rs = PMA_query_as_cu($test_qry, TRUE, PMA_DBI_QUERY_STORE);
    if ($test_rs && PMA_DBI_num_rows($test_rs) > 0) {
        $row = PMA_DBI_fetch_assoc($test_rs);
        PMA_DBI_free_result($test_rs);
        if (strlen($comment) > 0 || strlen($row['mimetype']) > 0 || strlen($row['transformation']) > 0 || strlen($row['transformation_options']) > 0) {
            $upd_query = 'UPDATE ' . PMA_backquote($cfgRelation['column_info']) . ' SET ' . PMA_backquote('comment') . ' = \'' . PMA_sqlAddslashes($comment) . '\'' . ' WHERE ' . $cols['db_name'] . ' = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND   ' . $cols['table_name'] . ' = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND   ' . $cols['column_name'] . ' = \'' . PMA_sqlAddSlashes($col) . '\'';
        } else {
            $upd_query = 'DELETE FROM ' . PMA_backquote($cfgRelation['column_info']) . ' WHERE ' . $cols['db_name'] . ' = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND   ' . $cols['table_name'] . ' = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND   ' . $cols['column_name'] . ' = \'' . PMA_sqlAddslashes($col) . '\'';
        }
    } else {
        if (strlen($comment) > 0) {
            $upd_query = 'INSERT INTO ' . PMA_backquote($cfgRelation['column_info']) . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ') ' . ' VALUES(' . '\'' . PMA_sqlAddslashes($db) . '\',' . '\'' . PMA_sqlAddslashes($table) . '\',' . '\'' . PMA_sqlAddslashes($col) . '\',' . '\'' . PMA_sqlAddslashes($comment) . '\')';
        }
    }
    if (isset($upd_query)) {
        $upd_rs = PMA_query_as_cu($upd_query);
        unset($upd_query);
        return true;
    } else {
        return false;
    }
}
 /**
  * Tests simulated UPDATE/DELETE query.
  *
  * @param string $sql_query       SQL query
  * @param string $simulated_query Simulated query
  *
  * @return void
  */
 function simulatedQueryTest($sql_query, $simulated_query)
 {
     $parsed_sql = PMA_SQP_parse($sql_query);
     $analyzed_sql = PMA_SQP_analyze($parsed_sql);
     $analyzed_sql_results = array('parsed_sql' => $parsed_sql, 'analyzed_sql' => $analyzed_sql);
     $simulated_data = PMA_getMatchedRows($analyzed_sql_results);
     // URL to matched rows.
     $_url_params = array('db' => 'PMA', 'sql_query' => $simulated_query);
     $matched_rows_url = 'sql.php' . PMA_URL_getCommon($_url_params);
     $this->assertEquals(array('sql_query' => PMA_Util::formatSql($analyzed_sql_results['parsed_sql']['raw']), 'matched_rows' => 2, 'matched_rows_url' => $matched_rows_url), $simulated_data);
 }
 /**
  * Returns the analysis of 'SHOW CREATE TABLE' query for the table.
  * In case of a view, the values are taken from the information_schema.
  *
  * @return array analysis of 'SHOW CREATE TABLE' query for the table
  */
 public function analyzeStructure()
 {
     if (empty($this->_db_name) || empty($this->_name)) {
         return false;
     }
     $analyzed_sql = array();
     if ($this->isView()) {
         // For a view, 'SHOW CREATE TABLE' returns the definition,
         // but the structure of the view. So, we try to mock
         // the result of analyzing 'SHOW CREATE TABLE' query.
         $analyzed_sql[0] = array();
         $analyzed_sql[0]['create_table_fields'] = array();
         $results = $this->_dbi->fetchResult("SELECT COLUMN_NAME, DATA_TYPE\r\n                FROM information_schema.COLUMNS\r\n                WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($this->_db_name) . " AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($this->_name) . "'");
         foreach ($results as $result) {
             $analyzed_sql[0]['create_table_fields'][$result['COLUMN_NAME']] = array('type' => mb_strtoupper($result['DATA_TYPE']));
         }
     } else {
         $show_create_table = $this->_dbi->fetchValue('SHOW CREATE TABLE ' . PMA_Util::backquote($this->_db_name) . '.' . PMA_Util::backquote($this->_name), 0, 1);
         $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
     }
     return $analyzed_sql;
 }
Beispiel #15
0
 /**
  * Dispatches between the versions of 'getTableContent' to use depending
  * on the php version
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @global  boolean  whether to use backquotes to allow the use of special
  *                   characters in database, table and fields names or not
  * @global  integer  the number of records
  * @global  integer  the current record position
  *
  * @access  public
  *
  * @see     PMA_getTableContentFast(), PMA_getTableContentOld()
  *
  * @author  staybyte
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $sql_backquotes;
     global $rows_cnt;
     global $current_row;
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_backquote($table) : '\'' . $table . '\'';
     $head = $crlf . $GLOBALS['comment_marker'] . $crlf . $GLOBALS['comment_marker'] . $GLOBALS['strDumpingData'] . ' ' . $formatted_table_name . $crlf . $GLOBALS['comment_marker'] . $crlf . $crlf;
     if (!PMA_exportOutputHandler($head)) {
         return FALSE;
     }
     $buffer = '';
     // 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_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     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 ';
             }
             $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 (isset($GLOBALS['sql_columns'])) {
                 $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 (isset($GLOBALS['sql_extended']) && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             $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 binary field
                     // Note: with mysqli, under MySQL 4.1.3, we get the flag
                     // "binary" for those field types (I don't know why)
                 } elseif (stristr($field_flags[$j], 'BINARY') && isset($GLOBALS['sql_hex_for_binary']) && $fields_meta[$j]->type != 'datetime' && $fields_meta[$j]->type != 'date' && $fields_meta[$j]->type != 'time' && $fields_meta[$j]->type != 'timestamp') {
                     // 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]);
                     }
                     // 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 ($i > 0) {
                         $insert_line .= ', ';
                     }
                     $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                 }
                 $insert_line .= ' WHERE ' . PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
             } else {
                 // Extended inserts case
                 if (isset($GLOBALS['sql_extended'])) {
                     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;
 }
Beispiel #16
0
/**
 * Gets all Relations to foreign tables for a given table or
 * optionally a given column in a table
 *
 * @param   string   the name of the db to check for
 * @param   string   the name of the table to check for
 * @param   string   the name of the column to check for
 * @param   string   the source for foreign key information
 *
 * @return  array    db,table,column
 *
 * @global  array    the list of relations settings
 * @global  string   the URL of the page to show in case of error
 *
 * @access  public
 *
 * @author  Mike Beck <*****@*****.**> and Marc Delisle
 */
function PMA_getForeigners($db, $table, $column = '', $source = 'both')
{
    global $cfgRelation, $err_url_0;
    if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
        $rel_query = '
             SELECT master_field,
                    foreign_db,
                    foreign_table,
                    foreign_field
               FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
              WHERE master_db =  \'' . PMA_sqlAddslashes($db) . '\'
                AND master_table = \'' . PMA_sqlAddslashes($table) . '\' ';
        if (isset($column) && strlen($column)) {
            $rel_query .= ' AND   master_field = \'' . PMA_sqlAddslashes($column) . '\'';
        }
        $relations = PMA_query_as_cu($rel_query);
        $i = 0;
        while ($relrow = PMA_DBI_fetch_assoc($relations)) {
            $field = $relrow['master_field'];
            $foreign[$field]['foreign_db'] = $relrow['foreign_db'];
            $foreign[$field]['foreign_table'] = $relrow['foreign_table'];
            $foreign[$field]['foreign_field'] = $relrow['foreign_field'];
            $i++;
        }
        // end while
        PMA_DBI_free_result($relations);
        unset($relations);
    }
    if (($source == 'both' || $source == 'innodb') && isset($table) && strlen($table)) {
        $show_create_table_query = 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table);
        $show_create_table_res = PMA_DBI_query($show_create_table_query);
        list(, $show_create_table) = PMA_DBI_fetch_row($show_create_table_res);
        PMA_DBI_free_result($show_create_table_res);
        unset($show_create_table_res, $show_create_table_query);
        $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
        foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
            // the analyzer may return more than one column name in the
            // index list or the ref_index_list
            foreach ($one_key['index_list'] as $i => $field) {
                // If a foreign key is defined in the 'internal' source (pmadb)
                // and in 'innodb', we won't get it twice if $source='both'
                // because we use $field as key
                // The parser looks for a CONSTRAINT clause just before
                // the FOREIGN KEY clause. It finds it (as output from
                // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
                // versions like 3.23.58.
                // In those cases, the FOREIGN KEY parsing will put numbers
                // like -1, 0, 1... instead of the constraint number.
                if (isset($one_key['constraint'])) {
                    $foreign[$field]['constraint'] = $one_key['constraint'];
                }
                if (isset($one_key['ref_db_name'])) {
                    $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
                } else {
                    $foreign[$field]['foreign_db'] = $db;
                }
                $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
                $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
                if (isset($one_key['on_delete'])) {
                    $foreign[$field]['on_delete'] = $one_key['on_delete'];
                }
                if (isset($one_key['on_update'])) {
                    $foreign[$field]['on_update'] = $one_key['on_update'];
                }
            }
        }
    }
    /**
     * Emulating relations for some information_schema tables
     */
    if (PMA_MYSQL_INT_VERSION >= 50002 && $db == 'information_schema' && ($source == 'internal' || $source == 'both')) {
        require_once './libraries/information_schema_relations.lib.php';
        if (!isset($foreign)) {
            $foreign = array();
        }
        if (isset($GLOBALS['information_schema_relations'][$table])) {
            foreach ($GLOBALS['information_schema_relations'][$table] as $field => $relations) {
                if ((!isset($column) || !strlen($column) || $column == $field) && (!isset($foreign[$field]) || !strlen($foreign[$field]))) {
                    $foreign[$field] = $relations;
                }
            }
        }
    }
    if (!empty($foreign) && is_array($foreign)) {
        return $foreign;
    } else {
        return FALSE;
    }
}
Beispiel #17
0
/**
 * Generate table html when SQL statement have multiple queries
 * which return displayable results
 *
 * @param PMA_DisplayResults $displayResultsObject object
 * @param string             $db                   database name
 * @param array              $sql_data             information about SQL statement
 * @param string             $goto                 URL to go back in case of errors
 * @param string             $pmaThemeImage        path for theme images directory
 * @param string             $text_dir             text direction
 * @param string             $printview            whether printview is enabled
 * @param string             $url_query            URL query
 * @param array              $disp_mode            the display mode
 * @param string             $sql_limit_to_append  limit clause
 * @param bool               $editable             whether result set is editable
 *
 * @return string   $table_html   html content
 */
function getTableHtmlForMultipleQueries($displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage, $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append, $editable)
{
    $table_html = '';
    $tables_array = PMA_DBI_get_tables($db);
    $databases_array = PMA_DBI_get_databases_full();
    $multi_sql = implode(";", $sql_data['valid_sql']);
    $querytime_before = array_sum(explode(' ', microtime()));
    // Assignment for variable is not needed since the results are
    // looiping using the connection
    @PMA_DBI_try_multi_query($multi_sql);
    $querytime_after = array_sum(explode(' ', microtime()));
    $querytime = $querytime_after - $querytime_before;
    $sql_no = 0;
    do {
        $analyzed_sql = array();
        $is_affected = false;
        $result = PMA_DBI_store_result();
        $fields_meta = $result !== false ? PMA_DBI_get_fields_meta($result) : array();
        $fields_cnt = count($fields_meta);
        // Initialize needed params related to each query in multiquery statement
        if (isset($sql_data['valid_sql'][$sql_no])) {
            // 'Use' query can change the database
            if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
                $db = PMA_getNewDatabase($sql_data['valid_sql'][$sql_no], $databases_array);
            }
            $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
            $table = PMA_getTableNameBySQL($sql_data['valid_sql'][$sql_no], $tables_array);
            $analyzed_sql = PMA_SQP_analyze($parsed_sql);
            $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
            $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
            $showtable = PMA_Table::sGetStatusInfo($db, $table, null, true);
            $url_query = PMA_generate_common_url($db, $table);
            list($is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain, $is_delete, $is_affected, $is_insert, $is_replace, $is_show, $is_maint) = PMA_getDisplayPropertyParams($sql_data['valid_sql'][$sql_no], $is_select);
            // Handle remembered sorting order, only for single table query
            if ($GLOBALS['cfg']['RememberSorting'] && !($is_count || $is_export || $is_func || $is_analyse) && isset($analyzed_sql[0]['select_expr']) && count($analyzed_sql[0]['select_expr']) == 0 && isset($analyzed_sql[0]['queryflags']['select_from']) && count($analyzed_sql[0]['table_ref']) == 1) {
                PMA_handleSortOrder($db, $table, $analyzed_sql, $sql_data['valid_sql'][$sql_no]);
            }
            // Do append a "LIMIT" clause?
            if ($_SESSION['tmp_user_values']['max_rows'] != 'all' && !($is_count || $is_export || $is_func || $is_analyse) && isset($analyzed_sql[0]['queryflags']['select_from']) && !isset($analyzed_sql[0]['queryflags']['offset']) && empty($analyzed_sql[0]['limit_clause'])) {
                $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
                $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause($sql_data['valid_sql'][$sql_no], $analyzed_sql, $sql_limit_to_append);
            }
            // Set the needed properties related to executing sql query
            $displayResultsObject->__set('db', $db);
            $displayResultsObject->__set('table', $table);
            $displayResultsObject->__set('goto', $goto);
        }
        if (!$is_affected) {
            $num_rows = $result ? @PMA_DBI_num_rows($result) : 0;
        } elseif (!isset($num_rows)) {
            $num_rows = @PMA_DBI_affected_rows();
        }
        if (isset($sql_data['valid_sql'][$sql_no])) {
            $displayResultsObject->__set('sql_query', $sql_data['valid_sql'][$sql_no]);
            $displayResultsObject->setProperties($unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func, $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage, $text_dir, $is_maint, $is_explain, $is_show, $showtable, $printview, $url_query, $editable);
        }
        if ($num_rows == 0) {
            continue;
        }
        // With multiple results, operations are limied
        $disp_mode = 'nnnn000000';
        $is_limited_display = true;
        // Collect the tables
        $table_html .= $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql, $is_limited_display);
        // Free the result to save the memory
        PMA_DBI_free_result($result);
        $sql_no++;
    } while (PMA_DBI_more_results() && PMA_DBI_next_result());
    return $table_html;
}
Beispiel #18
0
        . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";

    $full_sql_query  = $analyzed_sql[0]['section_before_limit'] . "\n"
        . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
    /**
     * @todo pretty printing of this modified query
     */
    if (isset($display_query)) {
        // if the analysis of the original query revealed that we found
        // a section_after_limit, we now have to analyze $display_query
        // to display it correctly

        if (! empty($analyzed_sql[0]['section_after_limit'])
            && trim($analyzed_sql[0]['section_after_limit']) != ';'
        ) {
            $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
            $display_query  = $analyzed_display_query[0]['section_before_limit']
                . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
        }
    }

}

if (strlen($db)) {
    PMA_DBI_select_db($db);
}

//  E x e c u t e    t h e    q u e r y

// Only if we didn't ask to see the php code (mikebeck)
if (isset($GLOBALS['show_as_php']) || ! empty($GLOBALS['validatequery'])) {
Beispiel #19
0
 /**
  * Dispatches between the versions of 'getTableContent' to use depending
  * on the php version
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @global  boolean  whether to use backquotes to allow the use of special
  *                   characters in database, table and fields names or not
  * @global  integer  the number of records
  * @global  integer  the current record position
  *
  * @access  public
  *
  * @see     PMA_getTableContentFast(), PMA_getTableContentOld()
  *
  * @author  staybyte
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $sql_backquotes;
     global $rows_cnt;
     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 = $crlf . PMA_exportComment() . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name) . PMA_exportComment($GLOBALS['strData'] . ': ' . $GLOBALS['strNone']) . PMA_exportComment() . $crlf;
         if (!PMA_exportOutputHandler($head)) {
             return FALSE;
         }
         return true;
     }
     // it's not a VIEW
     $head = $crlf . PMA_exportComment() . PMA_exportComment($GLOBALS['strDumpingData'] . ' ' . $formatted_table_name) . PMA_exportComment() . $crlf;
     if (!PMA_exportOutputHandler($head)) {
         return FALSE;
     }
     $buffer = '';
     // 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_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     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 (isset($GLOBALS['sql_columns'])) {
                 $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 (isset($GLOBALS['sql_extended']) && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             $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];
                 }
                 $insert_line .= ' WHERE ' . PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
             } else {
                 // Extended inserts case
                 if (isset($GLOBALS['sql_extended'])) {
                     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;
 }
Beispiel #20
0
 /**
  * Copies or renames table
  *
  * @param string $source_db    source database
  * @param string $source_table source table
  * @param string $target_db    target database
  * @param string $target_table target table
  * @param string $what         what to be moved or copied (data, dataonly)
  * @param bool   $move         whether to move
  * @param string $mode         mode
  *
  * @return bool true if success, false otherwise
  */
 public static function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
 {
     global $err_url;
     /* Try moving table directly */
     if ($move && $what == 'data') {
         $tbl = new PMA_Table($source_table, $source_db);
         $result = $tbl->rename($target_table, $target_db);
         if ($result) {
             $GLOBALS['message'] = $tbl->getLastMessage();
             return true;
         }
     }
     // set export settings we need
     $GLOBALS['sql_backquotes'] = 1;
     $GLOBALS['asfile'] = 1;
     // Ensure the target is valid
     if (!$GLOBALS['pma']->databases->exists($source_db, $target_db)) {
         if (!$GLOBALS['pma']->databases->exists($source_db)) {
             $GLOBALS['message'] = PMA_Message::rawError(sprintf(__('Source database `%s` was not found!'), htmlspecialchars($source_db)));
         }
         if (!$GLOBALS['pma']->databases->exists($target_db)) {
             $GLOBALS['message'] = PMA_Message::rawError(sprintf(__('Target database `%s` was not found!'), htmlspecialchars($target_db)));
         }
         return false;
     }
     $source = PMA_Util::backquote($source_db) . '.' . PMA_Util::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_Util::backquote($target_db) . '.' . PMA_Util::backquote($target_table);
     // do not create the table if dataonly
     if ($what != 'dataonly') {
         include_once "libraries/plugin_interface.lib.php";
         // get Export SQL instance
         $export_sql_plugin = PMA_getPlugin("export", "sql", 'libraries/plugins/export/', array('export_type' => 'table', 'single_table' => isset($single_table)));
         $no_constraints_comments = true;
         $GLOBALS['sql_constraints_query'] = '';
         $sql_structure = $export_sql_plugin->getTableDef($source_db, $source_table, "\n", $err_url, false, false);
         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_Util::backquote($target_db);
             while (true) {
                 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
                     break;
                 }
                 $i++;
             }
         }
         unset($analyzed_sql);
         if (PMA_DRIZZLE) {
             $table_delimiter = 'quote_backtick';
         } else {
             $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
             // ANSI_QUOTES might be a subset of sql_mode, for example
             // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
             if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
                 $table_delimiter = 'quote_double';
             } else {
                 $table_delimiter = 'quote_backtick';
             }
             unset($server_sql_mode);
         }
         /* Find table name in query and replace it */
         while ($parsed_sql[$i]['type'] != $table_delimiter) {
             $i++;
         }
         /* no need to 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_Util::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 - 1]['type'] != 'punct_qualifier') {
                     $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($_REQUEST['drop_if_exists']) && $_REQUEST['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_Util::backquote($target_db) . '.' . PMA_Util::backquote($target_table);
             PMA_DBI_query($drop_query);
             $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
             // 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 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_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
         PMA_DBI_query($sql_set_mode);
         $GLOBALS['sql_query'] .= "\n\n" . $sql_set_mode . ';';
         $sql_insert_data = 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
         PMA_DBI_query($sql_insert_data);
         $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
     }
     $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);
         // Renable table in configuration storage
         PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table);
         $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
         // end if ($move)
     } else {
         // we are copying
         // 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, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
                                         FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['column_info']) . '
                                         WHERE
                                             db_name = \'' . PMA_Util::sqlAddSlashes($source_db) . '\' AND
                                             table_name = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
                 $comments_copy_rs = PMA_queryAsControlUser($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_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['column_info']) . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') ' . ' VALUES(' . '\'' . PMA_Util::sqlAddSlashes($target_db) . '\',' . '\'' . PMA_Util::sqlAddSlashes($target_table) . '\',' . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['column_name']) . '\'' . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_Util::sqlAddSlashes($comments_copy_row['comment']) . '\',' . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['mimetype']) . '\',' . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['transformation']) . '\',' . '\'' . PMA_Util::sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '') . ')';
                     PMA_queryAsControlUser($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 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
                );
                             }
             */
         }
     }
     return true;
 }
Beispiel #21
0
/**
 * displays the message and the query
 * usually the message is the result of the query executed
 *
 * @param   string  $message    the message to display
 * @param   string  $sql_query  the query to display
 * @global  array   the configuration array
 * @uses    $cfg
 * @access  public
 */
function PMA_showMessage($message, $sql_query = null)
{
    global $cfg;
    $query_too_big = false;
    if (null === $sql_query) {
        if (!empty($GLOBALS['display_query'])) {
            $sql_query = $GLOBALS['display_query'];
        } elseif ($cfg['SQP']['fmtType'] == 'none' && !empty($GLOBALS['unparsed_sql'])) {
            $sql_query = $GLOBALS['unparsed_sql'];
        } elseif (!empty($GLOBALS['sql_query'])) {
            $sql_query = $GLOBALS['sql_query'];
        } else {
            $sql_query = '';
        }
    }
    // Corrects the tooltip text via JS if required
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
        $result = PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
        if ($result) {
            $tbl_status = PMA_DBI_fetch_assoc($result);
            $tooltip = empty($tbl_status['Comment']) ? '' : $tbl_status['Comment'] . ' ';
            $tooltip .= '(' . PMA_formatNumber($tbl_status['Rows'], 0) . ' ' . $GLOBALS['strRows'] . ')';
            PMA_DBI_free_result($result);
            $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
            echo "\n";
            echo '<script type="text/javascript">' . "\n";
            echo '//<![CDATA[' . "\n";
            echo "window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
            echo '//]]>' . "\n";
            echo '</script>' . "\n";
        }
        // end if
    }
    // end if ... elseif
    // Checks if the table needs to be repaired after a TRUNCATE query.
    // @todo what about $GLOBALS['display_query']???
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (strlen($GLOBALS['table']) && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
        if (!isset($tbl_status)) {
            $result = @PMA_DBI_try_query('SHOW TABLE STATUS FROM ' . PMA_backquote($GLOBALS['db']) . ' LIKE \'' . PMA_sqlAddslashes($GLOBALS['table'], true) . '\'');
            if ($result) {
                $tbl_status = PMA_DBI_fetch_assoc($result);
                PMA_DBI_free_result($result);
            }
        }
        if (isset($tbl_status) && (int) $tbl_status['Index_length'] > 1024) {
            PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
        }
    }
    unset($tbl_status);
    echo '<br />' . "\n";
    echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
    if (!empty($GLOBALS['show_error_header'])) {
        echo '<div class="error">' . "\n";
        echo '<h1>' . $GLOBALS['strError'] . '</h1>' . "\n";
    }
    echo '<div class="notice">';
    echo PMA_sanitize($message);
    if (isset($GLOBALS['special_message'])) {
        echo PMA_sanitize($GLOBALS['special_message']);
        unset($GLOBALS['special_message']);
    }
    echo '</div>';
    if (!empty($GLOBALS['show_error_header'])) {
        echo '</div>';
    }
    if ($cfg['ShowSQL'] == true && !empty($sql_query)) {
        // Basic url query part
        $url_qpart = '?' . PMA_generate_common_url($GLOBALS['db'], $GLOBALS['table']);
        // Html format the query to be displayed
        // The nl2br function isn't used because its result isn't a valid
        // xhtml1.0 statement before php4.0.5 ("<br>" and not "<br />")
        // If we want to show some sql code it is easiest to create it here
        /* SQL-Parser-Analyzer */
        if (!empty($GLOBALS['show_as_php'])) {
            $new_line = '\'<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;. \' ';
        }
        if (isset($new_line)) {
            /* SQL-Parser-Analyzer */
            $query_base = PMA_sqlAddslashes(htmlspecialchars($sql_query), false, false, true);
            /* SQL-Parser-Analyzer */
            $query_base = preg_replace("@((\r\n)|(\r)|(\n))+@", $new_line, $query_base);
        } else {
            $query_base = $sql_query;
        }
        if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
            $query_too_big = true;
            $query_base = nl2br(htmlspecialchars($sql_query));
            unset($GLOBALS['parsed_sql']);
        }
        // Parse SQL if needed
        // (here, use "! empty" because when deleting a bookmark,
        // $GLOBALS['parsed_sql'] is set but empty
        if (!empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
            $parsed_sql = $GLOBALS['parsed_sql'];
        } else {
            // when the query is large (for example an INSERT of binary
            // data), the parser chokes; so avoid parsing the query
            if (!$query_too_big) {
                $parsed_sql = PMA_SQP_parse($query_base);
            }
        }
        // Analyze it
        if (isset($parsed_sql)) {
            $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
        }
        // Here we append the LIMIT added for navigation, to
        // enable its display. Adding it higher in the code
        // to $sql_query would create a problem when
        // using the Refresh or Edit links.
        // Only append it on SELECTs.
        /**
         * @todo what would be the best to do when someone hits Refresh:
         * use the current LIMITs ?
         */
        if (isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_limit_to_append'])) {
            $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
            // Need to reparse query
            $parsed_sql = PMA_SQP_parse($query_base);
        }
        if (!empty($GLOBALS['show_as_php'])) {
            $query_base = '$sql  = \'' . $query_base;
        } elseif (!empty($GLOBALS['validatequery'])) {
            $query_base = PMA_validateSQL($query_base);
        } else {
            if (isset($parsed_sql)) {
                $query_base = PMA_formatSql($parsed_sql, $query_base);
            }
        }
        // Prepares links that may be displayed to edit/explain the query
        // (don't go to default pages, we must go to the page
        // where the query box is available)
        $edit_target = strlen($GLOBALS['db']) ? strlen($GLOBALS['table']) ? 'tbl_sql.php' : 'db_sql.php' : 'server_sql.php';
        if (isset($cfg['SQLQuery']['Edit']) && $cfg['SQLQuery']['Edit'] == true && !empty($edit_target) && !$query_too_big) {
            if ($cfg['EditInWindow'] == true) {
                $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
            } else {
                $onclick = '';
            }
            $edit_link = $edit_target . $url_qpart . '&amp;sql_query=' . urlencode($sql_query) . '&amp;show_query=1#querybox';
            $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
        } else {
            $edit_link = '';
        }
        // Want to have the query explained (Mike Beck 2002-05-22)
        // but only explain a SELECT (that has not been explained)
        /* SQL-Parser-Analyzer */
        if (isset($cfg['SQLQuery']['Explain']) && $cfg['SQLQuery']['Explain'] == true && !$query_too_big) {
            // Detect if we are validating as well
            // To preserve the validate uRL data
            if (!empty($GLOBALS['validatequery'])) {
                $explain_link_validate = '&amp;validatequery=1';
            } else {
                $explain_link_validate = '';
            }
            $explain_link = 'import.php' . $url_qpart . $explain_link_validate . '&amp;sql_query=';
            if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
                $explain_link .= urlencode('EXPLAIN ' . $sql_query);
                $message = $GLOBALS['strExplain'];
            } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
                $explain_link .= urlencode(substr($sql_query, 8));
                $message = $GLOBALS['strNoExplain'];
            } else {
                $explain_link = '';
            }
            if (!empty($explain_link)) {
                $explain_link = ' [' . PMA_linkOrButton($explain_link, $message) . ']';
            }
        } else {
            $explain_link = '';
        }
        //show explain
        // Also we would like to get the SQL formed in some nice
        // php-code (Mike Beck 2002-05-22)
        if (isset($cfg['SQLQuery']['ShowAsPHP']) && $cfg['SQLQuery']['ShowAsPHP'] == true && !$query_too_big) {
            $php_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($sql_query) . '&amp;show_as_php=';
            if (!empty($GLOBALS['show_as_php'])) {
                $php_link .= '0';
                $message = $GLOBALS['strNoPhp'];
            } else {
                $php_link .= '1';
                $message = $GLOBALS['strPhp'];
            }
            $php_link = ' [' . PMA_linkOrButton($php_link, $message) . ']';
            if (isset($GLOBALS['show_as_php'])) {
                $runquery_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($sql_query);
                $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
            }
        } else {
            $php_link = '';
        }
        //show as php
        // Refresh query
        if (isset($cfg['SQLQuery']['Refresh']) && $cfg['SQLQuery']['Refresh'] && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
            $refresh_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($sql_query);
            $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
        } else {
            $refresh_link = '';
        }
        //show as php
        if (isset($cfg['SQLValidator']['use']) && $cfg['SQLValidator']['use'] == true && isset($cfg['SQLQuery']['Validate']) && $cfg['SQLQuery']['Validate'] == true) {
            $validate_link = 'import.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($sql_query) . '&amp;validatequery=';
            if (!empty($GLOBALS['validatequery'])) {
                $validate_link .= '0';
                $validate_message = $GLOBALS['strNoValidateSQL'];
            } else {
                $validate_link .= '1';
                $validate_message = $GLOBALS['strValidateSQL'];
            }
            $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
        } else {
            $validate_link = '';
        }
        //validator
        // why this?
        //unset($sql_query);
        // Displays the message
        echo '<fieldset class="">' . "\n";
        echo '    <legend>' . $GLOBALS['strSQLQuery'] . ':</legend>';
        echo '    <div>';
        // when uploading a 700 Kio binary file into a LONGBLOB,
        // I get a white page, strlen($query_base) is 2 x 700 Kio
        // so put a hard limit here (let's say 1000)
        if ($query_too_big) {
            echo '    ' . substr($query_base, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]';
        } else {
            echo '    ' . $query_base;
        }
        //Clean up the end of the PHP
        if (!empty($GLOBALS['show_as_php'])) {
            echo '\';';
        }
        echo '    </div>';
        echo '</fieldset>' . "\n";
        if (!empty($edit_target)) {
            echo '<fieldset class="tblFooters">';
            // avoid displaying a Profiling checkbox that could
            // be checked, which would reexecute an INSERT, for example
            if (!empty($refresh_link)) {
                PMA_profilingCheckbox($sql_query);
            }
            echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
            echo '</fieldset>';
        }
    }
    echo '</div><br />' . "\n";
}
Beispiel #22
0
 /**
  * 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
  */
 public function exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $current_row, $sql_backquotes;
     if (isset($GLOBALS['sql_compatibility'])) {
         $compat = $GLOBALS['sql_compatibility'];
     } else {
         $compat = 'NONE';
     }
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_Util::backquoteCompat($table, $compat) : '\'' . $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 = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment('VIEW ' . ' ' . $formatted_table_name) . $this->_exportComment(__('Data') . ': ' . __('None')) . $this->_exportComment() . $this->_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($this->_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_Util::backquoteCompat($analyzed_sql[0]['select_expr'][$j]['column'], $compat, $sql_backquotes);
             } else {
                 $field_set[$j] = PMA_Util::backquoteCompat($fields_meta[$j]->name, $compat, $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_Util::backquoteCompat($table, $compat, $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';
             }
             //truncate table before insert
             if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sql_command == 'INSERT') {
                 $truncate = 'TRUNCATE TABLE ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ";";
                 $truncatehead = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Truncate table before insert') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf;
                 PMA_exportOutputHandler($truncatehead);
                 PMA_exportOutputHandler($truncate);
             } else {
                 $truncate = '';
             }
             // 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_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' (' . $fields . ') VALUES';
             } else {
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' VALUES';
             }
         }
         //\x08\\x09, not required
         $search = array("", "\n", "\r", "");
         $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 = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf;
                 if (!PMA_exportOutputHandler($head)) {
                     return false;
                 }
             }
             // We need to SET IDENTITY_INSERT ON for MSSQL
             if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row == 0) {
                 if (!PMA_exportOutputHandler('SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' ON ;' . $crlf)) {
                     return false;
                 }
             }
             $current_row++;
             for ($j = 0; $j < $fields_cnt; $j++) {
                 // NULL
                 if (!isset($row[$j]) || is_null($row[$j])) {
                     $values[] = 'NULL';
                 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                     // a number
                     // timestamp is numeric on some MySQL 4.1, BLOBs are
                     // sometimes numeric
                     $values[] = $row[$j];
                 } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob && isset($GLOBALS['sql_hex_for_blob'])) {
                     // 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
                     // 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]);
                     }
                 } elseif ($fields_meta[$j]->type == 'bit') {
                     // detection of 'bit' works only on mysqli extension
                     $values[] = "b'" . PMA_Util::sqlAddSlashes(PMA_Util::printableBitValue($row[$j], $fields_meta[$j]->length)) . "'";
                 } else {
                     // something else -> treat as a string
                     $values[] = '\'' . str_replace($search, $replace, PMA_Util::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_Util::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) . ')';
                         $sql_max_size = $GLOBALS['sql_max_query_size'];
                         if (isset($sql_max_size) && $sql_max_size > 0 && $query_size + strlen($insert_line) > $sql_max_size) {
                             if (!PMA_exportOutputHandler(';' . $crlf)) {
                                 return false;
                             }
                             $query_size = 0;
                             $current_row = 1;
                             $insert_line = $schema_insert . $insert_line;
                         }
                     }
                     $query_size += strlen($insert_line);
                     // Other inserts case
                 } 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;
             }
         }
         // We need to SET IDENTITY_INSERT OFF for MSSQL
         if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row > 0) {
             $outputSucceeded = PMA_exportOutputHandler($crlf . 'SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' OFF;' . $crlf);
             if (!$outputSucceeded) {
                 return false;
             }
         }
     }
     // end if ($result != false)
     PMA_DBI_free_result($result);
     return true;
 }
Beispiel #23
0
 /**
  * Prepare the message and the query
  * usually the message is the result of the query executed
  *
  * @param string  $message   the message to display
  * @param string  $sql_query the query to display
  * @param string  $type      the type (level) of the message
  * @param boolean $is_view   is this a message after a VIEW operation?
  *
  * @return string
  *
  * @access  public
  */
 public static function getMessage($message, $sql_query = null, $type = 'notice', $is_view = false)
 {
     global $cfg;
     $retval = '';
     if (null === $sql_query) {
         if (!empty($GLOBALS['display_query'])) {
             $sql_query = $GLOBALS['display_query'];
         } elseif (!empty($GLOBALS['unparsed_sql'])) {
             $sql_query = $GLOBALS['unparsed_sql'];
         } elseif (!empty($GLOBALS['sql_query'])) {
             $sql_query = $GLOBALS['sql_query'];
         } else {
             $sql_query = '';
         }
     }
     if (isset($GLOBALS['using_bookmark_message'])) {
         $retval .= $GLOBALS['using_bookmark_message']->getDisplay();
         unset($GLOBALS['using_bookmark_message']);
     }
     // In an Ajax request, $GLOBALS['cell_align_left'] may not be defined. Hence,
     // check for it's presence before using it
     $retval .= '<div id="result_query"' . (isset($GLOBALS['cell_align_left']) ? ' style="text-align: ' . $GLOBALS['cell_align_left'] . '"' : '') . '>' . "\n";
     if ($message instanceof PMA_Message) {
         if (isset($GLOBALS['special_message'])) {
             $message->addMessage($GLOBALS['special_message']);
             unset($GLOBALS['special_message']);
         }
         $retval .= $message->getDisplay();
     } else {
         $retval .= '<div class="' . $type . '">';
         $retval .= PMA_sanitize($message);
         if (isset($GLOBALS['special_message'])) {
             $retval .= PMA_sanitize($GLOBALS['special_message']);
             unset($GLOBALS['special_message']);
         }
         $retval .= '</div>';
     }
     if ($cfg['ShowSQL'] == true && !empty($sql_query)) {
         // Html format the query to be displayed
         // If we want to show some sql code it is easiest to create it here
         /* SQL-Parser-Analyzer */
         if (!empty($GLOBALS['show_as_php'])) {
             $new_line = '\\n"<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
             $query_base = htmlspecialchars(addslashes($sql_query));
             $query_base = preg_replace('/((\\015\\012)|(\\015)|(\\012))/', $new_line, $query_base);
         } else {
             $query_base = $sql_query;
         }
         $query_too_big = false;
         if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
             // when the query is large (for example an INSERT of binary
             // data), the parser chokes; so avoid parsing the query
             $query_too_big = true;
             $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
         } elseif (!empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
             // (here, use "! empty" because when deleting a bookmark,
             // $GLOBALS['parsed_sql'] is set but empty
             $parsed_sql = $GLOBALS['parsed_sql'];
         } else {
             // Parse SQL if needed
             $parsed_sql = PMA_SQP_parse($query_base);
         }
         // Analyze it
         if (isset($parsed_sql) && !PMA_SQP_isError()) {
             $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
             // Same as below (append LIMIT), append the remembered ORDER BY
             if ($GLOBALS['cfg']['RememberSorting'] && isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_order_to_append'])) {
                 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_order_to_append'] . $analyzed_display_query[0]['limit_clause'] . ' ' . $analyzed_display_query[0]['section_after_limit'];
                 // Need to reparse query
                 $parsed_sql = PMA_SQP_parse($query_base);
                 // update the $analyzed_display_query
                 $analyzed_display_query[0]['section_before_limit'] .= $GLOBALS['sql_order_to_append'];
                 $analyzed_display_query[0]['order_by_clause'] = $GLOBALS['sorted_col'];
             }
             // Here we append the LIMIT added for navigation, to
             // enable its display. Adding it higher in the code
             // to $sql_query would create a problem when
             // using the Refresh or Edit links.
             // Only append it on SELECTs.
             /**
              * @todo what would be the best to do when someone hits Refresh:
              * use the current LIMITs ?
              */
             if (isset($analyzed_display_query[0]['queryflags']['select_from']) && !empty($GLOBALS['sql_limit_to_append'])) {
                 $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
                 // Need to reparse query
                 $parsed_sql = PMA_SQP_parse($query_base);
             }
         }
         if (!empty($GLOBALS['show_as_php'])) {
             $query_base = '$sql  = "' . $query_base;
         } elseif (isset($query_base)) {
             $query_base = self::formatSql($query_base);
         }
         // Prepares links that may be displayed to edit/explain the query
         // (don't go to default pages, we must go to the page
         // where the query box is available)
         // Basic url query part
         $url_params = array();
         if (!isset($GLOBALS['db'])) {
             $GLOBALS['db'] = '';
         }
         if (strlen($GLOBALS['db'])) {
             $url_params['db'] = $GLOBALS['db'];
             if (strlen($GLOBALS['table'])) {
                 $url_params['table'] = $GLOBALS['table'];
                 $edit_link = 'tbl_sql.php';
             } else {
                 $edit_link = 'db_sql.php';
             }
         } else {
             $edit_link = 'server_sql.php';
         }
         // Want to have the query explained
         // but only explain a SELECT (that has not been explained)
         /* SQL-Parser-Analyzer */
         $explain_link = '';
         $is_select = preg_match('@^SELECT[[:space:]]+@i', $sql_query);
         if (!empty($cfg['SQLQuery']['Explain']) && !$query_too_big) {
             $explain_params = $url_params;
             if ($is_select) {
                 $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
                 $_message = __('Explain SQL');
             } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
                 $explain_params['sql_query'] = substr($sql_query, 8);
                 $_message = __('Skip Explain SQL');
             }
             if (isset($explain_params['sql_query'])) {
                 $explain_link = 'import.php' . PMA_URL_getCommon($explain_params);
                 $explain_link = ' [' . self::linkOrButton($explain_link, $_message) . ']';
             }
         }
         //show explain
         $url_params['sql_query'] = $sql_query;
         $url_params['show_query'] = 1;
         // even if the query is big and was truncated, offer the chance
         // to edit it (unless it's enormous, see linkOrButton() )
         if (!empty($cfg['SQLQuery']['Edit'])) {
             if ($cfg['EditInWindow'] == true) {
                 $onclick = 'PMA_querywindow.focus(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
             } else {
                 $onclick = '';
             }
             $edit_link .= PMA_URL_getCommon($url_params) . '#querybox';
             $edit_link = ' [' . self::linkOrButton($edit_link, __('Edit'), array('onclick' => $onclick, 'class' => 'disableAjax')) . ']';
         } else {
             $edit_link = '';
         }
         // Also we would like to get the SQL formed in some nice
         // php-code
         if (!empty($cfg['SQLQuery']['ShowAsPHP']) && !$query_too_big) {
             $php_params = $url_params;
             if (!empty($GLOBALS['show_as_php'])) {
                 $_message = __('Without PHP Code');
             } else {
                 $php_params['show_as_php'] = 1;
                 $_message = __('Create PHP Code');
             }
             $php_link = 'import.php' . PMA_URL_getCommon($php_params);
             $php_link = ' [' . self::linkOrButton($php_link, $_message) . ']';
             if (isset($GLOBALS['show_as_php'])) {
                 $runquery_link = 'import.php' . PMA_URL_getCommon($url_params);
                 $php_link .= ' [' . self::linkOrButton($runquery_link, __('Submit Query')) . ']';
             }
         } else {
             $php_link = '';
         }
         //show as php
         // Refresh query
         if (!empty($cfg['SQLQuery']['Refresh']) && !isset($GLOBALS['show_as_php']) && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
             $refresh_link = 'import.php' . PMA_URL_getCommon($url_params);
             $refresh_link = ' [' . self::linkOrButton($refresh_link, __('Refresh')) . ']';
         } else {
             $refresh_link = '';
         }
         //refresh
         $retval .= '<div class="sqlOuter">';
         if ($query_too_big) {
             $retval .= $shortened_query_base;
         } else {
             $retval .= $query_base;
         }
         //Clean up the end of the PHP
         if (!empty($GLOBALS['show_as_php'])) {
             $retval .= '";';
         }
         $retval .= '</div>';
         $retval .= '<div class="tools">';
         $retval .= '<form action="sql.php" method="post">';
         $retval .= PMA_URL_getHiddenInputs($GLOBALS['db'], $GLOBALS['table']);
         $retval .= '<input type="hidden" name="sql_query" value="' . htmlspecialchars($sql_query) . '" />';
         // avoid displaying a Profiling checkbox that could
         // be checked, which would reexecute an INSERT, for example
         if (!empty($refresh_link) && self::profilingSupported()) {
             $retval .= '<input type="hidden" name="profiling_form" value="1" />';
             $retval .= self::getCheckbox('profiling', __('Profiling'), isset($_SESSION['profiling']), true);
         }
         $retval .= '</form>';
         /**
          * TODO: Should we have $cfg['SQLQuery']['InlineEdit']?
          */
         if (!empty($cfg['SQLQuery']['Edit']) && !$query_too_big) {
             $inline_edit_link = ' [' . self::linkOrButton('#', _pgettext('Inline edit query', 'Inline'), array('class' => 'inline_edit_sql')) . ']';
         } else {
             $inline_edit_link = '';
         }
         $retval .= $inline_edit_link . $edit_link . $explain_link . $php_link . $refresh_link;
         $retval .= '</div>';
     }
     $retval .= '</div>';
     if ($GLOBALS['is_ajax_request'] === false) {
         $retval .= '<br class="clearfloat" />';
     }
     return $retval;
 }
Beispiel #24
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);
                             }
             */
         }
     }
 }
Beispiel #25
0
/**
 * displays the message and the query
 * usually the message is the result of the query executed
 *
 * @param   string  $message    the message to display
 * @param   string  $sql_query  the query to display
 * @param   string  $type       the type (level) of the message
 * @global  array   the configuration array
 * @uses    $cfg
 * @access  public
 */
function PMA_showMessage($message, $sql_query = null, $type = 'notice')
{
    global $cfg;
    if (null === $sql_query) {
        if (!empty($GLOBALS['display_query'])) {
            $sql_query = $GLOBALS['display_query'];
        } elseif ($cfg['SQP']['fmtType'] == 'none' && !empty($GLOBALS['unparsed_sql'])) {
            $sql_query = $GLOBALS['unparsed_sql'];
        } elseif (!empty($GLOBALS['sql_query'])) {
            $sql_query = $GLOBALS['sql_query'];
        } else {
            $sql_query = '';
        }
    }
    // Corrects the tooltip text via JS if required
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (strlen($GLOBALS['table']) && $cfg['ShowTooltip']) {
        $tooltip = PMA_Table::sGetToolTip($GLOBALS['db'], $GLOBALS['table']);
        $uni_tbl = PMA_jsFormat($GLOBALS['db'] . '.' . $GLOBALS['table'], false);
        echo "\n";
        echo '<script type="text/javascript">' . "\n";
        echo '//<![CDATA[' . "\n";
        echo "if (window.parent.updateTableTitle) window.parent.updateTableTitle('" . $uni_tbl . "', '" . PMA_jsFormat($tooltip, false) . "');" . "\n";
        echo '//]]>' . "\n";
        echo '</script>' . "\n";
    }
    // end if ... elseif
    // Checks if the table needs to be repaired after a TRUNCATE query.
    // @todo what about $GLOBALS['display_query']???
    // @todo this is REALLY the wrong place to do this - very unexpected here
    if (strlen($GLOBALS['table']) && $GLOBALS['sql_query'] == 'TRUNCATE TABLE ' . PMA_backquote($GLOBALS['table'])) {
        if (PMA_Table::sGetStatusInfo($GLOBALS['db'], $GLOBALS['table'], 'Index_length') > 1024) {
            PMA_DBI_try_query('REPAIR TABLE ' . PMA_backquote($GLOBALS['table']));
        }
    }
    unset($tbl_status);
    echo '<div align="' . $GLOBALS['cell_align_left'] . '">' . "\n";
    if ($message instanceof PMA_Message) {
        if (isset($GLOBALS['special_message'])) {
            $message->addMessage($GLOBALS['special_message']);
            unset($GLOBALS['special_message']);
        }
        $message->display();
        $type = $message->getLevel();
    } else {
        echo '<div class="' . $type . '">';
        echo PMA_sanitize($message);
        if (isset($GLOBALS['special_message'])) {
            echo PMA_sanitize($GLOBALS['special_message']);
            unset($GLOBALS['special_message']);
        }
        echo '</div>';
    }
    if ($cfg['ShowSQL'] == true && !empty($sql_query)) {
        // Html format the query to be displayed
        // If we want to show some sql code it is easiest to create it here
        /* SQL-Parser-Analyzer */
        if (!empty($GLOBALS['show_as_php'])) {
            $new_line = '\\n"<br />' . "\n" . '&nbsp;&nbsp;&nbsp;&nbsp;. "';
            $query_base = htmlspecialchars(addslashes($sql_query));
            $query_base = preg_replace('/((\\015\\012)|(\\015)|(\\012))/', $new_line, $query_base);
        } else {
            $query_base = $sql_query;
        }
        $query_too_big = false;
        if (strlen($query_base) > $cfg['MaxCharactersInDisplayedSQL']) {
            // when the query is large (for example an INSERT of binary
            // data), the parser chokes; so avoid parsing the query
            $query_too_big = true;
            $shortened_query_base = nl2br(htmlspecialchars(substr($sql_query, 0, $cfg['MaxCharactersInDisplayedSQL']) . '[...]'));
        } elseif (!empty($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
            // (here, use "! empty" because when deleting a bookmark,
            // $GLOBALS['parsed_sql'] is set but empty
            $parsed_sql = $GLOBALS['parsed_sql'];
        } else {
            // Parse SQL if needed
            $parsed_sql = PMA_SQP_parse($query_base);
        }
        // Analyze it
        if (isset($parsed_sql)) {
            $analyzed_display_query = PMA_SQP_analyze($parsed_sql);
            // Here we append the LIMIT added for navigation, to
            // enable its display. Adding it higher in the code
            // to $sql_query would create a problem when
            // using the Refresh or Edit links.
            // Only append it on SELECTs.
            /**
             * @todo what would be the best to do when someone hits Refresh:
             * use the current LIMITs ?
             */
            if (isset($analyzed_display_query[0]['queryflags']['select_from']) && isset($GLOBALS['sql_limit_to_append'])) {
                $query_base = $analyzed_display_query[0]['section_before_limit'] . "\n" . $GLOBALS['sql_limit_to_append'] . $analyzed_display_query[0]['section_after_limit'];
                // Need to reparse query
                $parsed_sql = PMA_SQP_parse($query_base);
            }
        }
        if (!empty($GLOBALS['show_as_php'])) {
            $query_base = '$sql  = "' . $query_base;
        } elseif (!empty($GLOBALS['validatequery'])) {
            $query_base = PMA_validateSQL($query_base);
        } elseif (isset($parsed_sql)) {
            $query_base = PMA_formatSql($parsed_sql, $query_base);
        }
        // Prepares links that may be displayed to edit/explain the query
        // (don't go to default pages, we must go to the page
        // where the query box is available)
        // Basic url query part
        $url_params = array();
        if (strlen($GLOBALS['db'])) {
            $url_params['db'] = $GLOBALS['db'];
            if (strlen($GLOBALS['table'])) {
                $url_params['table'] = $GLOBALS['table'];
                $edit_link = 'tbl_sql.php';
            } else {
                $edit_link = 'db_sql.php';
            }
        } else {
            $edit_link = 'server_sql.php';
        }
        // Want to have the query explained (Mike Beck 2002-05-22)
        // but only explain a SELECT (that has not been explained)
        /* SQL-Parser-Analyzer */
        $explain_link = '';
        if (!empty($cfg['SQLQuery']['Explain']) && !$query_too_big) {
            $explain_params = $url_params;
            // Detect if we are validating as well
            // To preserve the validate uRL data
            if (!empty($GLOBALS['validatequery'])) {
                $explain_params['validatequery'] = 1;
            }
            if (preg_match('@^SELECT[[:space:]]+@i', $sql_query)) {
                $explain_params['sql_query'] = 'EXPLAIN ' . $sql_query;
                $_message = $GLOBALS['strExplain'];
            } elseif (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $sql_query)) {
                $explain_params['sql_query'] = substr($sql_query, 8);
                $_message = $GLOBALS['strNoExplain'];
            }
            if (isset($explain_params['sql_query'])) {
                $explain_link = 'import.php' . PMA_generate_common_url($explain_params);
                $explain_link = ' [' . PMA_linkOrButton($explain_link, $_message) . ']';
            }
        }
        //show explain
        $url_params['sql_query'] = $sql_query;
        $url_params['show_query'] = 1;
        if (!empty($cfg['SQLQuery']['Edit']) && !$query_too_big) {
            if ($cfg['EditInWindow'] == true) {
                $onclick = 'window.parent.focus_querywindow(\'' . PMA_jsFormat($sql_query, false) . '\'); return false;';
            } else {
                $onclick = '';
            }
            $edit_link .= PMA_generate_common_url($url_params) . '#querybox';
            $edit_link = ' [' . PMA_linkOrButton($edit_link, $GLOBALS['strEdit'], array('onclick' => $onclick)) . ']';
        } else {
            $edit_link = '';
        }
        $url_qpart = PMA_generate_common_url($url_params);
        // Also we would like to get the SQL formed in some nice
        // php-code (Mike Beck 2002-05-22)
        if (!empty($cfg['SQLQuery']['ShowAsPHP']) && !$query_too_big) {
            $php_params = $url_params;
            if (!empty($GLOBALS['show_as_php'])) {
                $_message = $GLOBALS['strNoPhp'];
            } else {
                $php_params['show_as_php'] = 1;
                $_message = $GLOBALS['strPhp'];
            }
            $php_link = 'import.php' . PMA_generate_common_url($php_params);
            $php_link = ' [' . PMA_linkOrButton($php_link, $_message) . ']';
            if (isset($GLOBALS['show_as_php'])) {
                $runquery_link = 'import.php' . PMA_generate_common_url($url_params);
                $php_link .= ' [' . PMA_linkOrButton($runquery_link, $GLOBALS['strRunQuery']) . ']';
            }
        } else {
            $php_link = '';
        }
        //show as php
        // Refresh query
        if (!empty($cfg['SQLQuery']['Refresh']) && preg_match('@^(SELECT|SHOW)[[:space:]]+@i', $sql_query)) {
            $refresh_link = 'import.php' . PMA_generate_common_url($url_params);
            $refresh_link = ' [' . PMA_linkOrButton($refresh_link, $GLOBALS['strRefresh']) . ']';
        } else {
            $refresh_link = '';
        }
        //show as php
        if (!empty($cfg['SQLValidator']['use']) && !empty($cfg['SQLQuery']['Validate'])) {
            $validate_params = $url_params;
            if (!empty($GLOBALS['validatequery'])) {
                $validate_message = $GLOBALS['strNoValidateSQL'];
            } else {
                $validate_params['validatequery'] = 1;
                $validate_message = $GLOBALS['strValidateSQL'];
            }
            $validate_link = 'import.php' . PMA_generate_common_url($validate_params);
            $validate_link = ' [' . PMA_linkOrButton($validate_link, $validate_message) . ']';
        } else {
            $validate_link = '';
        }
        //validator
        echo '<code class="sql">';
        if ($query_too_big) {
            echo $shortened_query_base;
        } else {
            echo $query_base;
        }
        //Clean up the end of the PHP
        if (!empty($GLOBALS['show_as_php'])) {
            echo '";';
        }
        echo '</code>';
        echo '<div class="tools">';
        // avoid displaying a Profiling checkbox that could
        // be checked, which would reexecute an INSERT, for example
        if (!empty($refresh_link)) {
            PMA_profilingCheckbox($sql_query);
        }
        echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
        echo '</div>';
    }
    echo '</div><br />' . "\n";
}
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);
    }
/**
 * Checks if ROLLBACK is possible for a SQL query or not.
 *
 * @param string $sql_query SQL query
 *
 * @return bool
 */
function PMA_checkIfRollbackPossible($sql_query)
{
    // Supported queries.
    $supported_queries = array('INSERT', 'UPDATE', 'DELETE', 'REPLACE');
    // Parse and Analyze the query.
    $parsed_sql = PMA_SQP_parse($sql_query);
    $analyzed_sql = PMA_SQP_analyze($parsed_sql);
    $analyzed_sql_results = array('parsed_sql' => $parsed_sql, 'analyzed_sql' => $analyzed_sql);
    // Get the query type.
    $query_type = isset($analyzed_sql_results['analyzed_sql'][0]['querytype']) ? $analyzed_sql_results['analyzed_sql'][0]['querytype'] : '';
    // Check if query is supported.
    if (!in_array($query_type, $supported_queries)) {
        return false;
    }
    // Get table_references from the query.
    $table_references = PMA_getTableReferences($analyzed_sql_results);
    $table_references = $table_references ? $table_references : '';
    // Get table names from table_references.
    $tables = PMA_getTableNamesFromTableReferences($table_references);
    // Check if each table is 'InnoDB'.
    foreach ($tables as $table) {
        if (!PMA_isTableTransactional($table)) {
            return false;
        }
    }
    return true;
}
/**
 * return html for tables' detail
 *
 * @param array  $the_tables      tables list
 * @param string $db              database name
 * @param array  $cfg             global config
 * @param array  $cfgRelation     config from PMA_getRelationsParam
 * @param int    $cell_align_left cell align left
 *
 * @return string
 */
function PMA_getHtmlForTablesDetail($the_tables, $db, $cfg, $cfgRelation, $cell_align_left)
{
    $html = '';
    $tables_cnt = count($the_tables);
    $multi_tables = count($the_tables) > 1;
    $counter = 0;
    foreach ($the_tables as $table) {
        if ($counter + 1 >= $tables_cnt) {
            $breakstyle = '';
        } else {
            $breakstyle = ' style="page-break-after: always;"';
        }
        $counter++;
        $html .= '<div' . $breakstyle . '>' . "\n";
        $html .= '<h1>' . htmlspecialchars($table) . '</h1>' . "\n";
        /**
         * Gets table informations
         */
        $showtable = PMA_Table::sGetStatusInfo($db, $table);
        $num_rows = isset($showtable['Rows']) ? $showtable['Rows'] : 0;
        $show_comment = isset($showtable['Comment']) ? $showtable['Comment'] : '';
        $tbl_is_view = PMA_Table::isView($db, $table);
        /**
         * Gets fields properties
         */
        $columns = $GLOBALS['dbi']->getColumns($db, $table);
        // We need this to correctly learn if a TIMESTAMP is NOT NULL, since
        // SHOW FULL FIELDS or INFORMATION_SCHEMA incorrectly says NULL
        // and SHOW CREATE TABLE says NOT NULL (tested
        // in MySQL 4.0.25 and 5.0.21, http://bugs.mysql.com/20910).
        $show_create_table = $GLOBALS['dbi']->fetchValue('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table), 0, 1);
        $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
        // Check if we can use Relations
        // Find which tables are related with the current one and write it in
        // an array
        $res_rel = PMA_getForeigners($db, $table);
        $have_rel = (bool) count($res_rel);
        /**
         * Displays the comments of the table if MySQL >= 3.23
         */
        if (!empty($show_comment)) {
            $html .= __('Table comments:') . ' ' . htmlspecialchars($show_comment) . '<br /><br />';
        }
        $html .= PMA_getHtmlForTableStructure($have_rel, $tbl_is_view, $columns, $analyzed_sql, $res_rel, $db, $table, $cfgRelation, $cfg, $showtable, $cell_align_left);
        if ($multi_tables) {
            unset($num_rows, $show_comment);
            $html .= '<hr />' . "\n";
        }
        // end if
        $html .= '</div>' . "\n";
    }
    // end while
    return $html;
}
Beispiel #29
0
/**
 * Gets all Relations to foreign tables for a given table or
 * optionally a given column in a table
 *
 * @param   string   the name of the db to check for
 * @param   string   the name of the table to check for
 * @param   string   the name of the column to check for
 * @param   string   the source for foreign key information
 *
 * @return  array    db,table,column
 *
 * @global  array    the list of relations settings
 * @global  string   the URL of the page to show in case of error
 *
 * @access  public
 *
 * @author  Mike Beck <*****@*****.**> and Marc Delisle
 */
function PMA_getForeigners($db, $table, $column = '', $source = 'both')
{
    global $cfgRelation, $err_url_0;
    if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
        $rel_query = 'SELECT master_field, foreign_db, foreign_table, foreign_field' . ' FROM ' . PMA_backquote($cfgRelation['relation']) . ' WHERE master_db =  \'' . PMA_sqlAddslashes($db) . '\' ' . ' AND   master_table = \'' . PMA_sqlAddslashes($table) . '\' ';
        if (!empty($column)) {
            $rel_query .= ' AND master_field = \'' . PMA_sqlAddslashes($column) . '\'';
        }
        $relations = PMA_query_as_cu($rel_query);
        $i = 0;
        while ($relrow = @PMA_mysql_fetch_array($relations)) {
            $field = $relrow['master_field'];
            $foreign[$field]['foreign_db'] = $relrow['foreign_db'];
            $foreign[$field]['foreign_table'] = $relrow['foreign_table'];
            $foreign[$field]['foreign_field'] = $relrow['foreign_field'];
            $i++;
        }
        // end while
    }
    if (($source == 'both' || $source == 'innodb') && !empty($table)) {
        $show_create_table_query = 'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table);
        $show_create_table_res = PMA_mysql_query($show_create_table_query);
        list(, $show_create_table) = PMA_mysql_fetch_row($show_create_table_res);
        $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
        foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
            // the analyzer may return more than one column name in the
            // index list or the ref_index_list
            foreach ($one_key['index_list'] as $i => $field) {
                // If a foreign key is defined in the 'internal' source (pmadb)
                // and in 'innodb', we won't get it twice if $source='both'
                // because we use $field as key
                $foreign[$field]['constraint'] = $one_key['constraint'];
                if (isset($one_key['ref_db_name'])) {
                    $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
                } else {
                    $foreign[$field]['foreign_db'] = $db;
                }
                $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
                $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
                if (isset($one_key['on_delete'])) {
                    $foreign[$field]['on_delete'] = $one_key['on_delete'];
                }
                if (isset($one_key['on_update'])) {
                    $foreign[$field]['on_update'] = $one_key['on_update'];
                }
            }
        }
    }
    if (isset($foreign) && is_array($foreign)) {
        return $foreign;
    } else {
        return FALSE;
    }
}