/**
* Prints details about the current Git commit revision
*
* @return void
*/
function PMA_printGitRevision()
{
    if (!$GLOBALS['PMA_Config']->get('PMA_VERSION_GIT')) {
        $response = Response::getInstance();
        $response->setRequestStatus(false);
        return;
    }
    // load revision data from repo
    $GLOBALS['PMA_Config']->checkGitRevision();
    // if using a remote commit fast-forwarded, link to GitHub
    $commit_hash = substr($GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_COMMITHASH'), 0, 7);
    $commit_hash = '<strong title="' . htmlspecialchars($GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_MESSAGE')) . '">' . $commit_hash . '</strong>';
    if ($GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_ISREMOTECOMMIT')) {
        $commit_hash = '<a href="' . PMA_linkURL('https://github.com/phpmyadmin/phpmyadmin/commit/' . $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_COMMITHASH')) . '" rel="noopener noreferrer" target="_blank">' . $commit_hash . '</a>';
    }
    $branch = $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_BRANCH');
    if ($GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_ISREMOTEBRANCH')) {
        $branch = '<a href="' . PMA_linkURL('https://github.com/phpmyadmin/phpmyadmin/tree/' . $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_BRANCH')) . '" rel="noopener noreferrer" target="_blank">' . $branch . '</a>';
    }
    if ($branch !== false) {
        $branch = sprintf(__('%1$s from %2$s branch'), $commit_hash, $branch);
    } else {
        $branch = $commit_hash . ' (' . __('no branch') . ')';
    }
    $committer = $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_COMMITTER');
    $author = $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT_AUTHOR');
    PMA_printListItem(__('Git revision:') . ' ' . $branch . ',<br /> ' . sprintf(__('committed on %1$s by %2$s'), PMA\libraries\Util::localisedDate(strtotime($committer['date'])), '<a href="' . PMA_linkURL('mailto:' . htmlspecialchars($committer['email'])) . '">' . htmlspecialchars($committer['name']) . '</a>') . ($author != $committer ? ', <br />' . sprintf(__('authored on %1$s by %2$s'), PMA\libraries\Util::localisedDate(strtotime($author['date'])), '<a href="' . PMA_linkURL('mailto:' . htmlspecialchars($author['email'])) . '">' . htmlspecialchars($author['name']) . '</a>') : ''), 'li_pma_version_git', null, null, null);
}
Esempio n. 2
0
/**
 * Send TRI or EVN editor via ajax or by echoing.
 *
 * @param string $type      TRI or EVN
 * @param string $mode      Editor mode 'add' or 'edit'
 * @param array  $item      Data necessary to create the editor
 * @param string $title     Title of the editor
 * @param string $db        Database
 * @param string $operation Operation 'change' or ''
 *
 * @return void
 */
function PMA_RTE_sendEditor($type, $mode, $item, $title, $db, $operation = null)
{
    if ($item !== false) {
        // Show form
        if ($type == 'TRI') {
            $editor = PMA_TRI_getEditorForm($mode, $item);
        } else {
            // EVN
            $editor = PMA_EVN_getEditorForm($mode, $operation, $item);
        }
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            $response->addJSON('message', $editor);
            $response->addJSON('title', $title);
        } else {
            echo "\n\n<h2>{$title}</h2>\n\n{$editor}";
            unset($_POST);
        }
        exit;
    } else {
        $message = __('Error in processing request:') . ' ';
        $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA\libraries\Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA\libraries\Util::backquote($db)));
        $message = Message::error($message);
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            $response->setRequestStatus(false);
            $response->addJSON('message', $message);
            exit;
        } else {
            $message->display();
        }
    }
}
Esempio n. 3
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();
        }
    }
}
Esempio n. 4
0
 /**
  * No-arg constructor
  */
 public function __construct()
 {
     if (!empty($GLOBALS['cfg']['CodemirrorEnable'])) {
         $response = Response::getInstance();
         $scripts = $response->getHeader()->getScripts();
         $scripts->addFile('codemirror/lib/codemirror.js');
         $scripts->addFile('codemirror/mode/sql/sql.js');
         $scripts->addFile('codemirror/addon/runmode/runmode.js');
         $scripts->addFile('function.js');
     }
 }
Esempio n. 5
0
 /**
  * No-arg constructor
  */
 public function __construct()
 {
     if (!empty($GLOBALS['cfg']['CodemirrorEnable'])) {
         $response = PMA\libraries\Response::getInstance();
         $scripts = $response->getHeader()->getScripts();
         $scripts->addFile('codemirror/lib/codemirror.js');
         $scripts->addFile('codemirror/mode/javascript/javascript.js');
         $scripts->addFile('codemirror/addon/runmode/runmode.js');
         $scripts->addFile('transformations/json.js');
     }
 }
 /**
  * Index action
  *
  * @return void
  */
 public function indexAction()
 {
     include_once 'libraries/check_user_privileges.lib.php';
     $response = Response::getInstance();
     if (isset($_REQUEST['drop_selected_dbs']) && $response->isAjax() && ($GLOBALS['is_superuser'] || $GLOBALS['cfg']['AllowUserDropDatabase'])) {
         $this->dropDatabasesAction();
         return;
     }
     include_once 'libraries/replication.inc.php';
     if (!empty($_POST['new_db']) && $response->isAjax()) {
         $this->createDatabaseAction();
         return;
     }
     include_once 'libraries/server_common.inc.php';
     $header = $this->response->getHeader();
     $scripts = $header->getScripts();
     $scripts->addFile('server_databases.js');
     $this->_setSortDetails();
     $this->_dbstats = empty($_REQUEST['dbstats']) ? false : true;
     $this->_pos = empty($_REQUEST['pos']) ? 0 : (int) $_REQUEST['pos'];
     /**
      * Displays the sub-page heading
      */
     $header_type = $this->_dbstats ? "database_statistics" : "databases";
     $this->response->addHTML(PMA_getHtmlForSubPageHeader($header_type));
     /**
      * Displays For Create database.
      */
     $html = '';
     if ($GLOBALS['cfg']['ShowCreateDb']) {
         $html .= Template::get('server/databases/create')->render();
     }
     $html .= Template::get('filter')->render(array('filterValue' => ''));
     /**
      * Gets the databases list
      */
     if ($GLOBALS['server'] > 0) {
         $this->_databases = $this->dbi->getDatabasesFull(null, $this->_dbstats, null, $this->_sort_by, $this->_sort_order, $this->_pos, true);
         $this->_database_count = count($GLOBALS['dblist']->databases);
     } else {
         $this->_database_count = 0;
     }
     /**
      * Displays the page
      */
     if ($this->_database_count > 0 && !empty($this->_databases)) {
         $html .= $this->_getHtmlForDatabases($replication_types);
     } else {
         $html .= __('No databases');
     }
     $this->response->addHTML($html);
 }
Esempio n. 7
0
 /**
  * Displays authentication form
  *
  * @return boolean
  */
 public function authForm()
 {
     /* Perform logout to custom URL */
     if (!empty($_REQUEST['old_usr']) && !empty($GLOBALS['cfg']['Server']['LogoutURL'])) {
         PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
         if (!defined('TESTSUITE')) {
             exit;
         } else {
             return false;
         }
     }
     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;
     }
 }
Esempio n. 8
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;
 }
Esempio n. 9
0
/**
 * Calls the parser on a query
 *
 * @param string $sql_query the query to parse
 * @param string $db        the current database
 *
 * @return array
 *
 * @access  public
 */
function PMA_parseAnalyze($sql_query, $db)
{
    // @todo: move to returned results (also in all the calling chain)
    $GLOBALS['unparsed_sql'] = $sql_query;
    // Get details about the SQL query.
    $analyzed_sql_results = SqlParser\Utils\Query::getAll($sql_query);
    extract($analyzed_sql_results);
    $table = '';
    // If the targeted table (and database) are different than the ones that is
    // currently browsed, edit `$db` and `$table` to match them so other elements
    // (page headers, links, navigation panel) can be updated properly.
    if (!empty($analyzed_sql_results['select_tables'])) {
        // Previous table and database name is stored to check if it changed.
        $prev_db = $db;
        if (count($analyzed_sql_results['select_tables']) > 1) {
            /**
             * @todo if there are more than one table name in the Select:
             * - do not extract the first table name
             * - do not show a table name in the page header
             * - do not display the sub-pages links)
             */
            $table = '';
        } else {
            $table = $analyzed_sql_results['select_tables'][0][0];
            if (!empty($analyzed_sql_results['select_tables'][0][1])) {
                $db = $analyzed_sql_results['select_tables'][0][1];
            }
        }
        // There is no point checking if a reload is required if we already decided
        // to reload. Also, no reload is required for AJAX requests.
        $response = Response::getInstance();
        if (empty($reload) && !$response->isAjax()) {
            // NOTE: Database names are case-insensitive.
            $reload = strcasecmp($db, $prev_db) != 0;
        }
        // Updating the array.
        $analyzed_sql_results['reload'] = $reload;
    }
    return array($analyzed_sql_results, $db, $table);
}
/**
 * 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;
    }
}
Esempio n. 11
0
 /**
  * Output Dia Document for download
  *
  * @param string $fileName name of the dia document
  *
  * @return void
  * @access public
  * @see    XMLWriter::flush()
  */
 public function showOutput($fileName)
 {
     if (ob_get_clean()) {
         ob_end_clean();
     }
     $output = $this->flush();
     PMA\libraries\Response::getInstance()->disable();
     PMA_downloadHeader($fileName, 'application/x-dia-diagram', mb_strlen($output));
     print $output;
 }
Esempio n. 12
0
 /**
  * Prepares a Delete link
  *
  * @param string $del_url delete url
  * @param string $del_str text for the delete link
  * @param string $js_conf text for the JS confirmation
  * @param string $class   css classes for the td element
  *
  * @return string  the generated HTML
  *
  * @access  private
  *
  * @see     _getTableBody(), _getCheckboxAndLinks()
  */
 private function _getDeleteLink($del_url, $del_str, $js_conf, $class)
 {
     $ret = '';
     if (empty($del_url)) {
         return $ret;
     }
     $ret .= '<td class="';
     if (!empty($class)) {
         $ret .= $class . ' ';
     }
     $ajax = Response::getInstance()->isAjax() ? ' ajax' : '';
     $ret .= 'center print_ignore" ' . ' >' . Util::linkOrButton($del_url, $del_str, array('class' => 'delete_row requireConfirm' . $ajax), false) . '<div class="hide">' . $js_conf . '</div>' . '</td>';
     return $ret;
 }
<?php

/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Database structure manipulation
 *
 * @package PhpMyAdmin
 */
namespace PMA;

use PMA\libraries\controllers\database\DatabaseStructureController;
use PMA\libraries\Response;
use PMA\libraries\Util;
require_once 'libraries/common.inc.php';
require_once 'libraries/db_common.inc.php';
list($tables, $num_tables, $total_num_tables, $sub_part, $is_show_stats, $db_is_system_schema, $tooltip_truename, $tooltip_aliasname, $pos) = Util::getDbInfo($GLOBALS['db'], isset($sub_part) ? $sub_part : '');
$container = libraries\di\Container::getDefaultContainer();
$container->factory('PMA\\libraries\\controllers\\database\\DatabaseStructureController');
$container->alias('DatabaseStructureController', 'PMA\\libraries\\controllers\\database\\DatabaseStructureController');
$container->set('PMA\\libraries\\Response', Response::getInstance());
$container->alias('response', 'PMA\\libraries\\Response');
global $db, $pos, $db_is_system_schema, $total_num_tables, $tables, $num_tables;
/* Define dependencies for the concerned controller */
$dependency_definitions = array('db' => $db, 'url_query' => &$GLOBALS['url_query'], 'pos' => $pos, 'db_is_system_schema' => $db_is_system_schema, 'num_tables' => $num_tables, 'total_num_tables' => $total_num_tables, 'tables' => $tables);
/** @var DatabaseStructureController $controller */
$controller = $container->get('DatabaseStructureController', $dependency_definitions);
$controller->indexAction();
Esempio n. 14
0
/**
 * Function to add a bookmark
 *
 * @param String $pmaAbsoluteUri absolute URI
 * @param String $goto           goto page URL
 *
 * @return void
 */
function PMA_addBookmark($pmaAbsoluteUri, $goto)
{
    $result = PMA_Bookmark_save($_POST['bkm_fields'], isset($_POST['bkm_all_users']) && $_POST['bkm_all_users'] == 'true' ? true : false);
    $response = Response::getInstance();
    if ($response->isAjax()) {
        if ($result) {
            $msg = Message::success(__('Bookmark %s has been created.'));
            $msg->addParam($_POST['bkm_fields']['bkm_label']);
            $response->addJSON('message', $msg);
        } else {
            $msg = PMA\libraries\message::error(__('Bookmark not created!'));
            $response->setRequestStatus(false);
            $response->addJSON('message', $msg);
        }
        exit;
    } else {
        // go back to sql.php to redisplay query; do not use &amp; in this case:
        /**
         * @todo In which scenario does this happen?
         */
        PMA_sendHeaderLocation($pmaAbsoluteUri . $goto . '&label=' . $_POST['bkm_fields']['bkm_label']);
    }
}
Esempio n. 15
0
    /**
     * Displays a MySQL error message in the main panel when $exit is true.
     * Returns the error message otherwise.
     *
     * @param string|bool $server_msg     Server's error message.
     * @param string      $sql_query      The SQL query that failed.
     * @param bool        $is_modify_link Whether to show a "modify" link or not.
     * @param string      $back_url       URL for the "back" link (full path is
     *                                    not required).
     * @param bool        $exit           Whether execution should be stopped or
     *                                    the error message should be returned.
     *
     * @return string
     *
     * @global string $table The current table.
     * @global string $db    The current database.
     *
     * @access public
     */
    public static function mysqlDie(
        $server_msg = '',
        $sql_query = '',
        $is_modify_link = true,
        $back_url = '',
        $exit = true
    ) {
        global $table, $db;

        /**
         * Error message to be built.
         * @var string $error_msg
         */
        $error_msg = '';

        // Checking for any server errors.
        if (empty($server_msg)) {
            $server_msg = $GLOBALS['dbi']->getError();
        }

        // Finding the query that failed, if not specified.
        if ((empty($sql_query) && (!empty($GLOBALS['sql_query'])))) {
            $sql_query = $GLOBALS['sql_query'];
        }
        $sql_query = trim($sql_query);

        /**
         * The lexer used for analysis.
         * @var Lexer $lexer
         */
        $lexer = new Lexer($sql_query);

        /**
         * The parser used for analysis.
         * @var Parser $parser
         */
        $parser = new Parser($lexer->list);

        /**
         * The errors found by the lexer and the parser.
         * @var array $errors
         */
        $errors = ParserError::get(array($lexer, $parser));

        if (empty($sql_query)) {
            $formatted_sql = '';
        } elseif (count($errors)) {
            $formatted_sql = htmlspecialchars($sql_query);
        } else {
            $formatted_sql = self::formatSql($sql_query, true);
        }

        $error_msg .= '<div class="error"><h1>' . __('Error') . '</h1>';

        // For security reasons, if the MySQL refuses the connection, the query
        // is hidden so no details are revealed.
        if ((!empty($sql_query)) && (!(mb_strstr($sql_query, 'connect')))) {
            // Static analysis errors.
            if (!empty($errors)) {
                $error_msg .= '<p><strong>' . __('Static analysis:')
                    . '</strong></p>';
                $error_msg .= '<p>' . sprintf(
                    __('%d errors were found during analysis.'),
                    count($errors)
                ) . '</p>';
                $error_msg .= '<p><ol>';
                $error_msg .= implode(
                    ParserError::format(
                        $errors,
                        '<li>%2$s (near "%4$s" at position %5$d)</li>'
                    )
                );
                $error_msg .= '</ol></p>';
            }

            // Display the SQL query and link to MySQL documentation.
            $error_msg .= '<p><strong>' . __('SQL query:') . '</strong>' . "\n";
            $formattedSqlToLower = mb_strtolower($formatted_sql);

            // TODO: Show documentation for all statement types.
            if (mb_strstr($formattedSqlToLower, 'select')) {
                // please show me help to the error on select
                $error_msg .= self::showMySQLDocu('SELECT');
            }

            if ($is_modify_link) {
                $_url_params = array(
                    'sql_query' => $sql_query,
                    'show_query' => 1,
                );
                if (strlen($table) > 0) {
                    $_url_params['db'] = $db;
                    $_url_params['table'] = $table;
                    $doedit_goto = '<a href="tbl_sql.php'
                        . URL::getCommon($_url_params) . '">';
                } elseif (strlen($db) > 0) {
                    $_url_params['db'] = $db;
                    $doedit_goto = '<a href="db_sql.php'
                        . URL::getCommon($_url_params) . '">';
                } else {
                    $doedit_goto = '<a href="server_sql.php'
                        . URL::getCommon($_url_params) . '">';
                }

                $error_msg .= $doedit_goto
                   . self::getIcon('b_edit.png', __('Edit'))
                   . '</a>';
            }

            $error_msg .= '    </p>' . "\n"
                . '<p>' . "\n"
                . $formatted_sql . "\n"
                . '</p>' . "\n";
        }

        // Display server's error.
        if (!empty($server_msg)) {
            $server_msg = preg_replace(
                "@((\015\012)|(\015)|(\012)){3,}@",
                "\n\n",
                $server_msg
            );

            // Adds a link to MySQL documentation.
            $error_msg .= '<p>' . "\n"
                . '    <strong>' . __('MySQL said: ') . '</strong>'
                . self::showMySQLDocu('Error-messages-server')
                . "\n"
                . '</p>' . "\n";

            // The error message will be displayed within a CODE segment.
            // To preserve original formatting, but allow word-wrapping,
            // a couple of replacements are done.
            // All non-single blanks and  TAB-characters are replaced with their
            // HTML-counterpart
            $server_msg = str_replace(
                array('  ', "\t"),
                array('&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;&nbsp;'),
                $server_msg
            );

            // Replace line breaks
            $server_msg = nl2br($server_msg);

            $error_msg .= '<code>' . $server_msg . '</code><br/>';
        }

        $error_msg .= '</div>';
        $_SESSION['Import_message']['message'] = $error_msg;

        if (!$exit) {
            return $error_msg;
        }

        /**
         * If this is an AJAX request, there is no "Back" link and
         * `Response()` is used to send the response.
         */
        $response = Response::getInstance();
        if ($response->isAjax()) {
            $response->setRequestStatus(false);
            $response->addJSON('message', $error_msg);
            exit;
        }

        if (!empty($back_url)) {
            if (mb_strstr($back_url, '?')) {
                $back_url .= '&amp;no_history=true';
            } else {
                $back_url .= '?no_history=true';
            }

            $_SESSION['Import_message']['go_back_url'] = $back_url;

            $error_msg .= '<fieldset class="tblFooters">'
                . '[ <a href="' . $back_url . '">' . __('Back') . '</a> ]'
                . '</fieldset>' . "\n\n";
        }

        exit($error_msg);
    }
Esempio n. 16
0
/**
 * Handles export template actions
 *
 * @param array $cfgRelation Relation configuration
 *
 * @return void
 */
function PMA_handleExportTemplateActions($cfgRelation)
{
    if (isset($_REQUEST['templateId'])) {
        $id = $GLOBALS['dbi']->escapeString($_REQUEST['templateId']);
    } else {
        $id = '';
    }
    $templateTable = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['export_templates']);
    $user = $GLOBALS['dbi']->escapeString($GLOBALS['cfg']['Server']['user']);
    switch ($_REQUEST['templateAction']) {
        case 'create':
            $query = "INSERT INTO " . $templateTable . "(" . " `username`, `export_type`," . " `template_name`, `template_data`" . ") VALUES (" . "'" . $user . "', " . "'" . $GLOBALS['dbi']->escapeString($_REQUEST['exportType']) . "', '" . $GLOBALS['dbi']->escapeString($_REQUEST['templateName']) . "', '" . $GLOBALS['dbi']->escapeString($_REQUEST['templateData']) . "');";
            break;
        case 'load':
            $query = "SELECT `template_data` FROM " . $templateTable . " WHERE `id` = " . $id . " AND `username` = '" . $user . "'";
            break;
        case 'update':
            $query = "UPDATE " . $templateTable . " SET `template_data` = " . "'" . $GLOBALS['dbi']->escapeString($_REQUEST['templateData']) . "'" . " WHERE `id` = " . $id . " AND `username` = '" . $user . "'";
            break;
        case 'delete':
            $query = "DELETE FROM " . $templateTable . " WHERE `id` = " . $id . " AND `username` = '" . $user . "'";
            break;
        default:
            $query = '';
            break;
    }
    $result = PMA_queryAsControlUser($query, false);
    $response = Response::getInstance();
    if (!$result) {
        $error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
        $response->setRequestStatus(false);
        $response->addJSON('message', $error);
        exit;
    }
    $response->setRequestStatus(true);
    if ('create' == $_REQUEST['templateAction']) {
        $response->addJSON('data', PMA_getOptionsForExportTemplates($_REQUEST['exportType']));
    } elseif ('load' == $_REQUEST['templateAction']) {
        $data = null;
        while ($row = $GLOBALS['dbi']->fetchAssoc($result, $GLOBALS['controllink'])) {
            $data = $row['template_data'];
        }
        $response->addJSON('data', $data);
    }
    $GLOBALS['dbi']->freeResult($result);
}
Esempio n. 17
0
 /**
  * Renders the footer
  *
  * @return string
  */
 public function getDisplay()
 {
     $retval = '';
     $this->_setHistory();
     if ($this->_isEnabled) {
         if (!$this->_isAjax) {
             $retval .= "</div>";
         }
         if (!$this->_isAjax && !$this->_isMinimal) {
             if (PMA_getenv('SCRIPT_NAME') && empty($_POST) && empty($GLOBALS['checked_special']) && !$this->_isAjax) {
                 $url = $this->getSelfUrl('unencoded');
                 $header = Response::getInstance()->getHeader();
                 $scripts = $header->getScripts()->getFiles();
                 $menuHash = $header->getMenu()->getHash();
                 // prime the client-side cache
                 $this->_scripts->addCode(sprintf('if (! (history && history.pushState)) ' . 'PMA_MicroHistory.primer = {' . ' url: "%s",' . ' scripts: %s,' . ' menuHash: "%s"' . '};', PMA_escapeJsString($url), json_encode($scripts), PMA_escapeJsString($menuHash)));
             }
             if (PMA_getenv('SCRIPT_NAME') && !$this->_isAjax) {
                 $url = $this->getSelfUrl();
                 $retval .= $this->_getSelfLink($url);
             }
             $this->_scripts->addCode('var debugSQLInfo = ' . $this->getDebugMessage() . ';');
             $retval .= $this->getErrorMessages();
             $retval .= $this->_scripts->getDisplay();
             if ($GLOBALS['cfg']['DBG']['demo']) {
                 $retval .= '<div id="pma_demo">';
                 $retval .= $this->_getDemoMessage();
                 $retval .= '</div>';
             }
             // Include possible custom footers
             if (file_exists(CUSTOM_FOOTER_FILE)) {
                 $retval .= '<div id="pma_footer">';
                 ob_start();
                 include CUSTOM_FOOTER_FILE;
                 $retval .= ob_get_contents();
                 ob_end_clean();
                 $retval .= '</div>';
             }
         }
         if (!$this->_isAjax) {
             $retval .= "</body></html>";
         }
     }
     return $retval;
 }
Esempio n. 18
0
/**
 * Handles editor requests for adding or editing an item
 *
 * @return void
 */
function PMA_TRI_handleEditor()
{
    global $_REQUEST, $_POST, $errors, $db, $table;
    if (!empty($_REQUEST['editor_process_add']) || !empty($_REQUEST['editor_process_edit'])) {
        $sql_query = '';
        $item_query = PMA_TRI_getQueryFromRequest();
        if (!count($errors)) {
            // set by PMA_RTN_getQueryFromRequest()
            // Execute the created query
            if (!empty($_REQUEST['editor_process_edit'])) {
                // Backup the old trigger, in case something goes wrong
                $trigger = PMA_TRI_getDataFromName($_REQUEST['item_original_name']);
                $create_item = $trigger['create'];
                $drop_item = $trigger['drop'] . ';';
                $result = $GLOBALS['dbi']->tryQuery($drop_item);
                if (!$result) {
                    $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($drop_item)) . '<br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $result = $GLOBALS['dbi']->tryQuery($item_query);
                    if (!$result) {
                        $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                        // We dropped the old item, but were unable to create the
                        // new one. Try to restore the backup query.
                        $result = $GLOBALS['dbi']->tryQuery($create_item);
                        $errors = checkResult($result, __('Sorry, we failed to restore the dropped trigger.'), $create_item, $errors);
                    } else {
                        $message = PMA\libraries\Message::success(__('Trigger %1$s has been modified.'));
                        $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
                        $sql_query = $drop_item . $item_query;
                    }
                }
            } else {
                // 'Add a new item' mode
                $result = $GLOBALS['dbi']->tryQuery($item_query);
                if (!$result) {
                    $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br /><br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $message = PMA\libraries\Message::success(__('Trigger %1$s has been created.'));
                    $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
                    $sql_query = $item_query;
                }
            }
        }
        if (count($errors)) {
            $message = PMA\libraries\Message::error('<b>' . __('One or more errors have occurred while processing your request:') . '</b>');
            $message->addHtml('<ul>');
            foreach ($errors as $string) {
                $message->addHtml('<li>' . $string . '</li>');
            }
            $message->addHtml('</ul>');
        }
        $output = PMA\libraries\Util::getMessage($message, $sql_query);
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            if ($message->isSuccess()) {
                $items = $GLOBALS['dbi']->getTriggers($db, $table, '');
                $trigger = false;
                foreach ($items as $value) {
                    if ($value['name'] == $_REQUEST['item_name']) {
                        $trigger = $value;
                    }
                }
                $insert = false;
                if (empty($table) || $trigger !== false && $table == $trigger['table']) {
                    $insert = true;
                    $response->addJSON('new_row', PMA_TRI_getRowForList($trigger));
                    $response->addJSON('name', htmlspecialchars(mb_strtoupper($_REQUEST['item_name'])));
                }
                $response->addJSON('insert', $insert);
                $response->addJSON('message', $output);
            } else {
                $response->addJSON('message', $message);
                $response->setRequestStatus(false);
            }
            exit;
        }
    }
    /**
     * Display a form used to add/edit a trigger, if necessary
     */
    if (count($errors) || empty($_REQUEST['editor_process_add']) && empty($_REQUEST['editor_process_edit']) && (!empty($_REQUEST['add_item']) || !empty($_REQUEST['edit_item']))) {
        // Get the data for the form (if any)
        if (!empty($_REQUEST['add_item'])) {
            $title = PMA_RTE_getWord('add');
            $item = PMA_TRI_getDataFromRequest();
            $mode = 'add';
        } else {
            if (!empty($_REQUEST['edit_item'])) {
                $title = __("Edit trigger");
                if (!empty($_REQUEST['item_name']) && empty($_REQUEST['editor_process_edit'])) {
                    $item = PMA_TRI_getDataFromName($_REQUEST['item_name']);
                    if ($item !== false) {
                        $item['item_original_name'] = $item['item_name'];
                    }
                } else {
                    $item = PMA_TRI_getDataFromRequest();
                }
                $mode = 'edit';
            }
        }
        PMA_RTE_sendEditor('TRI', $mode, $item, $title, $db);
    }
}
Esempio n. 19
0
/**
 * Function to execute the query and send the response
 *
 * @param array      $analyzed_sql_results   analysed sql results
 * @param bool       $is_gotofile            whether goto file or not
 * @param string     $db                     current database
 * @param string     $table                  current table
 * @param bool|null  $find_real_end          whether to find real end or not
 * @param string     $sql_query_for_bookmark the sql query to be stored as bookmark
 * @param array|null $extra_data             extra data
 * @param string     $message_to_show        message to show
 * @param string     $message                message
 * @param array|null $sql_data               sql data
 * @param string     $goto                   goto page url
 * @param string     $pmaThemeImage          uri of the PMA theme image
 * @param string     $disp_query             display query
 * @param string     $disp_message           display message
 * @param string     $query_type             query type
 * @param string     $sql_query              sql query
 * @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     $complete_query         complete query
 *
 * @return void
 */
function PMA_executeQueryAndSendQueryResponse($analyzed_sql_results, $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark, $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage, $disp_query, $disp_message, $query_type, $sql_query, $selectedTables, $complete_query)
{
    $html_output = PMA_executeQueryAndGetQueryResponse($analyzed_sql_results, $is_gotofile, $db, $table, $find_real_end, $sql_query_for_bookmark, $extra_data, $message_to_show, $message, $sql_data, $goto, $pmaThemeImage, $disp_query, $disp_message, $query_type, $sql_query, $selectedTables, $complete_query);
    $response = PMA\libraries\Response::getInstance();
    $response->addHTML($html_output);
}
Esempio n. 20
0
/**
 * Handles editor requests for adding or editing an item
 *
 * @return void
 */
function PMA_EVN_handleEditor()
{
    global $_REQUEST, $_POST, $errors, $db;
    if (!empty($_REQUEST['editor_process_add']) || !empty($_REQUEST['editor_process_edit'])) {
        $sql_query = '';
        $item_query = PMA_EVN_getQueryFromRequest();
        if (!count($errors)) {
            // set by PMA_RTN_getQueryFromRequest()
            // Execute the created query
            if (!empty($_REQUEST['editor_process_edit'])) {
                // Backup the old trigger, in case something goes wrong
                $create_item = $GLOBALS['dbi']->getDefinition($db, 'EVENT', $_REQUEST['item_original_name']);
                $drop_item = "DROP EVENT " . PMA\libraries\Util::backquote($_REQUEST['item_original_name']) . ";\n";
                $result = $GLOBALS['dbi']->tryQuery($drop_item);
                if (!$result) {
                    $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($drop_item)) . '<br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $result = $GLOBALS['dbi']->tryQuery($item_query);
                    if (!$result) {
                        $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                        // We dropped the old item, but were unable to create
                        // the new one. Try to restore the backup query
                        $result = $GLOBALS['dbi']->tryQuery($create_item);
                        $errors = checkResult($result, __('Sorry, we failed to restore the dropped event.'), $create_item, $errors);
                    } else {
                        $message = PMA\libraries\Message::success(__('Event %1$s has been modified.'));
                        $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
                        $sql_query = $drop_item . $item_query;
                    }
                }
            } else {
                // 'Add a new item' mode
                $result = $GLOBALS['dbi']->tryQuery($item_query);
                if (!$result) {
                    $errors[] = sprintf(__('The following query has failed: "%s"'), htmlspecialchars($item_query)) . '<br /><br />' . __('MySQL said: ') . $GLOBALS['dbi']->getError(null);
                } else {
                    $message = PMA\libraries\Message::success(__('Event %1$s has been created.'));
                    $message->addParam(PMA\libraries\Util::backquote($_REQUEST['item_name']));
                    $sql_query = $item_query;
                }
            }
        }
        if (count($errors)) {
            $message = PMA\libraries\Message::error('<b>' . __('One or more errors have occurred while processing your request:') . '</b>');
            $message->addString('<ul>');
            foreach ($errors as $string) {
                $message->addString('<li>' . $string . '</li>');
            }
            $message->addString('</ul>');
        }
        $output = PMA\libraries\Util::getMessage($message, $sql_query);
        if ($GLOBALS['is_ajax_request']) {
            $response = PMA\libraries\Response::getInstance();
            if ($message->isSuccess()) {
                $events = $GLOBALS['dbi']->getEvents($db, $_REQUEST['item_name']);
                $event = $events[0];
                $response->addJSON('name', htmlspecialchars(mb_strtoupper($_REQUEST['item_name'])));
                $response->addJSON('new_row', PMA_EVN_getRowForList($event));
                $response->addJSON('insert', !empty($event));
                $response->addJSON('message', $output);
            } else {
                $response->setRequestStatus(false);
                $response->addJSON('message', $message);
            }
            exit;
        }
    }
    /**
     * Display a form used to add/edit a trigger, if necessary
     */
    if (count($errors) || empty($_REQUEST['editor_process_add']) && empty($_REQUEST['editor_process_edit']) && (!empty($_REQUEST['add_item']) || !empty($_REQUEST['edit_item']) || !empty($_REQUEST['item_changetype']))) {
        // FIXME: this must be simpler than that
        $operation = '';
        if (!empty($_REQUEST['item_changetype'])) {
            $operation = 'change';
        }
        // Get the data for the form (if any)
        if (!empty($_REQUEST['add_item'])) {
            $title = PMA_RTE_getWord('add');
            $item = PMA_EVN_getDataFromRequest();
            $mode = 'add';
        } else {
            if (!empty($_REQUEST['edit_item'])) {
                $title = __("Edit event");
                if (!empty($_REQUEST['item_name']) && empty($_REQUEST['editor_process_edit']) && empty($_REQUEST['item_changetype'])) {
                    $item = PMA_EVN_getDataFromName($_REQUEST['item_name']);
                    if ($item !== false) {
                        $item['item_original_name'] = $item['item_name'];
                    }
                } else {
                    $item = PMA_EVN_getDataFromRequest();
                }
                $mode = 'edit';
            }
        }
        PMA_RTE_sendEditor('EVN', $mode, $item, $title, $db, $operation);
    }
}
 /**
  * Index action
  *
  * @return void
  */
 public function indexAction()
 {
     $response = Response::getInstance();
     // Add/Remove favorite tables using Ajax request.
     if ($response->isAjax() && !empty($_REQUEST['favorite_table'])) {
         $this->addRemoveFavoriteTablesAction();
         return;
     }
     // If there is an Ajax request for real row count of a table.
     if ($response->isAjax() && isset($_REQUEST['real_row_count']) && $_REQUEST['real_row_count'] == true) {
         $this->handleRealRowCountRequestAction();
         return;
     }
     // Drops/deletes/etc. multiple tables if required
     if (!empty($_POST['submit_mult']) && isset($_POST['selected_tbl']) || isset($_POST['mult_btn'])) {
         $this->multiSubmitAction();
     }
     $this->response->getHeader()->getScripts()->addFiles(array('db_structure.js', 'tbl_change.js', 'jquery/jquery-ui-timepicker-addon.js'));
     $this->_url_query .= '&amp;goto=db_structure.php';
     // Gets the database structure
     $this->_getDbInfo('_structure');
     include_once 'libraries/replication.inc.php';
     PageSettings::showGroup('DbStructure');
     // 1. No tables
     if ($this->_num_tables == 0) {
         $this->response->addHTML(Message::notice(__('No tables found in database.')));
         if (empty($this->_db_is_system_schema)) {
             $this->response->addHTML(PMA_getHtmlForCreateTable($this->db));
         }
         return;
     }
     // else
     // 2. Shows table information
     /**
      * Displays the tables list
      */
     $this->response->addHTML('<div id="tableslistcontainer">');
     $_url_params = array('pos' => $this->_pos, 'db' => $this->db);
     // Add the sort options if they exists
     if (isset($_REQUEST['sort'])) {
         $_url_params['sort'] = $_REQUEST['sort'];
     }
     if (isset($_REQUEST['sort_order'])) {
         $_url_params['sort_order'] = $_REQUEST['sort_order'];
     }
     $this->response->addHTML(Util::getListNavigator($this->_total_num_tables, $this->_pos, $_url_params, 'db_structure.php', 'frame_content', $GLOBALS['cfg']['MaxTableList']));
     $this->displayTableList();
     // display again the table list navigator
     $this->response->addHTML(Util::getListNavigator($this->_total_num_tables, $this->_pos, $_url_params, 'db_structure.php', 'frame_content', $GLOBALS['cfg']['MaxTableList']));
     $this->response->addHTML('</div><hr />');
     /**
      * Work on the database
      */
     /* DATABASE WORK */
     /* Printable view of a table */
     $this->response->addHTML(Template::get('database/structure/print_view_data_dictionary_link')->render(array('url_query' => $this->_url_query)));
     if (empty($this->_db_is_system_schema)) {
         $this->response->addHTML(PMA_getHtmlForCreateTable($this->db));
     }
 }
Esempio n. 22
0
 /**
  * Renders a part of the tree, used for Ajax
  * requests in light mode
  *
  * @return string HTML code for the navigation tree
  */
 public function renderPath()
 {
     $node = $this->_buildPath();
     if ($node === false) {
         $retval = false;
     } else {
         $this->groupTree();
         $retval = "<div class='list_container' style='display: none;'>";
         if (!empty($this->_searchClause) || !empty($this->_searchClause2)) {
             $retval .= "<ul class='search_results'>";
         } else {
             $retval .= "<ul>";
         }
         $listContent = $this->_fastFilterHtml($node);
         $listContent .= $this->_getPageSelector($node);
         $children = $node->children;
         usort($children, array('PMA\\libraries\\navigation\\NavigationTree', 'sortNode'));
         for ($i = 0, $nbChildren = count($children); $i < $nbChildren; $i++) {
             if ($i + 1 != $nbChildren) {
                 $listContent .= $this->_renderNode($children[$i], true);
             } else {
                 $listContent .= $this->_renderNode($children[$i], true, 'last');
             }
         }
         $retval .= $listContent;
         $retval .= "</ul>";
         if (!$GLOBALS['cfg']['ShowDatabasesNavigationAsTree']) {
             $retval .= "<span class='hide loaded_db'>";
             $parents = $node->parents(true);
             $retval .= urlencode($parents[0]->real_name);
             $retval .= "</span>";
             if (empty($listContent)) {
                 $retval .= "<div style='margin:0.75em'>";
                 $retval .= __('No tables found in database.');
                 $retval .= "</div>";
             }
         }
         $retval .= "</div>";
     }
     if (!empty($this->_searchClause) || !empty($this->_searchClause2)) {
         $results = 0;
         if (!empty($this->_searchClause2)) {
             if (is_object($node->realParent())) {
                 $results = $node->realParent()->getPresence($node->real_name, $this->_searchClause2);
             }
         } else {
             $results = $this->_tree->getPresence('databases', $this->_searchClause);
         }
         $results = sprintf(_ngettext('%s result found', '%s results found', $results), $results);
         Response::getInstance()->addJSON('results', $results);
     }
     return $retval;
 }
Esempio n. 23
0
/**
 * Displays SQL query before executing.
 *
 * @param array|string $query_data Array containing queries or query itself
 *
 * @return void
 */
function PMA_previewSQL($query_data)
{
    $retval = '<div class="preview_sql">';
    if (empty($query_data)) {
        $retval .= __('No change');
    } elseif (is_array($query_data)) {
        foreach ($query_data as $query) {
            $retval .= PMA\libraries\Util::formatSql($query);
        }
    } else {
        $retval .= PMA\libraries\Util::formatSql($query_data);
    }
    $retval .= '</div>';
    $response = Response::getInstance();
    $response->addJSON('sql_data', $retval);
    exit;
}
Esempio n. 24
0
 /**
  * User is not allowed to login to MySQL -> authentication failed
  *
  * prepares error message and switches to auth() which display the error
  * and the login form
  *
  * this function MUST exit/quit the application,
  * currently done by call to auth()
  *
  * @return void
  */
 public function authFails()
 {
     global $conn_error;
     // Deletes password cookie and displays the login form
     $GLOBALS['PMA_Config']->removeCookie('pmaAuth-' . $GLOBALS['server']);
     $conn_error = $this->getErrorMessage();
     $response = Response::getInstance();
     // needed for PHP-CGI (not need for FastCGI or mod-php)
     $response->header('Cache-Control: no-store, no-cache, must-revalidate');
     $response->header('Pragma: no-cache');
     $this->auth();
 }
Esempio n. 25
0
 * Displays the 'User groups' sub page under 'Users' page.
 *
 * @package PhpMyAdmin
 */
use PMA\libraries\Response;

require_once 'libraries/common.inc.php';
require_once 'libraries/server_users.lib.php';
require_once 'libraries/server_user_groups.lib.php';

PMA_getRelationsParam();
if (! $GLOBALS['cfgRelation']['menuswork']) {
    exit;
}

$response = Response::getInstance();
$header   = $response->getHeader();
$scripts  = $header->getScripts();
$scripts->addFile('server_user_groups.js');

/**
 * Only allowed to superuser
 */
if (! $GLOBALS['is_superuser']) {
    $response->addHTML(
        PMA\libraries\Message::error(__('No Privileges'))
            ->getDisplay()
    );
    exit;
}
Esempio n. 26
0
/**
 * Function to export as entries
 *
 * @param array $entries entries
 *
 * @return void
 */
function PMA_exportAsFileDownload($entries)
{
    @ini_set('url_rewriter.tags', '');
    $dump = "# " . sprintf(__('Tracking report for table `%s`'), htmlspecialchars($_REQUEST['table'])) . "\n" . "# " . date('Y-m-d H:i:s') . "\n";
    foreach ($entries as $entry) {
        $dump .= $entry['statement'];
    }
    $filename = 'log_' . htmlspecialchars($_REQUEST['table']) . '.sql';
    PMA\libraries\Response::getInstance()->disable();
    PMA_downloadHeader($filename, 'text/x-sql', mb_strlen($dump));
    echo $dump;
    exit;
}
Esempio n. 27
0
require 'libraries/config/user_preferences.forms.php';
$cf = new ConfigFile($GLOBALS['PMA_Config']->base_settings);
PMA_userprefsPageInit($cf);
$error = '';
if (isset($_POST['submit_export']) && isset($_POST['export_type']) && $_POST['export_type'] == 'text_file') {
    // export to JSON file
    PMA\libraries\Response::getInstance()->disable();
    $filename = 'phpMyAdmin-config-' . urlencode(PMA_getenv('HTTP_HOST')) . '.json';
    PMA_downloadHeader($filename, 'application/json');
    $settings = PMA_loadUserprefs();
    echo json_encode($settings['config_data'], JSON_PRETTY_PRINT);
    exit;
} else {
    if (isset($_POST['submit_get_json'])) {
        $settings = PMA_loadUserprefs();
        $response = PMA\libraries\Response::getInstance();
        $response->addJSON('prefs', json_encode($settings['config_data']));
        $response->addJSON('mtime', $settings['mtime']);
        exit;
    } else {
        if (isset($_POST['submit_import'])) {
            // load from JSON file
            $json = '';
            if (isset($_POST['import_type']) && $_POST['import_type'] == 'text_file' && isset($_FILES['import_file']) && $_FILES['import_file']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['import_file']['tmp_name'])) {
                // read JSON from uploaded file
                $open_basedir = @ini_get('open_basedir');
                $file_to_unlink = '';
                $import_file = $_FILES['import_file']['tmp_name'];
                // If we are on a server with open_basedir, we must move the file
                // before opening it. The doc explains how to create the "./tmp"
                // directory
 /**
  * Function to report all the collected php errors.
  * Must be called at the end of each script
  *      by the $GLOBALS['error_handler'] only.
  *
  * @return void
  */
 public function reportErrors()
 {
     // if there're no actual errors,
     if (!$this->hasErrors() || $this->countErrors() == $this->countUserErrors()) {
         // then simply return.
         return;
     }
     // Delete all the prev_errors in session & store new prev_errors in session
     $this->savePreviousErrors();
     $response = Response::getInstance();
     $jsCode = '';
     if ($GLOBALS['cfg']['SendErrorReports'] == 'always') {
         if ($response->isAjax()) {
             // set flag for automatic report submission.
             $response->addJSON('_sendErrorAlways', '1');
         } else {
             // send the error reports asynchronously & without asking user
             $jsCode .= '$("#pma_report_errors_form").submit();' . 'PMA_ajaxShowMessage(
                         PMA_messages["phpErrorsBeingSubmitted"], false
                     );';
             // js code to appropriate focusing,
             $jsCode .= '$("html, body").animate({
                             scrollTop:$(document).height()
                         }, "slow");';
         }
     } elseif ($GLOBALS['cfg']['SendErrorReports'] == 'ask') {
         //ask user whether to submit errors or not.
         if (!$response->isAjax()) {
             // js code to show appropriate msgs, event binding & focusing.
             $jsCode = 'PMA_ajaxShowMessage(PMA_messages["phpErrorsFound"]);' . '$("#pma_ignore_errors_popup").bind("click", function() {
                         PMA_ignorePhpErrors()
                     });' . '$("#pma_ignore_all_errors_popup").bind("click",
                         function() {
                             PMA_ignorePhpErrors(false)
                         });' . '$("#pma_ignore_errors_bottom").bind("click", function(e) {
                         e.preventDefaulut();
                         PMA_ignorePhpErrors()
                     });' . '$("#pma_ignore_all_errors_bottom").bind("click",
                         function(e) {
                             e.preventDefault();
                             PMA_ignorePhpErrors(false)
                         });' . '$("html, body").animate({
                         scrollTop:$(document).height()
                     }, "slow");';
         }
     }
     // The errors are already sent from the response.
     // Just focus on errors division upon load event.
     $response->getFooter()->getScripts()->addCode($jsCode);
 }
Esempio n. 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;
                }
            }
        }
    }
}
 /**
  * User is not allowed to login to MySQL -> authentication failed
  *
  * @return boolean   always true (no return indeed)
  */
 public function authFails()
 {
     $conn_error = $GLOBALS['dbi']->getError();
     if (!$conn_error) {
         $conn_error = __('Cannot connect: invalid settings.');
     }
     /* HTML header */
     $response = PMA\libraries\Response::getInstance();
     $response->getFooter()->setMinimal();
     $header = $response->getHeader();
     $header->setBodyId('loginform');
     $header->setTitle(__('Access denied!'));
     $header->disableMenuAndConsole();
     echo '<br /><br />
 <center>
     <h1>';
     echo sprintf(__('Welcome to %s'), ' phpMyAdmin ');
     echo '</h1>
 </center>
 <br />
 <table cellpadding="0" cellspacing="3" style="margin: 0 auto" width="80%">
     <tr>
         <td>';
     if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) {
         trigger_error(__('Access denied!'), E_USER_NOTICE);
     } else {
         // Check whether user has configured something
         if ($GLOBALS['PMA_Config']->source_mtime == 0) {
             echo '<p>', sprintf(__('You probably did not create a configuration file.' . ' You might want to use the %1$ssetup script%2$s to' . ' create one.'), '<a href="setup/">', '</a>'), '</p>', "\n";
         } elseif (!isset($GLOBALS['errno']) || isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002 && $GLOBALS['errno'] != 2003) {
             // if we display the "Server not responding" error, do not confuse
             // users by telling them they have a settings problem
             // (note: it's true that they could have a badly typed host name,
             // but anyway the current message tells that the server
             //  rejected the connection, which is not really what happened)
             // 2002 is the error given by mysqli
             // 2003 is the error given by mysql
             trigger_error(__('phpMyAdmin tried to connect to the MySQL server, and the' . ' server rejected the connection. You should check the' . ' host, username and password in your configuration and' . ' make sure that they correspond to the information given' . ' by the administrator of the MySQL server.'), E_USER_WARNING);
         }
         echo PMA\libraries\Util::mysqlDie($conn_error, '', true, '', false);
     }
     $GLOBALS['error_handler']->dispUserErrors();
     echo '</td>
     </tr>
     <tr>
         <td>', "\n";
     echo '<a href="', PMA\libraries\Util::getScriptNameForOption($GLOBALS['cfg']['DefaultTabServer'], 'server'), URL::getCommon(), '" class="button disableAjax">', __('Retry to connect'), '</a>', "\n";
     echo '</td>
     </tr>', "\n";
     if (count($GLOBALS['cfg']['Servers']) > 1) {
         // offer a chance to login to other servers if the current one failed
         include_once './libraries/select_server.lib.php';
         echo '<tr>', "\n";
         echo ' <td>', "\n";
         echo PMA_selectServer(true, true);
         echo ' </td>', "\n";
         echo '</tr>', "\n";
     }
     echo '</table>', "\n";
     if (!defined('TESTSUITE')) {
         exit;
     }
     return true;
 }