Expression.php 15 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
<?php

/**
 * Parses a reference to an expression (column, table or database name, function
 * call, mathematical expression, etc.).
 */

namespace PhpMyAdmin\SqlParser\Components;

use PhpMyAdmin\SqlParser\Component;
use PhpMyAdmin\SqlParser\Context;
use PhpMyAdmin\SqlParser\Parser;
use PhpMyAdmin\SqlParser\Token;
use PhpMyAdmin\SqlParser\TokensList;

/**
 * Parses a reference to an expression (column, table or database name, function
 * call, mathematical expression, etc.).
 *
 * @category   Components
 *
 * @license    https://www.gnu.org/licenses/gpl-2.0.txt GPL-2.0+
 */
class Expression extends Component
{
    /**
     * List of allowed reserved keywords in expressions.
     *
     * @var array
     */
    private static $ALLOWED_KEYWORDS = array(
        'AS' => 1,
        'DUAL' => 1,
        'NULL' => 1,
        'REGEXP' => 1,
        'CASE' => 1,
        'DIV' => 1,
        'AND' => 1,
        'OR' => 1,
        'XOR' => 1,
        'NOT' => 1,
        'MOD' => 1
    );

    /**
     * The name of this database.
     *
     * @var string
     */
    public $database;

    /**
     * The name of this table.
     *
     * @var string
     */
    public $table;

    /**
     * The name of the column.
     *
     * @var string
     */
    public $column;

    /**
     * The sub-expression.
     *
     * @var string
     */
    public $expr = '';

    /**
     * The alias of this expression.
     *
     * @var string
     */
    public $alias;

    /**
     * The name of the function.
     *
     * @var mixed
     */
    public $function;

    /**
     * The type of subquery.
     *
     * @var string
     */
    public $subquery;

    /**
     * Constructor.
     *
     * Syntax:
     *     new Expression('expr')
     *     new Expression('expr', 'alias')
     *     new Expression('database', 'table', 'column')
     *     new Expression('database', 'table', 'column', 'alias')
     *
     * If the database, table or column name is not required, pass an empty
     * string.
     *
     * @param string $database The name of the database or the the expression.
     *                         the the expression.
     * @param string $table    The name of the table or the alias of the expression.
     *                         the alias of the expression.
     * @param string $column   the name of the column
     * @param string $alias    the name of the alias
     */
    public function __construct($database = null, $table = null, $column = null, $alias = null)
    {
        if (($column === null) && ($alias === null)) {
            $this->expr = $database; // case 1
            $this->alias = $table; // case 2
        } else {
            $this->database = $database; // case 3
            $this->table = $table; // case 3
            $this->column = $column; // case 3
            $this->alias = $alias; // case 4
        }
    }

    /**
     * Possible options:.
     *
     *      `field`
     *
     *          First field to be filled.
     *          If this is not specified, it takes the value of `parseField`.
     *
     *      `parseField`
     *
     *          Specifies the type of the field parsed. It may be `database`,
     *          `table` or `column`. These expressions may not include
     *          parentheses.
     *
     *      `breakOnAlias`
     *
     *          If not empty, breaks when the alias occurs (it is not included).
     *
     *      `breakOnParentheses`
     *
     *          If not empty, breaks when the first parentheses occurs.
     *
     *      `parenthesesDelimited`
     *
     *          If not empty, breaks after last parentheses occurred.
     *
     * @param Parser     $parser  the parser that serves as context
     * @param TokensList $list    the list of tokens that are being parsed
     * @param array      $options parameters for parsing
     *
     * @return Expression|null
     * @throws \PhpMyAdmin\SqlParser\Exceptions\ParserException
     */
    public static function parse(Parser $parser, TokensList $list, array $options = array())
    {
        $ret = new self();

        /**
         * Whether current tokens make an expression or a table reference.
         *
         * @var bool
         */
        $isExpr = false;

        /**
         * Whether a period was previously found.
         *
         * @var bool
         */
        $dot = false;

        /**
         * Whether an alias is expected. Is 2 if `AS` keyword was found.
         *
         * @var bool
         */
        $alias = false;

        /**
         * Counts brackets.
         *
         * @var int
         */
        $brackets = 0;

        /**
         * Keeps track of the last two previous tokens.
         *
         * @var Token[]
         */
        $prev = array(
            null,
            null
        );

        // When a field is parsed, no parentheses are expected.
        if (! empty($options['parseField'])) {
            $options['breakOnParentheses'] = true;
            $options['field'] = $options['parseField'];
        }

        for (; $list->idx < $list->count; ++$list->idx) {
            /**
             * Token parsed at this moment.
             *
             * @var Token
             */
            $token = $list->tokens[$list->idx];

            // End of statement.
            if ($token->type === Token::TYPE_DELIMITER) {
                break;
            }

            // Skipping whitespaces and comments.
            if (($token->type === Token::TYPE_WHITESPACE)
                || ($token->type === Token::TYPE_COMMENT)
            ) {
                if ($isExpr) {
                    $ret->expr .= $token->token;
                }
                continue;
            }

            if ($token->type === Token::TYPE_KEYWORD) {
                if (($brackets > 0) && empty($ret->subquery)
                    && ! empty(Parser::$STATEMENT_PARSERS[$token->keyword])
                ) {
                    // A `(` was previously found and this keyword is the
                    // beginning of a statement, so this is a subquery.
                    $ret->subquery = $token->keyword;
                } elseif (($token->flags & Token::FLAG_KEYWORD_FUNCTION)
                    && (empty($options['parseField'])
                    && ! $alias)
                ) {
                    $isExpr = true;
                } elseif (($token->flags & Token::FLAG_KEYWORD_RESERVED)
                    && ($brackets === 0)
                ) {
                    if (empty(self::$ALLOWED_KEYWORDS[$token->keyword])) {
                        // A reserved keyword that is not allowed in the
                        // expression was found so the expression must have
                        // ended and a new clause is starting.
                        break;
                    }
                    if ($token->keyword === 'AS') {
                        if (! empty($options['breakOnAlias'])) {
                            break;
                        }
                        if ($alias) {
                            $parser->error(
                                'An alias was expected.',
                                $token
                            );
                            break;
                        }
                        $alias = true;
                        continue;
                    } elseif ($token->keyword === 'CASE') {
                        // For a use of CASE like
                        // 'SELECT a = CASE .... END, b=1, `id`, ... FROM ...'
                        $tempCaseExpr = CaseExpression::parse($parser, $list);
                        $ret->expr .= CaseExpression::build($tempCaseExpr);
                        $isExpr = true;
                        continue;
                    }
                    $isExpr = true;
                } elseif ($brackets === 0 && strlen($ret->expr) > 0 && ! $alias) {
                    /* End of expression */
                    break;
                }
            }

            if (($token->type === Token::TYPE_NUMBER)
                || ($token->type === Token::TYPE_BOOL)
                || (($token->type === Token::TYPE_SYMBOL)
                && ($token->flags & Token::FLAG_SYMBOL_VARIABLE))
                || (($token->type === Token::TYPE_SYMBOL)
                && ($token->flags & Token::FLAG_SYMBOL_PARAMETER))
                || (($token->type === Token::TYPE_OPERATOR)
                && ($token->value !== '.'))
            ) {
                if (! empty($options['parseField'])) {
                    break;
                }

                // Numbers, booleans and operators (except dot) are usually part
                // of expressions.
                $isExpr = true;
            }

            if ($token->type === Token::TYPE_OPERATOR) {
                if (! empty($options['breakOnParentheses'])
                    && (($token->value === '(') || ($token->value === ')'))
                ) {
                    // No brackets were expected.
                    break;
                }
                if ($token->value === '(') {
                    ++$brackets;
                    if (empty($ret->function) && ($prev[1] !== null)
                        && (($prev[1]->type === Token::TYPE_NONE)
                        || ($prev[1]->type === Token::TYPE_SYMBOL)
                        || (($prev[1]->type === Token::TYPE_KEYWORD)
                        && ($prev[1]->flags & Token::FLAG_KEYWORD_FUNCTION)))
                    ) {
                        $ret->function = $prev[1]->value;
                    }
                } elseif ($token->value === ')') {
                    if ($brackets === 0) {
                        // Not our bracket
                        break;
                    } else {
                        --$brackets;
                        if ($brackets === 0) {
                            if (! empty($options['parenthesesDelimited'])) {
                                // The current token is the last bracket, the next
                                // one will be outside the expression.
                                $ret->expr .= $token->token;
                                ++$list->idx;
                                break;
                            }
                        } elseif ($brackets < 0) {
                            // $parser->error('Unexpected closing bracket.', $token);
                            // $brackets = 0;
                            break;
                        }
                    }
                } elseif ($token->value === ',') {
                    // Expressions are comma-delimited.
                    if ($brackets === 0) {
                        break;
                    }
                }
            }

            // Saving the previous tokens.
            $prev[0] = $prev[1];
            $prev[1] = $token;

            if ($alias) {
                // An alias is expected (the keyword `AS` was previously found).
                if (! empty($ret->alias)) {
                    $parser->error('An alias was previously found.', $token);
                    break;
                }
                $ret->alias = $token->value;
                $alias = false;
            } elseif ($isExpr) {
                // Handling aliases.
                if (/* (empty($ret->alias)) && */ ($brackets === 0)
                    && (($prev[0] === null)
                    || ((($prev[0]->type !== Token::TYPE_OPERATOR)
                    || ($prev[0]->token === ')'))
                    && (($prev[0]->type !== Token::TYPE_KEYWORD)
                    || (! ($prev[0]->flags & Token::FLAG_KEYWORD_RESERVED)))))
                    && (($prev[1]->type === Token::TYPE_STRING)
                    || (($prev[1]->type === Token::TYPE_SYMBOL)
                    && (! ($prev[1]->flags & Token::FLAG_SYMBOL_VARIABLE)))
                    || ($prev[1]->type === Token::TYPE_NONE))
                ) {
                    if (! empty($ret->alias)) {
                        $parser->error('An alias was previously found.', $token);
                        break;
                    }
                    $ret->alias = $prev[1]->value;
                } else {
                    $ret->expr .= $token->token;
                }
            } elseif (! $isExpr) {
                if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '.')) {
                    // Found a `.` which means we expect a column name and
                    // the column name we parsed is actually the table name
                    // and the table name is actually a database name.
                    if (! empty($ret->database) || $dot) {
                        $parser->error('Unexpected dot.', $token);
                    }
                    $ret->database = $ret->table;
                    $ret->table = $ret->column;
                    $ret->column = null;
                    $dot = true;
                    $ret->expr .= $token->token;
                } else {
                    $field = empty($options['field']) ? 'column' : $options['field'];
                    if (empty($ret->$field)) {
                        $ret->$field = $token->value;
                        $ret->expr .= $token->token;
                        $dot = false;
                    } else {
                        // No alias is expected.
                        if (! empty($options['breakOnAlias'])) {
                            break;
                        }
                        if (! empty($ret->alias)) {
                            $parser->error('An alias was previously found.', $token);
                            break;
                        }
                        $ret->alias = $token->value;
                    }
                }
            }
        }

        if ($alias) {
            $parser->error(
                'An alias was expected.',
                $list->tokens[$list->idx - 1]
            );
        }

        // White-spaces might be added at the end.
        $ret->expr = trim($ret->expr);

        if ($ret->expr === '') {
            return null;
        }

        --$list->idx;

        return $ret;
    }

    /**
     * @param Expression|Expression[] $component the component to be built
     * @param array                   $options   parameters for building
     *
     * @return string
     */
    public static function build($component, array $options = array())
    {
        if (is_array($component)) {
            return implode(', ', $component);
        }

        if ($component->expr !== '' && ! is_null($component->expr)) {
            $ret = $component->expr;
        } else {
            $fields = array();
            if (isset($component->database) && ($component->database !== '')) {
                $fields[] = $component->database;
            }
            if (isset($component->table) && ($component->table !== '')) {
                $fields[] = $component->table;
            }
            if (isset($component->column) && ($component->column !== '')) {
                $fields[] = $component->column;
            }
            $ret = implode('.', Context::escape($fields));
        }

        if (! empty($component->alias)) {
            $ret .= ' AS ' . Context::escape($component->alias);
        }

        return $ret;
    }
}