simple usage examples: display simple error message 'Error' Message::error()->display(); get simple success message 'Success' $message = Message::success(); get special notice $message = Message::notice(__('This is a localized notice')); more advanced usage example: create another message, a hint, with a localized string which expects $hint = Message::notice('Read the %smanual%s'); replace placeholders with the following params $hint->addParam('[doc@cfg_Example]'); $hint->addParam('[/doc]'); add this hint as a tooltip $hint = showHint($hint); add the retrieved tooltip reference to the original message $message->addMessage($hint);
Example #1
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();
        }
    }
}
Example #2
0
/**
 * 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();
        }
    }
}
/**
 * Get HTML for the Change password dialog
 *
 * @param string $username username
 * @param string $hostname hostname
 *
 * @return string html snippet
 */
function PMA_getHtmlForChangePassword($username, $hostname)
{
    /**
     * autocomplete feature of IE kills the "onchange" event handler and it
     * must be replaced by the "onpropertychange" one in this case
     */
    $chg_evt_handler = PMA_USR_BROWSER_AGENT == 'IE' && PMA_USR_BROWSER_VER >= 5 && PMA_USR_BROWSER_VER < 7 ? 'onpropertychange' : 'onchange';
    $is_privileges = basename($_SERVER['SCRIPT_NAME']) === 'server_privileges.php';
    $html = '<form method="post" id="change_password_form" ' . 'action="' . basename($GLOBALS['PMA_PHP_SELF']) . '" ' . 'name="chgPassword" ' . 'class="' . ($is_privileges ? 'submenu-item' : '') . '">';
    $html .= PMA_URL_getHiddenInputs();
    if (strpos($GLOBALS['PMA_PHP_SELF'], 'server_privileges') !== false) {
        $html .= '<input type="hidden" name="username" ' . 'value="' . htmlspecialchars($username) . '" />' . '<input type="hidden" name="hostname" ' . 'value="' . htmlspecialchars($hostname) . '" />';
    }
    $html .= '<fieldset id="fieldset_change_password">' . '<legend' . ($is_privileges ? ' data-submenu-label="' . __('Change password') . '"' : '') . '>' . __('Change password') . '</legend>' . '<table class="data noclick">' . '<tr class="odd">' . '<td colspan="2">' . '<input type="radio" name="nopass" value="1" id="nopass_1" ' . 'onclick="pma_pw.value = \'\'; pma_pw2.value = \'\'; ' . 'this.checked = true" />' . '<label for="nopass_1">' . __('No Password') . '</label>' . '</td>' . '</tr>' . '<tr class="even vmiddle">' . '<td>' . '<input type="radio" name="nopass" value="0" id="nopass_0" ' . 'onclick="document.getElementById(\'text_pma_pw\').focus();" ' . 'checked="checked" />' . '<label for="nopass_0">' . __('Password:'******'&nbsp;</label>' . '</td>' . '<td>' . '<input type="password" name="pma_pw" id="text_pma_pw" size="10" ' . 'class="textfield"' . $chg_evt_handler . '="nopass[1].checked = true" />' . '&nbsp;&nbsp;' . __('Re-type:') . '&nbsp;' . '<input type="password" name="pma_pw2" id="text_pma_pw2" size="10" ' . 'class="textfield"' . $chg_evt_handler . '="nopass[1].checked = true" />' . '</td>' . '</tr>';
    $html .= '<tr class="vmiddle">' . '<td>' . __('Password Hashing:') . '</td><td>';
    $serverType = PMA\libraries\Util::getServerType();
    $orig_auth_plugin = PMA_getCurrentAuthenticationPlugin('change', $username, $hostname);
    if ($serverType == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50507 || $serverType == 'MariaDB' && PMA_MYSQL_INT_VERSION >= 50200) {
        $auth_plugin_dropdown = PMA_getHtmlForAuthPluginsDropdown($username, $hostname, $orig_auth_plugin, 'change_pw', 'new');
        $html .= $auth_plugin_dropdown;
        $html .= '</td></tr>';
        $html .= '<tr id="tr_element_before_generate_password"></tr>';
        $html .= '</table>';
        $html .= '<div ' . ($orig_auth_plugin != 'sha256_password' ? 'style="display:none"' : '') . ' id="ssl_reqd_warning_cp">' . Message::notice(__('This method requires using an \'<i>SSL connection</i>\' ' . 'or an \'<i>unencrypted connection that encrypts the password ' . 'using RSA</i>\'; while connecting to the server.') . PMA\libraries\Util::showMySQLDocu('sha256-authentication-plugin'))->getDisplay() . '</div>';
        $html .= '<div ' . ($orig_auth_plugin != 'sha256_password' ? 'style="display:none"' : '') . ' id="ssl_reqd_warning_cp">' . Message::notice(__('This method requires using an \'<i>SSL connection</i>\' ' . 'or an \'<i>unencrypted connection that encrypts the password ' . 'using RSA</i>\'; while connecting to the server.') . PMA\libraries\Util::showMySQLDocu('sha256-authentication-plugin'))->getDisplay() . '</div>';
    } else {
        $auth_plugin_dropdown = PMA_getHtmlForAuthPluginsDropdown($username, $hostname, $orig_auth_plugin, 'change_pw', 'old');
        $html .= $auth_plugin_dropdown . '</td></tr>' . '<tr id="tr_element_before_generate_password"></tr>' . '</table>';
    }
    $html .= '</fieldset>' . '<fieldset id="fieldset_change_password_footer" class="tblFooters">' . '<input type="hidden" name="change_pw" value="1" />' . '<input type="submit" value="' . __('Go') . '" />' . '</fieldset>' . '</form>';
    return $html;
}
Example #4
0
 /**
  * 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;
 }
/**
 * 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));
}
Example #6
0
 /**
  * Returns the message for demo server to error messages
  *
  * @return string
  */
 private function _getDemoMessage()
 {
     $message = '<a href="/">' . __('phpMyAdmin Demo Server') . '</a>: ';
     if (file_exists('./revision-info.php')) {
         include './revision-info.php';
         $message .= sprintf(__('Currently running Git revision %1$s from the %2$s branch.'), '<a target="_blank" href="' . $repobase . $fullrevision . '">' . $revision . '</a>', '<a target="_blank" href="' . $repobranchbase . $branch . '">' . $branch . '</a>');
     } else {
         $message .= __('Git information missing!');
     }
     return Message::notice($message)->getDisplay();
 }
/**
 * Prints html for auto refreshing processes list
 *
 * @return string
 */
function PMA_getHtmlForProcessListAutoRefresh()
{
    $notice = Message::notice(__('Note: Enabling the auto refresh here might cause ' . 'heavy traffic between the web server and the MySQL server.'))->getDisplay();
    $retval = $notice . '<div class="tabLinks">';
    $retval .= '<label>' . __('Refresh rate') . ': ';
    $retval .= ServerStatusData::getHtmlForRefreshList('refreshRate', 5, array(2, 3, 4, 5, 10, 20, 40, 60, 120, 300, 600, 1200));
    $retval .= '</label>';
    $retval .= '<a id="toggleRefresh" href="#">';
    $retval .= Util::getImage('play.png') . __('Start auto refresh');
    $retval .= '</a>';
    $retval .= '</div>';
    return $retval;
}
 /**
  * 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());
     }
 }
Example #9
0
 /**
  * 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;
 }
 /**
  * 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;
     }
 }
Example #11
0
 /**
  * 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;
     }
 }
Example #12
0
            $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();
    unset($db_charset);
    /**
     * If we are in an Ajax request, let us stop the execution here. Necessary for
     * db charset change action on db_operations.php.  If this causes a bug on
     * other pages, we might have to move this to a different location.
     */
    if ($GLOBALS['is_ajax_request'] == true) {
        $response = PMA\libraries\Response::getInstance();
        $response->setRequestStatus($message->isSuccess());
        $response->addJSON('message', $message);
        exit;
    }
}
/**
 * Set parameters for links
Example #13
0
/**
 * Flush privileges and get message
 *
 * @param bool $flushPrivileges Flush privileges
 *
 * @return PMA\libraries\Message
 */
function PMA_RTN_flushPrivileges($flushPrivileges)
{
    if ($flushPrivileges) {
        // Flush the Privileges
        $flushPrivQuery = 'FLUSH PRIVILEGES;';
        $GLOBALS['dbi']->query($flushPrivQuery);
        $message = PMA\libraries\Message::success(__('Routine %1$s has been modified. Privileges have been adjusted.'));
    } else {
        $message = PMA\libraries\Message::success(__('Routine %1$s has been modified.'));
    }
    $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
    return $message;
}
Example #14
0
                     class="prefsmanage_opts disabled">
                    <span class="localStorage-supported">
                        <?php 
echo __('Settings will be saved in your browser\'s local ' . 'storage.');
?>
                        <div class="localStorage-exists">
                            <b>
                                <?php 
echo __('Existing settings will be overwritten!');
?>
                            </b>
                        </div>
                    </span>
                    <div class="localStorage-unsupported">
                        <?php 
Message::notice(__('This feature is not supported by your web browser'))->display();
?>
                    </div>
                </div>
                <br />
                <?php 
echo '<input type="submit" name="submit_export" value="', __('Go'), '" />';
?>
            </form>
        </div>
        <div class="group">
            <h2><?php 
echo __('Reset');
?>
</h2>
            <form class="group-cnt prefs-form disableAjax" name="prefs_reset"
Example #15
0
 /**
  * Set the content that needs to be shown in message
  *
  * @param string  $sorted_column_message the message for sorted column
  * @param array   $analyzed_sql_results  the analyzed query
  * @param integer $total                 the total number of rows returned by
  *                                       the SQL query without any
  *                                       programmatically appended LIMIT clause
  * @param integer $pos_next              the offset for next page
  * @param string  $pre_count             the string renders before row count
  * @param string  $after_count           the string renders after row count
  *
  * @return Message $message an object of Message
  *
  * @access  private
  *
  * @see     getTable()
  */
 private function _setMessageInformation($sorted_column_message, $analyzed_sql_results, $total, $pos_next, $pre_count, $after_count)
 {
     $unlim_num_rows = $this->__get('unlim_num_rows');
     // To use in isset()
     if (!empty($analyzed_sql_results['statement']->limit)) {
         $first_shown_rec = $analyzed_sql_results['statement']->limit->offset;
         $row_count = $analyzed_sql_results['statement']->limit->rowCount;
         if ($row_count < $total) {
             $last_shown_rec = $first_shown_rec + $row_count - 1;
         } else {
             $last_shown_rec = $first_shown_rec + $total - 1;
         }
     } elseif ($_SESSION['tmpval']['max_rows'] == self::ALL_ROWS || $pos_next > $total) {
         $first_shown_rec = $_SESSION['tmpval']['pos'];
         $last_shown_rec = $total - 1;
     } else {
         $first_shown_rec = $_SESSION['tmpval']['pos'];
         $last_shown_rec = $pos_next - 1;
     }
     $table = new Table($this->__get('table'), $this->__get('db'));
     if ($table->isView() && $total == $GLOBALS['cfg']['MaxExactCountViews']) {
         $message = Message::notice(__('This view has at least this number of rows. ' . 'Please refer to %sdocumentation%s.'));
         $message->addParam('[doc@cfg_MaxExactCount]');
         $message->addParam('[/doc]');
         $message_view_warning = Util::showHint($message);
     } else {
         $message_view_warning = false;
     }
     $message = Message::success(__('Showing rows %1s - %2s'));
     $message->addParam($first_shown_rec);
     if ($message_view_warning !== false) {
         $message->addParam('... ' . $message_view_warning, false);
     } else {
         $message->addParam($last_shown_rec);
     }
     $message->addMessage('(');
     if ($message_view_warning === false) {
         if (isset($unlim_num_rows) && $unlim_num_rows != $total) {
             $message_total = Message::notice($pre_count . __('%1$d total, %2$d in query'));
             $message_total->addParam($total);
             $message_total->addParam($unlim_num_rows);
         } else {
             $message_total = Message::notice($pre_count . __('%d total'));
             $message_total->addParam($total);
         }
         if (!empty($after_count)) {
             $message_total->addMessage($after_count);
         }
         $message->addMessage($message_total, '');
         $message->addMessage(', ', '');
     }
     $message_qt = Message::notice(__('Query took %01.4f seconds.') . ')');
     $message_qt->addParam($this->__get('querytime'));
     $message->addMessage($message_qt, '');
     if (!is_null($sorted_column_message)) {
         $message->addMessage($sorted_column_message, '');
     }
     return $message;
 }
Example #16
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
 }
 /**
  * Handles actions related to multiple tables
  *
  * @return void
  */
 public function multiSubmitAction()
 {
     $action = 'db_structure.php';
     $err_url = 'db_structure.php' . PMA_URL_getCommon(array('db' => $this->db));
     // see bug #2794840; in this case, code path is:
     // db_structure.php -> libraries/mult_submits.inc.php -> sql.php
     // -> db_structure.php and if we got an error on the multi submit,
     // we must display it here and not call again mult_submits.inc.php
     if (!isset($_POST['error']) || false === $_POST['error']) {
         include 'libraries/mult_submits.inc.php';
     }
     if (empty($_POST['message'])) {
         $_POST['message'] = Message::success();
     }
 }
Example #18
0
/**
 * Get Html for PMA tables fixing anchor.
 *
 * @param boolean $allTables whether to create all tables
 * @param boolean $createDb  whether to create the pmadb also
 *
 * @return string Html
 */
function PMA_getHtmlFixPMATables($allTables, $createDb = false)
{
    $retval = '';
    $url_query = PMA_URL_getCommon(array('db' => $GLOBALS['db']));
    if ($allTables) {
        if ($createDb) {
            $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
            $message = Message::notice(__('%sCreate%s a database named \'phpmyadmin\' and setup ' . 'the phpMyAdmin configuration storage there.'));
        } else {
            $url_query .= '&amp;goto=db_operations.php&amp;fixall_pmadb=1';
            $message = Message::notice(__('%sCreate%s the phpMyAdmin configuration storage in the ' . 'current database.'));
        }
    } else {
        $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
        $message = Message::notice(__('%sCreate%s missing phpMyAdmin configuration storage tables.'));
    }
    $message->addParam('<a href="' . $GLOBALS['cfg']['PmaAbsoluteUri'] . 'chk_rel.php' . $url_query . '">', false);
    $message->addParam('</a>', false);
    $retval .= $message->getDisplay();
    return $retval;
}
Example #19
0
 /**
  * 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();
 }
Example #20
0
/**
 * Function to respond back when the query returns zero rows
 * This method is called
 * 1-> When browsing an empty table
 * 2-> When executing a query on a non empty table which returns zero results
 * 3-> When executing a query on an empty table
 * 4-> When executing an INSERT, UPDATE, DELETE query from the SQL tab
 * 5-> When deleting a row from BROWSE tab
 * 6-> When searching using the SEARCH tab which returns zero results
 * 7-> When changing the structure of the table except change operation
 *
 * @param array          $analyzed_sql_results analyzed sql results
 * @param string         $db                   current database
 * @param string         $table                current table
 * @param string         $message_to_show      message to show
 * @param int            $num_rows             number of rows
 * @param DisplayResults $displayResultsObject DisplayResult instance
 * @param array          $extra_data           extra data
 * @param string         $pmaThemeImage        uri of the theme image
 * @param object         $result               executed query results
 * @param string         $sql_query            sql query
 * @param string         $complete_query       complete sql query
 *
 * @return string html
 */
function PMA_getQueryResponseForNoResultsReturned($analyzed_sql_results, $db, $table, $message_to_show, $num_rows, $displayResultsObject, $extra_data, $pmaThemeImage, $result, $sql_query, $complete_query)
{
    if (PMA_isDeleteTransformationInfo($analyzed_sql_results)) {
        PMA_deleteTransformationInfo($db, $table, $analyzed_sql_results);
    }
    if (isset($extra_data['error'])) {
        $message = PMA\libraries\Message::rawError($extra_data['error']);
    } else {
        $message = PMA_getMessageForNoRowsReturned(isset($message_to_show) ? $message_to_show : null, $analyzed_sql_results, $num_rows);
    }
    $html_output = '';
    if (!isset($GLOBALS['show_as_php'])) {
        if (!empty($GLOBALS['reload'])) {
            $extra_data['reload'] = 1;
            $extra_data['db'] = $GLOBALS['db'];
        }
        $html_message = PMA\libraries\Util::getMessage($message, $GLOBALS['sql_query'], 'success');
        $html_output .= $html_message;
        // For ajax requests add message and sql_query as JSON
        if (empty($_REQUEST['ajax_page_request'])) {
            $extra_data['message'] = $message;
            if ($GLOBALS['cfg']['ShowSQL']) {
                $extra_data['sql_query'] = $html_message;
            }
        }
        $response = PMA\libraries\Response::getInstance();
        $response->addJSON(isset($extra_data) ? $extra_data : array());
        if (!empty($analyzed_sql_results['is_select']) && !isset($extra_data['error'])) {
            $url_query = isset($url_query) ? $url_query : null;
            $displayParts = array('edit_lnk' => null, 'del_lnk' => null, 'sort_lnk' => '1', 'nav_bar' => '0', 'bkm_form' => '1', 'text_btn' => '1', 'pview_lnk' => '1');
            $html_output .= PMA_getHtmlForSqlQueryResultsTable($displayResultsObject, $pmaThemeImage, $url_query, $displayParts, false, 0, $num_rows, true, $result, $analyzed_sql_results, true);
            $html_output .= $displayResultsObject->getCreateViewQueryResultOp($analyzed_sql_results);
            $cfgBookmark = PMA_Bookmark_getParams();
            if ($cfgBookmark) {
                $html_output .= PMA_getHtmlForBookmark($displayParts, $cfgBookmark, $sql_query, $db, $table, isset($complete_query) ? $complete_query : $sql_query, $cfgBookmark['user']);
            }
        }
    }
    return $html_output;
}
Example #21
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);
    }
    $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;
    }
}
Example #22
0
/**
 * Function to display results when the executed query returns non empty results
 *
 * @param object         $result               executed query results
 * @param array          $analyzed_sql_results analysed sql results
 * @param string         $db                   current database
 * @param string         $table                current table
 * @param string         $message              message to show
 * @param array          $sql_data             sql data
 * @param DisplayResults $displayResultsObject Instance of DisplayResults
 * @param string         $pmaThemeImage        uri of the theme image
 * @param int            $unlim_num_rows       unlimited number of rows
 * @param int            $num_rows             number of rows
 * @param string         $disp_query           display query
 * @param string         $disp_message         display message
 * @param array          $profiling_results    profiling results
 * @param string         $query_type           query type
 * @param array|null     $selectedTables       array of table names selected
 *                                             from the database structure page, for
 *                                             an action like check table,
 *                                             optimize table, analyze table or
 *                                             repair table
 * @param string         $sql_query            sql query
 * @param string         $complete_query       complete sql query
 *
 * @return string html
 */
function PMA_getQueryResponseForResultsReturned($result, $analyzed_sql_results, $db, $table, $message, $sql_data, $displayResultsObject, $pmaThemeImage, $unlim_num_rows, $num_rows, $disp_query, $disp_message, $profiling_results, $query_type, $selectedTables, $sql_query, $complete_query)
{
    // If we are retrieving the full value of a truncated field or the original
    // value of a transformed field, show it here
    if (isset($_REQUEST['grid_edit']) && $_REQUEST['grid_edit'] == true) {
        PMA_sendResponseForGridEdit($result);
        // script has exited at this point
    }
    // Gets the list of fields properties
    if (isset($result) && $result) {
        $fields_meta = $GLOBALS['dbi']->getFieldsMeta($result);
    }
    // Should be initialized these parameters before parsing
    $showtable = isset($showtable) ? $showtable : null;
    $url_query = isset($url_query) ? $url_query : null;
    $response = PMA\libraries\Response::getInstance();
    $header = $response->getHeader();
    $scripts = $header->getScripts();
    // hide edit and delete links:
    // - for information_schema
    // - if the result set does not contain all the columns of a unique key
    //   (unless this is an updatable view)
    $updatableView = false;
    $statement = $analyzed_sql_results['statement'];
    if ($statement instanceof SqlParser\Statements\SelectStatement) {
        if (!empty($statement->expr)) {
            if ($statement->expr[0]->expr === '*') {
                $_table = new Table($table, $db);
                $updatableView = $_table->isUpdatableView();
            }
        }
    }
    $has_unique = PMA_resultSetContainsUniqueKey($db, $table, $fields_meta);
    $just_one_table = PMA_resultSetHasJustOneTable($fields_meta);
    $editable = ($has_unique || $GLOBALS['cfg']['RowActionLinksWithoutUnique'] || $updatableView) && $just_one_table;
    $displayParts = array('edit_lnk' => $displayResultsObject::UPDATE_ROW, 'del_lnk' => $displayResultsObject::DELETE_ROW, 'sort_lnk' => '1', 'nav_bar' => '1', 'bkm_form' => '1', 'text_btn' => '0', 'pview_lnk' => '1');
    if (!empty($table) && ($GLOBALS['dbi']->isSystemSchema($db) || !$editable)) {
        $displayParts = array('edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE, 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE, 'sort_lnk' => '1', 'nav_bar' => '1', 'bkm_form' => '1', 'text_btn' => '1', 'pview_lnk' => '1');
    }
    if (isset($_REQUEST['printview']) && $_REQUEST['printview'] == '1') {
        $displayParts = array('edit_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE, 'del_lnk' => $displayResultsObject::NO_EDIT_OR_DELETE, 'sort_lnk' => '0', 'nav_bar' => '0', 'bkm_form' => '0', 'text_btn' => '0', 'pview_lnk' => '0');
    }
    if (isset($_REQUEST['table_maintenance'])) {
        $scripts->addFile('makegrid.js');
        $scripts->addFile('sql.js');
        $table_maintenance_html = '';
        if (isset($message)) {
            $message = Message::success($message);
            $table_maintenance_html = PMA\libraries\Util::getMessage($message, $GLOBALS['sql_query'], 'success');
        }
        $table_maintenance_html .= PMA_getHtmlForSqlQueryResultsTable($displayResultsObject, $pmaThemeImage, $url_query, $displayParts, false, $unlim_num_rows, $num_rows, $showtable, $result, $analyzed_sql_results);
        if (empty($sql_data) || ($sql_data['valid_queries'] = 1)) {
            $response->addHTML($table_maintenance_html);
            exit;
        }
    }
    if (!isset($_REQUEST['printview']) || $_REQUEST['printview'] != '1') {
        $scripts->addFile('makegrid.js');
        $scripts->addFile('sql.js');
        unset($GLOBALS['message']);
        //we don't need to buffer the output in getMessage here.
        //set a global variable and check against it in the function
        $GLOBALS['buffer_message'] = false;
    }
    $previous_update_query_html = PMA_getHtmlForPreviousUpdateQuery(isset($disp_query) ? $disp_query : null, $GLOBALS['cfg']['ShowSQL'], isset($sql_data) ? $sql_data : null, isset($disp_message) ? $disp_message : null);
    $profiling_chart_html = PMA_getHtmlForProfilingChart($url_query, $db, isset($profiling_results) ? $profiling_results : array());
    $missing_unique_column_msg = PMA_getMessageIfMissingColumnIndex($table, $db, $editable, $has_unique);
    $bookmark_created_msg = PMA_getBookmarkCreatedMessage();
    $table_html = PMA_getHtmlForSqlQueryResultsTable($displayResultsObject, $pmaThemeImage, $url_query, $displayParts, $editable, $unlim_num_rows, $num_rows, $showtable, $result, $analyzed_sql_results);
    $indexes_problems_html = PMA_getHtmlForIndexesProblems(isset($query_type) ? $query_type : null, isset($selectedTables) ? $selectedTables : null, $db);
    $cfgBookmark = PMA_Bookmark_getParams();
    if ($cfgBookmark) {
        $bookmark_support_html = PMA_getHtmlForBookmark($displayParts, $cfgBookmark, $sql_query, $db, $table, isset($complete_query) ? $complete_query : $sql_query, $cfgBookmark['user']);
    } else {
        $bookmark_support_html = '';
    }
    $html_output = isset($table_maintenance_html) ? $table_maintenance_html : '';
    $html_output .= PMA_getHtmlForSqlQueryResults($previous_update_query_html, $profiling_chart_html, $missing_unique_column_msg, $bookmark_created_msg, $table_html, $indexes_problems_html, $bookmark_support_html);
    return $html_output;
}
Example #23
0
    } 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 {
            $message = Message::success(__('Success!'));
        }
    } else {
        $message = Message::success(__('No change'));
    }
}
/**
 * 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;
}
Example #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);
}
/**
 * get the warning messages array
 *
 * @return array  $warning_essages
 */
function PMA_getWarningMessages()
{
    $warning_essages = array();
    foreach ($GLOBALS['dbi']->getWarnings() as $warning) {
        $warning_essages[] = Message::sanitize($warning['Level'] . ': #' . $warning['Code'] . ' ' . $warning['Message']);
    }
    return $warning_essages;
}
/**
 * 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;
    }
}
/**
 * Prepares queries for adding users and
 * also create database and return query and message
 *
 * @param boolean $_error         whether user create or not
 * @param string  $real_sql_query SQL query for add a user
 * @param string  $sql_query      SQL query to be displayed
 * @param string  $username       username
 * @param string  $hostname       host name
 * @param string  $dbname         database name
 *
 * @return array  $sql_query, $message
 */
function PMA_addUserAndCreateDatabase($_error, $real_sql_query, $sql_query, $username, $hostname, $dbname)
{
    if ($_error || !empty($real_sql_query) && !$GLOBALS['dbi']->tryQuery($real_sql_query)) {
        $_REQUEST['createdb-1'] = $_REQUEST['createdb-2'] = $_REQUEST['createdb-3'] = null;
        $message = Message::rawError($GLOBALS['dbi']->getError());
    } else {
        $message = Message::success(__('You have added a new user.'));
    }
    if (isset($_REQUEST['createdb-1'])) {
        // Create database with same name and grant all privileges
        $q = 'CREATE DATABASE IF NOT EXISTS ' . Util::backquote(Util::sqlAddSlashes($username)) . ';';
        $sql_query .= $q;
        if (!$GLOBALS['dbi']->tryQuery($q)) {
            $message = Message::rawError($GLOBALS['dbi']->getError());
        }
        /**
         * Reload the navigation
         */
        $GLOBALS['reload'] = true;
        $GLOBALS['db'] = $username;
        $q = 'GRANT ALL PRIVILEGES ON ' . Util::backquote(Util::escapeMysqlWildcards(Util::sqlAddSlashes($username))) . '.* TO \'' . Util::sqlAddSlashes($username) . '\'@\'' . Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (!$GLOBALS['dbi']->tryQuery($q)) {
            $message = Message::rawError($GLOBALS['dbi']->getError());
        }
    }
    if (isset($_REQUEST['createdb-2'])) {
        // Grant all privileges on wildcard name (username\_%)
        $q = 'GRANT ALL PRIVILEGES ON ' . Util::backquote(Util::sqlAddSlashes($username) . '\\_%') . '.* TO \'' . Util::sqlAddSlashes($username) . '\'@\'' . Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (!$GLOBALS['dbi']->tryQuery($q)) {
            $message = Message::rawError($GLOBALS['dbi']->getError());
        }
    }
    if (isset($_REQUEST['createdb-3'])) {
        // Grant all privileges on the specified database to the new user
        $q = 'GRANT ALL PRIVILEGES ON ' . Util::backquote(Util::sqlAddSlashes($dbname)) . '.* TO \'' . Util::sqlAddSlashes($username) . '\'@\'' . Util::sqlAddSlashes($hostname) . '\';';
        $sql_query .= $q;
        if (!$GLOBALS['dbi']->tryQuery($q)) {
            $message = Message::rawError($GLOBALS['dbi']->getError());
        }
    }
    return array($sql_query, $message);
}
Example #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;
                }
            }
        }
    }
}
Example #30
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;
    }
}