error() public static method

shorthand for getting a simple error message
public static error ( string $string = '' ) : Message
$string string A localized string e.g. __('Error')
return Message
コード例 #1
0
ファイル: rte_export.lib.php プロジェクト: netroby/phpmyadmin
/**
 * This function is called from one of the other functions in this file
 * and it completes the handling of the export functionality.
 *
 * @param string $export_data The SQL query to create the requested item
 *
 * @return void
 */
function PMA_RTE_handleExport($export_data)
{
    global $db;
    $item_name = htmlspecialchars(PMA\libraries\Util::backquote($_GET['item_name']));
    if ($export_data !== false) {
        $export_data = htmlspecialchars(trim($export_data));
        $title = sprintf(PMA_RTE_getWord('export'), $item_name);
        if ($GLOBALS['is_ajax_request'] == true) {
            $response = PMA\libraries\Response::getInstance();
            $response->addJSON('message', $export_data);
            $response->addJSON('title', $title);
            exit;
        } else {
            $export_data = '<textarea cols="40" rows="15" style="width: 100%;">' . $export_data . '</textarea>';
            echo "<fieldset>\n" . "<legend>{$title}</legend>\n" . $export_data . "</fieldset>\n";
        }
    } else {
        $_db = htmlspecialchars(PMA\libraries\Util::backquote($db));
        $message = __('Error in processing request:') . ' ' . sprintf(PMA_RTE_getWord('not_found'), $item_name, $_db);
        $response = Message::error($message);
        if ($GLOBALS['is_ajax_request'] == true) {
            $response = PMA\libraries\Response::getInstance();
            $response->setRequestStatus(false);
            $response->addJSON('message', $message);
            exit;
        } else {
            $response->display();
        }
    }
}
コード例 #2
0
/**
 * Send TRI or EVN editor via ajax or by echoing.
 *
 * @param string $type      TRI or EVN
 * @param string $mode      Editor mode 'add' or 'edit'
 * @param array  $item      Data necessary to create the editor
 * @param string $title     Title of the editor
 * @param string $db        Database
 * @param string $operation Operation 'change' or ''
 *
 * @return void
 */
function PMA_RTE_sendEditor($type, $mode, $item, $title, $db, $operation = null)
{
    if ($item !== false) {
        // Show form
        if ($type == 'TRI') {
            $editor = PMA_TRI_getEditorForm($mode, $item);
        } else {
            // EVN
            $editor = PMA_EVN_getEditorForm($mode, $operation, $item);
        }
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            $response->addJSON('message', $editor);
            $response->addJSON('title', $title);
        } else {
            echo "\n\n<h2>{$title}</h2>\n\n{$editor}";
            unset($_POST);
        }
        exit;
    } else {
        $message = __('Error in processing request:') . ' ';
        $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA\libraries\Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA\libraries\Util::backquote($db)));
        $message = Message::error($message);
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            $response->setRequestStatus(false);
            $response->addJSON('message', $message);
            exit;
        } else {
            $message->display();
        }
    }
}
コード例 #3
0
ファイル: ImportLdi.php プロジェクト: phpmyadmin/phpmyadmin
 /**
  * Handles the whole import logic
  *
  * @param array &$sql_data 2-element array with sql data
  *
  * @return void
  */
 public function doImport(&$sql_data = array())
 {
     global $finished, $import_file, $charset_conversion, $table;
     global $ldi_local_option, $ldi_replace, $ldi_ignore, $ldi_terminated, $ldi_enclosed, $ldi_escaped, $ldi_new_line, $skip_queries, $ldi_columns;
     $compression = $GLOBALS['import_handle']->getCompression();
     if ($import_file == 'none' || $compression != 'none' || $charset_conversion) {
         // We handle only some kind of data!
         $GLOBALS['message'] = PMA\libraries\Message::error(__('This plugin does not support compressed imports!'));
         $GLOBALS['error'] = true;
         return;
     }
     $sql = 'LOAD DATA';
     if (isset($ldi_local_option)) {
         $sql .= ' LOCAL';
     }
     $sql .= ' INFILE \'' . $GLOBALS['dbi']->escapeString($import_file) . '\'';
     if (isset($ldi_replace)) {
         $sql .= ' REPLACE';
     } elseif (isset($ldi_ignore)) {
         $sql .= ' IGNORE';
     }
     $sql .= ' INTO TABLE ' . PMA\libraries\Util::backquote($table);
     if (strlen($ldi_terminated) > 0) {
         $sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\'';
     }
     if (strlen($ldi_enclosed) > 0) {
         $sql .= ' ENCLOSED BY \'' . $GLOBALS['dbi']->escapeString($ldi_enclosed) . '\'';
     }
     if (strlen($ldi_escaped) > 0) {
         $sql .= ' ESCAPED BY \'' . $GLOBALS['dbi']->escapeString($ldi_escaped) . '\'';
     }
     if (strlen($ldi_new_line) > 0) {
         if ($ldi_new_line == 'auto') {
             $ldi_new_line = PMA\libraries\Util::whichCrlf() == "\n" ? '\\n' : '\\r\\n';
         }
         $sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\'';
     }
     if ($skip_queries > 0) {
         $sql .= ' IGNORE ' . $skip_queries . ' LINES';
         $skip_queries = 0;
     }
     if (strlen($ldi_columns) > 0) {
         $sql .= ' (';
         $tmp = preg_split('/,( ?)/', $ldi_columns);
         $cnt_tmp = count($tmp);
         for ($i = 0; $i < $cnt_tmp; $i++) {
             if ($i > 0) {
                 $sql .= ', ';
             }
             /* Trim also `, if user already included backquoted fields */
             $sql .= PMA\libraries\Util::backquote(trim($tmp[$i], " \t\r\n\v`"));
         }
         // end for
         $sql .= ')';
     }
     PMA_importRunQuery($sql, $sql, $sql_data);
     PMA_importRunQuery('', '', $sql_data);
     $finished = true;
 }
コード例 #4
0
/**
 * Function to get html for displaying the schema export
 *
 * @param string $db   database name
 * @param int    $page the page to be exported
 *
 * @return string
 */
function PMA_getHtmlForSchemaExport($db, $page)
{
    /* Scan for schema plugins */
    /* @var $export_list SchemaPlugin[] */
    $export_list = PMA_getPlugins("schema", 'libraries/plugins/schema/', null);
    /* Fail if we didn't find any schema plugin */
    if (empty($export_list)) {
        return Message::error(__('Could not load schema plugins, please check your installation!'))->getDisplay();
    }
    return PMA\libraries\Template::get('database/designer/schema_export')->render(array('db' => $db, 'page' => $page, 'export_list' => $export_list));
}
コード例 #5
0
 /**
  * Index action
  *
  * @return void
  */
 public function indexAction()
 {
     $request = Request::getInstance();
     if ($request->isAjax() && isset($_REQUEST['type']) && $_REQUEST['type'] === 'getval') {
         $this->getValueAction();
         return;
     }
     if ($request->isAjax() && isset($_REQUEST['type']) && $_REQUEST['type'] === 'setval') {
         $this->setValueAction();
         return;
     }
     include 'libraries/server_common.inc.php';
     $header = $this->response->getHeader();
     $scripts = $header->getScripts();
     $scripts->addFile('server_variables.js');
     /**
      * Displays the sub-page heading
      */
     $doc_link = Util::showMySQLDocu('server_system_variables');
     $this->response->addHtml(PMA_getHtmlForSubPageHeader('variables', $doc_link));
     /**
      * Sends the queries and buffers the results
      */
     $serverVarsResult = $this->dbi->tryQuery('SHOW SESSION VARIABLES;');
     if ($serverVarsResult !== false) {
         $serverVarsSession = array();
         while ($arr = $this->dbi->fetchRow($serverVarsResult)) {
             $serverVarsSession[$arr[0]] = $arr[1];
         }
         $this->dbi->freeResult($serverVarsResult);
         $serverVars = $this->dbi->fetchResult('SHOW GLOBAL VARIABLES;', 0, 1);
         /**
          * Link templates
          */
         $this->response->addHtml($this->_getHtmlForLinkTemplates());
         /**
          * Displays the page
          */
         $this->response->addHtml($this->_getHtmlForServerVariables($serverVars, $serverVarsSession));
     } else {
         /**
          * Display the error message
          */
         $this->response->addHTML(Message::error(sprintf(__('Not enough privilege to view server variables and ' . 'settings. %s'), Util::showMySQLDocu('server-system-variables', false, 'sysvar_show_compatibility_56')))->getDisplay());
     }
 }
コード例 #6
0
ファイル: Navigation.php プロジェクト: poush/phpmyadmin
 /**
  * Renders the navigation tree, or part of it
  *
  * @return string The navigation tree
  */
 public function getDisplay()
 {
     /* Init */
     $retval = '';
     if (!Response::getInstance()->isAjax()) {
         $header = new NavigationHeader();
         $retval = $header->getDisplay();
     }
     $tree = new NavigationTree();
     if (!Response::getInstance()->isAjax() || !empty($_REQUEST['full']) || !empty($_REQUEST['reload'])) {
         if ($GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
             // provide database tree in navigation
             $navRender = $tree->renderState();
         } else {
             // provide legacy pre-4.0 navigation
             $navRender = $tree->renderDbSelect();
         }
     } else {
         $navRender = $tree->renderPath();
     }
     if (!$navRender) {
         $retval .= Message::error(__('An error has occurred while loading the navigation display'))->getDisplay();
     } else {
         $retval .= $navRender;
     }
     if (!Response::getInstance()->isAjax()) {
         // closes the tags that were opened by the navigation header
         $retval .= '</div>';
         // pma_navigation_tree
         $retval .= '<div id="pma_navi_settings_container">';
         if (!defined('PMA_DISABLE_NAVI_SETTINGS')) {
             $retval .= PageSettings::getNaviSettings();
         }
         $retval .= '</div>';
         //pma_navi_settings_container
         $retval .= '</div>';
         // pma_navigation_content
         $retval .= $this->_getDropHandler();
         $retval .= '</div>';
         // pma_navigation
     }
     return $retval;
 }
コード例 #7
0
 /**
  * Displays authentication form
  *
  * @return boolean
  */
 public function authForm()
 {
     if (empty($GLOBALS['cfg']['Server']['auth_http_realm'])) {
         if (empty($GLOBALS['cfg']['Server']['verbose'])) {
             $server_message = $GLOBALS['cfg']['Server']['host'];
         } else {
             $server_message = $GLOBALS['cfg']['Server']['verbose'];
         }
         $realm_message = 'phpMyAdmin ' . $server_message;
     } else {
         $realm_message = $GLOBALS['cfg']['Server']['auth_http_realm'];
     }
     $response = Response::getInstance();
     // remove non US-ASCII to respect RFC2616
     $realm_message = preg_replace('/[^\\x20-\\x7e]/i', '', $realm_message);
     $response->header('WWW-Authenticate: Basic realm="' . $realm_message . '"');
     $response->header('HTTP/1.0 401 Unauthorized');
     if (php_sapi_name() !== 'cgi-fcgi') {
         $response->header('status: 401 Unauthorized');
     }
     /* HTML header */
     $footer = $response->getFooter();
     $footer->setMinimal();
     $header = $response->getHeader();
     $header->setTitle(__('Access denied!'));
     $header->disableMenuAndConsole();
     $header->setBodyId('loginform');
     $response->addHTML('<h1>');
     $response->addHTML(sprintf(__('Welcome to %s'), ' phpMyAdmin'));
     $response->addHTML('</h1>');
     $response->addHTML('<h3>');
     $response->addHTML(Message::error(__('Wrong username/password. Access denied.')));
     $response->addHTML('</h3>');
     if (@file_exists(CUSTOM_FOOTER_FILE)) {
         include CUSTOM_FOOTER_FILE;
     }
     if (!defined('TESTSUITE')) {
         exit;
     } else {
         return false;
     }
 }
コード例 #8
0
/**
 * Handle request to create or edit a routine
 *
 * @param array  $errors Errors
 * @param string $db     DB name
 *
 * @return array
 */
function PMA_RTN_handleRequestCreateOrEdit($errors, $db)
{
    if (empty($_REQUEST['editor_process_add']) && empty($_REQUEST['editor_process_edit'])) {
        return $errors;
    }
    $sql_query = '';
    $routine_query = PMA_RTN_getQueryFromRequest();
    if (!count($errors)) {
        // set by PMA_RTN_getQueryFromRequest()
        // Execute the created query
        if (!empty($_REQUEST['editor_process_edit'])) {
            $isProcOrFunc = in_array($_REQUEST['item_original_type'], array('PROCEDURE', 'FUNCTION'));
            if (!$isProcOrFunc) {
                $errors[] = sprintf(__('Invalid routine type: "%s"'), htmlspecialchars($_REQUEST['item_original_type']));
            } else {
                // Backup the old routine, in case something goes wrong
                $create_routine = $GLOBALS['dbi']->getDefinition($db, $_REQUEST['item_original_type'], $_REQUEST['item_original_name']);
                $privilegesBackup = PMA_RTN_backupPrivileges();
                $drop_routine = "DROP {$_REQUEST['item_original_type']} " . PMA\libraries\Util::backquote($_REQUEST['item_original_name']) . ";\n";
                $result = $GLOBALS['dbi']->tryQuery($drop_routine);
                if (!$result) {
                    $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($drop_routine)) . '<br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    list($newErrors, $message) = PMA_RTN_createRoutine($routine_query, $create_routine, $privilegesBackup);
                    if (empty($newErrors)) {
                        $sql_query = $drop_routine . $routine_query;
                    } else {
                        $errors = array_merge($errors, $newErrors);
                    }
                    unset($newErrors);
                    if (null === $message) {
                        unset($message);
                    }
                }
            }
        } else {
            // 'Add a new routine' mode
            $result = $GLOBALS['dbi']->tryQuery($routine_query);
            if (!$result) {
                $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($routine_query)) . '<br /><br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
            } else {
                $message = PMA\libraries\Message::success(__('Routine %1$s has been created.'));
                $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
                $sql_query = $routine_query;
            }
        }
    }
    if (count($errors)) {
        $message = PMA\libraries\Message::error(__('One or more errors have occurred while' . ' processing your request:'));
        $message->addString('<ul>');
        foreach ($errors as $string) {
            $message->addString('<li>' . $string . '</li>');
        }
        $message->addString('</ul>');
    }
    $output = PMA\libraries\Util::getMessage($message, $sql_query);
    if (!$GLOBALS['is_ajax_request']) {
        return $errors;
    }
    $response = PMA\libraries\Response::getInstance();
    if (!$message->isSuccess()) {
        $response->setRequestStatus(false);
        $response->addJSON('message', $output);
        exit;
    }
    $routines = $GLOBALS['dbi']->getRoutines($db, $_REQUEST['item_type'], $_REQUEST['item_name']);
    $routine = $routines[0];
    $response->addJSON('name', htmlspecialchars(mb_strtoupper($_REQUEST['item_name'])));
    $response->addJSON('new_row', PMA_RTN_getRowForList($routine));
    $response->addJSON('insert', !empty($routine));
    $response->addJSON('message', $output);
    exit;
}
コード例 #9
0
                } else {
                    $error = $result;
                }
                exit;
            }
        }
    }
}
$response = Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('config.js');
require 'libraries/user_preferences.inc.php';
if ($error) {
    if (!$error instanceof Message) {
        $error = Message::error($error);
    }
    $error->display();
}
?>
<script type="text/javascript">
<?php 
PMA_printJsValue("PMA_messages['strSavedOn']", __('Saved on: @DATE@'));
?>
</script>
<div id="maincontainer">
    <div id="main_pane_left">
        <div class="group">
<?php 
echo '<h2>', __('Import'), '</h2>', '<form class="group-cnt prefs-form disableAjax" name="prefs_import"', ' action="prefs_manage.php" method="post" enctype="multipart/form-data">', Util::generateHiddenMaxFileSize($GLOBALS['max_upload_size']), PMA_URL_getHiddenInputs(), '<input type="hidden" name="json" value="" />', '<input type="radio" id="import_text_file" name="import_type"', ' value="text_file" checked="checked" />', '<label for="import_text_file">' . __('Import from file') . '</label>', '<div id="opts_import_text_file" class="prefsmanage_opts">', '<label for="input_import_file">', __('Browse your computer:'), '</label>', '<input type="file" name="import_file" id="input_import_file" />', '</div>', '<input type="radio" id="import_local_storage" name="import_type"', ' value="local_storage" disabled="disabled" />', '<label for="import_local_storage">', __('Import from browser\'s storage'), '</label>', '<div id="opts_import_local_storage" class="prefsmanage_opts disabled">', '<div class="localStorage-supported">', __('Settings will be imported from your browser\'s local storage.'), '<br />', '<div class="localStorage-exists">', __('Saved on: @DATE@'), '</div>', '<div class="localStorage-empty">';
Message::notice(__('You have no saved settings!'))->display();
コード例 #10
0
         */
        include_once 'libraries/parse_analyze.lib.php';
        list($analyzed_sql_results, $db, $table) = PMA_parseAnalyze($sql_query, $db);
        // @todo: possibly refactor
        extract($analyzed_sql_results);
        PMA_executeQueryAndSendQueryResponse($analyzed_sql_results, false, $db, $table, null, null, null, null, null, null, $goto, $pmaThemeImage, null, null, $query_type, $sql_query, $selected, null);
    } elseif (!$run_parts) {
        $GLOBALS['dbi']->selectDb($db);
        $result = $GLOBALS['dbi']->tryQuery($sql_query);
        if ($result && !empty($sql_query_views)) {
            $sql_query .= ' ' . $sql_query_views . ';';
            $result = $GLOBALS['dbi']->tryQuery($sql_query_views);
            unset($sql_query_views);
        }
        if (!$result) {
            $message = Message::error($GLOBALS['dbi']->getError());
        }
    }
    if ($query_type == 'drop_tbl' || $query_type == 'empty_tbl' || $query_type == 'row_delete') {
        PMA\libraries\Util::handleDisableFKCheckCleanup($default_fk_check_value);
    }
    if ($rebuild_database_list) {
        // avoid a problem with the database list navigator
        // when dropping a db from server_databases
        $GLOBALS['pma']->databases->build();
    }
} else {
    if (isset($submit_mult) && ($submit_mult == 'sync_unique_columns_central_list' || $submit_mult == 'delete_unique_columns_central_list' || $submit_mult == 'add_to_central_columns' || $submit_mult == 'remove_from_central_columns' || $submit_mult == 'make_consistent_with_central_list')) {
        if (isset($centralColsError) && $centralColsError !== true) {
            $message = $centralColsError;
        } else {
コード例 #11
0
ファイル: core.lib.php プロジェクト: nijel/phpmyadmin
/**
 * displays the given error message on phpMyAdmin error page in foreign language,
 * ends script execution and closes session
 *
 * loads language file if not loaded already
 *
 * @param string       $error_message  the error message or named error message
 * @param string|array $message_args   arguments applied to $error_message
 * @param boolean      $delete_session whether to delete session cookie
 *
 * @return void
 */
function PMA_fatalError($error_message, $message_args = null, $delete_session = true)
{
    /* Use format string if applicable */
    if (is_string($message_args)) {
        $error_message = sprintf($error_message, $message_args);
    } elseif (is_array($message_args)) {
        $error_message = vsprintf($error_message, $message_args);
    }
    $response = Response::getInstance();
    if ($response->isAjax()) {
        $response->setRequestStatus(false);
        $response->addJSON('message', PMA\libraries\Message::error($error_message));
    } else {
        $error_message = strtr($error_message, array('<br />' => '[br]'));
        // these variables are used in the included file libraries/error.inc.php
        //first check if php-mbstring is available
        if (function_exists('mb_detect_encoding')) {
            //If present use gettext
            $error_header = __('Error');
        } else {
            $error_header = 'Error';
        }
        $lang = isset($GLOBALS['lang']) ? $GLOBALS['lang'] : 'en';
        $dir = isset($GLOBALS['text_dir']) ? $GLOBALS['text_dir'] : 'ltr';
        // on fatal errors it cannot hurt to always delete the current session
        if ($delete_session && isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
            $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
        }
        // Displays the error message
        include './libraries/error.inc.php';
    }
    if (!defined('TESTSUITE')) {
        exit;
    }
}
コード例 #12
0
ファイル: ImportCsv.php プロジェクト: pboutin44/maintest
 /**
  * Handles the whole import logic
  *
  * @param array &$sql_data 2-element array with sql data
  *
  * @return void
  */
 public function doImport(&$sql_data = array())
 {
     global $db, $table, $csv_terminated, $csv_enclosed, $csv_escaped, $csv_new_line, $csv_columns, $err_url;
     // $csv_replace and $csv_ignore should have been here,
     // but we use directly from $_POST
     global $error, $timeout_passed, $finished, $message;
     $replacements = array('\\n' => "\n", '\\t' => "\t", '\\r' => "\r");
     $csv_terminated = strtr($csv_terminated, $replacements);
     $csv_enclosed = strtr($csv_enclosed, $replacements);
     $csv_escaped = strtr($csv_escaped, $replacements);
     $csv_new_line = strtr($csv_new_line, $replacements);
     $param_error = false;
     if (mb_strlen($csv_terminated) < 1) {
         $message = PMA\libraries\Message::error(__('Invalid parameter for CSV import: %s'));
         $message->addParam(__('Columns terminated with'), false);
         $error = true;
         $param_error = true;
         // The default dialog of MS Excel when generating a CSV produces a
         // semi-colon-separated file with no chance of specifying the
         // enclosing character. Thus, users who want to import this file
         // tend to remove the enclosing character on the Import dialog.
         // I could not find a test case where having no enclosing characters
         // confuses this script.
         // But the parser won't work correctly with strings so we allow just
         // one character.
     } elseif (mb_strlen($csv_enclosed) > 1) {
         $message = PMA\libraries\Message::error(__('Invalid parameter for CSV import: %s'));
         $message->addParam(__('Columns enclosed with'), false);
         $error = true;
         $param_error = true;
         // I could not find a test case where having no escaping characters
         // confuses this script.
         // But the parser won't work correctly with strings so we allow just
         // one character.
     } elseif (mb_strlen($csv_escaped) > 1) {
         $message = PMA\libraries\Message::error(__('Invalid parameter for CSV import: %s'));
         $message->addParam(__('Columns escaped with'), false);
         $error = true;
         $param_error = true;
     } elseif (mb_strlen($csv_new_line) != 1 && $csv_new_line != 'auto') {
         $message = PMA\libraries\Message::error(__('Invalid parameter for CSV import: %s'));
         $message->addParam(__('Lines terminated with'), false);
         $error = true;
         $param_error = true;
     }
     // If there is an error in the parameters entered,
     // indicate that immediately.
     if ($param_error) {
         PMA\libraries\Util::mysqlDie($message->getMessage(), '', false, $err_url);
     }
     $buffer = '';
     $required_fields = 0;
     if (!$this->_getAnalyze()) {
         $sql_template = 'INSERT';
         if (isset($_POST['csv_ignore'])) {
             $sql_template .= ' IGNORE';
         }
         $sql_template .= ' INTO ' . PMA\libraries\Util::backquote($table);
         $tmp_fields = $GLOBALS['dbi']->getColumns($db, $table);
         if (empty($csv_columns)) {
             $fields = $tmp_fields;
         } else {
             $sql_template .= ' (';
             $fields = array();
             $tmp = preg_split('/,( ?)/', $csv_columns);
             foreach ($tmp as $key => $val) {
                 if (count($fields) > 0) {
                     $sql_template .= ', ';
                 }
                 /* Trim also `, if user already included backquoted fields */
                 $val = trim($val, " \t\r\n\v`");
                 $found = false;
                 foreach ($tmp_fields as $field) {
                     if ($field['Field'] == $val) {
                         $found = true;
                         break;
                     }
                 }
                 if (!$found) {
                     $message = PMA\libraries\Message::error(__('Invalid column (%s) specified! Ensure that columns' . ' names are spelled correctly, separated by commas' . ', and not enclosed in quotes.'));
                     $message->addParam($val);
                     $error = true;
                     break;
                 }
                 $fields[] = $field;
                 $sql_template .= PMA\libraries\Util::backquote($val);
             }
             $sql_template .= ') ';
         }
         $required_fields = count($fields);
         $sql_template .= ' VALUES (';
     }
     // Defaults for parser
     $i = 0;
     $len = 0;
     $lastlen = null;
     $line = 1;
     $lasti = -1;
     $values = array();
     $csv_finish = false;
     $tempRow = array();
     $rows = array();
     $col_names = array();
     $tables = array();
     $col_count = 0;
     $max_cols = 0;
     $csv_terminated_len = mb_strlen($csv_terminated);
     while (!($finished && $i >= $len) && !$error && !$timeout_passed) {
         $data = PMA_importGetNextChunk();
         if ($data === false) {
             // subtract data we didn't handle yet and stop processing
             $GLOBALS['offset'] -= strlen($buffer);
             break;
         } elseif ($data === true) {
             // Handle rest of buffer
         } else {
             // Append new data to buffer
             $buffer .= $data;
             unset($data);
             // Force a trailing new line at EOF to prevent parsing problems
             if ($finished && $buffer) {
                 $finalch = mb_substr($buffer, -1);
                 if ($csv_new_line == 'auto' && $finalch != "\r" && $finalch != "\n") {
                     $buffer .= "\n";
                 } elseif ($csv_new_line != 'auto' && $finalch != $csv_new_line) {
                     $buffer .= $csv_new_line;
                 }
             }
             // Do not parse string when we're not at the end
             // and don't have new line inside
             if ($csv_new_line == 'auto' && mb_strpos($buffer, "\r") === false && mb_strpos($buffer, "\n") === false || $csv_new_line != 'auto' && mb_strpos($buffer, $csv_new_line) === false) {
                 continue;
             }
         }
         // Current length of our buffer
         $len = mb_strlen($buffer);
         // Currently parsed char
         $ch = mb_substr($buffer, $i, 1);
         if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
             $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
             $i += $csv_terminated_len - 1;
         }
         while ($i < $len) {
             // Deadlock protection
             if ($lasti == $i && $lastlen == $len) {
                 $message = PMA\libraries\Message::error(__('Invalid format of CSV input on line %d.'));
                 $message->addParam($line);
                 $error = true;
                 break;
             }
             $lasti = $i;
             $lastlen = $len;
             // This can happen with auto EOL and \r at the end of buffer
             if (!$csv_finish) {
                 // Grab empty field
                 if ($ch == $csv_terminated) {
                     if ($i == $len - 1) {
                         break;
                     }
                     $values[] = '';
                     $i++;
                     $ch = mb_substr($buffer, $i, 1);
                     if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                         $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                         $i += $csv_terminated_len - 1;
                     }
                     continue;
                 }
                 // Grab one field
                 $fallbacki = $i;
                 if ($ch == $csv_enclosed) {
                     if ($i == $len - 1) {
                         break;
                     }
                     $need_end = true;
                     $i++;
                     $ch = mb_substr($buffer, $i, 1);
                     if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                         $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                         $i += $csv_terminated_len - 1;
                     }
                 } else {
                     $need_end = false;
                 }
                 $fail = false;
                 $value = '';
                 while ($need_end && ($ch != $csv_enclosed || $csv_enclosed == $csv_escaped) || !$need_end && !($ch == $csv_terminated || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))) {
                     if ($ch == $csv_escaped) {
                         if ($i == $len - 1) {
                             $fail = true;
                             break;
                         }
                         $i++;
                         $ch = mb_substr($buffer, $i, 1);
                         if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                             $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                             $i += $csv_terminated_len - 1;
                         }
                         if ($csv_enclosed == $csv_escaped && ($ch == $csv_terminated || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))) {
                             break;
                         }
                     }
                     $value .= $ch;
                     if ($i == $len - 1) {
                         if (!$finished) {
                             $fail = true;
                         }
                         break;
                     }
                     $i++;
                     $ch = mb_substr($buffer, $i, 1);
                     if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                         $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                         $i += $csv_terminated_len - 1;
                     }
                 }
                 // unquoted NULL string
                 if (false === $need_end && $value === 'NULL') {
                     $value = null;
                 }
                 if ($fail) {
                     $i = $fallbacki;
                     $ch = mb_substr($buffer, $i, 1);
                     if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                         $i += $csv_terminated_len - 1;
                     }
                     break;
                 }
                 // Need to strip trailing enclosing char?
                 if ($need_end && $ch == $csv_enclosed) {
                     if ($finished && $i == $len - 1) {
                         $ch = null;
                     } elseif ($i == $len - 1) {
                         $i = $fallbacki;
                         $ch = mb_substr($buffer, $i, 1);
                         if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                             $i += $csv_terminated_len - 1;
                         }
                         break;
                     } else {
                         $i++;
                         $ch = mb_substr($buffer, $i, 1);
                         if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                             $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                             $i += $csv_terminated_len - 1;
                         }
                     }
                 }
                 // Are we at the end?
                 if ($ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n") || $finished && $i == $len - 1) {
                     $csv_finish = true;
                 }
                 // Go to next char
                 if ($ch == $csv_terminated) {
                     if ($i == $len - 1) {
                         $i = $fallbacki;
                         $ch = mb_substr($buffer, $i, 1);
                         if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                             $i += $csv_terminated_len - 1;
                         }
                         break;
                     }
                     $i++;
                     $ch = mb_substr($buffer, $i, 1);
                     if ($csv_terminated_len > 1 && $ch == $csv_terminated[0]) {
                         $ch = $this->readCsvTerminatedString($buffer, $ch, $i, $csv_terminated_len);
                         $i += $csv_terminated_len - 1;
                     }
                 }
                 // If everything went okay, store value
                 $values[] = $value;
             }
             // End of line
             if ($csv_finish || $ch == $csv_new_line || $csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n")) {
                 if ($csv_new_line == 'auto' && $ch == "\r") {
                     // Handle "\r\n"
                     if ($i >= $len - 2 && !$finished) {
                         break;
                         // We need more data to decide new line
                     }
                     if (mb_substr($buffer, $i + 1, 1) == "\n") {
                         $i++;
                     }
                 }
                 // We didn't parse value till the end of line, so there was
                 // empty one
                 if (!$csv_finish) {
                     $values[] = '';
                 }
                 if ($this->_getAnalyze()) {
                     foreach ($values as $val) {
                         $tempRow[] = $val;
                         ++$col_count;
                     }
                     if ($col_count > $max_cols) {
                         $max_cols = $col_count;
                     }
                     $col_count = 0;
                     $rows[] = $tempRow;
                     $tempRow = array();
                 } else {
                     // Do we have correct count of values?
                     if (count($values) != $required_fields) {
                         // Hack for excel
                         if ($values[count($values) - 1] == ';') {
                             unset($values[count($values) - 1]);
                         } else {
                             $message = PMA\libraries\Message::error(__('Invalid column count in CSV input' . ' on line %d.'));
                             $message->addParam($line);
                             $error = true;
                             break;
                         }
                     }
                     $first = true;
                     $sql = $sql_template;
                     foreach ($values as $key => $val) {
                         if (!$first) {
                             $sql .= ', ';
                         }
                         if ($val === null) {
                             $sql .= 'NULL';
                         } else {
                             $sql .= '\'' . PMA\libraries\Util::sqlAddSlashes($val) . '\'';
                         }
                         $first = false;
                     }
                     $sql .= ')';
                     if (isset($_POST['csv_replace'])) {
                         $sql .= " ON DUPLICATE KEY UPDATE ";
                         foreach ($fields as $field) {
                             $fieldName = PMA\libraries\Util::backquote($field['Field']);
                             $sql .= $fieldName . " = VALUES(" . $fieldName . "), ";
                         }
                         $sql = rtrim($sql, ', ');
                     }
                     /**
                      * @todo maybe we could add original line to verbose
                      * SQL in comment
                      */
                     PMA_importRunQuery($sql, $sql, $sql_data);
                 }
                 $line++;
                 $csv_finish = false;
                 $values = array();
                 $buffer = mb_substr($buffer, $i + 1);
                 $len = mb_strlen($buffer);
                 $i = 0;
                 $lasti = -1;
                 $ch = mb_substr($buffer, 0, 1);
             }
         }
         // End of parser loop
     }
     // End of import loop
     if ($this->_getAnalyze()) {
         /* Fill out all rows */
         $num_rows = count($rows);
         for ($i = 0; $i < $num_rows; ++$i) {
             for ($j = count($rows[$i]); $j < $max_cols; ++$j) {
                 $rows[$i][] = 'NULL';
             }
         }
         if (isset($_REQUEST['csv_col_names'])) {
             $col_names = array_splice($rows, 0, 1);
             $col_names = $col_names[0];
             // MySQL column names can't end with a space character.
             foreach ($col_names as $key => $col_name) {
                 $col_names[$key] = rtrim($col_name);
             }
         }
         if (isset($col_names) && count($col_names) != $max_cols || !isset($col_names)) {
             // Fill out column names
             for ($i = 0; $i < $max_cols; ++$i) {
                 $col_names[] = 'COL ' . ($i + 1);
             }
         }
         if (mb_strlen($db)) {
             $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES');
             $tbl_name = 'TABLE ' . (count($result) + 1);
         } else {
             $tbl_name = 'TBL_NAME';
         }
         $tables[] = array($tbl_name, $col_names, $rows);
         /* Obtain the best-fit MySQL types for each column */
         $analyses = array();
         $analyses[] = PMA_analyzeTable($tables[0]);
         /**
          * string $db_name (no backquotes)
          *
          * array $table = array(table_name, array() column_names, array()() rows)
          * array $tables = array of "$table"s
          *
          * array $analysis = array(array() column_types, array() column_sizes)
          * array $analyses = array of "$analysis"s
          *
          * array $create = array of SQL strings
          *
          * array $options = an associative array of options
          */
         /* Set database name to the currently selected one, if applicable */
         list($db_name, $options) = $this->getDbnameAndOptions($db, 'CSV_DB');
         /* Non-applicable parameters */
         $create = null;
         /* Created and execute necessary SQL statements from data */
         PMA_buildSQL($db_name, $tables, $analyses, $create, $options, $sql_data);
         unset($tables);
         unset($analyses);
     }
     // Commit any possible data in buffers
     PMA_importRunQuery('', '', $sql_data);
     if (count($values) != 0 && !$error) {
         $message = PMA\libraries\Message::error(__('Invalid format of CSV input on line %d.'));
         $message->addParam($line);
         $error = true;
     }
 }
コード例 #13
0
/**
 * displays the given error message on phpMyAdmin error page in foreign language,
 * ends script execution and closes session
 *
 * loads language file if not loaded already
 *
 * @param string       $error_message  the error message or named error message
 * @param string|array $message_args   arguments applied to $error_message
 * @param boolean      $delete_session whether to delete session cookie
 *
 * @return void
 */
function PMA_fatalError($error_message, $message_args = null, $delete_session = true)
{
    /* Use format string if applicable */
    if (is_string($message_args)) {
        $error_message = sprintf($error_message, $message_args);
    } elseif (is_array($message_args)) {
        $error_message = vsprintf($error_message, $message_args);
    }
    if (!empty($GLOBALS['is_ajax_request']) && $GLOBALS['is_ajax_request']) {
        $response = PMA\libraries\Response::getInstance();
        $response->setRequestStatus(false);
        $response->addJSON('message', PMA\libraries\Message::error($error_message));
    } else {
        $error_message = strtr($error_message, array('<br />' => '[br]'));
        /* Load gettext for fatal errors */
        if (!function_exists('__')) {
            // It is possible that PMA_fatalError() is called before including
            // vendor_config.php which defines GETTEXT_INC. See bug #4557
            if (defined(GETTEXT_INC)) {
                include_once GETTEXT_INC;
            } else {
                include_once './libraries/php-gettext/gettext.inc';
            }
        }
        // these variables are used in the included file libraries/error.inc.php
        //first check if php-mbstring is available
        if (function_exists('mb_detect_encoding')) {
            //If present use gettext
            $error_header = __('Error');
        } else {
            $error_header = 'Error';
        }
        $lang = $GLOBALS['lang'];
        $dir = $GLOBALS['text_dir'];
        // on fatal errors it cannot hurt to always delete the current session
        if ($delete_session && isset($GLOBALS['session_name']) && isset($_COOKIE[$GLOBALS['session_name']])) {
            $GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
        }
        // Displays the error message
        include './libraries/error.inc.php';
    }
    if (!defined('TESTSUITE')) {
        exit;
    }
}
コード例 #14
0
 /**
  * Moves columns in the table's structure based on $_REQUEST
  *
  * @return void
  */
 protected function moveColumns()
 {
     $this->dbi->selectDb($this->db);
     /*
      * load the definitions for all columns
      */
     $columns = $this->dbi->getColumnsFull($this->db, $this->table);
     $column_names = array_keys($columns);
     $changes = array();
     // move columns from first to last
     for ($i = 0, $l = count($_REQUEST['move_columns']); $i < $l; $i++) {
         $column = $_REQUEST['move_columns'][$i];
         // is this column already correctly placed?
         if ($column_names[$i] == $column) {
             continue;
         }
         // it is not, let's move it to index $i
         $data = $columns[$column];
         $extracted_columnspec = Util::extractColumnSpec($data['Type']);
         if (isset($data['Extra']) && $data['Extra'] == 'on update CURRENT_TIMESTAMP') {
             $extracted_columnspec['attribute'] = $data['Extra'];
             unset($data['Extra']);
         }
         $current_timestamp = ($data['Type'] == 'timestamp' || $data['Type'] == 'datetime') && $data['Default'] == 'CURRENT_TIMESTAMP';
         if ($data['Null'] === 'YES' && $data['Default'] === null) {
             $default_type = 'NULL';
         } elseif ($current_timestamp) {
             $default_type = 'CURRENT_TIMESTAMP';
         } elseif ($data['Default'] === null) {
             $default_type = 'NONE';
         } else {
             $default_type = 'USER_DEFINED';
         }
         $virtual = array('VIRTUAL', 'PERSISTENT', 'VIRTUAL GENERATED', 'STORED GENERATED');
         $data['Virtuality'] = '';
         $data['Expression'] = '';
         if (isset($data['Extra']) && in_array($data['Extra'], $virtual)) {
             $data['Virtuality'] = str_replace(' GENERATED', '', $data['Extra']);
             $expressions = $this->table->getColumnGenerationExpression($column);
             $data['Expression'] = $expressions[$column];
         }
         $changes[] = 'CHANGE ' . Table::generateAlter($column, $column, mb_strtoupper($extracted_columnspec['type']), $extracted_columnspec['spec_in_brackets'], $extracted_columnspec['attribute'], isset($data['Collation']) ? $data['Collation'] : '', $data['Null'] === 'YES' ? 'NULL' : 'NOT NULL', $default_type, $current_timestamp ? '' : $data['Default'], isset($data['Extra']) && $data['Extra'] !== '' ? $data['Extra'] : false, isset($data['COLUMN_COMMENT']) && $data['COLUMN_COMMENT'] !== '' ? $data['COLUMN_COMMENT'] : false, $data['Virtuality'], $data['Expression'], $i === 0 ? '-first' : $column_names[$i - 1]);
         // update current column_names array, first delete old position
         for ($j = 0, $ll = count($column_names); $j < $ll; $j++) {
             if ($column_names[$j] == $column) {
                 unset($column_names[$j]);
             }
         }
         // insert moved column
         array_splice($column_names, $i, 0, $column);
     }
     if (empty($changes)) {
         // should never happen
         $this->response->setRequestStatus(false);
         return;
     }
     // move columns
     $this->dbi->tryQuery(sprintf('ALTER TABLE %s %s', Util::backquote($this->table), implode(', ', $changes)));
     $tmp_error = $this->dbi->getError();
     if ($tmp_error) {
         $this->response->setRequestStatus(false);
         $this->response->addJSON('message', Message::error($tmp_error));
     } else {
         $message = Message::success(__('The columns have been moved successfully.'));
         $this->response->addJSON('message', $message);
         $this->response->addJSON('columns', $column_names);
     }
 }
コード例 #15
0
/**
 * Saves user preferences
 *
 * @param array $config_array configuration array
 *
 * @return true|PMA\libraries\Message
 */
function PMA_saveUserprefs(array $config_array)
{
    $cfgRelation = PMA_getRelationsParam();
    $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : $GLOBALS['cfg']['ServerDefault'];
    $cache_key = 'server_' . $server;
    if (!$cfgRelation['userconfigwork']) {
        // no pmadb table, use session storage
        $_SESSION['userconfig'] = array('db' => $config_array, 'ts' => time());
        if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
            unset($_SESSION['cache'][$cache_key]['userprefs']);
        }
        return true;
    }
    // save configuration to pmadb
    $query_table = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['userconfig']);
    $query = 'SELECT `username` FROM ' . $query_table . ' WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\'';
    $has_config = $GLOBALS['dbi']->fetchValue($query, 0, 0, $GLOBALS['controllink']);
    $config_data = json_encode($config_array);
    if ($has_config) {
        $query = 'UPDATE ' . $query_table . ' SET `timevalue` = NOW(), `config_data` = \'' . $GLOBALS['dbi']->escapeString($config_data) . '\'' . ' WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\'';
    } else {
        $query = 'INSERT INTO ' . $query_table . ' (`username`, `timevalue`,`config_data`) ' . 'VALUES (\'' . $GLOBALS['dbi']->escapeString($cfgRelation['user']) . '\', NOW(), ' . '\'' . $GLOBALS['dbi']->escapeString($config_data) . '\')';
    }
    if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
        unset($_SESSION['cache'][$cache_key]['userprefs']);
    }
    if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {
        $message = Message::error(__('Could not save configuration'));
        $message->addMessage('<br /><br />');
        $message->addMessage(Message::rawError($GLOBALS['dbi']->getError($GLOBALS['controllink'])));
        return $message;
    }
    return true;
}
コード例 #16
0
/**
 * update a column in central columns list if a edit is requested
 *
 * @param string $db            current database
 * @param string $orig_col_name original column name before edit
 * @param string $col_name      new column name
 * @param string $col_type      new column type
 * @param string $col_attribute new column attribute
 * @param string $col_length    new column length
 * @param int    $col_isNull    value 1 if new column isNull is true, 0 otherwise
 * @param string $collation     new column collation
 * @param string $col_extra     new column extra property
 * @param string $col_default   new column default value
 *
 * @return true|PMA\libraries\Message
 */
function PMA_updateOneColumn($db, $orig_col_name, $col_name, $col_type, $col_attribute, $col_length, $col_isNull, $collation, $col_extra, $col_default)
{
    $cfgCentralColumns = PMA_centralColumnsGetParams();
    if (empty($cfgCentralColumns)) {
        return PMA_configErrorMessage();
    }
    $centralTable = $cfgCentralColumns['table'];
    $GLOBALS['dbi']->selectDb($cfgCentralColumns['db'], $GLOBALS['controllink']);
    if ($orig_col_name == "") {
        $def = array();
        $def['Type'] = $col_type;
        if ($col_length) {
            $def['Type'] .= '(' . $col_length . ')';
        }
        $def['Collation'] = $collation;
        $def['Null'] = $col_isNull ? __('YES') : __('NO');
        $def['Extra'] = $col_extra;
        $def['Attribute'] = $col_attribute;
        $def['Default'] = $col_default;
        $query = PMA_getInsertQuery($col_name, $def, $db, $centralTable);
    } else {
        $query = 'UPDATE ' . Util::backquote($centralTable) . ' SET col_type = \'' . Util::sqlAddSlashes($col_type) . '\'' . ', col_name = \'' . Util::sqlAddSlashes($col_name) . '\'' . ', col_length = \'' . Util::sqlAddSlashes($col_length) . '\'' . ', col_isNull = ' . $col_isNull . ', col_collation = \'' . Util::sqlAddSlashes($collation) . '\'' . ', col_extra = \'' . implode(',', array($col_extra, $col_attribute)) . '\'' . ', col_default = \'' . Util::sqlAddSlashes($col_default) . '\'' . ' WHERE db_name = \'' . Util::sqlAddSlashes($db) . '\' ' . 'AND col_name = \'' . Util::sqlAddSlashes($orig_col_name) . '\'';
    }
    if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {
        return Message::error($GLOBALS['dbi']->getError($GLOBALS['controllink']));
    }
    return true;
}
コード例 #17
0
/**
 * Get HTML snippet for display user properties
 *
 * @param boolean $dbname_is_wildcard whether database name is wildcard or not
 * @param string  $url_dbname         url database name that urlencode() string
 * @param string  $username           username
 * @param string  $hostname           host name
 * @param string  $dbname             database name
 * @param string  $tablename          table name
 *
 * @return string $html_output
 */
function PMA_getHtmlForUserProperties($dbname_is_wildcard, $url_dbname, $username, $hostname, $dbname, $tablename)
{
    $html_output = '<div id="edit_user_dialog">';
    $html_output .= PMA_getHtmlHeaderForUserProperties($dbname_is_wildcard, $url_dbname, $dbname, $username, $hostname, $tablename);
    $sql = "SELECT '1' FROM `mysql`.`user`" . " WHERE `User` = '" . Util::sqlAddSlashes($username) . "'" . " AND `Host` = '" . Util::sqlAddSlashes($hostname) . "';";
    $user_does_not_exists = (bool) (!$GLOBALS['dbi']->fetchValue($sql));
    if ($user_does_not_exists) {
        $html_output .= Message::error(__('The selected user was not found in the privilege table.'))->getDisplay();
        $html_output .= PMA_getHtmlForLoginInformationFields();
    }
    $_params = array('username' => $username, 'hostname' => $hostname);
    if (!is_array($dbname) && mb_strlen($dbname)) {
        $_params['dbname'] = $dbname;
        if (mb_strlen($tablename)) {
            $_params['tablename'] = $tablename;
        }
    } else {
        $_params['dbname'] = $dbname;
    }
    $html_output .= '<form class="submenu-item" name="usersForm" ' . 'id="addUsersForm" action="server_privileges.php" method="post">' . "\n";
    $html_output .= PMA_URL_getHiddenInputs($_params);
    $html_output .= PMA_getHtmlToDisplayPrivilegesTable(PMA_ifSetOr($dbname, is_array($dbname) ? $dbname[0] : '*', 'length'), PMA_ifSetOr($tablename, '*', 'length'));
    $html_output .= '</form>' . "\n";
    if (!is_array($dbname) && !mb_strlen($tablename) && empty($dbname_is_wildcard)) {
        // no table name was given, display all table specific rights
        // but only if $dbname contains no wildcards
        if (!mb_strlen($dbname)) {
            $html_output .= PMA_getHtmlForAllTableSpecificRights($username, $hostname, 'database');
        } else {
            // unescape wildcards in dbname at table level
            $unescaped_db = Util::unescapeMysqlWildcards($dbname);
            $html_output .= PMA_getHtmlForAllTableSpecificRights($username, $hostname, 'table', $unescaped_db);
            $html_output .= PMA_getHtmlForAllTableSpecificRights($username, $hostname, 'routine', $unescaped_db);
        }
    }
    // Provide a line with links to the relevant database and table
    if (!is_array($dbname) && mb_strlen($dbname) && empty($dbname_is_wildcard)) {
        $html_output .= PMA_getLinkToDbAndTable($url_dbname, $dbname, $tablename);
    }
    if (!is_array($dbname) && !mb_strlen($dbname) && !$user_does_not_exists) {
        //change login information
        $html_output .= PMA_getHtmlForChangePassword('edit_other', $username, $hostname);
        $html_output .= PMA_getChangeLoginInformationHtmlForm($username, $hostname);
    }
    $html_output .= '</div>';
    return $html_output;
}
コード例 #18
0
ファイル: Table.php プロジェクト: ryanfmurphy/phpmyadmin
 /**
  * Function to handle foreign key updates
  *
  * @param array  $destination_foreign_db     destination foreign database
  * @param array  $multi_edit_columns_name    multi edit column names
  * @param array  $destination_foreign_table  destination foreign table
  * @param array  $destination_foreign_column destination foreign column
  * @param array  $options_array              options array
  * @param string $table                      current table
  * @param array  $existrel_foreign           db, table, column
  *
  * @return array
  */
 public function updateForeignKeys($destination_foreign_db, $multi_edit_columns_name, $destination_foreign_table, $destination_foreign_column, $options_array, $table, $existrel_foreign)
 {
     $html_output = '';
     $preview_sql_data = '';
     $display_query = '';
     $seen_error = false;
     foreach ($destination_foreign_db as $master_field_md5 => $foreign_db) {
         $create = false;
         $drop = false;
         // Map the fieldname's md5 back to its real name
         $master_field = $multi_edit_columns_name[$master_field_md5];
         $foreign_table = $destination_foreign_table[$master_field_md5];
         $foreign_field = $destination_foreign_column[$master_field_md5];
         if (isset($existrel_foreign[$master_field_md5]['ref_db_name'])) {
             $ref_db_name = $existrel_foreign[$master_field_md5]['ref_db_name'];
         } else {
             $ref_db_name = $GLOBALS['db'];
         }
         $empty_fields = false;
         foreach ($master_field as $key => $one_field) {
             if (!empty($one_field) && empty($foreign_field[$key]) || empty($one_field) && !empty($foreign_field[$key])) {
                 $empty_fields = true;
             }
             if (empty($one_field) && empty($foreign_field[$key])) {
                 unset($master_field[$key]);
                 unset($foreign_field[$key]);
             }
         }
         if (!empty($foreign_db) && !empty($foreign_table) && !$empty_fields) {
             if (isset($existrel_foreign[$master_field_md5])) {
                 $constraint_name = $existrel_foreign[$master_field_md5]['constraint'];
                 $on_delete = !empty($existrel_foreign[$master_field_md5]['on_delete']) ? $existrel_foreign[$master_field_md5]['on_delete'] : 'RESTRICT';
                 $on_update = !empty($existrel_foreign[$master_field_md5]['on_update']) ? $existrel_foreign[$master_field_md5]['on_update'] : 'RESTRICT';
                 if ($ref_db_name != $foreign_db || $existrel_foreign[$master_field_md5]['ref_table_name'] != $foreign_table || $existrel_foreign[$master_field_md5]['ref_index_list'] != $foreign_field || $existrel_foreign[$master_field_md5]['index_list'] != $master_field || $_REQUEST['constraint_name'][$master_field_md5] != $constraint_name || $_REQUEST['on_delete'][$master_field_md5] != $on_delete || $_REQUEST['on_update'][$master_field_md5] != $on_update) {
                     // another foreign key is already defined for this field
                     // or an option has been changed for ON DELETE or ON UPDATE
                     $drop = true;
                     $create = true;
                 }
                 // end if... else....
             } else {
                 // no key defined for this field(s)
                 $create = true;
             }
         } elseif (isset($existrel_foreign[$master_field_md5])) {
             $drop = true;
         }
         // end if... else....
         $tmp_error_drop = false;
         if ($drop) {
             $drop_query = 'ALTER TABLE ' . Util::backquote($table) . ' DROP FOREIGN KEY ' . Util::backquote($existrel_foreign[$master_field_md5]['constraint']) . ';';
             if (!isset($_REQUEST['preview_sql'])) {
                 $display_query .= $drop_query . "\n";
                 $this->_dbi->tryQuery($drop_query);
                 $tmp_error_drop = $this->_dbi->getError();
                 if (!empty($tmp_error_drop)) {
                     $seen_error = true;
                     $html_output .= Util::mysqlDie($tmp_error_drop, $drop_query, false, '', false);
                     continue;
                 }
             } else {
                 $preview_sql_data .= $drop_query . "\n";
             }
         }
         $tmp_error_create = false;
         if (!$create) {
             continue;
         }
         $create_query = $this->_getSQLToCreateForeignKey($table, $master_field, $foreign_db, $foreign_table, $foreign_field, $_REQUEST['constraint_name'][$master_field_md5], $options_array[$_REQUEST['on_delete'][$master_field_md5]], $options_array[$_REQUEST['on_update'][$master_field_md5]]);
         if (!isset($_REQUEST['preview_sql'])) {
             $display_query .= $create_query . "\n";
             $this->_dbi->tryQuery($create_query);
             $tmp_error_create = $this->_dbi->getError();
             if (!empty($tmp_error_create)) {
                 $seen_error = true;
                 if (substr($tmp_error_create, 1, 4) == '1005') {
                     $message = Message::error(__('Error creating foreign key on %1$s (check data ' . 'types)'));
                     $message->addParam(implode(', ', $master_field));
                     $html_output .= $message->getDisplay();
                 } else {
                     $html_output .= Util::mysqlDie($tmp_error_create, $create_query, false, '', false);
                 }
                 $html_output .= Util::showMySQLDocu('InnoDB_foreign_key_constraints') . "\n";
             }
         } else {
             $preview_sql_data .= $create_query . "\n";
         }
         // this is an alteration and the old constraint has been dropped
         // without creation of a new one
         if ($drop && $create && empty($tmp_error_drop) && !empty($tmp_error_create)) {
             // a rollback may be better here
             $sql_query_recreate = '# Restoring the dropped constraint...' . "\n";
             $sql_query_recreate .= $this->_getSQLToCreateForeignKey($table, $master_field, $existrel_foreign[$master_field_md5]['ref_db_name'], $existrel_foreign[$master_field_md5]['ref_table_name'], $existrel_foreign[$master_field_md5]['ref_index_list'], $existrel_foreign[$master_field_md5]['constraint'], $options_array[$existrel_foreign[$master_field_md5]['on_delete']], $options_array[$existrel_foreign[$master_field_md5]['on_update']]);
             if (!isset($_REQUEST['preview_sql'])) {
                 $display_query .= $sql_query_recreate . "\n";
                 $this->_dbi->tryQuery($sql_query_recreate);
             } else {
                 $preview_sql_data .= $sql_query_recreate;
             }
         }
     }
     // end foreach
     return array($html_output, $preview_sql_data, $display_query, $seen_error);
 }
コード例 #19
0
ファイル: db_common.inc.php プロジェクト: pjiahao/phpmyadmin
        // after calling a MySQL procedure; at this point we can't select
        // the db but it's not necessarily wrong
        if ($GLOBALS['dbi']->getError() && $GLOBALS['errno'] == 2014) {
            $is_db = true;
            unset($GLOBALS['errno']);
        }
    } else {
        $is_db = false;
    }
    // Not a valid db name -> back to the welcome page
    $uri = $cfg['PmaAbsoluteUri'] . 'index.php' . PMA_URL_getCommon(array(), 'text') . (isset($message) ? '&message=' . urlencode($message) : '') . '&reload=1';
    if (!mb_strlen($db) || !$is_db) {
        $response = PMA\libraries\Response::getInstance();
        if ($response->isAjax()) {
            $response->setRequestStatus(false);
            $response->addJSON('message', Message::error(__('No databases selected.')));
        } else {
            PMA_sendHeaderLocation($uri);
        }
        exit;
    }
}
// end if (ensures db exists)
/**
 * Changes database charset if requested by the user
 */
if (isset($_REQUEST['submitcollation']) && isset($_REQUEST['db_collation']) && !empty($_REQUEST['db_collation'])) {
    list($db_charset) = explode('_', $_REQUEST['db_collation']);
    $sql_query = 'ALTER DATABASE ' . PMA\libraries\Util::backquote($db) . ' DEFAULT' . PMA_generateCharsetQueryPart($_REQUEST['db_collation']);
    $result = $GLOBALS['dbi']->query($sql_query);
    $message = Message::success();
コード例 #20
0
ファイル: Header.php プロジェクト: iShareLife/phpmyadmin
 /**
  * Returns some warnings to be displayed at the top of the page
  *
  * @return string The warnings
  */
 private function _getWarnings()
 {
     $retval = '';
     if ($this->_warningsEnabled) {
         $retval .= "<noscript>";
         $retval .= Message::error(__("Javascript must be enabled past this point!"))->getDisplay();
         $retval .= "</noscript>";
     }
     return $retval;
 }
コード例 #21
0
ファイル: ImportShp.php プロジェクト: iShareLife/phpmyadmin
 /**
  * Handles the whole import logic
  *
  * @return void
  */
 public function doImport()
 {
     global $db, $error, $finished, $compression, $import_file, $local_import_file, $message;
     $GLOBALS['finished'] = false;
     $shp = new ShapeFile(1);
     // If the zip archive has more than one file,
     // get the correct content to the buffer from .shp file.
     if ($compression == 'application/zip' && PMA_getNoOfFilesInZip($import_file) > 1) {
         $zip_content = PMA_getZipContents($import_file, '/^.*\\.shp$/i');
         $GLOBALS['import_text'] = $zip_content['data'];
     }
     $temp_dbf_file = false;
     // We need dbase extension to handle .dbf file
     if (extension_loaded('dbase')) {
         // If we can extract the zip archive to 'TempDir'
         // and use the files in it for import
         if ($compression == 'application/zip' && !empty($GLOBALS['cfg']['TempDir']) && is_writable($GLOBALS['cfg']['TempDir'])) {
             $dbf_file_name = PMA_findFileFromZipArchive('/^.*\\.dbf$/i', $import_file);
             // If the corresponding .dbf file is in the zip archive
             if ($dbf_file_name) {
                 // Extract the .dbf file and point to it.
                 $extracted = PMA_zipExtract($import_file, realpath($GLOBALS['cfg']['TempDir']), array($dbf_file_name));
                 if ($extracted) {
                     $dbf_file_path = realpath($GLOBALS['cfg']['TempDir']) . (PMA_IS_WINDOWS ? '\\' : '/') . $dbf_file_name;
                     $temp_dbf_file = true;
                     // Replace the .dbf with .*, as required
                     // by the bsShapeFiles library.
                     $file_name = mb_substr($dbf_file_path, 0, mb_strlen($dbf_file_path) - 4) . '.*';
                     $shp->FileName = $file_name;
                 }
             }
         } elseif (!empty($local_import_file) && !empty($GLOBALS['cfg']['UploadDir']) && $compression == 'none') {
             // If file is in UploadDir, use .dbf file in the same UploadDir
             // to load extra data.
             // Replace the .shp with .*,
             // so the bsShapeFiles library correctly locates .dbf file.
             $file_name = mb_substr($import_file, 0, mb_strlen($import_file) - 4) . '.*';
             $shp->FileName = $file_name;
         }
     }
     // Load data
     $shp->loadFromFile('');
     if ($shp->lastError != "") {
         $error = true;
         $message = PMA\libraries\Message::error(__('There was an error importing the ESRI shape file: "%s".'));
         $message->addParam($shp->lastError);
         return;
     }
     // Delete the .dbf file extracted to 'TempDir'
     if ($temp_dbf_file && isset($dbf_file_path) && file_exists($dbf_file_path)) {
         unlink($dbf_file_path);
     }
     $esri_types = array(0 => 'Null Shape', 1 => 'Point', 3 => 'PolyLine', 5 => 'Polygon', 8 => 'MultiPoint', 11 => 'PointZ', 13 => 'PolyLineZ', 15 => 'PolygonZ', 18 => 'MultiPointZ', 21 => 'PointM', 23 => 'PolyLineM', 25 => 'PolygonM', 28 => 'MultiPointM', 31 => 'MultiPatch');
     switch ($shp->shapeType) {
         // ESRI Null Shape
         case 0:
             break;
             // ESRI Point
         // ESRI Point
         case 1:
             $gis_type = 'point';
             break;
             // ESRI PolyLine
         // ESRI PolyLine
         case 3:
             $gis_type = 'multilinestring';
             break;
             // ESRI Polygon
         // ESRI Polygon
         case 5:
             $gis_type = 'multipolygon';
             break;
             // ESRI MultiPoint
         // ESRI MultiPoint
         case 8:
             $gis_type = 'multipoint';
             break;
         default:
             $error = true;
             if (!isset($esri_types[$shp->shapeType])) {
                 $message = PMA\libraries\Message::error(__('You tried to import an invalid file or the imported file' . ' contains invalid data!'));
             } else {
                 $message = PMA\libraries\Message::error(__('MySQL Spatial Extension does not support ESRI type "%s".'));
                 $message->addParam($esri_types[$shp->shapeType]);
             }
             return;
     }
     if (isset($gis_type)) {
         /** @var GISMultilinestring|\PMA\libraries\gis\GISMultipoint|\PMA\libraries\gis\GISPoint|GISPolygon $gis_obj */
         $gis_obj = GISFactory::factory($gis_type);
     } else {
         $gis_obj = null;
     }
     $num_rows = count($shp->records);
     // If .dbf file is loaded, the number of extra data columns
     $num_data_cols = isset($shp->DBFHeader) ? count($shp->DBFHeader) : 0;
     $rows = array();
     $col_names = array();
     if ($num_rows != 0) {
         foreach ($shp->records as $record) {
             $tempRow = array();
             if ($gis_obj == null) {
                 $tempRow[] = null;
             } else {
                 $tempRow[] = "GeomFromText('" . $gis_obj->getShape($record->SHPData) . "')";
             }
             if (isset($shp->DBFHeader)) {
                 foreach ($shp->DBFHeader as $c) {
                     $cell = trim($record->DBFData[$c[0]]);
                     if (!strcmp($cell, '')) {
                         $cell = 'NULL';
                     }
                     $tempRow[] = $cell;
                 }
             }
             $rows[] = $tempRow;
         }
     }
     if (count($rows) == 0) {
         $error = true;
         $message = PMA\libraries\Message::error(__('The imported file does not contain any data!'));
         return;
     }
     // Column names for spatial column and the rest of the columns,
     // if they are available
     $col_names[] = 'SPATIAL';
     for ($n = 0; $n < $num_data_cols; $n++) {
         $col_names[] = $shp->DBFHeader[$n][0];
     }
     // Set table name based on the number of tables
     if (mb_strlen($db)) {
         $result = $GLOBALS['dbi']->fetchResult('SHOW TABLES');
         $table_name = 'TABLE ' . (count($result) + 1);
     } else {
         $table_name = 'TBL_NAME';
     }
     $tables = array(array($table_name, $col_names, $rows));
     // Use data from shape file to chose best-fit MySQL types for each column
     $analyses = array();
     $analyses[] = PMA_analyzeTable($tables[0]);
     $table_no = 0;
     $spatial_col = 0;
     $analyses[$table_no][TYPES][$spatial_col] = GEOMETRY;
     $analyses[$table_no][FORMATTEDSQL][$spatial_col] = true;
     // Set database name to the currently selected one, if applicable
     if (mb_strlen($db)) {
         $db_name = $db;
         $options = array('create_db' => false);
     } else {
         $db_name = 'SHP_DB';
         $options = null;
     }
     // Created and execute necessary SQL statements from data
     $null_param = null;
     PMA_buildSQL($db_name, $tables, $analyses, $null_param, $options);
     unset($tables);
     unset($analyses);
     $finished = true;
     $error = false;
     // Commit any possible data in buffers
     PMA_importRunQuery();
 }
コード例 #22
0
 /**
  * Index
  *
  * @return void
  */
 public function indexAction()
 {
     // Throw error if no sql query is set
     if (!isset($this->sql_query) || $this->sql_query == '') {
         $this->response->setRequestStatus(false);
         $this->response->addHTML(Message::error(__('No SQL query was set to fetch data.')));
         return;
     }
     // Execute the query and return the result
     $result = $this->dbi->tryQuery($this->sql_query);
     // Get the meta data of results
     $meta = $this->dbi->getFieldsMeta($result);
     // Find the candidate fields for label column and spatial column
     $labelCandidates = array();
     $spatialCandidates = array();
     foreach ($meta as $column_meta) {
         if ($column_meta->type == 'geometry') {
             $spatialCandidates[] = $column_meta->name;
         } else {
             $labelCandidates[] = $column_meta->name;
         }
     }
     // Get settings if any posted
     if (PMA_isValid($_REQUEST['visualizationSettings'], 'array')) {
         $this->visualizationSettings = $_REQUEST['visualizationSettings'];
     }
     if (!isset($this->visualizationSettings['labelColumn']) && isset($labelCandidates[0])) {
         $this->visualizationSettings['labelColumn'] = '';
     }
     // If spatial column is not set, use first geometric column as spatial column
     if (!isset($this->visualizationSettings['spatialColumn'])) {
         $this->visualizationSettings['spatialColumn'] = $spatialCandidates[0];
     }
     // Convert geometric columns from bytes to text.
     $pos = isset($_REQUEST['pos']) ? $_REQUEST['pos'] : $_SESSION['tmpval']['pos'];
     if (isset($_REQUEST['session_max_rows'])) {
         $rows = $_REQUEST['session_max_rows'];
     } else {
         if ($_SESSION['tmpval']['max_rows'] != 'all') {
             $rows = $_SESSION['tmpval']['max_rows'];
         } else {
             $rows = $GLOBALS['cfg']['MaxRows'];
         }
     }
     $this->visualization = GISVisualization::get($this->sql_query, $this->visualizationSettings, $rows, $pos);
     if (isset($_REQUEST['saveToFile'])) {
         $this->saveToFileAction();
         return;
     }
     $this->response->getHeader()->getScripts()->addFiles(array('openlayers/OpenLayers.js', 'jquery/jquery.svg.js', 'tbl_gis_visualization.js'));
     // If all the rows contain SRID, use OpenStreetMaps on the initial loading.
     if (!isset($_REQUEST['displayVisualization'])) {
         if ($this->visualization->hasSrid()) {
             $this->visualizationSettings['choice'] = 'useBaseLayer';
         } else {
             unset($this->visualizationSettings['choice']);
         }
     }
     $this->visualization->setUserSpecifiedSettings($this->visualizationSettings);
     if ($this->visualizationSettings != null) {
         foreach ($this->visualization->getSettings() as $setting => $val) {
             if (!isset($this->visualizationSettings[$setting])) {
                 $this->visualizationSettings[$setting] = $val;
             }
         }
     }
     /**
      * Displays the page
      */
     $this->url_params['sql_query'] = $this->sql_query;
     $downloadUrl = 'tbl_gis_visualization.php' . PMA_URL_getCommon(array_merge($this->url_params, array('saveToFile' => true, 'session_max_rows' => $rows, 'pos' => $pos)));
     $html = Template::get('table/gis_visualization/gis_visualization')->render(array('url_params' => $this->url_params, 'downloadUrl' => $downloadUrl, 'labelCandidates' => $labelCandidates, 'spatialCandidates' => $spatialCandidates, 'visualizationSettings' => $this->visualizationSettings, 'sql_query' => $this->sql_query, 'visualization' => $this->visualization->toImage('svg'), 'drawOl' => $this->visualization->asOl()));
     $this->response->addHTML($html);
 }
コード例 #23
0
 /**
  * Handles the whole import logic
  *
  * @return void
  */
 public function doImport()
 {
     global $error, $timeout_passed, $finished;
     // Defaults for parser
     // The buffer that will be used to store chunks read from the imported file
     $buffer = '';
     // Used as storage for the last part of the current chunk data
     // Will be appended to the first line of the next chunk, if there is one
     $last_chunk_line = '';
     // Remembers whether the current buffer line is part of a comment
     $inside_comment = false;
     // Remembers whether the current buffer line is part of a data comment
     $inside_data_comment = false;
     // Remembers whether the current buffer line is part of a structure comment
     $inside_structure_comment = false;
     // MediaWiki only accepts "\n" as row terminator
     $mediawiki_new_line = "\n";
     // Initialize the name of the current table
     $cur_table_name = "";
     while (!$finished && !$error && !$timeout_passed) {
         $data = PMA_importGetNextChunk();
         if ($data === false) {
             // Subtract data we didn't handle yet and stop processing
             $GLOBALS['offset'] -= mb_strlen($buffer);
             break;
         } elseif ($data === true) {
             // Handle rest of buffer
         } else {
             // Append new data to buffer
             $buffer = $data;
             unset($data);
             // Don't parse string if we're not at the end
             // and don't have a new line inside
             if (mb_strpos($buffer, $mediawiki_new_line) === false) {
                 continue;
             }
         }
         // Because of reading chunk by chunk, the first line from the buffer
         // contains only a portion of an actual line from the imported file.
         // Therefore, we have to append it to the last line from the previous
         // chunk. If we are at the first chunk, $last_chunk_line should be empty.
         $buffer = $last_chunk_line . $buffer;
         // Process the buffer line by line
         $buffer_lines = explode($mediawiki_new_line, $buffer);
         $full_buffer_lines_count = count($buffer_lines);
         // If the reading is not finalised, the final line of the current chunk
         // will not be complete
         if (!$finished) {
             $last_chunk_line = $buffer_lines[--$full_buffer_lines_count];
         }
         for ($line_nr = 0; $line_nr < $full_buffer_lines_count; ++$line_nr) {
             $cur_buffer_line = trim($buffer_lines[$line_nr]);
             // If the line is empty, go to the next one
             if ($cur_buffer_line === '') {
                 continue;
             }
             $first_character = $cur_buffer_line[0];
             $matches = array();
             // Check beginning of comment
             if (!strcmp(mb_substr($cur_buffer_line, 0, 4), "<!--")) {
                 $inside_comment = true;
                 continue;
             } elseif ($inside_comment) {
                 // Check end of comment
                 if (!strcmp(mb_substr($cur_buffer_line, 0, 4), "-->")) {
                     // Only data comments are closed. The structure comments
                     // will be closed when a data comment begins (in order to
                     // skip structure tables)
                     if ($inside_data_comment) {
                         $inside_data_comment = false;
                     }
                     // End comments that are not related to table structure
                     if (!$inside_structure_comment) {
                         $inside_comment = false;
                     }
                 } else {
                     // Check table name
                     $match_table_name = array();
                     if (preg_match("/^Table data for `(.*)`\$/", $cur_buffer_line, $match_table_name)) {
                         $cur_table_name = $match_table_name[1];
                         $inside_data_comment = true;
                         $inside_structure_comment = $this->_mngInsideStructComm($inside_structure_comment);
                     } elseif (preg_match("/^Table structure for `(.*)`\$/", $cur_buffer_line, $match_table_name)) {
                         // The structure comments will be ignored
                         $inside_structure_comment = true;
                     }
                 }
                 continue;
             } elseif (preg_match('/^\\{\\|(.*)$/', $cur_buffer_line, $matches)) {
                 // Check start of table
                 // This will store all the column info on all rows from
                 // the current table read from the buffer
                 $cur_temp_table = array();
                 // Will be used as storage for the current row in the buffer
                 // Once all its columns are read, it will be added to
                 // $cur_temp_table and then it will be emptied
                 $cur_temp_line = array();
                 // Helps us differentiate the header columns
                 // from the normal columns
                 $in_table_header = false;
                 // End processing because the current line does not
                 // contain any column information
             } elseif (mb_substr($cur_buffer_line, 0, 2) === '|-' || mb_substr($cur_buffer_line, 0, 2) === '|+' || mb_substr($cur_buffer_line, 0, 2) === '|}') {
                 // Check begin row or end table
                 // Add current line to the values storage
                 if (!empty($cur_temp_line)) {
                     // If the current line contains header cells
                     // ( marked with '!' ),
                     // it will be marked as table header
                     if ($in_table_header) {
                         // Set the header columns
                         $cur_temp_table_headers = $cur_temp_line;
                     } else {
                         // Normal line, add it to the table
                         $cur_temp_table[] = $cur_temp_line;
                     }
                 }
                 // Empty the temporary buffer
                 $cur_temp_line = array();
                 // No more processing required at the end of the table
                 if (mb_substr($cur_buffer_line, 0, 2) === '|}') {
                     $current_table = array($cur_table_name, $cur_temp_table_headers, $cur_temp_table);
                     // Import the current table data into the database
                     $this->_importDataOneTable($current_table);
                     // Reset table name
                     $cur_table_name = "";
                 }
                 // What's after the row tag is now only attributes
             } elseif ($first_character === '|' || $first_character === '!') {
                 // Check cell elements
                 // Header cells
                 if ($first_character === '!') {
                     // Mark as table header, but treat as normal row
                     $cur_buffer_line = str_replace('!!', '||', $cur_buffer_line);
                     // Will be used to set $cur_temp_line as table header
                     $in_table_header = true;
                 } else {
                     $in_table_header = false;
                 }
                 // Loop through each table cell
                 $cells = $this->_explodeMarkup($cur_buffer_line);
                 foreach ($cells as $cell) {
                     $cell = $this->_getCellData($cell);
                     // Delete the beginning of the column, if there is one
                     $cell = trim($cell);
                     $col_start_chars = array("|", "!");
                     foreach ($col_start_chars as $col_start_char) {
                         $cell = $this->_getCellContent($cell, $col_start_char);
                     }
                     // Add the cell to the row
                     $cur_temp_line[] = $cell;
                 }
                 // foreach $cells
             } else {
                 // If it's none of the above, then the current line has a bad
                 // format
                 $message = PMA\libraries\Message::error(__('Invalid format of mediawiki input on line: <br />%s.'));
                 $message->addParam($cur_buffer_line);
                 $error = true;
             }
         }
         // End treating full buffer lines
     }
     // while - finished parsing buffer
 }
コード例 #24
0
 /**
  * Execute the query and return the result
  *
  * @return void
  */
 public function indexAction()
 {
     if (isset($_REQUEST['ajax_request']) && isset($_REQUEST['pos']) && isset($_REQUEST['session_max_rows'])) {
         $this->ajaxAction();
         return;
     }
     // Throw error if no sql query is set
     if (!isset($this->sql_query) || $this->sql_query == '') {
         $this->response->setRequestStatus(false);
         $this->response->addHTML(Message::error(__('No SQL query was set to fetch data.')));
         return;
     }
     $this->response->getHeader()->getScripts()->addFiles(array('chart.js', 'tbl_chart.js', 'jqplot/jquery.jqplot.js', 'jqplot/plugins/jqplot.barRenderer.js', 'jqplot/plugins/jqplot.canvasAxisLabelRenderer.js', 'jqplot/plugins/jqplot.canvasTextRenderer.js', 'jqplot/plugins/jqplot.categoryAxisRenderer.js', 'jqplot/plugins/jqplot.dateAxisRenderer.js', 'jqplot/plugins/jqplot.pointLabels.js', 'jqplot/plugins/jqplot.pieRenderer.js', 'jqplot/plugins/jqplot.highlighter.js'));
     /**
      * Extract values for common work
      * @todo Extract common files
      */
     $db =& $this->db;
     $table =& $this->table;
     /**
      * Runs common work
      */
     if (mb_strlen($this->table)) {
         $url_params['goto'] = Util::getScriptNameForOption($this->cfg['DefaultTabTable'], 'table');
         $url_params['back'] = 'tbl_sql.php';
         include 'libraries/tbl_common.inc.php';
         include 'libraries/tbl_info.inc.php';
     } elseif (mb_strlen($this->db)) {
         $url_params['goto'] = Util::getScriptNameForOption($this->cfg['DefaultTabDatabase'], 'database');
         $url_params['back'] = 'sql.php';
         include 'libraries/db_common.inc.php';
     } else {
         $url_params['goto'] = Util::getScriptNameForOption($this->cfg['DefaultTabServer'], 'server');
         $url_params['back'] = 'sql.php';
         include 'libraries/server_common.inc.php';
     }
     $data = array();
     $result = $this->dbi->tryQuery($this->sql_query);
     $fields_meta = $this->dbi->getFieldsMeta($result);
     while ($row = $this->dbi->fetchAssoc($result)) {
         $data[] = $row;
     }
     $keys = array_keys($data[0]);
     $numeric_types = array('int', 'real');
     $numeric_column_count = 0;
     foreach ($keys as $idx => $key) {
         if (in_array($fields_meta[$idx]->type, $numeric_types)) {
             $numeric_column_count++;
         }
     }
     if ($numeric_column_count == 0) {
         $this->response->setRequestStatus(false);
         $this->response->addJSON('message', __('No numeric columns present in the table to plot.'));
         return;
     }
     $url_params['db'] = $this->db;
     $url_params['reload'] = 1;
     /**
      * Displays the page
      */
     $this->response->addHTML(Template::get('table/chart/tbl_chart')->render(array('url_query' => $this->url_query, 'url_params' => $url_params, 'keys' => $keys, 'fields_meta' => $fields_meta, 'numeric_types' => $numeric_types, 'numeric_column_count' => $numeric_column_count, 'sql_query' => $this->sql_query)));
 }
コード例 #25
0
/**
 * Gets HTML to display import dialogs
 *
 * @param String $import_type     Import type: server|database|table
 * @param String $db              Selected DB
 * @param String $table           Selected Table
 * @param int    $max_upload_size Max upload size
 *
 * @return string $html
 */
function PMA_getImportDisplay($import_type, $db, $table, $max_upload_size)
{
    global $SESSION_KEY;
    include_once './libraries/file_listing.lib.php';
    include_once './libraries/plugin_interface.lib.php';
    include_once './libraries/display_import_ajax.lib.php';
    list($SESSION_KEY, $upload_id, $plugins) = PMA_uploadProgressSetup();
    /* Scan for plugins */
    /* @var $import_list ImportPlugin[] */
    $import_list = PMA_getPlugins("import", 'libraries/plugins/import/', $import_type);
    /* Fail if we didn't find any plugin */
    if (empty($import_list)) {
        Message::error(__('Could not load import plugins, please check your installation!'))->display();
        exit;
    }
    if (PMA_isValid($_REQUEST['offset'], 'numeric')) {
        $offset = $_REQUEST['offset'];
    }
    if (isset($_REQUEST['timeout_passed'])) {
        $timeout_passed = $_REQUEST['timeout_passed'];
    }
    $local_import_file = '';
    if (isset($_REQUEST['local_import_file'])) {
        $local_import_file = $_REQUEST['local_import_file'];
    }
    $timeout_passed_str = isset($timeout_passed) ? $timeout_passed : null;
    $offset_str = isset($offset) ? $offset : null;
    return PMA_getHtmlForImport($upload_id, $import_type, $db, $table, $max_upload_size, $import_list, $timeout_passed_str, $offset_str, $local_import_file);
}
コード例 #26
0
/**
 * Gets HTML to display export dialogs
 *
 * @param String $export_type    export type: server|database|table
 * @param String $db             selected DB
 * @param String $table          selected table
 * @param String $sql_query      SQL query
 * @param Int    $num_tables     number of tables
 * @param Int    $unlim_num_rows unlimited number of rows
 * @param String $multi_values   selector options
 *
 * @return string $html
 */
function PMA_getExportDisplay($export_type, $db, $table, $sql_query, $num_tables, $unlim_num_rows, $multi_values)
{
    $cfgRelation = PMA_getRelationsParam();
    if (isset($_REQUEST['single_table'])) {
        $GLOBALS['single_table'] = $_REQUEST['single_table'];
    }
    include_once './libraries/file_listing.lib.php';
    include_once './libraries/plugin_interface.lib.php';
    include_once './libraries/display_export.lib.php';
    /* Scan for plugins */
    /* @var $export_list ExportPlugin[] */
    $export_list = PMA_getPlugins("export", 'libraries/plugins/export/', array('export_type' => $export_type, 'single_table' => isset($GLOBALS['single_table'])));
    /* Fail if we didn't find any plugin */
    if (empty($export_list)) {
        Message::error(__('Could not load export plugins, please check your installation!'))->display();
        exit;
    }
    $html = PMA_getHtmlForExportOptionHeader($export_type, $db, $table);
    if ($cfgRelation['exporttemplateswork']) {
        $html .= PMA_getHtmlForExportTemplateLoading($export_type);
    }
    $html .= '<form method="post" action="export.php" ' . ' name="dump" class="disableAjax">';
    //output Hidden Inputs
    $single_table_str = isset($GLOBALS['single_table']) ? $GLOBALS['single_table'] : '';
    $html .= PMA_getHtmlForHiddenInput($export_type, $db, $table, $single_table_str, $sql_query);
    //output Export Options
    $html .= PMA_getHtmlForExportOptions($export_type, $db, $table, $multi_values, $num_tables, $export_list, $unlim_num_rows);
    $html .= '</form>';
    return $html;
}
コード例 #27
0
/**
 * Move or copy a table
 *
 * @param string $db    current database name
 * @param string $table current table name
 *
 * @return void
 */
function PMA_moveOrCopyTable($db, $table)
{
    /**
     * Selects the database to work with
     */
    $GLOBALS['dbi']->selectDb($db);
    /**
     * $_REQUEST['target_db'] could be empty in case we came from an input field
     * (when there are many databases, no drop-down)
     */
    if (empty($_REQUEST['target_db'])) {
        $_REQUEST['target_db'] = $db;
    }
    /**
     * A target table name has been sent to this script -> do the work
     */
    if (PMA_isValid($_REQUEST['new_name'])) {
        if ($db == $_REQUEST['target_db'] && $table == $_REQUEST['new_name']) {
            if (isset($_REQUEST['submit_move'])) {
                $message = Message::error(__('Can\'t move table to same one!'));
            } else {
                $message = Message::error(__('Can\'t copy table to same one!'));
            }
        } else {
            Table::moveCopy($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name'], $_REQUEST['what'], isset($_REQUEST['submit_move']), 'one_table');
            if (isset($_REQUEST['adjust_privileges']) && !empty($_REQUEST['adjust_privileges'])) {
                if (isset($_REQUEST['submit_move'])) {
                    PMA_AdjustPrivileges_renameOrMoveTable($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name']);
                } else {
                    PMA_AdjustPrivileges_copyTable($db, $table, $_REQUEST['target_db'], $_REQUEST['new_name']);
                }
                if (isset($_REQUEST['submit_move'])) {
                    $message = Message::success(__('Table %s has been moved to %s. Privileges have been ' . 'adjusted.'));
                } else {
                    $message = Message::success(__('Table %s has been copied to %s. Privileges have been ' . 'adjusted.'));
                }
            } else {
                if (isset($_REQUEST['submit_move'])) {
                    $message = Message::success(__('Table %s has been moved to %s.'));
                } else {
                    $message = Message::success(__('Table %s has been copied to %s.'));
                }
            }
            $old = PMA\libraries\Util::backquote($db) . '.' . PMA\libraries\Util::backquote($table);
            $message->addParam($old);
            $new = PMA\libraries\Util::backquote($_REQUEST['target_db']) . '.' . PMA\libraries\Util::backquote($_REQUEST['new_name']);
            $message->addParam($new);
            /* Check: Work on new table or on old table? */
            if (isset($_REQUEST['submit_move']) || PMA_isValid($_REQUEST['switch_to_new'])) {
            }
        }
    } else {
        /**
         * No new name for the table!
         */
        $message = Message::error(__('The table name is empty!'));
    }
    if ($GLOBALS['is_ajax_request'] == true) {
        $response = PMA\libraries\Response::getInstance();
        $response->addJSON('message', $message);
        if ($message->isSuccess()) {
            $response->addJSON('db', $GLOBALS['db']);
        } else {
            $response->setRequestStatus(false);
        }
        exit;
    }
}
コード例 #28
0
ファイル: ImportXml.php プロジェクト: kbigbus/phpmyadmin
 /**
  * Handles the whole import logic
  *
  * @return void
  */
 public function doImport()
 {
     global $error, $timeout_passed, $finished, $db;
     $i = 0;
     $len = 0;
     $buffer = "";
     /**
      * Read in the file via PMA_importGetNextChunk so that
      * it can process compressed files
      */
     while (!($finished && $i >= $len) && !$error && !$timeout_passed) {
         $data = PMA_importGetNextChunk();
         if ($data === false) {
             /* subtract data we didn't handle yet and stop processing */
             $GLOBALS['offset'] -= strlen($buffer);
             break;
         } elseif ($data === true) {
             /* Handle rest of buffer */
         } else {
             /* Append new data to buffer */
             $buffer .= $data;
             unset($data);
         }
     }
     unset($data);
     /**
      * Disable loading of external XML entities.
      */
     libxml_disable_entity_loader();
     /**
      * Load the XML string
      *
      * The option LIBXML_COMPACT is specified because it can
      * result in increased performance without the need to
      * alter the code in any way. It's basically a freebee.
      */
     $xml = @simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT);
     unset($buffer);
     /**
      * The XML was malformed
      */
     if ($xml === false) {
         PMA\libraries\Message::error(__('The XML file specified was either malformed or incomplete.' . ' Please correct the issue and try again.'))->display();
         unset($xml);
         $GLOBALS['finished'] = false;
         return;
     }
     /**
      * Table accumulator
      */
     $tables = array();
     /**
      * Row accumulator
      */
     $rows = array();
     /**
      * Temp arrays
      */
     $tempRow = array();
     $tempCells = array();
     /**
      * CREATE code included (by default: no)
      */
     $struct_present = false;
     /**
      * Analyze the data in each table
      */
     $namespaces = $xml->getNameSpaces(true);
     /**
      * Get the database name, collation and charset
      */
     $db_attr = $xml->children($namespaces['pma'])->{'structure_schemas'}->{'database'};
     if ($db_attr instanceof SimpleXMLElement) {
         $db_attr = $db_attr->attributes();
         $db_name = (string) $db_attr['name'];
         $collation = (string) $db_attr['collation'];
         $charset = (string) $db_attr['charset'];
     } else {
         /**
          * If the structure section is not present
          * get the database name from the data section
          */
         $db_attr = $xml->children()->attributes();
         $db_name = (string) $db_attr['name'];
         $collation = null;
         $charset = null;
     }
     /**
      * The XML was malformed
      */
     if ($db_name === null) {
         PMA\libraries\Message::error(__('The XML file specified was either malformed or incomplete.' . ' Please correct the issue and try again.'))->display();
         unset($xml);
         $GLOBALS['finished'] = false;
         return;
     }
     /**
      * Retrieve the structure information
      */
     if (isset($namespaces['pma'])) {
         /**
          * Get structures for all tables
          *
          * @var SimpleXMLElement $struct
          */
         $struct = $xml->children($namespaces['pma']);
         $create = array();
         /** @var SimpleXMLElement $val1 */
         foreach ($struct as $val1) {
             /** @var SimpleXMLElement $val2 */
             foreach ($val1 as $val2) {
                 // Need to select the correct database for the creation of
                 // tables, views, triggers, etc.
                 /**
                  * @todo    Generating a USE here blocks importing of a table
                  *          into another database.
                  */
                 $attrs = $val2->attributes();
                 $create[] = "USE " . PMA\libraries\Util::backquote($attrs["name"]);
                 foreach ($val2 as $val3) {
                     /**
                      * Remove the extra cosmetic spacing
                      */
                     $val3 = str_replace("                ", "", (string) $val3);
                     $create[] = $val3;
                 }
             }
         }
         $struct_present = true;
     }
     /**
      * Move down the XML tree to the actual data
      */
     $xml = $xml->children()->children();
     $data_present = false;
     /**
      * Only attempt to analyze/collect data if there is data present
      */
     if ($xml && @count($xml->children())) {
         $data_present = true;
         /**
          * Process all database content
          */
         foreach ($xml as $v1) {
             $tbl_attr = $v1->attributes();
             $isInTables = false;
             $num_tables = count($tables);
             for ($i = 0; $i < $num_tables; ++$i) {
                 if (!strcmp($tables[$i][TBL_NAME], (string) $tbl_attr['name'])) {
                     $isInTables = true;
                     break;
                 }
             }
             if (!$isInTables) {
                 $tables[] = array((string) $tbl_attr['name']);
             }
             foreach ($v1 as $v2) {
                 $row_attr = $v2->attributes();
                 if (!array_search((string) $row_attr['name'], $tempRow)) {
                     $tempRow[] = (string) $row_attr['name'];
                 }
                 $tempCells[] = (string) $v2;
             }
             $rows[] = array((string) $tbl_attr['name'], $tempRow, $tempCells);
             $tempRow = array();
             $tempCells = array();
         }
         unset($tempRow);
         unset($tempCells);
         unset($xml);
         /**
          * Bring accumulated rows into the corresponding table
          */
         $num_tables = count($tables);
         for ($i = 0; $i < $num_tables; ++$i) {
             $num_rows = count($rows);
             for ($j = 0; $j < $num_rows; ++$j) {
                 if (!strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) {
                     if (!isset($tables[$i][COL_NAMES])) {
                         $tables[$i][] = $rows[$j][COL_NAMES];
                     }
                     $tables[$i][ROWS][] = $rows[$j][ROWS];
                 }
             }
         }
         unset($rows);
         if (!$struct_present) {
             $analyses = array();
             $len = count($tables);
             for ($i = 0; $i < $len; ++$i) {
                 $analyses[] = PMA_analyzeTable($tables[$i]);
             }
         }
     }
     unset($xml);
     unset($tempCells);
     unset($rows);
     /**
      * Only build SQL from data if there is data present
      */
     if ($data_present) {
         /**
          * Set values to NULL if they were not present
          * to maintain PMA_buildSQL() call integrity
          */
         if (!isset($analyses)) {
             $analyses = null;
             if (!$struct_present) {
                 $create = null;
             }
         }
     }
     /**
      * string $db_name (no backquotes)
      *
      * array $table = array(table_name, array() column_names, array()() rows)
      * array $tables = array of "$table"s
      *
      * array $analysis = array(array() column_types, array() column_sizes)
      * array $analyses = array of "$analysis"s
      *
      * array $create = array of SQL strings
      *
      * array $options = an associative array of options
      */
     /* Set database name to the currently selected one, if applicable */
     if (strlen($db)) {
         /* Override the database name in the XML file, if one is selected */
         $db_name = $db;
         $options = array('create_db' => false);
     } else {
         if ($db_name === null) {
             $db_name = 'XML_DB';
         }
         /* Set database collation/charset */
         $options = array('db_collation' => $collation, 'db_charset' => $charset);
     }
     /* Created and execute necessary SQL statements from data */
     PMA_buildSQL($db_name, $tables, $analyses, $create, $options);
     unset($analyses);
     unset($tables);
     unset($create);
     /* Commit any possible data in buffers */
     PMA_importRunQuery();
 }
コード例 #29
0
/**
 * Handles requests for executing a routine
 *
 * @return void
 */
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, true);
        if ($routine === false) {
            $message = __('Error in processing request:') . ' ';
            $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA\libraries\Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA\libraries\Util::backquote($db)));
            $message = Message::error($message);
            if ($GLOBALS['is_ajax_request']) {
                $response = PMA\libraries\Response::getInstance();
                $response->setRequestStatus(false);
                $response->addJSON('message', $message);
                exit;
            } else {
                echo $message->getDisplay();
                unset($_POST);
            }
        }
        $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 = $GLOBALS['dbi']->escapeString($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\libraries\Util::backquote($routine['item_param_name'][$i]);
                }
            }
        }
        if ($routine['item_type'] == 'PROCEDURE') {
            $queries[] = "CALL " . PMA\libraries\Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n";
            if (count($end_query)) {
                $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
            }
        } else {
            $queries[] = "SELECT " . PMA\libraries\Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA\libraries\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 (!$GLOBALS['dbi']->tryMultiQuery($multiple_query)) {
            $outcome = false;
        }
        // Generate output
        if ($outcome) {
            // Pass the SQL queries through the "pretty printer"
            $output = PMA\libraries\Util::formatSql(implode($queries, "\n"));
            // Display results
            $output .= "<fieldset><legend>";
            $output .= sprintf(__('Execution results of routine %s'), PMA\libraries\Util::backquote(htmlspecialchars($routine['item_name'])));
            $output .= "</legend>";
            $nbResultsetToDisplay = 0;
            do {
                $result = $GLOBALS['dbi']->storeResult();
                $num_rows = $GLOBALS['dbi']->numRows($result);
                if ($result !== false && $num_rows > 0) {
                    $output .= "<table><tr>";
                    foreach ($GLOBALS['dbi']->getFieldsMeta($result) as $field) {
                        $output .= "<th>";
                        $output .= htmlspecialchars($field->name);
                        $output .= "</th>";
                    }
                    $output .= "</tr>";
                    $color_class = 'odd';
                    while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
                        $output .= "<tr>" . browseRow($row, $color_class) . "</tr>";
                        $color_class = $color_class == 'odd' ? 'even' : 'odd';
                    }
                    $output .= "</table>";
                    $nbResultsetToDisplay++;
                    $affected = $num_rows;
                }
                if (!$GLOBALS['dbi']->moreResults()) {
                    break;
                }
                $output .= "<br/>";
                $GLOBALS['dbi']->freeResult($result);
            } while ($GLOBALS['dbi']->nextResult());
            $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 = Message::success($message);
            if ($nbResultsetToDisplay == 0) {
                $notice = __('MySQL returned an empty result set (i.e. zero rows).');
                $output .= Message::notice($notice)->getDisplay();
            }
        } else {
            $output = '';
            $message = Message::error(sprintf(__('The following query has failed: "%s"'), htmlspecialchars($multiple_query)) . '<br /><br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null));
        }
        // Print/send output
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            $response->setRequestStatus($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
        }
        return;
    } 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, true);
            if ($routine !== false) {
                $form = PMA_RTN_getExecuteForm($routine);
                if ($GLOBALS['is_ajax_request'] == true) {
                    $title = __("Execute routine") . " " . PMA\libraries\Util::backquote(htmlentities($_GET['item_name'], ENT_QUOTES));
                    $response = PMA\libraries\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\libraries\Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA\libraries\Util::backquote($db)));
                    $message = Message::error($message);
                    $response = PMA\libraries\Response::getInstance();
                    $response->setRequestStatus(false);
                    $response->addJSON('message', $message);
                    exit;
                }
            }
        }
    }
}
コード例 #30
0
ファイル: Util.php プロジェクト: nijel/phpmyadmin
    /**
     * Prepare the form used to select a file to import from the server upload
     * directory
     *
     * @param ImportPlugin[] $import_list array of import plugins
     * @param string         $uploaddir   upload directory
     *
     * @return String
     */
    public static function getSelectUploadFileBlock($import_list, $uploaddir)
    {
        $block_html = '';
        $block_html .= '<label for="radio_local_import_file">'
            . sprintf(
                __("Select from the web server upload directory <b>%s</b>:"),
                htmlspecialchars(self::userDir($uploaddir))
            )
            . '</label>';

        $extensions = '';
        foreach ($import_list as $import_plugin) {
            if (! empty($extensions)) {
                $extensions .= '|';
            }
            $extensions .= $import_plugin->getProperties()->getExtension();
        }

        $matcher = '@\.(' . $extensions . ')(\.('
            . PMA_supportedDecompressions() . '))?$@';

        $active = (isset($GLOBALS['timeout_passed']) && $GLOBALS['timeout_passed']
            && isset($GLOBALS['local_import_file']))
            ? $GLOBALS['local_import_file']
            : '';

        $files = PMA_getFileSelectOptions(
            self::userDir($uploaddir),
            $matcher,
            $active
        );

        if ($files === false) {
            Message::error(
                __('The directory you set for upload work cannot be reached.')
            )->display();
        } elseif (! empty($files)) {
            $block_html .= "\n"
                . '    <select style="margin: 5px" size="1" '
                . 'name="local_import_file" '
                . 'id="select_local_import_file">' . "\n"
                . '        <option value="">&nbsp;</option>' . "\n"
                . $files
                . '    </select>' . "\n";
        } elseif (empty($files)) {
            $block_html .= '<i>' . __('There are no files to upload!') . '</i>';
        }

        return $block_html;

    }