Exemplo n.º 1
0
 /**
  * Outputs export header
  *
  * @return  bool        Whether it suceeded
  *
  * @access  public
  */
 function PMA_exportHeader()
 {
     global $crlf;
     global $cfg;
     global $what;
     global $db;
     global $table;
     global $tables;
     $export_struct = isset($GLOBALS[$what . '_export_struc']) ? true : false;
     $export_data = isset($GLOBALS[$what . '_export_contents']) ? true : false;
     if ($GLOBALS['output_charset_conversion']) {
         $charset = $GLOBALS['charset_of_file'];
     } else {
         $charset = $GLOBALS['charset'];
     }
     $head = '<?xml version="1.0" encoding="' . $charset . '"?>' . $crlf . '<!--' . $crlf . '- phpMyAdmin XML Dump' . $crlf . '- version ' . PMA_VERSION . $crlf . '- http://www.phpmyadmin.net' . $crlf . '-' . $crlf . '- ' . $GLOBALS['strHost'] . ': ' . $cfg['Server']['host'];
     if (!empty($cfg['Server']['port'])) {
         $head .= ':' . $cfg['Server']['port'];
     }
     $head .= $crlf . '- ' . $GLOBALS['strGenTime'] . ': ' . PMA_localisedDate() . $crlf . '- ' . $GLOBALS['strServerVersion'] . ': ' . substr(PMA_MYSQL_INT_VERSION, 0, 1) . '.' . (int) substr(PMA_MYSQL_INT_VERSION, 1, 2) . '.' . (int) substr(PMA_MYSQL_INT_VERSION, 3) . $crlf . '- ' . $GLOBALS['strPHPVersion'] . ': ' . phpversion() . $crlf . '-->' . $crlf . $crlf;
     $head .= '<pma_xml_export version="1.0"' . ($export_struct ? ' xmlns:pma="http://www.phpmyadmin.net/some_doc_url/"' : '') . '>' . $crlf;
     if ($export_struct) {
         $result = PMA_DBI_fetch_result('SELECT `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME` FROM `information_schema`.`SCHEMATA` WHERE `SCHEMA_NAME` = \'' . $db . '\' LIMIT 1');
         $db_collation = $result[0]['DEFAULT_COLLATION_NAME'];
         $db_charset = $result[0]['DEFAULT_CHARACTER_SET_NAME'];
         $head .= '    <!--' . $crlf;
         $head .= '    - Structure schemas' . $crlf;
         $head .= '    -->' . $crlf;
         $head .= '    <pma:structure_schemas>' . $crlf;
         $head .= '        <pma:database name="' . $db . '" collation="' . $db_collation . '" charset="' . $db_charset . '">' . $crlf;
         if (count($tables) == 0) {
             $tables[] = $table;
         }
         foreach ($tables as $table) {
             // Export tables and views
             $result = PMA_DBI_fetch_result('SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table), 0);
             $tbl = $result[$table][1];
             $is_view = PMA_isView($db, $table);
             if ($is_view) {
                 $type = 'view';
             } else {
                 $type = 'table';
             }
             if ($is_view && !isset($GLOBALS[$what . '_export_views'])) {
                 continue;
             }
             if (!$is_view && !isset($GLOBALS[$what . '_export_tables'])) {
                 continue;
             }
             $head .= '            <pma:' . $type . ' name="' . $table . '">' . $crlf;
             $tbl = "                " . $tbl;
             $tbl = str_replace("\n", "\n                ", $tbl);
             $head .= $tbl . ';' . $crlf;
             $head .= '            </pma:' . $type . '>' . $crlf;
             if (isset($GLOBALS[$what . '_export_triggers']) && $GLOBALS[$what . '_export_triggers']) {
                 // Export triggers
                 $triggers = PMA_DBI_get_triggers($db, $table);
                 if ($triggers) {
                     foreach ($triggers as $trigger) {
                         $code = $trigger['create'];
                         $head .= '            <pma:trigger name="' . $trigger['name'] . '">' . $crlf;
                         // Do some formatting
                         $code = substr(rtrim($code), 0, -3);
                         $code = "                " . $code;
                         $code = str_replace("\n", "\n                ", $code);
                         $head .= $code . $crlf;
                         $head .= '            </pma:trigger>' . $crlf;
                     }
                     unset($trigger);
                     unset($triggers);
                 }
             }
         }
         if (isset($GLOBALS[$what . '_export_functions']) && $GLOBALS[$what . '_export_functions']) {
             // Export functions
             $functions = PMA_DBI_get_procedures_or_functions($db, 'FUNCTION');
             if ($functions) {
                 foreach ($functions as $function) {
                     $head .= '            <pma:function name="' . $function . '">' . $crlf;
                     // Do some formatting
                     $sql = PMA_DBI_get_definition($db, 'FUNCTION', $function);
                     $sql = rtrim($sql);
                     $sql = "                " . $sql;
                     $sql = str_replace("\n", "\n                ", $sql);
                     $head .= $sql . $crlf;
                     $head .= '            </pma:function>' . $crlf;
                 }
                 unset($create_func);
                 unset($function);
                 unset($functions);
             }
         }
         if (isset($GLOBALS[$what . '_export_procedures']) && $GLOBALS[$what . '_export_procedures']) {
             // Export procedures
             $procedures = PMA_DBI_get_procedures_or_functions($db, 'PROCEDURE');
             if ($procedures) {
                 foreach ($procedures as $procedure) {
                     $head .= '            <pma:procedure name="' . $procedure . '">' . $crlf;
                     // Do some formatting
                     $sql = PMA_DBI_get_definition($db, 'PROCEDURE', $procedure);
                     $sql = rtrim($sql);
                     $sql = "                " . $sql;
                     $sql = str_replace("\n", "\n                ", $sql);
                     $head .= $sql . $crlf;
                     $head .= '            </pma:procedure>' . $crlf;
                 }
                 unset($create_proc);
                 unset($procedure);
                 unset($procedures);
             }
         }
         unset($result);
         $head .= '        </pma:database>' . $crlf;
         $head .= '    </pma:structure_schemas>' . $crlf;
         if ($export_data) {
             $head .= $crlf;
         }
     }
     return PMA_exportOutputHandler($head);
 }
Exemplo n.º 2
0
/**
 * Builds and executes SQL statements to create the database and tables
 * as necessary, as well as insert all the data.
 *
 * @author  Derek Schaefer (derek.schaefer@gmail.com)
 *
 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
 *
 * @access  public
 *
 * @uses    TBL_NAME
 * @uses    COL_NAMES
 * @uses    ROWS
 * @uses    TYPES
 * @uses    SIZES
 * @uses    strcmp()
 * @uses    count()
 * @uses    ereg()
 * @uses    ereg_replace()
 * @uses    PMA_isView()
 * @uses    PMA_backquote()
 * @uses    PMA_importRunQuery()
 * @uses    PMA_generate_common_url()
 * @uses    PMA_Message::notice()
 * @param   string  $db_name                 Name of the database
 * @param   array   &$tables                 Array of tables for the specified database
 * @param   array   &$analyses = NULL        Analyses of the tables
 * @param   array   &$additional_sql = NULL  Additional SQL statements to be executed
 * @param   array   $options = NULL          Associative array of options
 * @return  void
 */
function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL)
{
    /* Take care of the options */
    if (isset($options['db_collation'])) {
        $collation = $options['db_collation'];
    } else {
        $collation = "utf8_general_ci";
    }
    if (isset($options['db_charset'])) {
        $charset = $options['db_charset'];
    } else {
        $charset = "utf8";
    }
    if (isset($options['create_db'])) {
        $create_db = $options['create_db'];
    } else {
        $create_db = true;
    }
    /* Create SQL code to handle the database */
    $sql = array();
    if ($create_db) {
        $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
    }
    /**
     * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
     *
     * $sql[] = "USE " . PMA_backquote($db_name);
     */
    /* Execute the SQL statements create above */
    $sql_len = count($sql);
    for ($i = 0; $i < $sql_len; ++$i) {
        PMA_importRunQuery($sql[$i], $sql[$i]);
    }
    /* No longer needed */
    unset($sql);
    /* Run the $additional_sql statements supplied by the caller plug-in */
    if ($additional_sql != NULL) {
        /* Clean the SQL first */
        $additional_sql_len = count($additional_sql);
        /**
         * Only match tables for now, because CREATE IF NOT EXISTS
         * syntax is lacking or nonexisting for views, triggers,
         * functions, and procedures.
         *
         * See: http://bugs.mysql.com/bug.php?id=15287
         *
         * To the best of my knowledge this is still an issue.
         *
         * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
         */
        $pattern = 'CREATE .*(TABLE)';
        $replacement = 'CREATE \\1 IF NOT EXISTS';
        /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
        for ($i = 0; $i < $additional_sql_len; ++$i) {
            $additional_sql[$i] = ereg_replace($pattern, $replacement, $additional_sql[$i]);
            /* Execute the resulting statements */
            PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
        }
    }
    if ($analyses != NULL) {
        $type_array = array(NONE => "NULL", VARCHAR => "varchar", INT => "int", DECIMAL => "decimal");
        /* TODO: Do more checking here to make sure they really are matched */
        if (count($tables) != count($analyses)) {
            exit;
        }
        /* Create SQL code to create the tables */
        $tempSQLStr = "";
        $num_tables = count($tables);
        for ($i = 0; $i < $num_tables; ++$i) {
            $num_cols = count($tables[$i][COL_NAMES]);
            $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
            for ($j = 0; $j < $num_cols; ++$j) {
                $size = $analyses[$i][SIZES][$j];
                if ((int) $size == 0) {
                    $size = 10;
                }
                $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " " . $type_array[$analyses[$i][TYPES][$j]] . "(" . $size . ")";
                if ($j != count($tables[$i][COL_NAMES]) - 1) {
                    $tempSQLStr .= ", ";
                }
            }
            $tempSQLStr .= ") ENGINE=MyISAM;";
            /**
             * Each SQL statement is executed immediately
             * after it is formed so that we don't have
             * to store them in a (possibly large) buffer
             */
            PMA_importRunQuery($tempSQLStr, $tempSQLStr);
        }
    }
    /**
     * Create the SQL statements to insert all the data
     *
     * Only one insert query is formed for each table
     */
    $tempSQLStr = "";
    $col_count = 0;
    $num_tables = count($tables);
    for ($i = 0; $i < $num_tables; ++$i) {
        $num_cols = count($tables[$i][COL_NAMES]);
        $num_rows = count($tables[$i][ROWS]);
        $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
        for ($m = 0; $m < $num_cols; ++$m) {
            $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
            if ($m != $num_cols - 1) {
                $tempSQLStr .= ", ";
            }
        }
        $tempSQLStr .= ") VALUES ";
        for ($j = 0; $j < $num_rows; ++$j) {
            $tempSQLStr .= "(";
            for ($k = 0; $k < $num_cols; ++$k) {
                if ($analyses != NULL) {
                    $is_varchar = $analyses[$i][TYPES][$col_count] === VARCHAR;
                } else {
                    $is_varchar = !is_numeric($tables[$i][ROWS][$j][$k]);
                }
                /* Don't put quotes around NULL fields */
                if (!strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
                    $is_varchar = false;
                }
                $tempSQLStr .= $is_varchar ? "'" : "";
                $tempSQLStr .= str_replace("'", "\\'", (string) $tables[$i][ROWS][$j][$k]);
                $tempSQLStr .= $is_varchar ? "'" : "";
                if ($k != $num_cols - 1) {
                    $tempSQLStr .= ", ";
                }
                if ($col_count == $num_cols - 1) {
                    $col_count = 0;
                } else {
                    $col_count++;
                }
                /* Delete the cell after we are done with it */
                unset($tables[$i][ROWS][$j][$k]);
            }
            $tempSQLStr .= ")";
            if ($j != $num_rows - 1) {
                $tempSQLStr .= ",\n ";
            }
            $col_count = 0;
            /* Delete the row after we are done with it */
            unset($tables[$i][ROWS][$j]);
        }
        $tempSQLStr .= ";";
        /**
         * Each SQL statement is executed immediately
         * after it is formed so that we don't have
         * to store them in a (possibly large) buffer
         */
        PMA_importRunQuery($tempSQLStr, $tempSQLStr);
    }
    /* No longer needed */
    unset($tempSQLStr);
    /**
     * A work in progress
     */
    /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
    $view_pattern = 'VIEW `[^`]+`\\.`([^`]+)';
    $table_pattern = 'CREATE TABLE IF NOT EXISTS `([^`]+)`';
    /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
    $regs = array();
    $inTables = false;
    $additional_sql_len = count($additional_sql);
    for ($i = 0; $i < $additional_sql_len; ++$i) {
        ereg($view_pattern, $additional_sql[$i], $regs);
        if (count($regs) == 0) {
            ereg($table_pattern, $additional_sql[$i], $regs);
        }
        if (count($regs)) {
            for ($n = 0; $n < $num_tables; ++$n) {
                if (!strcmp($regs[1], $tables[$n][TBL_NAME])) {
                    $inTables = true;
                    break;
                }
            }
            if (!$inTables) {
                $tables[] = array(TBL_NAME => $regs[1]);
            }
        }
        /* Reset the array */
        $regs = array();
        $inTables = false;
    }
    $params = array('db' => (string) $db_name);
    $db_url = 'db_structure.php' . PMA_generate_common_url($params);
    $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
    $message = '<br /><br />';
    $message .= '<strong>' . $GLOBALS['strImportNoticePt1'] . '</strong><br />';
    $message .= '<ul><li>' . $GLOBALS['strImportNoticePt2'] . '</li>';
    $message .= '<li>' . $GLOBALS['strImportNoticePt3'] . '</li>';
    $message .= '<li>' . $GLOBALS['strImportNoticePt4'] . '</li>';
    $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>', $db_url, $GLOBALS['strGoToDatabase'] . ': ' . PMA_backquote($db_name), $db_name, $db_ops_url, $GLOBALS['strEdit'] . ' ' . PMA_backquote($db_name) . ' ' . $GLOBALS['strSettings']);
    $message .= '<ul>';
    unset($params);
    $num_tables = count($tables);
    for ($i = 0; $i < $num_tables; ++$i) {
        $params = array('db' => (string) $db_name, 'table' => (string) $tables[$i][TBL_NAME]);
        $tbl_url = 'sql.php' . PMA_generate_common_url($params);
        $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
        $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
        unset($params);
        if (!PMA_isView($db_name, $tables[$i][TBL_NAME])) {
            $message .= sprintf('<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strStructure'] . '</a>) (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>', $tbl_url, $GLOBALS['strGoToTable'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]), $tables[$i][TBL_NAME], $tbl_struct_url, PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strStructureLC'], $tbl_ops_url, $GLOBALS['strEdit'] . ' ' . PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strSettings']);
        } else {
            $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>', $tbl_url, $GLOBALS['strGoToView'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]), $tables[$i][TBL_NAME]);
        }
    }
    $message .= '</ul></ul>';
    global $import_notice;
    $import_notice = $message;
    unset($tables);
}