Remove embedded libraries

- phpseclib
- sql-parser
- tcpdf

These are now loaded by composer.

Signed-off-by: Michal Čihař <michal@cihar.com>
This commit is contained in:
Michal Čihař 2016-02-17 14:46:16 +01:00
parent 5a58f81776
commit cc481fecb4
95 changed files with 0 additions and 68135 deletions

View File

@ -1,131 +0,0 @@
<?php
/**
* Pure-PHP implementation of AES.
*
* Uses mcrypt, if available/possible, and an internal implementation, otherwise.
*
* PHP version 5
*
* NOTE: Since AES.php is (for compatibility and phpseclib-historical reasons) virtually
* just a wrapper to Rijndael.php you may consider using Rijndael.php instead of
* to save one include_once().
*
* If {@link self::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
* {@link self::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits
* it'll be null-padded to 192-bits and 192 bits will be the key length until {@link self::setKey() setKey()}
* is called, again, at which point, it'll be recalculated.
*
* Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, some functions are available to be called that, in the context of AES, don't
* make a whole lot of sense. {@link self::setBlockLength() setBlockLength()}, for instance. Calling that function,
* however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* $aes = new \phpseclib\Crypt\AES();
*
* $aes->setKey('abcdefghijklmnop');
*
* $size = 10 * 1024;
* $plaintext = '';
* for ($i = 0; $i < $size; $i++) {
* $plaintext.= 'a';
* }
*
* echo $aes->decrypt($aes->encrypt($plaintext));
* ?>
* </code>
*
* @category Crypt
* @package AES
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2008 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\Crypt;
if (! defined('PHPMYADMIN')) {
exit;
}
use phpseclib\Crypt\Rijndael;
/**
* Pure-PHP implementation of AES.
*
* @package AES
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class AES extends Rijndael
{
/**
* Dummy function
*
* Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, this function is, technically, available, but it doesn't do anything.
*
* @see \phpseclib\Crypt\Rijndael::setBlockLength()
* @access public
* @param int $length
*/
function setBlockLength($length)
{
return;
}
/**
* Sets the key length
*
* Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to
* 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
*
* @see \phpseclib\Crypt\Rijndael:setKeyLength()
* @access public
* @param int $length
*/
function setKeyLength($length)
{
switch ($length) {
case 160:
$length = 192;
break;
case 224:
$length = 256;
}
parent::setKeyLength($length);
}
/**
* Sets the key.
*
* Rijndael supports five different key lengths, AES only supports three.
*
* @see \phpseclib\Crypt\Rijndael:setKey()
* @see setKeyLength()
* @access public
* @param string $key
*/
function setKey($key)
{
parent::setKey($key);
if (!$this->explicit_key_length) {
$length = strlen($key);
switch (true) {
case $length <= 16:
$this->key_length = 16;
break;
case $length <= 24:
$this->key_length = 24;
break;
default:
$this->key_length = 32;
}
$this->_setEngine();
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,243 +0,0 @@
<?php
/**
* Random Number Generator
*
* PHP version 5
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* echo bin2hex(\phpseclib\Crypt\Random::string(8));
* ?>
* </code>
*
* @category Crypt
* @package Random
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\Crypt;
use phpseclib\Crypt\AES;
use phpseclib\Crypt\Base;
use phpseclib\Crypt\Blowfish;
use phpseclib\Crypt\DES;
use phpseclib\Crypt\RC4;
use phpseclib\Crypt\TripleDES;
use phpseclib\Crypt\Twofish;
/**
* Pure-PHP Random Number Generator
*
* @package Random
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class Random
{
/**
* Generate a random string.
*
* Although microoptimizations are generally discouraged as they impair readability this function is ripe with
* microoptimizations because this function has the potential of being called a huge number of times.
* eg. for RSA key generation.
*
* @param int $length
* @return string
*/
static function string($length)
{
if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
try {
return \random_bytes($length);
} catch (\Throwable $e) {
// If a sufficient source of randomness is unavailable, random_bytes() will throw an
// object that implements the Throwable interface (Exception, TypeError, Error).
// We don't actually need to do anything here. The string() method should just continue
// as normal. Note, however, that if we don't have a sufficient source of randomness for
// random_bytes(), most of the other calls here will fail too, so we'll end up using
// the PHP implementation.
}
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
// ie. class_alias is a function that was introduced in PHP 5.3
if (extension_loaded('mcrypt') && function_exists('class_alias')) {
return mcrypt_create_iv($length);
}
// method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
// to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
// openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
// call php_win32_get_random_bytes():
//
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
//
// php_win32_get_random_bytes() is defined thusly:
//
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
//
// we're calling it, all the same, in the off chance that the mcrypt extension is not available
if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
return openssl_random_pseudo_bytes($length);
}
} else {
// method 1. the fastest
if (extension_loaded('openssl')) {
return openssl_random_pseudo_bytes($length);
}
// method 2
static $fp = true;
if ($fp === true) {
// warning's will be output unles the error suppression operator is used. errors such as
// "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
$fp = @fopen('/dev/urandom', 'rb');
}
if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
return fread($fp, $length);
}
// method 3. pretty much does the same thing as method 2 per the following url:
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
// surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
// not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
// restrictions or some such
if (extension_loaded('mcrypt')) {
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}
}
// at this point we have no choice but to use a pure-PHP CSPRNG
// cascade entropy across multiple PHP instances by fixing the session and collecting all
// environmental variables, including the previous session data and the current session
// data.
//
// mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
// easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
// PHP isn't low level to be able to use those as sources and on a web server there's not likely
// going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
// however, a ton of people visiting the website. obviously you don't want to base your seeding
// soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
// by the user and (2) this isn't just looking at the data sent by the current user - it's based
// on the data sent by all users. one user requests the page and a hash of their info is saved.
// another user visits the page and the serialization of their data is utilized along with the
// server envirnment stuff and a hash of the previous http request data (which itself utilizes
// a hash of the session data before that). certainly an attacker should be assumed to have
// full control over his own http requests. he, however, is not going to have control over
// everyone's http requests.
static $crypto = false, $v;
if ($crypto === false) {
// save old session data
$old_session_id = session_id();
$old_use_cookies = ini_get('session.use_cookies');
$old_session_cache_limiter = session_cache_limiter();
$_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
if ($old_session_id != '') {
session_write_close();
}
session_id(1);
ini_set('session.use_cookies', 0);
session_cache_limiter('');
session_start();
$v = $seed = $_SESSION['seed'] = pack('H*', sha1(
serialize($_SERVER) .
serialize($_POST) .
serialize($_GET) .
serialize($_COOKIE) .
serialize($GLOBALS) .
serialize($_SESSION) .
serialize($_OLD_SESSION)
));
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
}
$_SESSION['count']++;
session_write_close();
// restore old session data
if ($old_session_id != '') {
session_id($old_session_id);
session_start();
ini_set('session.use_cookies', $old_use_cookies);
session_cache_limiter($old_session_cache_limiter);
} else {
if ($_OLD_SESSION !== false) {
$_SESSION = $_OLD_SESSION;
unset($_OLD_SESSION);
} else {
unset($_SESSION);
}
}
// in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
// the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
// if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
// original hash and the current hash. we'll be emulating that. for more info see the following URL:
//
// http://tools.ietf.org/html/rfc4253#section-7.2
//
// see the is_string($crypto) part for an example of how to expand the keys
$key = pack('H*', sha1($seed . 'A'));
$iv = pack('H*', sha1($seed . 'C'));
// ciphers are used as per the nist.gov link below. also, see this link:
//
// http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
switch (true) {
case class_exists('\phpseclib\Crypt\AES'):
$crypto = new AES(Base::MODE_CTR);
break;
case class_exists('\phpseclib\Crypt\Twofish'):
$crypto = new Twofish(Base::MODE_CTR);
break;
case class_exists('\phpseclib\Crypt\Blowfish'):
$crypto = new Blowfish(Base::MODE_CTR);
break;
case class_exists('\phpseclib\Crypt\TripleDES'):
$crypto = new TripleDES(Base::MODE_CTR);
break;
case class_exists('\phpseclib\Crypt\DES'):
$crypto = new DES(Base::MODE_CTR);
break;
case class_exists('\phpseclib\Crypt\RC4'):
$crypto = new RC4();
break;
default:
user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
return false;
}
$crypto->setKey($key);
$crypto->setIV($iv);
$crypto->enableContinuousBuffer();
}
//return $crypto->encrypt(str_repeat("\0", $length));
// the following is based off of ANSI X9.31:
//
// http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
//
// OpenSSL uses that same standard for it's random numbers:
//
// http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
// (do a search for "ANS X9.31 A.2.4")
$result = '';
while (strlen($result) < $length) {
$i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
$r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
$v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
$result.= $r;
}
return substr($result, 0, $length);
}
}

View File

@ -1,941 +0,0 @@
<?php
/**
* Pure-PHP implementation of Rijndael.
*
* Uses mcrypt, if available/possible, and an internal implementation, otherwise.
*
* PHP version 5
*
* If {@link self::setBlockLength() setBlockLength()} isn't called, it'll be assumed to be 128 bits. If
* {@link self::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
* {@link self::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's
* 136-bits it'll be null-padded to 192-bits and 192 bits will be the key length until
* {@link self::setKey() setKey()} is called, again, at which point, it'll be recalculated.
*
* Not all Rijndael implementations may support 160-bits or 224-bits as the block length / key length. mcrypt, for example,
* does not. AES, itself, only supports block lengths of 128 and key lengths of 128, 192, and 256.
* {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=10 Rijndael-ammended.pdf#page=10} defines the
* algorithm for block lengths of 192 and 256 but not for block lengths / key lengths of 160 and 224. Indeed, 160 and 224
* are first defined as valid key / block lengths in
* {@link http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=44 Rijndael-ammended.pdf#page=44}:
* Extensions: Other block and Cipher Key lengths.
* Note: Use of 160/224-bit Keys must be explicitly set by setKeyLength(160) respectively setKeyLength(224).
*
* {@internal The variable names are the same as those in
* {@link http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf#page=10 fips-197.pdf#page=10}.}}
*
* Here's a short example of how to use this library:
* <code>
* <?php
* include 'vendor/autoload.php';
*
* $rijndael = new \phpseclib\Crypt\Rijndael();
*
* $rijndael->setKey('abcdefghijklmnop');
*
* $size = 10 * 1024;
* $plaintext = '';
* for ($i = 0; $i < $size; $i++) {
* $plaintext.= 'a';
* }
*
* echo $rijndael->decrypt($rijndael->encrypt($plaintext));
* ?>
* </code>
*
* @category Crypt
* @package Rijndael
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2008 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\Crypt;
if (! defined('PHPMYADMIN')) {
exit;
}
use phpseclib\Crypt\Base;
/**
* Pure-PHP implementation of Rijndael.
*
* @package Rijndael
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class Rijndael extends Base
{
/**
* The mcrypt specific name of the cipher
*
* Mcrypt is useable for 128/192/256-bit $block_size/$key_length. For 160/224 not.
* \phpseclib\Crypt\Rijndael determines automatically whether mcrypt is useable
* or not for the current $block_size/$key_length.
* In case of, $cipher_name_mcrypt will be set dynamically at run time accordingly.
*
* @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @see \phpseclib\Crypt\Base::engine
* @see self::isValidEngine()
* @var string
* @access private
*/
var $cipher_name_mcrypt = 'rijndael-128';
/**
* The default salt used by setPassword()
*
* @see \phpseclib\Crypt\Base::password_default_salt
* @see \phpseclib\Crypt\Base::setPassword()
* @var string
* @access private
*/
var $password_default_salt = 'phpseclib';
/**
* The Key Schedule
*
* @see self::_setup()
* @var array
* @access private
*/
var $w;
/**
* The Inverse Key Schedule
*
* @see self::_setup()
* @var array
* @access private
*/
var $dw;
/**
* The Block Length divided by 32
*
* @see self::setBlockLength()
* @var int
* @access private
* @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size
* because the encryption / decryption / key schedule creation requires this number and not $block_size. We could
* derive this from $block_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
* of that, we'll just precompute it once.
*/
var $Nb = 4;
/**
* The Key Length (in bytes)
*
* @see self::setKeyLength()
* @var int
* @access private
* @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk
* because the encryption / decryption / key schedule creation requires this number and not $key_length. We could
* derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
* of that, we'll just precompute it once.
*/
var $key_length = 16;
/**
* The Key Length divided by 32
*
* @see self::setKeyLength()
* @var int
* @access private
* @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4
*/
var $Nk = 4;
/**
* The Number of Rounds
*
* @var int
* @access private
* @internal The max value is 14, the min value is 10.
*/
var $Nr;
/**
* Shift offsets
*
* @var array
* @access private
*/
var $c;
/**
* Holds the last used key- and block_size information
*
* @var array
* @access private
*/
var $kl;
/**
* Sets the key length.
*
* Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
* 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
*
* Note: phpseclib extends Rijndael (and AES) for using 160- and 224-bit keys but they are officially not defined
* and the most (if not all) implementations are not able using 160/224-bit keys but round/pad them up to
* 192/256 bits as, for example, mcrypt will do.
*
* That said, if you want be compatible with other Rijndael and AES implementations,
* you should not setKeyLength(160) or setKeyLength(224).
*
* Additional: In case of 160- and 224-bit keys, phpseclib will/can, for that reason, not use
* the mcrypt php extension, even if available.
* This results then in slower encryption.
*
* @access public
* @param int $length
*/
function setKeyLength($length)
{
switch (true) {
case $length <= 128:
$this->key_length = 16;
break;
case $length <= 160:
$this->key_length = 20;
break;
case $length <= 192:
$this->key_length = 24;
break;
case $length <= 224:
$this->key_length = 28;
break;
default:
$this->key_length = 32;
}
parent::setKeyLength($length);
}
/**
* Sets the block length
*
* Valid block lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to
* 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
*
* @access public
* @param int $length
*/
function setBlockLength($length)
{
$length >>= 5;
if ($length > 8) {
$length = 8;
} elseif ($length < 4) {
$length = 4;
}
$this->Nb = $length;
$this->block_size = $length << 2;
$this->changed = true;
$this->_setEngine();
}
/**
* Test for engine validity
*
* This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
*
* @see \phpseclib\Crypt\Base::__construct()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
switch ($engine) {
case self::ENGINE_OPENSSL:
if ($this->block_size != 16) {
return false;
}
$this->cipher_name_openssl_ecb = 'aes-' . ($this->key_length << 3) . '-ecb';
$this->cipher_name_openssl = 'aes-' . ($this->key_length << 3) . '-' . $this->_openssl_translate_mode();
break;
case self::ENGINE_MCRYPT:
$this->cipher_name_mcrypt = 'rijndael-' . ($this->block_size << 3);
if ($this->key_length % 8) { // is it a 160/224-bit key?
// mcrypt is not usable for them, only for 128/192/256-bit keys
return false;
}
}
return parent::isValidEngine($engine);
}
/**
* Encrypts a block
*
* @access private
* @param string $in
* @return string
*/
function _encryptBlock($in)
{
static $tables;
if (empty($tables)) {
$tables = &$this->_getTables();
}
$t0 = $tables[0];
$t1 = $tables[1];
$t2 = $tables[2];
$t3 = $tables[3];
$sbox = $tables[4];
$state = array();
$words = unpack('N*', $in);
$c = $this->c;
$w = $this->w;
$Nb = $this->Nb;
$Nr = $this->Nr;
// addRoundKey
$wc = $Nb - 1;
foreach ($words as $word) {
$state[] = $word ^ $w[++$wc];
}
// fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components -
// subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding
// Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf.
// Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization.
// Unfortunately, the description given there is not quite correct. Per aes.spec.v316.pdf#page=19 [1],
// equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well.
// [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf
$temp = array();
for ($round = 1; $round < $Nr; ++$round) {
$i = 0; // $c[0] == 0
$j = $c[1];
$k = $c[2];
$l = $c[3];
while ($i < $Nb) {
$temp[$i] = $t0[$state[$i] >> 24 & 0x000000FF] ^
$t1[$state[$j] >> 16 & 0x000000FF] ^
$t2[$state[$k] >> 8 & 0x000000FF] ^
$t3[$state[$l] & 0x000000FF] ^
$w[++$wc];
++$i;
$j = ($j + 1) % $Nb;
$k = ($k + 1) % $Nb;
$l = ($l + 1) % $Nb;
}
$state = $temp;
}
// subWord
for ($i = 0; $i < $Nb; ++$i) {
$state[$i] = $sbox[$state[$i] & 0x000000FF] |
($sbox[$state[$i] >> 8 & 0x000000FF] << 8) |
($sbox[$state[$i] >> 16 & 0x000000FF] << 16) |
($sbox[$state[$i] >> 24 & 0x000000FF] << 24);
}
// shiftRows + addRoundKey
$i = 0; // $c[0] == 0
$j = $c[1];
$k = $c[2];
$l = $c[3];
while ($i < $Nb) {
$temp[$i] = ($state[$i] & 0xFF000000) ^
($state[$j] & 0x00FF0000) ^
($state[$k] & 0x0000FF00) ^
($state[$l] & 0x000000FF) ^
$w[$i];
++$i;
$j = ($j + 1) % $Nb;
$k = ($k + 1) % $Nb;
$l = ($l + 1) % $Nb;
}
switch ($Nb) {
case 8:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
case 7:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
case 6:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
case 5:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
default:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
}
}
/**
* Decrypts a block
*
* @access private
* @param string $in
* @return string
*/
function _decryptBlock($in)
{
static $invtables;
if (empty($invtables)) {
$invtables = &$this->_getInvTables();
}
$dt0 = $invtables[0];
$dt1 = $invtables[1];
$dt2 = $invtables[2];
$dt3 = $invtables[3];
$isbox = $invtables[4];
$state = array();
$words = unpack('N*', $in);
$c = $this->c;
$dw = $this->dw;
$Nb = $this->Nb;
$Nr = $this->Nr;
// addRoundKey
$wc = $Nb - 1;
foreach ($words as $word) {
$state[] = $word ^ $dw[++$wc];
}
$temp = array();
for ($round = $Nr - 1; $round > 0; --$round) {
$i = 0; // $c[0] == 0
$j = $Nb - $c[1];
$k = $Nb - $c[2];
$l = $Nb - $c[3];
while ($i < $Nb) {
$temp[$i] = $dt0[$state[$i] >> 24 & 0x000000FF] ^
$dt1[$state[$j] >> 16 & 0x000000FF] ^
$dt2[$state[$k] >> 8 & 0x000000FF] ^
$dt3[$state[$l] & 0x000000FF] ^
$dw[++$wc];
++$i;
$j = ($j + 1) % $Nb;
$k = ($k + 1) % $Nb;
$l = ($l + 1) % $Nb;
}
$state = $temp;
}
// invShiftRows + invSubWord + addRoundKey
$i = 0; // $c[0] == 0
$j = $Nb - $c[1];
$k = $Nb - $c[2];
$l = $Nb - $c[3];
while ($i < $Nb) {
$word = ($state[$i] & 0xFF000000) |
($state[$j] & 0x00FF0000) |
($state[$k] & 0x0000FF00) |
($state[$l] & 0x000000FF);
$temp[$i] = $dw[$i] ^ ($isbox[$word & 0x000000FF] |
($isbox[$word >> 8 & 0x000000FF] << 8) |
($isbox[$word >> 16 & 0x000000FF] << 16) |
($isbox[$word >> 24 & 0x000000FF] << 24));
++$i;
$j = ($j + 1) % $Nb;
$k = ($k + 1) % $Nb;
$l = ($l + 1) % $Nb;
}
switch ($Nb) {
case 8:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]);
case 7:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]);
case 6:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]);
case 5:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]);
default:
return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]);
}
}
/**
* Setup the key (expansion)
*
* @see \phpseclib\Crypt\Base::_setupKey()
* @access private
*/
function _setupKey()
{
// Each number in $rcon is equal to the previous number multiplied by two in Rijndael's finite field.
// See http://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplicative_inverse
static $rcon = array(0,
0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000,
0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000,
0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000,
0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000,
0x97000000, 0x35000000, 0x6A000000, 0xD4000000, 0xB3000000,
0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000
);
if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_length === $this->kl['key_length'] && $this->block_size === $this->kl['block_size']) {
// already expanded
return;
}
$this->kl = array('key' => $this->key, 'key_length' => $this->key_length, 'block_size' => $this->block_size);
$this->Nk = $this->key_length >> 2;
// see Rijndael-ammended.pdf#page=44
$this->Nr = max($this->Nk, $this->Nb) + 6;
// shift offsets for Nb = 5, 7 are defined in Rijndael-ammended.pdf#page=44,
// "Table 8: Shift offsets in Shiftrow for the alternative block lengths"
// shift offsets for Nb = 4, 6, 8 are defined in Rijndael-ammended.pdf#page=14,
// "Table 2: Shift offsets for different block lengths"
switch ($this->Nb) {
case 4:
case 5:
case 6:
$this->c = array(0, 1, 2, 3);
break;
case 7:
$this->c = array(0, 1, 2, 4);
break;
case 8:
$this->c = array(0, 1, 3, 4);
}
$w = array_values(unpack('N*words', $this->key));
$length = $this->Nb * ($this->Nr + 1);
for ($i = $this->Nk; $i < $length; $i++) {
$temp = $w[$i - 1];
if ($i % $this->Nk == 0) {
// according to <http://php.net/language.types.integer>, "the size of an integer is platform-dependent".
// on a 32-bit machine, it's 32-bits, and on a 64-bit machine, it's 64-bits. on a 32-bit machine,
// 0xFFFFFFFF << 8 == 0xFFFFFF00, but on a 64-bit machine, it equals 0xFFFFFFFF00. as such, doing 'and'
// with 0xFFFFFFFF (or 0xFFFFFF00) on a 32-bit machine is unnecessary, but on a 64-bit machine, it is.
$temp = (($temp << 8) & 0xFFFFFF00) | (($temp >> 24) & 0x000000FF); // rotWord
$temp = $this->_subWord($temp) ^ $rcon[$i / $this->Nk];
} elseif ($this->Nk > 6 && $i % $this->Nk == 4) {
$temp = $this->_subWord($temp);
}
$w[$i] = $w[$i - $this->Nk] ^ $temp;
}
// convert the key schedule from a vector of $Nb * ($Nr + 1) length to a matrix with $Nr + 1 rows and $Nb columns
// and generate the inverse key schedule. more specifically,
// according to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=23> (section 5.3.3),
// "The key expansion for the Inverse Cipher is defined as follows:
// 1. Apply the Key Expansion.
// 2. Apply InvMixColumn to all Round Keys except the first and the last one."
// also, see fips-197.pdf#page=27, "5.3.5 Equivalent Inverse Cipher"
list($dt0, $dt1, $dt2, $dt3) = $this->_getInvTables();
$temp = $this->w = $this->dw = array();
for ($i = $row = $col = 0; $i < $length; $i++, $col++) {
if ($col == $this->Nb) {
if ($row == 0) {
$this->dw[0] = $this->w[0];
} else {
// subWord + invMixColumn + invSubWord = invMixColumn
$j = 0;
while ($j < $this->Nb) {
$dw = $this->_subWord($this->w[$row][$j]);
$temp[$j] = $dt0[$dw >> 24 & 0x000000FF] ^
$dt1[$dw >> 16 & 0x000000FF] ^
$dt2[$dw >> 8 & 0x000000FF] ^
$dt3[$dw & 0x000000FF];
$j++;
}
$this->dw[$row] = $temp;
}
$col = 0;
$row++;
}
$this->w[$row][$col] = $w[$i];
}
$this->dw[$row] = $this->w[$row];
// Converting to 1-dim key arrays (both ascending)
$this->dw = array_reverse($this->dw);
$w = array_pop($this->w);
$dw = array_pop($this->dw);
foreach ($this->w as $r => $wr) {
foreach ($wr as $c => $wc) {
$w[] = $wc;
$dw[] = $this->dw[$r][$c];
}
}
$this->w = $w;
$this->dw = $dw;
}
/**
* Performs S-Box substitutions
*
* @access private
* @param int $word
*/
function _subWord($word)
{
static $sbox;
if (empty($sbox)) {
list(, , , , $sbox) = $this->_getTables();
}
return $sbox[$word & 0x000000FF] |
($sbox[$word >> 8 & 0x000000FF] << 8) |
($sbox[$word >> 16 & 0x000000FF] << 16) |
($sbox[$word >> 24 & 0x000000FF] << 24);
}
/**
* Provides the mixColumns and sboxes tables
*
* @see self::_encryptBlock()
* @see self::_setupInlineCrypt()
* @see self::_subWord()
* @access private
* @return array &$tables
*/
function &_getTables()
{
static $tables;
if (empty($tables)) {
// according to <http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf#page=19> (section 5.2.1),
// precomputed tables can be used in the mixColumns phase. in that example, they're assigned t0...t3, so
// those are the names we'll use.
$t3 = array_map('intval', array(
// with array_map('intval', ...) we ensure we have only int's and not
// some slower floats converted by php automatically on high values
0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491,
0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC,
0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB,
0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B,
0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83,
0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A,
0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F,
0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA,
0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B,
0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713,
0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6,
0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85,
0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411,
0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B,
0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1,
0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF,
0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E,
0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6,
0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B,
0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD,
0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8,
0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2,
0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049,
0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810,
0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197,
0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F,
0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C,
0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927,
0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733,
0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5,
0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0,
0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C
));
foreach ($t3 as $t3i) {
$t0[] = (($t3i << 24) & 0xFF000000) | (($t3i >> 8) & 0x00FFFFFF);
$t1[] = (($t3i << 16) & 0xFFFF0000) | (($t3i >> 16) & 0x0000FFFF);
$t2[] = (($t3i << 8) & 0xFFFFFF00) | (($t3i >> 24) & 0x000000FF);
}
$tables = array(
// The Precomputed mixColumns tables t0 - t3
$t0,
$t1,
$t2,
$t3,
// The SubByte S-Box
array(
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
)
);
}
return $tables;
}
/**
* Provides the inverse mixColumns and inverse sboxes tables
*
* @see self::_decryptBlock()
* @see self::_setupInlineCrypt()
* @see self::_setupKey()
* @access private
* @return array &$tables
*/
function &_getInvTables()
{
static $tables;
if (empty($tables)) {
$dt3 = array_map('intval', array(
0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B,
0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5,
0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B,
0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E,
0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D,
0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9,
0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66,
0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED,
0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4,
0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD,
0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60,
0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79,
0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C,
0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24,
0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C,
0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814,
0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B,
0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084,
0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077,
0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22,
0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F,
0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582,
0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB,
0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF,
0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035,
0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17,
0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46,
0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D,
0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A,
0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678,
0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF,
0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0
));
foreach ($dt3 as $dt3i) {
$dt0[] = (($dt3i << 24) & 0xFF000000) | (($dt3i >> 8) & 0x00FFFFFF);
$dt1[] = (($dt3i << 16) & 0xFFFF0000) | (($dt3i >> 16) & 0x0000FFFF);
$dt2[] = (($dt3i << 8) & 0xFFFFFF00) | (($dt3i >> 24) & 0x000000FF);
};
$tables = array(
// The Precomputed inverse mixColumns tables dt0 - dt3
$dt0,
$dt1,
$dt2,
$dt3,
// The inverse SubByte S-Box
array(
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
)
);
}
return $tables;
}
/**
* Setup the performance-optimized function for de/encrypt()
*
* @see \phpseclib\Crypt\Base::_setupInlineCrypt()
* @access private
*/
function _setupInlineCrypt()
{
// Note: _setupInlineCrypt() will be called only if $this->changed === true
// So here we are'nt under the same heavy timing-stress as we are in _de/encryptBlock() or de/encrypt().
// However...the here generated function- $code, stored as php callback in $this->inline_crypt, must work as fast as even possible.
$lambda_functions =& self::_getLambdaFunctions();
// We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
// (Currently, for Crypt_Rijndael/AES, one generated $lambda_function cost on php5.5@32bit ~80kb unfreeable mem and ~130kb on php5.5@64bit)
// After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one.
$gen_hi_opt_code = (bool)(count($lambda_functions) < 10);
// Generation of a uniqe hash for our generated code
$code_hash = "Crypt_Rijndael, {$this->mode}, {$this->Nr}, {$this->Nb}";
if ($gen_hi_opt_code) {
$code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
}
if (!isset($lambda_functions[$code_hash])) {
switch (true) {
case $gen_hi_opt_code:
// The hi-optimized $lambda_functions will use the key-words hardcoded for better performance.
$w = $this->w;
$dw = $this->dw;
$init_encrypt = '';
$init_decrypt = '';
break;
default:
for ($i = 0, $cw = count($this->w); $i < $cw; ++$i) {
$w[] = '$w[' . $i . ']';
$dw[] = '$dw[' . $i . ']';
}
$init_encrypt = '$w = $self->w;';
$init_decrypt = '$dw = $self->dw;';
}
$Nr = $this->Nr;
$Nb = $this->Nb;
$c = $this->c;
// Generating encrypt code:
$init_encrypt.= '
static $tables;
if (empty($tables)) {
$tables = &$self->_getTables();
}
$t0 = $tables[0];
$t1 = $tables[1];
$t2 = $tables[2];
$t3 = $tables[3];
$sbox = $tables[4];
';
$s = 'e';
$e = 's';
$wc = $Nb - 1;
// Preround: addRoundKey
$encrypt_block = '$in = unpack("N*", $in);'."\n";
for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n";
}
// Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
for ($round = 1; $round < $Nr; ++$round) {
list($s, $e) = array($e, $s);
for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.=
'$'.$e.$i.' =
$t0[($'.$s.$i .' >> 24) & 0xff] ^
$t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^
$t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^
$t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^
'.$w[++$wc].";\n";
}
}
// Finalround: subWord + shiftRows + addRoundKey
for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.=
'$'.$e.$i.' =
$sbox[ $'.$e.$i.' & 0xff] |
($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
}
$encrypt_block .= '$in = pack("N*"'."\n";
for ($i = 0; $i < $Nb; ++$i) {
$encrypt_block.= ',
($'.$e.$i .' & '.((int)0xFF000000).') ^
($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000 ) ^
($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00 ) ^
($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF ) ^
'.$w[$i]."\n";
}
$encrypt_block .= ');';
// Generating decrypt code:
$init_decrypt.= '
static $invtables;
if (empty($invtables)) {
$invtables = &$self->_getInvTables();
}
$dt0 = $invtables[0];
$dt1 = $invtables[1];
$dt2 = $invtables[2];
$dt3 = $invtables[3];
$isbox = $invtables[4];
';
$s = 'e';
$e = 's';
$wc = $Nb - 1;
// Preround: addRoundKey
$decrypt_block = '$in = unpack("N*", $in);'."\n";
for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n";
}
// Mainrounds: shiftRows + subWord + mixColumns + addRoundKey
for ($round = 1; $round < $Nr; ++$round) {
list($s, $e) = array($e, $s);
for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.=
'$'.$e.$i.' =
$dt0[($'.$s.$i .' >> 24) & 0xff] ^
$dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^
$dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^
$dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^
'.$dw[++$wc].";\n";
}
}
// Finalround: subWord + shiftRows + addRoundKey
for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.=
'$'.$e.$i.' =
$isbox[ $'.$e.$i.' & 0xff] |
($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) |
($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) |
($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n";
}
$decrypt_block .= '$in = pack("N*"'."\n";
for ($i = 0; $i < $Nb; ++$i) {
$decrypt_block.= ',
($'.$e.$i. ' & '.((int)0xFF000000).') ^
($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000 ) ^
($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00 ) ^
($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF ) ^
'.$dw[$i]."\n";
}
$decrypt_block .= ');';
$lambda_functions[$code_hash] = $this->_createInlineCryptFunction(
array(
'init_crypt' => '',
'init_encrypt' => $init_encrypt,
'init_decrypt' => $init_decrypt,
'encrypt_block' => $encrypt_block,
'decrypt_block' => $decrypt_block
)
);
}
$this->inline_crypt = $lambda_functions[$code_hash];
}
}

View File

@ -1,21 +0,0 @@
Copyright 2007-2013 TerraFrost and other contributors
http://phpseclib.sourceforge.net/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,250 +0,0 @@
<?php
/**
* This file is based on Composer's autoloader.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* @package SqlParser
* @subpackage Autoload
*/
namespace SqlParser\Autoload;
/**
* ClassLoader implements a PSR-4 class loader,
*
* This class is loosely based on the Symfony UniversalClassLoader.
* This class is a stripped version of Composer's ClassLoader.
*
* @package SqlParser
* @subpackage Autoload
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassLoader
{
public $prefixLengths = array();
public $prefixDirs = array();
public $fallbackDirs = array();
public $classMap = array();
public $classMapAuthoritative = false;
/**
* @param array $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if (!empty($this->classMap)) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-0 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirs = array_merge(
(array) $paths,
$this->fallbackDirs
);
} else {
$this->fallbackDirs = array_merge(
$this->fallbackDirs,
(array) $paths
);
}
} elseif (!isset($this->prefixDirs[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengths[$prefix[0]][$prefix] = $length;
$this->prefixDirs[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirs[$prefix] = array_merge(
(array) $paths,
$this->prefixDirs[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirs[$prefix] = array_merge(
$this->prefixDirs[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirs = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengths[$prefix[0]][$prefix] = $length;
$this->prefixDirs[$prefix] = (array) $paths;
}
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
*
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
if ('\\' == $class[0]) {
$class = substr($class, 1);
}
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative) {
return false;
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if ($file === null && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if ($file === null) {
// Remember that this class does not exist.
return $this->classMap[$class] = false;
}
return $file;
}
/**
* Finds a file that defines the specified class and has the specified
* extension.
*
* @param string $class The name of the class
* @param string $ext The extension of the file
*
* @return string|false The path if found, false otherwise
*/
public function findFileWithExtension($class, $ext)
{
$logicalPath = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengths[$first])) {
foreach ($this->prefixLengths[$first] as $prefix => $length) {
if (0 === strpos($class, $prefix)) {
foreach ($this->prefixDirs[$prefix] as $dir) {
if (is_file($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPath, $length))) {
return $file;
}
}
}
}
}
foreach ($this->fallbackDirs as $dir) {
if (is_file($file = $dir . DIRECTORY_SEPARATOR . $logicalPath)) {
return $file;
}
}
return false;
}
}
if (!function_exists('SqlParser\\Autoload\\includeFile')) {
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file The name of the file
*
* @return void
*/
function includeFile($file)
{
include $file;
}
}

View File

@ -1,77 +0,0 @@
<?php
/**
* The autoloader used for loading sql-parser's components.
*
* This file is based on Composer's autoloader.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* @package SqlParser
* @subpackage Autoload
*/
namespace SqlParser\Autoload;
if (!class_exists('SqlParser\\Autoload\\ClassLoader')) {
if (! file_exists('./libraries/sql-parser/ClassLoader.php')) {
die('Invalid invocation');
}
include_once './libraries/sql-parser/ClassLoader.php';
}
use SqlParser\Autoload\ClassLoader;
/**
* Initializes the autoloader.
*
* @package SqlParser
* @subpackage Autoload
*/
class AutoloaderInit
{
/**
* The loader instance.
*
* @var ClassLoader
*/
public static $loader;
/**
* Constructs and returns the class loader.
*
* @param array $map Array containing path to each namespace.
*
* @return ClassLoader
*/
public static function getLoader(array $map)
{
if (null !== self::$loader) {
return self::$loader;
}
self::$loader = $loader = new ClassLoader();
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$loader->register(true);
return $loader;
}
}
// php-gettext is used to translate error messages.
// This must be included before any class of the parser is loaded because
// if there is no `__` function defined, the library defines a dummy one
// in `common.php`.
require_once './libraries/php-gettext/gettext.inc';
// Initializing the autoloader.
return AutoloaderInit::getLoader(
array(
'SqlParser\\' => array(dirname(__FILE__) . '/src'),
)
);

View File

@ -1,82 +0,0 @@
<?php
/**
* Defines a component that is later extended to parse specialized components or
* keywords.
*
* There is a small difference between *Component and *Keyword classes: usually,
* *Component parsers can be reused in multiple situations and *Keyword parsers
* count on the *Component classes to do their job.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
/**
* A component (of a statement) is a part of a statement that is common to
* multiple query types.
*
* @category Components
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
abstract class Component
{
/**
* Parses the tokens contained in the given list in the context of the given
* parser.
*
* @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.
*
* @throws \Exception Not implemented yet.
*
* @return mixed
*/
public static function parse(
Parser $parser,
TokensList $list,
array $options = array()
) {
// This method should be abstract, but it can't be both static and
// abstract.
throw new \Exception(\__('Not implemented yet.'));
}
/**
* Builds the string representation of a component of this type.
*
* In other words, this function represents the inverse function of
* `static::parse`.
*
* @param mixed $component The component to be built.
* @param array $options Parameters for building.
*
* @throws \Exception Not implemented yet.
*
* @return string
*/
public static function build($component, array $options = array())
{
// This method should be abstract, but it can't be both static and
// abstract.
throw new \Exception(\__('Not implemented yet.'));
}
/**
* Builds the string representation of a component of this type.
*
* @see static::build
*
* @return string
*/
public function __toString()
{
return static::build($this);
}
}

View File

@ -1,225 +0,0 @@
<?php
/**
* Parses an alter operation.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses an alter operation.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class AlterOperation extends Component
{
/**
* All alter operations.
*
* @var array
*/
public static $OPTIONS = array(
// table_options
'ENGINE' => array(1, 'var='),
'AUTO_INCREMENT' => array(1, 'var='),
'AVG_ROW_LENGTH' => array(1, 'var'),
'MAX_ROWS' => array(1, 'var'),
'ROW_FORMAT' => array(1, 'var'),
'ADD' => 1,
'ALTER' => 1,
'ANALYZE' => 1,
'CHANGE' => 1,
'CHECK' => 1,
'COALESCE' => 1,
'CONVERT' => 1,
'DISABLE' => 1,
'DISCARD' => 1,
'DROP' => 1,
'ENABLE' => 1,
'IMPORT' => 1,
'MODIFY' => 1,
'OPTIMIZE' => 1,
'ORDER' => 1,
'PARTITION' => 1,
'REBUILD' => 1,
'REMOVE' => 1,
'RENAME' => 1,
'REORGANIZE' => 1,
'REPAIR' => 1,
'COLUMN' => 2,
'CONSTRAINT' => 2,
'DEFAULT' => 2,
'TO' => 2,
'BY' => 2,
'FOREIGN' => 2,
'FULLTEXT' => 2,
'KEY' => 2,
'KEYS' => 2,
'PARTITIONING' => 2,
'PRIMARY KEY' => 2,
'SPATIAL' => 2,
'TABLESPACE' => 2,
'INDEX' => 2,
'DEFAULT CHARACTER SET' => array(3, 'var'),
'DEFAULT CHARSET' => array(3, 'var'),
'COLLATE' => array(4, 'var'),
);
/**
* Options of this operation.
*
* @var OptionsArray
*/
public $options;
/**
* The altered field.
*
* @var Expression
*/
public $field;
/**
* Unparsed tokens.
*
* @var Token[]|string
*/
public $unknown = array();
/**
* @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 AlterOperation
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new AlterOperation();
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ options ]---------------------> 1
*
* 1 ----------------------[ field ]----------------------> 2
*
* 2 -------------------------[ , ]-----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Skipping whitespaces.
if ($token->type === Token::TYPE_WHITESPACE) {
if ($state === 2) {
// When parsing the unknown part, the whitespaces are
// included to not break anything.
$ret->unknown[] = $token;
}
continue;
}
if ($state === 0) {
$ret->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$state = 1;
} elseif ($state === 1) {
$ret->field = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'column',
)
);
if ($ret->field === null) {
// No field was read. We go back one token so the next
// iteration will parse the same token, but in state 2.
--$list->idx;
}
$state = 2;
} elseif ($state === 2) {
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
} elseif (($token->value === ',') && ($brackets === 0)) {
break;
}
}
$ret->unknown[] = $token;
}
}
if ($ret->options->isEmpty()) {
$parser->error(
__('Unrecognized alter operation.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param AlterOperation $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = $component->options . ' ';
if ((isset($component->field)) && ($component->field !== '')) {
$ret .= $component->field . ' ';
}
$ret .= TokensList::build($component->unknown);
return $ret;
}
}

View File

@ -1,134 +0,0 @@
<?php
/**
* `VALUES` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `VALUES` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Array2d extends Component
{
/**
* @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 ArrayObj[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
/**
* The number of values in each set.
*
* @var int $count
*/
$count = -1;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ array ]----------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
// No keyword is expected.
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
break;
}
if ($state === 0) {
if ($token->value === '(') {
$arr = ArrayObj::parse($parser, $list, $options);
$arrCount = count($arr->values);
if ($count === -1) {
$count = $arrCount;
} elseif ($arrCount != $count) {
$parser->error(
sprintf(
__('%1$d values were expected, but found %2$d.'),
$count,
$arrCount
),
$token
);
}
$ret[] = $arr;
$state = 1;
} else {
break;
}
} elseif ($state === 1) {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
}
}
if ($state === 0) {
$parser->error(
__('An opening bracket followed by a set of values was expected.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param ArrayObj[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return ArrayObj::build($component);
}
}

View File

@ -1,194 +0,0 @@
<?php
/**
* Parses an array.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses an array.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ArrayObj extends Component
{
/**
* The array that contains the unprocessed value of each token.
*
* @var array
*/
public $raw = array();
/**
* The array that contains the processed value of each token.
*
* @var array
*/
public $values = array();
/**
* Constructor.
*
* @param array $raw The unprocessed values.
* @param array $values The processed values.
*/
public function __construct(array $raw = array(), array $values = array())
{
$this->raw = $raw;
$this->values = $values;
}
/**
* @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 ArrayObj|Component[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = empty($options['type']) ? new ArrayObj() : array();
/**
* The last raw expression.
*
* @var string $lastRaw
*/
$lastRaw = '';
/**
* The last value.
*
* @var string $lastValue
*/
$lastValue = '';
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Last separator (bracket or comma).
*
* @var boolean $isCommaLast
*/
$isCommaLast = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)
) {
$lastRaw .= $token->token;
$lastValue = trim($lastValue) .' ';
continue;
}
if (($brackets === 0)
&& (($token->type !== Token::TYPE_OPERATOR)
|| ($token->value !== '('))
) {
$parser->error(__('An opening bracket was expected.'), $token);
break;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
if (++$brackets === 1) { // 1 is the base level.
continue;
}
} elseif ($token->value === ')') {
if (--$brackets === 0) { // Array ended.
break;
}
} elseif ($token->value === ',') {
if ($brackets === 1) {
$isCommaLast = true;
if (empty($options['type'])) {
$ret->raw[] = trim($lastRaw);
$ret->values[] = trim($lastValue);
$lastRaw = $lastValue = '';
}
}
continue;
}
}
if (empty($options['type'])) {
$lastRaw .= $token->token;
$lastValue .= $token->value;
} else {
$ret[] = $options['type']::parse(
$parser,
$list,
empty($options['typeOptions']) ? array() : $options['typeOptions']
);
}
}
// Handling last element.
//
// This is treated differently to treat the following cases:
//
// => array()
// (,) => array('', '')
// () => array()
// (a,) => array('a', '')
// (a) => array('a')
//
$lastRaw = trim($lastRaw);
if ((empty($options['type']))
&& ((strlen($lastRaw) > 0) || ($isCommaLast))
) {
$ret->raw[] = $lastRaw;
$ret->values[] = trim($lastValue);
}
return $ret;
}
/**
* @param ArrayObj|ArrayObj[] $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);
} elseif (!empty($component->raw)) {
return '(' . implode(', ', $component->raw) . ')';
} else {
return '(' . implode(', ', $component->values) . ')';
}
}
}

View File

@ -1,223 +0,0 @@
<?php
/**
* `WHERE` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `WHERE` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Condition extends Component
{
/**
* Logical operators that can be used to delimit expressions.
*
* @var array
*/
public static $DELIMITERS = array('&&', '||', 'AND', 'OR', 'XOR');
/**
* List of allowed reserved keywords in conditions.
*
* @var array
*/
public static $ALLOWED_KEYWORDS = array(
'AND' => 1,
'BETWEEN' => 1,
'EXISTS' => 1,
'IF' => 1,
'IN' => 1,
'INTERVAL' => 1,
'IS' => 1,
'LIKE' => 1,
'MATCH' => 1,
'NOT IN' => 1,
'NOT NULL' => 1,
'NOT' => 1,
'NULL' => 1,
'OR' => 1,
'XOR' => 1,
);
/**
* Identifiers recognized.
*
* @var array
*/
public $identifiers = array();
/**
* Whether this component is an operator.
*
* @var bool
*/
public $isOperator = false;
/**
* The condition.
*
* @var string
*/
public $expr;
/**
* Constructor.
*
* @param string $expr The condition or the operator.
*/
public function __construct($expr = null)
{
$this->expr = trim($expr);
}
/**
* @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 Condition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new Condition();
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Whether there was a `BETWEEN` keyword before or not.
*
* It is required to keep track of them because their structure contains
* the keyword `AND`, which is also an operator that delimits
* expressions.
*
* @var bool $betweenBefore
*/
$betweenBefore = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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_COMMENT) {
continue;
}
// Replacing all whitespaces (new lines, tabs, etc.) with a single
// space character.
if ($token->type === Token::TYPE_WHITESPACE) {
$expr->expr .= ' ';
continue;
}
// Conditions are delimited by logical operators.
if (in_array($token->value, static::$DELIMITERS, true)) {
if (($betweenBefore) && ($token->value === 'AND')) {
// The syntax of keyword `BETWEEN` is hard-coded.
$betweenBefore = false;
} else {
// The expression ended.
$expr->expr = trim($expr->expr);
if (!empty($expr->expr)) {
$ret[] = $expr;
}
// Adding the operator.
$expr = new Condition($token->value);
$expr->isOperator = true;
$ret[] = $expr;
// Preparing to parse another condition.
$expr = new Condition();
continue;
}
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
if ($token->value === 'BETWEEN') {
$betweenBefore = true;
}
if (($brackets === 0) && (empty(static::$ALLOWED_KEYWORDS[$token->value]))) {
break;
}
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
$expr->expr .= $token->token;
if (($token->type === Token::TYPE_NONE)
|| (($token->type === Token::TYPE_KEYWORD)
&& (!($token->flags & Token::FLAG_KEYWORD_RESERVED)))
|| ($token->type === Token::TYPE_STRING)
|| ($token->type === Token::TYPE_SYMBOL)
) {
if (!in_array($token->value, $expr->identifiers)) {
$expr->identifiers[] = $token->value;
}
}
}
// Last iteration was not processed.
$expr->expr = trim($expr->expr);
if (!empty($expr->expr)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param Condition[] $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);
} else {
return $component->expr;
}
}
}

View File

@ -1,317 +0,0 @@
<?php
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the create definition of a column or a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class CreateDefinition extends Component
{
/**
* All field options.
*
* @var array
*/
public static $FIELD_OPTIONS = array(
// Tells the `OptionsArray` to not sort the options.
// See the note below.
'_UNSORTED' => true,
'NOT NULL' => 1,
'NULL' => 1,
'DEFAULT' => array(2, 'expr'),
'AUTO_INCREMENT' => 3,
'PRIMARY' => 4,
'PRIMARY KEY' => 4,
'UNIQUE' => 4,
'UNIQUE KEY' => 4,
'COMMENT' => array(5, 'var'),
'COLUMN_FORMAT' => array(6, 'var'),
'ON UPDATE' => array(7, 'var'),
// Generated columns options.
'GENERATED ALWAYS' => 8,
'AS' => array(9, 'expr', array('parenthesesDelimited' => true)),
'VIRTUAL' => 10,
'PERSISTENT' => 11,
'STORED' => 11,
// Common entries.
//
// NOTE: Some of the common options are not in the same order which
// causes troubles when checking if the options are in the right order.
// I should find a way to define multiple sets of options and make the
// parser select the right set.
//
// 'UNIQUE' => 4,
// 'UNIQUE KEY' => 4,
// 'COMMENT' => array(5, 'var'),
// 'NOT NULL' => 1,
// 'NULL' => 1,
// 'PRIMARY' => 4,
// 'PRIMARY KEY' => 4,
);
/**
* The name of the new column.
*
* @var string
*/
public $name;
/**
* Whether this field is a constraint or not.
*
* @var bool
*/
public $isConstraint;
/**
* The data type of thew new column.
*
* @var DataType
*/
public $type;
/**
* The key.
*
* @var Key
*/
public $key;
/**
* The table that is referenced.
*
* @var Reference
*/
public $references;
/**
* The options of this field.
*
* @var OptionsArray
*/
public $options;
/**
* Constructor.
*
* @param string $name The name of the field.
* @param OptionsArray $options The options of this field.
* @param DataType|Key $type The data type of this field or the key.
* @param bool $isConstraint Whether this field is a constraint or not.
* @param Reference $references References.
*/
public function __construct(
$name = null,
$options = null,
$type = null,
$isConstraint = false,
$references = null
) {
$this->name = $name;
$this->options = $options;
if ($type instanceof DataType) {
$this->type = $type;
} elseif ($type instanceof Key) {
$this->key = $type;
$this->isConstraint = $isConstraint;
$this->references = $references;
}
}
/**
* @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 CreateDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new CreateDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ ( ]------------------------> 1
*
* 1 --------------------[ CONSTRAINT ]------------------> 1
* 1 -----------------------[ key ]----------------------> 2
* 1 -------------[ constraint / column name ]-----------> 2
*
* 2 --------------------[ data type ]-------------------> 3
*
* 3 ---------------------[ options ]--------------------> 4
*
* 4 --------------------[ REFERENCES ]------------------> 4
*
* 5 ------------------------[ , ]-----------------------> 1
* 5 ------------------------[ ) ]-----------------------> 6 (-1)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
} else {
$parser->error(
__('An opening bracket was expected.'),
$token
);
break;
}
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'CONSTRAINT')) {
$expr->isConstraint = true;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_KEY)) {
$expr->key = Key::parse($parser, $list);
$state = 4;
} else {
$expr->name = $token->value;
if (!$expr->isConstraint) {
$state = 2;
}
}
} elseif ($state === 2) {
$expr->type = DataType::parse($parser, $list);
$state = 3;
} elseif ($state === 3) {
$expr->options = OptionsArray::parse($parser, $list, static::$FIELD_OPTIONS);
$state = 4;
} elseif ($state === 4) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'REFERENCES')) {
++$list->idx; // Skipping keyword 'REFERENCES'.
$expr->references = Reference::parse($parser, $list);
} else {
--$list->idx;
}
$state = 5;
} elseif ($state === 5) {
if ((!empty($expr->type)) || (!empty($expr->key))) {
$ret[] = $expr;
}
$expr = new CreateDefinition();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
$state = 6;
++$list->idx;
break;
} else {
$parser->error(
__('A comma or a closing bracket was expected.'),
$token
);
$state = 0;
break;
}
}
}
// Last iteration was not saved.
if ((!empty($expr->type)) || (!empty($expr->key))) {
$ret[] = $expr;
}
if (($state !== 0) && ($state !== 6)) {
$parser->error(
__('A closing bracket was expected.'),
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
return $ret;
}
/**
* @param CreateDefinition|CreateDefinition[] $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 "(\n " . implode(",\n ", $component) . "\n)";
} else {
$tmp = '';
if ($component->isConstraint) {
$tmp .= 'CONSTRAINT ';
}
if ((isset($component->name)) && ($component->name !== '')) {
$tmp .= Context::escape($component->name) . ' ';
}
if (!empty($component->type)) {
$tmp .= DataType::build(
$component->type,
array('lowercase' => true)
) . ' ';
}
if (!empty($component->key)) {
$tmp .= $component->key . ' ';
}
if (!empty($component->references)) {
$tmp .= 'REFERENCES ' . $component->references . ' ';
}
$tmp .= $component->options;
return trim($tmp);
}
}
}

View File

@ -1,171 +0,0 @@
<?php
/**
* Parses a data type.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a data type.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class DataType extends Component
{
/**
* All data type options.
*
* @var array
*/
public static $DATA_TYPE_OPTIONS = array(
'BINARY' => 1,
'CHARACTER SET' => array(2, 'var'),
'CHARSET' => array(2, 'var'),
'COLLATE' => array(3, 'var'),
'UNSIGNED' => 4,
'ZEROFILL' => 5,
);
/**
* The name of the data type.
*
* @var string
*/
public $name;
/**
* The parameters of this data type.
*
* Some data types have no parameters.
* Numeric types might have parameters for the maximum number of digits,
* precision, etc.
* String types might have parameters for the maximum length stored.
* `ENUM` and `SET` have parameters for possible values.
*
* For more information, check the MySQL manual.
*
* @var array
*/
public $parameters = array();
/**
* The options of this data type.
*
* @var OptionsArray
*/
public $options;
/**
* Constructor.
*
* @param string $name The name of this data type.
* @param array $parameters The parameters (size or possible values).
* @param OptionsArray $options The options of this data type.
*/
public function __construct(
$name = null,
array $parameters = array(),
$options = null
) {
$this->name = $name;
$this->parameters = $parameters;
$this->options = $options;
}
/**
* @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 DataType
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new DataType();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------------[ data type ]--------------------> 1
*
* 1 ----------------[ size and options ]----------------> 2
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// Skipping whitespaces and comments.
if (($token->type === Token::TYPE_WHITESPACE) || ($token->type === Token::TYPE_COMMENT)) {
continue;
}
if ($state === 0) {
$ret->name = strtoupper($token->value);
if (($token->type !== Token::TYPE_KEYWORD) || (!($token->flags & Token::FLAG_KEYWORD_DATA_TYPE))) {
$parser->error(__('Unrecognized data type.'), $token);
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$parameters = ArrayObj::parse($parser, $list);
++$list->idx;
$ret->parameters = (($ret->name === 'ENUM') || ($ret->name === 'SET')) ?
$parameters->raw : $parameters->values;
}
$ret->options = OptionsArray::parse($parser, $list, static::$DATA_TYPE_OPTIONS);
++$list->idx;
break;
}
}
if (empty($ret->name)) {
return null;
}
--$list->idx;
return $ret;
}
/**
* @param DataType $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$name = (empty($options['lowercase'])) ?
$component->name : strtolower($component->name);
$parameters = '';
if (!empty($component->parameters)) {
$parameters = '(' . implode(',', $component->parameters) . ')';
}
return trim($name . $parameters . ' ' . $component->options);
}
}

View File

@ -1,435 +0,0 @@
<?php
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a reference to an expression (column, table or database name, function
* call, mathematical expression, etc.).
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
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
);
/**
* 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
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Expression();
/**
* Whether current tokens make an expression or a table reference.
*
* @var bool $isExpr
*/
$isExpr = false;
/**
* Whether a period was previously found.
*
* @var bool $dot
*/
$dot = false;
/**
* Whether an alias is expected. Is 2 if `AS` keyword was found.
*
* @var bool $alias
*/
$alias = false;
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* Keeps track of the last two previous tokens.
*
* @var Token[] $prev
*/
$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
*/
$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->value]))
) {
// A `(` was previously found and this keyword is the
// beginning of a statement, so this is a subquery.
$ret->subquery = $token->value;
} elseif (($token->flags & Token::FLAG_KEYWORD_FUNCTION)
&& (empty($options['parseField']))
) {
$isExpr = true;
} elseif (($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ($brackets === 0)
) {
if (empty(self::$ALLOWED_KEYWORDS[$token->value])) {
// 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->value === 'AS') {
if (!empty($options['breakOnAlias'])) {
break;
}
if (!empty($ret->alias)) {
$parser->error(
__('An alias was previously found.'),
$token
);
break;
}
$alias = true;
continue;
}
$isExpr = true;
}
}
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_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 === ')') {
--$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 (empty($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, ', ');
} else {
if (!empty($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;
}
}
}

View File

@ -1,122 +0,0 @@
<?php
/**
* Parses a a list of expressions delimited by a comma.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a a list of expressions delimited by a comma.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ExpressionArray extends Component
{
/**
* @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[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ array ]---------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD)
&& ($token->flags & Token::FLAG_KEYWORD_RESERVED)
&& ((~$token->flags & Token::FLAG_KEYWORD_FUNCTION))
&& ($token->value !== 'DUAL')
&& ($token->value !== 'NULL')
) {
// No keyword is expected.
break;
}
if ($state === 0) {
$expr = Expression::parse($parser, $list, $options);
if ($expr === null) {
break;
}
$ret[] = $expr;
$state = 1;
} elseif ($state === 1) {
if ($token->value === ',') {
$state = 0;
} else {
break;
}
}
}
if ($state === 0) {
$parser->error(
__('An expression was expected.'),
$list->tokens[$list->idx]
);
}
--$list->idx;
return $ret;
}
/**
* @param Expression[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = array();
foreach ($component as $frag) {
$ret[] = $frag::build($frag);
}
return implode($ret, ', ');
}
}

View File

@ -1,125 +0,0 @@
<?php
/**
* Parses a function call.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a function call.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class FunctionCall extends Component
{
/**
* The name of this function.
*
* @var string
*/
public $name;
/**
* The list of parameters
*
* @var ArrayObj
*/
public $parameters;
/**
* Constructor.
*
* @param string $name The name of the function to be called.
* @param array|ArrayObj $parameters The parameters of this function.
*/
public function __construct($name = null, $parameters = null)
{
$this->name = $name;
if (is_array($parameters)) {
$this->parameters = new ArrayObj($parameters);
} elseif ($parameters instanceof ArrayObj) {
$this->parameters = $parameters;
}
}
/**
* @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 FunctionCall
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new FunctionCall();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ name ]-----------------------> 1
*
* 1 --------------------[ parameters ]-------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$ret->name = $token->value;
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->parameters = ArrayObj::parse($parser, $list);
}
break;
}
}
return $ret;
}
/**
* @param FunctionCall $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return $component->name . $component->parameters;
}
}

View File

@ -1,148 +0,0 @@
<?php
/**
* `INTO` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `INTO` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class IntoKeyword extends Component
{
/**
* Type of target (OUTFILE or SYMBOL).
*
* @var string
*/
public $type;
/**
* The destination, which can be a table or a file.
*
* @var string|Expression
*/
public $dest;
/**
* The name of the columns.
*
* @var array
*/
public $columns;
/**
* @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 IntoKeyword
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new IntoKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ name ]----------------------> 1
* 0 ---------------------[ OUTFILE ]---------------------> 2
*
* 1 ------------------------[ ( ]------------------------> (END)
*
* 2 ---------------------[ filename ]--------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
if (($state === 0) && ($token->value === 'OUTFILE')) {
$ret->type = 'OUTFILE';
$state = 2;
continue;
}
// No other keyword is expected.
break;
}
if ($state === 0) {
$ret->dest = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->columns = ArrayObj::parse($parser, $list)->values;
++$list->idx;
}
break;
} elseif ($state === 2) {
$ret->dest = $token->value;
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param IntoKeyword $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if ($component->dest instanceof Expression) {
$columns = !empty($component->columns) ?
'(' . implode(', ', $component->columns) . ')' : '';
return $component->dest . $columns;
} else {
return 'OUTFILE "' . $component->dest . '"';
}
}
}

View File

@ -1,169 +0,0 @@
<?php
/**
* `JOIN` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `JOIN` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class JoinKeyword extends Component
{
/**
* Types of join.
*
* @var array
*/
public static $JOINS = array(
'FULL JOIN' => 'FULL',
'INNER JOIN' => 'INNER',
'JOIN' => 'JOIN',
'LEFT JOIN' => 'LEFT',
'LEFT OUTER JOIN' => 'LEFT',
'RIGHT JOIN' => 'RIGHT',
'RIGHT OUTER JOIN' => 'RIGHT',
'STRAIGHT_JOIN' => 'STRAIGHT',
);
/**
* Type of this join.
*
* @see static::$JOINS
* @var string
*/
public $type;
/**
* Join expression.
*
* @var Expression
*/
public $expr;
/**
* Join conditions.
*
* @var Condition[]
*/
public $on;
/**
* @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 JoinKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new JoinKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ JOIN ]----------------------> 1
*
* 1 -----------------------[ expr ]----------------------> 2
*
* 2 ------------------------[ ON ]-----------------------> 3
*
* 3 --------------------[ conditions ]-------------------> 0
*
* @var int $state
*/
$state = 0;
// By design, the parser will parse first token after the keyword.
// In this case, the keyword must be analyzed too, in order to determine
// the type of this join.
if ($list->idx > 0) {
--$list->idx;
}
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_KEYWORD)
&& (!empty(static::$JOINS[$token->value]))
) {
$expr->type = static::$JOINS[$token->value];
$state = 1;
} else {
break;
}
} elseif ($state === 1) {
$expr->expr = Expression::parse($parser, $list, array('field' => 'table'));
$state = 2;
} elseif ($state === 2) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'ON')) {
$state = 3;
}
} elseif ($state === 3) {
$expr->on = Condition::parse($parser, $list);
$ret[] = $expr;
$expr = new JoinKeyword();
$state = 0;
}
}
if (!empty($expr->type)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param JoinKeyword[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = array();
foreach ($component as $c) {
$ret[] = array_search($c->type, static::$JOINS) . ' '
. $c->expr . ' ON ' . Condition::build($c->on);
}
return implode(' ', $ret);
}
}

View File

@ -1,208 +0,0 @@
<?php
/**
* Parses the definition of a key.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the definition of a key.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Key extends Component
{
/**
* All key options.
*
* @var array
*/
public static $KEY_OPTIONS = array(
'KEY_BLOCK_SIZE' => array(1, 'var'),
'USING' => array(2, 'var'),
'WITH PARSER' => array(3, 'var'),
'COMMENT' => array(4, 'var='),
);
/**
* The name of this key.
*
* @var string
*/
public $name;
/**
* Columns.
*
* @var array
*/
public $columns;
/**
* The type of this key.
*
* @var string
*/
public $type;
/**
* The options of this key.
*
* @var OptionsArray
*/
public $options;
/**
* Constructor.
*
* @param string $name The name of the key.
* @param array $columns The columns covered by this key.
* @param string $type The type of this key.
* @param OptionsArray $options The options of this key.
*/
public function __construct(
$name = null,
array $columns = array(),
$type = null,
$options = null
) {
$this->name = $name;
$this->columns = $columns;
$this->type = $type;
$this->options = $options;
}
/**
* @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 Key[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Key();
/**
* Last parsed column.
*
* @var array
*/
$lastColumn = array();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ type ]-----------------------> 1
*
* 1 ----------------------[ name ]-----------------------> 1
* 1 ---------------------[ columns ]---------------------> 2
*
* 2 ---------------------[ options ]---------------------> 3
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$ret->type = $token->value;
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 2;
} else {
$ret->name = $token->value;
}
} elseif ($state === 2) {
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
$state = 3;
} elseif (($token->value === ',') || ($token->value === ')')) {
$state = ($token->value === ',') ? 2 : 4;
if (!empty($lastColumn)) {
$ret->columns[] = $lastColumn;
$lastColumn = array();
}
}
} else {
$lastColumn['name'] = $token->value;
}
} elseif ($state === 3) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
$state = 2;
} else {
$lastColumn['length'] = $token->value;
}
} elseif ($state === 4) {
$ret->options = OptionsArray::parse($parser, $list, static::$KEY_OPTIONS);
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param Key $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$ret = $component->type . ' ';
if (!empty($component->name)) {
$ret .= Context::escape($component->name) . ' ';
}
$columns = array();
foreach ($component->columns as $column) {
$tmp = Context::escape($column['name']);
if (isset($column['length'])) {
$tmp .= '(' . $column['length'] . ')';
}
$columns[] = $tmp;
}
$ret .= '(' . implode(',', $columns) . ') ' . $component->options;
return trim($ret);
}
}

View File

@ -1,136 +0,0 @@
<?php
/**
* `LIMIT` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `LIMIT` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Limit extends Component
{
/**
* The number of rows skipped.
*
* @var int
*/
public $offset;
/**
* The number of rows to be returned.
*
* @var int
*/
public $rowCount;
/**
* Constructor.
*
* @param int $rowCount The row count.
* @param int $offset The offset.
*/
public function __construct($rowCount = 0, $offset = 0)
{
$this->rowCount = $rowCount;
$this->offset = $offset;
}
/**
* @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 Limit
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Limit();
$offset = false;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED)) {
break;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'OFFSET')) {
if ($offset) {
$parser->error(__('An offset was expected.'), $token);
}
$offset = true;
continue;
}
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret->offset = $ret->rowCount;
$ret->rowCount = 0;
continue;
}
if ($offset) {
$ret->offset = $token->value;
$offset = false;
} else {
$ret->rowCount = $token->value;
}
}
if ($offset) {
$parser->error(
__('An offset was expected.'),
$list->tokens[$list->idx - 1]
);
}
--$list->idx;
return $ret;
}
/**
* @param Limit $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (empty($component->offset)) {
return $component->rowCount;
} else {
return $component->offset . ', ' . $component->rowCount;
}
}
}

View File

@ -1,345 +0,0 @@
<?php
/**
* Parses a list of options.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses a list of options.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class OptionsArray extends Component
{
/**
* ArrayObj of selected options.
*
* @var array
*/
public $options = array();
/**
* Constructor.
*
* @param array $options The array of options. Options that have a value
* must be an array with at least two keys `name` and
* `expr` or `value`.
*/
public function __construct(array $options = array())
{
$this->options = $options;
}
/**
* @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 OptionsArray
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new OptionsArray();
/**
* The ID that will be assigned to duplicate options.
*
* @var int $lastAssignedId
*/
$lastAssignedId = count($options) + 1;
/**
* The option that was processed last time.
*
* @var array $lastOption
*/
$lastOption = null;
/**
* The index of the option that was processed last time.
*
* @var int $lastOptionId
*/
$lastOptionId = 0;
/**
* Counts brackets.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ option ]----------------------> 1
*
* 1 -------------------[ = (optional) ]------------------> 2
*
* 2 ----------------------[ value ]----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
// Skipping whitespace if not parsing value.
if (($token->type === Token::TYPE_WHITESPACE) && ($brackets === 0)) {
continue;
}
if ($lastOption === null) {
$upper = strtoupper($token->token);
if (isset($options[$upper])) {
$lastOption = $options[$upper];
$lastOptionId = is_array($lastOption) ?
$lastOption[0] : $lastOption;
$state = 0;
// Checking for option conflicts.
// For example, in `SELECT` statements the keywords `ALL`
// and `DISTINCT` conflict and if used together, they
// produce an invalid query.
//
// Usually, tokens can be identified in the array by the
// option ID, but if conflicts occur, a generated option ID
// is used.
//
// The first pseudo duplicate ID is the maximum value of the
// real options (e.g. if there are 5 options, the first
// fake ID is 6).
if (isset($ret->options[$lastOptionId])) {
$parser->error(
sprintf(
__('This option conflicts with "%1$s".'),
is_array($ret->options[$lastOptionId])
? $ret->options[$lastOptionId]['name']
: $ret->options[$lastOptionId]
),
$token
);
$lastOptionId = $lastAssignedId++;
}
} else {
// There is no option to be processed.
break;
}
}
if ($state === 0) {
if (!is_array($lastOption)) {
// This is a just keyword option without any value.
// This is the beginning and the end of it.
$ret->options[$lastOptionId] = $token->value;
$lastOption = null;
$state = 0;
} elseif (($lastOption[1] === 'var') || ($lastOption[1] === 'var=')) {
// This is a keyword that is followed by a value.
// This is only the beginning. The value is parsed in state
// 1 and 2. State 1 is used to skip the first equals sign
// and state 2 to parse the actual value.
$ret->options[$lastOptionId] = array(
// @var string The name of the option.
'name' => $token->value,
// @var bool Whether it contains an equal sign.
// This is used by the builder to rebuild it.
'equals' => $lastOption[1] === 'var=',
// @var string Raw value.
'expr' => '',
// @var string Processed value.
'value' => '',
);
$state = 1;
} elseif ($lastOption[1] === 'expr') {
// This is a keyword that is followed by an expression.
// The expression is used by the specialized parser.
// Skipping this option in order to parse the expression.
++$list->idx;
$ret->options[$lastOptionId] = array(
// @var string The name of the option.
'name' => $token->value,
// @var Expression The parsed expression.
'expr' => null,
);
$state = 1;
}
} elseif ($state === 1) {
$state = 2;
if ($token->token === '=') {
$ret->options[$lastOptionId]['equals'] = true;
continue;
}
}
// This is outside the `elseif` group above because the change might
// change this iteration.
if ($state === 2) {
if ($lastOption[1] === 'expr') {
$ret->options[$lastOptionId]['expr'] = Expression::parse(
$parser,
$list,
empty($lastOption[2]) ? array() : $lastOption[2]
);
$ret->options[$lastOptionId]['value']
= $ret->options[$lastOptionId]['expr']->expr;
$lastOption = null;
$state = 0;
} else {
if ($token->token === '(') {
++$brackets;
} elseif ($token->token === ')') {
--$brackets;
}
$ret->options[$lastOptionId]['expr'] .= $token->token;
if (!((($token->token === '(') && ($brackets === 1))
|| (($token->token === ')') && ($brackets === 0)))
) {
// First pair of brackets is being skipped.
$ret->options[$lastOptionId]['value'] .= $token->value;
}
// Checking if we finished parsing.
if ($brackets === 0) {
$lastOption = null;
}
}
}
}
if (empty($options['_UNSORTED'])) {
ksort($ret->options);
}
--$list->idx;
return $ret;
}
/**
* @param OptionsArray $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
if (empty($component->options)) {
return '';
}
$options = array();
foreach ($component->options as $option) {
if (!is_array($option)) {
$options[] = $option;
} else {
$options[] = $option['name']
. (!empty($option['equals']) ? '=' : ' ')
. (!empty($option['expr']) ? $option['expr'] : $option['value']);
}
}
return implode(' ', $options);
}
/**
* Checks if it has the specified option and returns it value or true.
*
* @param string $key The key to be checked.
* @param bool $getExpr Gets the expression instead of the value.
* The value is the processed form of the expression.
*
* @return mixed
*/
public function has($key, $getExpr = false)
{
foreach ($this->options as $option) {
if ($key === $option) {
return true;
} elseif ((is_array($option)) && ($key === $option['name'])) {
return $getExpr ? $option['expr'] : $option['value'];
}
}
return false;
}
/**
* Removes the option from the array.
*
* @param string $key The key to be removed.
*
* @return bool Whether the key was found and deleted or not.
*/
public function remove($key)
{
foreach ($this->options as $idx => $option) {
if (($key === $option)
|| ((is_array($option)) && ($key === $option['name']))
) {
unset($this->options[$idx]);
return true;
}
}
return false;
}
/**
* Merges the specified options with these ones. Values with same ID will be
* replaced.
*
* @param array|OptionsArray $options The options to be merged.
*
* @return void
*/
public function merge($options)
{
if (is_array($options)) {
$this->options = array_merge_recursive($this->options, $options);
} elseif ($options instanceof OptionsArray) {
$this->options = array_merge_recursive($this->options, $options->options);
}
}
/**
* Checks tf there are no options set.
*
* @return bool
*/
public function isEmpty()
{
return empty($this->options);
}
}

View File

@ -1,141 +0,0 @@
<?php
/**
* `ORDER BY` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `ORDER BY` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class OrderKeyword extends Component
{
/**
* The expression that is used for ordering.
*
* @var Expression
*/
public $expr;
/**
* The order type.
*
* @var string
*/
public $type;
/**
* Constructor.
*
* @param Expression $expr The expression that we are sorting by.
* @param string $type The sorting type.
*/
public function __construct($expr = null, $type = 'ASC')
{
$this->expr = $expr;
$this->type = $type;
}
/**
* @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 OrderKeyword[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new OrderKeyword();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 --------------------[ expression ]-------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 -------------------[ ASC / DESC ]--------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$expr->expr = Expression::parse($parser, $list);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD) && (($token->value === 'ASC') || ($token->value === 'DESC'))) {
$expr->type = $token->value;
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
if (!empty($expr->expr)) {
$ret[] = $expr;
}
$expr = new OrderKeyword();
$state = 0;
} else {
break;
}
}
}
// Last iteration was not processed.
if (!empty($expr->expr)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param OrderKeyword|OrderKeyword[] $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);
} else {
return $component->expr . ' ' . $component->type;
}
}
}

View File

@ -1,161 +0,0 @@
<?php
/**
* The definition of a parameter of a function or procedure.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* The definition of a parameter of a function or procedure.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ParameterDefinition extends Component
{
/**
* The name of the new column.
*
* @var string
*/
public $name;
/**
* Parameter's direction (IN, OUT or INOUT).
*
* @var string
*/
public $inOut;
/**
* The data type of thew new column.
*
* @var DataType
*/
public $type;
/**
* @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 ParameterDefinition[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new ParameterDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------------[ ( ]------------------------> 1
*
* 1 ----------------[ IN / OUT / INOUT ]----------------> 1
* 1 ----------------------[ name ]----------------------> 2
*
* 2 -------------------[ data type ]--------------------> 3
*
* 3 ------------------------[ , ]-----------------------> 1
* 3 ------------------------[ ) ]-----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$state = 1;
}
continue;
} elseif ($state === 1) {
if (($token->value === 'IN') || ($token->value === 'OUT') || ($token->value === 'INOUT')) {
$expr->inOut = $token->value;
++$list->idx;
} elseif ($token->value === ')') {
++$list->idx;
break;
} else {
$expr->name = $token->value;
$state = 2;
}
} elseif ($state === 2) {
$expr->type = DataType::parse($parser, $list);
$state = 3;
} elseif ($state === 3) {
$ret[] = $expr;
$expr = new ParameterDefinition();
if ($token->value === ',') {
$state = 1;
} elseif ($token->value === ')') {
++$list->idx;
break;
}
}
}
// Last iteration was not saved.
if ((isset($expr->name)) && ($expr->name !== '')) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param ParameterDefinition[] $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) . ')';
} else {
$tmp = '';
if (!empty($component->inOut)) {
$tmp .= $component->inOut . ' ';
}
return trim(
$tmp . Context::escape($component->name) . ' ' . $component->type
);
}
}
}

View File

@ -1,224 +0,0 @@
<?php
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Parses the create definition of a partition.
*
* Used for parsing `CREATE TABLE` statement.
*
* @category Components
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class PartitionDefinition extends Component
{
/**
* All field options.
*
* @var array
*/
public static $OPTIONS = array(
'STORAGE ENGINE' => array(1, 'var'),
'ENGINE' => array(1, 'var'),
'COMMENT' => array(2, 'var'),
'DATA DIRECTORY' => array(3, 'var'),
'INDEX DIRECTORY' => array(4, 'var'),
'MAX_ROWS' => array(5, 'var'),
'MIN_ROWS' => array(6, 'var'),
'TABLESPACE' => array(7, 'var'),
'NODEGROUP' => array(8, 'var'),
);
/**
* Whether this entry is a subpartition or a partition.
*
* @var bool
*/
public $isSubpartition;
/**
* The name of this partition.
*
* @var string
*/
public $name;
/**
* The type of this partition (what follows the `VALUES` keyword).
*
* @var string
*/
public $type;
/**
* The expression used to defined this partition.
*
* @var Expression|string
*/
public $expr;
/**
* The subpartitions of this partition.
*
* @var PartitionDefinition[]
*/
public $subpartitions;
/**
* The options of this field.
*
* @var OptionsArray
*/
public $options;
/**
* @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 PartitionDefinition
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new PartitionDefinition();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------[ PARTITION | SUBPARTITION ]------------> 1
*
* 1 -----------------------[ name ]----------------------> 2
*
* 2 ----------------------[ VALUES ]---------------------> 3
*
* 3 ---------------------[ LESS THAN ]-------------------> 4
* 3 ------------------------[ IN ]-----------------------> 4
*
* 4 -----------------------[ expr ]----------------------> 5
*
* 5 ----------------------[ options ]--------------------> 6
*
* 6 ------------------[ subpartitions ]------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$ret->isSubpartition = ($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITION');
$state = 1;
} elseif ($state === 1) {
$ret->name = $token->value;
// Looking ahead for a 'VALUES' keyword.
$idx = $list->idx;
$list->getNext();
$nextToken = $list->getNext();
$list->idx = $idx;
$state = ($nextToken->type === Token::TYPE_KEYWORD)
&& ($nextToken->value === 'VALUES')
? 2 : 5;
} elseif ($state === 2) {
$state = 3;
} elseif ($state === 3) {
$ret->type = $token->value;
$state = 4;
} elseif ($state === 4) {
if ($token->value === 'MAXVALUE') {
$ret->expr = $token->value;
} else {
$ret->expr = Expression::parse(
$parser,
$list,
array(
'parenthesesDelimited' => true,
'breakOnAlias' => true,
)
);
}
$state = 5;
} elseif ($state === 5) {
$ret->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
$state = 6;
} elseif ($state === 6) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
$ret->subpartitions = ArrayObj::parse(
$parser,
$list,
array(
'type' => 'SqlParser\\Components\\PartitionDefinition'
)
);
++$list->idx;
}
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param PartitionDefinition|PartitionDefinition[] $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 "(\n" . implode(",\n", $component) . "\n)";
} else {
if ($component->isSubpartition) {
return trim('SUBPARTITION ' . $component->name . ' ' . $component->options);
} else {
$subpartitions = empty($component->subpartitions)
? '' : ' ' . PartitionDefinition::build($component->subpartitions);
return trim(
'PARTITION ' . $component->name
. (empty($component->type) ? '' : ' VALUES ' . $component->type . ' ' . $component->expr)
. $component->options . $subpartitions
);
}
}
}
}

View File

@ -1,158 +0,0 @@
<?php
/**
* `REFERENCES` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Context;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `REFERENCES` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Reference extends Component
{
/**
* All references options.
*
* @var array
*/
public static $REFERENCES_OPTIONS = array(
'MATCH' => array(1, 'var'),
'ON DELETE' => array(2, 'var'),
'ON UPDATE' => array(3, 'var'),
);
/**
* The referenced table.
*
* @var Expression
*/
public $table;
/**
* The referenced columns.
*
* @var array
*/
public $columns;
/**
* The options of the referencing.
*
* @var OptionsArray
*/
public $options;
/**
* Constructor.
*
* @param Expression $table The name of the table referenced.
* @param array $columns The columns referenced.
* @param OptionsArray $options The options.
*/
public function __construct($table = null, array $columns = array(), $options = null)
{
$this->table = $table;
$this->columns = $columns;
$this->options = $options;
}
/**
* @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 Reference
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = new Reference();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ----------------------[ table ]---------------------> 1
*
* 1 ---------------------[ columns ]--------------------> 2
*
* 2 ---------------------[ options ]--------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$ret->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
$state = 1;
} elseif ($state === 1) {
$ret->columns = ArrayObj::parse($parser, $list)->values;
$state = 2;
} elseif ($state === 2) {
$ret->options = OptionsArray::parse($parser, $list, static::$REFERENCES_OPTIONS);
++$list->idx;
break;
}
}
--$list->idx;
return $ret;
}
/**
* @param Reference $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
return trim(
$component->table
. ' (' . implode(', ', Context::escape($component->columns)) . ') '
. $component->options
);
}
}

View File

@ -1,174 +0,0 @@
<?php
/**
* `RENAME TABLE` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `RENAME TABLE` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class RenameOperation extends Component
{
/**
* The old table name.
*
* @var Expression
*/
public $old;
/**
* The new table name.
*
* @var Expression
*/
public $new;
/**
* @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 RenameOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new RenameOperation();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 ---------------------[ old name ]--------------------> 1
*
* 1 ------------------------[ TO ]-----------------------> 2
*
* 2 ---------------------[ old name ]--------------------> 3
*
* 3 ------------------------[ , ]------------------------> 0
* 3 -----------------------[ else ]----------------------> (END)
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$expr->old = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'table',
)
);
if (empty($expr->old)) {
$parser->error(
__('The old name of the table was expected.'),
$token
);
}
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'TO')) {
$state = 2;
} else {
$parser->error(
__('Keyword "TO" was expected.'),
$token
);
break;
}
} elseif ($state === 2) {
$expr->new = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
'parseField' => 'table',
)
);
if (empty($expr->new)) {
$parser->error(
__('The new name of the table was expected.'),
$token
);
}
$state = 3;
} elseif ($state === 3) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$ret[] = $expr;
$expr = new RenameOperation();
$state = 0;
} else {
break;
}
}
}
if ($state !== 3) {
$parser->error(
__('A rename operation was expected.'),
$list->tokens[$list->idx - 1]
);
}
// Last iteration was not saved.
if (!empty($expr->old)) {
$ret[] = $expr;
}
--$list->idx;
return $ret;
}
/**
* @param RenameOperation $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);
} else {
return $component->old . ' TO ' . $component->new;
}
}
}

View File

@ -1,136 +0,0 @@
<?php
/**
* `SET` keyword parser.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* `SET` keyword parser.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class SetOperation extends Component
{
/**
* The name of the column that is being updated.
*
* @var string
*/
public $column;
/**
* The new value.
*
* @var string
*/
public $value;
/**
* @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 SetOperation[]
*/
public static function parse(Parser $parser, TokensList $list, array $options = array())
{
$ret = array();
$expr = new SetOperation();
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -------------------[ column name ]-------------------> 1
*
* 1 ------------------------[ , ]------------------------> 0
* 1 ----------------------[ value ]----------------------> 1
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
// No keyword is expected.
if (($token->type === Token::TYPE_KEYWORD) && ($token->flags & Token::FLAG_KEYWORD_RESERVED) && ($state == 0)) {
break;
}
if ($state === 0) {
if ($token->token === '=') {
$state = 1;
} elseif ($token->value !== ',') {
$expr->column .= $token->token;
}
} elseif ($state === 1) {
$tmp = Expression::parse(
$parser,
$list,
array(
'breakOnAlias' => true,
)
);
if ($tmp == null) {
$expr = null;
break;
}
$expr->column = trim($expr->column);
$expr->value = $tmp->expr;
$ret[] = $expr;
$expr = new SetOperation();
$state = 0;
}
}
--$list->idx;
return $ret;
}
/**
* @param SetOperation|SetOperation[] $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);
} else {
return $component->column . ' = ' . $component->value;
}
}
}

View File

@ -1,40 +0,0 @@
<?php
/**
* `UNION` keyword builder.
*
* @package SqlParser
* @subpackage Components
*/
namespace SqlParser\Components;
use SqlParser\Component;
use SqlParser\Statements\SelectStatement;
/**
* `UNION` keyword builder.
*
* @category Keywords
* @package SqlParser
* @subpackage Components
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class UnionKeyword extends Component
{
/**
* @param SelectStatement[] $component The component to be built.
* @param array $options Parameters for building.
*
* @return string
*/
public static function build($component, array $options = array())
{
$tmp = array();
foreach ($component as $component) {
$tmp[] = $component[0] . ' ' . $component[1];
}
return implode(' ', $tmp);
}
}

View File

@ -1,545 +0,0 @@
<?php
/**
* Defines a context class that is later extended to define other contexts.
*
* A context is a collection of keywords, operators and functions used for
* parsing.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* Holds the configuration of the context that is currently used.
*
* @category Contexts
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
abstract class Context
{
/**
* The maximum length of a keyword.
*
* @see static::$TOKEN_KEYWORD
*
* @var int
*/
const KEYWORD_MAX_LENGTH = 30;
/**
* The maximum length of an operator.
*
* @see static::$TOKEN_OPERATOR
*
* @var int
*/
const OPERATOR_MAX_LENGTH = 4;
/**
* The name of the default content.
*
* @var string
*/
public static $defaultContext = '\\SqlParser\\Contexts\\ContextMySql50700';
/**
* The name of the loaded context.
*
* @var string
*/
public static $loadedContext = '\\SqlParser\\Contexts\\ContextMySql50700';
/**
* The prefix concatenated to the context name when an incomplete class name
* is specified.
*
* @var string
*/
public static $contextPrefix = '\\SqlParser\\Contexts\\Context';
/**
* List of keywords.
*
* Because, PHP's associative arrays are basically hash tables, it is more
* efficient to store keywords as keys instead of values.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* Elements are sorted by flags, length and keyword.
*
* @var array
*/
public static $KEYWORDS = array();
/**
* List of operators and their flags.
*
* @var array
*/
public static $OPERATORS = array(
// Some operators (*, =) may have ambiguous flags, because they depend on
// the context they are being used in.
// For example: 1. SELECT * FROM table; # SQL specific (wildcard)
// SELECT 2 * 3; # arithmetic
// 2. SELECT * FROM table WHERE foo = 'bar';
// SET @i = 0;
// @see Token::FLAG_OPERATOR_ARITHMETIC
'%' => 1, '*' => 1, '+' => 1, '-' => 1, '/' => 1,
// @see Token::FLAG_OPERATOR_LOGICAL
'!' => 2, '!=' => 2, '&&' => 2, '<' => 2, '<=' => 2,
'<=>' => 2, '<>' => 2, '=' => 2, '>' => 2, '>=' => 2,
'||' => 2,
// @see Token::FLAG_OPERATOR_BITWISE
'&' => 4, '<<' => 4, '>>' => 4, '^' => 4, '|' => 4,
'~' => 4,
// @see Token::FLAG_OPERATOR_ASSIGNMENT
':=' => 8,
// @see Token::FLAG_OPERATOR_SQL
'(' => 16, ')' => 16, '.' => 16, ',' => 16, ';' => 16,
);
/**
* The mode of the MySQL server that will be used in lexing, parsing and
* building the statements.
*
* @var int
*/
public static $MODE = 0;
/*
* Server SQL Modes
* https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html
*/
// Compatibility mode for Microsoft's SQL server.
// This is the equivalent of ANSI_QUOTES.
const COMPAT_MYSQL = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_allow_invalid_dates
const ALLOW_INVALID_DATES = 1;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ansi_quotes
const ANSI_QUOTES = 2;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_error_for_division_by_zero
const ERROR_FOR_DIVISION_BY_ZERO = 4;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_high_not_precedence
const HIGH_NOT_PRECEDENCE = 8;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_ignore_space
const IGNORE_SPACE = 16;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_create_user
const NO_AUTO_CREATE_USER = 32;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_auto_value_on_zero
const NO_AUTO_VALUE_ON_ZERO = 64;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_backslash_escapes
const NO_BACKSLASH_ESCAPES = 128;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
const NO_DIR_IN_CREATE = 256;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_dir_in_create
const NO_ENGINE_SUBSTITUTION = 512;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_field_options
const NO_FIELD_OPTIONS = 1024;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_key_options
const NO_KEY_OPTIONS = 2048;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_table_options
const NO_TABLE_OPTIONS = 4096;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_unsigned_subtraction
const NO_UNSIGNED_SUBTRACTION = 8192;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_date
const NO_ZERO_DATE = 16384;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_no_zero_in_date
const NO_ZERO_IN_DATE = 32768;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_only_full_group_by
const ONLY_FULL_GROUP_BY = 65536;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_pipes_as_concat
const PIPES_AS_CONCAT = 131072;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_real_as_float
const REAL_AS_FLOAT = 262144;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_all_tables
const STRICT_ALL_TABLES = 524288;
// https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sqlmode_strict_trans_tables
const STRICT_TRANS_TABLES = 1048576;
// Custom modes.
// The table and column names and any other field that must be escaped will
// not be.
// Reserved keywords are being escaped regardless this mode is used or not.
const NO_ENCLOSING_QUOTES = 1073741824;
/*
* Combination SQL Modes
* https://dev.mysql.com/doc/refman/5.0/en/sql-mode.html#sql-mode-combo
*/
// REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE
const SQL_MODE_ANSI = 393234;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS,
const SQL_MODE_DB2 = 138258;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER
const SQL_MODE_MAXDB = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
const SQL_MODE_MSSQL = 138258;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER
const SQL_MODE_ORACLE = 138290;
// PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS,
// NO_TABLE_OPTIONS, NO_FIELD_OPTIONS
const SQL_MODE_POSTGRESQL = 138258;
// STRICT_TRANS_TABLES, STRICT_ALL_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE,
// ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER
const SQL_MODE_TRADITIONAL = 1622052;
// -------------------------------------------------------------------------
// Keyword.
/**
* Checks if the given string is a keyword.
*
* @param string $str String to be checked.
* @param bool $isReserved Checks if the keyword is reserved.
*
* @return int
*/
public static function isKeyword($str, $isReserved = false)
{
$str = strtoupper($str);
if (isset(static::$KEYWORDS[$str])) {
if ($isReserved) {
if (!(static::$KEYWORDS[$str] & Token::FLAG_KEYWORD_RESERVED)) {
return null;
}
}
return static::$KEYWORDS[$str];
}
return null;
}
// -------------------------------------------------------------------------
// Operator.
/**
* Checks if the given string is an operator.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the operator.
*/
public static function isOperator($str)
{
if (!isset(static::$OPERATORS[$str])) {
return null;
}
return static::$OPERATORS[$str];
}
// -------------------------------------------------------------------------
// Whitespace.
/**
* Checks if the given character is a whitespace.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isWhitespace($str)
{
return ($str === ' ') || ($str === "\r") || ($str === "\n") || ($str === "\t");
}
// -------------------------------------------------------------------------
// Comment.
/**
* Checks if the given string is the beginning of a whitespace.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the comment type.
*/
public static function isComment($str)
{
$len = strlen($str);
if ($str[0] === '#') {
return Token::FLAG_COMMENT_BASH;
} elseif (($len > 1) && ($str[0] === '/') && ($str[1] === '*')) {
return (($len > 2) && ($str[2] == '!')) ?
Token::FLAG_COMMENT_MYSQL_CMD : Token::FLAG_COMMENT_C;
} elseif (($len > 1) && ($str[0] === '*') && ($str[1] === '/')) {
return Token::FLAG_COMMENT_C;
} elseif (($len > 2) && ($str[0] === '-')
&& ($str[1] === '-') && (static::isWhitespace($str[2]))
) {
return Token::FLAG_COMMENT_SQL;
}
return null;
}
// -------------------------------------------------------------------------
// Bool.
/**
* Checks if the given string is a boolean value.
* This actually check only for `TRUE` and `FALSE` because `1` or `0` are
* actually numbers and are parsed by specific methods.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isBool($str)
{
$str = strtoupper($str);
return ($str === 'TRUE') || ($str === 'FALSE');
}
// -------------------------------------------------------------------------
// Number.
/**
* Checks if the given character can be a part of a number.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isNumber($str)
{
return (($str >= '0') && ($str <= '9')) || ($str === '.')
|| ($str === '-') || ($str === '+') || ($str === 'e') || ($str === 'E');
}
// -------------------------------------------------------------------------
// Symbol.
/**
* Checks if the given character is the beginning of a symbol. A symbol
* can be either a variable or a field name.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the symbol type.
*/
public static function isSymbol($str)
{
if ($str[0] === '@') {
return Token::FLAG_SYMBOL_VARIABLE;
} elseif ($str[0] === '`') {
return Token::FLAG_SYMBOL_BACKTICK;
}
return null;
}
// -------------------------------------------------------------------------
// String.
/**
* Checks if the given character is the beginning of a string.
*
* @param string $str String to be checked.
*
* @return int The appropriate flag for the string type.
*/
public static function isString($str)
{
if ($str[0] === '\'') {
return Token::FLAG_STRING_SINGLE_QUOTES;
} elseif ($str[0] === '"') {
return Token::FLAG_STRING_DOUBLE_QUOTES;
}
return null;
}
// -------------------------------------------------------------------------
// Delimiter.
/**
* Checks if the given character can be a separator for two lexeme.
*
* @param string $str String to be checked.
*
* @return bool
*/
public static function isSeparator($str)
{
// NOTES: Only non alphanumeric ASCII characters may be separators.
// `~` is the last printable ASCII character.
return ($str <= '~') && ($str !== '_')
&& (($str < '0') || ($str > '9'))
&& (($str < 'a') || ($str > 'z'))
&& (($str < 'A') || ($str > 'Z'));
}
/**
* Loads the specified context.
*
* Contexts may be used by accessing the context directly.
*
* @param string $context Name of the context or full class name that
* defines the context.
*
* @throws \Exception If the specified context doesn't exist.
*
* @return void
*/
public static function load($context = '')
{
if (empty($context)) {
$context = self::$defaultContext;
}
if ($context[0] !== '\\') {
// Short context name (must be formatted into class name).
$context = self::$contextPrefix . $context;
}
if (!class_exists($context)) {
throw new \Exception(
'Specified context ("' . $context . '") does not exist.'
);
}
self::$loadedContext = $context;
self::$KEYWORDS = $context::$KEYWORDS;
}
/**
* Loads the context with the closest version to the one specified.
*
* The closest context is found by replacing last digits with zero until one
* is loaded successfully.
*
* @see Context::load()
*
* @param string $context Name of the context or full class name that
* defines the context.
*
* @return string The loaded context. `null` if no context was loaded.
*/
public static function loadClosest($context = '')
{
/**
* The number of replaces done by `preg_replace`.
* This actually represents whether a new context was generated or not.
*
* @var int $count
*/
$count = 0;
// As long as a new context can be generated, we try to load it.
do {
try {
// Trying to load the new context.
static::load($context);
} catch (\Exception $e) {
// If it didn't work, we are looking for a new one and skipping
// over to the next generation that will try the new context.
$context = preg_replace(
'/[1-9](0*)$/',
'0$1',
$context,
-1,
$count
);
continue;
}
// Last generated context was valid (did not throw any exceptions).
// So we return it, to let the user know what context was loaded.
return $context;
} while ($count !== 0);
return null;
}
/**
* Sets the SQL mode.
*
* @param string $mode The list of modes. If empty, the mode is reset.
*
* @return void
*/
public static function setMode($mode = '')
{
static::$MODE = 0;
if (empty($mode)) {
return;
}
$mode = explode(',', $mode);
foreach ($mode as $m) {
static::$MODE |= constant('static::' . $m);
}
}
/**
* Escapes the symbol by adding surrounding backticks.
*
* @param array|string $str The string to be escaped.
* @param string $quote Quote to be used when escaping.
*
* @return string
*/
public static function escape($str, $quote = '`')
{
if (is_array($str)) {
foreach ($str as $key => $value) {
$str[$key] = static::escape($value);
}
return $str;
}
if ((static::$MODE & Context::NO_ENCLOSING_QUOTES)
&& (!static::isKeyword($str, true))
) {
return $str;
}
if (static::$MODE & Context::ANSI_QUOTES) {
$quote = '"';
}
return $quote . str_replace($quote, $quote . $quote, $str) . $quote;
}
}
// Initializing the default context.
Context::load();

View File

@ -1,281 +0,0 @@
<?php
/**
* Context for MySQL 5.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.0/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ContextMySql50000 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
public static $KEYWORDS = array(
'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'BDB' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1,
'NEW' => 1, 'ONE' => 1, 'ROW' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'FAST' => 1,
'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1, 'LAST' => 1, 'LOGS' => 1,
'MODE' => 1, 'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PREV' => 1, 'ROWS' => 1, 'SOME' => 1, 'STOP' => 1, 'TYPE' => 1, 'VIEW' => 1,
'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1,
'FOUND' => 1, 'HOSTS' => 1, 'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1,
'MERGE' => 1, 'MUTEX' => 1, 'NAMES' => 1, 'NCHAR' => 1, 'PHASE' => 1,
'QUERY' => 1, 'QUICK' => 1, 'RAID0' => 1, 'RESET' => 1, 'RTREE' => 1,
'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1,
'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 1, 'OFFSET' => 1, 'RELOAD' => 1,
'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1, 'SIGNED' => 1, 'SIMPLE' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1,
'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1,
'EXECUTE' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INVOKER' => 1, 'MIGRATE' => 1,
'PARTIAL' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'RECOVER' => 1, 'RESTORE' => 1,
'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1, 'STORAGE' => 1, 'STRIPED' => 1,
'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1, 'UNKNOWN' => 1, 'UPGRADE' => 1,
'USE_FRM' => 1, 'VIRTUAL' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DUMPFILE' => 1, 'EXTENDED' => 1,
'FUNCTION' => 1, 'GEOMETRY' => 1, 'INNOBASE' => 1, 'LANGUAGE' => 1,
'MAX_ROWS' => 1, 'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1,
'ONE_SHOT' => 1, 'PROFILES' => 1, 'ROLLBACK' => 1, 'SECURITY' => 1,
'SHUTDOWN' => 1, 'SNAPSHOT' => 1, 'SWITCHES' => 1, 'TRIGGERS' => 1,
'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'PACK_KEYS' => 1, 'RAID_TYPE' => 1, 'REDUNDANT' => 1, 'SAVEPOINT' => 1,
'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1, 'UNDEFINED' => 1,
'VARIABLES' => 1,
'BERKELEYDB' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PRIVILEGES' => 1,
'REPEATABLE' => 1, 'ROW_FORMAT' => 1, 'SQL_THREAD' => 1, 'TABLESPACE' => 1,
'FRAC_SECOND' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'PROCESSLIST' => 1, 'RAID_CHUNKS' => 1, 'REPLICATION' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'DES_KEY_FILE' => 1, 'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1,
'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1, 'SQL_TSI_WEEK' => 1,
'SQL_TSI_YEAR' => 1,
'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'RELAY_LOG_POS' => 1,
'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'MASTER_LOG_POS' => 1,
'MASTER_SSL_KEY' => 1, 'RAID_CHUNKSIZE' => 1, 'RELAY_LOG_FILE' => 1,
'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1, 'USER_RESOURCES' => 1,
'DELAY_KEY_WRITE' => 1, 'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1,
'MASTER_SSL_CERT' => 1, 'SQL_TSI_QUARTER' => 1,
'MASTER_SERVER_ID' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3, 'USE' => 3,
'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3, 'UNION' => 3,
'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3, 'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'OPTION' => 3, 'REGEXP' => 3,
'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3, 'SONAME' => 3,
'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3,
'RESTRICT' => 3, 'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3,
'TRAILING' => 3, 'UNSIGNED' => 3, 'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3, 'DAY_SECOND' => 3,
'OPTIONALLY' => 3, 'REFERENCES' => 3, 'SQLWARNING' => 3, 'TERMINATED' => 3,
'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'INNER JOIN' => 7, 'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7,
'RIGHT JOIN' => 7,
'LINEAR HASH' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'START TRANSACTION' => 7,
'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'BINARY' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11,
'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'TRIM' => 33, 'USER' => 33,
'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ATAN2' => 33, 'COUNT' => 33, 'CRC32' => 33, 'FIELD' => 33,
'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33, 'LEAST' => 33, 'LOG10' => 33,
'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33, 'POINT' => 33, 'POWER' => 33,
'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33, 'SLEEP' => 33, 'SPACE' => 33,
'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'CONCAT' => 33, 'DECODE' => 33, 'ENCODE' => 33,
'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33, 'LENGTH' => 33,
'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33, 'SECOND' => 33,
'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'POLYGON' => 33, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33,
'SOUNDEX' => 33, 'SUBDATE' => 33, 'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33,
'TO_DAYS' => 33, 'VAR_POP' => 33, 'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33,
'CONTAINS' => 33, 'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33,
'DISJOINT' => 33, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33, 'CONCAT_WS' => 33,
'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33, 'FROM_DAYS' => 33,
'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'LINESTRING' => 33,
'MBRTOUCHES' => 33, 'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33,
'STARTPOINT' => 33, 'STDDEV_POP' => 33, 'UNCOMPRESS' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'GEOMFROMWKB' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'GEOMETRYTYPE' => 33,
'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33, 'IS_FREE_LOCK' => 33,
'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33, 'MLINEFROMWKB' => 33,
'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33, 'OCTET_LENGTH' => 33,
'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33,
'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'MULTILINESTRING' => 33,
'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'NUMINTERIORRINGS' => 33,
'GEOMETRYCOLLECTION' => 33,
'UNCOMPRESSED_LENGTH' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -1,305 +0,0 @@
<?php
/**
* Context for MySQL 5.1.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.1/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.1.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ContextMySql50100 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'BDB' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1,
'NEW' => 1, 'ONE' => 1, 'ROW' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'GOTO' => 1, 'HASH' => 1,
'HELP' => 1, 'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1,
'MODE' => 1, 'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'ROWS' => 1, 'SOME' => 1, 'STOP' => 1, 'THAN' => 1,
'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'EVENT' => 1, 'EVERY' => 1, 'FIRST' => 1,
'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1, 'LABEL' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'OWNER' => 1, 'PHASE' => 1, 'QUERY' => 1,
'QUICK' => 1, 'RAID0' => 1, 'RESET' => 1, 'RTREE' => 1, 'SHARE' => 1,
'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1, 'TYPES' => 1,
'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 1, 'OFFSET' => 1, 'PARSER' => 1,
'PLUGIN' => 1, 'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1,
'ROLLUP' => 1, 'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1,
'SONAME' => 1, 'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1,
'STRING' => 1, 'TABLES' => 1,
'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1,
'CONTEXT' => 1, 'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1,
'ENGINES' => 1, 'EXECUTE' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1,
'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1,
'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1,
'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1,
'STORAGE' => 1, 'STRIPED' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'VIRTUAL' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 1, 'INNOBASE' => 1,
'LANGUAGE' => 1, 'MAXVALUE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1,
'MIN_ROWS' => 1, 'NATIONAL' => 1, 'NVARCHAR' => 1, 'ONE_SHOT' => 1,
'PRESERVE' => 1, 'PROFILES' => 1, 'REDOFILE' => 1, 'ROLLBACK' => 1,
'SCHEDULE' => 1, 'SECURITY' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1,
'SWITCHES' => 1, 'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'PARTITION' => 1, 'RAID_TYPE' => 1,
'READ_ONLY' => 1, 'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SCHEDULER' => 1,
'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1, 'UNDEFINED' => 1,
'UNINSTALL' => 1, 'VARIABLES' => 1,
'BERKELEYDB' => 1, 'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1,
'CONNECTION' => 1, 'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1,
'MASTER_SSL' => 1, 'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1,
'PRIVILEGES' => 1, 'REORGANISE' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1,
'ROW_FORMAT' => 1, 'SQL_THREAD' => 1, 'TABLESPACE' => 1,
'EXTENT_SIZE' => 1, 'FRAC_SECOND' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1,
'MASTER_USER' => 1, 'PROCESSLIST' => 1, 'RAID_CHUNKS' => 1, 'REPLICATION' => 1,
'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CONTRIBUTORS' => 1, 'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 1,
'PARTITIONING' => 1, 'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1,
'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1, 'SQL_TSI_WEEK' => 1,
'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'PAGE_CHECKSUM' => 1,
'RELAY_LOG_POS' => 1, 'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'TRANSACTIONAL' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1,
'MASTER_LOG_POS' => 1, 'MASTER_SSL_KEY' => 1, 'RAID_CHUNKSIZE' => 1,
'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1,
'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'DELAY_KEY_WRITE' => 1, 'MASTER_LOG_FILE' => 1,
'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1, 'SQL_TSI_QUARTER' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'UNDO_BUFFER_SIZE' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3, 'USE' => 3,
'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 3, 'MODIFIES' => 3, 'OPTIMIZE' => 3,
'RESTRICT' => 3, 'SPECIFIC' => 3, 'SQLSTATE' => 3, 'STARTING' => 3,
'TRAILING' => 3, 'UNSIGNED' => 3, 'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'INNER JOIN' => 7, 'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7,
'RIGHT JOIN' => 7,
'LINEAR HASH' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'START TRANSACTION' => 7,
'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'BINARY' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11,
'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'TRIM' => 33, 'USER' => 33,
'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'DECOD' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33,
'LCASE' => 33, 'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33,
'MONTH' => 33, 'POINT' => 33, 'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33,
'RTRIM' => 33, 'SLEEP' => 33, 'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33,
'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'CONCAT' => 33, 'ENCODE' => 33, 'EQUALS' => 33,
'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33, 'LENGTH' => 33, 'LOCATE' => 33,
'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33, 'SECOND' => 33, 'STDDEV' => 33,
'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'POLYGON' => 33, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33,
'SOUNDEX' => 33, 'SUBDATE' => 33, 'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33,
'TO_DAYS' => 33, 'VAR_POP' => 33, 'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33,
'CONTAINS' => 33, 'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33,
'DISJOINT' => 33, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33, 'CONCAT_WS' => 33,
'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33, 'FROM_DAYS' => 33,
'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'LINESTRING' => 33,
'MBRTOUCHES' => 33, 'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33,
'STARTPOINT' => 33, 'STDDEV_POP' => 33, 'UNCOMPRESS' => 33, 'UUID_SHORT' => 33,
'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'GEOMFROMWKB' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33,
'GEOMETRYTYPE' => 33, 'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33,
'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33,
'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33,
'POLYFROMTEXT' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33,
'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'MULTILINESTRING' => 33,
'POLYGONFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'GEOMETRYCOLLECTION' => 33, 'MULTIPOINTFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -1,309 +0,0 @@
<?php
/**
* Context for MySQL 5.5.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.5/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.5.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ContextMySql50500 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'OPEN' => 1, 'PAGE' => 1, 'PORT' => 1,
'PREV' => 1, 'ROWS' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1, 'THAN' => 1,
'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'OWNER' => 1, 'PHASE' => 1, 'PROXY' => 1,
'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1, 'RTREE' => 1,
'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1,
'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'FAULTS' => 1, 'FIELDS' => 1, 'GLOBAL' => 1, 'GRANTS' => 1,
'IMPORT' => 1, 'INNODB' => 1, 'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1,
'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 1, 'OFFSET' => 1, 'PARSER' => 1,
'PLUGIN' => 1, 'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1,
'ROLLUP' => 1, 'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1,
'SONAME' => 1, 'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1,
'STRING' => 1, 'TABLES' => 1,
'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1, 'COMPACT' => 1,
'CONTEXT' => 1, 'DEFINER' => 1, 'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1,
'ENGINES' => 1, 'EXECUTE' => 1, 'GENERAL' => 1, 'HANDLER' => 1, 'INDEXES' => 1,
'INSTALL' => 1, 'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1,
'OPTIONS' => 1, 'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1,
'REBUILD' => 1, 'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1,
'SESSION' => 1, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'VIRTUAL' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 1, 'INNOBASE' => 1,
'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1, 'MIN_ROWS' => 1,
'NATIONAL' => 1, 'NVARCHAR' => 1, 'ONE_SHOT' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1,
'SCHEDULE' => 1, 'SECURITY' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1,
'SWITCHES' => 1, 'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'PARTITION' => 1, 'READ_ONLY' => 1,
'REDUNDANT' => 1, 'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1,
'TEMPTABLE' => 1, 'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PRIVILEGES' => 1,
'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1, 'SQL_THREAD' => 1,
'TABLESPACE' => 1, 'TABLE_NAME' => 1,
'COLUMN_NAME' => 1, 'CURSOR_NAME' => 1, 'EXTENT_SIZE' => 1, 'FRAC_SECOND' => 1,
'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1, 'MYSQL_ERRNO' => 1,
'PROCESSLIST' => 1, 'REPLICATION' => 1, 'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'CONTRIBUTORS' => 1,
'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 1, 'MESSAGE_TEXT' => 1,
'PARTITIONING' => 1, 'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1,
'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1, 'SQL_TSI_WEEK' => 1,
'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1, 'RELAY_LOG_POS' => 1,
'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1,
'MASTER_LOG_POS' => 1, 'MASTER_SSL_KEY' => 1, 'RELAY_LOG_FILE' => 1,
'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1, 'TABLE_CHECKSUM' => 1,
'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1,
'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'IGNORE_SERVER_IDS' => 1, 'MASTER_SSL_CAPATH' => 1,
'MASTER_SSL_CIPHER' => 1, 'SQL_BUFFER_RESULT' => 1,
'CONSTRAINT_CATALOG' => 1,
'SQL_TSI_FRAC_SECOND' => 1,
'MASTER_CONNECT_RETRY' => 1, 'MAX_QUERIES_PER_HOUR' => 1,
'MAX_UPDATES_PER_HOUR' => 1, 'MAX_USER_CONNECTIONS' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3, 'USE' => 3,
'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 3, 'MAXVALUE' => 3, 'MODIFIES' => 3,
'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3, 'SPECIFIC' => 3,
'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PRECISION' => 3,
'PROCEDURE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'INNER JOIN' => 7, 'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7,
'RIGHT JOIN' => 7,
'LINEAR HASH' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'START TRANSACTION' => 7,
'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'BINARY' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11,
'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'TRIM' => 33,
'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POINT' => 33, 'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33,
'SLEEP' => 33, 'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'CONCAT' => 33, 'DECODE' => 33, 'ENCODE' => 33,
'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33, 'LENGTH' => 33,
'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33, 'SECOND' => 33,
'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'POLYGON' => 33, 'QUARTER' => 33, 'RADIANS' => 33, 'REVERSE' => 33,
'SOUNDEX' => 33, 'SUBDATE' => 33, 'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33,
'TO_DAYS' => 33, 'VAR_POP' => 33, 'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33,
'CONTAINS' => 33, 'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33,
'DISJOINT' => 33, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33, 'CONCAT_WS' => 33,
'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33, 'FROM_DAYS' => 33,
'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'SUBSTRING' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INTERSECTS' => 33, 'LINESTRING' => 33,
'MBRTOUCHES' => 33, 'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33,
'STARTPOINT' => 33, 'STDDEV_POP' => 33, 'TO_SECONDS' => 33, 'UNCOMPRESS' => 33,
'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'GEOMFROMWKB' => 33,
'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33, 'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33,
'MICROSECOND' => 33, 'PERIOD_DIFF' => 33, 'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33,
'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33,
'GEOMETRYTYPE' => 33, 'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33,
'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33,
'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33,
'POLYFROMTEXT' => 33, 'RELEASE_LOCK' => 33, 'SESSION_USER' => 33,
'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'INTERIORRINGN' => 33,
'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33,
'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33,
'TIMESTAMPDIFF' => 33,
'LAST_INSERT_ID' => 33, 'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33,
'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'MULTILINESTRING' => 33,
'POLYGONFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33,
'GEOMETRYCOLLECTION' => 33, 'MULTIPOINTFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -1,340 +0,0 @@
<?php
/**
* Context for MySQL 5.6.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.6/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.6.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ContextMySql50600 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'ONLY' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'ROWS' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1,
'THAN' => 1, 'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'OWNER' => 1, 'PHASE' => 1, 'PROXY' => 1,
'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1, 'RTREE' => 1,
'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1, 'SWAPS' => 1,
'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1, 'CLIENT' => 1,
'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1, 'ESCAPE' => 1,
'EVENTS' => 1, 'EXPIRE' => 1, 'EXPORT' => 1, 'FAULTS' => 1, 'FIELDS' => 1,
'GLOBAL' => 1, 'GRANTS' => 1, 'IMPORT' => 1, 'ISSUER' => 1, 'LEAVES' => 1,
'MASTER' => 1, 'MEDIUM' => 1, 'MEMORY' => 1, 'MODIFY' => 1, 'NUMBER' => 1,
'OFFSET' => 1, 'PARSER' => 1, 'PLUGIN' => 1, 'RELOAD' => 1, 'REMOVE' => 1,
'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1, 'SERVER' => 1, 'SIGNED' => 1,
'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1, 'SOUNDS' => 1, 'SOURCE' => 1,
'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1, 'TABLES' => 1,
'ANALYSE' => 1, 'AUTHORS' => 1, 'CHANGED' => 1, 'COLUMNS' => 1, 'COMMENT' => 1,
'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1, 'DISABLE' => 1,
'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 1, 'GENERAL' => 1,
'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1, 'INVOKER' => 1, 'LOGFILE' => 1,
'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1, 'PARTIAL' => 1, 'PLUGINS' => 1,
'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1, 'RECOVER' => 1, 'RESTORE' => 1,
'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1, 'STORAGE' => 1, 'SUBJECT' => 1,
'SUSPEND' => 1, 'UNICODE' => 1, 'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1,
'VIRTUAL' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXCHANGE' => 1, 'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 1,
'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1, 'MIN_ROWS' => 1,
'NATIONAL' => 1, 'NVARCHAR' => 1, 'ONE_SHOT' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1,
'SCHEDULE' => 1, 'SECURITY' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1,
'SWITCHES' => 1, 'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'READ_ONLY' => 1, 'REDUNDANT' => 1,
'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1,
'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PLUGIN_DIR' => 1,
'PRIVILEGES' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1,
'SQL_THREAD' => 1, 'TABLESPACE' => 1, 'TABLE_NAME' => 1,
'COLUMN_NAME' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1, 'EXTENT_SIZE' => 1,
'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1, 'MYSQL_ERRNO' => 1,
'PROCESSLIST' => 1, 'REPLICATION' => 1, 'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1,
'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'CONTRIBUTORS' => 1,
'DEFAULT_AUTH' => 1, 'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 1,
'MASTER_DELAY' => 1, 'MESSAGE_TEXT' => 1, 'PARTITIONING' => 1,
'RELAY_THREAD' => 1, 'SERIALIZABLE' => 1, 'SQL_NO_CACHE' => 1,
'SQL_TSI_HOUR' => 1, 'SQL_TSI_WEEK' => 1, 'SQL_TSI_YEAR' => 1,
'SUBPARTITION' => 1,
'COLUMN_FORMAT' => 1, 'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1,
'RELAY_LOG_POS' => 1, 'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1,
'MASTER_LOG_POS' => 1, 'MASTER_SSL_CRL' => 1, 'MASTER_SSL_KEY' => 1,
'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1,
'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1,
'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1, 'MASTER_SSL_CERT' => 1,
'SQL_AFTER_GTIDS' => 1, 'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'SQL_BEFORE_GTIDS' => 1,
'STATS_PERSISTENT' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'IGNORE_SERVER_IDS' => 1, 'MASTER_SSL_CAPATH' => 1,
'MASTER_SSL_CIPHER' => 1, 'RETURNED_SQLSTATE' => 1, 'SQL_BUFFER_RESULT' => 1,
'STATS_AUTO_RECALC' => 1,
'CONSTRAINT_CATALOG' => 1, 'MASTER_RETRY_COUNT' => 1, 'MASTER_SSL_CRLPATH' => 1,
'SQL_AFTER_MTS_GAPS' => 1, 'STATS_SAMPLE_PAGES' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1,
'MAX_QUERIES_PER_HOUR' => 1, 'MAX_UPDATES_PER_HOUR' => 1,
'MAX_USER_CONNECTIONS' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'GET' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3,
'USE' => 3, 'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 3, 'MAXVALUE' => 3, 'MODIFIES' => 3,
'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3, 'SPECIFIC' => 3,
'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'MIDDLEINT' => 3, 'PARTITION' => 3,
'PRECISION' => 3, 'PROCEDURE' => 3, 'SENSITIVE' => 3, 'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'MASTER_BIND' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'IO_AFTER_GTIDS' => 3, 'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3, 'IO_BEFORE_GTIDS' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'INNER JOIN' => 7, 'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7,
'RIGHT JOIN' => 7,
'LINEAR HASH' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'START TRANSACTION' => 7,
'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'BINARY' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11,
'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'ST_X' => 33,
'ST_Y' => 33, 'TRIM' => 33, 'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POINT' => 33, 'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33,
'SLEEP' => 33, 'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'BUFFER' => 33, 'CONCAT' => 33, 'DECODE' => 33,
'ENCODE' => 33, 'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33,
'LENGTH' => 33, 'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33,
'SECOND' => 33, 'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'IS_IPV4' => 33, 'IS_IPV6' => 33, 'POLYGON' => 33, 'QUARTER' => 33,
'RADIANS' => 33, 'REVERSE' => 33, 'SOUNDEX' => 33, 'ST_AREA' => 33, 'ST_SRID' => 33,
'SUBDATE' => 33, 'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33, 'TO_DAYS' => 33,
'VAR_POP' => 33, 'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33,
'CONTAINS' => 33, 'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33,
'DISJOINT' => 33, 'ENDPOINT' => 33, 'ENVELOPE' => 33, 'GET_LOCK' => 33,
'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33, 'MAKEDATE' => 33,
'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33, 'OVERLAPS' => 33,
'PASSWORD' => 33, 'POSITION' => 33, 'ST_ASWKB' => 33, 'ST_ASWKT' => 33,
'ST_UNION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33, 'VARIANCE' => 33,
'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33, 'CONCAT_WS' => 33,
'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33, 'FROM_DAYS' => 33,
'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33, 'LOAD_FILE' => 33,
'MBRWITHIN' => 33, 'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33,
'ST_ASTEXT' => 33, 'ST_BUFFER' => 33, 'ST_EQUALS' => 33, 'ST_POINTN' => 33,
'ST_WITHIN' => 33, 'SUBSTRING' => 33, 'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'DAYOFMONTH' => 33, 'EXPORT_SET' => 33,
'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33, 'INET6_NTOA' => 33,
'INTERSECTS' => 33, 'LINESTRING' => 33, 'MBRTOUCHES' => 33, 'MULTIPOINT' => 33,
'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33, 'STDDEV_POP' => 33,
'ST_CROSSES' => 33, 'ST_ISEMPTY' => 33, 'ST_TOUCHES' => 33, 'TO_SECONDS' => 33,
'UNCOMPRESS' => 33, 'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'FROM_BASE64' => 33,
'GEOMFROMWKB' => 33, 'GTID_SUBSET' => 33, 'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33,
'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33, 'MICROSECOND' => 33, 'PERIOD_DIFF' => 33,
'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33, 'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33,
'ST_ASBINARY' => 33, 'ST_CENTROID' => 33, 'ST_CONTAINS' => 33, 'ST_DISJOINT' => 33,
'ST_DISTANCE' => 33, 'ST_ENDPOINT' => 33, 'ST_ENVELOPE' => 33, 'ST_ISCLOSED' => 33,
'ST_ISSIMPLE' => 33, 'ST_OVERLAPS' => 33, 'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33,
'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33,
'GEOMETRYTYPE' => 33, 'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33,
'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33,
'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33, 'MULTIPOLYGON' => 33,
'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33, 'POINTFROMWKB' => 33,
'POLYFROMTEXT' => 33, 'RANDOM_BYTES' => 33, 'RELEASE_LOCK' => 33,
'SESSION_USER' => 33, 'ST_DIMENSION' => 33, 'ST_GEOMETRYN' => 33,
'ST_NUMPOINTS' => 33, 'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'CREATE_DIGEST' => 33, 'FROM_UNIXTIME' => 33,
'GTID_SUBTRACT' => 33, 'INTERIORRINGN' => 33, 'MBRINTERSECTS' => 33,
'MLINEFROMTEXT' => 33, 'MPOINTFROMWKB' => 33, 'MPOLYFROMTEXT' => 33,
'NUMGEOMETRIES' => 33, 'POINTFROMTEXT' => 33, 'ST_DIFFERENCE' => 33,
'ST_INTERSECTS' => 33, 'ST_STARTPOINT' => 33, 'TIMESTAMPDIFF' => 33,
'WEIGHT_STRING' => 33,
'IS_IPV4_COMPAT' => 33, 'IS_IPV4_MAPPED' => 33, 'LAST_INSERT_ID' => 33,
'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33, 'ST_GEOMFROMWKB' => 33,
'ST_LINEFROMWKB' => 33, 'ST_POLYFROMWKB' => 33, 'UNIX_TIMESTAMP' => 33,
'ASYMMETRIC_SIGN' => 33, 'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33,
'MULTILINESTRING' => 33, 'POLYGONFROMTEXT' => 33, 'ST_EXTERIORRING' => 33,
'ST_GEOMETRYTYPE' => 33, 'ST_GEOMFROMTEXT' => 33, 'ST_INTERSECTION' => 33,
'ST_LINEFROMTEXT' => 33, 'ST_POINTFROMWKB' => 33, 'ST_POLYFROMTEXT' => 33,
'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33, 'ST_NUMGEOMETRIES' => 33,
'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'ASYMMETRIC_DERIVE' => 33, 'ASYMMETRIC_VERIFY' => 33, 'LINESTRINGFROMWKB' => 33,
'MULTIPOINTFROMWKB' => 33, 'ST_POLYGONFROMWKB' => 33,
'ASYMMETRIC_DECRYPT' => 33, 'ASYMMETRIC_ENCRYPT' => 33, 'GEOMETRYCOLLECTION' => 33,
'MULTIPOINTFROMTEXT' => 33, 'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33,
'ST_POLYGONFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33, 'ST_GEOMETRYFROMTEXT' => 33,
'ST_NUMINTERIORRINGS' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'CREATE_DH_PARAMETERS' => 33, 'MULTIPOLYGONFROMTEXT' => 33,
'ST_LINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33,
'CREATE_ASYMMETRIC_PUB_KEY' => 33, 'GEOMETRYCOLLECTIONFROMWKB' => 33,
'CREATE_ASYMMETRIC_PRIV_KEY' => 33, 'GEOMETRYCOLLECTIONFROMTEXT' => 33,
'VALIDATE_PASSWORD_STRENGTH' => 33,
'SQL_THREAD_WAIT_AFTER_GTIDS' => 33,
'ST_GEOMETRYCOLLECTIONFROMWKB' => 33,
'ST_GEOMETRYCOLLECTIONFROMTEXT' => 33,
'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -1,351 +0,0 @@
<?php
/**
* Context for MySQL 5.7.
*
* This file was auto-generated.
*
* @package SqlParser
* @subpackage Contexts
* @link https://dev.mysql.com/doc/refman/5.7/en/keywords.html
*/
namespace SqlParser\Contexts;
use SqlParser\Context;
/**
* Context for MySQL 5.7.
*
* @category Contexts
* @package SqlParser
* @subpackage Contexts
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ContextMySql50700 extends Context
{
/**
* List of keywords.
*
* The value associated to each keyword represents its flags.
*
* @see Token::FLAG_KEYWORD_*
*
* @var array
*/
public static $KEYWORDS = array(
'AT' => 1, 'DO' => 1, 'IO' => 1, 'NO' => 1, 'XA' => 1,
'ANY' => 1, 'CPU' => 1, 'END' => 1, 'IPC' => 1, 'NDB' => 1, 'NEW' => 1,
'ONE' => 1, 'ROW' => 1, 'XID' => 1,
'BOOL' => 1, 'BYTE' => 1, 'CODE' => 1, 'CUBE' => 1, 'DATA' => 1, 'DISK' => 1,
'ENDS' => 1, 'FAST' => 1, 'FILE' => 1, 'FULL' => 1, 'HASH' => 1, 'HELP' => 1,
'HOST' => 1, 'LAST' => 1, 'LESS' => 1, 'LIST' => 1, 'LOGS' => 1, 'MODE' => 1,
'NAME' => 1, 'NEXT' => 1, 'NONE' => 1, 'ONLY' => 1, 'OPEN' => 1, 'PAGE' => 1,
'PORT' => 1, 'PREV' => 1, 'ROWS' => 1, 'SLOW' => 1, 'SOME' => 1, 'STOP' => 1,
'THAN' => 1, 'TYPE' => 1, 'VIEW' => 1, 'WAIT' => 1, 'WORK' => 1, 'X509' => 1,
'AFTER' => 1, 'BEGIN' => 1, 'BLOCK' => 1, 'BTREE' => 1, 'CACHE' => 1,
'CHAIN' => 1, 'CLOSE' => 1, 'ERROR' => 1, 'EVENT' => 1, 'EVERY' => 1,
'FIRST' => 1, 'FIXED' => 1, 'FLUSH' => 1, 'FOUND' => 1, 'HOSTS' => 1,
'LEVEL' => 1, 'LOCAL' => 1, 'LOCKS' => 1, 'MERGE' => 1, 'MUTEX' => 1,
'NAMES' => 1, 'NCHAR' => 1, 'NEVER' => 1, 'OWNER' => 1, 'PHASE' => 1,
'PROXY' => 1, 'QUERY' => 1, 'QUICK' => 1, 'RELAY' => 1, 'RESET' => 1,
'RTREE' => 1, 'SHARE' => 1, 'SLAVE' => 1, 'START' => 1, 'SUPER' => 1,
'SWAPS' => 1, 'TYPES' => 1, 'UNTIL' => 1, 'VALUE' => 1,
'ACTION' => 1, 'ALWAYS' => 1, 'BACKUP' => 1, 'BINLOG' => 1, 'CIPHER' => 1,
'CLIENT' => 1, 'COMMIT' => 1, 'ENABLE' => 1, 'ENGINE' => 1, 'ERRORS' => 1,
'ESCAPE' => 1, 'EVENTS' => 1, 'EXPIRE' => 1, 'EXPORT' => 1, 'FAULTS' => 1,
'FIELDS' => 1, 'FILTER' => 1, 'GLOBAL' => 1, 'GRANTS' => 1, 'IMPORT' => 1,
'ISSUER' => 1, 'LEAVES' => 1, 'MASTER' => 1, 'MEDIUM' => 1, 'MEMORY' => 1,
'MODIFY' => 1, 'NUMBER' => 1, 'OFFSET' => 1, 'PARSER' => 1, 'PLUGIN' => 1,
'RELOAD' => 1, 'REMOVE' => 1, 'REPAIR' => 1, 'RESUME' => 1, 'ROLLUP' => 1,
'SERVER' => 1, 'SIGNED' => 1, 'SIMPLE' => 1, 'SOCKET' => 1, 'SONAME' => 1,
'SOUNDS' => 1, 'SOURCE' => 1, 'STARTS' => 1, 'STATUS' => 1, 'STRING' => 1,
'TABLES' => 1,
'ACCOUNT' => 1, 'ANALYSE' => 1, 'CHANGED' => 1, 'CHANNEL' => 1, 'COLUMNS' => 1,
'COMMENT' => 1, 'COMPACT' => 1, 'CONTEXT' => 1, 'CURRENT' => 1, 'DEFINER' => 1,
'DISABLE' => 1, 'DISCARD' => 1, 'DYNAMIC' => 1, 'ENGINES' => 1, 'EXECUTE' => 1,
'FOLLOWS' => 1, 'GENERAL' => 1, 'HANDLER' => 1, 'INDEXES' => 1, 'INSTALL' => 1,
'INVOKER' => 1, 'LOGFILE' => 1, 'MIGRATE' => 1, 'NO_WAIT' => 1, 'OPTIONS' => 1,
'PARTIAL' => 1, 'PLUGINS' => 1, 'PREPARE' => 1, 'PROFILE' => 1, 'REBUILD' => 1,
'RECOVER' => 1, 'RESTORE' => 1, 'RETURNS' => 1, 'ROUTINE' => 1, 'SESSION' => 1,
'STACKED' => 1, 'STORAGE' => 1, 'SUBJECT' => 1, 'SUSPEND' => 1, 'UNICODE' => 1,
'UNKNOWN' => 1, 'UPGRADE' => 1, 'USE_FRM' => 1, 'WITHOUT' => 1, 'WRAPPER' => 1,
'CASCADED' => 1, 'CHECKSUM' => 1, 'DATAFILE' => 1, 'DUMPFILE' => 1,
'EXCHANGE' => 1, 'EXTENDED' => 1, 'FUNCTION' => 1, 'GEOMETRY' => 1,
'LANGUAGE' => 1, 'MAX_ROWS' => 1, 'MAX_SIZE' => 1, 'MIN_ROWS' => 1,
'NATIONAL' => 1, 'NVARCHAR' => 1, 'PRECEDES' => 1, 'PRESERVE' => 1,
'PROFILES' => 1, 'REDOFILE' => 1, 'RELAYLOG' => 1, 'ROLLBACK' => 1,
'SCHEDULE' => 1, 'SECURITY' => 1, 'SHUTDOWN' => 1, 'SNAPSHOT' => 1,
'SWITCHES' => 1, 'TRIGGERS' => 1, 'UNDOFILE' => 1, 'WARNINGS' => 1,
'AGGREGATE' => 1, 'ALGORITHM' => 1, 'COMMITTED' => 1, 'DIRECTORY' => 1,
'DUPLICATE' => 1, 'EXPANSION' => 1, 'IO_THREAD' => 1, 'ISOLATION' => 1,
'NODEGROUP' => 1, 'PACK_KEYS' => 1, 'READ_ONLY' => 1, 'REDUNDANT' => 1,
'SAVEPOINT' => 1, 'SQL_CACHE' => 1, 'TEMPORARY' => 1, 'TEMPTABLE' => 1,
'UNDEFINED' => 1, 'UNINSTALL' => 1, 'VARIABLES' => 1,
'COMPLETION' => 1, 'COMPRESSED' => 1, 'CONCURRENT' => 1, 'CONNECTION' => 1,
'CONSISTENT' => 1, 'DEALLOCATE' => 1, 'IDENTIFIED' => 1, 'MASTER_SSL' => 1,
'NDBCLUSTER' => 1, 'PARTITIONS' => 1, 'PERSISTENT' => 1, 'PLUGIN_DIR' => 1,
'PRIVILEGES' => 1, 'REORGANIZE' => 1, 'REPEATABLE' => 1, 'ROW_FORMAT' => 1,
'SQL_THREAD' => 1, 'TABLESPACE' => 1, 'TABLE_NAME' => 1, 'VALIDATION' => 1,
'COLUMN_NAME' => 1, 'COMPRESSION' => 1, 'CURSOR_NAME' => 1, 'DIAGNOSTICS' => 1,
'EXTENT_SIZE' => 1, 'MASTER_HOST' => 1, 'MASTER_PORT' => 1, 'MASTER_USER' => 1,
'MYSQL_ERRNO' => 1, 'NONBLOCKING' => 1, 'PROCESSLIST' => 1, 'REPLICATION' => 1,
'SCHEMA_NAME' => 1, 'SQL_TSI_DAY' => 1, 'TRANSACTION' => 1, 'UNCOMMITTED' => 1,
'CATALOG_NAME' => 1, 'CLASS_ORIGIN' => 1, 'DEFAULT_AUTH' => 1,
'DES_KEY_FILE' => 1, 'INITIAL_SIZE' => 1, 'MASTER_DELAY' => 1,
'MESSAGE_TEXT' => 1, 'PARTITIONING' => 1, 'RELAY_THREAD' => 1,
'SERIALIZABLE' => 1, 'SQL_NO_CACHE' => 1, 'SQL_TSI_HOUR' => 1,
'SQL_TSI_WEEK' => 1, 'SQL_TSI_YEAR' => 1, 'SUBPARTITION' => 1,
'COLUMN_FORMAT' => 1, 'INSERT_METHOD' => 1, 'MASTER_SSL_CA' => 1,
'RELAY_LOG_POS' => 1, 'SQL_TSI_MONTH' => 1, 'SUBPARTITIONS' => 1,
'AUTO_INCREMENT' => 1, 'AVG_ROW_LENGTH' => 1, 'KEY_BLOCK_SIZE' => 1,
'MASTER_LOG_POS' => 1, 'MASTER_SSL_CRL' => 1, 'MASTER_SSL_KEY' => 1,
'RELAY_LOG_FILE' => 1, 'SQL_TSI_MINUTE' => 1, 'SQL_TSI_SECOND' => 1,
'TABLE_CHECKSUM' => 1, 'USER_RESOURCES' => 1,
'AUTOEXTEND_SIZE' => 1, 'CONSTRAINT_NAME' => 1, 'DELAY_KEY_WRITE' => 1,
'FILE_BLOCK_SIZE' => 1, 'MASTER_LOG_FILE' => 1, 'MASTER_PASSWORD' => 1,
'MASTER_SSL_CERT' => 1, 'PARSE_GCOL_EXPR' => 1, 'REPLICATE_DO_DB' => 1,
'SQL_AFTER_GTIDS' => 1, 'SQL_TSI_QUARTER' => 1, 'SUBCLASS_ORIGIN' => 1,
'MASTER_SERVER_ID' => 1, 'REDO_BUFFER_SIZE' => 1, 'SQL_BEFORE_GTIDS' => 1,
'STATS_PERSISTENT' => 1, 'UNDO_BUFFER_SIZE' => 1,
'CONSTRAINT_SCHEMA' => 1, 'GROUP_REPLICATION' => 1, 'IGNORE_SERVER_IDS' => 1,
'MASTER_SSL_CAPATH' => 1, 'MASTER_SSL_CIPHER' => 1, 'RETURNED_SQLSTATE' => 1,
'SQL_BUFFER_RESULT' => 1, 'STATS_AUTO_RECALC' => 1,
'CONSTRAINT_CATALOG' => 1, 'MASTER_RETRY_COUNT' => 1, 'MASTER_SSL_CRLPATH' => 1,
'MAX_STATEMENT_TIME' => 1, 'REPLICATE_DO_TABLE' => 1, 'SQL_AFTER_MTS_GAPS' => 1,
'STATS_SAMPLE_PAGES' => 1,
'REPLICATE_IGNORE_DB' => 1,
'MASTER_AUTO_POSITION' => 1, 'MASTER_CONNECT_RETRY' => 1,
'MAX_QUERIES_PER_HOUR' => 1, 'MAX_UPDATES_PER_HOUR' => 1,
'MAX_USER_CONNECTIONS' => 1, 'REPLICATE_REWRITE_DB' => 1,
'REPLICATE_IGNORE_TABLE' => 1,
'MASTER_HEARTBEAT_PERIOD' => 1, 'REPLICATE_WILD_DO_TABLE' => 1,
'MAX_CONNECTIONS_PER_HOUR' => 1,
'REPLICATE_WILD_IGNORE_TABLE' => 1,
'AS' => 3, 'BY' => 3, 'IS' => 3, 'ON' => 3, 'OR' => 3, 'TO' => 3,
'ADD' => 3, 'ALL' => 3, 'AND' => 3, 'ASC' => 3, 'DEC' => 3, 'DIV' => 3,
'FOR' => 3, 'GET' => 3, 'NOT' => 3, 'OUT' => 3, 'SQL' => 3, 'SSL' => 3,
'USE' => 3, 'XOR' => 3,
'BOTH' => 3, 'CALL' => 3, 'CASE' => 3, 'DESC' => 3, 'DROP' => 3, 'DUAL' => 3,
'EACH' => 3, 'ELSE' => 3, 'EXIT' => 3, 'FROM' => 3, 'INT1' => 3, 'INT2' => 3,
'INT3' => 3, 'INT4' => 3, 'INT8' => 3, 'INTO' => 3, 'JOIN' => 3, 'KEYS' => 3,
'KILL' => 3, 'LIKE' => 3, 'LOAD' => 3, 'LOCK' => 3, 'LONG' => 3, 'LOOP' => 3,
'NULL' => 3, 'READ' => 3, 'SHOW' => 3, 'THEN' => 3, 'TRUE' => 3, 'UNDO' => 3,
'WHEN' => 3, 'WITH' => 3,
'ALTER' => 3, 'CHECK' => 3, 'CROSS' => 3, 'FALSE' => 3, 'FETCH' => 3,
'FORCE' => 3, 'GRANT' => 3, 'GROUP' => 3, 'INNER' => 3, 'INOUT' => 3,
'LEAVE' => 3, 'LIMIT' => 3, 'LINES' => 3, 'ORDER' => 3, 'OUTER' => 3,
'PURGE' => 3, 'RANGE' => 3, 'READS' => 3, 'RLIKE' => 3, 'TABLE' => 3,
'UNION' => 3, 'USAGE' => 3, 'USING' => 3, 'WHERE' => 3, 'WHILE' => 3,
'WRITE' => 3,
'BEFORE' => 3, 'CHANGE' => 3, 'COLUMN' => 3, 'CREATE' => 3, 'CURSOR' => 3,
'DELETE' => 3, 'ELSEIF' => 3, 'EXISTS' => 3, 'FLOAT4' => 3, 'FLOAT8' => 3,
'HAVING' => 3, 'IGNORE' => 3, 'INFILE' => 3, 'LINEAR' => 3, 'OPTION' => 3,
'REGEXP' => 3, 'RENAME' => 3, 'RETURN' => 3, 'REVOKE' => 3, 'SELECT' => 3,
'SIGNAL' => 3, 'STORED' => 3, 'UNLOCK' => 3, 'UPDATE' => 3,
'ANALYZE' => 3, 'BETWEEN' => 3, 'CASCADE' => 3, 'COLLATE' => 3, 'DECLARE' => 3,
'DELAYED' => 3, 'ESCAPED' => 3, 'EXPLAIN' => 3, 'FOREIGN' => 3, 'ITERATE' => 3,
'LEADING' => 3, 'NATURAL' => 3, 'OUTFILE' => 3, 'PRIMARY' => 3, 'RELEASE' => 3,
'REQUIRE' => 3, 'SCHEMAS' => 3, 'SPATIAL' => 3, 'TRIGGER' => 3, 'VARYING' => 3,
'VIRTUAL' => 3,
'CONTINUE' => 3, 'DAY_HOUR' => 3, 'DESCRIBE' => 3, 'DISTINCT' => 3,
'ENCLOSED' => 3, 'FULLTEXT' => 3, 'MAXVALUE' => 3, 'MODIFIES' => 3,
'OPTIMIZE' => 3, 'RESIGNAL' => 3, 'RESTRICT' => 3, 'SPECIFIC' => 3,
'SQLSTATE' => 3, 'STARTING' => 3, 'TRAILING' => 3, 'UNSIGNED' => 3,
'ZEROFILL' => 3,
'CONDITION' => 3, 'DATABASES' => 3, 'GENERATED' => 3, 'MIDDLEINT' => 3,
'PARTITION' => 3, 'PRECISION' => 3, 'PROCEDURE' => 3, 'SENSITIVE' => 3,
'SEPARATOR' => 3,
'ACCESSIBLE' => 3, 'ASENSITIVE' => 3, 'CONSTRAINT' => 3, 'DAY_MINUTE' => 3,
'DAY_SECOND' => 3, 'OPTIONALLY' => 3, 'READ_WRITE' => 3, 'REFERENCES' => 3,
'SQLWARNING' => 3, 'TERMINATED' => 3, 'YEAR_MONTH' => 3,
'DISTINCTROW' => 3, 'HOUR_MINUTE' => 3, 'HOUR_SECOND' => 3, 'INSENSITIVE' => 3,
'MASTER_BIND' => 3,
'LOW_PRIORITY' => 3, 'SQLEXCEPTION' => 3, 'VARCHARACTER' => 3,
'DETERMINISTIC' => 3, 'HIGH_PRIORITY' => 3, 'MINUTE_SECOND' => 3,
'STRAIGHT_JOIN' => 3,
'IO_AFTER_GTIDS' => 3, 'SQL_BIG_RESULT' => 3,
'DAY_MICROSECOND' => 3, 'IO_BEFORE_GTIDS' => 3, 'OPTIMIZER_COSTS' => 3,
'HOUR_MICROSECOND' => 3, 'SQL_SMALL_RESULT' => 3,
'MINUTE_MICROSECOND' => 3, 'NO_WRITE_TO_BINLOG' => 3, 'SECOND_MICROSECOND' => 3,
'SQL_CALC_FOUND_ROWS' => 3,
'MASTER_SSL_VERIFY_SERVER_CERT' => 3,
'GROUP BY' => 7, 'NOT NULL' => 7, 'ORDER BY' => 7, 'SET NULL' => 7,
'AND CHAIN' => 7, 'FULL JOIN' => 7, 'IF EXISTS' => 7, 'LEFT JOIN' => 7,
'LESS THAN' => 7, 'NO ACTION' => 7, 'ON DELETE' => 7, 'ON UPDATE' => 7,
'UNION ALL' => 7,
'INNER JOIN' => 7, 'LINEAR KEY' => 7, 'NO RELEASE' => 7, 'OR REPLACE' => 7,
'RIGHT JOIN' => 7,
'LINEAR HASH' => 7,
'AND NO CHAIN' => 7, 'FOR EACH ROW' => 7, 'PARTITION BY' => 7,
'SET PASSWORD' => 7, 'SQL SECURITY' => 7,
'CHARACTER SET' => 7, 'IF NOT EXISTS' => 7,
'DATA DIRECTORY' => 7,
'DEFAULT CHARSET' => 7, 'DEFAULT COLLATE' => 7, 'INDEX DIRECTORY' => 7,
'LEFT OUTER JOIN' => 7, 'SUBPARTITION BY' => 7,
'GENERATED ALWAYS' => 7, 'RIGHT OUTER JOIN' => 7,
'START TRANSACTION' => 7,
'SELECT TRANSACTION' => 7,
'DEFAULT CHARACTER SET' => 7,
'WITH CONSISTENT SNAPSHOT' => 7,
'BIT' => 9, 'XML' => 9,
'ENUM' => 9, 'JSON' => 9, 'TEXT' => 9,
'ARRAY' => 9,
'SERIAL' => 9,
'BOOLEAN' => 9,
'DATETIME' => 9, 'MULTISET' => 9,
'INT' => 11, 'SET' => 11,
'BLOB' => 11, 'REAL' => 11,
'FLOAT' => 11,
'BIGINT' => 11, 'BINARY' => 11, 'DOUBLE' => 11,
'DECIMAL' => 11, 'INTEGER' => 11, 'NUMERIC' => 11, 'TINYINT' => 11, 'VARCHAR' => 11,
'LONGBLOB' => 11, 'LONGTEXT' => 11, 'SMALLINT' => 11, 'TINYBLOB' => 11,
'TINYTEXT' => 11,
'CHARACTER' => 11, 'MEDIUMINT' => 11, 'VARBINARY' => 11,
'MEDIUMBLOB' => 11, 'MEDIUMTEXT' => 11,
'BINARY VARYING' => 15,
'KEY' => 19,
'INDEX' => 19,
'UNIQUE' => 19,
'INDEX KEY' => 23,
'UNIQUE KEY' => 23,
'FOREIGN KEY' => 23, 'PRIMARY KEY' => 23, 'SPATIAL KEY' => 23,
'FULLTEXT KEY' => 23, 'UNIQUE INDEX' => 23,
'SPATIAL INDEX' => 23,
'FULLTEXT INDEX' => 23,
'X' => 33, 'Y' => 33,
'LN' => 33, 'PI' => 33,
'ABS' => 33, 'AVG' => 33, 'BIN' => 33, 'COS' => 33, 'COT' => 33, 'DAY' => 33,
'ELT' => 33, 'EXP' => 33, 'HEX' => 33, 'LOG' => 33, 'MAX' => 33, 'MD5' => 33,
'MID' => 33, 'MIN' => 33, 'NOW' => 33, 'OCT' => 33, 'ORD' => 33, 'POW' => 33,
'SHA' => 33, 'SIN' => 33, 'STD' => 33, 'SUM' => 33, 'TAN' => 33,
'ACOS' => 33, 'AREA' => 33, 'ASIN' => 33, 'ATAN' => 33, 'CAST' => 33, 'CEIL' => 33,
'CONV' => 33, 'HOUR' => 33, 'LOG2' => 33, 'LPAD' => 33, 'RAND' => 33, 'RPAD' => 33,
'SHA1' => 33, 'SHA2' => 33, 'SIGN' => 33, 'SQRT' => 33, 'SRID' => 33, 'ST_X' => 33,
'ST_Y' => 33, 'TRIM' => 33, 'USER' => 33, 'UUID' => 33, 'WEEK' => 33,
'ASCII' => 33, 'ASWKB' => 33, 'ASWKT' => 33, 'ATAN2' => 33, 'COUNT' => 33,
'CRC32' => 33, 'FIELD' => 33, 'FLOOR' => 33, 'INSTR' => 33, 'LCASE' => 33,
'LEAST' => 33, 'LOG10' => 33, 'LOWER' => 33, 'LTRIM' => 33, 'MONTH' => 33,
'POINT' => 33, 'POWER' => 33, 'QUOTE' => 33, 'ROUND' => 33, 'RTRIM' => 33,
'SLEEP' => 33, 'SPACE' => 33, 'UCASE' => 33, 'UNHEX' => 33, 'UPPER' => 33,
'ASTEXT' => 33, 'BIT_OR' => 33, 'BUFFER' => 33, 'CONCAT' => 33, 'DECODE' => 33,
'ENCODE' => 33, 'EQUALS' => 33, 'FORMAT' => 33, 'IFNULL' => 33, 'ISNULL' => 33,
'LENGTH' => 33, 'LOCATE' => 33, 'MINUTE' => 33, 'NULLIF' => 33, 'POINTN' => 33,
'SECOND' => 33, 'STDDEV' => 33, 'STRCMP' => 33, 'SUBSTR' => 33, 'WITHIN' => 33,
'ADDDATE' => 33, 'ADDTIME' => 33, 'AGAINST' => 33, 'BIT_AND' => 33, 'BIT_XOR' => 33,
'CEILING' => 33, 'CHARSET' => 33, 'CROSSES' => 33, 'CURDATE' => 33, 'CURTIME' => 33,
'DAYNAME' => 33, 'DEGREES' => 33, 'ENCRYPT' => 33, 'EXTRACT' => 33, 'GLENGTH' => 33,
'ISEMPTY' => 33, 'IS_IPV4' => 33, 'IS_IPV6' => 33, 'POLYGON' => 33, 'QUARTER' => 33,
'RADIANS' => 33, 'REVERSE' => 33, 'SOUNDEX' => 33, 'ST_AREA' => 33, 'ST_SRID' => 33,
'SUBDATE' => 33, 'SUBTIME' => 33, 'SYSDATE' => 33, 'TOUCHES' => 33, 'TO_DAYS' => 33,
'VAR_POP' => 33, 'VERSION' => 33, 'WEEKDAY' => 33,
'ASBINARY' => 33, 'CENTROID' => 33, 'COALESCE' => 33, 'COMPRESS' => 33,
'CONTAINS' => 33, 'DATEDIFF' => 33, 'DATE_ADD' => 33, 'DATE_SUB' => 33,
'DISJOINT' => 33, 'DISTANCE' => 33, 'ENDPOINT' => 33, 'ENVELOPE' => 33,
'GET_LOCK' => 33, 'GREATEST' => 33, 'ISCLOSED' => 33, 'ISSIMPLE' => 33,
'MAKEDATE' => 33, 'MAKETIME' => 33, 'MAKE_SET' => 33, 'MBREQUAL' => 33,
'OVERLAPS' => 33, 'PASSWORD' => 33, 'POSITION' => 33, 'ST_ASWKB' => 33,
'ST_ASWKT' => 33, 'ST_UNION' => 33, 'TIMEDIFF' => 33, 'TRUNCATE' => 33,
'VARIANCE' => 33, 'VAR_SAMP' => 33, 'YEARWEEK' => 33,
'ANY_VALUE' => 33, 'BENCHMARK' => 33, 'BIT_COUNT' => 33, 'COLLATION' => 33,
'CONCAT_WS' => 33, 'DAYOFWEEK' => 33, 'DAYOFYEAR' => 33, 'DIMENSION' => 33,
'FROM_DAYS' => 33, 'GEOMETRYN' => 33, 'INET_ATON' => 33, 'INET_NTOA' => 33,
'LOAD_FILE' => 33, 'MBRCOVERS' => 33, 'MBREQUALS' => 33, 'MBRWITHIN' => 33,
'MONTHNAME' => 33, 'NUMPOINTS' => 33, 'ROW_COUNT' => 33, 'ST_ASTEXT' => 33,
'ST_BUFFER' => 33, 'ST_EQUALS' => 33, 'ST_LENGTH' => 33, 'ST_POINTN' => 33,
'ST_WITHIN' => 33, 'SUBSTRING' => 33, 'TO_BASE64' => 33, 'UPDATEXML' => 33,
'BIT_LENGTH' => 33, 'CONVERT_TZ' => 33, 'CONVEXHULL' => 33, 'DAYOFMONTH' => 33,
'EXPORT_SET' => 33, 'FOUND_ROWS' => 33, 'GET_FORMAT' => 33, 'INET6_ATON' => 33,
'INET6_NTOA' => 33, 'INTERSECTS' => 33, 'LINESTRING' => 33, 'MBRTOUCHES' => 33,
'MULTIPOINT' => 33, 'NAME_CONST' => 33, 'PERIOD_ADD' => 33, 'STARTPOINT' => 33,
'STDDEV_POP' => 33, 'ST_CROSSES' => 33, 'ST_GEOHASH' => 33, 'ST_ISEMPTY' => 33,
'ST_ISVALID' => 33, 'ST_TOUCHES' => 33, 'TO_SECONDS' => 33, 'UNCOMPRESS' => 33,
'UUID_SHORT' => 33, 'WEEKOFYEAR' => 33,
'AES_DECRYPT' => 33, 'AES_ENCRYPT' => 33, 'CHAR_LENGTH' => 33, 'DATE_FORMAT' => 33,
'DES_DECRYPT' => 33, 'DES_ENCRYPT' => 33, 'FIND_IN_SET' => 33, 'FROM_BASE64' => 33,
'GEOMFROMWKB' => 33, 'GTID_SUBSET' => 33, 'LINEFROMWKB' => 33, 'MBRCONTAINS' => 33,
'MBRDISJOINT' => 33, 'MBROVERLAPS' => 33, 'MICROSECOND' => 33, 'PERIOD_DIFF' => 33,
'POLYFROMWKB' => 33, 'SEC_TO_TIME' => 33, 'STDDEV_SAMP' => 33, 'STR_TO_DATE' => 33,
'ST_ASBINARY' => 33, 'ST_CENTROID' => 33, 'ST_CONTAINS' => 33, 'ST_DISJOINT' => 33,
'ST_DISTANCE' => 33, 'ST_ENDPOINT' => 33, 'ST_ENVELOPE' => 33, 'ST_ISCLOSED' => 33,
'ST_ISSIMPLE' => 33, 'ST_OVERLAPS' => 33, 'ST_SIMPLIFY' => 33, 'ST_VALIDATE' => 33,
'SYSTEM_USER' => 33, 'TIME_FORMAT' => 33, 'TIME_TO_SEC' => 33,
'COERCIBILITY' => 33, 'EXTERIORRING' => 33, 'EXTRACTVALUE' => 33,
'GEOMETRYTYPE' => 33, 'GEOMFROMTEXT' => 33, 'GROUP_CONCAT' => 33,
'IS_FREE_LOCK' => 33, 'IS_USED_LOCK' => 33, 'LINEFROMTEXT' => 33,
'MBRCOVEREDBY' => 33, 'MLINEFROMWKB' => 33, 'MPOLYFROMWKB' => 33,
'MULTIPOLYGON' => 33, 'OCTET_LENGTH' => 33, 'OLD_PASSWORD' => 33,
'POINTFROMWKB' => 33, 'POLYFROMTEXT' => 33, 'RANDOM_BYTES' => 33,
'RELEASE_LOCK' => 33, 'SESSION_USER' => 33, 'ST_ASGEOJSON' => 33,
'ST_DIMENSION' => 33, 'ST_GEOMETRYN' => 33, 'ST_NUMPOINTS' => 33,
'TIMESTAMPADD' => 33,
'CONNECTION_ID' => 33, 'FROM_UNIXTIME' => 33, 'GTID_SUBTRACT' => 33,
'INTERIORRINGN' => 33, 'MBRINTERSECTS' => 33, 'MLINEFROMTEXT' => 33,
'MPOINTFROMWKB' => 33, 'MPOLYFROMTEXT' => 33, 'NUMGEOMETRIES' => 33,
'POINTFROMTEXT' => 33, 'ST_CONVEXHULL' => 33, 'ST_DIFFERENCE' => 33,
'ST_INTERSECTS' => 33, 'ST_STARTPOINT' => 33, 'TIMESTAMPDIFF' => 33,
'WEIGHT_STRING' => 33,
'IS_IPV4_COMPAT' => 33, 'IS_IPV4_MAPPED' => 33, 'LAST_INSERT_ID' => 33,
'MPOINTFROMTEXT' => 33, 'POLYGONFROMWKB' => 33, 'ST_GEOMFROMWKB' => 33,
'ST_LINEFROMWKB' => 33, 'ST_POLYFROMWKB' => 33, 'UNIX_TIMESTAMP' => 33,
'GEOMCOLLFROMWKB' => 33, 'MASTER_POS_WAIT' => 33, 'MULTILINESTRING' => 33,
'POLYGONFROMTEXT' => 33, 'ST_EXTERIORRING' => 33, 'ST_GEOMETRYTYPE' => 33,
'ST_GEOMFROMTEXT' => 33, 'ST_INTERSECTION' => 33, 'ST_LINEFROMTEXT' => 33,
'ST_MAKEENVELOPE' => 33, 'ST_MLINEFROMWKB' => 33, 'ST_MPOLYFROMWKB' => 33,
'ST_POINTFROMWKB' => 33, 'ST_POLYFROMTEXT' => 33, 'SUBSTRING_INDEX' => 33,
'CHARACTER_LENGTH' => 33, 'GEOMCOLLFROMTEXT' => 33, 'GEOMETRYFROMTEXT' => 33,
'NUMINTERIORRINGS' => 33, 'ST_INTERIORRINGN' => 33, 'ST_MLINEFROMTEXT' => 33,
'ST_MPOINTFROMWKB' => 33, 'ST_MPOLYFROMTEXT' => 33, 'ST_NUMGEOMETRIES' => 33,
'ST_POINTFROMTEXT' => 33, 'ST_SYMDIFFERENCE' => 33,
'LINESTRINGFROMWKB' => 33, 'MULTIPOINTFROMWKB' => 33, 'RELEASE_ALL_LOCKS' => 33,
'ST_LATFROMGEOHASH' => 33, 'ST_MPOINTFROMTEXT' => 33, 'ST_POLYGONFROMWKB' => 33,
'GEOMETRYCOLLECTION' => 33, 'MULTIPOINTFROMTEXT' => 33, 'ST_BUFFER_STRATEGY' => 33,
'ST_DISTANCE_SPHERE' => 33, 'ST_GEOMCOLLFROMTXT' => 33, 'ST_GEOMCOLLFROMWKB' => 33,
'ST_GEOMFROMGEOJSON' => 33, 'ST_LONGFROMGEOHASH' => 33, 'ST_POLYGONFROMTEXT' => 33,
'MULTIPOLYGONFROMWKB' => 33, 'ST_GEOMCOLLFROMTEXT' => 33, 'ST_GEOMETRYFROMTEXT' => 33,
'ST_NUMINTERIORRINGS' => 33, 'ST_POINTFROMGEOHASH' => 33, 'UNCOMPRESSED_LENGTH' => 33,
'MULTIPOLYGONFROMTEXT' => 33, 'ST_LINESTRINGFROMWKB' => 33,
'ST_MULTIPOINTFROMWKB' => 33,
'ST_MULTIPOINTFROMTEXT' => 33,
'MULTILINESTRINGFROMWKB' => 33, 'ST_MULTIPOLYGONFROMWKB' => 33,
'MULTILINESTRINGFROMTEXT' => 33, 'ST_MULTIPOLYGONFROMTEXT' => 33,
'GEOMETRYCOLLECTIONFROMWKB' => 33, 'ST_MULTILINESTRINGFROMWKB' => 33,
'GEOMETRYCOLLECTIONFROMTEXT' => 33, 'ST_MULTILINESTRINGFROMTEXT' => 33,
'VALIDATE_PASSWORD_STRENGTH' => 33, 'WAIT_FOR_EXECUTED_GTID_SET' => 33,
'ST_GEOMETRYCOLLECTIONFROMWKB' => 33,
'ST_GEOMETRYCOLLECTIONFROMTEXT' => 33,
'WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS' => 33,
'IF' => 35, 'IN' => 35,
'MOD' => 35,
'LEFT' => 35,
'MATCH' => 35, 'RIGHT' => 35,
'INSERT' => 35, 'REPEAT' => 35, 'SCHEMA' => 35, 'VALUES' => 35,
'CONVERT' => 35, 'DEFAULT' => 35, 'REPLACE' => 35,
'DATABASE' => 35, 'UTC_DATE' => 35, 'UTC_TIME' => 35,
'LOCALTIME' => 35,
'CURRENT_DATE' => 35, 'CURRENT_TIME' => 35, 'CURRENT_USER' => 35,
'UTC_TIMESTAMP' => 35,
'LOCALTIMESTAMP' => 35,
'CURRENT_TIMESTAMP' => 35,
'NOT IN' => 39,
'DATE' => 41, 'TIME' => 41, 'YEAR' => 41,
'TIMESTAMP' => 41,
'CHAR' => 43,
'INTERVAL' => 43,
);
}

View File

@ -1,51 +0,0 @@
<?php
/**
* Exception thrown by the lexer.
*
* @package SqlParser
* @subpackage Exceptions
*/
namespace SqlParser\Exceptions;
/**
* Exception thrown by the lexer.
*
* @category Exceptions
* @package SqlParser
* @subpackage Exceptions
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class LexerException extends \Exception
{
/**
* The character that produced this error.
*
* @var string
*/
public $ch;
/**
* The index of the character that produced this error.
*
* @var int
*/
public $pos;
/**
* Constructor.
*
* @param string $msg The message of this exception.
* @param string $ch The character that produced this exception.
* @param int $pos The position of the character.
* @param int $code The code of this error.
*/
public function __construct($msg = '', $ch = '', $pos = 0, $code = 0)
{
parent::__construct($msg, $code);
$this->ch = $ch;
$this->pos = $pos;
}
}

View File

@ -1,44 +0,0 @@
<?php
/**
* Exception thrown by the parser.
*
* @package SqlParser
* @subpackage Exceptions
*/
namespace SqlParser\Exceptions;
use SqlParser\Token;
/**
* Exception thrown by the parser.
*
* @category Exceptions
* @package SqlParser
* @subpackage Exceptions
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ParserException extends \Exception
{
/**
* The token that produced this error.
*
* @var Token
*/
public $token;
/**
* Constructor.
*
* @param string $msg The message of this exception.
* @param Token $token The token that produced this exception.
* @param int $code The code of this error.
*/
public function __construct($msg = '', Token $token = null, $code = 0)
{
parent::__construct($msg, $code);
$this->token = $token;
}
}

View File

@ -1,876 +0,0 @@
<?php
/**
* Defines the lexer of the library.
*
* This is one of the most important components, along with the parser.
*
* Depends on context to extract lexemes.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
use SqlParser\Exceptions\LexerException;
if (!defined('USE_UTF_STRINGS')) {
// NOTE: In previous versions of PHP (5.5 and older) the default
// internal encoding is "ISO-8859-1".
// All `mb_` functions must specify the correct encoding, which is
// 'UTF-8' in order to work properly.
/**
* Forces usage of `UtfString` if the string is multibyte.
* `UtfString` may be slower, but it gives better results.
*
* @var bool
*/
define('USE_UTF_STRINGS', true);
}
/**
* Performs lexical analysis over a SQL statement and splits it in multiple
* tokens.
*
* The output of the lexer is affected by the context of the SQL statement.
*
* @category Lexer
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
* @see Context
*/
class Lexer
{
/**
* A list of methods that are used in lexing the SQL query.
*
* @var array
*/
public static $PARSER_METHODS = array(
// It is best to put the parsers in order of their complexity
// (ascending) and their occurrence rate (descending).
//
// Conflicts:
//
// 1. `parseDelimiter`, `parseUnknown`, `parseKeyword`, `parseNumber`
// They fight over delimiter. The delimiter may be a keyword, a
// number or almost any character which makes the delimiter one of
// the first tokens that must be parsed.
//
// 1. `parseNumber` and `parseOperator`
// They fight over `+` and `-`.
//
// 2. `parseComment` and `parseOperator`
// They fight over `/` (as in ```/*comment*/``` or ```a / b```)
//
// 3. `parseBool` and `parseKeyword`
// They fight over `TRUE` and `FALSE`.
//
// 4. `parseKeyword` and `parseUnknown`
// They fight over words. `parseUnknown` does not know about
// keywords.
'parseDelimiter', 'parseWhitespace', 'parseNumber',
'parseComment', 'parseOperator', 'parseBool', 'parseString',
'parseSymbol', 'parseKeyword', 'parseUnknown'
);
/**
* Whether errors should throw exceptions or just be stored.
*
* @var bool
*
* @see static::$errors
*/
public $strict = false;
/**
* The string to be parsed.
*
* @var string|UtfString
*/
public $str = '';
/**
* The length of `$str`.
*
* By storing its length, a lot of time is saved, because parsing methods
* would call `strlen` everytime.
*
* @var int
*/
public $len = 0;
/**
* The index of the last parsed character.
*
* @var int
*/
public $last = 0;
/**
* Tokens extracted from given strings.
*
* @var TokensList
*/
public $list;
/**
* The default delimiter. This is used, by default, in all new instances.
*
* @var string
*/
public static $DEFAULT_DELIMITER = ';';
/**
* Statements delimiter.
* This may change during lexing.
*
* @var string
*/
public $delimiter;
/**
* The length of the delimiter.
*
* Because `parseDelimiter` can be called a lot, it would perform a lot of
* calls to `strlen`, which might affect performance when the delimiter is
* big.
*
* @var int
*/
public $delimiterLen;
/**
* List of errors that occurred during lexing.
*
* Usually, the lexing does not stop once an error occurred because that
* error might be false positive or a partial result (even a bad one)
* might be needed.
*
* @var LexerException[]
*
* @see Lexer::error()
*/
public $errors = array();
/**
* Gets the tokens list parsed by a new instance of a lexer.
*
* @param string|UtfString $str The query to be lexed.
* @param bool $strict Whether strict mode should be
* enabled or not.
* @param string $delimiter The delimiter to be used.
*
* @return TokensList
*/
public static function getTokens($str, $strict = false, $delimiter = null)
{
$lexer = new Lexer($str, $strict, $delimiter);
return $lexer->list;
}
/**
* Constructor.
*
* @param string|UtfString $str The query to be lexed.
* @param bool $strict Whether strict mode should be
* enabled or not.
* @param string $delimiter The delimiter to be used.
*/
public function __construct($str, $strict = false, $delimiter = null)
{
// `strlen` is used instead of `mb_strlen` because the lexer needs to
// parse each byte of the input.
$len = ($str instanceof UtfString) ? $str->length() : strlen($str);
// For multi-byte strings, a new instance of `UtfString` is
// initialized (only if `UtfString` usage is forced.
if (!($str instanceof UtfString)) {
if ((USE_UTF_STRINGS) && ($len !== mb_strlen($str, 'UTF-8'))) {
$str = new UtfString($str);
}
}
$this->str = $str;
$this->len = ($str instanceof UtfString) ? $str->length() : $len;
$this->strict = $strict;
// Setting the delimiter.
$this->setDelimiter(
!empty($delimiter) ? $delimiter : static::$DEFAULT_DELIMITER
);
$this->lex();
}
/**
* Sets the delimiter.
*
* @param string $delimiter The new delimiter.
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
$this->delimiterLen = strlen($delimiter);
}
/**
* Parses the string and extracts lexemes.
*
* @return void
*/
public function lex()
{
// TODO: Sometimes, static::parse* functions make unnecessary calls to
// is* functions. For a better performance, some rules can be deduced
// from context.
// For example, in `parseBool` there is no need to compare the token
// every time with `true` and `false`. The first step would be to
// compare with 'true' only and just after that add another letter from
// context and compare again with `false`.
// Another example is `parseComment`.
$list = new TokensList();
/**
* Last processed token.
*
* @var Token $lastToken
*/
$lastToken = null;
for ($this->last = 0, $lastIdx = 0; $this->last < $this->len; $lastIdx = ++$this->last) {
/**
* The new token.
*
* @var Token $token
*/
$token = null;
foreach (static::$PARSER_METHODS as $method) {
if (($token = $this->$method())) {
break;
}
}
if ($token === null) {
// @assert($this->last === $lastIdx);
$token = new Token($this->str[$this->last]);
$this->error(
__('Unexpected character.'),
$this->str[$this->last],
$this->last
);
} elseif (($lastToken !== null)
&& ($token->type === Token::TYPE_SYMBOL)
&& ($token->flags & Token::FLAG_SYMBOL_VARIABLE)
&& (($lastToken->type === Token::TYPE_STRING)
|| (($lastToken->type === Token::TYPE_SYMBOL)
&& ($lastToken->flags & Token::FLAG_SYMBOL_BACKTICK)))
) {
// Handles ```... FROM 'user'@'%' ...```.
$lastToken->token .= $token->token;
$lastToken->type = Token::TYPE_SYMBOL;
$lastToken->flags = Token::FLAG_SYMBOL_USER;
$lastToken->value .= '@' . $token->value;
continue;
} elseif (($lastToken !== null)
&& ($token->type === Token::TYPE_KEYWORD)
&& ($lastToken->type === Token::TYPE_OPERATOR)
&& ($lastToken->value === '.')
) {
// Handles ```... tbl.FROM ...```. In this case, FROM is not
// a reserved word.
$token->type = Token::TYPE_NONE;
$token->flags = 0;
$token->value = $token->token;
}
$token->position = $lastIdx;
$list->tokens[$list->count++] = $token;
// Handling delimiters.
if (($token->type === Token::TYPE_NONE) && ($token->value === 'DELIMITER')) {
if ($this->last + 1 >= $this->len) {
$this->error(
__('Expected whitespace(s) before delimiter.'),
'',
$this->last + 1
);
continue;
}
// Skipping last R (from `delimiteR`) and whitespaces between
// the keyword `DELIMITER` and the actual delimiter.
$pos = ++$this->last;
if (($token = $this->parseWhitespace()) !== null) {
$token->position = $pos;
$list->tokens[$list->count++] = $token;
}
// Preparing the token that holds the new delimiter.
if ($this->last + 1 >= $this->len) {
$this->error(
__('Expected delimiter.'),
'',
$this->last + 1
);
continue;
}
$pos = $this->last + 1;
// Parsing the delimiter.
$this->delimiter = null;
while ((++$this->last < $this->len) && (!Context::isWhitespace($this->str[$this->last]))) {
$this->delimiter .= $this->str[$this->last];
}
if (empty($this->delimiter)) {
$this->error(
__('Expected delimiter.'),
'',
$this->last
);
$this->delimiter = ';';
}
--$this->last;
// Saving the delimiter and its token.
$this->delimiterLen = strlen($this->delimiter);
$token = new Token($this->delimiter, Token::TYPE_DELIMITER);
$token->position = $pos;
$list->tokens[$list->count++] = $token;
}
$lastToken = $token;
}
// Adding a final delimiter to mark the ending.
$list->tokens[$list->count++] = new Token(null, Token::TYPE_DELIMITER);
// Saving the tokens list.
$this->list = $list;
}
/**
* Creates a new error log.
*
* @param string $msg The error message.
* @param string $str The character that produced the error.
* @param int $pos The position of the character.
* @param int $code The code of the error.
*
* @throws LexerException Throws the exception, if strict mode is enabled.
*
* @return void
*/
public function error($msg = '', $str = '', $pos = 0, $code = 0)
{
$error = new LexerException($msg, $str, $pos, $code);
if ($this->strict) {
throw $error;
}
$this->errors[] = $error;
}
/**
* Parses a keyword.
*
* @return Token
*/
public function parseKeyword()
{
$token = '';
/**
* Value to be returned.
*
* @var Token $ret
*/
$ret = null;
/**
* The value of `$this->last` where `$token` ends in `$this->str`.
*
* @var int $iEnd
*/
$iEnd = $this->last;
/**
* Whether last parsed character is a whitespace.
*
* @var bool $lastSpace
*/
$lastSpace = false;
for ($j = 1; $j < Context::KEYWORD_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
// Composed keywords shouldn't have more than one whitespace between
// keywords.
if (Context::isWhitespace($this->str[$this->last])) {
if ($lastSpace) {
--$j; // The size of the keyword didn't increase.
continue;
} else {
$lastSpace = true;
}
} else {
$lastSpace = false;
}
$token .= $this->str[$this->last];
if (($this->last + 1 === $this->len) || (Context::isSeparator($this->str[$this->last + 1]))) {
if (($flags = Context::isKeyword($token))) {
$ret = new Token($token, Token::TYPE_KEYWORD, $flags);
$iEnd = $this->last;
// We don't break so we find longest keyword.
// For example, `OR` and `ORDER` have a common prefix `OR`.
// If we stopped at `OR`, the parsing would be invalid.
}
}
}
$this->last = $iEnd;
return $ret;
}
/**
* Parses an operator.
*
* @return Token
*/
public function parseOperator()
{
$token = '';
/**
* Value to be returned.
*
* @var Token $ret
*/
$ret = null;
/**
* The value of `$this->last` where `$token` ends in `$this->str`.
*
* @var int $iEnd
*/
$iEnd = $this->last;
for ($j = 1; $j < Context::OPERATOR_MAX_LENGTH && $this->last < $this->len; ++$j, ++$this->last) {
$token .= $this->str[$this->last];
if ($flags = Context::isOperator($token)) {
$ret = new Token($token, Token::TYPE_OPERATOR, $flags);
$iEnd = $this->last;
}
}
$this->last = $iEnd;
return $ret;
}
/**
* Parses a whitespace.
*
* @return Token
*/
public function parseWhitespace()
{
$token = $this->str[$this->last];
if (!Context::isWhitespace($token)) {
return null;
}
while ((++$this->last < $this->len) && (Context::isWhitespace($this->str[$this->last]))) {
$token .= $this->str[$this->last];
}
--$this->last;
return new Token($token, Token::TYPE_WHITESPACE);
}
/**
* Parses a comment.
*
* @return Token
*/
public function parseComment()
{
$iBak = $this->last;
$token = $this->str[$this->last];
// Bash style comments. (#comment\n)
if (Context::isComment($token)) {
while ((++$this->last < $this->len) && ($this->str[$this->last] !== "\n")) {
$token .= $this->str[$this->last];
}
$token .= "\n"; // Adding the line ending.
return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_BASH);
}
// C style comments. (/*comment*\/)
if (++$this->last < $this->len) {
$token .= $this->str[$this->last];
if (Context::isComment($token)) {
$flags = Token::FLAG_COMMENT_C;
// This comment already ended. It may be a part of a
// previous MySQL specific command.
if ($token === '*/') {
return new Token($token, Token::TYPE_COMMENT, $flags);
}
// Checking if this is a MySQL-specific command.
if (($this->last + 1 < $this->len) && ($this->str[$this->last + 1] === '!')) {
$flags |= Token::FLAG_COMMENT_MYSQL_CMD;
$token .= $this->str[++$this->last];
while ((++$this->last < $this->len)
&& ('0' <= $this->str[$this->last])
&& ($this->str[$this->last] <= '9')
) {
$token .= $this->str[$this->last];
}
--$this->last;
// We split this comment and parse only its beginning
// here.
return new Token($token, Token::TYPE_COMMENT, $flags);
}
// Parsing the comment.
while ((++$this->last < $this->len)
&& (($this->str[$this->last - 1] !== '*') || ($this->str[$this->last] !== '/'))
) {
$token .= $this->str[$this->last];
}
// Adding the ending.
if ($this->last < $this->len) {
$token .= $this->str[$this->last];
}
return new Token($token, Token::TYPE_COMMENT, $flags);
}
}
// SQL style comments. (-- comment\n)
if (++$this->last < $this->len) {
$token .= $this->str[$this->last];
if (Context::isComment($token)) {
// Checking if this comment did not end already (```--\n```).
if ($this->str[$this->last] !== "\n") {
while ((++$this->last < $this->len) && ($this->str[$this->last] !== "\n")) {
$token .= $this->str[$this->last];
}
$token .= "\n"; // Adding the line ending.
}
return new Token($token, Token::TYPE_COMMENT, Token::FLAG_COMMENT_SQL);
}
}
$this->last = $iBak;
return null;
}
/**
* Parses a boolean.
*
* @return Token
*/
public function parseBool()
{
if ($this->last + 3 >= $this->len) {
// At least `min(strlen('TRUE'), strlen('FALSE'))` characters are
// required.
return null;
}
$iBak = $this->last;
$token = $this->str[$this->last] . $this->str[++$this->last]
. $this->str[++$this->last] . $this->str[++$this->last]; // _TRUE_ or _FALS_e
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL);
} elseif (++$this->last < $this->len) {
$token .= $this->str[$this->last]; // fals_E_
if (Context::isBool($token)) {
return new Token($token, Token::TYPE_BOOL, 1);
}
}
$this->last = $iBak;
return null;
}
/**
* Parses a number.
*
* @return Token
*/
public function parseNumber()
{
// A rudimentary state machine is being used to parse numbers due to
// the various forms of their notation.
//
// Below are the states of the machines and the conditions to change
// the state.
//
// 1 --------------------[ + or - ]-------------------> 1
// 1 -------------------[ 0x or 0X ]------------------> 2
// 1 --------------------[ 0 to 9 ]-------------------> 3
// 1 -----------------------[ . ]---------------------> 4
// 1 -----------------------[ b ]---------------------> 7
//
// 2 --------------------[ 0 to F ]-------------------> 2
//
// 3 --------------------[ 0 to 9 ]-------------------> 3
// 3 -----------------------[ . ]---------------------> 4
// 3 --------------------[ e or E ]-------------------> 5
//
// 4 --------------------[ 0 to 9 ]-------------------> 4
// 4 --------------------[ e or E ]-------------------> 5
//
// 5 ---------------[ + or - or 0 to 9 ]--------------> 6
//
// 7 -----------------------[ ' ]---------------------> 8
//
// 8 --------------------[ 0 or 1 ]-------------------> 8
// 8 -----------------------[ ' ]---------------------> 9
//
// State 1 may be reached by negative numbers.
// State 2 is reached only by hex numbers.
// State 4 is reached only by float numbers.
// State 5 is reached only by numbers in approximate form.
// State 7 is reached only by numbers in bit representation.
//
// Valid final states are: 2, 3, 4 and 6. Any parsing that finished in a
// state other than these is invalid.
$iBak = $this->last;
$token = '';
$flags = 0;
$state = 1;
for (; $this->last < $this->len; ++$this->last) {
if ($state === 1) {
if ($this->str[$this->last] === '-') {
$flags |= Token::FLAG_NUMBER_NEGATIVE;
} elseif (($this->last + 1 < $this->len)
&& ($this->str[$this->last] === '0')
&& (($this->str[$this->last + 1] === 'x')
|| ($this->str[$this->last + 1] === 'X'))
) {
$token .= $this->str[$this->last++];
$state = 2;
} elseif (($this->str[$this->last] >= '0') && ($this->str[$this->last] <= '9')) {
$state = 3;
} elseif ($this->str[$this->last] === '.') {
$state = 4;
} elseif ($this->str[$this->last] === 'b') {
$state = 7;
} elseif ($this->str[$this->last] !== '+') {
// `+` is a valid character in a number.
break;
}
} elseif ($state === 2) {
$flags |= Token::FLAG_NUMBER_HEX;
if (!((($this->str[$this->last] >= '0') && ($this->str[$this->last] <= '9'))
|| (($this->str[$this->last] >= 'A') && ($this->str[$this->last] <= 'F'))
|| (($this->str[$this->last] >= 'a') && ($this->str[$this->last] <= 'f')))
) {
break;
}
} elseif ($state === 3) {
if ($this->str[$this->last] === '.') {
$state = 4;
} elseif (($this->str[$this->last] === 'e') || ($this->str[$this->last] === 'E')) {
$state = 5;
} elseif (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits and `.`, `e` and `E` are valid characters.
break;
}
} elseif ($state === 4) {
$flags |= Token::FLAG_NUMBER_FLOAT;
if (($this->str[$this->last] === 'e') || ($this->str[$this->last] === 'E')) {
$state = 5;
} elseif (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits, `e` and `E` are valid characters.
break;
}
} elseif ($state === 5) {
$flags |= Token::FLAG_NUMBER_APPROXIMATE;
if (($this->str[$this->last] === '+') || ($this->str[$this->last] === '-')
|| ((($this->str[$this->last] >= '0') && ($this->str[$this->last] <= '9')))
) {
$state = 6;
} else {
break;
}
} elseif ($state === 6) {
if (($this->str[$this->last] < '0') || ($this->str[$this->last] > '9')) {
// Just digits are valid characters.
break;
}
} elseif ($state === 7) {
$flags |= Token::FLAG_NUMBER_BINARY;
if ($this->str[$this->last] === '\'') {
$state = 8;
} else {
break;
}
} elseif ($state === 8) {
if ($this->str[$this->last] === '\'') {
$state = 9;
} elseif (($this->str[$this->last] !== '0')
&& ($this->str[$this->last] !== '1')
) {
break;
}
} elseif ($state === 9) {
break;
}
$token .= $this->str[$this->last];
}
if (($state === 2) || ($state === 3)
|| (($token !== '.') && ($state === 4))
|| ($state === 6) || ($state === 9)
) {
--$this->last;
return new Token($token, Token::TYPE_NUMBER, $flags);
}
$this->last = $iBak;
return null;
}
/**
* Parses a string.
*
* @param string $quote Additional starting symbol.
*
* @return Token
*/
public function parseString($quote = '')
{
$token = $this->str[$this->last];
if ((!($flags = Context::isString($token))) && ($token !== $quote)) {
return null;
}
$quote = $token;
while (++$this->last < $this->len) {
if (($this->last + 1 < $this->len)
&& ((($this->str[$this->last] === $quote) && ($this->str[$this->last + 1] === $quote))
|| (($this->str[$this->last] === '\\') && ($quote !== '`')))
) {
$token .= $this->str[$this->last] . $this->str[++$this->last];
} else {
if ($this->str[$this->last] === $quote) {
break;
}
$token .= $this->str[$this->last];
}
}
if (($this->last >= $this->len) || ($this->str[$this->last] !== $quote)) {
$this->error(
sprintf(
__('Ending quote %1$s was expected.'),
$quote
),
'',
$this->last
);
} else {
$token .= $this->str[$this->last];
}
return new Token($token, Token::TYPE_STRING, $flags);
}
/**
* Parses a symbol.
*
* @return Token
*/
public function parseSymbol()
{
$token = $this->str[$this->last];
if (!($flags = Context::isSymbol($token))) {
return null;
}
if ($flags & Token::FLAG_SYMBOL_VARIABLE) {
if ($this->str[++$this->last] === '@') {
// This is a system variable (e.g. `@@hostname`).
$token .= $this->str[$this->last++];
$flags |= Token::FLAG_SYMBOL_SYSTEM;
}
} else {
$token = '';
}
$str = null;
if ($this->last < $this->len) {
if (($str = $this->parseString('`')) === null) {
if (($str = static::parseUnknown()) === null) {
$this->error(
__('Variable name was expected.'),
$this->str[$this->last],
$this->last
);
}
}
}
if ($str !== null) {
$token .= $str->token;
}
return new Token($token, Token::TYPE_SYMBOL, $flags);
}
/**
* Parses unknown parts of the query.
*
* @return Token
*/
public function parseUnknown()
{
$token = $this->str[$this->last];
if (Context::isSeparator($token)) {
return null;
}
while ((++$this->last < $this->len) && (!Context::isSeparator($this->str[$this->last]))) {
$token .= $this->str[$this->last];
}
--$this->last;
return new Token($token);
}
/**
* Parses the delimiter of the query.
*
* @return Token
*/
public function parseDelimiter()
{
$idx = 0;
while (($idx < $this->delimiterLen) && ($this->last + $idx < $this->len)) {
if ($this->delimiter[$idx] !== $this->str[$this->last + $idx]) {
return null;
}
++$idx;
}
$this->last += $this->delimiterLen - 1;
return new Token($this->delimiter, Token::TYPE_DELIMITER);
}
}

View File

@ -1,560 +0,0 @@
<?php
/**
* Defines the parser of the library.
*
* This is one of the most important components, along with the lexer.
*
* @package SqlParser
*/
namespace SqlParser;
require_once 'common.php';
use SqlParser\Exceptions\ParserException;
use SqlParser\Statements\SelectStatement;
use SqlParser\Statements\TransactionStatement;
/**
* Takes multiple tokens (contained in a Lexer instance) as input and builds a
* parse tree.
*
* @category Parser
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Parser
{
/**
* Array of classes that are used in parsing the SQL statements.
*
* @var array
*/
public static $STATEMENT_PARSERS = array(
// MySQL Utility Statements
'DESCRIBE' => 'SqlParser\\Statements\\ExplainStatement',
'DESC' => 'SqlParser\\Statements\\ExplainStatement',
'EXPLAIN' => 'SqlParser\\Statements\\ExplainStatement',
'FLUSH' => '',
'GRANT' => '',
'HELP' => '',
'SET PASSWORD' => '',
'STATUS' => '',
'USE' => '',
// Table Maintenance Statements
// https://dev.mysql.com/doc/refman/5.7/en/table-maintenance-sql.html
'ANALYZE' => 'SqlParser\\Statements\\AnalyzeStatement',
'BACKUP' => 'SqlParser\\Statements\\BackupStatement',
'CHECK' => 'SqlParser\\Statements\\CheckStatement',
'CHECKSUM' => 'SqlParser\\Statements\\ChecksumStatement',
'OPTIMIZE' => 'SqlParser\\Statements\\OptimizeStatement',
'REPAIR' => 'SqlParser\\Statements\\RepairStatement',
'RESTORE' => 'SqlParser\\Statements\\RestoreStatement',
// Database Administration Statements
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-server-administration.html
'SET' => 'SqlParser\\Statements\\SetStatement',
'SHOW' => 'SqlParser\\Statements\\ShowStatement',
// Data Definition Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-definition.html
'ALTER' => 'SqlParser\\Statements\\AlterStatement',
'CREATE' => 'SqlParser\\Statements\\CreateStatement',
'DROP' => 'SqlParser\\Statements\\DropStatement',
'RENAME' => 'SqlParser\\Statements\\RenameStatement',
'TRUNCATE' => 'SqlParser\\Statements\\TruncateStatement',
// Data Manipulation Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-data-manipulation.html
'CALL' => 'SqlParser\\Statements\\CallStatement',
'DELETE' => 'SqlParser\\Statements\\DeleteStatement',
'DO' => '',
'HANDLER' => '',
'INSERT' => 'SqlParser\\Statements\\InsertStatement',
'LOAD' => '',
'REPLACE' => 'SqlParser\\Statements\\ReplaceStatement',
'SELECT' => 'SqlParser\\Statements\\SelectStatement',
'UPDATE' => 'SqlParser\\Statements\\UpdateStatement',
// Prepared Statements.
// https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
'DEALLOCATE' => '',
'EXECUTE' => '',
'PREPARE' => '',
// Transactional and Locking Statements
// https://dev.mysql.com/doc/refman/5.7/en/commit.html
'BEGIN' => 'SqlParser\\Statements\\TransactionStatement',
'COMMIT' => 'SqlParser\\Statements\\TransactionStatement',
'ROLLBACK' => 'SqlParser\\Statements\\TransactionStatement',
'START TRANSACTION' => 'SqlParser\\Statements\\TransactionStatement',
);
/**
* Array of classes that are used in parsing SQL components.
*
* @var array
*/
public static $KEYWORD_PARSERS = array(
// This is not a proper keyword and was added here to help the
// formatter.
'PARTITION BY' => array(),
'SUBPARTITION BY' => array(),
// This is not a proper keyword and was added here to help the
// builder.
'_OPTIONS' => array(
'class' => 'SqlParser\\Components\\OptionsArray',
'field' => 'options',
),
'UNION' => array(
'class' => 'SqlParser\\Components\\UnionKeyword',
'field' => 'union',
),
'UNION ALL' => array(
'class' => 'SqlParser\\Components\\UnionKeyword',
'field' => 'union',
),
// Actual clause parsers.
'ALTER' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('parseField' => 'table'),
),
'ANALYZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'BACKUP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'CALL' => array(
'class' => 'SqlParser\\Components\\FunctionCall',
'field' => 'call',
),
'CHECK' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'CHECKSUM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'DROP' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'fields',
'options' => array('parseField' => 'table'),
),
'FROM' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'from',
'options' => array('parseField' => 'table'),
),
'GROUP BY' => array(
'class' => 'SqlParser\\Components\\OrderKeyword',
'field' => 'group',
),
'HAVING' => array(
'class' => 'SqlParser\\Components\\Condition',
'field' => 'having',
),
'INTO' => array(
'class' => 'SqlParser\\Components\\IntoKeyword',
'field' => 'into',
),
'JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LEFT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LEFT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'RIGHT JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'RIGHT OUTER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'INNER JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'FULL JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'STRAIGHT_JOIN' => array(
'class' => 'SqlParser\\Components\\JoinKeyword',
'field' => 'join',
),
'LIMIT' => array(
'class' => 'SqlParser\\Components\\Limit',
'field' => 'limit',
),
'OPTIMIZE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'ORDER BY' => array(
'class' => 'SqlParser\\Components\\OrderKeyword',
'field' => 'order',
),
'PARTITION' => array(
'class' => 'SqlParser\\Components\\ArrayObj',
'field' => 'partition',
),
'PROCEDURE' => array(
'class' => 'SqlParser\\Components\\FunctionCall',
'field' => 'procedure',
),
'RENAME' => array(
'class' => 'SqlParser\\Components\\RenameOperation',
'field' => 'renames',
),
'REPAIR' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'RESTORE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'SET' => array(
'class' => 'SqlParser\\Components\\SetOperation',
'field' => 'set',
),
'SELECT' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'expr',
),
'TRUNCATE' => array(
'class' => 'SqlParser\\Components\\Expression',
'field' => 'table',
'options' => array('parseField' => 'table'),
),
'UPDATE' => array(
'class' => 'SqlParser\\Components\\ExpressionArray',
'field' => 'tables',
'options' => array('parseField' => 'table'),
),
'VALUE' => array(
'class' => 'SqlParser\\Components\\Array2d',
'field' => 'values',
),
'VALUES' => array(
'class' => 'SqlParser\\Components\\Array2d',
'field' => 'values',
),
'WHERE' => array(
'class' => 'SqlParser\\Components\\Condition',
'field' => 'where',
),
);
/**
* The list of tokens that are parsed.
*
* @var TokensList
*/
public $list;
/**
* Whether errors should throw exceptions or just be stored.
*
* @var bool
*
* @see static::$errors
*/
public $strict = false;
/**
* List of errors that occurred during parsing.
*
* Usually, the parsing does not stop once an error occurred because that
* error might be a false positive or a partial result (even a bad one)
* might be needed.
*
* @var ParserException[]
*
* @see Parser::error()
*/
public $errors = array();
/**
* List of statements parsed.
*
* @var Statement[]
*/
public $statements = array();
/**
* The number of opened brackets.
*
* @var int
*/
public $brackets = 0;
/**
* Constructor.
*
* @param string|UtfString|TokensList $list The list of tokens to be parsed.
* @param bool $strict Whether strict mode should be enabled or not.
*/
public function __construct($list = null, $strict = false)
{
if ((is_string($list)) || ($list instanceof UtfString)) {
$lexer = new Lexer($list, $strict);
$this->list = $lexer->list;
} elseif ($list instanceof TokensList) {
$this->list = $list;
}
$this->strict = $strict;
if ($list !== null) {
$this->parse();
}
}
/**
* Builds the parse trees.
*
* @return void
*/
public function parse()
{
/**
* Last transaction.
*
* @var TransactionStatement $lastTransaction
*/
$lastTransaction = null;
/**
* Last parsed statement.
*
* @var Statement $lastStatement
*/
$lastStatement = null;
/**
* Union's type or false for no union.
*
* @var bool|string $unionType
*/
$unionType = false;
/**
* The index of the last token from the last statement.
*
* @var int $prevLastIdx
*/
$prevLastIdx = -1;
/**
* The list of tokens.
*
* @var TokensList $list
*/
$list = &$this->list;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// `DELIMITER` is not an actual statement and it requires
// special handling.
if (($token->type === Token::TYPE_NONE)
&& (strtoupper($token->token) === 'DELIMITER')
) {
// Skipping to the end of this statement.
$list->getNextOfType(Token::TYPE_DELIMITER);
$prevLastIdx = $list->idx;
continue;
}
// Counting the brackets around statements.
if ($token->value === '(') {
++$this->brackets;
continue;
}
// Statements can start with keywords only.
// Comments, whitespaces, etc. are ignored.
if ($token->type !== Token::TYPE_KEYWORD) {
if (($token->type !== TOKEN::TYPE_COMMENT)
&& ($token->type !== Token::TYPE_WHITESPACE)
&& ($token->type !== Token::TYPE_OPERATOR) // `(` and `)`
&& ($token->type !== Token::TYPE_DELIMITER)
) {
$this->error(
__('Unexpected beginning of statement.'),
$token
);
}
continue;
}
if (($token->value === 'UNION') || ($token->value === 'UNION ALL')) {
$unionType = $token->value;
continue;
}
// Checking if it is a known statement that can be parsed.
if (empty(static::$STATEMENT_PARSERS[$token->value])) {
if (!isset(static::$STATEMENT_PARSERS[$token->value])) {
// A statement is considered recognized if the parser
// is aware that it is a statement, but it does not have
// a parser for it yet.
$this->error(
__('Unrecognized statement type.'),
$token
);
}
// Skipping to the end of this statement.
$list->getNextOfType(Token::TYPE_DELIMITER);
$prevLastIdx = $list->idx;
continue;
}
/**
* The name of the class that is used for parsing.
*
* @var string $class
*/
$class = static::$STATEMENT_PARSERS[$token->value];
/**
* Processed statement.
*
* @var Statement $statement
*/
$statement = new $class($this, $this->list);
// The first token that is a part of this token is the next token
// unprocessed by the previous statement.
// There might be brackets around statements and this shouldn't
// affect the parser
$statement->first = $prevLastIdx + 1;
// Storing the index of the last token parsed and updating the old
// index.
$statement->last = $list->idx;
$prevLastIdx = $list->idx;
// Handles unions.
if ((!empty($unionType))
&& ($lastStatement instanceof SelectStatement)
&& ($statement instanceof SelectStatement)
) {
/**
* This SELECT statement.
*
* @var SelectStatement $statement
*/
/**
* Last SELECT statement.
*
* @var SelectStatement $lastStatement
*/
$lastStatement->union[] = array($unionType, $statement);
// if there are no no delimiting brackets, the `ORDER` and
// `LIMIT` keywords actually belong to the first statement.
$lastStatement->order = $statement->order;
$lastStatement->limit = $statement->limit;
$statement->order = array();
$statement->limit = null;
// The statement actually ends where the last statement in
// union ends.
$lastStatement->last = $statement->last;
$unionType = false;
continue;
}
// Handles transactions.
if ($statement instanceof TransactionStatement) {
/**
* @var TransactionStatement $statement
*/
if ($statement->type === TransactionStatement::TYPE_BEGIN) {
$lastTransaction = $statement;
$this->statements[] = $statement;
} elseif ($statement->type === TransactionStatement::TYPE_END) {
if ($lastTransaction === null) {
// Even though an error occurred, the query is being
// saved.
$this->statements[] = $statement;
$this->error(
__('No transaction was previously started.'),
$token
);
} else {
$lastTransaction->end = $statement;
}
$lastTransaction = null;
}
continue;
}
// Finally, storing the statement.
if ($lastTransaction !== null) {
$lastTransaction->statements[] = $statement;
} else {
$this->statements[] = $statement;
}
$lastStatement = $statement;
}
}
/**
* Creates a new error log.
*
* @param string $msg The error message.
* @param Token $token The token that produced the error.
* @param int $code The code of the error.
*
* @throws ParserException Throws the exception, if strict mode is enabled.
*
* @return void
*/
public function error($msg = '', Token $token = null, $code = 0)
{
$error = new ParserException($msg, $token, $code);
if ($this->strict) {
throw $error;
}
$this->errors[] = $error;
}
}

View File

@ -1,400 +0,0 @@
<?php
/**
* The result of the parser is an array of statements are extensions of the
* class defined here.
*
* A statement represents the result of parsing the lexemes.
*
* @package SqlParser
*/
namespace SqlParser;
use SqlParser\Components\OptionsArray;
/**
* Abstract statement definition.
*
* @category Statements
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
abstract class Statement
{
/**
* Options for this statement.
*
* The option would be the key and the value can be an integer or an array.
*
* The integer represents only the index used.
*
* The array may have two keys: `0` is used to represent the index used and
* `1` is the type of the option (which may be 'var' or 'var='). Both
* options mean they expect a value after the option (e.g. `A = B` or `A B`,
* in which case `A` is the key and `B` is the value). The only difference
* is in the building process. `var` options are built as `A B` and `var=`
* options are built as `A = B`
*
* Two options that can be used together must have different values for
* indexes, else, when they will be used together, an error will occur.
*
* @var array
*/
public static $OPTIONS = array();
/**
* The clauses of this statement, in order.
*
* The value attributed to each clause is used by the builder and it may
* have one of the following values:
*
* - 1 = 01 - add the clause only
* - 2 = 10 - add the keyword
* - 3 = 11 - add both the keyword and the clause
*
* @var array
*/
public static $CLAUSES = array();
/**
* The options of this query.
*
* @var OptionsArray
*
* @see static::$OPTIONS
*/
public $options;
/**
* The index of the first token used in this statement.
*
* @var int
*/
public $first;
/**
* The index of the last token used in this statement.
*
* @var int
*/
public $last;
/**
* Constructor.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*/
public function __construct(Parser $parser = null, TokensList $list = null)
{
if (($parser !== null) && ($list !== null)) {
$this->parse($parser, $list);
}
}
/**
* Builds the string representation of this statement.
*
* @return string
*/
public function build()
{
/**
* Query to be returned.
*
* @var string $query
*/
$query = '';
/**
* Clauses which were built already.
*
* It is required to keep track of built clauses because some fields,
* for example `join` is used by multiple clauses (`JOIN`, `LEFT JOIN`,
* `LEFT OUTER JOIN`, etc.). The same happens for `VALUE` and `VALUES`.
*
* A clause is considered built just after fields' value
* (`$this->field`) was used in building.
*
* @var array
*/
$built = array();
/**
* Statement's clauses.
*
* @var array
*/
$clauses = $this->getClauses();
foreach ($clauses as $clause) {
/**
* The name of the clause.
*
* @var string $name
*/
$name = $clause[0];
/**
* The type of the clause.
*
* @see self::$CLAUSES
* @var int $type
*/
$type = $clause[1];
/**
* The builder (parser) of this clause.
*
* @var Component $class
*/
$class = Parser::$KEYWORD_PARSERS[$name]['class'];
/**
* The name of the field that is used as source for the builder.
* Same field is used to store the result of parsing.
*
* @var string $field
*/
$field = Parser::$KEYWORD_PARSERS[$name]['field'];
// The field is empty, there is nothing to be built.
if (empty($this->$field)) {
continue;
}
// Checking if this field was already built.
if ($type & 1) {
if (!empty($built[$field])) {
continue;
}
$built[$field] = true;
}
// Checking if the name of the clause should be added.
if ($type & 2) {
$query .= $name . ' ';
}
// Checking if the result of the builder should be added.
if ($type & 1) {
$query .= $class::build($this->$field) . ' ';
}
}
return $query;
}
/**
* Parses the statements defined by the tokens list.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
/**
* Array containing all list of clauses parsed.
* This is used to check for duplicates.
*
* @var array $parsedClauses
*/
$parsedClauses = array();
// This may be corrected by the parser.
$this->first = $list->idx;
/**
* Whether options were parsed or not.
* For statements that do not have any options this is set to `true` by
* default.
*
* @var bool $parsedOptions
*/
$parsedOptions = empty(static::$OPTIONS);
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Checking if this closing bracket is the pair for a bracket
// outside the statement.
if (($token->value === ')') && ($parser->brackets > 0)) {
--$parser->brackets;
continue;
}
// Only keywords are relevant here. Other parts of the query are
// processed in the functions below.
if ($token->type !== Token::TYPE_KEYWORD) {
if (($token->type !== TOKEN::TYPE_COMMENT)
&& ($token->type !== Token::TYPE_WHITESPACE)
) {
$parser->error(__('Unexpected token.'), $token);
}
continue;
}
// Unions are parsed by the parser because they represent more than
// one statement.
if (($token->value === 'UNION') || ($token->value === 'UNION ALL')) {
break;
}
/**
* The name of the class that is used for parsing.
*
* @var Component $class
*/
$class = null;
/**
* The name of the field where the result of the parsing is stored.
*
* @var string $field
*/
$field = null;
/**
* Parser's options.
*
* @var array $options
*/
$options = array();
// Looking for duplicated clauses.
if ((!empty(Parser::$KEYWORD_PARSERS[$token->value]))
|| (!empty(Parser::$STATEMENT_PARSERS[$token->value]))
) {
if (!empty($parsedClauses[$token->value])) {
$parser->error(
__('This type of clause was previously parsed.'),
$token
);
break;
}
$parsedClauses[$token->value] = true;
}
// Checking if this is the beginning of a clause.
if (!empty(Parser::$KEYWORD_PARSERS[$token->value])) {
$class = Parser::$KEYWORD_PARSERS[$token->value]['class'];
$field = Parser::$KEYWORD_PARSERS[$token->value]['field'];
if (!empty(Parser::$KEYWORD_PARSERS[$token->value]['options'])) {
$options = Parser::$KEYWORD_PARSERS[$token->value]['options'];
}
}
// Checking if this is the beginning of the statement.
if (!empty(Parser::$STATEMENT_PARSERS[$token->value])) {
if ((!empty(static::$CLAUSES)) // Undefined for some statements.
&& (empty(static::$CLAUSES[$token->value]))
) {
// Some keywords (e.g. `SET`) may be the beginning of a
// statement and a clause.
// If such keyword was found and it cannot be a clause of
// this statement it means it is a new statement, but no
// delimiter was found between them.
$parser->error(
__('A new statement was found, but no delimiter between it and the previous one.'),
$token
);
break;
}
if (!$parsedOptions) {
if (empty(static::$OPTIONS[$token->value])) {
// Skipping keyword because if it is not a option.
++$list->idx;
}
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
$parsedOptions = true;
}
} elseif ($class === null) {
// There is no parser for this keyword and isn't the beginning
// of a statement (so no options) either.
$parser->error(__('Unrecognized keyword.'), $token);
continue;
}
$this->before($parser, $list, $token);
// Parsing this keyword.
if ($class !== null) {
++$list->idx; // Skipping keyword or last option.
$this->$field = $class::parse($parser, $list, $options);
}
$this->after($parser, $list, $token);
}
// This may be corrected by the parser.
$this->last = --$list->idx; // Go back to last used token.
}
/**
* Function called before the token is processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Function called after the token was processed.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function after(Parser $parser, TokensList $list, Token $token)
{
}
/**
* Gets the clauses of this statement.
*
* @return array
*/
public function getClauses()
{
return static::$CLAUSES;
}
/**
* Builds the string representation of this statement.
*
* @see static::build
*
* @return string
*/
public function __toString()
{
return $this->build();
}
}

View File

@ -1,141 +0,0 @@
<?php
/**
* `ALTER` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\AlterOperation;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
/**
* `ALTER` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class AlterStatement extends Statement
{
/**
* Table affected.
*
* @var Expression
*/
public $table;
/**
* Column affected by this statement.
*
* @var AlterOperation[]
*/
public $altered = array();
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'ONLINE' => 1,
'OFFLINE' => 1,
'IGNORE' => 2,
);
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `ALTER`.
$this->options = OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
);
// Skipping `TABLE`.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
// Parsing affected table.
$this->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'column',
'breakOnAlias' => true,
)
);
++$list->idx; // Skipping field.
/**
* The state of the parser.
*
* Below are the states of the parser.
*
* 0 -----------------[ alter operation ]-----------------> 1
*
* 1 -------------------------[ , ]-----------------------> 0
*
* @var int $state
*/
$state = 0;
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $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)) {
continue;
}
if ($state === 0) {
$this->altered[] = AlterOperation::parse($parser, $list);
$state = 1;
} elseif ($state === 1) {
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === ',')) {
$state = 0;
}
}
}
}
/**
* @return string
*/
public function build()
{
$tmp = array();
foreach ($this->altered as $altered) {
$tmp[] = $altered::build($altered);
}
return 'ALTER ' . OptionsArray::build($this->options)
. ' TABLE ' . Expression::build($this->table)
. ' ' . implode(', ', $tmp);
}
}

View File

@ -1,48 +0,0 @@
<?php
/**
* `ANALYZE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `ANALYZE` statement.
*
* ANALYZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class AnalyzeStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
);
/**
* Analyzed tables.
*
* @var Expression[]
*/
public $tables;
}

View File

@ -1,39 +0,0 @@
<?php
/**
* `BACKUP` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `BACKUP` statement.
*
* BACKUP TABLE tbl_name [, tbl_name] ... TO '/path/to/backup/directory'
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class BackupStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
'TO' => array(4, 'var'),
);
}

View File

@ -1,38 +0,0 @@
<?php
/**
* `CALL` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\FunctionCall;
/**
* `CALL` statement.
*
* CALL sp_name([parameter[,...]])
*
* or
*
* CALL sp_name[()]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class CallStatement extends Statement
{
/**
* The name of the function and its parameters.
*
* @var FunctionCall
*/
public $call;
}

View File

@ -1,41 +0,0 @@
<?php
/**
* `CHECK` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `CHECK` statement.
*
* CHECK TABLE tbl_name [, tbl_name] ... [option] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class CheckStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'FOR UPGRADE' => 2,
'QUICK' => 3,
'FAST' => 4,
'MEDIUM' => 5,
'EXTENDED' => 6,
'CHANGED' => 7,
);
}

View File

@ -1,37 +0,0 @@
<?php
/**
* `CHECKSUM` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `CHECKSUM` statement.
*
* CHECKSUM TABLE tbl_name [, tbl_name] ... [ QUICK | EXTENDED ]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ChecksumStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'QUICK' => 2,
'EXTENDED' => 3,
);
}

View File

@ -1,563 +0,0 @@
<?php
/**
* `CREATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\DataType;
use SqlParser\Components\CreateDefinition;
use SqlParser\Components\PartitionDefinition;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
use SqlParser\Components\ParameterDefinition;
/**
* `CREATE` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class CreateStatement extends Statement
{
/**
* Options for `CREATE` statements.
*
* @var array
*/
public static $OPTIONS = array(
// CREATE TABLE
'TEMPORARY' => 1,
// CREATE VIEW
'OR REPLACE' => array(2, 'var='),
'ALGORITHM' => array(3, 'var='),
// `DEFINER` is also used for `CREATE FUNCTION / PROCEDURE`
'DEFINER' => array(4, 'var='),
'SQL SECURITY' => array(5, 'var'),
'DATABASE' => 6,
'EVENT' => 6,
'FUNCTION' => 6,
'INDEX' => 6,
'PROCEDURE' => 6,
'SERVER' => 6,
'TABLE' => 6,
'TABLESPACE' => 6,
'TRIGGER' => 6,
'USER' => 6,
'VIEW' => 6,
// CREATE TABLE
'IF NOT EXISTS' => 7,
);
/**
* All database options.
*
* @var array
*/
public static $DB_OPTIONS = array(
'CHARACTER SET' => array(1, 'var='),
'CHARSET' => array(1, 'var='),
'DEFAULT CHARACTER SET' => array(1, 'var='),
'DEFAULT CHARSET' => array(1, 'var='),
'DEFAULT COLLATE' => array(2, 'var='),
'COLLATE' => array(2, 'var='),
);
/**
* All table options.
*
* @var array
*/
public static $TABLE_OPTIONS = array(
'ENGINE' => array(1, 'var='),
'AUTO_INCREMENT' => array(2, 'var='),
'AVG_ROW_LENGTH' => array(3, 'var'),
'CHARACTER SET' => array(4, 'var='),
'CHARSET' => array(4, 'var='),
'DEFAULT CHARACTER SET' => array(4, 'var='),
'DEFAULT CHARSET' => array(4, 'var='),
'CHECKSUM' => array(5, 'var'),
'DEFAULT COLLATE' => array(6, 'var='),
'COLLATE' => array(6, 'var='),
'COMMENT' => array(7, 'var='),
'CONNECTION' => array(8, 'var'),
'DATA DIRECTORY' => array(9, 'var'),
'DELAY_KEY_WRITE' => array(10, 'var'),
'INDEX DIRECTORY' => array(11, 'var'),
'INSERT_METHOD' => array(12, 'var'),
'KEY_BLOCK_SIZE' => array(13, 'var'),
'MAX_ROWS' => array(14, 'var'),
'MIN_ROWS' => array(15, 'var'),
'PACK_KEYS' => array(16, 'var'),
'PASSWORD' => array(17, 'var'),
'ROW_FORMAT' => array(18, 'var'),
'TABLESPACE' => array(19, 'var'),
'STORAGE' => array(20, 'var'),
'UNION' => array(21, 'var'),
);
/**
* All function options.
*
* @var array
*/
public static $FUNC_OPTIONS = array(
'COMMENT' => array(1, 'var='),
'LANGUAGE SQL' => 2,
'DETERMINISTIC' => 3,
'NOT DETERMINISTIC' => 3,
'CONTAINS SQL' => 4,
'NO SQL' => 4,
'READS SQL DATA' => 4,
'MODIFIES SQL DATA' => 4,
'SQL SECURITY DEFINER' => array(5, 'var'),
);
/**
* All trigger options.
*
* @var array
*/
public static $TRIGGER_OPTIONS = array(
'BEFORE' => 1,
'AFTER' => 1,
'INSERT' => 2,
'UPDATE' => 2,
'DELETE' => 2,
);
/**
* The name of the entity that is created.
*
* Used by all `CREATE` statements.
*
* @var Expression
*/
public $name;
/**
* The options of the entity (table, procedure, function, etc.).
*
* Used by `CREATE TABLE`, `CREATE FUNCTION` and `CREATE PROCEDURE`.
*
* @var OptionsArray
*
* @see static::$TABLE_OPTIONS
* @see static::$FUNC_OPTIONS
* @see static::$TRIGGER_OPTIONS
*/
public $entityOptions;
/**
* If `CREATE TABLE`, a list of columns and keys.
* If `CREATE VIEW`, a list of columns.
*
* Used by `CREATE TABLE` and `CREATE VIEW`.
*
* @var CreateDefinition[]|ArrayObj
*/
public $fields;
/**
* Expression used for partitioning.
*
* @var string
*/
public $partitionBy;
/**
* The number of partitions.
*
* @var int
*/
public $partitionsNum;
/**
* Expression used for subpartitioning.
*
* @var string
*/
public $subpartitionBy;
/**
* The number of subpartitions.
*
* @var int
*/
public $subpartitionsNum;
/**
* The partition of the new table.
*
* @var PartitionDefinition[]
*/
public $partitions;
/**
* If `CREATE TRIGGER` the name of the table.
*
* Used by `CREATE TRIGGER`.
*
* @var Expression
*/
public $table;
/**
* The return data type of this routine.
*
* Used by `CREATE FUNCTION`.
*
* @var DataType
*/
public $return;
/**
* The parameters of this routine.
*
* Used by `CREATE FUNCTION` and `CREATE PROCEDURE`.
*
* @var ParameterDefinition[]
*/
public $parameters;
/**
* The body of this function or procedure. For views, it is the select
* statement that gets the
*
* Used by `CREATE FUNCTION`, `CREATE PROCEDURE` and `CREATE VIEW`.
*
* @var Token[]|string
*/
public $body = array();
/**
* @return string
*/
public function build()
{
$fields = '';
if (!empty($this->fields)) {
if (is_array($this->fields)) {
$fields = CreateDefinition::build($this->fields) . ' ';
} elseif ($this->fields instanceof ArrayObj) {
$fields = ArrayObj::build($this->fields);
}
}
if ($this->options->has('DATABASE')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. OptionsArray::build($this->entityOptions);
} elseif ($this->options->has('TABLE')) {
$partition = '';
if (!empty($this->partitionBy)) {
$partition .= "\nPARTITION BY " . $this->partitionBy;
}
if (!empty($this->partitionsNum)) {
$partition .= "\nPARTITIONS " . $this->partitionsNum;
}
if (!empty($this->subpartitionBy)) {
$partition .= "\nSUBPARTITION BY " . $this->subpartitionBy;
}
if (!empty($this->subpartitionsNum)) {
$partition .= "\nSUBPARTITIONS " . $this->subpartitionsNum;
}
if (!empty($this->partitions)) {
$partition .= "\n" . PartitionDefinition::build($this->partitions);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields
. OptionsArray::build($this->entityOptions)
. $partition;
} elseif ($this->options->has('VIEW')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. $fields . ' AS ' . TokensList::build($this->body) . ' '
. OptionsArray::build($this->entityOptions);
} elseif ($this->options->has('TRIGGER')) {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. OptionsArray::build($this->entityOptions) . ' '
. 'ON ' . Expression::build($this->table) . ' '
. 'FOR EACH ROW ' . TokensList::build($this->body);
} elseif (($this->options->has('PROCEDURE'))
|| ($this->options->has('FUNCTION'))
) {
$tmp = '';
if ($this->options->has('FUNCTION')) {
$tmp = 'RETURNS ' . DataType::build($this->return);
}
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. ParameterDefinition::build($this->parameters) . ' '
. $tmp . ' ' . TokensList::build($this->body);
} else {
return 'CREATE '
. OptionsArray::build($this->options) . ' '
. Expression::build($this->name) . ' '
. TokensList::build($this->body);
}
return '';
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
++$list->idx; // Skipping `CREATE`.
// Parsing options.
$this->options = OptionsArray::parse($parser, $list, static::$OPTIONS);
++$list->idx; // Skipping last option.
// Parsing the field name.
$this->name = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
if ((!isset($this->name)) || ($this->name === '')) {
$parser->error(
__('The name of the entity was expected.'),
$list->tokens[$list->idx]
);
} else {
++$list->idx; // Skipping field.
}
if ($this->options->has('DATABASE')) {
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$DB_OPTIONS
);
} elseif ($this->options->has('TABLE')) {
$this->fields = CreateDefinition::parse($parser, $list);
if (empty($this->fields)) {
$parser->error(
__('At least one column definition was expected.'),
$list->tokens[$list->idx]
);
}
++$list->idx;
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TABLE_OPTIONS
);
/**
* The field that is being filled (`partitionBy` or
* `subpartitionBy`).
*
* @var string $field
*/
$field = null;
/**
* The number of brackets. `false` means no bracket was found
* previously. At least one bracket is required to validate the
* expression.
*
* @var int|bool $brackets
*/
$brackets = false;
/*
* Handles partitions.
*/
for (; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $token
*/
$token = $list->tokens[$list->idx];
// End of statement.
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
// Skipping comments.
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'PARTITION BY')) {
$field = 'partitionBy';
$brackets = false;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITION BY')) {
$field = 'subpartitionBy';
$brackets = false;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'PARTITIONS')) {
$token = $list->getNextOfType(Token::TYPE_NUMBER);
--$list->idx; // `getNextOfType` also advances one position.
$this->partitionsNum = $token->value;
} elseif (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'SUBPARTITIONS')) {
$token = $list->getNextOfType(Token::TYPE_NUMBER);
--$list->idx; // `getNextOfType` also advances one position.
$this->subpartitionsNum = $token->value;
} elseif (!empty($field)) {
/*
* Handling the content of `PARTITION BY` and `SUBPARTITION BY`.
*/
// Counting brackets.
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
// This is used instead of `++$brackets` because,
// initially, `$brackets` is `false` cannot be
// incremented.
$brackets = $brackets + 1;
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === ')')) {
--$brackets;
}
// Building the expression used for partitioning.
$this->$field .= ($token->type === Token::TYPE_WHITESPACE) ? ' ' : $token->token;
// Last bracket was read, the expression ended.
// Comparing with `0` and not `false`, because `false` means
// that no bracket was found and at least one must is
// required.
if ($brackets === 0) {
$this->$field = trim($this->$field);
$field = null;
}
} elseif (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
if (!empty($this->partitionBy)) {
$this->partitions = ArrayObj::parse(
$parser,
$list,
array(
'type' => 'SqlParser\\Components\\PartitionDefinition'
)
);
}
break;
}
}
} elseif (($this->options->has('PROCEDURE'))
|| ($this->options->has('FUNCTION'))
) {
$this->parameters = ParameterDefinition::parse($parser, $list);
if ($this->options->has('FUNCTION')) {
$token = $list->getNextOfType(Token::TYPE_KEYWORD);
if ($token->value !== 'RETURNS') {
$parser->error(
__('A "RETURNS" keyword was expected.'),
$token
);
} else {
++$list->idx;
$this->return = DataType::parse(
$parser,
$list
);
}
}
++$list->idx;
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$FUNC_OPTIONS
);
++$list->idx;
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
$this->body[] = $token;
}
} elseif ($this->options->has('VIEW')) {
$token = $list->getNext(); // Skipping whitespaces and comments.
// Parsing columns list.
if (($token->type === Token::TYPE_OPERATOR) && ($token->value === '(')) {
--$list->idx; // getNext() also goes forward one field.
$this->fields = ArrayObj::parse($parser, $list);
++$list->idx; // Skipping last token from the array.
$list->getNext();
}
// Parsing the `AS` keyword.
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
$this->body[] = $token;
}
} elseif ($this->options->has('TRIGGER')) {
// Parsing the time and the event.
$this->entityOptions = OptionsArray::parse(
$parser,
$list,
static::$TRIGGER_OPTIONS
);
++$list->idx;
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'ON');
++$list->idx; // Skipping `ON`.
// Parsing the name of the table.
$this->table = Expression::parse(
$parser,
$list,
array(
'parseField' => 'table',
'breakOnAlias' => true,
)
);
++$list->idx;
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'FOR EACH ROW');
++$list->idx; // Skipping `FOR EACH ROW`.
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
$this->body[] = $token;
}
} else {
for (; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_DELIMITER) {
break;
}
$this->body[] = $token;
}
}
}
}

View File

@ -1,99 +0,0 @@
<?php
/**
* `DELETE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\Expression;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\Condition;
/**
* `DELETE` statement.
*
* DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
* [PARTITION (partition_name,...)]
* [WHERE where_condition]
* [ORDER BY ...]
* [LIMIT row_count]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class DeleteStatement extends Statement
{
/**
* Options for `DELETE` statements.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'QUICK' => 2,
'IGNORE' => 3,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'DELETE' => array('DELETE', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
'FROM' => array('FROM', 3),
'PARTITION' => array('PARTITION', 3),
'WHERE' => array('WHERE', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
);
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $from;
/**
* Partitions used as source for this statement.
*
* @var ArrayObj
*/
public $partition;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
}

View File

@ -1,70 +0,0 @@
<?php
/**
* `DROP` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `DROP` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class DropStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'DATABASE' => 1,
'EVENT' => 1,
'FUNCTION' => 1,
'INDEX' => 1,
'LOGFILE' => 1,
'PROCEDURE' => 1,
'SCHEMA' => 1,
'SERVER' => 1,
'TABLE' => 1,
'TABLESPACE' => 1,
'TRIGGER' => 1,
'TEMPORARY' => 2,
'IF EXISTS' => 3,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'DROP' => array('DROP', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for select expressions.
'DROP_' => array('DROP', 1),
);
/**
* Dropped elements.
*
* @var Expression[]
*/
public $fields;
}

View File

@ -1,23 +0,0 @@
<?php
/**
* `EXPLAIN` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `EXPLAIN` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ExplainStatement extends NotImplementedStatement
{
}

View File

@ -1,93 +0,0 @@
<?php
/**
* `INSERT` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\Array2d;
use SqlParser\Components\ArrayObj;
/**
* `INSERT` statement.
*
* INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* or
*
* INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* SET col_name={expr | DEFAULT}, ...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* or
*
* INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
* [INTO] tbl_name
* [PARTITION (partition_name,...)]
* [(col_name,...)]
* SELECT ...
* [ ON DUPLICATE KEY UPDATE
* col_name=expr
* [, col_name=expr] ... ]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class InsertStatement extends Statement
{
/**
* Options for `INSERT` statements.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 2,
'HIGH_PRIORITY' => 3,
'IGNORE' => 4,
);
/**
* Tables used as target for this statement.
*
* @var IntoKeyword
*/
public $into;
/**
* Values to be inserted.
*
* @var ArrayObj[]
*/
public $values;
/**
* @return string
*/
public function build()
{
return 'INSERT ' . $this->options
. ' INTO ' . $this->into
. ' VALUES ' . ArrayObj::build($this->values);
}
}

View File

@ -1,68 +0,0 @@
<?php
/**
* Maintenance statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\Expression;
use SqlParser\Components\OptionsArray;
/**
* Maintenance statement.
*
* They follow the syntax:
* STMT [some options] tbl_name [, tbl_name] ... [some more options]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class MaintenanceStatement extends Statement
{
/**
* Tables maintained.
*
* @var Expression[]
*/
public $tables;
/**
* Function called after the token was processed.
*
* Parses the additional options from the end.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function after(Parser $parser, TokensList $list, Token $token)
{
// [some options] is going to be parsed first.
//
// There is a parser specified in `Parser::$KEYWORD_PARSERS`
// which parses the name of the tables.
//
// Finally, we parse here [some more options] and that's all.
++$list->idx;
$this->options->merge(
OptionsArray::parse(
$parser,
$list,
static::$OPTIONS
)
);
}
}

View File

@ -1,68 +0,0 @@
<?php
/**
* Not implemented (yet) statements.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Not implemented (yet) statements.
*
* The `after` function makes the parser jump straight to the first delimiter.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class NotImplementedStatement extends Statement
{
/**
* The part of the statement that can't be parsed.
*
* @var Token[]
*/
public $unknown = array();
/**
* @return string
*/
public function build()
{
// Building the parsed part of the query (if any).
$query = parent::build() . ' ';
// Rebuilding the unknown part from tokens.
foreach ($this->unknown as $token) {
$query .= $token->token;
}
return $query;
}
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
for (; $list->idx < $list->count; ++$list->idx) {
if ($list->tokens[$list->idx]->type === Token::TYPE_DELIMITER) {
break;
}
$this->unknown[] = $list->tokens[$list->idx];
}
}
}

View File

@ -1,48 +0,0 @@
<?php
/**
* `OPTIMIZE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `OPTIMIZE` statement.
*
* OPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class OptimizeStatement extends Statement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
);
/**
* Optimized tables.
*
* @var Expression[]
*/
public $tables;
}

View File

@ -1,57 +0,0 @@
<?php
/**
* `RENAME` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\RenameOperation;
/**
* `RENAME` statement.
*
* RENAME TABLE tbl_name TO new_tbl_name
* [, tbl_name2 TO new_tbl_name2] ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class RenameStatement extends Statement
{
/**
* The old and new names of the tables.
*
* @var RenameOperation[]
*/
public $renames;
/**
* Function called before the token is processed.
*
* Skips the `TABLE` keyword after `RENAME`.
*
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
* @param Token $token The token that is being parsed.
*
* @return void
*/
public function before(Parser $parser, TokensList $list, Token $token)
{
if (($token->type === Token::TYPE_KEYWORD) && ($token->value === 'RENAME')) {
// Checking if it is the beginning of the query.
$list->getNextOfTypeAndValue(Token::TYPE_KEYWORD, 'TABLE');
}
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* `REPAIR` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `REPAIR` statement.
*
* REPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE
* tbl_name [, tbl_name] ...
* [QUICK] [EXTENDED] [USE_FRM]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class RepairStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'NO_WRITE_TO_BINLOG' => 2,
'LOCAL' => 3,
'QUICK' => 4,
'EXTENDED' => 5,
'USE_FRM' => 6,
);
}

View File

@ -1,84 +0,0 @@
<?php
/**
* `REPLACE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\SetOperation;
use SqlParser\Components\Array2d;
/**
* `REPLACE` statement.
*
* REPLACE [LOW_PRIORITY | DELAYED]
* [INTO] tbl_name [(col_name,...)]
* {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
*
* or
*
* REPLACE [LOW_PRIORITY | DELAYED]
* [INTO] tbl_name
* SET col_name={expr | DEFAULT}, ...
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ReplaceStatement extends Statement
{
/**
* Options for `REPLACE` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'DELAYED' => 1,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'REPLACE' => array('REPLACE', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
'INTO' => array('FROM', 3),
'VALUES' => array('VALUES', 1),
'SET' => array('PARTITION', 3),
);
/**
* Tables used as target for this statement.
*
* @var IntoKeyword
*/
public $into;
/**
* Values to be replaced.
*
* @var Array2d
*/
public $values;
/**
* The replaced values.
*
* @var SetOperation[]
*/
public $set;
}

View File

@ -1,36 +0,0 @@
<?php
/**
* `RESTORE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `RESTORE` statement.
*
* RESTORE TABLE tbl_name [, tbl_name] ... FROM '/path/to/backup/directory'
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class RestoreStatement extends MaintenanceStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
'FROM' => array(2, 'var'),
);
}

View File

@ -1,219 +0,0 @@
<?php
/**
* `SELECT` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\ArrayObj;
use SqlParser\Components\FunctionCall;
use SqlParser\Components\Expression;
use SqlParser\Components\IntoKeyword;
use SqlParser\Components\JoinKeyword;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\Condition;
/**
* `SELECT` statement.
*
* SELECT
* [ALL | DISTINCT | DISTINCTROW ]
* [HIGH_PRIORITY]
* [MAX_STATEMENT_TIME = N]
* [STRAIGHT_JOIN]
* [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
* [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
* select_expr [, select_expr ...]
* [FROM table_references
* [PARTITION partition_list]
* [WHERE where_condition]
* [GROUP BY {col_name | expr | position}
* [ASC | DESC], ... [WITH ROLLUP]]
* [HAVING where_condition]
* [ORDER BY {col_name | expr | position}
* [ASC | DESC], ...]
* [LIMIT {[offset,] row_count | row_count OFFSET offset}]
* [PROCEDURE procedure_name(argument_list)]
* [INTO OUTFILE 'file_name'
* [CHARACTER SET charset_name]
* export_options
* | INTO DUMPFILE 'file_name'
* | INTO var_name [, var_name]]
* [FOR UPDATE | LOCK IN SHARE MODE]]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class SelectStatement extends Statement
{
/**
* Options for `SELECT` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'ALL' => 1,
'DISTINCT' => 1,
'DISTINCTROW' => 1,
'HIGH_PRIORITY' => 2,
'MAX_STATEMENT_TIME' => array(3, 'var='),
'STRAIGHT_JOIN' => 4,
'SQL_SMALL_RESULT' => 5,
'SQL_BIG_RESULT' => 6,
'SQL_BUFFER_RESULT' => 7,
'SQL_CACHE' => 8,
'SQL_NO_CACHE' => 8,
'SQL_CALC_FOUND_ROWS' => 9,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'SELECT' => array('SELECT', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for selected expressions.
'_SELECT' => array('SELECT', 1),
'FROM' => array('FROM', 3),
'PARTITION' => array('PARTITION', 3),
'JOIN' => array('JOIN', 1),
'FULL JOIN' => array('FULL JOIN', 1),
'INNER JOIN' => array('INNER JOIN', 1),
'LEFT JOIN' => array('LEFT JOIN', 1),
'LEFT OUTER JOIN' => array('LEFT OUTER JOIN', 1),
'RIGHT JOIN' => array('RIGHT JOIN', 1),
'RIGHT OUTER JOIN' => array('RIGHT OUTER JOIN', 1),
'WHERE' => array('WHERE', 3),
'GROUP BY' => array('GROUP BY', 3),
'HAVING' => array('HAVING', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
'PROCEDURE' => array('PROCEDURE', 3),
'INTO' => array('INTO', 3),
'UNION' => array('UNION', 1),
// These are available only when `UNION` is present.
// 'ORDER BY' => array('ORDER BY', 3),
// 'LIMIT' => array('LIMIT', 3),
);
/**
* Expressions that are being selected by this statement.
*
* @var Expression[]
*/
public $expr = array();
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $from = array();
/**
* Partitions used as source for this statement.
*
* @var ArrayObj
*/
public $partition;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Conditions used for grouping the result set.
*
* @var OrderKeyword[]
*/
public $group;
/**
* Conditions used for filtering the result set.
*
* @var Condition[]
*/
public $having;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
/**
* Procedure that should process the data in the result set.
*
* @var FunctionCall
*/
public $procedure;
/**
* Destination of this result set.
*
* @var IntoKeyword
*/
public $into;
/**
* Joins.
*
* @var JoinKeyword[]
*/
public $join;
/**
* Unions.
*
* @var SelectStatement[]
*/
public $union = array();
/**
* Gets the clauses of this statement.
*
* @return array
*/
public function getClauses()
{
// This is a cheap fix for `SELECT` statements that contain `UNION`.
// The `ORDER BY` and `LIMIT` clauses should be at the end of the
// statement.
if (!empty($this->union)) {
$clauses = static::$CLAUSES;
unset($clauses['ORDER BY']);
unset($clauses['LIMIT']);
$clauses['ORDER BY'] = array('ORDER BY', 3);
$clauses['LIMIT'] = array('LIMIT', 3);
return $clauses;
}
return static::$CLAUSES;
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* `SET` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\SetOperation;
/**
* `SET` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class SetStatement extends Statement
{
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'SET' => array('SET', 3),
);
/**
* The updated values.
*
* @var SetOperation[]
*/
public $set;
}

View File

@ -1,71 +0,0 @@
<?php
/**
* `SHOW` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
/**
* `SHOW` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class ShowStatement extends NotImplementedStatement
{
/**
* Options of this statement.
*
* @var array
*/
public static $OPTIONS = array(
'CREATE' => 1,
'AUTHORS' => 2,
'BINARY' => 2,
'BINLOG' => 2,
'CHARACTER' => 2,
'CODE' => 2,
'COLLATION' => 2,
'COLUMNS' => 2,
'CONTRIBUTORS' => 2,
'DATABASE' => 2,
'DATABASES' => 2,
'ENGINE' => 2,
'ENGINES' => 2,
'ERRORS' => 2,
'EVENT' => 2,
'EVENTS' => 2,
'FUNCTION' => 2,
'GRANTS' => 2,
'HOSTS' => 2,
'INDEX' => 2,
'INNODB' => 2,
'LOGS' => 2,
'MASTER' => 2,
'OPEN' => 2,
'PLUGINS' => 2,
'PRIVILEGES' => 2,
'PROCEDURE' => 2,
'PROCESSLIST' => 2,
'PROFILE' => 2,
'PROFILES' => 2,
'SCHEDULER' => 2,
'SET' => 2,
'SLAVE' => 2,
'STATUS' => 2,
'TABLE' => 2,
'TABLES' => 2,
'TRIGGER' => 2,
'TRIGGERS' => 2,
'VARIABLES' => 2,
'VIEW' => 2,
'WARNINGS' => 2,
);
}

View File

@ -1,120 +0,0 @@
<?php
/**
* Transaction statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\TokensList;
use SqlParser\Components\OptionsArray;
/**
* Transaction statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class TransactionStatement extends Statement
{
/**
* START TRANSACTION and BEGIN
*
* @var int
*/
const TYPE_BEGIN = 1;
/**
* COMMIT and ROLLBACK
*
* @var int
*/
const TYPE_END = 2;
/**
* The type of this query.
*
* @var int
*/
public $type;
/**
* The list of statements in this transaction.
*
* @var Statement[]
*/
public $statements;
/**
* The ending transaction statement which may be a `COMMIT` or a `ROLLBACK`.
*
* @var TransactionStatement
*/
public $end;
/**
* Options for this query.
*
* @var array
*/
public static $OPTIONS = array(
'START TRANSACTION' => 1,
'BEGIN' => 1,
'COMMIT' => 1,
'ROLLBACK' => 1,
'WITH CONSISTENT SNAPSHOT' => 2,
'WORK' => 2,
'AND NO CHAIN' => 3,
'AND CHAIN' => 3,
'RELEASE' => 4,
'NO RELEASE' => 4,
);
/**
* @param Parser $parser The instance that requests parsing.
* @param TokensList $list The list of tokens to be parsed.
*
* @return void
*/
public function parse(Parser $parser, TokensList $list)
{
parent::parse($parser, $list);
// Checks the type of this query.
if (($this->options->has('START TRANSACTION'))
|| ($this->options->has('BEGIN'))
) {
$this->type = TransactionStatement::TYPE_BEGIN;
} elseif (($this->options->has('COMMIT'))
|| ($this->options->has('ROLLBACK'))
) {
$this->type = TransactionStatement::TYPE_END;
}
}
/**
* @return string
*/
public function build()
{
$ret = OptionsArray::build($this->options);
if ($this->type === TransactionStatement::TYPE_BEGIN) {
foreach ($this->statements as $statement) {
/**
* @var SelectStatement $statement
*/
$ret .= ';' . $statement->build();
}
$ret .= ';' . $this->end->build();
}
return $ret;
}
}

View File

@ -1,41 +0,0 @@
<?php
/**
* `TRUNCATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
/**
* `TRUNCATE` statement.
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class TruncateStatement extends Statement
{
/**
* Options for `TRUNCATE` statements.
*
* @var array
*/
public static $OPTIONS = array(
'TABLE' => 1,
);
/**
* The name of the truncated table.
*
* @var Expression
*/
public $table;
}

View File

@ -1,105 +0,0 @@
<?php
/**
* `UPDATE` statement.
*
* @package SqlParser
* @subpackage Statements
*/
namespace SqlParser\Statements;
use SqlParser\Statement;
use SqlParser\Components\Expression;
use SqlParser\Components\Limit;
use SqlParser\Components\OrderKeyword;
use SqlParser\Components\SetOperation;
use SqlParser\Components\Condition;
/**
* `UPDATE` statement.
*
* UPDATE [LOW_PRIORITY] [IGNORE] table_reference
* SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
* [WHERE where_condition]
* [ORDER BY ...]
* [LIMIT row_count]
*
* or
*
* UPDATE [LOW_PRIORITY] [IGNORE] table_references
* SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
* [WHERE where_condition]
*
* @category Statements
* @package SqlParser
* @subpackage Statements
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class UpdateStatement extends Statement
{
/**
* Options for `UPDATE` statements and their slot ID.
*
* @var array
*/
public static $OPTIONS = array(
'LOW_PRIORITY' => 1,
'IGNORE' => 2,
);
/**
* The clauses of this statement, in order.
*
* @see Statement::$CLAUSES
*
* @var array
*/
public static $CLAUSES = array(
'UPDATE' => array('UPDATE', 2),
// Used for options.
'_OPTIONS' => array('_OPTIONS', 1),
// Used for updated tables.
'_UPDATE' => array('UPDATE', 1),
'SET' => array('SET', 3),
'WHERE' => array('WHERE', 3),
'ORDER BY' => array('ORDER BY', 3),
'LIMIT' => array('LIMIT', 3),
);
/**
* Tables used as sources for this statement.
*
* @var Expression[]
*/
public $tables;
/**
* The updated values.
*
* @var SetOperation[]
*/
public $set;
/**
* Conditions used for filtering each row of the result set.
*
* @var Condition[]
*/
public $where;
/**
* Specifies the order of the rows in the result set.
*
* @var OrderKeyword[]
*/
public $order;
/**
* Conditions used for limiting the size of the result set.
*
* @var Limit
*/
public $limit;
}

View File

@ -1,292 +0,0 @@
<?php
/**
* Defines a token along with a set of types and flags and utility functions.
*
* An array of tokens will result after parsing the query.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* A structure representing a lexeme that explicitly indicates its
* categorization for the purpose of parsing.
*
* @category Tokens
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Token
{
// Types of tokens (a vague description of a token's purpose).
/**
* This type is used when the token is invalid or its type cannot be
* determined because of the ambiguous context. Further analysis might be
* required to detect its type.
*
* @var int
*/
const TYPE_NONE = 0;
/**
* SQL specific keywords: SELECT, UPDATE, INSERT, etc.
*
* @var int
*/
const TYPE_KEYWORD = 1;
/**
* Any type of legal operator.
*
* Arithmetic operators: +, -, *, /, etc.
* Logical operators: ===, <>, !==, etc.
* Bitwise operators: &, |, ^, etc.
* Assignment operators: =, +=, -=, etc.
* SQL specific operators: . (e.g. .. WHERE database.table ..),
* * (e.g. SELECT * FROM ..)
*
* @var int
*/
const TYPE_OPERATOR = 2;
/**
* Spaces, tabs, new lines, etc.
*
* @var int
*/
const TYPE_WHITESPACE = 3;
/**
* Any type of legal comment.
*
* Bash (#), C (/* *\/) or SQL (--) comments:
*
* -- SQL-comment
*
* #Bash-like comment
*
* /*C-like comment*\/
*
* or:
*
* /*C-like
* comment*\/
*
* Backslashes were added to respect PHP's comments syntax.
*
* @var int
*/
const TYPE_COMMENT = 4;
/**
* Boolean values: true or false.
*
* @var int
*/
const TYPE_BOOL = 5;
/**
* Numbers: 4, 0x8, 15.16, 23e42, etc.
*
* @var int
*/
const TYPE_NUMBER = 6;
/**
* Literal strings: 'string', "test".
* Some of these strings are actually symbols.
*
* @var int
*/
const TYPE_STRING = 7;
/**
* Database, table names, variables, etc.
* For example: ```SELECT `foo`, `bar` FROM `database`.`table`;```
*
* @var int
*/
const TYPE_SYMBOL = 8;
/**
* Delimits an unknown string.
* For example: ```SELECT * FROM test;```, `test` is a delimiter.
*
* @var int
*/
const TYPE_DELIMITER = 9;
// Flags that describe the tokens in more detail.
// All keywords must have flag 1 so `Context::isKeyword` method doesn't
// require strict comparison.
const FLAG_KEYWORD_RESERVED = 2;
const FLAG_KEYWORD_COMPOSED = 4;
const FLAG_KEYWORD_DATA_TYPE = 8;
const FLAG_KEYWORD_KEY = 16;
const FLAG_KEYWORD_FUNCTION = 32;
// Numbers related flags.
const FLAG_NUMBER_HEX = 1;
const FLAG_NUMBER_FLOAT = 2;
const FLAG_NUMBER_APPROXIMATE = 4;
const FLAG_NUMBER_NEGATIVE = 8;
const FLAG_NUMBER_BINARY = 16;
// Strings related flags.
const FLAG_STRING_SINGLE_QUOTES = 1;
const FLAG_STRING_DOUBLE_QUOTES = 2;
// Comments related flags.
const FLAG_COMMENT_BASH = 1;
const FLAG_COMMENT_C = 2;
const FLAG_COMMENT_SQL = 4;
const FLAG_COMMENT_MYSQL_CMD = 8;
// Operators related flags.
const FLAG_OPERATOR_ARITHMETIC = 1;
const FLAG_OPERATOR_LOGICAL = 2;
const FLAG_OPERATOR_BITWISE = 4;
const FLAG_OPERATOR_ASSIGNMENT = 8;
const FLAG_OPERATOR_SQL = 16;
// Symbols related flags.
const FLAG_SYMBOL_VARIABLE = 1;
const FLAG_SYMBOL_BACKTICK = 2;
const FLAG_SYMBOL_USER = 4;
const FLAG_SYMBOL_SYSTEM = 8;
/**
* The token it its raw string representation.
*
* @var string
*/
public $token;
/**
* The value this token contains (i.e. token after some evaluation)
*
* @var mixed
*/
public $value;
/**
* The type of this token.
*
* @var int
*/
public $type;
/**
* The flags of this token.
*
* @var int
*/
public $flags;
/**
* The position in the initial string where this token started.
*
* @var int
*/
public $position;
/**
* Constructor.
*
* @param string $token The value of the token.
* @param int $type The type of the token.
* @param int $flags The flags of the token.
*/
public function __construct($token, $type = 0, $flags = 0)
{
$this->token = $token;
$this->type = $type;
$this->flags = $flags;
$this->value = $this->extract();
}
/**
* Does little processing to the token to extract a value.
*
* If no processing can be done it will return the initial string.
*
* @return mixed
*/
public function extract()
{
switch ($this->type) {
case Token::TYPE_KEYWORD:
if (!($this->flags & Token::FLAG_KEYWORD_RESERVED)) {
// Unreserved keywords should stay the way they are because they
// might represent field names.
return $this->token;
}
return strtoupper($this->token);
case Token::TYPE_WHITESPACE:
return ' ';
case Token::TYPE_BOOL:
return strtoupper($this->token) === 'TRUE';
case Token::TYPE_NUMBER:
$ret = str_replace('--', '', $this->token); // e.g. ---42 === -42
if ($this->flags & Token::FLAG_NUMBER_HEX) {
if ($this->flags & Token::FLAG_NUMBER_NEGATIVE) {
$ret = str_replace('-', '', $this->token);
sscanf($ret, "%x", $ret);
$ret = -$ret;
} else {
sscanf($ret, "%x", $ret);
}
} elseif (($this->flags & Token::FLAG_NUMBER_APPROXIMATE)
|| ($this->flags & Token::FLAG_NUMBER_FLOAT)
) {
sscanf($ret, "%f", $ret);
} else {
sscanf($ret, "%d", $ret);
}
return $ret;
case Token::TYPE_STRING:
$quote = $this->token[0];
$str = str_replace($quote . $quote, $quote, $this->token);
return mb_substr($str, 1, -1, 'UTF-8'); // trims quotes
case Token::TYPE_SYMBOL:
$str = $this->token;
if ((isset($str[0])) && ($str[0] === '@')) {
// `mb_strlen($str)` must be used instead of `null` because
// in PHP 5.3- the `null` parameter isn't handled correctly.
$str = mb_substr(
$str,
((!empty($str[1])) && ($str[1] === '@')) ? 2 : 1,
mb_strlen($str),
'UTF-8'
);
}
if ((isset($str[0])) && (($str[0] === '`')
|| ($str[0] === '"') || ($str[0] === '\''))
) {
$quote = $str[0];
$str = str_replace($quote . $quote, $quote, $str);
$str = mb_substr($str, 1, -1, 'UTF-8');
}
return $str;
}
return $this->token;
}
/**
* Converts the token into an inline token by replacing tabs and new lines.
*
* @return string
*/
public function getInlineToken()
{
return str_replace(
array("\r", "\n", "\t"),
array('\r', '\n', '\t'),
$this->token
);
}
}

View File

@ -1,208 +0,0 @@
<?php
/**
* Defines an array of tokens and utility functions to iterate through it.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* A structure representing a list of tokens.
*
* @category Tokens
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class TokensList implements \ArrayAccess
{
/**
* The array of tokens.
*
* @var array
*/
public $tokens = array();
/**
* The count of tokens.
*
* @var int
*/
public $count = 0;
/**
* The index of the next token to be returned.
*
* @var int
*/
public $idx = 0;
/**
* Constructor.
*
* @param array $tokens The initial array of tokens.
* @param int $count The count of tokens in the initial array.
*/
public function __construct(array $tokens = array(), $count = -1)
{
if (!empty($tokens)) {
$this->tokens = $tokens;
if ($count === -1) {
$this->count = count($tokens);
}
}
}
/**
* Builds an array of tokens by merging their raw value.
*
* @param string|Token[]|TokensList $list The tokens to be built.
*
* @return string
*/
public static function build($list)
{
if (is_string($list)) {
return $list;
}
if ($list instanceof TokensList) {
$list = $list->tokens;
}
$ret = '';
if (is_array($list)) {
foreach ($list as $tok) {
$ret .= $tok->token;
}
}
return $ret;
}
/**
* Adds a new token.
*
* @param Token $token Token to be added in list.
*
* @return void
*/
public function add(Token $token)
{
$this->tokens[$this->count++] = $token;
}
/**
* Gets the next token. Skips any irrelevant token (whitespaces and
* comments).
*
* @return Token
*/
public function getNext()
{
for (; $this->idx < $this->count; ++$this->idx) {
if (($this->tokens[$this->idx]->type !== Token::TYPE_WHITESPACE)
&& ($this->tokens[$this->idx]->type !== Token::TYPE_COMMENT)
) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Gets the next token.
*
* @param int $type The type.
*
* @return Token
*/
public function getNextOfType($type)
{
for (; $this->idx < $this->count; ++$this->idx) {
if ($this->tokens[$this->idx]->type === $type) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Gets the next token.
*
* @param int $type The type of the token.
* @param string $value The value of the token.
*
* @return Token
*/
public function getNextOfTypeAndValue($type, $value)
{
for (; $this->idx < $this->count; ++$this->idx) {
if (($this->tokens[$this->idx]->type === $type)
&& ($this->tokens[$this->idx]->value === $value)
) {
return $this->tokens[$this->idx++];
}
}
return null;
}
/**
* Sets an value inside the container.
*
* @param int $offset The offset to be set.
* @param Token $value The token to be saved.
*
* @return void
*/
public function offsetSet($offset, $value)
{
if ($offset === null) {
$this->tokens[$this->count++] = $value;
} else {
$this->tokens[$offset] = $value;
}
}
/**
* Gets a value from the container.
*
* @param int $offset The offset to be returned.
*
* @return Token
*/
public function offsetGet($offset)
{
return $offset < $this->count ? $this->tokens[$offset] : null;
}
/**
* Checks if an offset was previously set.
*
* @param int $offset The offset to be checked.
*
* @return bool
*/
public function offsetExists($offset)
{
return $offset < $this->count;
}
/**
* Unsets the value of an offset.
*
* @param int $offset The offset to be unset.
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->tokens[$offset]);
--$this->count;
for ($i = $offset; $i < $this->count; ++$i) {
$this->tokens[$i] = $this->tokens[$i + 1];
}
unset($this->tokens[$this->count]);
}
}

View File

@ -1,218 +0,0 @@
<?php
/**
* Implementation for UTF-8 strings.
*
* The subscript operator in PHP, when used with string will return a byte
* and not a character. Because in UTF-8 strings a character may occupy more
* than one byte, the subscript operator may return an invalid character.
*
* Because the lexer relies on the subscript operator this class had to be
* implemented.
*
* @package SqlParser
*/
namespace SqlParser;
/**
* Implements array-like access for UTF-8 strings.
*
* In this library, this class should be used to parse UTF-8 queries.
*
* @category Misc
* @package SqlParser
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class UtfString implements \ArrayAccess
{
/**
* The raw, multi-byte string.
*
* @var string
*/
public $str = '';
/**
* The index of current byte.
*
* For ASCII strings, the byte index is equal to the character index.
*
* @var int
*/
public $byteIdx = 0;
/**
* The index of current character.
*
* For non-ASCII strings, some characters occupy more than one byte and
* the character index will have a lower value than the byte index.
*
* @var int
*/
public $charIdx = 0;
/**
* The length of the string (in bytes).
*
* @var int
*/
public $byteLen = 0;
/**
* The length of the string (in characters).
*
* @var int
*/
public $charLen = 0;
/**
* Constructor.
*
* @param string $str The string.
*/
public function __construct($str)
{
$this->str = $str;
$this->byteIdx = 0;
$this->charIdx = 0;
// TODO: `strlen($str)` might return a wrong length when function
// overloading is enabled.
// https://php.net/manual/ro/mbstring.overload.php
$this->byteLen = strlen($str);
$this->charLen = mb_strlen($str, 'UTF-8');
}
/**
* Checks if the given offset exists.
*
* @param int $offset The offset to be checked.
*
* @return bool
*/
public function offsetExists($offset)
{
return ($offset >= 0) && ($offset < $this->charLen);
}
/**
* Gets the character at given offset.
*
* @param int $offset The offset to be returned.
*
* @return string
*/
public function offsetGet($offset)
{
if (($offset < 0) || ($offset >= $this->charLen)) {
return null;
}
$delta = $offset - $this->charIdx;
if ($delta > 0) {
// Fast forwarding.
while ($delta-- > 0) {
$this->byteIdx += static::getCharLength($this->str[$this->byteIdx]);
++$this->charIdx;
}
} elseif ($delta < 0) {
// Rewinding.
while ($delta++ < 0) {
do {
$byte = ord($this->str[--$this->byteIdx]);
} while ((128 <= $byte) && ($byte < 192));
--$this->charIdx;
}
}
$bytesCount = static::getCharLength($this->str[$this->byteIdx]);
$ret = '';
for ($i = 0; $bytesCount-- > 0; ++$i) {
$ret .= $this->str[$this->byteIdx + $i];
}
return $ret;
}
/**
* Sets the value of a character.
*
* @param int $offset The offset to be set.
* @param string $value The value to be set.
*
* @throws \Exception Not implemented.
*
* @return void
*/
public function offsetSet($offset, $value)
{
throw new \Exception('Not implemented.');
}
/**
* Unsets an index.
*
* @param int $offset The value to be unset.
*
* @throws \Exception Not implemented.
*
* @return void
*/
public function offsetUnset($offset)
{
throw new \Exception('Not implemented.');
}
/**
* Gets the length of an UTF-8 character.
*
* According to RFC 3629, a UTF-8 character can have at most 4 bytes.
* However, this implementation supports UTF-8 characters containing up to 6
* bytes.
*
* @param string $byte The byte to be analyzed.
*
* @see http://tools.ietf.org/html/rfc3629
*
* @return int
*/
public static function getCharLength($byte)
{
$byte = ord($byte);
if ($byte < 128) {
return 1;
} elseif ($byte < 224) {
return 2;
} elseif ($byte < 240) {
return 3;
} elseif ($byte < 248) {
return 4;
} elseif ($byte < 252) {
return 5; // unofficial
}
return 6; // unofficial
}
/**
* Returns the length in characters of the string.
*
* @return int
*/
public function length()
{
return $this->charLen;
}
/**
* Returns the contained string.
*
* @return string
*/
public function __toString()
{
return $this->str;
}
}

View File

@ -1,417 +0,0 @@
<?php
/**
* Buffered query utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Context;
/**
* Buffer query utilities.
*
* Implements a specialized lexer used to extract statements from large inputs
* that are being buffered. After each statement has been extracted, a lexer or
* a parser may be used.
*
* All comments are skipped, with one exception: MySQL commands inside `/*!`.
*
* @category Lexer
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class BufferedQuery
{
// Constants that describe the current status of the parser.
// A string is being parsed.
const STATUS_STRING = 16; // 0001 0000
const STATUS_STRING_SINGLE_QUOTES = 17; // 0001 0001
const STATUS_STRING_DOUBLE_QUOTES = 18; // 0001 0010
const STATUS_STRING_BACKTICK = 20; // 0001 0100
// A comment is being parsed.
const STATUS_COMMENT = 32; // 0010 0000
const STATUS_COMMENT_BASH = 33; // 0010 0001
const STATUS_COMMENT_C = 34; // 0010 0010
const STATUS_COMMENT_SQL = 36; // 0010 0100
/**
* The query that is being processed.
*
* This field can be modified just by appending to it!
*
* @var string
*/
public $query = '';
/**
* The options of this parser.
*
* @var array
*/
public $options = array();
/**
* The last delimiter used.
*
* @var string
*/
public $delimiter;
/**
* The length of the delimiter.
*
* @var int
*/
public $delimiterLen;
/**
* The current status of the parser.
*
* @var int
*/
public $status;
/**
* The last incomplete query that was extracted.
*
* @var string
*/
public $current = '';
/**
* Constructor.
*
* @param string $query The query to be parsed.
* @param array $options The options of this parser.
*/
public function __construct($query = '', array $options = array())
{
// Merges specified options with defaults.
$this->options = array_merge(
array(
/**
* The starting delimiter.
*
* @var string
*/
'delimiter' => ';',
/**
* Whether `DELIMITER` statements should be parsed.
*
* @var bool
*/
'parse_delimiter' => false,
/**
* Whether a delimiter should be added at the end of the
* statement.
*
* @var bool
*/
'add_delimiter' => false,
),
$options
);
$this->query = $query;
$this->setDelimiter($this->options['delimiter']);
}
/**
* Sets the delimiter.
*
* Used to update the length of it too.
*
* @param string $delimiter
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
$this->delimiterLen = strlen($delimiter);
}
/**
* Extracts a statement from the buffer.
*
* @param bool $end Whether the end of the buffer was reached.
*
* @return string
*/
public function extract($end = false)
{
/**
* The last parsed position.
*
* This is statically defined because it is not used outside anywhere
* outside this method and there is probably a (minor) performance
* improvement to it.
*
* @var int
*/
static $i = 0;
if (empty($this->query)) {
return false;
}
/**
* The length of the buffer.
*
* @var int $len
*/
$len = strlen($this->query);
/**
* The last index of the string that is going to be parsed.
*
* There must be a few characters left in the buffer so the parser can
* avoid confusing some symbols that may have multiple meanings.
*
* For example, if the buffer ends in `-` that may be an operator or the
* beginning of a comment.
*
* Another example if the buffer ends in `DELIMITE`. The parser is going
* to require a few more characters because that may be a part of the
* `DELIMITER` keyword or just a column named `DELIMITE`.
*
* Those extra characters are required only if there is more data
* expected (the end of the buffer was not reached).
*
* @var int $loopLen
*/
$loopLen = $end ? $len : $len - 16;
for (; $i < $loopLen; ++$i) {
/**
* Handling backslash.
*
* Even if the next character is a special character that should be
* treated differently, because of the preceding backslash, it will
* be ignored.
*/
if (($this->status & static::STATUS_COMMENT == 0) && ($this->query[$i] === '\\')) {
$this->current .= $this->query[$i] . $this->query[++$i];
continue;
}
/*
* Handling special parses statuses.
*/
if ($this->status === static::STATUS_STRING_SINGLE_QUOTES) {
// Single-quoted strings like 'foo'.
if ($this->query[$i] === '\'') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif ($this->status === static::STATUS_STRING_DOUBLE_QUOTES) {
// Double-quoted strings like "bar".
if ($this->query[$i] === '"') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif ($this->status === static::STATUS_STRING_BACKTICK) {
if ($this->query[$i] === '`') {
$this->status = 0;
}
$this->current .= $this->query[$i];
continue;
} elseif (($this->status === static::STATUS_COMMENT_BASH)
|| ($this->status === static::STATUS_COMMENT_SQL)
) {
// Bash-like (#) or SQL-like (-- ) comments end in new line.
if ($this->query[$i] === "\n") {
$this->status = 0;
}
continue;
} elseif ($this->status === static::STATUS_COMMENT_C) {
// C-like comments end in */.
if (($this->query[$i - 1] === '*') && ($this->query[$i] === '/')) {
$this->status = 0;
}
continue;
}
/*
* Checking if a string started.
*/
if ($this->query[$i] === '\'') {
$this->status = static::STATUS_STRING_SINGLE_QUOTES;
$this->current .= $this->query[$i];
continue;
} elseif ($this->query[$i] === '"') {
$this->status = static::STATUS_STRING_DOUBLE_QUOTES;
$this->current .= $this->query[$i];
continue;
} elseif ($this->query[$i] === '`') {
$this->status = static::STATUS_STRING_BACKTICK;
$this->current .= $this->query[$i];
continue;
}
/*
* Checking if a comment started.
*/
if ($this->query[$i] === '#') {
$this->status = static::STATUS_COMMENT_BASH;
continue;
} elseif (($i + 2 < $len)
&& ($this->query[$i] === '-')
&& ($this->query[$i + 1] === '-')
&& (Context::isWhitespace($this->query[$i + 2]))
) {
$this->status = static::STATUS_COMMENT_SQL;
continue;
} elseif (($i + 2 < $len)
&& ($this->query[$i] === '/')
&& ($this->query[$i + 1] === '*')
&& ($this->query[$i + 2] !== '!')
) {
$this->status = static::STATUS_COMMENT_C;
continue;
}
/*
* Handling `DELIMITER` statement.
*
* The code below basically checks for
* `strtoupper(substr($this->query, $i, 9)) === 'DELIMITER'`
*
* This optimization makes the code about 3 times faster.
*
* `DELIMITER` is not being considered a keyword. The only context
* it has a special meaning is when it is the beginning of a
* statement. This is the reason for the last condition.
*/
if (($i + 9 < $len)
&& (($this->query[$i ] === 'D') || ($this->query[$i ] === 'd'))
&& (($this->query[$i + 1] === 'E') || ($this->query[$i + 1] === 'e'))
&& (($this->query[$i + 2] === 'L') || ($this->query[$i + 2] === 'l'))
&& (($this->query[$i + 3] === 'I') || ($this->query[$i + 3] === 'i'))
&& (($this->query[$i + 4] === 'M') || ($this->query[$i + 4] === 'm'))
&& (($this->query[$i + 5] === 'I') || ($this->query[$i + 5] === 'i'))
&& (($this->query[$i + 6] === 'T') || ($this->query[$i + 6] === 't'))
&& (($this->query[$i + 7] === 'E') || ($this->query[$i + 7] === 'e'))
&& (($this->query[$i + 8] === 'R') || ($this->query[$i + 8] === 'r'))
&& (Context::isWhitespace($this->query[$i + 9]))
&& (trim($this->current) === '')
) {
// Saving the current index to be able to revert any parsing
// done in this block.
$iBak = $i;
$i += 9; // Skipping `DELIMITER`.
// Skipping whitespaces.
while (($i < $len) && (Context::isWhitespace($this->query[$i]))) {
++$i;
}
// Parsing the delimiter.
$delimiter = '';
while (($i < $len) && (!Context::isWhitespace($this->query[$i]))) {
$delimiter .= $this->query[$i++];
}
// Checking if the delimiter definition ended.
if (($delimiter != '')
&& ((($i < $len) && (Context::isWhitespace($this->query[$i])))
|| (($i === $len) && ($end)))
) {
// Saving the delimiter.
$this->setDelimiter($delimiter);
// Whether this statement should be returned or not.
$ret = '';
if (!empty($this->options['parse_delimiter'])) {
// Appending the `DELIMITER` statement that was just
// found to the current statement.
$ret = trim(
$this->current . ' ' . substr($this->query, $iBak, $i - $iBak)
);
}
// Removing the statement that was just extracted from the
// query.
$this->query = substr($this->query, $i);
$i = 0;
// Resetting the current statement.
$this->current = '';
return $ret;
}
// Incomplete statement. Reverting
$i = $iBak;
return false;
}
/*
* Checking if the current statement finished.
*
* The first letter of the delimiter is being checked as an
* optimization. This code is almost as fast as the one above.
*
* There is no point in checking if two strings match if not even
* the first letter matches.
*/
if (($this->query[$i] === $this->delimiter[0])
&& (($this->delimiterLen === 1)
|| (substr($this->query, $i, $this->delimiterLen) === $this->delimiter))
) {
// Saving the statement that just ended.
$ret = $this->current;
// If needed, adds a delimiter at the end of the statement.
if (!empty($this->options['add_delimiter'])) {
$ret .= $this->delimiter;
}
// Removing the statement that was just extracted from the
// query.
$this->query = substr($this->query, $i + $this->delimiterLen);
$i = 0;
// Resetting the current statement.
$this->current = '';
// Returning the statement.
return trim($ret);
}
/*
* Appending current character to current statement.
*/
$this->current .= $this->query[$i];
}
if (($end) && ($i === $len)) {
// If the end of the buffer was reached, the buffer is emptied and
// the current statement that was extracted is returned.
$ret = $this->current;
// Emptying the buffer.
$this->query = '';
$i = 0;
// Resetting the current statement.
$this->current = '';
// Returning the statement.
return trim($ret);
}
return '';
}
}

View File

@ -1,100 +0,0 @@
<?php
/**
* Error related utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
/**
* Error related utilities.
*
* @category Exceptions
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Error
{
/**
* Gets the errors of a lexer and a parser.
*
* @param array $objs Objects from where the errors will be extracted.
*
* @return array Each element of the array represents an error.
* `$err[0]` holds the error message.
* `$err[1]` holds the error code.
* `$err[2]` holds the string that caused the issue.
* `$err[3]` holds the position of the string.
* (i.e. `array($msg, $code, $str, $pos)`)
*/
public static function get($objs)
{
$ret = array();
foreach ($objs as $obj) {
if ($obj instanceof Lexer) {
foreach ($obj->errors as $err) {
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->ch,
$err->pos
);
}
} elseif ($obj instanceof Parser) {
foreach ($obj->errors as $err) {
$ret[] = array(
$err->getMessage(),
$err->getCode(),
$err->token->token,
$err->token->position
);
}
}
}
return $ret;
}
/**
* Formats the specified errors
*
* @param array $errors The errors to be formatted.
* @param string $format The format of an error.
* '$1$d' is replaced by the position of this error.
* '$2$s' is replaced by the error message.
* '$3$d' is replaced by the error code.
* '$4$s' is replaced by the string that caused the
* issue.
* '$5$d' is replaced by the position of the string.
* @return array
*/
public static function format(
$errors,
$format = '#%1$d: %2$s (near "%4$s" at position %5$d)'
) {
$ret = array();
$i = 0;
foreach ($errors as $key => $err) {
$ret[$key] = sprintf(
$format,
++$i,
$err[0],
$err[1],
$err[2],
$err[3]
);
}
return $ret;
}
}

View File

@ -1,532 +0,0 @@
<?php
/**
* Utilities that are used for formatting queries.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Utilities that are used for formatting queries.
*
* @category Misc
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Formatter
{
/**
* The formatting options.
*
* @var array
*/
public $options;
/**
* Clauses that must be inlined.
*
* These clauses usually are short and it's nicer to have them inline.
*
* @var array
*/
public static $INLINE_CLAUSES = array(
'CREATE' => true,
'LIMIT' => true,
'PARTITION BY' => true,
'PARTITION' => true,
'PROCEDURE' => true,
'SUBPARTITION BY' => true,
'VALUES' => true,
);
/**
* Constructor.
*
* @param array $options The formatting options.
*/
public function __construct(array $options = array())
{
// The specified formatting options are merged with the default values.
$this->options = array_merge(
array(
/**
* The format of the result.
*
* @var string The type ('text', 'cli' or 'html')
*/
'type' => php_sapi_name() == 'cli' ? 'cli' : 'text',
/**
* The line ending used.
* By default, for text this is "\n" and for HTML this is "<br/>".
*
* @var string
*/
'line_ending' => $this->options['type'] == 'html' ? '<br/>' : "\n",
/**
* The string used for indentation.
*
* @var string
*/
'indentation' => " ",
/**
* Whether comments should be removed or not.
*
* @var bool
*/
'remove_comments' => false,
/**
* Whether each clause should be on a new line.
*
* @var bool
*/
'clause_newline' => true,
/**
* Whether each part should be on a new line.
* Parts are delimited by brackets and commas.
*
* @var bool
*/
'parts_newline' => true,
/**
* Whether each part of each clause should be indented.
*
* @var bool
*/
'indent_parts' => true,
/**
* The styles used for HTML formatting.
* array($type, $flags, $span, $callback)
*
* @var array[]
*/
'formats' => array(
array(
'type' => Token::TYPE_KEYWORD,
'flags' => Token::FLAG_KEYWORD_RESERVED,
'html' => 'class="sql-reserved"',
'cli' => "\e[35m",
'function' => 'strtoupper',
),
array(
'type' => Token::TYPE_KEYWORD,
'flags' => 0,
'html' => 'class="sql-keyword"',
'cli' => "\e[95m",
'function' => 'strtoupper',
),
array(
'type' => Token::TYPE_COMMENT,
'flags' => 0,
'html' => 'class="sql-comment"',
'cli' => "\e[37m",
'function' => '',
),
array(
'type' => Token::TYPE_BOOL,
'flags' => 0,
'html' => 'class="sql-atom"',
'cli' => "\e[36m",
'function' => 'strtoupper',
),
array(
'type' => Token::TYPE_NUMBER,
'flags' => 0,
'html' => 'class="sql-number"',
'cli' => "\e[92m",
'function' => 'strtolower',
),
array(
'type' => Token::TYPE_STRING,
'flags' => 0,
'html' => 'class="sql-string"',
'cli' => "\e[91m",
'function' => '',
),
array(
'type' => Token::TYPE_SYMBOL,
'flags' => 0,
'html' => 'class="sql-variable"',
'cli' => "\e[36m",
'function' => '',
),
)
),
$options
);
// `parts_newline` requires `clause_newline`
$this->options['parts_newline'] &= $this->options['clause_newline'];
}
/**
* Formats the given list of tokens.
*
* @param TokensList $list The list of tokens.
*
* @return string
*/
public function formatList($list)
{
/**
* The query to be returned.
*
* @var string $ret
*/
$ret = '';
/**
* The indentation level.
*
* @var int $indent
*/
$indent = 0;
/**
* Whether the line ended.
*
* @var bool $lineEnded
*/
$lineEnded = false;
/**
* The name of the last clause.
*
* @var string $lastClause
*/
$lastClause = '';
/**
* A stack that keeps track of the indentation level every time a new
* block is found.
*
* @var array $blocksIndentation
*/
$blocksIndentation = array();
/**
* A stack that keeps track of the line endings every time a new block
* is found.
*
* @var array $blocksLineEndings
*/
$blocksLineEndings = array();
/**
* Whether clause's options were formatted.
*
* @var bool $formattedOptions
*/
$formattedOptions = false;
/**
* Previously parsed token.
*
* @var Token $prev
*/
$prev = null;
/**
* Comments are being formatted separately to maintain the whitespaces
* before and after them.
*
* @var string $comment
*/
$comment = '';
// In order to be able to format the queries correctly, the next token
// must be taken into consideration. The loop below uses two pointers,
// `$prev` and `$curr` which store two consecutive tokens.
// Actually, at every iteration the previous token is being used.
for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
/**
* Token parsed at this moment.
*
* @var Token $curr
*/
$curr = $list->tokens[$list->idx];
if ($curr->type === Token::TYPE_WHITESPACE) {
// Whitespaces are skipped because the formatter adds its own.
continue;
} elseif ($curr->type === Token::TYPE_COMMENT) {
// Whether the comments should be parsed.
if (!empty($this->options['remove_comments'])) {
continue;
}
if ($list->tokens[$list->idx - 1]->type === Token::TYPE_WHITESPACE) {
// The whitespaces before and after are preserved for
// formatting reasons.
$comment .= $list->tokens[$list->idx - 1]->token;
}
$comment .= $this->toString($curr);
if (($list->tokens[$list->idx + 1]->type === Token::TYPE_WHITESPACE)
&& ($list->tokens[$list->idx + 2]->type !== Token::TYPE_COMMENT)
) {
// Adding the next whitespace only there is no comment that
// follows it immediately which may cause adding a
// whitespace twice.
$comment .= $list->tokens[$list->idx + 1]->token;
}
// Everything was handled here, no need to continue.
continue;
}
// Checking if pointers were initialized.
if ($prev !== null) {
// Checking if a new clause started.
if (static::isClause($prev) !== false) {
$lastClause = $prev->value;
$formattedOptions = false;
}
// The options of a clause should stay on the same line and everything that follows.
if (($this->options['parts_newline'])
&& (!$formattedOptions)
&& (empty(self::$INLINE_CLAUSES[$lastClause]))
&& (($curr->type !== Token::TYPE_KEYWORD)
|| (($curr->type === Token::TYPE_KEYWORD)
&& ($curr->flags & Token::FLAG_KEYWORD_FUNCTION)))
) {
$formattedOptions = true;
$lineEnded = true;
++$indent;
}
// Checking if this clause ended.
if ($tmp = static::isClause($curr)) {
if (($tmp == 2) || ($this->options['clause_newline'])) {
$lineEnded = true;
if ($this->options['parts_newline']) {
--$indent;
}
}
}
// Indenting BEGIN ... END blocks.
if (($prev->type === Token::TYPE_KEYWORD) && ($prev->value === 'BEGIN')) {
$lineEnded = true;
array_push($blocksIndentation, $indent);
++$indent;
} elseif (($curr->type === Token::TYPE_KEYWORD) && ($curr->value === 'END')) {
$lineEnded = true;
$indent = array_pop($blocksIndentation);
}
// Formatting fragments delimited by comma.
if (($prev->type === Token::TYPE_OPERATOR) && ($prev->value === ',')) {
// Fragments delimited by a comma are broken into multiple
// pieces only if the clause is not inlined or this fragment
// is between brackets that are on new line.
if (((empty(self::$INLINE_CLAUSES[$lastClause]))
&& ($this->options['parts_newline']))
|| (end($blocksLineEndings) === true)
) {
$lineEnded = true;
}
}
// Handling brackets.
// Brackets are indented only if the length of the fragment between
// them is longer than 30 characters.
if (($prev->type === Token::TYPE_OPERATOR) && ($prev->value === '(')) {
array_push($blocksIndentation, $indent);
if (static::getGroupLength($list) > 30) {
++$indent;
$lineEnded = true;
}
array_push($blocksLineEndings, $lineEnded);
} elseif (($curr->type === Token::TYPE_OPERATOR) && ($curr->value === ')')) {
$indent = array_pop($blocksIndentation);
$lineEnded |= array_pop($blocksLineEndings);
}
// Delimiter must be placed on the same line with the last
// clause.
if ($curr->type === Token::TYPE_DELIMITER) {
$lineEnded = false;
}
// Adding the token.
$ret .= $this->toString($prev);
// Finishing the line.
if ($lineEnded) {
if ($indent < 0) {
// TODO: Make sure this never occurs and delete it.
$indent = 0;
}
if ($curr->type !== Token::TYPE_COMMENT) {
$ret .= $this->options['line_ending']
. str_repeat($this->options['indentation'], $indent);
}
$lineEnded = false;
} else {
// If the line ended there is no point in adding whitespaces.
// Also, some tokens do not have spaces before or after them.
if (!((($prev->type === Token::TYPE_OPERATOR) && (($prev->value === '.') || ($prev->value === '(')))
// No space after . (
|| (($curr->type === Token::TYPE_OPERATOR) && (($curr->value === '.') || ($curr->value === ',') || ($curr->value === '(') || ($curr->value === ')')))
// No space before . , ( )
|| (($curr->type === Token::TYPE_DELIMITER)) && (mb_strlen($curr->value, 'UTF-8') < 2))
// A space after delimiters that are longer than 2 characters.
|| ($prev->value === 'DELIMITER')
) {
$ret .= ' ';
}
}
}
if (!empty($comment)) {
$ret .= $comment;
$comment = '';
}
// Iteration finished, consider current token as previous.
$prev = $curr;
}
return $ret;
}
/**
* Tries to print the query and returns the result.
*
* @param Token $token The token to be printed.
*
* @return string
*/
public function toString($token)
{
$text = $token->token;
foreach ($this->options['formats'] as $format) {
if (($token->type === $format['type'])
&& (($token->flags & $format['flags']) === $format['flags'])
) {
// Running transformation function.
if (!empty($format['function'])) {
$func = $format['function'];
$text = $func($text);
}
// Formatting HTML.
if ($this->options['type'] === 'html') {
return '<span ' . $format['html'] . '>' . $text . '</span>';
} elseif ($this->options['type'] === 'cli') {
return $format['cli'] . $text;
}
break;
}
}
if ($this->options['type'] === 'cli') {
return "\e[39m" . $text;
}
return $text;
}
/**
* Formats a query.
*
* @param string $query The query to be formatted
* @param array $options The formatting options.
*
* @return string The formatted string.
*/
public static function format($query, array $options = array())
{
$lexer = new Lexer($query);
$formatter = new Formatter($options);
return $formatter->formatList($lexer->list);
}
/**
* Computes the length of a group.
*
* A group is delimited by a pair of brackets.
*
* @param TokensList $list The list of tokens.
*
* @return int
*/
public static function getGroupLength($list)
{
/**
* The number of opening brackets found.
* This counter starts at one because by the time this function called,
* the list already advanced one position and the opening bracket was
* already parsed.
*
* @var int $count
*/
$count = 1;
/**
* The length of this group.
*
* @var int $length
*/
$length = 0;
for ($idx = $list->idx; $idx < $list->count; ++$idx) {
// Counting the brackets.
if ($list->tokens[$idx]->type === Token::TYPE_OPERATOR) {
if ($list->tokens[$idx]->value === '(') {
++$count;
} elseif ($list->tokens[$idx]->value === ')') {
--$count;
if ($count == 0) {
break;
}
}
}
// Keeping track of this group's length.
$length += mb_strlen($list->tokens[$idx]->value, 'UTF-8');
}
return $length;
}
/**
* Checks if a token is a statement or a clause inside a statement.
*
* @param Token $token The token to be checked.
*
* @return int|bool
*/
public static function isClause($token)
{
if ((($token->type === Token::TYPE_NONE) && (strtoupper($token->token) === 'DELIMITER'))
|| (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$STATEMENT_PARSERS[$token->value])))
) {
return 2;
} elseif (($token->type === Token::TYPE_KEYWORD) && (isset(Parser::$KEYWORD_PARSERS[$token->value]))) {
return 1;
}
return false;
}
}

View File

@ -1,114 +0,0 @@
<?php
/**
* Miscellaneous utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Components\Expression;
use SqlParser\Statements\SelectStatement;
/**
* Miscellaneous utilities.
*
* @category Misc
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Misc
{
/**
* Gets a list of all aliases and their original names.
*
* @param SelectStatement $statement The statement to be processed.
* @param string $database The name of the database.
*
* @return array
*/
public static function getAliases($statement, $database)
{
if (!($statement instanceof SelectStatement)
|| (empty($statement->expr))
|| (empty($statement->from))
) {
return array();
}
$retval = array();
$tables = array();
/**
* Expressions that may contain aliases.
* These are extracted from `FROM` and `JOIN` keywords.
*
* @var Expression[] $expressions
*/
$expressions = $statement->from;
// Adding expressions from JOIN.
if (!empty($statement->join)) {
foreach ($statement->join as $join) {
$expressions[] = $join->expr;
}
}
foreach ($expressions as $expr) {
if ((!isset($expr->table)) || ($expr->table === '')) {
continue;
}
$thisDb = ((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : $database;
if (!isset($retval[$thisDb])) {
$retval[$thisDb] = array(
'alias' => null,
'tables' => array(),
);
}
if (!isset($retval[$thisDb]['tables'][$expr->table])) {
$retval[$thisDb]['tables'][$expr->table] = array(
'alias' => ((isset($expr->alias)) && ($expr->alias !== '')) ?
$expr->alias : null,
'columns' => array(),
);
}
if (!isset($tables[$thisDb])) {
$tables[$thisDb] = array();
}
$tables[$thisDb][$expr->alias] = $expr->table;
}
foreach ($statement->expr as $expr) {
if ((!isset($expr->column)) || ($expr->column === '')
|| (!isset($expr->alias)) || ($expr->alias === '')
) {
continue;
}
$thisDb = ((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : $database;
if ((isset($expr->table)) && ($expr->table !== '')) {
$thisTable = isset($tables[$thisDb][$expr->table]) ?
$tables[$thisDb][$expr->table] : $expr->table;
$retval[$thisDb]['tables'][$thisTable]['columns'][$expr->column] = $expr->alias;
} else {
foreach ($retval[$thisDb]['tables'] as &$table) {
$table['columns'][$expr->column] = $expr->alias;
}
}
}
return $retval;
}
}

View File

@ -1,787 +0,0 @@
<?php
/**
* Statement utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Statement;
use SqlParser\Token;
use SqlParser\TokensList;
use SqlParser\Components\Expression;
use SqlParser\Statements\AlterStatement;
use SqlParser\Statements\AnalyzeStatement;
use SqlParser\Statements\CallStatement;
use SqlParser\Statements\CheckStatement;
use SqlParser\Statements\ChecksumStatement;
use SqlParser\Statements\CreateStatement;
use SqlParser\Statements\DeleteStatement;
use SqlParser\Statements\DropStatement;
use SqlParser\Statements\ExplainStatement;
use SqlParser\Statements\InsertStatement;
use SqlParser\Statements\OptimizeStatement;
use SqlParser\Statements\RenameStatement;
use SqlParser\Statements\RepairStatement;
use SqlParser\Statements\ReplaceStatement;
use SqlParser\Statements\SelectStatement;
use SqlParser\Statements\ShowStatement;
use SqlParser\Statements\TruncateStatement;
use SqlParser\Statements\UpdateStatement;
/**
* Statement utilities.
*
* @category Statement
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Query
{
/**
* Functions that set the flag `is_func`.
*
* @var array
*/
public static $FUNCTIONS = array(
'SUM', 'AVG', 'STD', 'STDDEV', 'MIN', 'MAX', 'BIT_OR', 'BIT_AND'
);
/**
* Gets an array with flags this statement has.
*
* @param Statement $statement The statement to be processed.
* @param bool $all If `false`, false values will not be included.
*
* @return array
*/
public static function getFlags($statement, $all = false)
{
$flags = array();
if ($all) {
$flags = array(
/**
* select ... DISTINCT ...
*/
'distinct' => false,
/**
* drop ... DATABASE ...
*/
'drop_database' => false,
/**
* ... GROUP BY ...
*/
'group' => false,
/**
* ... HAVING ...
*/
'having' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* DELETE ...
*/
'is_affected' => false,
/**
* select ... PROCEDURE ANALYSE( ... ) ...
*/
'is_analyse' => false,
/**
* select COUNT( ... ) ...
*/
'is_count' => false,
/**
* DELETE ...
*/
'is_delete' => false, // @deprecated; use `querytype`
/**
* EXPLAIN ...
*/
'is_explain' => false, // @deprecated; use `querytype`
/**
* select ... INTO OUTFILE ...
*/
'is_export' => false,
/**
* select FUNC( ... ) ...
*/
'is_func' => false,
/**
* select ... GROUP BY ...
* or
* select ... HAVING ...
*/
'is_group' => false,
/**
* INSERT ...
* or
* REPLACE ...
* or
* TODO: LOAD DATA ...
*/
'is_insert' => false,
/**
* ANALYZE ...
* or
* CHECK ...
* or
* CHECKSUM ...
* or
* OPTIMIZE ...
* or
* REPAIR ...
*/
'is_maint' => false,
/**
* CALL ...
*/
'is_procedure' => false,
/**
* REPLACE ...
*/
'is_replace' => false, // @deprecated; use `querytype`
/**
* SELECT ...
*/
'is_select' => false, // @deprecated; use `querytype`
/**
* SHOW ...
*/
'is_show' => false, // @deprecated; use `querytype`
/**
* Contains a subquery.
*/
'is_subquery' => false,
/**
* ... JOIN ...
*/
'join' => false,
/**
* ... LIMIT ...
*/
'limit' => false,
/**
* TODO
*/
'offset' => false,
/**
* ... ORDER ...
*/
'order' => false,
/**
* The type of the query (which is usually the first keyword of
* the statement).
*/
'querytype' => false,
/**
* Whether a page reload is required.
*/
'reload' => false,
/**
* SELECT ... FROM ...
*/
'select_from' => false,
/**
* ... UNION ...
*/
'union' => false
);
}
if ($statement instanceof AlterStatement) {
$flags['querytype'] = 'ALTER';
$flags['reload'] = true;
} elseif ($statement instanceof CreateStatement) {
$flags['querytype'] = 'CREATE';
$flags['reload'] = true;
} elseif ($statement instanceof AnalyzeStatement) {
$flags['querytype'] = 'ANALYZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof CheckStatement) {
$flags['querytype'] = 'CHECK';
$flags['is_maint'] = true;
} elseif ($statement instanceof ChecksumStatement) {
$flags['querytype'] = 'CHECKSUM';
$flags['is_maint'] = true;
} elseif ($statement instanceof OptimizeStatement) {
$flags['querytype'] = 'OPTIMIZE';
$flags['is_maint'] = true;
} elseif ($statement instanceof RepairStatement) {
$flags['querytype'] = 'REPAIR';
$flags['is_maint'] = true;
} elseif ($statement instanceof CallStatement) {
$flags['querytype'] = 'CALL';
$flags['is_procedure'] = true;
} elseif ($statement instanceof DeleteStatement) {
$flags['querytype'] = 'DELETE';
$flags['is_delete'] = true;
$flags['is_affected'] = true;
} elseif ($statement instanceof DropStatement) {
$flags['querytype'] = 'DROP';
$flags['reload'] = true;
if (($statement->options->has('DATABASE')
|| ($statement->options->has('SCHEMA')))
) {
$flags['drop_database'] = true;
}
} elseif ($statement instanceof ExplainStatement) {
$flags['querytype'] = 'EXPLAIN';
$flags['is_explain'] = true;
} elseif ($statement instanceof InsertStatement) {
$flags['querytype'] = 'INSERT';
$flags['is_affected'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof ReplaceStatement) {
$flags['querytype'] = 'REPLACE';
$flags['is_affected'] = true;
$flags['is_replace'] = true;
$flags['is_insert'] = true;
} elseif ($statement instanceof SelectStatement) {
$flags['querytype'] = 'SELECT';
$flags['is_select'] = true;
if (!empty($statement->from)) {
$flags['select_from'] = true;
}
if ($statement->options->has('DISTINCT')) {
$flags['distinct'] = true;
}
if ((!empty($statement->group)) || (!empty($statement->having))) {
$flags['is_group'] = true;
}
if ((!empty($statement->into))
&& ($statement->into->type === 'OUTFILE')
) {
$flags['is_export'] = true;
}
$expressions = $statement->expr;
if (!empty($statement->join)) {
foreach ($statement->join as $join) {
$expressions[] = $join->expr;
}
}
foreach ($expressions as $expr) {
if (!empty($expr->function)) {
if ($expr->function === 'COUNT') {
$flags['is_count'] = true;
} elseif (in_array($expr->function, static::$FUNCTIONS)) {
$flags['is_func'] = true;
}
}
if (!empty($expr->subquery)) {
$flags['is_subquery'] = true;
}
}
if ((!empty($statement->procedure))
&& ($statement->procedure->name === 'ANALYSE')
) {
$flags['is_analyse'] = true;
}
if (!empty($statement->group)) {
$flags['group'] = true;
}
if (!empty($statement->having)) {
$flags['having'] = true;
}
if (!empty($statement->union)) {
$flags['union'] = true;
}
if (!empty($statement->join)) {
$flags['join'] = true;
}
} elseif ($statement instanceof ShowStatement) {
$flags['querytype'] = 'SHOW';
$flags['is_show'] = true;
} elseif ($statement instanceof UpdateStatement) {
$flags['querytype'] = 'UPDATE';
$flags['is_affected'] = true;
}
if (($statement instanceof SelectStatement)
|| ($statement instanceof UpdateStatement)
|| ($statement instanceof DeleteStatement)
) {
if (!empty($statement->limit)) {
$flags['limit'] = true;
}
if (!empty($statement->order)) {
$flags['order'] = true;
}
}
return $flags;
}
/**
* Parses a query and gets all information about it.
*
* @param string $query The query to be parsed.
*
* @return array The array returned is the one returned by
* `static::getFlags()`, with the following keys added:
* - parser - the parser used to analyze the query;
* - statement - the first statement resulted from parsing;
* - select_tables - the real name of the tables selected;
* if there are no table names in the `SELECT`
* expressions, the table names are fetched from the
* `FROM` expressions
* - select_expr - selected expressions
*/
public static function getAll($query)
{
$parser = new Parser($query);
if (empty($parser->statements[0])) {
return array();
}
$statement = $parser->statements[0];
$ret = static::getFlags($statement, true);
$ret['parser'] = $parser;
$ret['statement'] = $statement;
if ($statement instanceof SelectStatement) {
$ret['select_tables'] = array();
$ret['select_expr'] = array();
// Finding tables' aliases and their associated real names.
$tableAliases = array();
foreach ($statement->from as $expr) {
if ((isset($expr->table)) && ($expr->table !== '')
&& (isset($expr->alias)) && ($expr->alias !== '')
) {
$tableAliases[$expr->alias] = array(
$expr->table,
isset($expr->database) ? $expr->database : null
);
}
}
// Trying to find selected tables only from the select expression.
// Sometimes, this is not possible because the tables aren't defined
// explicitly (e.g. SELECT * FROM film, SELECT film_id FROM film).
foreach ($statement->expr as $expr) {
if ((isset($expr->table)) && ($expr->table !== '')) {
if (isset($tableAliases[$expr->table])) {
$arr = $tableAliases[$expr->table];
} else {
$arr = array(
$expr->table,
((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : null
);
}
if (!in_array($arr, $ret['select_tables'])) {
$ret['select_tables'][] = $arr;
}
} else {
$ret['select_expr'][] = $expr->expr;
}
}
// If no tables names were found in the SELECT clause or if there
// are expressions like * or COUNT(*), etc. tables names should be
// extracted from the FROM clause.
if (empty($ret['select_tables'])) {
foreach ($statement->from as $expr) {
if ((isset($expr->table)) && ($expr->table !== '')) {
$arr = array(
$expr->table,
((isset($expr->database)) && ($expr->database !== '')) ?
$expr->database : null
);
if (!in_array($arr, $ret['select_tables'])) {
$ret['select_tables'][] = $arr;
}
}
}
}
}
return $ret;
}
/**
* Gets a list of all tables used in this statement.
*
* @param Statement $statement Statement to be scanned.
*
* @return array
*/
public static function getTables($statement)
{
$expressions = array();
if (($statement instanceof InsertStatement)
|| ($statement instanceof ReplaceStatement)
) {
$expressions = array($statement->into->dest);
} elseif ($statement instanceof UpdateStatement) {
$expressions = $statement->tables;
} elseif (($statement instanceof SelectStatement)
|| ($statement instanceof DeleteStatement)
) {
$expressions = $statement->from;
} elseif (($statement instanceof AlterStatement)
|| ($statement instanceof TruncateStatement)
) {
$expressions = array($statement->table);
} elseif ($statement instanceof DropStatement) {
if (!$statement->options->has('TABLE')) {
// No tables are dropped.
return array();
}
$expressions = $statement->fields;
} elseif ($statement instanceof RenameStatement) {
foreach ($statement->renames as $rename) {
$expressions[] = $rename->old;
}
}
$ret = array();
foreach ($expressions as $expr) {
if (!empty($expr->table)) {
$expr->expr = null; // Force rebuild.
$expr->alias = null; // Aliases are not required.
$ret[] = Expression::build($expr);
}
}
return $ret;
}
/**
* Gets a specific clause.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $clause The clause to be returned.
* @param int|string $type The type of the search.
* If int,
* -1 for everything that was before
* 0 only for the clause
* 1 for everything after
* If string, the name of the first clause that
* should not be included.
* @param bool $skipFirst Whether to skip the first keyword in clause.
*
* @return string
*/
public static function getClause($statement, $list, $clause, $type = 0, $skipFirst = true)
{
/**
* The index of the current clause.
*
* @var int $currIdx
*/
$currIdx = 0;
/**
* The count of brackets.
* We keep track of them so we won't insert the clause in a subquery.
*
* @var int $brackets
*/
$brackets = 0;
/**
* The string to be returned.
*
* @var string $ret
*/
$ret = '';
/**
* The clauses of this type of statement and their index.
*
* @var array $clauses
*/
$clauses = array_flip(array_keys($statement->getClauses()));
/**
* Lexer used for lexing the clause.
*
* @var Lexer $lexer
*/
$lexer = new Lexer($clause);
/**
* The type of this clause.
*
* @var string $clauseType
*/
$clauseType = $lexer->list->getNextOfType(Token::TYPE_KEYWORD)->value;
/**
* The index of this clause.
*
* @var int $clauseIdx
*/
$clauseIdx = $clauses[$clauseType];
$firstClauseIdx = $clauseIdx;
$lastClauseIdx = $clauseIdx + 1;
// Determining the behavior of this function.
if ($type === -1) {
$firstClauseIdx = -1; // Something small enough.
$lastClauseIdx = $clauseIdx - 1;
} elseif ($type === 1) {
$firstClauseIdx = $clauseIdx + 1;
$lastClauseIdx = 10000; // Something big enough.
} elseif (is_string($type)) {
if ($clauses[$type] > $clauseIdx) {
$firstClauseIdx = $clauseIdx + 1;
$lastClauseIdx = $clauses[$type] - 1;
} else {
$firstClauseIdx = $clauses[$type] + 1;
$lastClauseIdx = $clauseIdx - 1;
}
}
// This option is unavailable for multiple clauses.
if ($type !== 0) {
$skipFirst = false;
}
for ($i = $statement->first; $i <= $statement->last; ++$i) {
$token = $list->tokens[$i];
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
if ($token->type === Token::TYPE_OPERATOR) {
if ($token->value === '(') {
++$brackets;
} elseif ($token->value === ')') {
--$brackets;
}
}
if ($brackets == 0) {
// Checking if the section was changed.
if (($token->type === Token::TYPE_KEYWORD)
&& (isset($clauses[$token->value]))
&& ($clauses[$token->value] >= $currIdx)
) {
$currIdx = $clauses[$token->value];
if (($skipFirst) && ($currIdx == $clauseIdx)) {
// This token is skipped (not added to the old
// clause) because it will be replaced.
continue;
}
}
}
if (($firstClauseIdx <= $currIdx) && ($currIdx <= $lastClauseIdx)) {
$ret .= $token->token;
}
}
return trim($ret);
}
/**
* Builds a query by rebuilding the statement from the tokens list supplied
* and replaces a clause.
*
* It is a very basic version of a query builder.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param string $old The type of the clause that should be
* replaced. This can be an entire clause.
* @param string $new The new clause. If this parameter is omitted
* it is considered to be equal with `$old`.
* @param bool $onlyType Whether only the type of the clause should
* be replaced or the entire clause.
*
* @return string
*/
public static function replaceClause($statement, $list, $old, $new = null, $onlyType = false)
{
// TODO: Update the tokens list and the statement.
if ($new === null) {
$new = $old;
}
if ($onlyType) {
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getClause($statement, $list, $old, 0) . ' ' .
static::getClause($statement, $list, $old, 1, false);
}
return static::getClause($statement, $list, $old, -1, false) . ' ' .
$new . ' ' . static::getClause($statement, $list, $old, 1, false);
}
/**
* Builds a query by rebuilding the statement from the tokens list supplied
* and replaces multiple clauses.
*
* @param Statement $statement The parsed query that has to be modified.
* @param TokensList $list The list of tokens.
* @param array $ops Clauses to be replaced. Contains multiple
* arrays having two values: array($old, $new).
* Clauses must be sorted.
*
* @return string
*/
public static function replaceClauses($statement, $list, array $ops)
{
$count = count($ops);
// Nothing to do.
if ($count === 0) {
return '';
}
/**
* Value to be returned.
*
* @var string $ret
*/
$ret = '';
// If there is only one clause, `replaceClause()` should be used.
if ($count === 1) {
return static::replaceClause(
$statement,
$list,
$ops[0][0],
$ops[0][1]
);
}
// Adding everything before first replacement.
$ret .= static::getClause($statement, $list, $ops[0][0], -1) . ' ';
// Doing replacements.
for ($i = 0; $i < $count; ++$i) {
$ret .= $ops[$i][1] . ' ';
// Adding everything between this and next replacement.
if ($i + 1 !== $count) {
$ret .= static::getClause($statement, $list, $ops[$i][0], $ops[$i + 1][0]) . ' ';
}
}
// Adding everything after the last replacement.
$ret .= static::getClause($statement, $list, $ops[$count - 1][0], 1);
return $ret;
}
/**
* Gets the first full statement in the query.
*
* @param string $query The query to be analyzed.
* @param string $delimiter The delimiter to be used.
*
* @return array Array containing the first full query, the
* remaining part of the query and the last
* delimiter.
*/
public static function getFirstStatement($query, $delimiter = null)
{
$lexer = new Lexer($query, false, $delimiter);
$list = $lexer->list;
/**
* Whether a full statement was found.
*
* @var bool $fullStatement
*/
$fullStatement = false;
/**
* The first full statement.
*
* @var string $statement
*/
$statement = '';
for ($list->idx = 0; $list->idx < $list->count; ++$list->idx) {
$token = $list->tokens[$list->idx];
if ($token->type === Token::TYPE_COMMENT) {
continue;
}
$statement .= $token->token;
if (($token->type === Token::TYPE_DELIMITER) && (!empty($token->token))) {
$delimiter = $token->token;
$fullStatement = true;
break;
}
}
// No statement was found so we return the entire query as being the
// remaining part.
if (!$fullStatement) {
return array(null, $query, $delimiter);
}
// At least one query was found so we have to build the rest of the
// remaining query.
$query = '';
for (++$list->idx; $list->idx < $list->count; ++$list->idx) {
$query .= $list->tokens[$list->idx]->token;
}
return array(trim($statement), $query, $delimiter);
}
}

View File

@ -1,136 +0,0 @@
<?php
/**
* Routine utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Parser;
use SqlParser\Components\DataType;
use SqlParser\Components\ParameterDefinition;
use SqlParser\Statements\CreateStatement;
/**
* Routine utilities.
*
* @category Routines
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Routine
{
/**
* Parses a parameter of a routine.
*
* @param string $param Parameter's definition.
*
* @return array
*/
public static function getReturnType($param)
{
$lexer = new Lexer($param);
// A dummy parser is used for error reporting.
$type = DataType::parse(new Parser(), $lexer->list);
if ($type === null) {
return array('', '', '', '', '');
}
$options = array();
foreach ($type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return array(
'',
'',
$type->name,
implode(',', $type->parameters),
implode(' ', $options)
);
}
/**
* Parses a parameter of a routine.
*
* @param string $param Parameter's definition.
*
* @return array
*/
public static function getParameter($param)
{
$lexer = new Lexer('(' . $param . ')');
// A dummy parser is used for error reporting.
$param = ParameterDefinition::parse(new Parser(), $lexer->list);
if (empty($param[0])) {
return array('', '', '', '', '');
}
$param = $param[0];
$options = array();
foreach ($param->type->options->options as $opt) {
$options[] = is_string($opt) ? $opt : $opt['value'];
}
return array(
empty($param->inOut) ? '' : $param->inOut,
$param->name,
$param->type->name,
implode(',', $param->type->parameters),
implode(' ', $options)
);
}
/**
* Gets the parameters of a routine from the parse tree.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getParameters($statement)
{
$retval = array(
'num' => 0,
'dir' => array(),
'name' => array(),
'type' => array(),
'length' => array(),
'length_arr' => array(),
'opts' => array(),
);
if (!empty($statement->parameters)) {
$idx = 0;
foreach ($statement->parameters as $param) {
$retval['dir'][$idx] = $param->inOut;
$retval['name'][$idx] = $param->name;
$retval['type'][$idx] = $param->type->name;
$retval['length'][$idx] = implode(',', $param->type->parameters);
$retval['length_arr'][$idx] = $param->type->parameters;
$retval['opts'][$idx] = array();
foreach ($param->type->options->options as $opt) {
$retval['opts'][$idx][] = is_string($opt) ?
$opt : $opt['value'];
}
$retval['opts'][$idx] = implode(' ', $retval['opts'][$idx]);
++$idx;
}
$retval['num'] = $idx;
}
return $retval;
}
}

View File

@ -1,142 +0,0 @@
<?php
/**
* Table utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Statements\CreateStatement;
/**
* Table utilities.
*
* @category Statement
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Table
{
/**
* Gets the foreign keys of the table.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getForeignKeys($statement)
{
if ((empty($statement->fields))
|| (!is_array($statement->fields))
|| (!$statement->options->has('TABLE'))
) {
return array();
}
$ret = array();
foreach ($statement->fields as $field) {
if ((empty($field->key)) || ($field->key->type !== 'FOREIGN KEY')) {
continue;
}
$columns = array();
foreach ($field->key->columns as $column) {
$columns[] = $column['name'];
}
$tmp = array(
'constraint' => $field->name,
'index_list' => $columns,
);
if (!empty($field->references)) {
$tmp['ref_db_name'] = $field->references->table->database;
$tmp['ref_table_name'] = $field->references->table->table;
$tmp['ref_index_list'] = $field->references->columns;
if (($opt = $field->references->options->has('ON UPDATE'))) {
$tmp['on_update'] = str_replace(' ', '_', $opt);
}
if (($opt = $field->references->options->has('ON DELETE'))) {
$tmp['on_delete'] = str_replace(' ', '_', $opt);
}
// if (($opt = $field->references->options->has('MATCH'))) {
// $tmp['match'] = str_replace(' ', '_', $opt);
// }
}
$ret[] = $tmp;
}
return $ret;
}
/**
* Gets fields of the table.
*
* @param CreateStatement $statement The statement to be processed.
*
* @return array
*/
public static function getFields($statement)
{
if ((empty($statement->fields))
|| (!is_array($statement->fields))
|| (!$statement->options->has('TABLE'))
) {
return array();
}
$ret = array();
foreach ($statement->fields as $field) {
// Skipping keys.
if (empty($field->type)) {
continue;
}
$ret[$field->name] = array(
'type' => $field->type->name,
'timestamp_not_null' => false,
);
if ($field->options) {
if ($field->type->name === 'TIMESTAMP') {
if ($field->options->has('NOT NULL')) {
$ret[$field->name]['timestamp_not_null'] = true;
}
}
if (($option = $field->options->has('DEFAULT'))) {
$ret[$field->name]['default_value'] = $option;
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['default_current_timestamp'] = true;
}
}
if (($option = $field->options->has('ON UPDATE'))) {
if ($option === 'CURRENT_TIMESTAMP') {
$ret[$field->name]['on_update_current_timestamp'] = true;
}
}
if (($option = $field->options->has('AS'))) {
$ret[$field->name]['generated'] = true;
$ret[$field->name]['expr'] = $option;
}
}
}
return $ret;
}
}

View File

@ -1,175 +0,0 @@
<?php
/**
* Token utilities.
*
* @package SqlParser
* @subpackage Utils
*/
namespace SqlParser\Utils;
use SqlParser\Lexer;
use SqlParser\Token;
use SqlParser\TokensList;
/**
* Token utilities.
*
* @category Token
* @package SqlParser
* @subpackage Utils
* @author Dan Ungureanu <udan1107@gmail.com>
* @license http://opensource.org/licenses/GPL-2.0 GNU Public License
*/
class Tokens
{
/**
* Checks if a pattern is a match for the specified token.
*
* @param Token $token The token to be matched.
* @param array $pattern The pattern to be matches.
*
* @return bool
*/
public static function match(Token $token, array $pattern)
{
// Token.
if ((isset($pattern['token']))
&& ($pattern['token'] !== $token->token)
) {
return false;
}
// Value.
if ((isset($pattern['value']))
&& ($pattern['value'] !== $token->value)
) {
return false;
}
if ((isset($pattern['value_str']))
&& (strcasecmp($pattern['value_str'], $token->value))
) {
return false;
}
// Type.
if ((isset($pattern['type']))
&& ($pattern['type'] !== $token->type)
) {
return false;
}
// Flags.
if ((isset($pattern['flags']))
&& (($pattern['flags'] & $token->flags) === 0)
) {
return false;
}
return true;
}
public static function replaceTokens($list, array $find, array $replace)
{
/**
* Whether the first parameter is a list.
*
* @var bool
*/
$isList = $list instanceof TokensList;
// Parsing the tokens.
if (!$isList) {
$list = Lexer::getTokens($list);
}
/**
* The list to be returned.
*
* @var array
*/
$newList = array();
/**
* The length of the find pattern is calculated only once.
*
* @var int
*/
$findCount = count($find);
/**
* The starting index of the pattern.
*
* @var int
*/
$i = 0;
while ($i < $list->count) {
// A sequence may not start with a comment.
if ($list->tokens[$i]->type === Token::TYPE_COMMENT) {
$newList[] = $list->tokens[$i];
++$i;
continue;
}
/**
* The index used to parse `$list->tokens`.
*
* This index might be running faster than `$k` because some tokens
* are skipped.
*
* @var int
*/
$j = $i;
/**
* The index used to parse `$find`.
*
* This index might be running slower than `$j` because some tokens
* are skipped.
*
* @var int
*/
$k = 0;
// Checking if the next tokens match the pattern described.
while (($j < $list->count) && ($k < $findCount)) {
// Comments are being skipped.
if ($list->tokens[$j]->type === Token::TYPE_COMMENT) {
++$j;
}
if (!static::match($list->tokens[$j], $find[$k])) {
// This token does not match the pattern.
break;
}
// Going to next token and segment of find pattern.
++$j;
++$k;
}
// Checking if the sequence was found.
if ($k === $findCount) {
// Inserting new tokens.
foreach ($replace as $token) {
$newList[] = $token;
}
// Skipping next `$findCount` tokens.
$i = $j;
} else {
// Adding the same token.
$newList[] = $list->tokens[$i];
++$i;
}
}
return $isList ?
new TokensList($newList) : TokensList::build($newList);
}
}

View File

@ -1,21 +0,0 @@
<?php
/**
* Defines common elements used by the library.
*
* @package SqlParser
*/
if (!function_exists('__')) {
/**
* Translates the given string.
*
* @param string $str String to be translated.
*
* @return string
*/
function __($str)
{
return $str;
}
}

View File

@ -1,858 +0,0 @@
**********************************************************************
* TCPDF LICENSE
**********************************************************************
TCPDF is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**********************************************************************
**********************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
**********************************************************************
**********************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************

View File

@ -1,115 +0,0 @@
TCPDF - README
============================================================
I WISH TO IMPROVE AND EXPAND TCPDF BUT I NEED YOUR SUPPORT.
PLEASE MAKE A DONATION:
http://sourceforge.net/donate/index.php?group_id=128076
------------------------------------------------------------
Name: TCPDF
Version: 6.2.9
Release date: 2015-06-18
Author: Nicola Asuni
Copyright (c) 2002-2015:
Nicola Asuni
Tecnick.com LTD
www.tecnick.com
URLs:
http://www.tcpdf.org
http://www.sourceforge.net/projects/tcpdf
Description:
TCPDF is a PHP class for generating PDF files on-the-fly without requiring external extensions.
This library includes also a class to extract data from existing PDF documents and
classes to generate 1D and 2D barcodes in various formats.
Main Features:
* no external libraries are required for the basic functions;
* all standard page formats, custom page formats, custom margins and units of measure;
* UTF-8 Unicode and Right-To-Left languages;
* TrueTypeUnicode, OpenTypeUnicode v1, TrueType, OpenType v1, Type1 and CID-0 fonts;
* font subsetting;
* methods to publish some XHTML + CSS code, Javascript and Forms;
* images, graphic (geometric figures) and transformation methods;
* supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/script/formats.php)
* 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
* JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
* automatic page header and footer management;
* document encryption up to 256 bit and digital signature certifications;
* transactions to UNDO commands;
* PDF annotations, including links, text and file attachments;
* text rendering modes (fill, stroke and clipping);
* multiple columns mode;
* no-write page regions;
* bookmarks, named destinations and table of content;
* text hyphenation;
* text stretching and spacing (tracking);
* automatic page break, line break and text alignments including justification;
* automatic page numbering and page groups;
* move and delete pages;
* page compression (requires php-zlib extension);
* XOBject Templates;
* Layers and object visibility.
* PDF/A-1b support.
Installation (full instructions on http: www.tcpdf.org):
1. copy the folder on your Web server
2. set your installation path and other parameters on the config/tcpdf_config.php
3. call the examples/example_001.php page with your browser to see an example
Source Code Documentation:
http://www.tcpdf.org
Additional Documentation:
http://www.tcpdf.org
License:
Copyright (C) 2002-2014 Nicola Asuni - Tecnick.com LTD
TCPDF is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
TCPDF is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the License
along with TCPDF. If not, see
<http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
See LICENSE.TXT file for more information.
Third party fonts:
This library may include third party font files released with different licenses.
All the PHP files on the fonts directory are subject to the general TCPDF license (GNU-LGPLv3),
they do not contain any binary data but just a description of the general properties of a particular font.
These files can be also generated on the fly using the font utilities and TCPDF methods.
All the original binary TTF font files have been renamed for compatibility with TCPDF and compressed using the gzcompress PHP function that uses the ZLIB data format (.z files).
The binary files (.z) that begins with the prefix "free" have been extracted from the GNU FreeFont collection (GNU-GPLv3).
The binary files (.z) that begins with the prefix "pdfa" have been derived from the GNU FreeFont, so they are subject to the same license.
For the details of Copyright, License and other information, please check the files inside the directory fonts/freefont-20120503
Link : http://www.gnu.org/software/freefont/
The binary files (.z) that begins with the prefix "dejavu" have been extracted from the DejaVu fonts 2.33 (Bitstream) collection.
For the details of Copyright, License and other information, please check the files inside the directory fonts/dejavu-fonts-ttf-2.33
Link : http://dejavu-fonts.org
The binary files (.z) that begins with the prefix "ae" have been extracted from the Arabeyes.org collection (GNU-GPLv2).
Link : http://projects.arabeyes.org/
ICC profile:
TCPDF includes the sRGB.icc profile from the icc-profiles-free Debian package:
https://packages.debian.org/source/stable/icc-profiles-free
============================================================

View File

@ -1,227 +0,0 @@
<?php
//============================================================+
// File name : tcpdf_config.php
// Begin : 2004-06-11
// Last Update : 2014-12-11
//
// Description : Configuration file for TCPDF.
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2004-2014 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
//============================================================+
/**
* Configuration file for TCPDF.
* @author Nicola Asuni
* @package com.tecnick.tcpdf
* @version 4.9.005
* @since 2004-10-27
*/
// IMPORTANT:
// If you define the constant K_TCPDF_EXTERNAL_CONFIG, all the following settings will be ignored.
// If you use the tcpdf_autoconfig.php, then you can overwrite some values here.
/**
* Installation path (/var/www/tcpdf/).
* By default it is automatically calculated but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_MAIN', '');
/**
* URL path to tcpdf installation folder (http://localhost/tcpdf/).
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_URL', '');
/**
* Path for PDF fonts.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');
/**
* Default images directory.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_IMAGES', '');
/**
* Deafult image logo used be the default Header() method.
* Please set here your own logo or an empty string to disable it.
*/
//define ('PDF_HEADER_LOGO', '');
/**
* Header logo image width in user units.
*/
//define ('PDF_HEADER_LOGO_WIDTH', 0);
/**
* Cache directory for temporary files (full path).
*/
//define ('K_PATH_CACHE', '/tmp/');
/**
* Generic name for a blank image.
*/
define ('K_BLANK_IMAGE', '_blank.png');
/**
* Page format.
*/
define ('PDF_PAGE_FORMAT', 'A4');
/**
* Page orientation (P=portrait, L=landscape).
*/
define ('PDF_PAGE_ORIENTATION', 'P');
/**
* Document creator.
*/
define ('PDF_CREATOR', 'TCPDF');
/**
* Document author.
*/
define ('PDF_AUTHOR', 'TCPDF');
/**
* Header title.
*/
define ('PDF_HEADER_TITLE', 'TCPDF Example');
/**
* Header description string.
*/
define ('PDF_HEADER_STRING', "by Nicola Asuni - Tecnick.com\nwww.tcpdf.org");
/**
* Document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch].
*/
define ('PDF_UNIT', 'mm');
/**
* Header margin.
*/
define ('PDF_MARGIN_HEADER', 5);
/**
* Footer margin.
*/
define ('PDF_MARGIN_FOOTER', 10);
/**
* Top margin.
*/
define ('PDF_MARGIN_TOP', 27);
/**
* Bottom margin.
*/
define ('PDF_MARGIN_BOTTOM', 25);
/**
* Left margin.
*/
define ('PDF_MARGIN_LEFT', 15);
/**
* Right margin.
*/
define ('PDF_MARGIN_RIGHT', 15);
/**
* Default main font name.
*/
define ('PDF_FONT_NAME_MAIN', 'helvetica');
/**
* Default main font size.
*/
define ('PDF_FONT_SIZE_MAIN', 10);
/**
* Default data font name.
*/
define ('PDF_FONT_NAME_DATA', 'helvetica');
/**
* Default data font size.
*/
define ('PDF_FONT_SIZE_DATA', 8);
/**
* Default monospaced font name.
*/
define ('PDF_FONT_MONOSPACED', 'courier');
/**
* Ratio used to adjust the conversion of pixels to user units.
*/
define ('PDF_IMAGE_SCALE_RATIO', 1.25);
/**
* Magnification factor for titles.
*/
define('HEAD_MAGNIFICATION', 1.1);
/**
* Height of cell respect font height.
*/
define('K_CELL_HEIGHT_RATIO', 1.25);
/**
* Title magnification respect main font size.
*/
define('K_TITLE_MAGNIFICATION', 1.3);
/**
* Reduction factor for small font.
*/
define('K_SMALL_RATIO', 2/3);
/**
* Set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language.
*/
define('K_THAI_TOPCHARS', true);
/**
* If true allows to call TCPDF methods using HTML syntax
* IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
*/
define('K_TCPDF_CALLS_IN_HTML', false);
/**
* If true and PHP version is greater than 5, then the Error() method throw new exception instead of terminating the execution.
*/
define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
/**
* Default timezone for datetime functions
*/
define('K_TIMEZONE', 'UTC');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -1,99 +0,0 @@
Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
Bitstream Vera Fonts Copyright
------------------------------
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of the fonts accompanying this license ("Fonts") and associated
documentation files (the "Font Software"), to reproduce and distribute the
Font Software, including without limitation the rights to use, copy, merge,
publish, distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to the
following conditions:
The above copyright and trademark notices and this permission notice shall
be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular
the designs of glyphs or characters in the Fonts may be modified and
additional glyphs or characters may be added to the Fonts, only if the fonts
are renamed to names not containing either the words "Bitstream" or the word
"Vera".
This License becomes null and void to the extent applicable to Fonts or Font
Software that has been modified and is distributed under the "Bitstream
Vera" names.
The Font Software may be sold as part of a larger software package but no
copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome
Foundation, and Bitstream Inc., shall not be used in advertising or
otherwise to promote the sale, use or other dealings in this Font Software
without prior written authorization from the Gnome Foundation or Bitstream
Inc., respectively. For further information, contact: fonts at gnome dot
org.
Arev Fonts Copyright
------------------------------
Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the fonts accompanying this license ("Fonts") and
associated documentation files (the "Font Software"), to reproduce
and distribute the modifications to the Bitstream Vera Font Software,
including without limitation the rights to use, copy, merge, publish,
distribute, and/or sell copies of the Font Software, and to permit
persons to whom the Font Software is furnished to do so, subject to
the following conditions:
The above copyright and trademark notices and this permission notice
shall be included in all copies of one or more of the Font Software
typefaces.
The Font Software may be modified, altered, or added to, and in
particular the designs of glyphs or characters in the Fonts may be
modified and additional glyphs or characters may be added to the
Fonts, only if the fonts are renamed to names not containing either
the words "Tavmjong Bah" or the word "Arev".
This License becomes null and void to the extent applicable to Fonts
or Font Software that has been modified and is distributed under the
"Tavmjong Bah Arev" names.
The Font Software may be sold as part of a larger software package but
no copy of one or more of the Font Software typefaces may be sold by
itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the name of Tavmjong Bah shall not
be used in advertising or otherwise to promote the sale, use or other
dealings in this Font Software without prior written authorization
from Tavmjong Bah. For further information, contact: tavmjong @ free
. fr.
$Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@ -1,13 +0,0 @@
<?php
// TCPDF FONT FILE DESCRIPTION
$type='core';
$name='Helvetica';
$up=-100;
$ut=50;
$dw=513;
$diff='';
$enc='';
$desc=array('Flags'=>32,'FontBBox'=>'[-166 -225 1000 931]','ItalicAngle'=>0,'Ascent'=>931,'Descent'=>-225,'Leading'=>0,'CapHeight'=>718,'XHeight'=>523,'StemV'=>88,'StemH'=>76,'AvgWidth'=>513,'MaxWidth'=>1015,'MissingWidth'=>513);
$cw=array(0=>500,1=>500,2=>500,3=>500,4=>500,5=>500,6=>500,7=>500,8=>500,9=>500,10=>500,11=>500,12=>500,13=>500,14=>500,15=>500,16=>500,17=>500,18=>500,19=>500,20=>500,21=>500,22=>500,23=>500,24=>500,25=>500,26=>500,27=>500,28=>500,29=>500,30=>500,31=>500,32=>278,33=>278,34=>355,35=>556,36=>556,37=>889,38=>667,39=>191,40=>333,41=>333,42=>389,43=>584,44=>278,45=>333,46=>278,47=>278,48=>556,49=>556,50=>556,51=>556,52=>556,53=>556,54=>556,55=>556,56=>556,57=>556,58=>278,59=>278,60=>584,61=>584,62=>584,63=>556,64=>1015,65=>667,66=>667,67=>722,68=>722,69=>667,70=>611,71=>778,72=>722,73=>278,74=>500,75=>667,76=>556,77=>833,78=>722,79=>778,80=>667,81=>778,82=>722,83=>667,84=>611,85=>722,86=>667,87=>944,88=>667,89=>667,90=>611,91=>278,92=>278,93=>277,94=>469,95=>556,96=>333,97=>556,98=>556,99=>500,100=>556,101=>556,102=>278,103=>556,104=>556,105=>222,106=>222,107=>500,108=>222,109=>833,110=>556,111=>556,112=>556,113=>556,114=>333,115=>500,116=>278,117=>556,118=>500,119=>722,120=>500,121=>500,122=>500,123=>334,124=>260,125=>334,126=>584,127=>500,128=>655,129=>500,130=>222,131=>278,132=>333,133=>1000,134=>556,135=>556,136=>333,137=>1000,138=>667,139=>250,140=>1000,141=>500,142=>611,143=>500,144=>500,145=>222,146=>221,147=>333,148=>333,149=>350,150=>556,151=>1000,152=>333,153=>1000,154=>500,155=>250,156=>938,157=>500,158=>500,159=>667,160=>278,161=>278,162=>556,163=>556,164=>556,165=>556,166=>260,167=>556,168=>333,169=>737,170=>370,171=>448,172=>584,173=>333,174=>737,175=>333,176=>606,177=>584,178=>350,179=>350,180=>333,181=>556,182=>537,183=>278,184=>333,185=>350,186=>365,187=>448,188=>869,189=>869,190=>879,191=>556,192=>667,193=>667,194=>667,195=>667,196=>667,197=>667,198=>1000,199=>722,200=>667,201=>667,202=>667,203=>667,204=>278,205=>278,206=>278,207=>278,208=>722,209=>722,210=>778,211=>778,212=>778,213=>778,214=>778,215=>584,216=>778,217=>722,218=>722,219=>722,220=>722,221=>667,222=>666,223=>611,224=>556,225=>556,226=>556,227=>556,228=>556,229=>556,230=>896,231=>500,232=>556,233=>556,234=>556,235=>556,236=>251,237=>251,238=>251,239=>251,240=>556,241=>556,242=>556,243=>556,244=>556,245=>556,246=>556,247=>584,248=>611,249=>556,250=>556,251=>556,252=>556,253=>500,254=>555,255=>500);
// --- EOF ---

Binary file not shown.

View File

@ -1,462 +0,0 @@
<?php
//============================================================+
// File name : tcpdf_colors.php
// Version : 1.0.004
// Begin : 2002-04-09
// Last Update : 2014-04-25
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2002-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Array of WEB safe colors
//
//============================================================+
/**
* @file
* PHP color class for TCPDF
* @author Nicola Asuni
* @package com.tecnick.tcpdf
*/
/**
* @class TCPDF_COLORS
* PHP color class for TCPDF
* @package com.tecnick.tcpdf
* @version 1.0.004
* @author Nicola Asuni - info@tecnick.com
*/
class TCPDF_COLORS {
/**
* Array of WEB safe colors
* @public static
*/
public static $webcolor = array (
'aliceblue' => 'f0f8ff',
'antiquewhite' => 'faebd7',
'aqua' => '00ffff',
'aquamarine' => '7fffd4',
'azure' => 'f0ffff',
'beige' => 'f5f5dc',
'bisque' => 'ffe4c4',
'black' => '000000',
'blanchedalmond' => 'ffebcd',
'blue' => '0000ff',
'blueviolet' => '8a2be2',
'brown' => 'a52a2a',
'burlywood' => 'deb887',
'cadetblue' => '5f9ea0',
'chartreuse' => '7fff00',
'chocolate' => 'd2691e',
'coral' => 'ff7f50',
'cornflowerblue' => '6495ed',
'cornsilk' => 'fff8dc',
'crimson' => 'dc143c',
'cyan' => '00ffff',
'darkblue' => '00008b',
'darkcyan' => '008b8b',
'darkgoldenrod' => 'b8860b',
'dkgray' => 'a9a9a9',
'darkgray' => 'a9a9a9',
'darkgrey' => 'a9a9a9',
'darkgreen' => '006400',
'darkkhaki' => 'bdb76b',
'darkmagenta' => '8b008b',
'darkolivegreen' => '556b2f',
'darkorange' => 'ff8c00',
'darkorchid' => '9932cc',
'darkred' => '8b0000',
'darksalmon' => 'e9967a',
'darkseagreen' => '8fbc8f',
'darkslateblue' => '483d8b',
'darkslategray' => '2f4f4f',
'darkslategrey' => '2f4f4f',
'darkturquoise' => '00ced1',
'darkviolet' => '9400d3',
'deeppink' => 'ff1493',
'deepskyblue' => '00bfff',
'dimgray' => '696969',
'dimgrey' => '696969',
'dodgerblue' => '1e90ff',
'firebrick' => 'b22222',
'floralwhite' => 'fffaf0',
'forestgreen' => '228b22',
'fuchsia' => 'ff00ff',
'gainsboro' => 'dcdcdc',
'ghostwhite' => 'f8f8ff',
'gold' => 'ffd700',
'goldenrod' => 'daa520',
'gray' => '808080',
'grey' => '808080',
'green' => '008000',
'greenyellow' => 'adff2f',
'honeydew' => 'f0fff0',
'hotpink' => 'ff69b4',
'indianred' => 'cd5c5c',
'indigo' => '4b0082',
'ivory' => 'fffff0',
'khaki' => 'f0e68c',
'lavender' => 'e6e6fa',
'lavenderblush' => 'fff0f5',
'lawngreen' => '7cfc00',
'lemonchiffon' => 'fffacd',
'lightblue' => 'add8e6',
'lightcoral' => 'f08080',
'lightcyan' => 'e0ffff',
'lightgoldenrodyellow' => 'fafad2',
'ltgray' => 'd3d3d3',
'lightgray' => 'd3d3d3',
'lightgrey' => 'd3d3d3',
'lightgreen' => '90ee90',
'lightpink' => 'ffb6c1',
'lightsalmon' => 'ffa07a',
'lightseagreen' => '20b2aa',
'lightskyblue' => '87cefa',
'lightslategray' => '778899',
'lightslategrey' => '778899',
'lightsteelblue' => 'b0c4de',
'lightyellow' => 'ffffe0',
'lime' => '00ff00',
'limegreen' => '32cd32',
'linen' => 'faf0e6',
'magenta' => 'ff00ff',
'maroon' => '800000',
'mediumaquamarine' => '66cdaa',
'mediumblue' => '0000cd',
'mediumorchid' => 'ba55d3',
'mediumpurple' => '9370d8',
'mediumseagreen' => '3cb371',
'mediumslateblue' => '7b68ee',
'mediumspringgreen' => '00fa9a',
'mediumturquoise' => '48d1cc',
'mediumvioletred' => 'c71585',
'midnightblue' => '191970',
'mintcream' => 'f5fffa',
'mistyrose' => 'ffe4e1',
'moccasin' => 'ffe4b5',
'navajowhite' => 'ffdead',
'navy' => '000080',
'oldlace' => 'fdf5e6',
'olive' => '808000',
'olivedrab' => '6b8e23',
'orange' => 'ffa500',
'orangered' => 'ff4500',
'orchid' => 'da70d6',
'palegoldenrod' => 'eee8aa',
'palegreen' => '98fb98',
'paleturquoise' => 'afeeee',
'palevioletred' => 'd87093',
'papayawhip' => 'ffefd5',
'peachpuff' => 'ffdab9',
'peru' => 'cd853f',
'pink' => 'ffc0cb',
'plum' => 'dda0dd',
'powderblue' => 'b0e0e6',
'purple' => '800080',
'red' => 'ff0000',
'rosybrown' => 'bc8f8f',
'royalblue' => '4169e1',
'saddlebrown' => '8b4513',
'salmon' => 'fa8072',
'sandybrown' => 'f4a460',
'seagreen' => '2e8b57',
'seashell' => 'fff5ee',
'sienna' => 'a0522d',
'silver' => 'c0c0c0',
'skyblue' => '87ceeb',
'slateblue' => '6a5acd',
'slategray' => '708090',
'slategrey' => '708090',
'snow' => 'fffafa',
'springgreen' => '00ff7f',
'steelblue' => '4682b4',
'tan' => 'd2b48c',
'teal' => '008080',
'thistle' => 'd8bfd8',
'tomato' => 'ff6347',
'turquoise' => '40e0d0',
'violet' => 'ee82ee',
'wheat' => 'f5deb3',
'white' => 'ffffff',
'whitesmoke' => 'f5f5f5',
'yellow' => 'ffff00',
'yellowgreen' => '9acd32'
); // end of web colors
/**
* Array of valid JavaScript color names
* @public static
*/
public static $jscolor = array ('transparent', 'black', 'white', 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'dkGray', 'gray', 'ltGray');
/**
* Array of Spot colors (C,M,Y,K,name)
* Color keys must be in lowercase and without spaces.
* As long as no open standard for spot colours exists, you have to buy a colour book by one of the colour manufacturers and insert the values and names of spot colours directly.
* Common industry standard spot colors are: ANPA-COLOR, DIC, FOCOLTONE, GCMI, HKS, PANTONE, TOYO, TRUMATCH.
* @public static
*/
public static $spotcolor = array (
// special registration colors
'none' => array( 0, 0, 0, 0, 'None'),
'all' => array(100, 100, 100, 100, 'All'),
// standard CMYK colors
'cyan' => array(100, 0, 0, 0, 'Cyan'),
'magenta' => array( 0, 100, 0, 0, 'Magenta'),
'yellow' => array( 0, 0, 100, 0, 'Yellow'),
'key' => array( 0, 0, 0, 100, 'Key'),
// alias
'white' => array( 0, 0, 0, 0, 'White'),
'black' => array( 0, 0, 0, 100, 'Black'),
// standard RGB colors
'red' => array( 0, 100, 100, 0, 'Red'),
'green' => array(100, 0, 100, 0, 'Green'),
'blue' => array(100, 100, 0, 0, 'Blue'),
// Add here standard spot colors or dynamically define them with AddSpotColor()
// ...
); // end of spot colors
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Return the Spot color array.
* @param $name (string) Name of the spot color.
* @param $spotc (array) Reference to an array of spot colors.
* @return (array) Spot color array or false if not defined.
* @since 5.9.125 (2011-10-03)
* @public static
*/
public static function getSpotColor($name, &$spotc) {
if (isset($spotc[$name])) {
return $spotc[$name];
}
$color = preg_replace('/[\s]*/', '', $name); // remove extra spaces
$color = strtolower($color);
if (isset(self::$spotcolor[$color])) {
if (!isset($spotc[$name])) {
$i = (1 + count($spotc));
$spotc[$name] = array('C' => self::$spotcolor[$color][0], 'M' => self::$spotcolor[$color][1], 'Y' => self::$spotcolor[$color][2], 'K' => self::$spotcolor[$color][3], 'name' => self::$spotcolor[$color][4], 'i' => $i);
}
return $spotc[self::$spotcolor[$color][4]];
}
return false;
}
/**
* Returns an array (RGB or CMYK) from an html color name, or a six-digit (i.e. #3FE5AA), or three-digit (i.e. #7FF) hexadecimal color, or a javascript color array, or javascript color name.
* @param $hcolor (string) HTML color.
* @param $spotc (array) Reference to an array of spot colors.
* @param $defcol (array) Color to return in case of error.
* @return array RGB or CMYK color, or false in case of error.
* @public static
*/
public static function convertHTMLColorToDec($hcolor, &$spotc, $defcol=array('R'=>128,'G'=>128,'B'=>128)) {
$color = preg_replace('/[\s]*/', '', $hcolor); // remove extra spaces
$color = strtolower($color);
// check for javascript color array syntax
if (strpos($color, '[') !== false) {
if (preg_match('/[\[][\"\'](t|g|rgb|cmyk)[\"\'][\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\,]?([0-9\.]*)[\]]/', $color, $m) > 0) {
$returncolor = array();
switch ($m[1]) {
case 'cmyk': {
// RGB
$returncolor['C'] = max(0, min(100, (floatval($m[2]) * 100)));
$returncolor['M'] = max(0, min(100, (floatval($m[3]) * 100)));
$returncolor['Y'] = max(0, min(100, (floatval($m[4]) * 100)));
$returncolor['K'] = max(0, min(100, (floatval($m[5]) * 100)));
break;
}
case 'rgb': {
// RGB
$returncolor['R'] = max(0, min(255, (floatval($m[2]) * 255)));
$returncolor['G'] = max(0, min(255, (floatval($m[3]) * 255)));
$returncolor['B'] = max(0, min(255, (floatval($m[4]) * 255)));
break;
}
case 'g': {
// grayscale
$returncolor['G'] = max(0, min(255, (floatval($m[2]) * 255)));
break;
}
case 't':
default: {
// transparent (empty array)
break;
}
}
return $returncolor;
}
} elseif ((substr($color, 0, 4) != 'cmyk') AND (substr($color, 0, 3) != 'rgb') AND (($dotpos = strpos($color, '.')) !== false)) {
// remove class parent (i.e.: color.red)
$color = substr($color, ($dotpos + 1));
if ($color == 'transparent') {
// transparent (empty array)
return array();
}
}
if (strlen($color) == 0) {
return $defcol;
}
// RGB ARRAY
if (substr($color, 0, 3) == 'rgb') {
$codes = substr($color, 4);
$codes = str_replace(')', '', $codes);
$returncolor = explode(',', $codes);
foreach ($returncolor as $key => $val) {
if (strpos($val, '%') > 0) {
// percentage
$returncolor[$key] = (255 * intval($val) / 100);
} else {
$returncolor[$key] = intval($val);
}
// normalize value
$returncolor[$key] = max(0, min(255, $returncolor[$key]));
}
return $returncolor;
}
// CMYK ARRAY
if (substr($color, 0, 4) == 'cmyk') {
$codes = substr($color, 5);
$codes = str_replace(')', '', $codes);
$returncolor = explode(',', $codes);
foreach ($returncolor as $key => $val) {
if (strpos($val, '%') !== false) {
// percentage
$returncolor[$key] = (100 * intval($val) / 100);
} else {
$returncolor[$key] = intval($val);
}
// normalize value
$returncolor[$key] = max(0, min(100, $returncolor[$key]));
}
return $returncolor;
}
if ($color[0] != '#') {
// COLOR NAME
if (isset(self::$webcolor[$color])) {
// web color
$color_code = self::$webcolor[$color];
} else {
// spot color
$returncolor = self::getSpotColor($color, $spotc);
if ($returncolor === false) {
$returncolor = $defcol;
}
return $returncolor;
}
} else {
$color_code = substr($color, 1);
}
// HEXADECIMAL REPRESENTATION
switch (strlen($color_code)) {
case 3: {
// 3-digit RGB hexadecimal representation
$r = substr($color_code, 0, 1);
$g = substr($color_code, 1, 1);
$b = substr($color_code, 2, 1);
$returncolor = array();
$returncolor['R'] = max(0, min(255, hexdec($r.$r)));
$returncolor['G'] = max(0, min(255, hexdec($g.$g)));
$returncolor['B'] = max(0, min(255, hexdec($b.$b)));
break;
}
case 6: {
// 6-digit RGB hexadecimal representation
$returncolor = array();
$returncolor['R'] = max(0, min(255, hexdec(substr($color_code, 0, 2))));
$returncolor['G'] = max(0, min(255, hexdec(substr($color_code, 2, 2))));
$returncolor['B'] = max(0, min(255, hexdec(substr($color_code, 4, 2))));
break;
}
case 8: {
// 8-digit CMYK hexadecimal representation
$returncolor = array();
$returncolor['C'] = max(0, min(100, round(hexdec(substr($color_code, 0, 2)) / 2.55)));
$returncolor['M'] = max(0, min(100, round(hexdec(substr($color_code, 2, 2)) / 2.55)));
$returncolor['Y'] = max(0, min(100, round(hexdec(substr($color_code, 4, 2)) / 2.55)));
$returncolor['K'] = max(0, min(100, round(hexdec(substr($color_code, 6, 2)) / 2.55)));
break;
}
default: {
$returncolor = $defcol;
break;
}
}
return $returncolor;
}
/**
* Convert a color array into a string representation.
* @param $c (array) Array of colors.
* @return (string) The color array representation.
* @since 5.9.137 (2011-12-01)
* @public static
*/
public static function getColorStringFromArray($c) {
$c = array_values($c);
$color = '[';
switch (count($c)) {
case 4: {
// CMYK
$color .= sprintf('%F %F %F %F', (max(0, min(100, floatval($c[0]))) / 100), (max(0, min(100, floatval($c[1]))) / 100), (max(0, min(100, floatval($c[2]))) / 100), (max(0, min(100, floatval($c[3]))) / 100));
break;
}
case 3: {
// RGB
$color .= sprintf('%F %F %F', (max(0, min(255, floatval($c[0]))) / 255), (max(0, min(255, floatval($c[1]))) / 255), (max(0, min(255, floatval($c[2]))) / 255));
break;
}
case 1: {
// grayscale
$color .= sprintf('%F', (max(0, min(255, floatval($c[0]))) / 255));
break;
}
}
$color .= ']';
return $color;
}
/**
* Convert color to javascript color.
* @param $color (string) color name or "#RRGGBB"
* @protected
* @since 2.1.002 (2008-02-12)
* @public static
*/
public static function _JScolor($color) {
if (substr($color, 0, 1) == '#') {
return sprintf("['RGB',%F,%F,%F]", (hexdec(substr($color, 1, 2)) / 255), (hexdec(substr($color, 3, 2)) / 255), (hexdec(substr($color, 5, 2)) / 255));
}
if (!in_array($color, self::$jscolor)) {
// default transparent color
$color = $jscolor[0];
}
return 'color.'.$color;
}
} // END OF TCPDF_COLORS CLASS
//============================================================+
// END OF FILE
//============================================================+

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,363 +0,0 @@
<?php
//============================================================+
// File name : tcpdf_images.php
// Version : 1.0.005
// Begin : 2002-08-03
// Last Update : 2014-11-15
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2002-2014 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the License
// along with TCPDF. If not, see
// <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description :
// Static image methods used by the TCPDF class.
//
//============================================================+
/**
* @file
* This is a PHP class that contains static image methods for the TCPDF class.<br>
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.005
*/
/**
* @class TCPDF_IMAGES
* Static image methods used by the TCPDF class.
* @package com.tecnick.tcpdf
* @brief PHP class for generating PDF documents without requiring external extensions.
* @version 1.0.005
* @author Nicola Asuni - info@tecnick.com
*/
class TCPDF_IMAGES {
/**
* Array of hinheritable SVG properties.
* @since 5.0.000 (2010-05-02)
* @public static
*/
public static $svginheritprop = array('clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cursor', 'direction', 'display', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'image-rendering', 'kerning', 'letter-spacing', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Return the image type given the file name or array returned by getimagesize() function.
* @param $imgfile (string) image file name
* @param $iminfo (array) array of image information returned by getimagesize() function.
* @return string image type
* @since 4.8.017 (2009-11-27)
* @public static
*/
public static function getImageFileType($imgfile, $iminfo=array()) {
$type = '';
if (isset($iminfo['mime']) AND !empty($iminfo['mime'])) {
$mime = explode('/', $iminfo['mime']);
if ((count($mime) > 1) AND ($mime[0] == 'image') AND (!empty($mime[1]))) {
$type = strtolower(trim($mime[1]));
}
}
if (empty($type)) {
$fileinfo = pathinfo($imgfile);
if (isset($fileinfo['extension']) AND (!TCPDF_STATIC::empty_string($fileinfo['extension']))) {
$type = strtolower(trim($fileinfo['extension']));
}
}
if ($type == 'jpg') {
$type = 'jpeg';
}
return $type;
}
/**
* Set the transparency for the given GD image.
* @param $new_image (image) GD image object
* @param $image (image) GD image object.
* return GD image object.
* @since 4.9.016 (2010-04-20)
* @public static
*/
public static function setGDImageTransparency($new_image, $image) {
// default transparency color (white)
$tcol = array('red' => 255, 'green' => 255, 'blue' => 255);
// transparency index
$tid = imagecolortransparent($image);
$palletsize = imagecolorstotal($image);
if (($tid >= 0) AND ($tid < $palletsize)) {
// get the colors for the transparency index
$tcol = imagecolorsforindex($image, $tid);
}
$tid = imagecolorallocate($new_image, $tcol['red'], $tcol['green'], $tcol['blue']);
imagefill($new_image, 0, 0, $tid);
imagecolortransparent($new_image, $tid);
return $new_image;
}
/**
* Convert the loaded image to a PNG and then return a structure for the PDF creator.
* This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
* @param $image (image) Image object.
* @param $tempfile (string) Temporary file name.
* return image PNG image object.
* @since 4.9.016 (2010-04-20)
* @public static
*/
public static function _toPNG($image, $tempfile) {
// turn off interlaced mode
imageinterlace($image, 0);
// create temporary PNG image
imagepng($image, $tempfile);
// remove image from memory
imagedestroy($image);
// get PNG image data
$retvars = self::_parsepng($tempfile);
// tidy up by removing temporary image
unlink($tempfile);
return $retvars;
}
/**
* Convert the loaded image to a JPEG and then return a structure for the PDF creator.
* This function requires GD library and write access to the directory defined on K_PATH_CACHE constant.
* @param $image (image) Image object.
* @param $quality (int) JPEG quality.
* @param $tempfile (string) Temporary file name.
* return image JPEG image object.
* @public static
*/
public static function _toJPEG($image, $quality, $tempfile) {
imagejpeg($image, $tempfile, $quality);
imagedestroy($image);
$retvars = self::_parsejpeg($tempfile);
// tidy up by removing temporary image
unlink($tempfile);
return $retvars;
}
/**
* Extract info from a JPEG file without using the GD library.
* @param $file (string) image file to parse
* @return array structure containing the image data
* @public static
*/
public static function _parsejpeg($file) {
// check if is a local file
if (!@file_exists($file)) {
// try to encode spaces on filename
$tfile = str_replace(' ', '%20', $file);
if (@file_exists($tfile)) {
$file = $tfile;
}
}
$a = getimagesize($file);
if (empty($a)) {
//Missing or incorrect image file
return false;
}
if ($a[2] != 2) {
// Not a JPEG file
return false;
}
// bits per pixel
$bpc = isset($a['bits']) ? intval($a['bits']) : 8;
// number of image channels
if (!isset($a['channels'])) {
$channels = 3;
} else {
$channels = intval($a['channels']);
}
// default colour space
switch ($channels) {
case 1: {
$colspace = 'DeviceGray';
break;
}
case 3: {
$colspace = 'DeviceRGB';
break;
}
case 4: {
$colspace = 'DeviceCMYK';
break;
}
default: {
$channels = 3;
$colspace = 'DeviceRGB';
break;
}
}
// get file content
$data = file_get_contents($file);
// check for embedded ICC profile
$icc = array();
$offset = 0;
while (($pos = strpos($data, "ICC_PROFILE\0", $offset)) !== false) {
// get ICC sequence length
$length = (TCPDF_STATIC::_getUSHORT($data, ($pos - 2)) - 16);
// marker sequence number
$msn = max(1, ord($data[($pos + 12)]));
// number of markers (total of APP2 used)
$nom = max(1, ord($data[($pos + 13)]));
// get sequence segment
$icc[($msn - 1)] = substr($data, ($pos + 14), $length);
// move forward to next sequence
$offset = ($pos + 14 + $length);
}
// order and compact ICC segments
if (count($icc) > 0) {
ksort($icc);
$icc = implode('', $icc);
if ((ord($icc[36]) != 0x61) OR (ord($icc[37]) != 0x63) OR (ord($icc[38]) != 0x73) OR (ord($icc[39]) != 0x70)) {
// invalid ICC profile
$icc = false;
}
} else {
$icc = false;
}
return array('w' => $a[0], 'h' => $a[1], 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'DCTDecode', 'data' => $data);
}
/**
* Extract info from a PNG file without using the GD library.
* @param $file (string) image file to parse
* @return array structure containing the image data
* @public static
*/
public static function _parsepng($file) {
$f = @fopen($file, 'rb');
if ($f === false) {
// Can't open image file
return false;
}
//Check signature
if (fread($f, 8) != chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) {
// Not a PNG file
return false;
}
//Read header chunk
fread($f, 4);
if (fread($f, 4) != 'IHDR') {
//Incorrect PNG file
return false;
}
$w = TCPDF_STATIC::_freadint($f);
$h = TCPDF_STATIC::_freadint($f);
$bpc = ord(fread($f, 1));
$ct = ord(fread($f, 1));
if ($ct == 0) {
$colspace = 'DeviceGray';
} elseif ($ct == 2) {
$colspace = 'DeviceRGB';
} elseif ($ct == 3) {
$colspace = 'Indexed';
} else {
// alpha channel
fclose($f);
return 'pngalpha';
}
if (ord(fread($f, 1)) != 0) {
// Unknown compression method
fclose($f);
return false;
}
if (ord(fread($f, 1)) != 0) {
// Unknown filter method
fclose($f);
return false;
}
if (ord(fread($f, 1)) != 0) {
// Interlacing not supported
fclose($f);
return false;
}
fread($f, 4);
$channels = ($ct == 2 ? 3 : 1);
$parms = '/DecodeParms << /Predictor 15 /Colors '.$channels.' /BitsPerComponent '.$bpc.' /Columns '.$w.' >>';
//Scan chunks looking for palette, transparency and image data
$pal = '';
$trns = '';
$data = '';
$icc = false;
do {
$n = TCPDF_STATIC::_freadint($f);
$type = fread($f, 4);
if ($type == 'PLTE') {
// read palette
$pal = TCPDF_STATIC::rfread($f, $n);
fread($f, 4);
} elseif ($type == 'tRNS') {
// read transparency info
$t = TCPDF_STATIC::rfread($f, $n);
if ($ct == 0) { // DeviceGray
$trns = array(ord($t[1]));
} elseif ($ct == 2) { // DeviceRGB
$trns = array(ord($t[1]), ord($t[3]), ord($t[5]));
} else { // Indexed
if ($n > 0) {
$trns = array();
for ($i = 0; $i < $n; ++ $i) {
$trns[] = ord($t{$i});
}
}
}
fread($f, 4);
} elseif ($type == 'IDAT') {
// read image data block
$data .= TCPDF_STATIC::rfread($f, $n);
fread($f, 4);
} elseif ($type == 'iCCP') {
// skip profile name
$len = 0;
while ((ord(fread($f, 1)) != 0) AND ($len < 80)) {
++$len;
}
// get compression method
if (ord(fread($f, 1)) != 0) {
// Unknown filter method
fclose($f);
return false;
}
// read ICC Color Profile
$icc = TCPDF_STATIC::rfread($f, ($n - $len - 2));
// decompress profile
$icc = gzuncompress($icc);
fread($f, 4);
} elseif ($type == 'IEND') {
break;
} else {
TCPDF_STATIC::rfread($f, $n + 4);
}
} while ($n);
if (($colspace == 'Indexed') AND (empty($pal))) {
// Missing palette
fclose($f);
return false;
}
fclose($f);
return array('w' => $w, 'h' => $h, 'ch' => $channels, 'icc' => $icc, 'cs' => $colspace, 'bpc' => $bpc, 'f' => 'FlateDecode', 'parms' => $parms, 'pal' => $pal, 'trns' => $trns, 'data' => $data);
}
} // END OF TCPDF_IMAGES CLASS
//============================================================+
// END OF FILE
//============================================================+

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,241 +0,0 @@
<?php
//============================================================+
// File name : tcpdf_autoconfig.php
// Version : 1.1.1
// Begin : 2013-05-16
// Last Update : 2014-12-18
// Authors : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2011-2014 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the License
// along with TCPDF. If not, see
// <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Try to automatically configure some TCPDF
// constants if not defined.
//
//============================================================+
/**
* @file
* Try to automatically configure some TCPDF constants if not defined.
* @package com.tecnick.tcpdf
* @version 1.1.1
*/
// DOCUMENT_ROOT fix for IIS Webserver
if ((!isset($_SERVER['DOCUMENT_ROOT'])) OR (empty($_SERVER['DOCUMENT_ROOT']))) {
if(isset($_SERVER['SCRIPT_FILENAME'])) {
$_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
} elseif(isset($_SERVER['PATH_TRANSLATED'])) {
$_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
} else {
// define here your DOCUMENT_ROOT path if the previous fails (e.g. '/var/www')
$_SERVER['DOCUMENT_ROOT'] = '/';
}
}
$_SERVER['DOCUMENT_ROOT'] = str_replace('//', '/', $_SERVER['DOCUMENT_ROOT']);
if (substr($_SERVER['DOCUMENT_ROOT'], -1) != '/') {
$_SERVER['DOCUMENT_ROOT'] .= '/';
}
// Load main configuration file only if the K_TCPDF_EXTERNAL_CONFIG constant is set to false.
if (!defined('K_TCPDF_EXTERNAL_CONFIG') OR !K_TCPDF_EXTERNAL_CONFIG) {
// define a list of default config files in order of priority
$tcpdf_config_files = array(dirname(__FILE__).'/config/tcpdf_config.php', '/etc/php-tcpdf/tcpdf_config.php', '/etc/tcpdf/tcpdf_config.php', '/etc/tcpdf_config.php');
foreach ($tcpdf_config_files as $tcpdf_config) {
if (@file_exists($tcpdf_config) AND is_readable($tcpdf_config)) {
require_once($tcpdf_config);
break;
}
}
}
if (!defined('K_PATH_MAIN')) {
define ('K_PATH_MAIN', dirname(__FILE__).'/');
}
if (!defined('K_PATH_FONTS')) {
define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');
}
if (!defined('K_PATH_URL')) {
$k_path_url = K_PATH_MAIN; // default value for console mode
if (isset($_SERVER['HTTP_HOST']) AND (!empty($_SERVER['HTTP_HOST']))) {
if(isset($_SERVER['HTTPS']) AND (!empty($_SERVER['HTTPS'])) AND (strtolower($_SERVER['HTTPS']) != 'off')) {
$k_path_url = 'https://';
} else {
$k_path_url = 'http://';
}
$k_path_url .= $_SERVER['HTTP_HOST'];
$k_path_url .= str_replace( '\\', '/', substr(K_PATH_MAIN, (strlen($_SERVER['DOCUMENT_ROOT']) - 1)));
}
define ('K_PATH_URL', $k_path_url);
}
if (!defined('K_PATH_IMAGES')) {
$tcpdf_images_dirs = array(K_PATH_MAIN.'examples/images/', K_PATH_MAIN.'images/', '/usr/share/doc/php-tcpdf/examples/images/', '/usr/share/doc/tcpdf/examples/images/', '/usr/share/doc/php/tcpdf/examples/images/', '/var/www/tcpdf/images/', '/var/www/html/tcpdf/images/', '/usr/local/apache2/htdocs/tcpdf/images/', K_PATH_MAIN);
foreach ($tcpdf_images_dirs as $tcpdf_images_path) {
if (@file_exists($tcpdf_images_path)) {
define ('K_PATH_IMAGES', $tcpdf_images_path);
break;
}
}
}
if (!defined('PDF_HEADER_LOGO')) {
$tcpdf_header_logo = '';
if (@file_exists(K_PATH_IMAGES.'tcpdf_logo.jpg')) {
$tcpdf_header_logo = 'tcpdf_logo.jpg';
}
define ('PDF_HEADER_LOGO', $tcpdf_header_logo);
}
if (!defined('PDF_HEADER_LOGO_WIDTH')) {
if (!empty($tcpdf_header_logo)) {
define ('PDF_HEADER_LOGO_WIDTH', 30);
} else {
define ('PDF_HEADER_LOGO_WIDTH', 0);
}
}
if (!defined('K_PATH_CACHE')) {
$K_PATH_CACHE = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir();
if (substr($K_PATH_CACHE, -1) != '/') {
$K_PATH_CACHE .= '/';
}
define ('K_PATH_CACHE', $K_PATH_CACHE);
}
if (!defined('K_BLANK_IMAGE')) {
define ('K_BLANK_IMAGE', '_blank.png');
}
if (!defined('PDF_PAGE_FORMAT')) {
define ('PDF_PAGE_FORMAT', 'A4');
}
if (!defined('PDF_PAGE_ORIENTATION')) {
define ('PDF_PAGE_ORIENTATION', 'P');
}
if (!defined('PDF_CREATOR')) {
define ('PDF_CREATOR', 'TCPDF');
}
if (!defined('PDF_AUTHOR')) {
define ('PDF_AUTHOR', 'TCPDF');
}
if (!defined('PDF_HEADER_TITLE')) {
define ('PDF_HEADER_TITLE', 'TCPDF Example');
}
if (!defined('PDF_HEADER_STRING')) {
define ('PDF_HEADER_STRING', "by Nicola Asuni - Tecnick.com\nwww.tcpdf.org");
}
if (!defined('PDF_UNIT')) {
define ('PDF_UNIT', 'mm');
}
if (!defined('PDF_MARGIN_HEADER')) {
define ('PDF_MARGIN_HEADER', 5);
}
if (!defined('PDF_MARGIN_FOOTER')) {
define ('PDF_MARGIN_FOOTER', 10);
}
if (!defined('PDF_MARGIN_TOP')) {
define ('PDF_MARGIN_TOP', 27);
}
if (!defined('PDF_MARGIN_BOTTOM')) {
define ('PDF_MARGIN_BOTTOM', 25);
}
if (!defined('PDF_MARGIN_LEFT')) {
define ('PDF_MARGIN_LEFT', 15);
}
if (!defined('PDF_MARGIN_RIGHT')) {
define ('PDF_MARGIN_RIGHT', 15);
}
if (!defined('PDF_FONT_NAME_MAIN')) {
define ('PDF_FONT_NAME_MAIN', 'helvetica');
}
if (!defined('PDF_FONT_SIZE_MAIN')) {
define ('PDF_FONT_SIZE_MAIN', 10);
}
if (!defined('PDF_FONT_NAME_DATA')) {
define ('PDF_FONT_NAME_DATA', 'helvetica');
}
if (!defined('PDF_FONT_SIZE_DATA')) {
define ('PDF_FONT_SIZE_DATA', 8);
}
if (!defined('PDF_FONT_MONOSPACED')) {
define ('PDF_FONT_MONOSPACED', 'courier');
}
if (!defined('PDF_IMAGE_SCALE_RATIO')) {
define ('PDF_IMAGE_SCALE_RATIO', 1.25);
}
if (!defined('HEAD_MAGNIFICATION')) {
define('HEAD_MAGNIFICATION', 1.1);
}
if (!defined('K_CELL_HEIGHT_RATIO')) {
define('K_CELL_HEIGHT_RATIO', 1.25);
}
if (!defined('K_TITLE_MAGNIFICATION')) {
define('K_TITLE_MAGNIFICATION', 1.3);
}
if (!defined('K_SMALL_RATIO')) {
define('K_SMALL_RATIO', 2/3);
}
if (!defined('K_THAI_TOPCHARS')) {
define('K_THAI_TOPCHARS', true);
}
if (!defined('K_TCPDF_CALLS_IN_HTML')) {
define('K_TCPDF_CALLS_IN_HTML', false);
}
if (!defined('K_TCPDF_THROW_EXCEPTION_ERROR')) {
define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
}
if (!defined('K_TIMEZONE')) {
define('K_TIMEZONE', @date_default_timezone_get());
}
//============================================================+
// END OF FILE
//============================================================+