formatSql() public static method

format sql strings
public static formatSql ( string $sqlQuery, boolean $truncate = false ) : string
$sqlQuery string raw SQL string
$truncate boolean truncate the query if it is too long
return string the formatted sql
Esempio n. 1
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;
                }
            }
        }
    }
}
Esempio n. 2
0
/**
 * Returns the html for all binary log items.
 *
 * @param resource $result         MySQL Query result
 * @param bool     $dontlimitchars Whether limit chars
 *
 * @return string
 */
function PMA_getAllLogItemInfo($result, $dontlimitchars)
{
    $html = "";
    $odd_row = true;
    while ($value = $GLOBALS['dbi']->fetchAssoc($result)) {
        $html .= '<tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">' . '<td>' . $value['Log_name'] . '</td>' . '<td class="right">' . $value['Pos'] . '</td>' . '<td>' . $value['Event_type'] . '</td>' . '<td class="right">' . $value['Server_id'] . '</td>' . '<td class="right">' . (isset($value['Orig_log_pos']) ? $value['Orig_log_pos'] : $value['End_log_pos']) . '</td>' . '<td>' . Util::formatSql($value['Info'], !$dontlimitchars) . '</td></tr>';
        $odd_row = !$odd_row;
    }
    return $html;
}
 /**
  * Does the actual work of each specific transformations plugin.
  *
  * @param string $buffer  text to be transformed
  * @param array  $options transformation options
  * @param string $meta    meta information
  *
  * @return string
  */
 public function applyTransformation($buffer, $options = array(), $meta = '')
 {
     // see PMA_highlightSQL()
     $result = PMA\libraries\Util::formatSql($buffer);
     return $result;
 }
/**
 * Prints Every Item of Server Process
 *
 * @param array $process       data of Every Item of Server Process
 * @param bool  $show_full_sql show full sql or not
 *
 * @return string
 */
function PMA_getHtmlForServerProcessItem($process, $show_full_sql)
{
    // Array keys need to modify due to the way it has used
    // to display column values
    if (!empty($_REQUEST['order_by_field']) && !empty($_REQUEST['sort_order']) || !empty($_REQUEST['showExecuting'])) {
        foreach (array_keys($process) as $key) {
            $new_key = ucfirst(mb_strtolower($key));
            if ($new_key !== $key) {
                $process[$new_key] = $process[$key];
                unset($process[$key]);
            }
        }
    }
    $url_params = array('kill' => $process['Id'], 'ajax_request' => true);
    $kill_process = 'server_status_processes.php' . URL::getCommon($url_params);
    $retval = '<tr>';
    $retval .= '<td><a class="ajax kill_process" href="' . $kill_process . '">' . __('Kill') . '</a></td>';
    $retval .= '<td class="value">' . $process['Id'] . '</td>';
    $retval .= '<td>' . htmlspecialchars($process['User']) . '</td>';
    $retval .= '<td>' . htmlspecialchars($process['Host']) . '</td>';
    $retval .= '<td>' . (!isset($process['db']) || strlen($process['db']) === 0 ? '<i>' . __('None') . '</i>' : htmlspecialchars($process['db'])) . '</td>';
    $retval .= '<td>' . htmlspecialchars($process['Command']) . '</td>';
    $retval .= '<td class="value">' . $process['Time'] . '</td>';
    $processStatusStr = empty($process['State']) ? '---' : $process['State'];
    $retval .= '<td>' . $processStatusStr . '</td>';
    $processProgress = empty($process['Progress']) ? '---' : $process['Progress'];
    $retval .= '<td>' . $processProgress . '</td>';
    $retval .= '<td>';
    if (empty($process['Info'])) {
        $retval .= '---';
    } else {
        $retval .= Util::formatSql($process['Info'], !$show_full_sql);
    }
    $retval .= '</td>';
    $retval .= '</tr>';
    return $retval;
}
Esempio n. 5
0
/**
 * Find the matching rows for UPDATE/DELETE query.
 *
 * @param array $analyzed_sql_results Analyzed SQL results from parser.
 *
 * @return mixed
 */
function PMA_getMatchedRows($analyzed_sql_results = array())
{
    $statement = $analyzed_sql_results['statement'];
    $matched_row_query = '';
    if ($statement instanceof SqlParser\Statements\DeleteStatement) {
        $matched_row_query = PMA_getSimulatedDeleteQuery($analyzed_sql_results);
    } elseif ($statement instanceof SqlParser\Statements\UpdateStatement) {
        $matched_row_query = PMA_getSimulatedUpdateQuery($analyzed_sql_results);
    }
    // Execute the query and get the number of matched rows.
    $matched_rows = PMA_executeMatchedRowQuery($matched_row_query);
    // URL to matched rows.
    $_url_params = array('db' => $GLOBALS['db'], 'sql_query' => $matched_row_query);
    $matched_rows_url = 'sql.php' . PMA_URL_getCommon($_url_params);
    return array('sql_query' => PMA\libraries\Util::formatSql($analyzed_sql_results['query']), 'matched_rows' => $matched_rows, 'matched_rows_url' => $matched_rows_url);
}