Пример #1
0
/**
 * Get SQL query for store new transformation details of a VIEW
 *
 * @param mysqli_result $pma_tranformation_data Result set of SQL execution
 * @param array         $column_map             Details of VIEW columns
 * @param string        $view_name              Name of the VIEW
 * @param string        $db                     Database name of the VIEW
 *
 * @return string $new_transformations_sql SQL query for new tranformations
 */
function PMA_getNewTransformationDataSql($pma_tranformation_data, $column_map, $view_name, $db)
{
    $cfgRelation = PMA_getRelationsParam();
    // Need to store new transformation details for VIEW
    $new_transformations_sql = 'INSERT INTO ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['column_info']) . ' (`db_name`, `table_name`, `column_name`, `comment`, ' . '`mimetype`, `transformation`, `transformation_options`)' . ' VALUES ';
    $column_count = 0;
    $add_comma = false;
    while ($data_row = PMA_DBI_fetch_assoc($pma_tranformation_data)) {
        foreach ($column_map as $column) {
            if ($data_row['table_name'] == $column['table_name'] && $data_row['column_name'] == $column['refering_column']) {
                $new_transformations_sql .= $add_comma ? ', ' : '';
                $new_transformations_sql .= '(' . '\'' . $db . '\', ' . '\'' . $view_name . '\', ' . '\'';
                $new_transformations_sql .= isset($column['real_column']) ? $column['real_column'] : $column['refering_column'];
                $new_transformations_sql .= '\', ' . '\'' . $data_row['comment'] . '\', ' . '\'' . $data_row['mimetype'] . '\', ' . '\'' . $data_row['transformation'] . '\', ' . '\'' . PMA_Util::sqlAddSlashes($data_row['transformation_options']) . '\')';
                $add_comma = true;
                $column_count++;
                break;
            }
        }
        if ($column_count == count($column_map)) {
            break;
        }
    }
    return $column_count > 0 ? $new_transformations_sql : '';
}
Пример #2
0
 /**
  * Builds the SQL search query
  *
  * @param   string   the table name
  * @param   string   the string to search
  * @param   integer  type of search (1 -> 1 word at least, 2 -> all words,
  *                                   3 -> exact string, 4 -> regexp)
  *
  * @return  array    3 SQL querys (for count, display and delete results)
  *
  * @global  string   the url to return to in case of errors
  */
 function PMA_getSearchSqls($table, $search_str, $search_option)
 {
     global $err_url, $charset_connection;
     // Statement types
     $sqlstr_select = 'SELECT';
     $sqlstr_delete = 'DELETE';
     // Fields to select
     $res = PMA_DBI_query('SHOW ' . (PMA_MYSQL_INT_VERSION >= 40100 ? 'FULL ' : '') . 'FIELDS FROM ' . PMA_backquote($table) . ' FROM ' . PMA_backquote($GLOBALS['db']) . ';');
     while ($current = PMA_DBI_fetch_assoc($res)) {
         if (PMA_MYSQL_INT_VERSION >= 40100) {
             list($current['Charset']) = explode('_', $current['Collation']);
         }
         $current['Field'] = PMA_backquote($current['Field']);
         $tblfields[] = $current;
     }
     // while
     PMA_DBI_free_result($res);
     unset($current, $res);
     $tblfields_cnt = count($tblfields);
     // Table to use
     $sqlstr_from = ' FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($table);
     // Beginning of WHERE clause
     $sqlstr_where = ' WHERE';
     $search_words = $search_option > 2 ? array($search_str) : explode(' ', $search_str);
     $search_wds_cnt = count($search_words);
     $like_or_regex = $search_option == 4 ? 'REGEXP' : 'LIKE';
     $automatic_wildcard = $search_option < 3 ? '%' : '';
     for ($i = 0; $i < $search_wds_cnt; $i++) {
         // Eliminates empty values
         // In MySQL 4.1, if a field has no collation we get NULL in Charset
         // but in MySQL 5.0.x we get ''
         if (!empty($search_words[$i])) {
             for ($j = 0; $j < $tblfields_cnt; $j++) {
                 if (PMA_MYSQL_INT_VERSION >= 40100 && $tblfields[$j]['Charset'] != $charset_connection && $tblfields[$j]['Charset'] != 'NULL' && $tblfields[$j]['Charset'] != '') {
                     $prefix = 'CONVERT(_utf8 ';
                     $suffix = ' USING ' . $tblfields[$j]['Charset'] . ') COLLATE ' . $tblfields[$j]['Collation'];
                 } else {
                     $prefix = $suffix = '';
                 }
                 $thefieldlikevalue[] = $tblfields[$j]['Field'] . ' ' . $like_or_regex . ' ' . $prefix . '\'' . $automatic_wildcard . $search_words[$i] . $automatic_wildcard . '\'' . $suffix;
             }
             // end for
             $fieldslikevalues[] = $search_wds_cnt > 1 ? '(' . implode(' OR ', $thefieldlikevalue) . ')' : implode(' OR ', $thefieldlikevalue);
             unset($thefieldlikevalue);
         }
         // end if
     }
     // end for
     $implode_str = $search_option == 1 ? ' OR ' : ' AND ';
     $sqlstr_where .= ' ' . implode($implode_str, $fieldslikevalues);
     unset($fieldslikevalues);
     // Builds complete queries
     $sql['select_fields'] = $sqlstr_select . ' * ' . $sqlstr_from . $sqlstr_where;
     // here, I think we need to still use the COUNT clause, even for
     // VIEWs, anyway we have a WHERE clause that should limit results
     $sql['select_count'] = $sqlstr_select . ' COUNT(*) AS count' . $sqlstr_from . $sqlstr_where;
     $sql['delete'] = $sqlstr_delete . $sqlstr_from . $sqlstr_where;
     return $sql;
 }
/**
 * Function to get all index information from a certain table
 *
 * @param   string      Table name
 * @param   string      Error URL
 *
 * @access  public
 * @return  array       Index keys
 */
function PMA_get_indexes($tbl_name, $err_url_0 = '')
{
    $tbl_local_query = 'SHOW KEYS FROM ' . PMA_backquote($tbl_name);
    $tbl_result = PMA_DBI_query($tbl_local_query) or PMA_mysqlDie('', $tbl_local_query, '', $err_url_0);
    $tbl_ret_keys = array();
    while ($tbl_row = PMA_DBI_fetch_assoc($tbl_result)) {
        $tbl_ret_keys[] = $tbl_row;
    }
    PMA_DBI_free_result($tbl_result);
    return $tbl_ret_keys;
}
function PMA_DBI_get_fields($database, $table, $link = NULL)
{
    if (empty($link)) {
        if (isset($GLOBALS['userlink'])) {
            $link = $GLOBALS['userlink'];
        } else {
            return FALSE;
        }
    }
    $result = PMA_DBI_query('SHOW FULL FIELDS FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table), $link);
    $fields = array();
    while ($row = PMA_DBI_fetch_assoc($result)) {
        $fields[] = $row;
    }
    return $fields;
}
/**
 * retrieves table column info
 *
 * @uses    $GLOBALS['db']
 * @uses    PMA_DBI_QUERY_STORE
 * @uses    PMA_DBI_select_db()
 * @uses    PMA_DBI_query()
 * @uses    PMA_DBI_num_rows()
 * @uses    PMA_backquote()
 * @uses    count()
 * @return  array   table column nfo
 */
function get_tab_info()
{
    PMA_DBI_select_db($GLOBALS['db']);
    $tab_column = array();
    for ($i = 0, $cnt = count($GLOBALS['PMD']["TABLE_NAME"]); $i < $cnt; $i++) {
        $fields_rs = PMA_DBI_query('SHOW FULL FIELDS FROM ' . PMA_backquote($GLOBALS['PMD']["TABLE_NAME_SMALL"][$i]), NULL, PMA_DBI_QUERY_STORE);
        $j = 0;
        while ($row = PMA_DBI_fetch_assoc($fields_rs)) {
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['COLUMN_ID'][$j] = $j;
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['COLUMN_NAME'][$j] = $row['Field'];
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['TYPE'][$j] = $row['Type'];
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['NULLABLE'][$j] = $row['Null'];
            $j++;
        }
    }
    return $tab_column;
}
Пример #6
0
/**
 * retrieves table column info
 *
 * @return array   table column nfo
 */
function get_columns_info()
{
    PMA_DBI_select_db($GLOBALS['db']);
    $tab_column = array();
    for ($i = 0, $cnt = count($GLOBALS['PMD']["TABLE_NAME"]); $i < $cnt; $i++) {
        $fields_rs = PMA_DBI_query(PMA_DBI_get_columns_sql($GLOBALS['db'], $GLOBALS['PMD']["TABLE_NAME_SMALL"][$i], null, true), null, PMA_DBI_QUERY_STORE);
        $j = 0;
        while ($row = PMA_DBI_fetch_assoc($fields_rs)) {
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['COLUMN_ID'][$j] = $j;
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['COLUMN_NAME'][$j] = $row['Field'];
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['TYPE'][$j] = $row['Type'];
            $tab_column[$GLOBALS['PMD']['TABLE_NAME'][$i]]['NULLABLE'][$j] = $row['Null'];
            $j++;
        }
    }
    return $tab_column;
}
Пример #7
0
/**
 * Analysing where clauses array
 *
 * @param array  $where_clause_array array of where clauses
 * @param string $table              name of the table
 * @param string $db                 name of the database
 *
 * @return array $where_clauses, $result, $rows
 */
function PMA_analyzeWhereClauses($where_clause_array, $table, $db)
{
    $rows = array();
    $result = array();
    $where_clauses = array();
    $found_unique_key = false;
    foreach ($where_clause_array as $key_id => $where_clause) {
        $local_query = 'SELECT * FROM ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table) . ' WHERE ' . $where_clause . ';';
        $result[$key_id] = PMA_DBI_query($local_query, null, PMA_DBI_QUERY_STORE);
        $rows[$key_id] = PMA_DBI_fetch_assoc($result[$key_id]);
        $where_clauses[$key_id] = str_replace('\\', '\\\\', $where_clause);
        $has_unique_condition = PMA_showEmptyResultMessageOrSetUniqueCondition($rows, $key_id, $where_clause_array, $local_query, $result);
        if ($has_unique_condition) {
            $found_unique_key = true;
        }
    }
    return array($where_clauses, $result, $rows, $found_unique_key);
}
Пример #8
0
    $dataLabel = PMA_getDisplayField($db, $table);
}
// Displays the zoom search form
$response->addHTML($table_search->getSelectionForm($goto, $dataLabel));
/*
 * Handle the input criteria and generate the query result
 * Form for displaying query results
 */
if (isset($zoom_submit) && $_POST['criteriaColumnNames'][0] != 'pma_null' && $_POST['criteriaColumnNames'][1] != 'pma_null' && $_POST['criteriaColumnNames'][0] != $_POST['criteriaColumnNames'][1]) {
    //Query generation part
    $sql_query = $table_search->buildSqlQuery();
    $sql_query .= ' LIMIT ' . $maxPlotLimit;
    //Query execution part
    $result = PMA_DBI_query($sql_query . ";", null, PMA_DBI_QUERY_STORE);
    $fields_meta = PMA_DBI_get_fields_meta($result);
    while ($row = PMA_DBI_fetch_assoc($result)) {
        //Need a row with indexes as 0,1,2 for the getUniqueCondition
        // hence using a temporary array
        $tmpRow = array();
        foreach ($row as $val) {
            $tmpRow[] = $val;
        }
        //Get unique conditon on each row (will be needed for row update)
        $uniqueCondition = PMA_Util::getUniqueCondition($result, count($table_search->getColumnNames()), $fields_meta, $tmpRow, true);
        //Append it to row array as where_clause
        $row['where_clause'] = $uniqueCondition[0];
        $tmpData = array($_POST['criteriaColumnNames'][0] => $row[$_POST['criteriaColumnNames'][0]], $_POST['criteriaColumnNames'][1] => $row[$_POST['criteriaColumnNames'][1]], 'where_clause' => $uniqueCondition[0]);
        $tmpData[$dataLabel] = $dataLabel ? $row[$dataLabel] : '';
        $data[] = $tmpData;
    }
    unset($tmpData);
?>
" align="right">
                <input type="submit" name="submitcomment" value="<?php 
echo $strGo;
?>
" style="vertical-align: middle" />
            </td>
        </tr>
    </form>
        <tr><td colspan="2" height="5"></td></tr>
    <!-- Table type -->
    <?php 
// modify robbat2 code - staybyte - 11. June 2001
$result = PMA_DBI_query('SHOW VARIABLES LIKE \'have_%\';');
if ($result) {
    while ($tmp = PMA_DBI_fetch_assoc($result)) {
        if (isset($tmp['Variable_name'])) {
            switch ($tmp['Variable_name']) {
                case 'have_bdb':
                    if ($tmp['Value'] == 'YES') {
                        $tbl_bdb = TRUE;
                    }
                    break;
                case 'have_gemini':
                    if ($tmp['Value'] == 'YES') {
                        $tbl_gemini = TRUE;
                    }
                    break;
                case 'have_innodb':
                    if ($tmp['Value'] == 'YES') {
                        $tbl_innodb = TRUE;
Пример #10
0
/**
 * Handles requests for executing a routine
 *
 * @return Does not return
 */
function PMA_RTN_handleExecute()
{
    global $_GET, $_POST, $_REQUEST, $GLOBALS, $db;
    /**
     * Handle all user requests other than the default of listing routines
     */
    if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) {
        // Build the queries
        $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false);
        if ($routine !== false) {
            $queries = array();
            $end_query = array();
            $args = array();
            $all_functions = $GLOBALS['PMA_Types']->getAllFunctions();
            for ($i = 0; $i < $routine['item_num_params']; $i++) {
                if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) {
                    $value = $_REQUEST['params'][$routine['item_param_name'][$i]];
                    if (is_array($value)) {
                        // is SET type
                        $value = implode(',', $value);
                    }
                    $value = PMA_Util::sqlAddSlashes($value);
                    if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $all_functions)) {
                        $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n";
                    } else {
                        $queries[] = "SET @p{$i}='{$value}';\n";
                    }
                    $args[] = "@p{$i}";
                } else {
                    $args[] = "@p{$i}";
                }
                if ($routine['item_type'] == 'PROCEDURE') {
                    if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') {
                        $end_query[] = "@p{$i} AS " . PMA_Util::backquote($routine['item_param_name'][$i]);
                    }
                }
            }
            if ($routine['item_type'] == 'PROCEDURE') {
                $queries[] = "CALL " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n";
                if (count($end_query)) {
                    $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
                }
            } else {
                $queries[] = "SELECT " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_Util::backquote($routine['item_name']) . ";\n";
            }
            // Get all the queries as one SQL statement
            $multiple_query = implode("", $queries);
            $outcome = true;
            $affected = 0;
            // Execute query
            if (!PMA_DBI_try_multi_query($multiple_query)) {
                $outcome = false;
            }
            // Generate output
            if ($outcome) {
                // Pass the SQL queries through the "pretty printer"
                $output = '<code class="sql" style="margin-bottom: 1em;">';
                $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries)));
                $output .= '</code>';
                // Display results
                $output .= "<fieldset><legend>";
                $output .= sprintf(__('Execution results of routine %s'), PMA_Util::backquote(htmlspecialchars($routine['item_name'])));
                $output .= "</legend>";
                $num_of_rusults_set_to_display = 0;
                do {
                    $result = PMA_DBI_store_result();
                    $num_rows = PMA_DBI_num_rows($result);
                    if ($result !== false && $num_rows > 0) {
                        $output .= "<table><tr>";
                        foreach (PMA_DBI_get_fields_meta($result) as $key => $field) {
                            $output .= "<th>";
                            $output .= htmlspecialchars($field->name);
                            $output .= "</th>";
                        }
                        $output .= "</tr>";
                        $color_class = 'odd';
                        while ($row = PMA_DBI_fetch_assoc($result)) {
                            $output .= "<tr>";
                            foreach ($row as $key => $value) {
                                if ($value === null) {
                                    $value = '<i>NULL</i>';
                                } else {
                                    $value = htmlspecialchars($value);
                                }
                                $output .= "<td class='" . $color_class . "'>" . $value . "</td>";
                            }
                            $output .= "</tr>";
                            $color_class = $color_class == 'odd' ? 'even' : 'odd';
                        }
                        $output .= "</table>";
                        $num_of_rusults_set_to_display++;
                        $affected = $num_rows;
                    }
                    if (!PMA_DBI_more_results()) {
                        break;
                    }
                    $output .= "<br/>";
                    PMA_DBI_free_result($result);
                } while (PMA_DBI_next_result());
                $output .= "</fieldset>";
                $message = __('Your SQL query has been executed successfully');
                if ($routine['item_type'] == 'PROCEDURE') {
                    $message .= '<br />';
                    // TODO : message need to be modified according to the
                    // output from the routine
                    $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected);
                }
                $message = PMA_message::success($message);
                if ($num_of_rusults_set_to_display == 0) {
                    $notice = __('MySQL returned an empty result set (i.e. zero rows).');
                    $output .= PMA_message::notice($notice)->getDisplay();
                }
            } else {
                $output = '';
                $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), htmlspecialchars($query)) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null));
            }
            // Print/send output
            if ($GLOBALS['is_ajax_request']) {
                $response = PMA_Response::getInstance();
                $response->isSuccess($message->isSuccess());
                $response->addJSON('message', $message->getDisplay() . $output);
                $response->addJSON('dialog', false);
                exit;
            } else {
                echo $message->getDisplay() . $output;
                if ($message->isError()) {
                    // At least one query has failed, so shouldn't
                    // execute any more queries, so we quit.
                    exit;
                }
                unset($_POST);
                // Now deliberately fall through to displaying the routines list
            }
        } else {
            $message = __('Error in processing request') . ' : ';
            $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db)));
            $message = PMA_message::error($message);
            if ($GLOBALS['is_ajax_request']) {
                $response = PMA_Response::getInstance();
                $response->isSuccess(false);
                $response->addJSON('message', $message);
                exit;
            } else {
                echo $message->getDisplay();
                unset($_POST);
            }
        }
    } else {
        if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) {
            /**
             * Display the execute form for a routine.
             */
            $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true);
            if ($routine !== false) {
                $form = PMA_RTN_getExecuteForm($routine);
                if ($GLOBALS['is_ajax_request'] == true) {
                    $title = __("Execute routine") . " " . PMA_Util::backquote(htmlentities($_GET['item_name'], ENT_QUOTES));
                    $response = PMA_Response::getInstance();
                    $response->addJSON('message', $form);
                    $response->addJSON('title', $title);
                    $response->addJSON('dialog', true);
                } else {
                    echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
                    echo $form;
                }
                exit;
            } else {
                if ($GLOBALS['is_ajax_request'] == true) {
                    $message = __('Error in processing request') . ' : ';
                    $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db)));
                    $message = PMA_message::error($message);
                    $response = PMA_Response::getInstance();
                    $response->isSuccess(false);
                    $response->addJSON('message', $message);
                    exit;
                }
            }
        }
    }
}
 // Blending out tables in use
 if ($db_info_result && PMA_DBI_num_rows($db_info_result) > 0) {
     while ($tmp = PMA_DBI_fetch_row($db_info_result)) {
         // if in use memorize tablename
         if (preg_match('@in_use=[1-9]+@i', $tmp[1])) {
             $sot_cache[$tmp[0]] = true;
         }
     }
     PMA_DBI_free_result($db_info_result);
     if (isset($sot_cache)) {
         $db_info_result = PMA_DBI_query('SHOW TABLES FROM ' . PMA_backquote($db) . $tbl_group_sql . ';', null, PMA_DBI_QUERY_STORE);
         if ($db_info_result && PMA_DBI_num_rows($db_info_result) > 0) {
             while ($tmp = PMA_DBI_fetch_row($db_info_result)) {
                 if (!isset($sot_cache[$tmp[0]])) {
                     $sts_result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . addslashes($tmp[0]) . '\';');
                     $sts_tmp = PMA_DBI_fetch_assoc($sts_result);
                     PMA_DBI_free_result($sts_result);
                     unset($sts_result);
                     if (!isset($sts_tmp['Type']) && isset($sts_tmp['Engine'])) {
                         $sts_tmp['Type'] =& $sts_tmp['Engine'];
                     }
                     if (!empty($tbl_group) && $cfg['ShowTooltipAliasTB'] && !preg_match('@' . preg_quote($tbl_group, '@') . '@i', $sts_tmp['Comment'])) {
                         continue;
                     }
                     if ($cfg['ShowTooltip']) {
                         PMA_fillTooltip($tooltip_truename, $tooltip_aliasname, $sts_tmp);
                     }
                     $tables[$sts_tmp['Name']] = $sts_tmp;
                 } else {
                     // table in use
                     $tables[$tmp[0]] = array('Name' => $tmp[0]);
Пример #12
0
        </td>
    </tr>

    <tr bgcolor="<?php 
        echo $cfg['BgcolorTwo'];
        ?>
">
        <td width="20">&nbsp;</td>
        <td colspan="2">
            <label for="pdf_page_number_opt"><?php 
        echo $strPageNumber;
        ?>
</label>
            <select name="pdf_page_number" id="pdf_page_number_opt">
            <?php 
        while ($pages = @PMA_DBI_fetch_assoc($test_rs)) {
            echo '                <option value="' . $pages['page_nr'] . '">' . $pages['page_nr'] . ': ' . $pages['page_descr'] . '</option>' . "\n";
        }
        // end while
        PMA_DBI_free_result($test_rs);
        unset($test_rs);
        ?>
            </select><br />

            <input type="checkbox" name="show_grid" id="show_grid_opt" /><label for="show_grid_opt"><?php 
        echo $strShowGrid;
        ?>
</label><br />
            <input type="checkbox" name="show_color" id="show_color_opt" checked="checked" /><label for="show_color_opt"><?php 
        echo $strShowColor;
        ?>
Пример #13
0
?>
</th>
    <th><?php 
echo __('Original position');
?>
</th>
    <th><?php 
echo __('Information');
?>
</th>
</tr>
</thead>
<tbody>
<?php 
$odd_row = true;
while ($value = PMA_DBI_fetch_assoc($result)) {
    if (!$dontlimitchars && PMA_strlen($value['Info']) > $GLOBALS['cfg']['LimitChars']) {
        $value['Info'] = PMA_substr($value['Info'], 0, $GLOBALS['cfg']['LimitChars']) . '...';
    }
    ?>
<tr class="noclick <?php 
    echo $odd_row ? 'odd' : 'even';
    ?>
">
    <td>&nbsp;<?php 
    echo $value['Log_name'];
    ?>
&nbsp;</td>
    <td align="right">&nbsp;<?php 
    echo $value['Pos'];
    ?>
/**
 * Get queries for database specific privileges for change or copy user
 *
 * @param array  $queries  queries array with string
 * @param string $username username
 * @param string $hostname host name
 *
 * @return array $queries
 */
function PMA_getDbSpecificPrivsQueriesForChangeOrCopyUser($queries, $username, $hostname)
{
    $user_host_condition = ' WHERE `User`' . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . "'" . ' AND `Host`' . ' = \'' . PMA_Util::sqlAddSlashes($_REQUEST['old_username']) . '\';';
    $res = PMA_DBI_query('SELECT * FROM `mysql`.`db`' . $user_host_condition);
    while ($row = PMA_DBI_fetch_assoc($res)) {
        $queries[] = 'GRANT ' . join(', ', PMA_extractPrivInfo($row)) . ' ON ' . PMA_Util::backquote($row['Db']) . '.*' . ' TO \'' . PMA_Util::sqlAddSlashes($username) . '\'@\'' . PMA_Util::sqlAddSlashes($hostname) . '\'' . ($row['Grant_priv'] == 'Y' ? ' WITH GRANT OPTION;' : ';');
    }
    PMA_DBI_free_result($res);
    $queries = PMA_getTablePrivsQueriesForChangeOrCopyUser($user_host_condition, $queries, $username, $hostname);
    return $queries;
}
Пример #15
0
 /**
  * returns array with detailed info about engine specific server variables
  *
  * @return array   with detailed info about specific engine server variables
  */
 function getVariablesStatus()
 {
     $variables = $this->getVariables();
     $like = $this->getVariablesLikePattern();
     if ($like) {
         $like = " LIKE '" . $like . "' ";
     } else {
         $like = '';
     }
     $mysql_vars = array();
     $sql_query = 'SHOW GLOBAL VARIABLES ' . $like . ';';
     $res = PMA_DBI_query($sql_query);
     while ($row = PMA_DBI_fetch_assoc($res)) {
         if (isset($variables[$row['Variable_name']])) {
             $mysql_vars[$row['Variable_name']] = $variables[$row['Variable_name']];
         } elseif (!$like && strpos(strtolower($row['Variable_name']), strtolower($this->engine)) !== 0) {
             continue;
         }
         $mysql_vars[$row['Variable_name']]['value'] = $row['Value'];
         if (empty($mysql_vars[$row['Variable_name']]['title'])) {
             $mysql_vars[$row['Variable_name']]['title'] = $row['Variable_name'];
         }
         if (!isset($mysql_vars[$row['Variable_name']]['type'])) {
             $mysql_vars[$row['Variable_name']]['type'] = PMA_ENGINE_DETAILS_TYPE_PLAINTEXT;
         }
     }
     PMA_DBI_free_result($res);
     return $mysql_vars;
 }
Пример #16
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 (!empty($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 .= '(' . $tbl_status['Rows'] . ' ' . $GLOBALS['strRows'] . ')';
                PMA_DBI_free_result($result);
                $md5_tbl = md5($GLOBALS['table']);
                echo "\n";
                ?>
<script type="text/javascript" language="javascript1.2">
<!--
if (typeof(document.getElementById) != 'undefined'
    && typeof(window.parent.frames['nav']) != 'undefined'
    && typeof(window.parent.frames['nav'].document) != 'undefined' && typeof(window.parent.frames['nav'].document) != 'unknown'
    && (window.parent.frames['nav'].document.getElementById('<?php 
                echo 'tbl_' . $md5_tbl;
                ?>
'))
    && typeof(window.parent.frames['nav'].document.getElementById('<?php 
                echo 'tbl_' . $md5_tbl;
                ?>
')) != 'undefined'
    && typeof(window.parent.frames['nav'].document.getElementById('<?php 
                echo 'tbl_' . $md5_tbl;
                ?>
').title) == 'string') {
    window.parent.frames['nav'].document.getElementById('<?php 
                echo 'tbl_' . $md5_tbl;
                ?>
').title = '<?php 
                echo PMA_jsFormat($tooltip, FALSE);
                ?>
';
}
//-->
</script>
                <?php 
            }
            // end if
        }
        // end if... else if
        // 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);
        echo "\n";
        ?>
<br />
<div align="<?php 
        echo $GLOBALS['cell_align_left'];
        ?>
">
    <table border="<?php 
        echo $cfg['Border'];
        ?>
" cellpadding="5" cellspacing="1">
    <tr>
        <th<?php 
        echo $GLOBALS['theme'] != 'original' ? ' class="tblHeaders"' : ' bgcolor="' . $cfg['ThBgcolor'] . '"';
        ?>
>
            <b><?php 
        echo $message;
        ?>
</b>
        </th>
    </tr>
        <?php 
        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'] : '');
            echo "\n";
            ?>
    <tr>
        <td bgcolor="<?php 
            echo $cfg['BgcolorOne'];
            ?>
">
            <?php 
            echo "\n";
            // 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 */
            $sqlnr = 1;
            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));
                /* SQL-Parser-Analyzer */
                $query_base = preg_replace("@((\r\n)|(\r)|(\n))+@", $new_line, $query_base);
            } else {
                $query_base = $local_query;
            }
            // 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 ?
            // TODO: use the parser instead of preg_match()
            if (preg_match('@^SELECT[[:space:]]+@i', $query_base) && isset($GLOBALS['sql_limit_to_append'])) {
                $query_base .= $GLOBALS['sql_limit_to_append'];
            }
            if (!empty($GLOBALS['show_as_php'])) {
                $query_base = '$sql  = \'' . $query_base;
            } else {
                if (!empty($GLOBALS['validatequery'])) {
                    $query_base = PMA_validateSQL($query_base);
                } else {
                    // avoid reparsing query:
                    if (isset($GLOBALS['parsed_sql']) && $query_base == $GLOBALS['parsed_sql']['raw']) {
                        $parsed_sql = $GLOBALS['parsed_sql'];
                    } else {
                        $parsed_sql = PMA_SQP_parse($query_base);
                    }
                    $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' : '';
            //} else if ($GLOBALS['goto'] != 'main.php') {
            //    $edit_target = $GLOBALS['goto'];
            //} else {
            //    $edit_target = '';
            //}
            if (isset($cfg['SQLQuery']['Edit']) && $cfg['SQLQuery']['Edit'] == TRUE && !empty($edit_target)) {
                $onclick = '';
                if ($cfg['QueryFrameJS'] && $cfg['QueryFrame']) {
                    $onclick = 'onclick="focus_querywindow(\'' . urlencode($local_query) . '\'); return false;"';
                }
                $edit_link = '&nbsp;[<a href="' . $edit_target . $url_qpart . '&amp;sql_query=' . urlencode($local_query) . '&amp;show_query=1#querybox" ' . $onclick . '>' . $GLOBALS['strEdit'] . '</a>]';
            } 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 = '&nbsp;[<a href="read_dump.php' . $url_qpart . $explain_link_validate . '&amp;sql_query=';
                if (preg_match('@^SELECT[[:space:]]+@i', $local_query)) {
                    $explain_link .= urlencode('EXPLAIN ' . $local_query) . '">' . $GLOBALS['strExplain'];
                } else {
                    if (preg_match('@^EXPLAIN[[:space:]]+SELECT[[:space:]]+@i', $local_query)) {
                        $explain_link .= urlencode(substr($local_query, 8)) . '">' . $GLOBALS['strNoExplain'];
                    } else {
                        $explain_link = '';
                    }
                }
                if (!empty($explain_link)) {
                    $explain_link .= '</a>]';
                }
            } 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 = '&nbsp;[<a href="read_dump.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">' . $GLOBALS['strNoPhp'];
                } else {
                    $php_link .= '1">' . $GLOBALS['strPhp'];
                }
                $php_link .= '</a>]';
                if (isset($GLOBALS['show_as_php']) && $GLOBALS['show_as_php'] == '1') {
                    $php_link .= '&nbsp;[<a href="read_dump.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query) . '">' . $GLOBALS['strRunQuery'] . '</a>]';
                }
            } 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 = '&nbsp;[<a href="read_dump.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query) . '">';
                $refresh_link .= $GLOBALS['strRefresh'];
                $refresh_link .= '</a>]';
            } 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 = '&nbsp;[<a href="read_dump.php' . $url_qpart . '&amp;show_query=1' . '&amp;sql_query=' . urlencode($local_query) . '&amp;validatequery=';
                if (!empty($GLOBALS['validatequery'])) {
                    $validate_link .= '0">' . $GLOBALS['strNoValidateSQL'];
                } else {
                    $validate_link .= '1">' . $GLOBALS['strValidateSQL'];
                }
                $validate_link .= '</a>]';
            } else {
                $validate_link = '';
            }
            //validator
            // Displays the message
            echo '            <b>' . $GLOBALS['strSQLQuery'] . ':</b>&nbsp;';
            echo '<br />' . "\n";
            echo '            ' . $query_base;
            unset($local_query);
            //Clean up the end of the PHP
            if (!empty($GLOBALS['show_as_php'])) {
                echo '\';';
            }
            echo "\n";
            ?>
        </td>
    </tr>
    <?php 
            if (!empty($edit_target)) {
                echo '<tr><td bgcolor="' . $cfg['BgcolorOne'] . '" align="center">';
                echo $edit_link . $explain_link . $php_link . $refresh_link . $validate_link;
                echo '</td></tr>' . "\n";
            }
        }
        echo "\n";
        ?>
    </table>
</div><br />
        <?php 
    }
Пример #17
0
 // Restore the "primary key" to a convenient format
 $primary_key = urldecode($enc_primary_key);
 // Defines the SET part of the sql query
 $valuelist = '';
 $fieldlist = '';
 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
 $me_fields = isset($fields['multi_edit']) && isset($fields['multi_edit'][$enc_primary_key]) ? $fields['multi_edit'][$enc_primary_key] : null;
 $me_fields_prev = isset($fields_prev['multi_edit']) && isset($fields_prev['multi_edit'][$enc_primary_key]) ? $fields_prev['multi_edit'][$enc_primary_key] : null;
 $me_funcs = isset($funcs['multi_edit']) && isset($funcs['multi_edit'][$enc_primary_key]) ? $funcs['multi_edit'][$enc_primary_key] : null;
 $me_fields_type = isset($fields_type['multi_edit']) && isset($fields_type['multi_edit'][$enc_primary_key]) ? $fields_type['multi_edit'][$enc_primary_key] : null;
 $me_fields_null = isset($fields_null['multi_edit']) && isset($fields_null['multi_edit'][$enc_primary_key]) ? $fields_null['multi_edit'][$enc_primary_key] : null;
 $me_fields_null_prev = isset($fields_null_prev['multi_edit']) && isset($fields_null_prev['multi_edit'][$enc_primary_key]) ? $fields_null_prev['multi_edit'][$enc_primary_key] : null;
 $me_auto_increment = isset($auto_increment['multi_edit']) && isset($auto_increment['multi_edit'][$enc_primary_key]) ? $auto_increment['multi_edit'][$enc_primary_key] : null;
 if ($using_key && isset($me_fields_type) && is_array($me_fields_type) && isset($primary_key)) {
     $prot_result = PMA_DBI_query('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $primary_key . ';');
     $prot_row = PMA_DBI_fetch_assoc($prot_result);
     PMA_DBI_free_result($prot_result);
     unset($prot_result);
 }
 foreach ($me_fields as $encoded_key => $val) {
     $key = urldecode($encoded_key);
     $fieldlist .= PMA_backquote($key) . ', ';
     require './libraries/tbl_replace_fields.inc.php';
     if (empty($me_funcs[$encoded_key])) {
         $cur_value = $val . ', ';
     } elseif (preg_match('@^(UNIX_TIMESTAMP)$@', $me_funcs[$encoded_key]) && $val != '\'\'') {
         $cur_value = $me_funcs[$encoded_key] . '(' . $val . '), ';
     } elseif (preg_match('@^(NOW|CURDATE|CURTIME|UTC_DATE|UTC_TIME|UTC_TIMESTAMP|UNIX_TIMESTAMP|RAND|USER|LAST_INSERT_ID)$@', $me_funcs[$encoded_key])) {
         $cur_value = $me_funcs[$encoded_key] . '(), ';
     } else {
         $cur_value = $me_funcs[$encoded_key] . '(' . $val . '), ';
    /**
     * this is just a backup, if all is fine this can be deleted later
     *
     * @deprecated
     */
    protected function _checkAgainstPrivTables()
    {
        // 1. get allowed dbs from the "mysql.db" table
        // lem9: User can be blank (anonymous user)
        $local_query = "
            SELECT DISTINCT `Db` FROM `mysql`.`db`
            WHERE `Select_priv` = 'Y'
            AND `User`
            IN ('" . PMA_sqlAddslashes($GLOBALS['cfg']['Server']['user']) . "', '')";
        $tmp_mydbs = PMA_DBI_fetch_result($local_query, null, null,
            $GLOBALS['controllink']);
        if ($tmp_mydbs) {
            // Will use as associative array of the following 2 code
            // lines:
            //   the 1st is the only line intact from before
            //     correction,
            //   the 2nd replaces $dblist[] = $row['Db'];

            // Code following those 2 lines in correction continues
            // populating $dblist[], as previous code did. But it is
            // now populated with actual database names instead of
            // with regular expressions.
            $tmp_alldbs = PMA_DBI_query('SHOW DATABASES;', $GLOBALS['controllink']);
            // loic1: all databases cases - part 2
            if (isset($tmp_mydbs['%'])) {
                while ($tmp_row = PMA_DBI_fetch_row($tmp_alldbs)) {
                    $dblist[] = $tmp_row[0];
                } // end while
            } else {
                while ($tmp_row = PMA_DBI_fetch_row($tmp_alldbs)) {
                    $tmp_db = $tmp_row[0];
                    if (isset($tmp_mydbs[$tmp_db]) && $tmp_mydbs[$tmp_db] == 1) {
                        $dblist[]           = $tmp_db;
                        $tmp_mydbs[$tmp_db] = 0;
                    } elseif (!isset($dblist[$tmp_db])) {
                        foreach ($tmp_mydbs as $tmp_matchpattern => $tmp_value) {
                            // loic1: fixed bad regexp
                            // TODO: db names may contain characters
                            //       that are regexp instructions
                            $re        = '(^|(\\\\\\\\)+|[^\])';
                            $tmp_regex = preg_replace('/' . addcslashes($re,'/') . '%/', '\\1.*', preg_replace('/' . addcslashes($re,'/') . '_/', '\\1.{1}', $tmp_matchpattern));
                            // Fixed db name matching
                            // 2000-08-28 -- Benjamin Gandon
                            if (preg_match('/^' . addcslashes($tmp_regex,'/') . '$/', $tmp_db)) {
                                $dblist[] = $tmp_db;
                                break;
                            }
                        } // end while
                    } // end if ... elseif ...
                } // end while
            } // end else
            PMA_DBI_free_result($tmp_alldbs);
            unset($tmp_mydbs);
        } // end if

        // 2. get allowed dbs from the "mysql.tables_priv" table
        $local_query = 'SELECT DISTINCT Db FROM mysql.tables_priv WHERE Table_priv LIKE \'%Select%\' AND User = \'' . PMA_sqlAddslashes($GLOBALS['cfg']['Server']['user']) . '\'';
        $rs          = PMA_DBI_try_query($local_query, $GLOBALS['controllink']);
        if ($rs && @PMA_DBI_num_rows($rs)) {
            while ($row = PMA_DBI_fetch_assoc($rs)) {
                if (!in_array($row['Db'], $dblist)) {
                    $dblist[] = $row['Db'];
                }
            } // end while
            PMA_DBI_free_result($rs);
        } // end if
    }
Пример #19
0
$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);
    }
    $result = array();
    $found_unique_key = false;
    $where_clauses = array();
    foreach ($where_clause_array as $key_id => $where_clause) {
        $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';';
        $result[$key_id] = PMA_DBI_query($local_query, null, PMA_DBI_QUERY_STORE);
        $rows[$key_id] = PMA_DBI_fetch_assoc($result[$key_id]);
        $where_clauses[$key_id] = str_replace('\\', '\\\\', $where_clause);
        // No row returned
        if (!$rows[$key_id]) {
            unset($rows[$key_id], $where_clause_array[$key_id]);
            PMA_showMessage($strEmptyResultSet, $local_query);
            echo "\n";
            require_once './libraries/footer.inc.php';
        } else {
            // end if (no row returned)
            $meta = PMA_DBI_get_fields_meta($result[$key_id]);
            list($unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result[$key_id], count($meta), $meta, $rows[$key_id], true);
            if (!empty($unique_condition)) {
                $found_unique_key = true;
            }
            unset($unique_condition, $tmp_clause_is_unique);
/**
 * returns array with databases containing extended infos about them
 *
 * @todo    move into PMA_List_Database?
 * @param   string      $databases      database
 * @param   boolean     $force_stats    retrieve stats also for MySQL < 5
 * @param   resource    $link           mysql link
 * @param   string      $sort_by        column to order by
 * @param   string      $sort_order     ASC or DESC
 * @param   integer     $limit_offset   starting offset for LIMIT
 * @param   bool|int    $limit_count    row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
 * @return  array       $databases
 */
function PMA_DBI_get_databases_full($database = null, $force_stats = false, $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC', $limit_offset = 0, $limit_count = false)
{
    $sort_order = strtoupper($sort_order);
    if (true === $limit_count) {
        $limit_count = $GLOBALS['cfg']['MaxDbList'];
    }
    // initialize to avoid errors when there are no databases
    $databases = array();
    $apply_limit_and_order_manual = true;
    if (!$GLOBALS['cfg']['Server']['DisableIS']) {
        /**
         * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
         * cause MySQL does not support natural ordering, we have to do it afterward
         */
        if ($GLOBALS['cfg']['NaturalOrder']) {
            $limit = '';
        } else {
            if ($limit_count) {
                $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
            }
            $apply_limit_and_order_manual = false;
        }
        // get table information from information_schema
        if ($database) {
            $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \'' . addslashes($database) . '\'';
        } else {
            $sql_where_schema = '';
        }
        // for PMA bc:
        // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
        $sql = '
             SELECT `information_schema`.`SCHEMATA`.*';
        if ($force_stats) {
            $sql .= ',
                    COUNT(`information_schema`.`TABLES`.`TABLE_SCHEMA`)
                        AS `SCHEMA_TABLES`,
                    SUM(`information_schema`.`TABLES`.`TABLE_ROWS`)
                        AS `SCHEMA_TABLE_ROWS`,
                    SUM(`information_schema`.`TABLES`.`DATA_LENGTH`)
                        AS `SCHEMA_DATA_LENGTH`,
                    SUM(`information_schema`.`TABLES`.`MAX_DATA_LENGTH`)
                        AS `SCHEMA_MAX_DATA_LENGTH`,
                    SUM(`information_schema`.`TABLES`.`INDEX_LENGTH`)
                        AS `SCHEMA_INDEX_LENGTH`,
                    SUM(`information_schema`.`TABLES`.`DATA_LENGTH`
                      + `information_schema`.`TABLES`.`INDEX_LENGTH`)
                        AS `SCHEMA_LENGTH`,
                    SUM(`information_schema`.`TABLES`.`DATA_FREE`)
                        AS `SCHEMA_DATA_FREE`';
        }
        $sql .= '
               FROM `information_schema`.`SCHEMATA`';
        if ($force_stats) {
            $sql .= '
          LEFT JOIN `information_schema`.`TABLES`
                 ON BINARY `information_schema`.`TABLES`.`TABLE_SCHEMA`
                  = BINARY `information_schema`.`SCHEMATA`.`SCHEMA_NAME`';
        }
        $sql .= '
              ' . $sql_where_schema . '
           GROUP BY BINARY `information_schema`.`SCHEMATA`.`SCHEMA_NAME`
           ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order . $limit;
        $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
        $mysql_error = PMA_DBI_getError($link);
        if (!count($databases) && $GLOBALS['errno']) {
            PMA_mysqlDie($mysql_error, $sql);
        }
        // display only databases also in official database list
        // f.e. to apply hide_db and only_db
        $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases);
        if (count($drops)) {
            foreach ($drops as $drop) {
                unset($databases[$drop]);
            }
            unset($drop);
        }
        unset($sql_where_schema, $sql, $drops);
    } else {
        foreach ($GLOBALS['pma']->databases as $database_name) {
            // MySQL forward compatibility
            // so pma could use this array as if every server is of version >5.0
            $databases[$database_name]['SCHEMA_NAME'] = $database_name;
            if ($force_stats) {
                require_once './libraries/mysql_charsets.lib.php';
                $databases[$database_name]['DEFAULT_COLLATION_NAME'] = PMA_getDbCollation($database_name);
                // get additional info about tables
                $databases[$database_name]['SCHEMA_TABLES'] = 0;
                $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
                $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
                $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
                $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
                $databases[$database_name]['SCHEMA_LENGTH'] = 0;
                $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
                $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';');
                while ($row = PMA_DBI_fetch_assoc($res)) {
                    $databases[$database_name]['SCHEMA_TABLES']++;
                    $databases[$database_name]['SCHEMA_TABLE_ROWS'] += $row['Rows'];
                    $databases[$database_name]['SCHEMA_DATA_LENGTH'] += $row['Data_length'];
                    $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] += $row['Max_data_length'];
                    $databases[$database_name]['SCHEMA_INDEX_LENGTH'] += $row['Index_length'];
                    // for InnoDB, this does not contain the number of
                    // overhead bytes but the total free space
                    if ('InnoDB' != $row['Engine']) {
                        $databases[$database_name]['SCHEMA_DATA_FREE'] += $row['Data_free'];
                    }
                    $databases[$database_name]['SCHEMA_LENGTH'] += $row['Data_length'] + $row['Index_length'];
                }
                PMA_DBI_free_result($res);
                unset($res);
            }
        }
    }
    /**
     * apply limit and order manually now
     * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
     */
    if ($apply_limit_and_order_manual) {
        $GLOBALS['callback_sort_order'] = $sort_order;
        $GLOBALS['callback_sort_by'] = $sort_by;
        usort($databases, 'PMA_usort_comparison_callback');
        unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
        /**
         * now apply limit
         */
        if ($limit_count) {
            $databases = array_slice($databases, $limit_offset, $limit_count);
        }
    }
    return $databases;
}
Пример #21
0
/**
* Set a single mimetype to a certain value.
*
* @param   string   the name of the db
* @param   string   the name of the table
* @param   string   the name of the column
* @param   string   the mimetype of the column
* @param   string   the transformation of the column
* @param   string   the transformation options of the column
* @param   string   (optional) force delete, will erase any existing comments for this column
*
* @return  boolean  true, if comment-query was made.
*
* @global  array    the list of relations settings
*
* @access  public
*/
function PMA_setMIME($db, $table, $key, $mimetype, $transformation, $transformation_options, $forcedelete = false)
{
    global $cfgRelation;
    $test_qry = 'SELECT mimetype, ' . PMA_backquote('comment') . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND column_name = \'' . PMA_sqlAddslashes($key) . '\'';
    $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);
        unset($test_rs);
        if (!$forcedelete && (strlen($mimetype) > 0 || strlen($transformation) > 0 || strlen($transformation_options) > 0 || strlen($row['comment']) > 0)) {
            $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' SET mimetype = \'' . PMA_sqlAddslashes($mimetype) . '\',' . '     transformation = \'' . PMA_sqlAddslashes($transformation) . '\',' . '     transformation_options = \'' . PMA_sqlAddslashes($transformation_options) . '\'' . ' WHERE db_name  = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND column_name = \'' . PMA_sqlAddslashes($key) . '\'';
        } else {
            $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' WHERE db_name  = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'' . ' AND column_name = \'' . PMA_sqlAddslashes($key) . '\'';
        }
    } elseif (strlen($mimetype) > 0 || strlen($transformation) > 0 || strlen($transformation_options) > 0) {
        $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . ' (db_name, table_name, column_name, mimetype, transformation, transformation_options) ' . ' VALUES(' . '\'' . PMA_sqlAddslashes($db) . '\',' . '\'' . PMA_sqlAddslashes($table) . '\',' . '\'' . PMA_sqlAddslashes($key) . '\',' . '\'' . PMA_sqlAddslashes($mimetype) . '\',' . '\'' . PMA_sqlAddslashes($transformation) . '\',' . '\'' . PMA_sqlAddslashes($transformation_options) . '\')';
    }
    if (isset($upd_query)) {
        $upd_rs = PMA_query_as_cu($upd_query);
        PMA_DBI_free_result($upd_rs);
        unset($upd_rs);
        return true;
    } else {
        return false;
    }
}
Пример #22
0
/**
 * Gets bookmarked DefaultQuery for a Table
 *
 * @global  resource  the controluser db connection handle
 *
 * @param   string    the current database name
 * @param   array     the bookmark parameters for the current user
 * @param   array     the list of all labels to look for
 *
 * @return  array     bookmark SQL statements
 *
 * @access  public
 */
function &PMA_queryDBBookmarks($db, $cfgBookmark, &$table_array)
{
    global $controllink;
    $bookmarks = array();
    if (empty($cfgBookmark['db']) || empty($cfgBookmark['table'])) {
        return $bookmarks;
    }
    $search_for = array();
    foreach ($table_array as $table => $table_sortkey) {
        $search_for[] = "'" . PMA_sqlAddslashes($table) . "'";
    }
    $query = 'SELECT label, query FROM ' . PMA_backquote($cfgBookmark['db']) . '.' . PMA_backquote($cfgBookmark['table']) . ' WHERE dbase = \'' . PMA_sqlAddslashes($db) . '\'' . (count($search_for) > 0 ? ' AND label IN (' . implode(', ', $search_for) . ')' : '');
    $result = PMA_DBI_try_query($query, $controllink, PMA_DBI_QUERY_STORE);
    if (!$result || PMA_DBI_num_rows($result) < 1) {
        return $bookmarks;
    }
    while ($row = PMA_DBI_fetch_assoc($result)) {
        $bookmarks[$row['label']] = $row['query'];
    }
    return $bookmarks;
}
Пример #23
0
        .'  `Db` ASC;';
    $res = PMA_DBI_query($sql_query);
    $row = PMA_DBI_fetch_assoc($res);
    if ($row) {
        $found = true;
    }

    if ($found) {
        while (true) {
            // prepare the current user
            $current_privileges = array();
            $current_user = $row['User'];
            $current_host = $row['Host'];
            while ($row && $current_user == $row['User'] && $current_host == $row['Host']) {
                $current_privileges[] = $row;
                $row = PMA_DBI_fetch_assoc($res);
            }
            $user_form .= '    <tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
               . '        <td';
            if (count($current_privileges) > 1) {
                $user_form .= ' rowspan="' . count($current_privileges) . '"';
            }
            $user_form .= '>' . (empty($current_user) ? '<span style="color: #FF0000">' . __('Any') . '</span>' : htmlspecialchars($current_user)) . "\n"
               . '        </td>' . "\n"
               . '        <td';
            if (count($current_privileges) > 1) {
                $user_form .= ' rowspan="' . count($current_privileges) . '"';
            }
            $user_form .= '>' . htmlspecialchars($current_host) . '</td>' . "\n";
            for ($i = 0; $i < count($current_privileges); $i++) {
                $current = $current_privileges[$i];
Пример #24
0
 /**
  * Finds all related tables
  *
  * @param   string   wether to go from master to foreign or vice versa
  *
  * @return  boolean  always TRUE
  *
  * @global  array    the list of tables that we still couldn't connect
  * @global  array    the list of allready connected tables
  * @global  string   the current databse name
  * @global  string   the super user connection id
  * @global  array    the list of relation settings
  *
  * @access  private
  */
 function PMA_getRelatives($from)
 {
     global $tab_left, $tab_know, $fromclause;
     global $controllink, $db, $cfgRelation;
     if ($from == 'master') {
         $to = 'foreign';
     } else {
         $to = 'master';
     }
     $in_know = '(\'' . implode('\', \'', $tab_know) . '\')';
     $in_left = '(\'' . implode('\', \'', $tab_left) . '\')';
     $rel_query = 'SELECT *' . ' FROM ' . PMA_backquote($cfgRelation['relation']) . ' WHERE ' . $from . '_db   = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND ' . $to . '_db   = \'' . PMA_sqlAddslashes($db) . '\'' . ' AND ' . $from . '_table IN ' . $in_know . ' AND ' . $to . '_table IN ' . $in_left;
     PMA_DBI_select_db($cfgRelation['db'], $controllink);
     $relations = @PMA_DBI_query($rel_query, $controllink);
     PMA_DBI_select_db($db, $controllink);
     while ($row = PMA_DBI_fetch_assoc($relations)) {
         $found_table = $row[$to . '_table'];
         if (isset($tab_left[$found_table])) {
             $fromclause .= "\n" . ' LEFT JOIN ' . PMA_backquote($row[$to . '_table']) . ' ON ' . PMA_backquote($row[$from . '_table']) . '.' . PMA_backquote($row[$from . '_field']) . ' = ' . PMA_backquote($row[$to . '_table']) . '.' . PMA_backquote($row[$to . '_field']) . ' ';
             $tab_know[$found_table] = $found_table;
             $tab_left = PMA_arrayShort($tab_left, $found_table);
         }
     }
     // end while
     return TRUE;
 }
Пример #25
0
                $drag_y = $temp_sh_page['y'];
                $draginit .= '    Drag.init(getElement("table_' . $i . '"), null, 0, parseInt(myid.style.width)-2, 0, parseInt(myid.style.height)-5);' . "\n";
                $draginit .= '    getElement("table_' . $i . '").onDrag = function (x, y) { document.edcoord.elements["c_table_' . $i . '[x]"].value = parseInt(x); document.edcoord.elements["c_table_' . $i . '[y]"].value = parseInt(y) }' . "\n";
                $draginit .= '    getElement("table_' . $i . '").style.left = "' . $drag_x . 'px";' . "\n";
                $draginit .= '    getElement("table_' . $i . '").style.top  = "' . $drag_y . 'px";' . "\n";
                $reset_draginit .= '    getElement("table_' . $i . '").style.left = "2px";' . "\n";
                $reset_draginit .= '    getElement("table_' . $i . '").style.top  = "' . 15 * $i . 'px";' . "\n";
                $reset_draginit .= '    document.edcoord.elements["c_table_' . $i . '[x]"].value = "2"' . "\n";
                $reset_draginit .= '    document.edcoord.elements["c_table_' . $i . '[y]"].value = "' . 15 * $i . '"' . "\n";
                $local_query = 'SHOW FIELDS FROM ' . PMA_backquote($temp_sh_page['table_name']) . ' FROM ' . PMA_backquote($db);
                $fields_rs = PMA_DBI_query($local_query);
                unset($local_query);
                $fields_cnt = PMA_DBI_num_rows($fields_rs);
                echo '<div id="table_' . $i . '" class="pdflayout_table"><u>' . $temp_sh_page['table_name'] . '</u>';
                if (isset($with_field_names)) {
                    while ($row = PMA_DBI_fetch_assoc($fields_rs)) {
                        echo '<br />' . htmlspecialchars($row['Field']) . "\n";
                    }
                }
                echo '</div>' . "\n";
                PMA_DBI_free_result($fields_rs);
                unset($fields_rs);
                $i++;
            }
            ?>
</div>
<script type="text/javascript" language="javascript">
//<![CDATA[
function init() {
    refreshLayout();
    myid = getElement('pdflayout');
$cfgRelation = PMA_getRelationsParam();
/**
 * Ensures db and table are valid, else moves to the "parent" script
 */
require_once './libs/db_table_exists.lib.php';
/**
 * Get the list of the fields of the current table
 */
PMA_DBI_select_db($db);
$table_def = PMA_DBI_query('SHOW FIELDS FROM ' . PMA_backquote($table), null, PMA_DBI_QUERY_STORE);
if (isset($primary_key)) {
    $result = PMA_DBI_query('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $primary_key . ';', null, PMA_DBI_QUERY_STORE);
    $row = PMA_DBI_fetch_assoc($result);
} else {
    $result = PMA_DBI_query('SELECT * FROM ' . PMA_backquote($table) . ' LIMIT 1;', null, PMA_DBI_QUERY_STORE);
    $row = PMA_DBI_fetch_assoc($result);
}
// No row returned
if (!$row) {
    exit;
}
// end if (no record returned)
$default_ct = 'application/octet-stream';
if ($cfgRelation['commwork'] && $cfgRelation['mimework']) {
    $mime_map = PMA_getMime($db, $table);
    $mime_options = PMA_transformation_getOptions(isset($mime_map[urldecode($transform_key)]['transformation_options']) ? $mime_map[urldecode($transform_key)]['transformation_options'] : '');
    foreach ($mime_options as $key => $option) {
        if (substr($option, 0, 10) == '; charset=') {
            $mime_options['charset'] = $option;
        }
    }
 /**
  * get all tables involved or included in page
  *
  * @param string  $db         name of the database
  * @param integer $pageNumber page no. whose tables will be fetched in an array
  *
  * @return Array an array of tables
  *
  * @access public
  */
 public function getAllTables($db, $pageNumber)
 {
     global $cfgRelation;
     // Get All tables
     $tab_sql = 'SELECT table_name FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util::backquote($cfgRelation['table_coords']) . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\'' . ' AND pdf_page_number = ' . $pageNumber;
     $tab_rs = PMA_queryAsControlUser($tab_sql, null, PMA_DBI_QUERY_STORE);
     if (!$tab_rs || !PMA_DBI_num_rows($tab_rs) > 0) {
         $this->dieSchema('', __('This page does not contain any tables!'));
     }
     while ($curr_table = @PMA_DBI_fetch_assoc($tab_rs)) {
         $alltables[] = PMA_Util::sqlAddSlashes($curr_table['table_name']);
     }
     return $alltables;
 }
Пример #28
0
 /**
  * Returns $table's CREATE definition
  *
  * @param string $db            the database name
  * @param string $table         the table name
  * @param string $crlf          the end of line sequence
  * @param string $error_url     the url to go back in case of error
  * @param bool   $show_dates    whether to include creation/update/check
  *                              dates
  * @param bool   $add_semicolon whether to add semicolon and end-of-line at
  *                              the end
  * @param bool   $view          whether we're handling a view
  *
  * @return string resulting schema
  */
 public function getTableDef($db, $table, $crlf, $error_url, $show_dates = false, $add_semicolon = true, $view = false)
 {
     global $sql_drop_table, $sql_backquotes, $sql_constraints, $sql_constraints_query, $sql_drop_foreign_keys;
     $schema_create = '';
     $auto_increment = '';
     $new_crlf = $crlf;
     if (isset($GLOBALS['sql_compatibility'])) {
         $compat = $GLOBALS['sql_compatibility'];
     } else {
         $compat = 'NONE';
     }
     // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
     $result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_Util::backquote($db) . ' LIKE \'' . PMA_Util::sqlAddSlashes($table, true) . '\'', null, PMA_DBI_QUERY_STORE);
     if ($result != false) {
         if (PMA_DBI_num_rows($result) > 0) {
             $tmpres = PMA_DBI_fetch_assoc($result);
             if (PMA_DRIZZLE && $show_dates) {
                 // Drizzle doesn't give Create_time and Update_time in
                 // SHOW TABLE STATUS, add it
                 $sql = "SELECT\n                            TABLE_CREATION_TIME AS Create_time,\n                            TABLE_UPDATE_TIME AS Update_time\n                        FROM data_dictionary.TABLES\n                        WHERE TABLE_SCHEMA = '" . PMA_Util::sqlAddSlashes($db) . "'\n                          AND TABLE_NAME = '" . PMA_Util::sqlAddSlashes($table) . "'";
                 $tmpres = array_merge(PMA_DBI_fetch_single_row($sql), $tmpres);
             }
             // Here we optionally add the AUTO_INCREMENT next value,
             // but starting with MySQL 5.0.24, the clause is already included
             // in SHOW CREATE TABLE so we'll remove it below
             // It's required for Drizzle because SHOW CREATE TABLE uses
             // the value from table's creation time
             if (isset($GLOBALS['sql_auto_increment']) && !empty($tmpres['Auto_increment'])) {
                 $auto_increment .= ' AUTO_INCREMENT=' . $tmpres['Auto_increment'] . ' ';
             }
             if ($show_dates && isset($tmpres['Create_time']) && !empty($tmpres['Create_time'])) {
                 $schema_create .= $this->_exportComment(__('Creation') . ': ' . PMA_Util::localisedDate(strtotime($tmpres['Create_time'])));
                 $new_crlf = $this->_exportComment() . $crlf;
             }
             if ($show_dates && isset($tmpres['Update_time']) && !empty($tmpres['Update_time'])) {
                 $schema_create .= $this->_exportComment(__('Last update') . ': ' . PMA_Util::localisedDate(strtotime($tmpres['Update_time'])));
                 $new_crlf = $this->_exportComment() . $crlf;
             }
             if ($show_dates && isset($tmpres['Check_time']) && !empty($tmpres['Check_time'])) {
                 $schema_create .= $this->_exportComment(__('Last check') . ': ' . PMA_Util::localisedDate(strtotime($tmpres['Check_time'])));
                 $new_crlf = $this->_exportComment() . $crlf;
             }
         }
         PMA_DBI_free_result($result);
     }
     $schema_create .= $new_crlf;
     // no need to generate a DROP VIEW here, it was done earlier
     if (!empty($sql_drop_table) && !PMA_Table::isView($db, $table)) {
         $schema_create .= 'DROP TABLE IF EXISTS ' . PMA_Util::backquote($table, $sql_backquotes) . ';' . $crlf;
     }
     // Complete table dump,
     // Whether to quote table and column names or not
     // Drizzle always quotes names
     if (!PMA_DRIZZLE) {
         if ($sql_backquotes) {
             PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 1');
         } else {
             PMA_DBI_query('SET SQL_QUOTE_SHOW_CREATE = 0');
         }
     }
     // I don't see the reason why this unbuffered query could cause problems,
     // because SHOW CREATE TABLE returns only one row, and we free the
     // results below. Nonetheless, we got 2 user reports about this
     // (see bug 1562533) so I removed the unbuffered mode.
     // $result = PMA_DBI_query('SHOW CREATE TABLE ' . backquote($db)
     // . '.' . backquote($table), null, PMA_DBI_QUERY_UNBUFFERED);
     //
     // Note: SHOW CREATE TABLE, at least in MySQL 5.1.23, does not
     // produce a displayable result for the default value of a BIT
     // column, nor does the mysqldump command. See MySQL bug 35796
     $result = PMA_DBI_try_query('SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table));
     // an error can happen, for example the table is crashed
     $tmp_error = PMA_DBI_getError();
     if ($tmp_error) {
         return $this->_exportComment(__('in use') . '(' . $tmp_error . ')');
     }
     if ($result != false && ($row = PMA_DBI_fetch_row($result))) {
         $create_query = $row[1];
         unset($row);
         // Convert end of line chars to one that we want (note that MySQL
         // doesn't return query it will accept in all cases)
         if (strpos($create_query, "(\r\n ")) {
             $create_query = str_replace("\r\n", $crlf, $create_query);
         } elseif (strpos($create_query, "(\n ")) {
             $create_query = str_replace("\n", $crlf, $create_query);
         } elseif (strpos($create_query, "(\r ")) {
             $create_query = str_replace("\r", $crlf, $create_query);
         }
         /*
          * Drop database name from VIEW creation.
          *
          * This is a bit tricky, but we need to issue SHOW CREATE TABLE with
          * database name, but we don't want name to show up in CREATE VIEW
          * statement.
          */
         if ($view) {
             $create_query = preg_replace('/' . PMA_Util::backquote($db) . '\\./', '', $create_query);
         }
         // Should we use IF NOT EXISTS?
         // It always must be OFF for MSSQL compatibility mode
         if (isset($GLOBALS['sql_if_not_exists']) && $compat != 'MSSQL') {
             $create_query = preg_replace('/^CREATE TABLE/', 'CREATE TABLE IF NOT EXISTS', $create_query);
         }
         // In MSSQL
         // 1. DATE field doesn't exists, we will use DATETIME instead
         // 2. UNSIGNED attribute doesn't exist
         // 3. No length on INT, TINYINT, SMALLINT, BIGINT and no precision on
         //    FLOAT fields
         // 4. No KEY and INDEX inside CREATE TABLE
         // 5. DOUBLE field doesn't exists, we will use FLOAT instead
         if ($compat == 'MSSQL') {
             // first we need  to replace all lines ended with '" DATE ...,\n'
             // last preg_replace preserve us from situation with date text
             // inside DEFAULT field value
             $create_query = preg_replace("/\" date DEFAULT NULL(,)?\n/", '" datetime DEFAULT NULL$1' . "\n", $create_query);
             $create_query = preg_replace("/\" date NOT NULL(,)?\n/", '" datetime NOT NULL$1' . "\n", $create_query);
             $create_query = preg_replace('/" date NOT NULL DEFAULT \'([^\'])/', '" datetime NOT NULL DEFAULT \'$1', $create_query);
             // next we need to replace all lines ended with ') UNSIGNED ...,'
             // last preg_replace preserve us from situation with unsigned text
             // inside DEFAULT field value
             $create_query = preg_replace("/\\) unsigned NOT NULL(,)?\n/", ') NOT NULL$1' . "\n", $create_query);
             $create_query = preg_replace("/\\) unsigned DEFAULT NULL(,)?\n/", ') DEFAULT NULL$1' . "\n", $create_query);
             $create_query = preg_replace('/\\) unsigned NOT NULL DEFAULT \'([^\'])/', ') NOT NULL DEFAULT \'$1', $create_query);
             // we need to replace all lines ended with
             // '" INT|TINYINT([0-9]{1,}) ...,' last preg_replace preserve us
             // from situation with int([0-9]{1,}) text inside DEFAULT field
             // value
             $create_query = preg_replace('/" (int|tinyint|smallint|bigint)\\([0-9]+\\) DEFAULT NULL(,)?\\n/', '" $1 DEFAULT NULL$2' . "\n", $create_query);
             $create_query = preg_replace('/" (int|tinyint|smallint|bigint)\\([0-9]+\\) NOT NULL(,)?\\n/', '" $1 NOT NULL$2' . "\n", $create_query);
             $create_query = preg_replace('/" (int|tinyint|smallint|bigint)\\([0-9]+\\) NOT NULL DEFAULT \'([^\'])/', '" $1 NOT NULL DEFAULT \'$2', $create_query);
             // we need to replace all lines ended with
             // '" FLOAT|DOUBLE([0-9,]{1,}) ...,'
             // last preg_replace preserve us from situation with
             // float([0-9,]{1,}) text inside DEFAULT field value
             $create_query = preg_replace('/" (float|double)(\\([0-9]+,[0-9,]+\\))? DEFAULT NULL(,)?\\n/', '" float DEFAULT NULL$3' . "\n", $create_query);
             $create_query = preg_replace('/" (float|double)(\\([0-9,]+,[0-9,]+\\))? NOT NULL(,)?\\n/', '" float NOT NULL$3' . "\n", $create_query);
             $create_query = preg_replace('/" (float|double)(\\([0-9,]+,[0-9,]+\\))? NOT NULL DEFAULT \'([^\'])/', '" float NOT NULL DEFAULT \'$3', $create_query);
             // @todo remove indexes from CREATE TABLE
         }
         // Drizzle (checked on 2011.03.13) returns ROW_FORMAT surrounded
         // with quotes, which is not accepted by parser
         if (PMA_DRIZZLE) {
             $create_query = preg_replace('/ROW_FORMAT=\'(\\S+)\'/', 'ROW_FORMAT=$1', $create_query);
         }
         // are there any constraints to cut out?
         if (preg_match('@CONSTRAINT|FOREIGN[\\s]+KEY@', $create_query)) {
             // Split the query into lines, so we can easily handle it.
             // We know lines are separated by $crlf (done few lines above).
             $sql_lines = explode($crlf, $create_query);
             $sql_count = count($sql_lines);
             // lets find first line with constraints
             for ($i = 0; $i < $sql_count; $i++) {
                 if (preg_match('@^[\\s]*(CONSTRAINT|FOREIGN[\\s]+KEY)@', $sql_lines[$i])) {
                     break;
                 }
             }
             // If we really found a constraint
             if ($i != $sql_count) {
                 // remove, from the end of create statement
                 $sql_lines[$i - 1] = preg_replace('@,$@', '', $sql_lines[$i - 1]);
                 // prepare variable for constraints
                 if (!isset($sql_constraints)) {
                     if (isset($GLOBALS['no_constraints_comments'])) {
                         $sql_constraints = '';
                     } else {
                         $sql_constraints = $crlf . $this->_exportComment() . $this->_exportComment(__('Constraints for dumped tables')) . $this->_exportComment();
                     }
                 }
                 // comments for current table
                 if (!isset($GLOBALS['no_constraints_comments'])) {
                     $sql_constraints .= $crlf . $this->_exportComment() . $this->_exportComment(__('Constraints for table') . ' ' . PMA_Util::backquoteCompat($table, $compat)) . $this->_exportComment();
                 }
                 // let's do the work
                 $sql_constraints_query .= 'ALTER TABLE ' . PMA_Util::backquoteCompat($table, $compat) . $crlf;
                 $sql_constraints .= 'ALTER TABLE ' . PMA_Util::backquoteCompat($table, $compat) . $crlf;
                 $sql_drop_foreign_keys .= 'ALTER TABLE ' . PMA_Util::backquoteCompat($db, $compat) . '.' . PMA_Util::backquoteCompat($table, $compat) . $crlf;
                 $first = true;
                 for ($j = $i; $j < $sql_count; $j++) {
                     if (preg_match('@CONSTRAINT|FOREIGN[\\s]+KEY@', $sql_lines[$j])) {
                         if (!$first) {
                             $sql_constraints .= $crlf;
                         }
                         if (strpos($sql_lines[$j], 'CONSTRAINT') === false) {
                             $tmp_str = preg_replace('/(FOREIGN[\\s]+KEY)/', 'ADD \\1', $sql_lines[$j]);
                             $sql_constraints_query .= $tmp_str;
                             $sql_constraints .= $tmp_str;
                         } else {
                             $tmp_str = preg_replace('/(CONSTRAINT)/', 'ADD \\1', $sql_lines[$j]);
                             $sql_constraints_query .= $tmp_str;
                             $sql_constraints .= $tmp_str;
                             preg_match('/(CONSTRAINT)([\\s])([\\S]*)([\\s])/', $sql_lines[$j], $matches);
                             if (!$first) {
                                 $sql_drop_foreign_keys .= ', ';
                             }
                             $sql_drop_foreign_keys .= 'DROP FOREIGN KEY ' . $matches[3];
                         }
                         $first = false;
                     } else {
                         break;
                     }
                 }
                 $sql_constraints .= ';' . $crlf;
                 $sql_constraints_query .= ';';
                 $create_query = implode($crlf, array_slice($sql_lines, 0, $i)) . $crlf . implode($crlf, array_slice($sql_lines, $j, $sql_count - 1));
                 unset($sql_lines);
             }
         }
         $schema_create .= $create_query;
     }
     // remove a possible "AUTO_INCREMENT = value" clause
     // that could be there starting with MySQL 5.0.24
     // in Drizzle it's useless as it contains the value given at table
     // creation time
     $schema_create = preg_replace('/AUTO_INCREMENT\\s*=\\s*([0-9])+/', '', $schema_create);
     $schema_create .= $compat != 'MSSQL' ? $auto_increment : '';
     PMA_DBI_free_result($result);
     return $schema_create . ($add_semicolon ? ';' . $crlf : '');
 }
Пример #29
0
 function PMA_exportStructure($db, $table, $crlf, $error_url, $do_relation = false, $do_comments = false, $do_mime = false, $dates = false, $dummy)
 {
     global $cfgRelation;
     /**
      * Get the unique keys in the table
      */
     $keys_query = 'SHOW KEYS FROM ' . PMA_backquote($table) . ' FROM ' . PMA_backquote($db);
     $keys_result = PMA_DBI_query($keys_query);
     $unique_keys = array();
     while ($key = PMA_DBI_fetch_assoc($keys_result)) {
         if ($key['Non_unique'] == 0) {
             $unique_keys[] = $key['Column_name'];
         }
     }
     PMA_DBI_free_result($keys_result);
     /**
      * Gets fields properties
      */
     PMA_DBI_select_db($db);
     $local_query = 'SHOW FIELDS FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table);
     $result = PMA_DBI_query($local_query);
     $fields_cnt = PMA_DBI_num_rows($result);
     // Check if we can use Relations (Mike Beck)
     if ($do_relation && !empty($cfgRelation['relation'])) {
         // Find which tables are related with the current one and write it in
         // an array
         $res_rel = PMA_getForeigners($db, $table);
         if ($res_rel && count($res_rel) > 0) {
             $have_rel = TRUE;
         } else {
             $have_rel = FALSE;
         }
     } else {
         $have_rel = FALSE;
     }
     // end if
     /**
      * Displays the table structure
      */
     $buffer = $crlf . '%' . $crlf . '% ' . $GLOBALS['strStructure'] . ': ' . $table . $crlf . '%' . $crlf . ' \\begin{longtable}{';
     if (!PMA_exportOutputHandler($buffer)) {
         return FALSE;
     }
     $columns_cnt = 4;
     $alignment = '|l|c|c|c|';
     if ($do_relation && $have_rel) {
         $columns_cnt++;
         $alignment .= 'l|';
     }
     if ($do_comments && ($cfgRelation['commwork'] || PMA_MYSQL_INT_VERSION >= 40100)) {
         $columns_cnt++;
         $alignment .= 'l|';
     }
     if ($do_mime && $cfgRelation['mimework']) {
         $columns_cnt++;
         $alignment .= 'l|';
     }
     $buffer = $alignment . '} ' . $crlf;
     $header = ' \\hline ';
     $header .= '\\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strField'] . '}} & \\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strType'] . '}} & \\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strNull'] . '}} & \\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strDefault'] . '}}';
     if ($do_relation && $have_rel) {
         $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strLinksTo'] . '}}';
     }
     if ($do_comments && ($cfgRelation['commwork'] || PMA_MYSQL_INT_VERSION >= 40100)) {
         $header .= ' & \\multicolumn{1}{|c|}{\\textbf{' . $GLOBALS['strComments'] . '}}';
         $comments = PMA_getComments($db, $table);
     }
     if ($do_mime && $cfgRelation['mimework']) {
         $header .= ' & \\multicolumn{1}{|c|}{\\textbf{MIME}}';
         $mime_map = PMA_getMIME($db, $table, true);
     }
     $local_buffer = PMA_texEscape($table);
     // Table caption for first page and label
     if (isset($GLOBALS['latex_caption'])) {
         $buffer .= ' \\caption{' . str_replace('__TABLE__', PMA_texEscape($table), $GLOBALS['latex_structure_caption']) . '} \\label{' . str_replace('__TABLE__', $table, $GLOBALS['latex_structure_label']) . '} \\\\' . $crlf;
     }
     $buffer .= $header . ' \\\\ \\hline \\hline' . $crlf . '\\endfirsthead' . $crlf;
     // Table caption on next pages
     if (isset($GLOBALS['latex_caption'])) {
         $buffer .= ' \\caption{' . str_replace('__TABLE__', PMA_texEscape($table), $GLOBALS['latex_structure_continued_caption']) . '} \\\\ ' . $crlf;
     }
     $buffer .= $header . ' \\\\ \\hline \\hline \\endhead \\endfoot ' . $crlf;
     if (!PMA_exportOutputHandler($buffer)) {
         return FALSE;
     }
     while ($row = PMA_DBI_fetch_assoc($result)) {
         $type = $row['Type'];
         // reformat mysql query output - staybyte - 9. June 2001
         // loic1: set or enum types: slashes single quotes inside options
         if (eregi('^(set|enum)\\((.+)\\)$', $type, $tmp)) {
             $tmp[2] = substr(ereg_replace('([^,])\'\'', '\\1\\\'', ',' . $tmp[2]), 1);
             $type = $tmp[1] . '(' . str_replace(',', ', ', $tmp[2]) . ')';
             $type_nowrap = '';
             $binary = 0;
             $unsigned = 0;
             $zerofill = 0;
         } else {
             $type_nowrap = ' nowrap="nowrap"';
             $type = eregi_replace('BINARY', '', $type);
             $type = eregi_replace('ZEROFILL', '', $type);
             $type = eregi_replace('UNSIGNED', '', $type);
             if (empty($type)) {
                 $type = '&nbsp;';
             }
             $binary = eregi('BINARY', $row['Type']);
             $unsigned = eregi('UNSIGNED', $row['Type']);
             $zerofill = eregi('ZEROFILL', $row['Type']);
         }
         if (!isset($row['Default'])) {
             if ($row['Null'] != '') {
                 $row['Default'] = 'NULL';
             }
         } else {
             $row['Default'] = $row['Default'];
         }
         $field_name = $row['Field'];
         $local_buffer = $field_name . "" . $type . "" . ($row['Null'] == '' ? $GLOBALS['strNo'] : $GLOBALS['strYes']) . "" . (isset($row['Default']) ? $row['Default'] : '');
         if ($do_relation && $have_rel) {
             $local_buffer .= "";
             if (isset($res_rel[$field_name])) {
                 $local_buffer .= $res_rel[$field_name]['foreign_table'] . ' (' . $res_rel[$field_name]['foreign_field'] . ')';
             }
         }
         if ($do_comments && $cfgRelation['commwork']) {
             $local_buffer .= "";
             if (isset($comments[$field_name])) {
                 $local_buffer .= $comments[$field_name];
             }
         }
         if ($do_mime && $cfgRelation['mimework']) {
             $local_buffer .= "";
             if (isset($mime_map[$field_name])) {
                 $local_buffer .= str_replace('_', '/', $mime_map[$field_name]['mimetype']);
             }
         }
         $local_buffer = PMA_texEscape($local_buffer);
         if ($row['Key'] == 'PRI') {
             $pos = strpos($local_buffer, "");
             $local_buffer = '\\textit{' . substr($local_buffer, 0, $pos) . '}' . substr($local_buffer, $pos);
         }
         if (in_array($field_name, $unique_keys)) {
             $pos = strpos($local_buffer, "");
             $local_buffer = '\\textbf{' . substr($local_buffer, 0, $pos) . '}' . substr($local_buffer, $pos);
         }
         $buffer = str_replace("", ' & ', $local_buffer);
         $buffer .= ' \\\\ \\hline ' . $crlf;
         if (!PMA_exportOutputHandler($buffer)) {
             return FALSE;
         }
     }
     // end while
     PMA_DBI_free_result($result);
     $buffer = ' \\end{longtable}' . $crlf;
     return PMA_exportOutputHandler($buffer);
 }
Пример #30
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);
                             }
             */
         }
     }
 }