/**
 * Saves user preferences
 *
 * @param array $config_array configuration array
 *
 * @return true|PMA\libraries\Message
 */
function PMA_saveUserprefs(array $config_array)
{
    $cfgRelation = PMA_getRelationsParam();
    $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : $GLOBALS['cfg']['ServerDefault'];
    $cache_key = 'server_' . $server;
    if (!$cfgRelation['userconfigwork']) {
        // no pmadb table, use session storage
        $_SESSION['userconfig'] = array('db' => $config_array, 'ts' => time());
        if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
            unset($_SESSION['cache'][$cache_key]['userprefs']);
        }
        return true;
    }
    // save configuration to pmadb
    $query_table = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['userconfig']);
    $query = 'SELECT `username` FROM ' . $query_table . ' WHERE `username` = \'' . PMA\libraries\Util::sqlAddSlashes($cfgRelation['user']) . '\'';
    $has_config = $GLOBALS['dbi']->fetchValue($query, 0, 0, $GLOBALS['controllink']);
    $config_data = json_encode($config_array);
    if ($has_config) {
        $query = 'UPDATE ' . $query_table . ' SET `timevalue` = NOW(), `config_data` = \'' . PMA\libraries\Util::sqlAddSlashes($config_data) . '\'' . ' WHERE `username` = \'' . PMA\libraries\Util::sqlAddSlashes($cfgRelation['user']) . '\'';
    } else {
        $query = 'INSERT INTO ' . $query_table . ' (`username`, `timevalue`,`config_data`) ' . 'VALUES (\'' . PMA\libraries\Util::sqlAddSlashes($cfgRelation['user']) . '\', NOW(), ' . '\'' . PMA\libraries\Util::sqlAddSlashes($config_data) . '\')';
    }
    if (isset($_SESSION['cache'][$cache_key]['userprefs'])) {
        unset($_SESSION['cache'][$cache_key]['userprefs']);
    }
    if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {
        $message = Message::error(__('Could not save configuration'));
        $message->addMessage('<br /><br />');
        $message->addMessage(Message::rawError($GLOBALS['dbi']->getError($GLOBALS['controllink'])));
        return $message;
    }
    return true;
}
/**
 * Retrieve IDs and names of schema pages
 *
 * @param string $db database name
 *
 * @return array array of schema page id and names
 */
function PMA_getPageIdsAndNames($db)
{
    $cfgRelation = PMA_getRelationsParam();
    $page_query = "SELECT `page_nr`, `page_descr` FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['pdf_pages']) . " WHERE db_name = '" . PMA\libraries\Util::sqlAddSlashes($db) . "'" . " ORDER BY `page_descr`";
    $page_rs = PMA_queryAsControlUser($page_query, false, PMA\libraries\DatabaseInterface::QUERY_STORE);
    $result = array();
    while ($curr_page = $GLOBALS['dbi']->fetchAssoc($page_rs)) {
        $result[$curr_page['page_nr']] = $curr_page['page_descr'];
    }
    return $result;
}
 /**
  * sqlAddslashes test
  *
  * @return void
  */
 public function testAddSlashes()
 {
     $string = "\\'test''\\''\\'\r\t\n";
     $this->assertEquals("\\\\\\\\\\'test\\'\\'\\\\\\\\\\'\\'\\\\\\\\\\'\\r\\t\\n", PMA\libraries\Util::sqlAddSlashes($string, true, true, true));
     $this->assertEquals("\\\\\\\\''test''''\\\\\\\\''''\\\\\\\\''\\r\\t\\n", PMA\libraries\Util::sqlAddSlashes($string, true, true, false));
     $this->assertEquals("\\\\\\\\\\'test\\'\\'\\\\\\\\\\'\\'\\\\\\\\\\'\r\t\n", PMA\libraries\Util::sqlAddSlashes($string, true, false, true));
     $this->assertEquals("\\\\\\\\''test''''\\\\\\\\''''\\\\\\\\''\r\t\n", PMA\libraries\Util::sqlAddSlashes($string, true, false, false));
     $this->assertEquals("\\\\\\'test\\'\\'\\\\\\'\\'\\\\\\'\\r\\t\\n", PMA\libraries\Util::sqlAddSlashes($string, false, true, true));
     $this->assertEquals("\\\\''test''''\\\\''''\\\\''\\r\\t\\n", PMA\libraries\Util::sqlAddSlashes($string, false, true, false));
     $this->assertEquals("\\\\\\'test\\'\\'\\\\\\'\\'\\\\\\'\r\t\n", PMA\libraries\Util::sqlAddSlashes($string, false, false, true));
     $this->assertEquals("\\\\''test''''\\\\''''\\\\''\r\t\n", PMA\libraries\Util::sqlAddSlashes($string, false, false, false));
 }
/**
 * Get Ajax return when $_REQUEST['type'] === 'setval'
 *
 * @param Array $variable_doc_links documentation links
 *
 * @return null
 */
function PMA_getAjaxReturnForSetVal($variable_doc_links)
{
    $response = PMA\libraries\Response::getInstance();
    $value = $_REQUEST['varValue'];
    $matches = array();
    if (isset($variable_doc_links[$_REQUEST['varName']][3]) && $variable_doc_links[$_REQUEST['varName']][3] == 'byte' && preg_match('/^\\s*(\\d+(\\.\\d+)?)\\s*(mb|kb|mib|kib|gb|gib)\\s*$/i', $value, $matches)) {
        $exp = array('kb' => 1, 'kib' => 1, 'mb' => 2, 'mib' => 2, 'gb' => 3, 'gib' => 3);
        $value = floatval($matches[1]) * PMA\libraries\Util::pow(1024, $exp[mb_strtolower($matches[3])]);
    } else {
        $value = PMA\libraries\Util::sqlAddSlashes($value);
    }
    if (!is_numeric($value)) {
        $value = "'" . $value . "'";
    }
    if (!preg_match("/[^a-zA-Z0-9_]+/", $_REQUEST['varName']) && $GLOBALS['dbi']->query('SET GLOBAL ' . $_REQUEST['varName'] . ' = ' . $value)) {
        // Some values are rounded down etc.
        $varValue = $GLOBALS['dbi']->fetchSingleRow('SHOW GLOBAL VARIABLES WHERE Variable_name="' . PMA\libraries\Util::sqlAddSlashes($_REQUEST['varName']) . '";', 'NUM');
        $response->addJSON('variable', PMA_formatVariable($_REQUEST['varName'], $varValue[1], $variable_doc_links));
    } else {
        $response->setRequestStatus(false);
        $response->addJSON('error', __('Setting variable failed'));
    }
}
    exit;
}
/**
 * get master replication from server
 */
$server_master_replication = $GLOBALS['dbi']->fetchResult('SHOW MASTER STATUS');
/**
 * set selected master server
 */
if (!empty($_REQUEST['master_connection'])) {
    /**
     * check for multi-master replication functionality
     */
    $server_slave_multi_replication = $GLOBALS['dbi']->fetchResult('SHOW ALL SLAVES STATUS');
    if ($server_slave_multi_replication) {
        $GLOBALS['dbi']->query("SET @@default_master_connection = '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['master_connection']) . "'");
        $GLOBALS['url_params']['master_connection'] = $_REQUEST['master_connection'];
    }
}
/**
 * get slave replication from server
 */
$server_slave_replication = $GLOBALS['dbi']->fetchResult('SHOW SLAVE STATUS');
/**
 * replication types
 */
$replication_types = array('master', 'slave');
/**
 * define variables for master status
 */
$master_variables = array('File', 'Position', 'Binlog_Do_DB', 'Binlog_Ignore_DB');
/**
 * Replace the placeholders in the bookmark query with variables
 *
 * @param string $query bookmarked query
 *
 * @return string query with variables applied
 */
function PMA_Bookmark_applyVariables($query)
{
    // remove comments that encloses a variable placeholder
    $query = preg_replace('|/\\*(.*\\[VARIABLE[0-9]*\\].*)\\*/|imsU', '${1}', $query);
    // replace variable placeholders with values
    $number_of_variables = PMA_Bookmark_getVariableCount($query);
    for ($i = 1; $i <= $number_of_variables; $i++) {
        $var = '';
        if (!empty($_REQUEST['bookmark_variable'][$i])) {
            $var = PMA\libraries\Util::sqlAddSlashes($_REQUEST['bookmark_variable'][$i]);
        }
        $query = str_replace('[VARIABLE' . $i . ']', $var, $query);
        // backward compatibility
        if ($i == 1) {
            $query = str_replace('[VARIABLE]', $var, $query);
        }
    }
    return $query;
}
Exemple #7
0
if (!isset($_SESSION['is_multi_query'])) {
    $_SESSION['is_multi_query'] = false;
}
$ajax_reload = array();
// Are we just executing plain query or sql file?
// (eg. non import, but query box/window run)
if (!empty($sql_query)) {
    // apply values for parameters
    if (!empty($_REQUEST['parameterized']) && !empty($_REQUEST['parameters']) && is_array($_REQUEST['parameters'])) {
        $parameters = $_REQUEST['parameters'];
        foreach ($parameters as $parameter => $replacement) {
            $quoted = preg_quote($parameter);
            // making sure that :param does not apply values to :param1
            $sql_query = preg_replace('/' . $quoted . '([^a-zA-Z0-9_])/', PMA\libraries\Util::sqlAddSlashes($replacement) . '${1}', $sql_query);
            // for parameters the appear at the end of the string
            $sql_query = preg_replace('/' . $quoted . '$/', PMA\libraries\Util::sqlAddSlashes($replacement), $sql_query);
        }
    }
    // run SQL query
    $import_text = $sql_query;
    $import_type = 'query';
    $format = 'sql';
    $_SESSION['sql_from_query_box'] = true;
    // If there is a request to ROLLBACK when finished.
    if (isset($_REQUEST['rollback_query'])) {
        PMA_handleRollbackRequest($import_text);
    }
    // refresh navigation and main panels
    if (preg_match('/^(DROP)\\s+(VIEW|TABLE|DATABASE|SCHEMA)\\s+/i', $sql_query)) {
        $GLOBALS['reload'] = true;
        $ajax_reload['reload'] = true;
Exemple #8
0
/**
 * Display tracked tables
 *
 * @param string $db                current database
 * @param object $all_tables_result result set of tracked tables
 * @param string $url_query         url query string
 * @param string $pmaThemeImage     path to theme's image folder
 * @param string $text_dir          text direction
 * @param array  $cfgRelation       configuration storage info
 *
 * @return void
 */
function PMA_displayTrackedTables($db, $all_tables_result, $url_query, $pmaThemeImage, $text_dir, $cfgRelation)
{
    ?>
    <div id="tracked_tables">
    <h3><?php 
    echo __('Tracked tables');
    ?>
</h3>

    <form method="post" action="db_tracking.php" name="trackedForm"
        id="trackedForm" class="ajax">
    <?php 
    echo URL::getHiddenInputs($db);
    ?>
    <table id="versions" class="data">
    <thead>
    <tr>
        <th></th>
        <th><?php 
    echo __('Table');
    ?>
</th>
        <th><?php 
    echo __('Last version');
    ?>
</th>
        <th><?php 
    echo __('Created');
    ?>
</th>
        <th><?php 
    echo __('Updated');
    ?>
</th>
        <th><?php 
    echo __('Status');
    ?>
</th>
        <th><?php 
    echo __('Action');
    ?>
</th>
        <th><?php 
    echo __('Show');
    ?>
</th>
    </tr>
    </thead>
    <tbody>
    <?php 
    // Print out information about versions
    $delete = PMA\libraries\Util::getIcon('b_drop.png', __('Delete tracking'));
    $versions = PMA\libraries\Util::getIcon('b_versions.png', __('Versions'));
    $report = PMA\libraries\Util::getIcon('b_report.png', __('Tracking report'));
    $structure = PMA\libraries\Util::getIcon('b_props.png', __('Structure snapshot'));
    $style = 'odd';
    while ($one_result = $GLOBALS['dbi']->fetchArray($all_tables_result)) {
        list($table_name, $version_number) = $one_result;
        $table_query = ' SELECT * FROM ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['tracking']) . ' WHERE `db_name` = \'' . PMA\libraries\Util::sqlAddSlashes($_REQUEST['db']) . '\' AND `table_name`  = \'' . PMA\libraries\Util::sqlAddSlashes($table_name) . '\' AND `version` = \'' . $version_number . '\'';
        $table_result = PMA_queryAsControlUser($table_query);
        $version_data = $GLOBALS['dbi']->fetchArray($table_result);
        $tbl_link = 'tbl_tracking.php' . $url_query . '&amp;table=' . htmlspecialchars($version_data['table_name']);
        $delete_link = 'db_tracking.php' . $url_query . '&amp;table=' . htmlspecialchars($version_data['table_name']) . '&amp;delete_tracking=true&amp';
        $checkbox_id = "selected_tbl_" . htmlspecialchars($version_data['table_name']);
        ?>
        <tr class="<?php 
        echo $style;
        ?>
">
            <td class="center">
                <input type="checkbox" name="selected_tbl[]"
                class="checkall" id="<?php 
        echo $checkbox_id;
        ?>
"
                value="<?php 
        echo htmlspecialchars($version_data['table_name']);
        ?>
"/>
            </td>
            <th>
                <label for="<?php 
        echo $checkbox_id;
        ?>
">
                    <?php 
        echo htmlspecialchars($version_data['table_name']);
        ?>
                </label>
            </th>
            <td class="right"><?php 
        echo $version_data['version'];
        ?>
</td>
            <td><?php 
        echo $version_data['date_created'];
        ?>
</td>
            <td><?php 
        echo $version_data['date_updated'];
        ?>
</td>
            <td>
            <?php 
        PMA_displayStatusButton($version_data, $tbl_link);
        ?>
            </td>
            <td>
            <a class="delete_tracking_anchor ajax"
               href="<?php 
        echo $delete_link;
        ?>
" >
            <?php 
        echo $delete;
        ?>
</a>
        <?php 
        echo '</td>', '<td>', '<a href="', $tbl_link, '">', $versions, '</a>', '&nbsp;&nbsp;', '<a href="', $tbl_link, '&amp;report=true&amp;version=', $version_data['version'], '">', $report, '</a>', '&nbsp;&nbsp;', '<a href="' . $tbl_link, '&amp;snapshot=true&amp;version=', $version_data['version'], '">', $structure, '</a>', '</td>', '</tr>';
        if ($style == 'even') {
            $style = 'odd';
        } else {
            $style = 'even';
        }
    }
    ?>
    </tbody>
    </table>
    <?php 
    echo PMA\libraries\Template::get('select_all')->render(array('pmaThemeImage' => $pmaThemeImage, 'text_dir' => $text_dir, 'formName' => 'trackedForm'));
    echo PMA\libraries\Util::getButtonOrImage('submit_mult', 'mult_submit', __('Delete tracking'), 'b_drop.png', 'delete_tracking');
    ?>
    </form>
    </div>
    <?php 
}
if (isset($_REQUEST['templateAction']) && $cfgRelation['exporttemplateswork']) {
    if (isset($_REQUEST['templateId'])) {
        $templateId = $_REQUEST['templateId'];
        $id = PMA\libraries\Util::sqlAddSlashes($templateId);
    }
    $templateTable = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['export_templates']);
    $user = PMA\libraries\Util::sqlAddSlashes($GLOBALS['cfg']['Server']['user']);
    switch ($_REQUEST['templateAction']) {
        case 'create':
            $query = "INSERT INTO " . $templateTable . "(" . " `username`, `export_type`," . " `template_name`, `template_data`" . ") VALUES (" . "'" . $user . "', " . "'" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['exportType']) . "', " . "'" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['templateName']) . "', " . "'" . PMA\libraries\Util::sqlAddSlashes($_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` = " . "'" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['templateData']) . "'" . " WHERE `id` = " . $id . " AND `username` = '" . $user . "'";
            break;
        case 'delete':
            $query = "DELETE FROM " . $templateTable . " WHERE `id` = " . $id . " AND `username` = '" . $user . "'";
            break;
        default:
            break;
    }
    $result = PMA_queryAsControlUser($query, false);
    $response = PMA\libraries\Response::getInstance();
    if (!$result) {
        $error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
        $response->setRequestStatus(false);
        $response->addJSON('message', $error);
        exit;
    }
/**
 * Cleanup user related relation stuff
 *
 * @param string $username username
 *
 * @return void
 */
function PMA_relationsCleanupUser($username)
{
    $cfgRelation = PMA_getRelationsParam();
    if ($cfgRelation['bookmarkwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['bookmark']) . " WHERE `user`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['historywork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['history']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['recentwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['recent']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['favoritework']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['favorite']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['uiprefswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['table_uiprefs']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['userconfigwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['userconfig']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['menuswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['users']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['navwork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['navigationhiding']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['savedsearcheswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['savedsearches']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
    if ($cfgRelation['designersettingswork']) {
        $remove_query = "DELETE FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['designer_settings']) . " WHERE `username`  = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'";
        PMA_queryAsControlUser($remove_query);
    }
}
/**
 * Changes password for a user
 *
 * @param string $username         Username
 * @param string $hostname         Hostname
 * @param string $password         Password
 * @param string $sql_query        SQL query
 * @param string $hashing_function Hashing function
 * @param string $orig_auth_plugin Original Authentication Plugin
 *
 * @return void
 */
function PMA_changePassUrlParamsAndSubmitQuery($username, $hostname, $password, $sql_query, $hashing_function, $orig_auth_plugin)
{
    $err_url = 'user_password.php' . PMA_URL_getCommon();
    $serverType = PMA\libraries\Util::getServerType();
    if ($serverType == 'MySQL' && PMA_MYSQL_INT_VERSION >= 50706) {
        $local_query = 'ALTER USER \'' . $username . '\'@\'' . $hostname . '\'' . ' IDENTIFIED with ' . $orig_auth_plugin . ' BY ' . ($password == '' ? '\'\'' : '\'' . PMA\libraries\Util::sqlAddSlashes($password) . '\'');
    } else {
        if ($serverType == 'MariaDB' && PMA_MYSQL_INT_VERSION >= 50200 && PMA_MYSQL_INT_VERSION < 100100 && $orig_auth_plugin !== '') {
            if ($orig_auth_plugin == 'mysql_native_password') {
                // Set the hashing method used by PASSWORD()
                // to be 'mysql_native_password' type
                $GLOBALS['dbi']->tryQuery('SET old_passwords = 0;');
            } else {
                if ($orig_auth_plugin == 'sha256_password') {
                    // Set the hashing method used by PASSWORD()
                    // to be 'sha256_password' type
                    $GLOBALS['dbi']->tryQuery('SET `old_passwords` = 2;');
                }
            }
            $hashedPassword = PMA_getHashedPassword($_POST['pma_pw']);
            $local_query = "UPDATE `mysql`.`user` SET" . " `authentication_string` = '" . $hashedPassword . "', `Password` = '', " . " `plugin` = '" . $orig_auth_plugin . "'" . " WHERE `User` = '" . $username . "' AND Host = '" . $hostname . "';";
        } else {
            $local_query = 'SET password = '******'' ? '\'\'' : $hashing_function . '(\'' . PMA\libraries\Util::sqlAddSlashes($password) . '\')');
        }
    }
    if (!@$GLOBALS['dbi']->tryQuery($local_query)) {
        PMA\libraries\Util::mysqlDie($GLOBALS['dbi']->getError(), $sql_query, false, $err_url);
    }
    // Flush privileges after successful password change
    $GLOBALS['dbi']->tryQuery("FLUSH PRIVILEGES;");
}
Exemple #12
0
/**
 * Function to get the default sql query for browsing page
 *
 * @param String $db    the current database
 * @param String $table the current table
 *
 * @return String $sql_query the default $sql_query for browse page
 */
function PMA_getDefaultSqlQueryForBrowse($db, $table)
{
    include_once 'libraries/bookmark.lib.php';
    $book_sql_query = PMA_Bookmark_get($db, '\'' . PMA\libraries\Util::sqlAddSlashes($table) . '\'', 'label', false, true);
    if (!empty($book_sql_query)) {
        $GLOBALS['using_bookmark_message'] = Message::notice(__('Using bookmark "%s" as default browse query.'));
        $GLOBALS['using_bookmark_message']->addParam($table);
        $GLOBALS['using_bookmark_message']->addMessage(PMA\libraries\Util::showDocu('faq', 'faq6-22'));
        $sql_query = $book_sql_query;
    } else {
        $defaultOrderByClause = '';
        if (isset($GLOBALS['cfg']['TablePrimaryKeyOrder']) && $GLOBALS['cfg']['TablePrimaryKeyOrder'] !== 'NONE') {
            $primaryKey = null;
            $primary = PMA\libraries\Index::getPrimary($table, $db);
            if ($primary !== false) {
                $primarycols = $primary->getColumns();
                foreach ($primarycols as $col) {
                    $primaryKey = $col->getName();
                    break;
                }
                if ($primaryKey != null) {
                    $defaultOrderByClause = ' ORDER BY ' . PMA\libraries\Util::backquote($table) . '.' . PMA\libraries\Util::backquote($primaryKey) . ' ' . $GLOBALS['cfg']['TablePrimaryKeyOrder'];
                }
            }
        }
        $sql_query = 'SELECT * FROM ' . PMA\libraries\Util::backquote($table) . $defaultOrderByClause;
    }
    unset($book_sql_query);
    return $sql_query;
}
Exemple #13
0
/**
 * Generate the error url and submit the query
 *
 * @param string $username         Username
 * @param string $hostname         Hostname
 * @param string $password         Password
 * @param string $sql_query        SQL query
 * @param string $hashing_function Hashing function
 * @param string $auth_plugin      Authentication Plugin
 *
 * @return void
 */
function PMA_changePassUrlParamsAndSubmitQuery($username, $hostname, $password, $sql_query, $hashing_function, $auth_plugin)
{
    $err_url = 'user_password.php' . PMA_URL_getCommon();
    if (PMA\libraries\Util::getServerType() === 'MySQL' && PMA_MYSQL_INT_VERSION >= 50706) {
        $local_query = 'ALTER USER \'' . $username . '\'@\'' . $hostname . '\'' . ' IDENTIFIED with ' . $auth_plugin . ' BY ' . ($password == '' ? '\'\'' : '\'' . PMA\libraries\Util::sqlAddSlashes($password) . '\'');
    } else {
        $local_query = 'SET password = '******'' ? '\'\'' : $hashing_function . '(\'' . PMA\libraries\Util::sqlAddSlashes($password) . '\')');
    }
    if (!@$GLOBALS['dbi']->tryQuery($local_query)) {
        PMA\libraries\Util::mysqlDie($GLOBALS['dbi']->getError(), $sql_query, false, $err_url);
    }
}
                if (isset($show_as_php)) {
                    $url_params['show_as_php'] = $show_as_php;
                }
                PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . 'index.php' . PMA_URL_getCommon($url_params, 'text'));
            }
            exit;
        }
    }
}
// end if (ensures db exists)
if (empty($is_table) && !defined('PMA_SUBMIT_MULT') && !defined('TABLE_MAY_BE_ABSENT')) {
    // Not a valid table name -> back to the db_sql.php
    if (mb_strlen($table)) {
        $is_table = $GLOBALS['dbi']->getCachedTableContent("{$db}.{$table}", false);
        if (!$is_table) {
            $_result = $GLOBALS['dbi']->tryQuery('SHOW TABLES LIKE \'' . PMA\libraries\Util::sqlAddSlashes($table, true) . '\';', null, PMA\libraries\DatabaseInterface::QUERY_STORE);
            $is_table = @$GLOBALS['dbi']->numRows($_result);
            $GLOBALS['dbi']->freeResult($_result);
        }
    } else {
        $is_table = false;
    }
    if (!$is_table) {
        if (!defined('IS_TRANSFORMATION_WRAPPER')) {
            if (mb_strlen($table)) {
                // SHOW TABLES doesn't show temporary tables, so try select
                // (as it can happen just in case temporary table, it should be
                // fast):
                /**
                 * @todo should this check really
                 * only happen if IS_TRANSFORMATION_WRAPPER?
/**
 * Save value for a designer setting
 *
 * @param string $index setting
 * @param string $value value
 *
 * @return bool whether the operation succeeded
 */
function PMA_saveDesignerSetting($index, $value)
{
    $cfgRelation = PMA_getRelationsParam();
    $cfgDesigner = array('user' => $GLOBALS['cfg']['Server']['user'], 'db' => $cfgRelation['db'], 'table' => $cfgRelation['designer_settings']);
    $success = true;
    if ($GLOBALS['cfgRelation']['designersettingswork']) {
        $orig_data_query = "SELECT settings_data" . " FROM " . PMA\libraries\Util::backquote($cfgDesigner['db']) . "." . PMA\libraries\Util::backquote($cfgDesigner['table']) . " WHERE username = '******'user']) . "';";
        $orig_data = $GLOBALS['dbi']->fetchSingleRow($orig_data_query, $GLOBALS['controllink']);
        if (!empty($orig_data)) {
            $orig_data = json_decode($orig_data['settings_data'], true);
            $orig_data[$index] = $value;
            $orig_data = json_encode($orig_data);
            $save_query = "UPDATE " . PMA\libraries\Util::backquote($cfgDesigner['db']) . "." . PMA\libraries\Util::backquote($cfgDesigner['table']) . " SET settings_data = '" . $orig_data . "'" . " WHERE username = '******'user']) . "';";
            $success = PMA_queryAsControlUser($save_query);
        } else {
            $save_data = array($index => $value);
            $query = "INSERT INTO " . PMA\libraries\Util::backquote($cfgDesigner['db']) . "." . PMA\libraries\Util::backquote($cfgDesigner['table']) . " (username, settings_data)" . " VALUES('" . $cfgDesigner['user'] . "'," . " '" . json_encode($save_data) . "');";
            $success = PMA_queryAsControlUser($query);
        }
    }
    return (bool) $success;
}
/**
 * Displays a form used to add/edit a trigger
 *
 * @param string $mode If the editor will be used to edit a trigger
 *                     or add a new one: 'edit' or 'add'.
 * @param array  $item Data for the trigger returned by PMA_TRI_getDataFromRequest()
 *                     or PMA_TRI_getDataFromName()
 *
 * @return string HTML code for the editor.
 */
function PMA_TRI_getEditorForm($mode, $item)
{
    global $db, $table, $event_manipulations, $action_timings;
    $modeToUpper = mb_strtoupper($mode);
    // Escape special characters
    $need_escape = array('item_original_name', 'item_name', 'item_definition', 'item_definer');
    foreach ($need_escape as $key => $index) {
        $item[$index] = htmlentities($item[$index], ENT_QUOTES, 'UTF-8');
    }
    $original_data = '';
    if ($mode == 'edit') {
        $original_data = "<input name='item_original_name' " . "type='hidden' value='{$item['item_original_name']}'/>\n";
    }
    $query = "SELECT `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES` ";
    $query .= "WHERE `TABLE_SCHEMA`='" . PMA\libraries\Util::sqlAddSlashes($db) . "' ";
    $query .= "AND `TABLE_TYPE`='BASE TABLE'";
    $tables = $GLOBALS['dbi']->fetchResult($query);
    // Create the output
    $retval = "";
    $retval .= "<!-- START " . $modeToUpper . " TRIGGER FORM -->\n\n";
    $retval .= "<form class='rte_form' action='db_triggers.php' method='post'>\n";
    $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
    $retval .= $original_data;
    $retval .= PMA_URL_getHiddenInputs($db, $table) . "\n";
    $retval .= "<fieldset>\n";
    $retval .= "<legend>" . __('Details') . "</legend>\n";
    $retval .= "<table class='rte_table' style='width: 100%'>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td style='width: 20%;'>" . __('Trigger name') . "</td>\n";
    $retval .= "    <td><input type='text' name='item_name' maxlength='64'\n";
    $retval .= "               value='{$item['item_name']}' /></td>\n";
    $retval .= "</tr>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td>" . __('Table') . "</td>\n";
    $retval .= "    <td>\n";
    $retval .= "        <select name='item_table'>\n";
    foreach ($tables as $key => $value) {
        $selected = "";
        if ($mode == 'add' && $value == $table) {
            $selected = " selected='selected'";
        } else {
            if ($mode == 'edit' && $value == $item['item_table']) {
                $selected = " selected='selected'";
            }
        }
        $retval .= "<option{$selected}>";
        $retval .= htmlspecialchars($value);
        $retval .= "</option>\n";
    }
    $retval .= "        </select>\n";
    $retval .= "    </td>\n";
    $retval .= "</tr>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td>" . _pgettext('Trigger action time', 'Time') . "</td>\n";
    $retval .= "    <td><select name='item_timing'>\n";
    foreach ($action_timings as $key => $value) {
        $selected = "";
        if (!empty($item['item_action_timing']) && $item['item_action_timing'] == $value) {
            $selected = " selected='selected'";
        }
        $retval .= "<option{$selected}>{$value}</option>";
    }
    $retval .= "    </select></td>\n";
    $retval .= "</tr>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td>" . __('Event') . "</td>\n";
    $retval .= "    <td><select name='item_event'>\n";
    foreach ($event_manipulations as $key => $value) {
        $selected = "";
        if (!empty($item['item_event_manipulation']) && $item['item_event_manipulation'] == $value) {
            $selected = " selected='selected'";
        }
        $retval .= "<option{$selected}>{$value}</option>";
    }
    $retval .= "    </select></td>\n";
    $retval .= "</tr>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td>" . __('Definition') . "</td>\n";
    $retval .= "    <td><textarea name='item_definition' rows='15' cols='40'>";
    $retval .= $item['item_definition'];
    $retval .= "</textarea></td>\n";
    $retval .= "</tr>\n";
    $retval .= "<tr>\n";
    $retval .= "    <td>" . __('Definer') . "</td>\n";
    $retval .= "    <td><input type='text' name='item_definer'\n";
    $retval .= "               value='{$item['item_definer']}' /></td>\n";
    $retval .= "</tr>\n";
    $retval .= "</table>\n";
    $retval .= "</fieldset>\n";
    if ($GLOBALS['is_ajax_request']) {
        $retval .= "<input type='hidden' name='editor_process_{$mode}'\n";
        $retval .= "       value='true' />\n";
        $retval .= "<input type='hidden' name='ajax_request' value='true' />\n";
    } else {
        $retval .= "<fieldset class='tblFooters'>\n";
        $retval .= "    <input type='submit' name='editor_process_{$mode}'\n";
        $retval .= "           value='" . __('Go') . "' />\n";
        $retval .= "</fieldset>\n";
    }
    $retval .= "</form>\n\n";
    $retval .= "<!-- END " . $modeToUpper . " TRIGGER FORM -->\n\n";
    return $retval;
}
/**
 * Export at the database level
 *
 * @param string       $db              the database to export
 * @param array        $tables          the tables to export
 * @param string       $whatStrucOrData structure or data or both
 * @param array        $table_structure whether to export structure for each table
 * @param array        $table_data      whether to export data for each table
 * @param ExportPlugin $export_plugin   the selected export plugin
 * @param string       $crlf            end of line character(s)
 * @param string       $err_url         the URL in case of error
 * @param string       $export_type     the export type
 * @param bool         $do_relation     whether to export relation info
 * @param bool         $do_comments     whether to add comments
 * @param bool         $do_mime         whether to add MIME info
 * @param bool         $do_dates        whether to add dates
 * @param array        $aliases         Alias information for db/table/column
 * @param string       $separate_files  whether it is a separate-files export
 *
 * @return void
 */
function PMA_exportDatabase($db, $tables, $whatStrucOrData, $table_structure, $table_data, $export_plugin, $crlf, $err_url, $export_type, $do_relation, $do_comments, $do_mime, $do_dates, $aliases, $separate_files)
{
    $db_alias = !empty($aliases[$db]['alias']) ? $aliases[$db]['alias'] : '';
    if (!$export_plugin->exportDBHeader($db, $db_alias)) {
        return;
    }
    if (!$export_plugin->exportDBCreate($db, $export_type, $db_alias)) {
        return;
    }
    if ($separate_files == 'database') {
        PMA_saveObjectInBuffer('database', true);
    }
    if (($GLOBALS['sql_structure_or_data'] == 'structure' || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') && isset($GLOBALS['sql_procedure_function'])) {
        $export_plugin->exportRoutines($db, $aliases);
        if ($separate_files == 'database') {
            PMA_saveObjectInBuffer('routines');
        }
    }
    $views = array();
    foreach ($tables as $table) {
        $_table = new Table($table, $db);
        // if this is a view, collect it for later;
        // views must be exported after the tables
        $is_view = $_table->isView();
        if ($is_view) {
            $views[] = $table;
        }
        if (($whatStrucOrData == 'structure' || $whatStrucOrData == 'structure_and_data') && in_array($table, $table_structure)) {
            // for a view, export a stand-in definition of the table
            // to resolve view dependencies (only when it's a single-file export)
            if ($is_view) {
                if ($separate_files == '' && isset($GLOBALS['sql_create_view']) && !$export_plugin->exportStructure($db, $table, $crlf, $err_url, 'stand_in', $export_type, $do_relation, $do_comments, $do_mime, $do_dates, $aliases)) {
                    break;
                }
            } else {
                if (isset($GLOBALS['sql_create_table'])) {
                    $table_size = $GLOBALS['maxsize'];
                    // Checking if the maximum table size constrain has been set
                    // And if that constrain is a valid number or not
                    if ($table_size !== '' && is_numeric($table_size)) {
                        // This obtains the current table's size
                        $query = 'SELECT data_length + index_length
                          from information_schema.TABLES
                          WHERE table_schema = "' . PMA\libraries\Util::sqlAddSlashes($db) . '"
                          AND table_name = "' . PMA\libraries\Util::sqlAddSlashes($table) . '"';
                        $size = $GLOBALS['dbi']->fetchValue($query);
                        //Converting the size to MB
                        $size = $size / 1024 / 1024;
                        if ($size > $table_size) {
                            continue;
                        }
                    }
                    if (!$export_plugin->exportStructure($db, $table, $crlf, $err_url, 'create_table', $export_type, $do_relation, $do_comments, $do_mime, $do_dates, $aliases)) {
                        break;
                    }
                }
            }
        }
        // if this is a view or a merge table, don't export data
        if (($whatStrucOrData == 'data' || $whatStrucOrData == 'structure_and_data') && in_array($table, $table_data) && !$is_view) {
            $local_query = 'SELECT * FROM ' . PMA\libraries\Util::backquote($db) . '.' . PMA\libraries\Util::backquote($table);
            if (!$export_plugin->exportData($db, $table, $crlf, $err_url, $local_query, $aliases)) {
                break;
            }
        }
        // this buffer was filled, we save it and go to the next one
        if ($separate_files == 'database') {
            PMA_saveObjectInBuffer('table_' . $table);
        }
        // now export the triggers (needs to be done after the data because
        // triggers can modify already imported tables)
        if (isset($GLOBALS['sql_create_trigger']) && ($whatStrucOrData == 'structure' || $whatStrucOrData == 'structure_and_data') && in_array($table, $table_structure)) {
            if (!$export_plugin->exportStructure($db, $table, $crlf, $err_url, 'triggers', $export_type, $do_relation, $do_comments, $do_mime, $do_dates, $aliases)) {
                break;
            }
            if ($separate_files == 'database') {
                PMA_saveObjectInBuffer('table_' . $table, true);
            }
        }
    }
    if (isset($GLOBALS['sql_create_view'])) {
        foreach ($views as $view) {
            // no data export for a view
            if ($whatStrucOrData == 'structure' || $whatStrucOrData == 'structure_and_data') {
                if (!$export_plugin->exportStructure($db, $view, $crlf, $err_url, 'create_view', $export_type, $do_relation, $do_comments, $do_mime, $do_dates, $aliases)) {
                    break;
                }
                if ($separate_files == 'database') {
                    PMA_saveObjectInBuffer('view_' . $view);
                }
            }
        }
    }
    if (!$export_plugin->exportDBFooter($db)) {
        return;
    }
    // export metadata related to this db
    if (isset($GLOBALS['sql_metadata'])) {
        // Types of metadata to export.
        // In the future these can be allowed to be selected by the user
        $metadataTypes = PMA_getMetadataTypesToExport();
        $export_plugin->exportMetadata($db, $tables, $metadataTypes);
        if ($separate_files == 'database') {
            PMA_saveObjectInBuffer('metadata');
        }
    }
    if ($separate_files == 'database') {
        PMA_saveObjectInBuffer('extra');
    }
    if (($GLOBALS['sql_structure_or_data'] == 'structure' || $GLOBALS['sql_structure_or_data'] == 'structure_and_data') && isset($GLOBALS['sql_procedure_function'])) {
        $export_plugin->exportEvents($db);
        if ($separate_files == 'database') {
            PMA_saveObjectInBuffer('events');
        }
    }
}
    /**
     * Copy database
     */
    $response->addHTML(PMA_getHtmlForCopyDatabase($GLOBALS['db']));
    /**
     * Change database charset
     */
    $response->addHTML(PMA_getHtmlForChangeDatabaseCharset($GLOBALS['db'], $table));
    if (!$cfgRelation['allworks'] && $cfg['PmaNoRelation_DisableWarning'] == false) {
        $message = PMA\libraries\Message::notice(__('The phpMyAdmin configuration storage has been deactivated. ' . '%sFind out why%s.'));
        $message->addParam('<a href="' . './chk_rel.php' . $url_query . '">', false);
        $message->addParam('</a>', false);
        /* Show error if user has configured something, notice elsewhere */
        if (!empty($cfg['Servers'][$server]['pmadb'])) {
            $message->isError(true);
        }
    }
    // end if
}
// end if (!$is_information_schema)
$response->addHTML('</div>');
// not sure about displaying the PDF dialog in case db is information_schema
if ($cfgRelation['pdfwork'] && $num_tables > 0) {
    // We only show this if we find something in the new pdf_pages table
    $test_query = '
        SELECT *
        FROM ' . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['pdf_pages']) . '
        WHERE db_name = \'' . PMA\libraries\Util::sqlAddSlashes($GLOBALS['db']) . '\'';
    $test_rs = PMA_queryAsControlUser($test_query, false, PMA\libraries\DatabaseInterface::QUERY_STORE);
}
// end if
Exemple #19
0
    }
}
// Get tracked data about the database
$data = Tracker::getTrackedData($_REQUEST['db'], '', '1');
// No tables present and no log exist
if ($num_tables == 0 && count($data['ddlog']) == 0) {
    echo '<p>', __('No tables found in database.'), '</p>', "\n";
    if (empty($db_is_system_schema)) {
        echo PMA_getHtmlForCreateTable($db);
    }
    exit;
}
// ---------------------------------------------------------------------------
$cfgRelation = PMA_getRelationsParam();
// Prepare statement to get HEAD version
$all_tables_query = ' SELECT table_name, MAX(version) as version FROM ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['tracking']) . ' WHERE db_name = \'' . PMA\libraries\Util::sqlAddSlashes($_REQUEST['db']) . '\' ' . ' GROUP BY table_name' . ' ORDER BY table_name ASC';
$all_tables_result = PMA_queryAsControlUser($all_tables_query);
// If a HEAD version exists
if (is_object($all_tables_result) && $GLOBALS['dbi']->numRows($all_tables_result) > 0) {
    PMA_displayTrackedTables($GLOBALS['db'], $all_tables_result, $url_query, $pmaThemeImage, $text_dir, $cfgRelation);
}
$untracked_tables = PMA_getUntrackedTables($GLOBALS['db']);
// If untracked tables exist
if (count($untracked_tables) > 0) {
    PMA_displayUntrackedTables($GLOBALS['db'], $untracked_tables, $url_query, $pmaThemeImage, $text_dir);
}
// If available print out database log
if (count($data['ddlog']) > 0) {
    $log = '';
    foreach ($data['ddlog'] as $entry) {
        $log .= '# ' . $entry['date'] . ' ' . $entry['username'] . "\n" . $entry['statement'] . "\n";
/**
 * Add/update a user group with allowed menu tabs.
 *
 * @param string  $userGroup user group name
 * @param boolean $new       whether this is a new user group
 *
 * @return void
 */
function PMA_editUserGroup($userGroup, $new = false)
{
    $tabs = PMA\libraries\Util::getMenuTabList();
    $cfgRelation = PMA_getRelationsParam();
    $groupTable = PMA\libraries\Util::backquote($cfgRelation['db']) . "." . PMA\libraries\Util::backquote($cfgRelation['usergroups']);
    if (!$new) {
        $sql_query = "DELETE FROM " . $groupTable . " WHERE `usergroup`='" . PMA\libraries\Util::sqlAddSlashes($userGroup) . "';";
        PMA_queryAsControlUser($sql_query, true);
    }
    $sql_query = "INSERT INTO " . $groupTable . "(`usergroup`, `tab`, `allowed`)" . " VALUES ";
    $first = true;
    foreach ($tabs as $tabGroupName => $tabGroup) {
        foreach ($tabGroup as $tab => $tabName) {
            if (!$first) {
                $sql_query .= ", ";
            }
            $tabName = $tabGroupName . '_' . $tab;
            $allowed = isset($_REQUEST[$tabName]) && $_REQUEST[$tabName] == 'Y';
            $sql_query .= "('" . PMA_Util::sqlAddSlashes($userGroup) . "', '" . $tabName . "', '" . ($allowed ? "Y" : "N") . "')";
            $first = false;
        }
    }
    $sql_query .= ";";
    PMA_queryAsControlUser($sql_query, true);
}
/**
 * handle control requests for Slave Change Master
 *
 * @return boolean
 */
function PMA_handleRequestForSlaveChangeMaster()
{
    $sr = array();
    $_SESSION['replication']['m_username'] = $sr['username'] = PMA\libraries\Util::sqlAddSlashes($_REQUEST['username']);
    $_SESSION['replication']['m_password'] = $sr['pma_pw'] = PMA\libraries\Util::sqlAddSlashes($_REQUEST['pma_pw']);
    $_SESSION['replication']['m_hostname'] = $sr['hostname'] = PMA\libraries\Util::sqlAddSlashes($_REQUEST['hostname']);
    $_SESSION['replication']['m_port'] = $sr['port'] = PMA\libraries\Util::sqlAddSlashes($_REQUEST['text_port']);
    $_SESSION['replication']['m_correct'] = '';
    $_SESSION['replication']['sr_action_status'] = 'error';
    $_SESSION['replication']['sr_action_info'] = __('Unknown error');
    // Attempt to connect to the new master server
    $link_to_master = PMA_Replication_connectToMaster($sr['username'], $sr['pma_pw'], $sr['hostname'], $sr['port']);
    if (!$link_to_master) {
        $_SESSION['replication']['sr_action_status'] = 'error';
        $_SESSION['replication']['sr_action_info'] = sprintf(__('Unable to connect to master %s.'), htmlspecialchars($sr['hostname']));
    } else {
        // Read the current master position
        $position = PMA_Replication_Slave_binLogMaster($link_to_master);
        if (empty($position)) {
            $_SESSION['replication']['sr_action_status'] = 'error';
            $_SESSION['replication']['sr_action_info'] = __('Unable to read master log position. ' . 'Possible privilege problem on master.');
        } else {
            $_SESSION['replication']['m_correct'] = true;
            if (!PMA_Replication_Slave_changeMaster($sr['username'], $sr['pma_pw'], $sr['hostname'], $sr['port'], $position, true, false)) {
                $_SESSION['replication']['sr_action_status'] = 'error';
                $_SESSION['replication']['sr_action_info'] = __('Unable to change master!');
            } else {
                $_SESSION['replication']['sr_action_status'] = 'success';
                $_SESSION['replication']['sr_action_info'] = sprintf(__('Master server changed successfully to %s.'), htmlspecialchars($sr['hostname']));
            }
        }
    }
    return $_SESSION['replication']['sr_action_status'] === 'success';
}
/**
 * Function to get table creation sql query
 *
 * @param string $db    database name
 * @param string $table table name
 *
 * @return string
 */
function PMA_getTableCreationQuery($db, $table)
{
    // get column addition statements
    $sql_statement = PMA_getColumnCreationStatements(true);
    // Builds the 'create table' statement
    $sql_query = 'CREATE TABLE ' . PMA\libraries\Util::backquote($db) . '.' . PMA\libraries\Util::backquote(trim($table)) . ' (' . $sql_statement . ')';
    // Adds table type, character set, comments and partition definition
    if (!empty($_REQUEST['tbl_storage_engine']) && $_REQUEST['tbl_storage_engine'] != 'Default') {
        $sql_query .= ' ENGINE = ' . $_REQUEST['tbl_storage_engine'];
    }
    if (!empty($_REQUEST['tbl_collation'])) {
        $sql_query .= PMA_generateCharsetQueryPart($_REQUEST['tbl_collation']);
    }
    if (!empty($_REQUEST['connection']) && !empty($_REQUEST['tbl_storage_engine']) && $_REQUEST['tbl_storage_engine'] == 'FEDERATED') {
        $sql_query .= " CONNECTION = '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['connection']) . "'";
    }
    if (!empty($_REQUEST['comment'])) {
        $sql_query .= ' COMMENT = \'' . PMA\libraries\Util::sqlAddSlashes($_REQUEST['comment']) . '\'';
    }
    $sql_query .= PMA_getPartitionsDefinition();
    $sql_query .= ';';
    return $sql_query;
}
/**
 * Returns HTML for the options in teplate dropdown
 *
 * @param string $export_type export type - server, database, or table
 *
 * @return string HTML for the options in teplate dropdown
 */
function PMA_getOptionsForExportTemplates($export_type)
{
    $ret = '<option value="">-- ' . __('Select a template') . ' --</option>';
    // Get the relation settings
    $cfgRelation = PMA_getRelationsParam();
    $query = "SELECT `id`, `template_name` FROM " . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['export_templates']) . " WHERE `username` = " . "'" . PMA\libraries\Util::sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . "'" . " AND `export_type` = '" . $export_type . "'" . " ORDER BY `template_name`;";
    $result = PMA_queryAsControlUser($query);
    if ($result) {
        while ($row = $GLOBALS['dbi']->fetchAssoc($result, $GLOBALS['controllink'])) {
            $ret .= '<option value="' . htmlspecialchars($row['id']) . '"';
            if (!empty($_GET['template_id']) && $_GET['template_id'] == $row['id']) {
                $ret .= ' selected="selected"';
            }
            $ret .= '>';
            $ret .= htmlspecialchars($row['template_name']) . '</option>';
        }
    }
    return $ret;
}
/**
 * Get the current column value in the form for different data types
 *
 * @param string|false $possibly_uploaded_val        uploaded file content
 * @param string       $key                          an md5 of the column name
 * @param array        $multi_edit_columns_type      array of multi edit column types
 * @param string       $current_value                current column value in the form
 * @param array        $multi_edit_auto_increment    multi edit auto increment
 * @param integer      $rownumber                    index of where clause array
 * @param array        $multi_edit_columns_name      multi edit column names array
 * @param array        $multi_edit_columns_null      multi edit columns null array
 * @param array        $multi_edit_columns_null_prev multi edit columns previous null
 * @param boolean      $is_insert                    whether insert or not
 * @param boolean      $using_key                    whether editing or new row
 * @param string       $where_clause                 where clause
 * @param string       $table                        table name
 *
 * @return string $current_value  current column value in the form
 */
function PMA_getCurrentValueForDifferentTypes($possibly_uploaded_val, $key, $multi_edit_columns_type, $current_value, $multi_edit_auto_increment, $rownumber, $multi_edit_columns_name, $multi_edit_columns_null, $multi_edit_columns_null_prev, $is_insert, $using_key, $where_clause, $table)
{
    // Fetch the current values of a row to use in case we have a protected field
    if ($is_insert && $using_key && isset($multi_edit_columns_type) && is_array($multi_edit_columns_type) && !empty($where_clause)) {
        $protected_row = $GLOBALS['dbi']->fetchSingleRow('SELECT * FROM ' . PMA\libraries\Util::backquote($table) . ' WHERE ' . $where_clause . ';');
    }
    if (false !== $possibly_uploaded_val) {
        $current_value = $possibly_uploaded_val;
    } else {
        // c o l u m n    v a l u e    i n    t h e    f o r m
        if (isset($multi_edit_columns_type[$key])) {
            $type = $multi_edit_columns_type[$key];
        } else {
            $type = '';
        }
        if ($type != 'protected' && $type != 'set' && 0 === mb_strlen($current_value)) {
            // best way to avoid problems in strict mode
            // (works also in non-strict mode)
            if (isset($multi_edit_auto_increment) && isset($multi_edit_auto_increment[$key])) {
                $current_value = 'NULL';
            } else {
                $current_value = "''";
            }
        } elseif ($type == 'set') {
            if (!empty($_REQUEST['fields']['multi_edit'][$rownumber][$key])) {
                $current_value = implode(',', $_REQUEST['fields']['multi_edit'][$rownumber][$key]);
                $current_value = "'" . PMA\libraries\Util::sqlAddSlashes($current_value) . "'";
            } else {
                $current_value = "''";
            }
        } elseif ($type == 'protected') {
            // here we are in protected mode (asked in the config)
            // so tbl_change has put this special value in the
            // columns array, so we do not change the column value
            // but we can still handle column upload
            // when in UPDATE mode, do not alter field's contents. When in INSERT
            // mode, insert empty field because no values were submitted.
            // If protected blobs where set, insert original fields content.
            if (!empty($protected_row[$multi_edit_columns_name[$key]])) {
                $current_value = '0x' . bin2hex($protected_row[$multi_edit_columns_name[$key]]);
            } else {
                $current_value = '';
            }
        } elseif ($type === 'hex') {
            $current_value = '0x' . $current_value;
        } elseif ($type == 'bit') {
            $current_value = preg_replace('/[^01]/', '0', $current_value);
            $current_value = "b'" . PMA\libraries\Util::sqlAddSlashes($current_value) . "'";
        } elseif (!($type == 'datetime' || $type == 'timestamp') || $current_value != 'CURRENT_TIMESTAMP') {
            $current_value = "'" . PMA\libraries\Util::sqlAddSlashes($current_value) . "'";
        }
        // Was the Null checkbox checked for this field?
        // (if there is a value, we ignore the Null checkbox: this could
        // be possible if Javascript is disabled in the browser)
        if (!empty($multi_edit_columns_null[$key]) && ($current_value == "''" || $current_value == '')) {
            $current_value = 'NULL';
        }
        // The Null checkbox was unchecked for this field
        if (empty($current_value) && !empty($multi_edit_columns_null_prev[$key]) && !isset($multi_edit_columns_null[$key])) {
            $current_value = "''";
        }
    }
    // end else (column value in the form)
    return $current_value;
}
/**
 * Handles export template actions
 *
 * @param array $cfgRelation Relation configuration
 *
 * @return void
 */
function PMA_handleExportTemplateActions($cfgRelation)
{
    if (isset($_REQUEST['templateId'])) {
        $id = PMA\libraries\Util::sqlAddSlashes($_REQUEST['templateId']);
    } else {
        $id = '';
    }
    $templateTable = PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['export_templates']);
    $user = PMA\libraries\Util::sqlAddSlashes($GLOBALS['cfg']['Server']['user']);
    switch ($_REQUEST['templateAction']) {
        case 'create':
            $query = "INSERT INTO " . $templateTable . "(" . " `username`, `export_type`," . " `template_name`, `template_data`" . ") VALUES (" . "'" . $user . "', " . "'" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['exportType']) . "', '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['templateName']) . "', '" . PMA\libraries\Util::sqlAddSlashes($_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` = " . "'" . PMA\libraries\Util::sqlAddSlashes($_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 = PMA\libraries\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);
}
/**
 * Get child table references for a table column.
 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
 *
 * @param string $db     name of master table db.
 * @param string $table  name of master table.
 * @param string $column name of master table column.
 *
 * @return array $child_references
 */
function PMA_getChildReferences($db, $table, $column = '')
{
    $child_references = array();
    if (!$GLOBALS['cfg']['Server']['DisableIS']) {
        $rel_query = "SELECT `column_name`, `table_name`," . " `table_schema`, `referenced_column_name`" . " FROM `information_schema`.`key_column_usage`" . " WHERE `referenced_table_name` = '" . PMA\libraries\Util::sqlAddSlashes($table) . "'" . " AND `referenced_table_schema` = '" . PMA\libraries\Util::sqlAddSlashes($db) . "'";
        if ($column) {
            $rel_query .= " AND `referenced_column_name` = '" . PMA\libraries\Util::sqlAddSlashes($column) . "'";
        }
        $child_references = $GLOBALS['dbi']->fetchResult($rel_query, array('referenced_column_name', null));
    }
    return $child_references;
}
/**
 * Composes the query necessary to create an event from an HTTP request.
 *
 * @return string  The CREATE EVENT query.
 */
function PMA_EVN_getQueryFromRequest()
{
    global $_REQUEST, $errors, $event_status, $event_type, $event_interval;
    $query = 'CREATE ';
    if (!empty($_REQUEST['item_definer'])) {
        if (mb_strpos($_REQUEST['item_definer'], '@') !== false) {
            $arr = explode('@', $_REQUEST['item_definer']);
            $query .= 'DEFINER=' . PMA\libraries\Util::backquote($arr[0]);
            $query .= '@' . PMA\libraries\Util::backquote($arr[1]) . ' ';
        } else {
            $errors[] = __('The definer must be in the "username@hostname" format!');
        }
    }
    $query .= 'EVENT ';
    if (!empty($_REQUEST['item_name'])) {
        $query .= PMA\libraries\Util::backquote($_REQUEST['item_name']) . ' ';
    } else {
        $errors[] = __('You must provide an event name!');
    }
    $query .= 'ON SCHEDULE ';
    if (!empty($_REQUEST['item_type']) && in_array($_REQUEST['item_type'], $event_type)) {
        if ($_REQUEST['item_type'] == 'RECURRING') {
            if (!empty($_REQUEST['item_interval_value']) && !empty($_REQUEST['item_interval_field']) && in_array($_REQUEST['item_interval_field'], $event_interval)) {
                $query .= 'EVERY ' . intval($_REQUEST['item_interval_value']) . ' ';
                $query .= $_REQUEST['item_interval_field'] . ' ';
            } else {
                $errors[] = __('You must provide a valid interval value for the event.');
            }
            if (!empty($_REQUEST['item_starts'])) {
                $query .= "STARTS '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['item_starts']) . "' ";
            }
            if (!empty($_REQUEST['item_ends'])) {
                $query .= "ENDS '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['item_ends']) . "' ";
            }
        } else {
            if (!empty($_REQUEST['item_execute_at'])) {
                $query .= "AT '" . PMA\libraries\Util::sqlAddSlashes($_REQUEST['item_execute_at']) . "' ";
            } else {
                $errors[] = __('You must provide a valid execution time for the event.');
            }
        }
    } else {
        $errors[] = __('You must provide a valid type for the event.');
    }
    $query .= 'ON COMPLETION ';
    if (empty($_REQUEST['item_preserve'])) {
        $query .= 'NOT ';
    }
    $query .= 'PRESERVE ';
    if (!empty($_REQUEST['item_status'])) {
        foreach ($event_status['display'] as $key => $value) {
            if ($value == $_REQUEST['item_status']) {
                $query .= $event_status['query'][$key] . ' ';
                break;
            }
        }
    }
    if (!empty($_REQUEST['item_comment'])) {
        $query .= "COMMENT '" . PMA\libraries\Util::sqlAddslashes($_REQUEST['item_comment']) . "' ";
    }
    $query .= 'DO ';
    if (!empty($_REQUEST['item_definition'])) {
        $query .= $_REQUEST['item_definition'];
    } else {
        $errors[] = __('You must provide an event definition.');
    }
    return $query;
}
 /**
  * Test for PMA_getSqlQueryForDisplayPrivTable
  *
  * @return void
  */
 public function testPMAGetSqlQueryForDisplayPrivTable()
 {
     $username = "******";
     $db = '*';
     $table = "pma_table";
     $hostname = "pma_hostname";
     //$db == '*'
     $ret = PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
     $sql = "SELECT * FROM `mysql`.`user`" . " WHERE `User` = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA\libraries\Util::sqlAddSlashes($hostname) . "';";
     $this->assertEquals($sql, $ret);
     //$table == '*'
     $db = "pma_db";
     $table = "*";
     $ret = PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
     $sql = "SELECT * FROM `mysql`.`db`" . " WHERE `User` = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA\libraries\Util::sqlAddSlashes($hostname) . "'" . " AND '" . PMA\libraries\Util::unescapeMysqlWildcards($db) . "'" . " LIKE `Db`;";
     $this->assertEquals($sql, $ret);
     //$table == 'pma_table'
     $db = "pma_db";
     $table = "pma_table";
     $ret = PMA_getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
     $sql = "SELECT `Table_priv`" . " FROM `mysql`.`tables_priv`" . " WHERE `User` = '" . PMA\libraries\Util::sqlAddSlashes($username) . "'" . " AND `Host` = '" . PMA\libraries\Util::sqlAddSlashes($hostname) . "'" . " AND `Db` = '" . PMA\libraries\Util::unescapeMysqlWildcards($db) . "'" . " AND `Table_name` = '" . PMA\libraries\Util::sqlAddSlashes($table) . "';";
     $this->assertEquals($sql, $ret);
 }
/**
 * Set a single mimetype to a certain value.
 *
 * @param string  $db                 the name of the db
 * @param string  $table              the name of the table
 * @param string  $key                the name of the column
 * @param string  $mimetype           the mimetype of the column
 * @param string  $transformation     the transformation of the column
 * @param string  $transformationOpts the transformation options of the column
 * @param string  $inputTransform     the input transformation of the column
 * @param string  $inputTransformOpts the input transformation options of the column
 * @param boolean $forcedelete        force delete, will erase any existing
 *                                    comments for this column
 *
 * @access  public
 *
 * @return boolean  true, if comment-query was made.
 */
function PMA_setMIME($db, $table, $key, $mimetype, $transformation, $transformationOpts, $inputTransform, $inputTransformOpts, $forcedelete = false)
{
    $cfgRelation = PMA_getRelationsParam();
    if (!$cfgRelation['commwork']) {
        return false;
    }
    // lowercase mimetype & transformation
    $mimetype = mb_strtolower($mimetype);
    $transformation = mb_strtolower($transformation);
    $test_qry = '
         SELECT `mimetype`,
                `comment`
           FROM ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['column_info']) . '
          WHERE `db_name`     = \'' . PMA\libraries\Util::sqlAddSlashes($db) . '\'
            AND `table_name`  = \'' . PMA\libraries\Util::sqlAddSlashes($table) . '\'
            AND `column_name` = \'' . PMA\libraries\Util::sqlAddSlashes($key) . '\'';
    $test_rs = PMA_queryAsControlUser($test_qry, true, PMA\libraries\DatabaseInterface::QUERY_STORE);
    if ($test_rs && $GLOBALS['dbi']->numRows($test_rs) > 0) {
        $row = @$GLOBALS['dbi']->fetchAssoc($test_rs);
        $GLOBALS['dbi']->freeResult($test_rs);
        $transformationLength = mb_strlen($transformation);
        if (!$forcedelete && (mb_strlen($mimetype) || $transformationLength || mb_strlen($transformationOpts) || mb_strlen($row['comment']))) {
            $upd_query = 'UPDATE ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['column_info']) . ' SET ' . '`mimetype` = \'' . PMA\libraries\Util::sqlAddSlashes($mimetype) . '\', ' . '`transformation` = \'' . PMA\libraries\Util::sqlAddSlashes($transformation) . '\', ' . '`transformation_options` = \'' . PMA\libraries\Util::sqlAddSlashes($transformationOpts) . '\', ' . '`input_transformation` = \'' . PMA\libraries\Util::sqlAddSlashes($inputTransform) . '\', ' . '`input_transformation_options` = \'' . PMA\libraries\Util::sqlAddSlashes($inputTransformOpts) . '\'';
        } else {
            $upd_query = 'DELETE FROM ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['column_info']);
        }
        $upd_query .= '
            WHERE `db_name`     = \'' . PMA\libraries\Util::sqlAddSlashes($db) . '\'
              AND `table_name`  = \'' . PMA\libraries\Util::sqlAddSlashes($table) . '\'
              AND `column_name` = \'' . PMA\libraries\Util::sqlAddSlashes($key) . '\'';
    } elseif (mb_strlen($mimetype) || mb_strlen($transformation) || mb_strlen($transformationOpts)) {
        $upd_query = 'INSERT INTO ' . PMA\libraries\Util::backquote($cfgRelation['db']) . '.' . PMA\libraries\Util::backquote($cfgRelation['column_info']) . ' (db_name, table_name, column_name, mimetype, ' . 'transformation, transformation_options, ' . 'input_transformation, input_transformation_options) ' . ' VALUES(' . '\'' . PMA\libraries\Util::sqlAddSlashes($db) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($table) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($key) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($mimetype) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($transformation) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($transformationOpts) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($inputTransform) . '\',' . '\'' . PMA\libraries\Util::sqlAddSlashes($inputTransformOpts) . '\')';
    }
    if (isset($upd_query)) {
        return PMA_queryAsControlUser($upd_query);
    } else {
        return false;
    }
}