Fixed bug #15047 Remove trailing whitespaces in front of EOL (Thanks to Nikolas Hagel...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_sqlparser.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2004-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * TYPO3 SQL parser
29 *
30 * $Id$
31 *
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 107: class t3lib_sqlparser
40 *
41 * SECTION: SQL Parsing, full queries
42 * 129: function parseSQL($parseString)
43 * 192: function parseSELECT($parseString)
44 * 261: function parseUPDATE($parseString)
45 * 315: function parseINSERT($parseString)
46 * 375: function parseDELETE($parseString)
47 * 413: function parseEXPLAIN($parseString)
48 * 435: function parseCREATETABLE($parseString)
49 * 514: function parseALTERTABLE($parseString)
50 * 583: function parseDROPTABLE($parseString)
51 * 616: function parseCREATEDATABASE($parseString)
52 *
53 * SECTION: SQL Parsing, helper functions for parts of queries
54 * 670: function parseFieldList(&$parseString, $stopRegex='')
55 * 791: function parseFromTables(&$parseString, $stopRegex='')
56 * 882: function parseWhereClause(&$parseString, $stopRegex='')
57 * 990: function parseFieldDef(&$parseString, $stopRegex='')
58 *
59 * SECTION: Parsing: Helper functions
60 * 1053: function nextPart(&$parseString,$regex,$trimAll=FALSE)
61 * 1068: function getValue(&$parseString,$comparator='')
62 * 1127: function getValueInQuotes(&$parseString,$quote)
63 * 1153: function parseStripslashes($str)
64 * 1167: function compileAddslashes($str)
65 * 1182: function parseError($msg,$restQuery)
66 * 1196: function trimSQL($str)
67 *
68 * SECTION: Compiling queries
69 * 1225: function compileSQL($components)
70 * 1263: function compileSELECT($components)
71 * 1294: function compileUPDATE($components)
72 * 1322: function compileINSERT($components)
73 * 1362: function compileDELETE($components)
74 * 1382: function compileCREATETABLE($components)
75 * 1415: function compileALTERTABLE($components)
76 *
77 * SECTION: Compiling queries, helper functions for parts of queries
78 * 1468: function compileFieldList($selectFields)
79 * 1510: function compileFromTables($tablesArray)
80 * 1551: function compileWhereClause($clauseArray)
81 * 1605: function compileFieldCfg($fieldCfg)
82 *
83 * SECTION: Debugging
84 * 1654: function debug_parseSQLpart($part,$str)
85 * 1679: function debug_parseSQLpartCompare($str,$newStr,$caseInsensitive=FALSE)
86 * 1712: function debug_testSQL($SQLquery)
87 *
88 * TOTAL FUNCTIONS: 35
89 * (This index is automatically created/updated by the extension "extdeveval")
90 *
91 */
92
93
94
95
96
97
98
99
100 /**
101 * TYPO3 SQL parser class.
102 *
103 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
104 * @package TYPO3
105 * @subpackage t3lib
106 */
107 class t3lib_sqlparser {
108
109 // Parser:
110 var $parse_error = ''; // Parsing error string
111 var $lastStopKeyWord = ''; // Last stop keyword used.
112
113
114
115
116 /*************************************
117 *
118 * SQL Parsing, full queries
119 *
120 **************************************/
121
122 /**
123 * Parses any single SQL query
124 *
125 * @param string SQL query
126 * @return array Result array with all the parts in - or error message string
127 * @see compileSQL(), debug_testSQL()
128 */
129 public function parseSQL($parseString) {
130 // Prepare variables:
131 $parseString = $this->trimSQL($parseString);
132 $this->parse_error = '';
133 $result = array();
134
135 // Finding starting keyword of string:
136 $_parseString = $parseString; // Protecting original string...
137 $keyword = $this->nextPart($_parseString, '^(SELECT|UPDATE|INSERT[[:space:]]+INTO|DELETE[[:space:]]+FROM|EXPLAIN|DROP[[:space:]]+TABLE|CREATE[[:space:]]+TABLE|CREATE[[:space:]]+DATABASE|ALTER[[:space:]]+TABLE|TRUNCATE[[:space:]]+TABLE)[[:space:]]+');
138 $keyword = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$keyword));
139
140 switch($keyword) {
141 case 'SELECT':
142 // Parsing SELECT query:
143 $result = $this->parseSELECT($parseString);
144 break;
145 case 'UPDATE':
146 // Parsing UPDATE query:
147 $result = $this->parseUPDATE($parseString);
148 break;
149 case 'INSERTINTO':
150 // Parsing INSERT query:
151 $result = $this->parseINSERT($parseString);
152 break;
153 case 'DELETEFROM':
154 // Parsing DELETE query:
155 $result = $this->parseDELETE($parseString);
156 break;
157 case 'EXPLAIN':
158 // Parsing EXPLAIN SELECT query:
159 $result = $this->parseEXPLAIN($parseString);
160 break;
161 case 'DROPTABLE':
162 // Parsing DROP TABLE query:
163 $result = $this->parseDROPTABLE($parseString);
164 break;
165 case 'ALTERTABLE':
166 // Parsing ALTER TABLE query:
167 $result = $this->parseALTERTABLE($parseString);
168 break;
169 case 'CREATETABLE':
170 // Parsing CREATE TABLE query:
171 $result = $this->parseCREATETABLE($parseString);
172 break;
173 case 'CREATEDATABASE':
174 // Parsing CREATE DATABASE query:
175 $result = $this->parseCREATEDATABASE($parseString);
176 break;
177 case 'TRUNCATETABLE':
178 // Parsing TRUNCATE TABLE query:
179 $result = $this->parseTRUNCATETABLE($parseString);
180 break;
181 default:
182 $result = $this->parseError('"'.$keyword.'" is not a keyword',$parseString);
183 break;
184 }
185
186 return $result;
187 }
188
189 /**
190 * Parsing SELECT query
191 *
192 * @param string SQL string with SELECT query to parse
193 * @return mixed Returns array with components of SELECT query on success, otherwise an error message string.
194 * @see compileSELECT()
195 */
196 protected function parseSELECT($parseString) {
197
198 // Removing SELECT:
199 $parseString = $this->trimSQL($parseString);
200 $parseString = ltrim(substr($parseString,6));
201
202 // Init output variable:
203 $result = array();
204 $result['type'] = 'SELECT';
205
206 // Looking for STRAIGHT_JOIN keyword:
207 $result['STRAIGHT_JOIN'] = $this->nextPart($parseString, '^(STRAIGHT_JOIN)[[:space:]]+');
208
209 // Select fields:
210 $result['SELECT'] = $this->parseFieldList($parseString, '^(FROM)[[:space:]]+');
211 if ($this->parse_error) { return $this->parse_error; }
212
213 // Continue if string is not ended:
214 if ($parseString) {
215
216 // Get table list:
217 $result['FROM'] = $this->parseFromTables($parseString, '^(WHERE)[[:space:]]+');
218 if ($this->parse_error) { return $this->parse_error; }
219
220 // If there are more than just the tables (a WHERE clause that would be...)
221 if ($parseString) {
222
223 // Get WHERE clause:
224 $result['WHERE'] = $this->parseWhereClause($parseString, '^(GROUP[[:space:]]+BY|ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
225 if ($this->parse_error) { return $this->parse_error; }
226
227 // If the WHERE clause parsing was stopped by GROUP BY, ORDER BY or LIMIT, then proceed with parsing:
228 if ($this->lastStopKeyWord) {
229
230 // GROUP BY parsing:
231 if ($this->lastStopKeyWord == 'GROUPBY') {
232 $result['GROUPBY'] = $this->parseFieldList($parseString, '^(ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
233 if ($this->parse_error) { return $this->parse_error; }
234 }
235
236 // ORDER BY parsing:
237 if ($this->lastStopKeyWord == 'ORDERBY') {
238 $result['ORDERBY'] = $this->parseFieldList($parseString, '^(LIMIT)[[:space:]]+');
239 if ($this->parse_error) { return $this->parse_error; }
240 }
241
242 // LIMIT parsing:
243 if ($this->lastStopKeyWord == 'LIMIT') {
244 if (preg_match('/^([0-9]+|[0-9]+[[:space:]]*,[[:space:]]*[0-9]+)$/',trim($parseString))) {
245 $result['LIMIT'] = $parseString;
246 } else {
247 return $this->parseError('No value for limit!',$parseString);
248 }
249 }
250 }
251 }
252 } else return $this->parseError('No table to select from!',$parseString);
253
254 // Store current parseString in the result array for possible further processing (e.g., subquery support by DBAL)
255 $result['parseString'] = $parseString;
256
257 // Return result:
258 return $result;
259 }
260
261 /**
262 * Parsing UPDATE query
263 *
264 * @param string SQL string with UPDATE query to parse
265 * @return mixed Returns array with components of UPDATE query on success, otherwise an error message string.
266 * @see compileUPDATE()
267 */
268 protected function parseUPDATE($parseString) {
269
270 // Removing UPDATE
271 $parseString = $this->trimSQL($parseString);
272 $parseString = ltrim(substr($parseString,6));
273
274 // Init output variable:
275 $result = array();
276 $result['type'] = 'UPDATE';
277
278 // Get table:
279 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
280
281 // Continue if string is not ended:
282 if ($result['TABLE']) {
283 if ($parseString && $this->nextPart($parseString, '^(SET)[[:space:]]+')) {
284
285 $comma = TRUE;
286
287 // Get field/value pairs:
288 while($comma) {
289 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*=')) {
290 $this->nextPart($parseString,'^(=)'); // Strip of "=" sign.
291 $value = $this->getValue($parseString);
292 $result['FIELDS'][$fieldName] = $value;
293 } else return $this->parseError('No fieldname found',$parseString);
294
295 $comma = $this->nextPart($parseString,'^(,)');
296 }
297
298 // WHERE
299 if ($this->nextPart($parseString,'^(WHERE)')) {
300 $result['WHERE'] = $this->parseWhereClause($parseString);
301 if ($this->parse_error) { return $this->parse_error; }
302 }
303 } else return $this->parseError('Query missing SET...',$parseString);
304 } else return $this->parseError('No table found!',$parseString);
305
306 // Should be no more content now:
307 if ($parseString) {
308 return $this->parseError('Still content in clause after parsing!',$parseString);
309 }
310
311 // Return result:
312 return $result;
313 }
314
315 /**
316 * Parsing INSERT query
317 *
318 * @param string SQL string with INSERT query to parse
319 * @return mixed Returns array with components of INSERT query on success, otherwise an error message string.
320 * @see compileINSERT()
321 */
322 protected function parseINSERT($parseString) {
323
324 // Removing INSERT
325 $parseString = $this->trimSQL($parseString);
326 $parseString = ltrim(substr(ltrim(substr($parseString,6)),4));
327
328 // Init output variable:
329 $result = array();
330 $result['type'] = 'INSERT';
331
332 // Get table:
333 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()');
334
335 if ($result['TABLE']) {
336
337 if ($this->nextPart($parseString,'^(VALUES)([[:space:]]+|\()')) { // In this case there are no field names mentioned in the SQL!
338 // Get values/fieldnames (depending...)
339 $result['VALUES_ONLY'] = $this->getValue($parseString,'IN');
340 if ($this->parse_error) {
341 return $this->parse_error;
342 }
343 if (preg_match('/^,/', $parseString)) {
344 $result['VALUES_ONLY'] = array($result['VALUES_ONLY']);
345 $result['EXTENDED'] = '1';
346 while ($this->nextPart($parseString, '^(,)') === ',') {
347 $result['VALUES_ONLY'][] = $this->getValue($parseString, 'IN');
348 if ($this->parse_error) {
349 return $this->parse_error;
350 }
351 }
352 }
353 } else { // There are apparently fieldnames listed:
354 $fieldNames = $this->getValue($parseString,'_LIST');
355 if ($this->parse_error) { return $this->parse_error; }
356
357 if ($this->nextPart($parseString,'^(VALUES)([[:space:]]+|\()')) { // "VALUES" keyword binds the fieldnames to values:
358 $result['FIELDS'] = array();
359 do {
360 $values = $this->getValue($parseString, 'IN'); // Using the "getValue" function to get the field list...
361 if ($this->parse_error) {
362 return $this->parse_error;
363 }
364
365 $insertValues = array();
366 foreach ($fieldNames as $k => $fN) {
367 if (preg_match('/^[[:alnum:]_]+$/', $fN)) {
368 if (isset($values[$k])) {
369 if (!isset($insertValues[$fN])) {
370 $insertValues[$fN] = $values[$k];
371 } else return $this->parseError('Fieldname ("' . $fN . '") already found in list!', $parseString);
372 } else return $this->parseError('No value set!', $parseString);
373 } else return $this->parseError('Invalid fieldname ("' . $fN . '")', $parseString);
374 }
375 if (isset($values[$k + 1])) {
376 return $this->parseError('Too many values in list!', $parseString);
377 }
378 $result['FIELDS'][] = $insertValues;
379 } while ($this->nextPart($parseString, '^(,)') === ',');
380
381 if (count($result['FIELDS']) === 1) {
382 $result['FIELDS'] = $result['FIELDS'][0];
383 } else {
384 $result['EXTENDED'] = '1';
385 }
386 } else return $this->parseError('VALUES keyword expected',$parseString);
387 }
388 } else return $this->parseError('No table found!',$parseString);
389
390 // Should be no more content now:
391 if ($parseString) {
392 return $this->parseError('Still content after parsing!',$parseString);
393 }
394
395 // Return result
396 return $result;
397 }
398
399 /**
400 * Parsing DELETE query
401 *
402 * @param string SQL string with DELETE query to parse
403 * @return mixed Returns array with components of DELETE query on success, otherwise an error message string.
404 * @see compileDELETE()
405 */
406 protected function parseDELETE($parseString) {
407
408 // Removing DELETE
409 $parseString = $this->trimSQL($parseString);
410 $parseString = ltrim(substr(ltrim(substr($parseString,6)),4));
411
412 // Init output variable:
413 $result = array();
414 $result['type'] = 'DELETE';
415
416 // Get table:
417 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
418
419 if ($result['TABLE']) {
420
421 // WHERE
422 if ($this->nextPart($parseString,'^(WHERE)')) {
423 $result['WHERE'] = $this->parseWhereClause($parseString);
424 if ($this->parse_error) { return $this->parse_error; }
425 }
426 } else return $this->parseError('No table found!',$parseString);
427
428 // Should be no more content now:
429 if ($parseString) {
430 return $this->parseError('Still content in clause after parsing!',$parseString);
431 }
432
433 // Return result:
434 return $result;
435 }
436
437 /**
438 * Parsing EXPLAIN query
439 *
440 * @param string SQL string with EXPLAIN query to parse
441 * @return mixed Returns array with components of EXPLAIN query on success, otherwise an error message string.
442 * @see parseSELECT()
443 */
444 protected function parseEXPLAIN($parseString) {
445
446 // Removing EXPLAIN
447 $parseString = $this->trimSQL($parseString);
448 $parseString = ltrim(substr($parseString,6));
449
450 // Init output variable:
451 $result = $this->parseSELECT($parseString);
452 if (is_array($result)) {
453 $result['type'] = 'EXPLAIN';
454 }
455
456 return $result;
457 }
458
459 /**
460 * Parsing CREATE TABLE query
461 *
462 * @param string SQL string starting with CREATE TABLE
463 * @return mixed Returns array with components of CREATE TABLE query on success, otherwise an error message string.
464 * @see compileCREATETABLE()
465 */
466 protected function parseCREATETABLE($parseString) {
467
468 // Removing CREATE TABLE
469 $parseString = $this->trimSQL($parseString);
470 $parseString = ltrim(substr(ltrim(substr($parseString,6)),5));
471
472 // Init output variable:
473 $result = array();
474 $result['type'] = 'CREATETABLE';
475
476 // Get table:
477 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*\(',TRUE);
478
479 if ($result['TABLE']) {
480
481 // While the parseString is not yet empty:
482 while(strlen($parseString)>0) {
483 if ($key = $this->nextPart($parseString, '^(KEY|PRIMARY KEY|UNIQUE KEY|UNIQUE)([[:space:]]+|\()')) { // Getting key
484 $key = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$key));
485
486 switch($key) {
487 case 'PRIMARYKEY':
488 $result['KEYS']['PRIMARYKEY'] = $this->getValue($parseString,'_LIST');
489 if ($this->parse_error) { return $this->parse_error; }
490 break;
491 case 'UNIQUE':
492 case 'UNIQUEKEY':
493 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()')) {
494 $result['KEYS']['UNIQUE'] = array($keyName => $this->getValue($parseString,'_LIST'));
495 if ($this->parse_error) { return $this->parse_error; }
496 } else return $this->parseError('No keyname found',$parseString);
497 break;
498 case 'KEY':
499 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()')) {
500 $result['KEYS'][$keyName] = $this->getValue($parseString, '_LIST', 'INDEX');
501 if ($this->parse_error) { return $this->parse_error; }
502 } else return $this->parseError('No keyname found',$parseString);
503 break;
504 }
505 } elseif ($fieldName = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) { // Getting field:
506 $result['FIELDS'][$fieldName]['definition'] = $this->parseFieldDef($parseString);
507 if ($this->parse_error) { return $this->parse_error; }
508 }
509
510 // Finding delimiter:
511 $delim = $this->nextPart($parseString, '^(,|\))');
512 if (!$delim) {
513 return $this->parseError('No delimiter found',$parseString);
514 } elseif ($delim==')') {
515 break;
516 }
517 }
518
519 // Finding what is after the table definition - table type in MySQL
520 if ($delim==')') {
521 if ($this->nextPart($parseString, '^((ENGINE|TYPE)[[:space:]]*=)')) {
522 $result['tableType'] = $parseString;
523 $parseString = '';
524 }
525 } else return $this->parseError('No fieldname found!',$parseString);
526
527 // Getting table type
528 } else return $this->parseError('No table found!',$parseString);
529
530 // Should be no more content now:
531 if ($parseString) {
532 return $this->parseError('Still content in clause after parsing!',$parseString);
533 }
534
535 return $result;
536 }
537
538 /**
539 * Parsing ALTER TABLE query
540 *
541 * @param string SQL string starting with ALTER TABLE
542 * @return mixed Returns array with components of ALTER TABLE query on success, otherwise an error message string.
543 * @see compileALTERTABLE()
544 */
545 protected function parseALTERTABLE($parseString) {
546
547 // Removing ALTER TABLE
548 $parseString = $this->trimSQL($parseString);
549 $parseString = ltrim(substr(ltrim(substr($parseString,5)),5));
550
551 // Init output variable:
552 $result = array();
553 $result['type'] = 'ALTERTABLE';
554
555 // Get table:
556 $hasBackquote = ($this->nextPart($parseString, '^(`)') === '`');
557 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)' . ($hasBackquote ? '`' : '') . '[[:space:]]+');
558 if ($hasBackquote && $this->nextPart($parseString, '^(`)') !== '`') {
559 return $this->parseError('No end backquote found!', $parseString);
560 }
561
562 if ($result['TABLE']) {
563 if ($result['action'] = $this->nextPart($parseString, '^(CHANGE|DROP[[:space:]]+KEY|DROP[[:space:]]+PRIMARY[[:space:]]+KEY|ADD[[:space:]]+KEY|ADD[[:space:]]+PRIMARY[[:space:]]+KEY|ADD[[:space:]]+UNIQUE|DROP|ADD|RENAME|DEFAULT[[:space:]]+CHARACTER[[:space:]]+SET|ENGINE)([[:space:]]+|\(|=)')) {
564 $actionKey = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$result['action']));
565
566 // Getting field:
567 if (t3lib_div::inList('ADDPRIMARYKEY,DROPPRIMARYKEY,ENGINE', $actionKey) || $fieldKey = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
568
569 switch($actionKey) {
570 case 'ADD':
571 $result['FIELD'] = $fieldKey;
572 $result['definition'] = $this->parseFieldDef($parseString);
573 if ($this->parse_error) { return $this->parse_error; }
574 break;
575 case 'DROP':
576 case 'RENAME':
577 $result['FIELD'] = $fieldKey;
578 break;
579 case 'CHANGE':
580 $result['FIELD'] = $fieldKey;
581 if ($result['newField'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
582 $result['definition'] = $this->parseFieldDef($parseString);
583 if ($this->parse_error) { return $this->parse_error; }
584 } else return $this->parseError('No NEW field name found',$parseString);
585 break;
586
587 case 'ADDKEY':
588 case 'ADDPRIMARYKEY':
589 case 'ADDUNIQUE':
590 $result['KEY'] = $fieldKey;
591 $result['fields'] = $this->getValue($parseString, '_LIST', 'INDEX');
592 if ($this->parse_error) { return $this->parse_error; }
593 break;
594 case 'DROPKEY':
595 $result['KEY'] = $fieldKey;
596 break;
597 case 'DROPPRIMARYKEY':
598 // ??? todo!
599 break;
600 case 'DEFAULTCHARACTERSET':
601 $result['charset'] = $fieldKey;
602 break;
603 case 'ENGINE':
604 $result['engine'] = $this->nextPart($parseString, '^=[[:space:]]*([[:alnum:]]+)[[:space:]]+', TRUE);
605 break;
606 }
607 } else return $this->parseError('No field name found',$parseString);
608 } else return $this->parseError('No action CHANGE, DROP or ADD found!',$parseString);
609 } else return $this->parseError('No table found!',$parseString);
610
611 // Should be no more content now:
612 if ($parseString) {
613 return $this->parseError('Still content in clause after parsing!',$parseString);
614 }
615
616 return $result;
617 }
618
619 /**
620 * Parsing DROP TABLE query
621 *
622 * @param string SQL string starting with DROP TABLE
623 * @return mixed Returns array with components of DROP TABLE query on success, otherwise an error message string.
624 */
625 protected function parseDROPTABLE($parseString) {
626
627 // Removing DROP TABLE
628 $parseString = $this->trimSQL($parseString);
629 $parseString = ltrim(substr(ltrim(substr($parseString,4)),5));
630
631 // Init output variable:
632 $result = array();
633 $result['type'] = 'DROPTABLE';
634
635 // IF EXISTS
636 $result['ifExists'] = $this->nextPart($parseString, '^(IF[[:space:]]+EXISTS[[:space:]]+)');
637
638 // Get table:
639 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
640
641 if ($result['TABLE']) {
642
643 // Should be no more content now:
644 if ($parseString) {
645 return $this->parseError('Still content in clause after parsing!',$parseString);
646 }
647
648 return $result;
649 } else return $this->parseError('No table found!',$parseString);
650 }
651
652 /**
653 * Parsing CREATE DATABASE query
654 *
655 * @param string SQL string starting with CREATE DATABASE
656 * @return mixed Returns array with components of CREATE DATABASE query on success, otherwise an error message string.
657 */
658 protected function parseCREATEDATABASE($parseString) {
659
660 // Removing CREATE DATABASE
661 $parseString = $this->trimSQL($parseString);
662 $parseString = ltrim(substr(ltrim(substr($parseString,6)),8));
663
664 // Init output variable:
665 $result = array();
666 $result['type'] = 'CREATEDATABASE';
667
668 // Get table:
669 $result['DATABASE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
670
671 if ($result['DATABASE']) {
672
673 // Should be no more content now:
674 if ($parseString) {
675 return $this->parseError('Still content in clause after parsing!',$parseString);
676 }
677
678 return $result;
679 } else return $this->parseError('No database found!',$parseString);
680 }
681
682 /**
683 * Parsing TRUNCATE TABLE query
684 *
685 * @param string SQL string starting with TRUNCATE TABLE
686 * @return mixed Returns array with components of TRUNCATE TABLE query on success, otherwise an error message string.
687 */
688 protected function parseTRUNCATETABLE($parseString) {
689
690 // Removing TRUNCATE TABLE
691 $parseString = $this->trimSQL($parseString);
692 $parseString = ltrim(substr(ltrim(substr($parseString, 8)), 5));
693
694 // Init output variable:
695 $result = array();
696 $result['type'] = 'TRUNCATETABLE';
697
698 // Get table:
699 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
700
701 if ($result['TABLE']) {
702
703 // Should be no more content now:
704 if ($parseString) {
705 return $this->parseError('Still content in clause after parsing!', $parseString);
706 }
707
708 return $result;
709 } else {
710 return $this->parseError('No table found!', $parseString);
711 }
712 }
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728 /**************************************
729 *
730 * SQL Parsing, helper functions for parts of queries
731 *
732 **************************************/
733
734 /**
735 * Parsing the fields in the "SELECT [$selectFields] FROM" part of a query into an array.
736 * The output from this function can be compiled back into a field list with ->compileFieldList()
737 * Will detect the keywords "DESC" and "ASC" after the table name; thus is can be used for parsing the more simply ORDER BY and GROUP BY field lists as well!
738 *
739 * @param string The string with fieldnames, eg. "title, uid AS myUid, max(tstamp), count(*)" etc. NOTICE: passed by reference!
740 * @param string Regular expressing to STOP parsing, eg. '^(FROM)([[:space:]]*)'
741 * @return array If successful parsing, returns an array, otherwise an error string.
742 * @see compileFieldList()
743 */
744 public function parseFieldList(&$parseString, $stopRegex = '') {
745
746 $stack = array(); // Contains the parsed content
747
748 if(strlen($parseString)==0) return $stack; // FIXME - should never happen, why does it?
749
750 $pnt = 0; // Pointer to positions in $stack
751 $level = 0; // Indicates the parenthesis level we are at.
752 $loopExit = 0; // Recursivity brake.
753
754 // Prepare variables:
755 $parseString = $this->trimSQL($parseString);
756 $this->lastStopKeyWord = '';
757 $this->parse_error = '';
758
759 // Parse any SQL hint / comments
760 $stack[$pnt]['comments'] = $this->nextPart($parseString, '^(\/\*.*\*\/)');
761
762 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
763 while (strlen($parseString)) {
764
765 // Checking if we are inside / outside parenthesis (in case of a function like count(), max(), min() etc...):
766 if ($level>0) { // Inside parenthesis here (does NOT detect if values in quotes are used, the only token is ")" or "("):
767
768 // Accumulate function content until next () parenthesis:
769 $funcContent = $this->nextPart($parseString,'^([^()]*.)');
770 $stack[$pnt]['func_content.'][] = array(
771 'level' => $level,
772 'func_content' => substr($funcContent,0,-1)
773 );
774 $stack[$pnt]['func_content'].= $funcContent;
775
776 // Detecting ( or )
777 switch(substr($stack[$pnt]['func_content'],-1)) {
778 case '(':
779 $level++;
780 break;
781 case ')':
782 $level--;
783 if (!$level) { // If this was the last parenthesis:
784 $stack[$pnt]['func_content'] = substr($stack[$pnt]['func_content'],0,-1);
785 $parseString = ltrim($parseString); // Remove any whitespace after the parenthesis.
786 }
787 break;
788 }
789 } else { // Outside parenthesis, looking for next field:
790
791 // Looking for a flow-control construct (only known constructs supported)
792 if (preg_match('/^case([[:space:]][[:alnum:]\*._]+)?[[:space:]]when/i', $parseString)) {
793 $stack[$pnt]['type'] = 'flow-control';
794 $stack[$pnt]['flow-control'] = $this->parseCaseStatement($parseString);
795 // Looking for "AS" alias:
796 if ($as = $this->nextPart($parseString, '^(AS)[[:space:]]+')) {
797 $stack[$pnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)(,|[[:space:]]+)');
798 $stack[$pnt]['as_keyword'] = $as;
799 }
800 } else {
801 // Looking for a known function (only known functions supported)
802 $func = $this->nextPart($parseString,'^(count|max|min|floor|sum|avg)[[:space:]]*\(');
803 if ($func) {
804 $parseString = trim(substr($parseString,1)); // Strip of "("
805 $stack[$pnt]['type'] = 'function';
806 $stack[$pnt]['function'] = $func;
807 $level++; // increse parenthesis level counter.
808 } else {
809 $stack[$pnt]['distinct'] = $this->nextPart($parseString,'^(distinct[[:space:]]+)');
810 // Otherwise, look for regular fieldname:
811 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)(,|[[:space:]]+)')) !== '') {
812 $stack[$pnt]['type'] = 'field';
813
814 // Explode fieldname into field and table:
815 $tableField = explode('.',$fieldName,2);
816 if (count($tableField)==2) {
817 $stack[$pnt]['table'] = $tableField[0];
818 $stack[$pnt]['field'] = $tableField[1];
819 } else {
820 $stack[$pnt]['table'] = '';
821 $stack[$pnt]['field'] = $tableField[0];
822 }
823 } else {
824 return $this->parseError('No field name found as expected in parseFieldList()',$parseString);
825 }
826 }
827 }
828 }
829
830 // After a function or field we look for "AS" alias and a comma to separate to the next field in the list:
831 if (!$level) {
832
833 // Looking for "AS" alias:
834 if ($as = $this->nextPart($parseString,'^(AS)[[:space:]]+')) {
835 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)');
836 $stack[$pnt]['as_keyword'] = $as;
837 }
838
839 // Looking for "ASC" or "DESC" keywords (for ORDER BY)
840 if ($sDir = $this->nextPart($parseString,'^(ASC|DESC)([[:space:]]+|,)')) {
841 $stack[$pnt]['sortDir'] = $sDir;
842 }
843
844 // Looking for stop-keywords:
845 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
846 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$this->lastStopKeyWord));
847 return $stack;
848 }
849
850 // Looking for comma (since the stop-keyword did not trigger a return...)
851 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
852 return $this->parseError('No comma found as expected in parseFieldList()',$parseString);
853 }
854
855 // Increasing pointer:
856 $pnt++;
857 }
858
859 // Check recursivity brake:
860 $loopExit++;
861 if ($loopExit>500) {
862 return $this->parseError('More than 500 loops, exiting prematurely in parseFieldList()...',$parseString);
863 }
864 }
865
866 // Return result array:
867 return $stack;
868 }
869
870 /**
871 * Parsing a CASE ... WHEN flow-control construct.
872 * The output from this function can be compiled back with ->compileCaseStatement()
873 *
874 * @param string The string with the CASE ... WHEN construct, eg. "CASE field WHEN 1 THEN 0 ELSE ..." etc. NOTICE: passed by reference!
875 * @return array If successful parsing, returns an array, otherwise an error string.
876 * @see compileCaseConstruct()
877 */
878 protected function parseCaseStatement(&$parseString) {
879 $result = array();
880 $result['type'] = $this->nextPart($parseString, '^(case)[[:space:]]+');
881 if (!preg_match('/^when[[:space:]]+/i', $parseString)) {
882 $value = $this->getValue($parseString);
883 if (!(isset($value[1]) || is_numeric($value[0]))) {
884 $result['case_field'] = $value[0];
885 } else {
886 $result['case_value'] = $value;
887 }
888 }
889 $result['when'] = array();
890 while ($this->nextPart($parseString, '^(when)[[:space:]]')) {
891 $when = array();
892 $when['when_value'] = $this->parseWhereClause($parseString, '^(then)[[:space:]]+');
893 $when['then_value'] = $this->getValue($parseString);
894 $result['when'][] = $when;
895 }
896 if ($this->nextPart($parseString, '^(else)[[:space:]]+')) {
897 $result['else'] = $this->getValue($parseString);
898 }
899 if (!$this->nextPart($parseString, '^(end)[[:space:]]+')) {
900 return $this->parseError('No "end" keyword found as expected in parseCaseStatement()', $parseString);
901 }
902 return $result;
903 }
904
905 /**
906 * Parsing the tablenames in the "FROM [$parseString] WHERE" part of a query into an array.
907 * The success of this parsing determines if that part of the query is supported by TYPO3.
908 *
909 * @param string list of tables, eg. "pages, tt_content" or "pages A, pages B". NOTICE: passed by reference!
910 * @param string Regular expressing to STOP parsing, eg. '^(WHERE)([[:space:]]*)'
911 * @return array If successful parsing, returns an array, otherwise an error string.
912 * @see compileFromTables()
913 */
914 public function parseFromTables(&$parseString, $stopRegex = '') {
915
916 // Prepare variables:
917 $parseString = $this->trimSQL($parseString);
918 $this->lastStopKeyWord = '';
919 $this->parse_error = '';
920
921 $stack = array(); // Contains the parsed content
922 $pnt = 0; // Pointer to positions in $stack
923 $loopExit = 0; // Recursivity brake.
924
925 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
926 while (strlen($parseString)) {
927 // Looking for the table:
928 if ($stack[$pnt]['table'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)')) {
929 // Looking for stop-keywords before fetching potential table alias:
930 if ($stopRegex && ($this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex))) {
931 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
932 return $stack;
933 }
934 if (!preg_match('/^(LEFT|RIGHT|JOIN|INNER)[[:space:]]+/i', $parseString)) {
935 $stack[$pnt]['as_keyword'] = $this->nextPart($parseString,'^(AS[[:space:]]+)');
936 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*');
937 }
938 } else return $this->parseError('No table name found as expected in parseFromTables()!', $parseString);
939
940 // Looking for JOIN
941 $joinCnt = 0;
942 while ($join = $this->nextPart($parseString,'^(LEFT[[:space:]]+JOIN|LEFT[[:space:]]+OUTER[[:space:]]+JOIN|RIGHT[[:space:]]+JOIN|RIGHT[[:space:]]+OUTER[[:space:]]+JOIN|INNER[[:space:]]+JOIN|JOIN)[[:space:]]+')) {
943 $stack[$pnt]['JOIN'][$joinCnt]['type'] = $join;
944 if ($stack[$pnt]['JOIN'][$joinCnt]['withTable'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+', 1)) {
945 if (!preg_match('/^ON[[:space:]]+/i', $parseString)) {
946 $stack[$pnt]['JOIN'][$joinCnt]['as_keyword'] = $this->nextPart($parseString, '^(AS[[:space:]]+)');
947 $stack[$pnt]['JOIN'][$joinCnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
948 }
949 if (!$this->nextPart($parseString, '^(ON[[:space:]]+)')) {
950 return $this->parseError('No join condition found in parseFromTables()!', $parseString);
951 }
952 $stack[$pnt]['JOIN'][$joinCnt]['ON'] = array();
953 $condition = array('operator' => '');
954 $parseCondition = TRUE;
955 while ($parseCondition) {
956 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)[[:space:]]*(<=|>=|<|>|=|!=)')) !== '') {
957 // Parse field name into field and table:
958 $tableField = explode('.', $fieldName, 2);
959 $condition['left'] = array();
960 if (count($tableField) == 2) {
961 $condition['left']['table'] = $tableField[0];
962 $condition['left']['field'] = $tableField[1];
963 } else {
964 $condition['left']['table'] = '';
965 $condition['left']['field'] = $tableField[0];
966 }
967 } else {
968 return $this->parseError('No join field found in parseFromTables()!', $parseString);
969 }
970 // Find "comparator":
971 $condition['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=)');
972 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) !== '') {
973 // Parse field name into field and table:
974 $tableField = explode('.', $fieldName, 2);
975 $condition['right'] = array();
976 if (count($tableField) == 2) {
977 $condition['right']['table'] = $tableField[0];
978 $condition['right']['field'] = $tableField[1];
979 } else {
980 $condition['right']['table'] = '';
981 $condition['right']['field'] = $tableField[0];
982 }
983 } else {
984 return $this->parseError('No join field found in parseFromTables()!', $parseString);
985 }
986 $stack[$pnt]['JOIN'][$joinCnt]['ON'][] = $condition;
987 if (($operator = $this->nextPart($parseString, '^(AND|OR)')) !== '') {
988 $condition = array('operator' => $operator);
989 } else {
990 $parseCondition = FALSE;
991 }
992 }
993 $joinCnt++;
994 } else return $this->parseError('No join table found in parseFromTables()!', $parseString);
995 }
996
997 // Looking for stop-keywords:
998 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
999 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
1000 return $stack;
1001 }
1002
1003 // Looking for comma:
1004 if (strlen($parseString) && !$this->nextPart($parseString, '^(,)')) {
1005 return $this->parseError('No comma found as expected in parseFromTables()', $parseString);
1006 }
1007
1008 // Increasing pointer:
1009 $pnt++;
1010
1011 // Check recursivity brake:
1012 $loopExit++;
1013 if ($loopExit > 500) {
1014 return $this->parseError('More than 500 loops, exiting prematurely in parseFromTables()...', $parseString);
1015 }
1016 }
1017
1018 // Return result array:
1019 return $stack;
1020 }
1021
1022 /**
1023 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1024 * The success of this parsing determines if that part of the query is supported by TYPO3.
1025 *
1026 * @param string WHERE clause to parse. NOTICE: passed by reference!
1027 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1028 * @return mixed If successful parsing, returns an array, otherwise an error string.
1029 */
1030 public function parseWhereClause(&$parseString, $stopRegex = '') {
1031
1032 // Prepare variables:
1033 $parseString = $this->trimSQL($parseString);
1034 $this->lastStopKeyWord = '';
1035 $this->parse_error = '';
1036
1037 $stack = array(0 => array()); // Contains the parsed content
1038 $pnt = array(0 => 0); // Pointer to positions in $stack
1039 $level = 0; // Determines parenthesis level
1040 $loopExit = 0; // Recursivity brake.
1041
1042 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
1043 while (strlen($parseString)) {
1044
1045 // Look for next parenthesis level:
1046 $newLevel = $this->nextPart($parseString,'^([(])');
1047 if ($newLevel == '(') { // If new level is started, manage stack/pointers:
1048 $level++; // Increase level
1049 $pnt[$level] = 0; // Reset pointer for this level
1050 $stack[$level] = array(); // Reset stack for this level
1051 } else { // If no new level is started, just parse the current level:
1052
1053 // Find "modifier", eg. "NOT or !"
1054 $stack[$level][$pnt[$level]]['modifier'] = trim($this->nextPart($parseString, '^(!|NOT[[:space:]]+)'));
1055
1056 // See if condition is EXISTS with a subquery
1057 if (preg_match('/^EXISTS[[:space:]]*[(]/i', $parseString)) {
1058 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(EXISTS)[[:space:]]*');
1059 $parseString = trim(substr($parseString, 1)); // Strip of "("
1060 $stack[$level][$pnt[$level]]['func']['subquery'] = $this->parseSELECT($parseString);
1061 // Seek to new position in parseString after parsing of the subquery
1062 $parseString = $stack[$level][$pnt[$level]]['func']['subquery']['parseString'];
1063 unset($stack[$level][$pnt[$level]]['func']['subquery']['parseString']);
1064 if (!$this->nextPart($parseString, '^([)])')) {
1065 return 'No ) parenthesis at end of subquery';
1066 }
1067 } else {
1068
1069 // See if LOCATE function is found
1070 if (preg_match('/^LOCATE[[:space:]]*[(]/i', $parseString)) {
1071 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(LOCATE)[[:space:]]*');
1072 $parseString = trim(substr($parseString, 1)); // Strip of "("
1073 $stack[$level][$pnt[$level]]['func']['substr'] = $this->getValue($parseString);
1074 if (!$this->nextPart($parseString, '^(,)')) {
1075 return $this->parseError('No comma found as expected in parseWhereClause()');
1076 }
1077 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)[[:space:]]*')) {
1078
1079 // Parse field name into field and table:
1080 $tableField = explode('.', $fieldName, 2);
1081 if (count($tableField) == 2) {
1082 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1083 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1084 } else {
1085 $stack[$level][$pnt[$level]]['func']['table'] = '';
1086 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1087 }
1088 } else {
1089 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1090 }
1091 if ($this->nextPart($parseString, '^(,)')) {
1092 $stack[$level][$pnt[$level]]['func']['pos'] = $this->getValue($parseString);
1093 }
1094 if (!$this->nextPart($parseString, '^([)])')) {
1095 return $this->parseError('No ) parenthesis at end of function');
1096 }
1097 } elseif (preg_match('/^IFNULL[[:space:]]*[(]/i', $parseString)) {
1098 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(IFNULL)[[:space:]]*');
1099 $parseString = trim(substr($parseString, 1)); // Strip of "("
1100 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)[[:space:]]*')) {
1101
1102 // Parse field name into field and table:
1103 $tableField = explode('.', $fieldName, 2);
1104 if (count($tableField) == 2) {
1105 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1106 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1107 } else {
1108 $stack[$level][$pnt[$level]]['func']['table'] = '';
1109 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1110 }
1111 } else {
1112 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1113 }
1114 if ($this->nextPart($parseString, '^(,)')) {
1115 $stack[$level][$pnt[$level]]['func']['default'] = $this->getValue($parseString);
1116 }
1117 if (!$this->nextPart($parseString, '^([)])')) {
1118 return $this->parseError('No ) parenthesis at end of function');
1119 }
1120 } else {
1121
1122 // Support calculated value only for:
1123 // - "&" (boolean AND)
1124 // - "+" (addition)
1125 // - "-" (substraction)
1126 // - "*" (multiplication)
1127 // - "/" (division)
1128 // - "%" (modulo)
1129 $calcOperators = '&|\+|-|\*|\/|%';
1130
1131 // Fieldname:
1132 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)([[:space:]]+|' . $calcOperators . '|<=|>=|<|>|=|!=|IS)')) !== '') {
1133
1134 // Parse field name into field and table:
1135 $tableField = explode('.', $fieldName, 2);
1136 if (count($tableField) == 2) {
1137 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
1138 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
1139 } else {
1140 $stack[$level][$pnt[$level]]['table'] = '';
1141 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
1142 }
1143 } else {
1144 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1145 }
1146
1147 // See if the value is calculated:
1148 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString, '^(' . $calcOperators . ')');
1149 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
1150 // Finding value for calculation:
1151 $calc_value = $this->getValue($parseString);
1152 $stack[$level][$pnt[$level]]['calc_value'] = $calc_value;
1153 if (count($calc_value) == 1 && is_string($calc_value[0])) {
1154 // Value is a field, store it to allow DBAL to post-process it (quoting, remapping)
1155 $tableField = explode('.', $calc_value[0], 2);
1156 if (count($tableField) == 2) {
1157 $stack[$level][$pnt[$level]]['calc_table'] = $tableField[0];
1158 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[1];
1159 } else {
1160 $stack[$level][$pnt[$level]]['calc_table'] = '';
1161 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[0];
1162 }
1163 }
1164 }
1165 }
1166
1167 // Find "comparator":
1168 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=|NOT[[:space:]]+IN|IN|NOT[[:space:]]+LIKE|LIKE|IS[[:space:]]+NOT|IS|BETWEEN|NOT[[:space]]+BETWEEN)');
1169 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
1170 if (preg_match('/^CONCAT[[:space:]]*\(/', $parseString)) {
1171 $this->nextPart($parseString, '^(CONCAT[[:space:]]?[(])');
1172 $values = array(
1173 'operator' => 'CONCAT',
1174 'args' => array(),
1175 );
1176 $cnt = 0;
1177 while ($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) {
1178 // Parse field name into field and table:
1179 $tableField = explode('.', $fieldName, 2);
1180 if (count($tableField) == 2) {
1181 $values['args'][$cnt]['table'] = $tableField[0];
1182 $values['args'][$cnt]['field'] = $tableField[1];
1183 } else {
1184 $values['args'][$cnt]['table'] = '';
1185 $values['args'][$cnt]['field'] = $tableField[0];
1186 }
1187 // Looking for comma:
1188 $this->nextPart($parseString, '^(,)');
1189 $cnt++;
1190 }
1191 // Look for ending parenthesis:
1192 $this->nextPart($parseString, '([)])');
1193 $stack[$level][$pnt[$level]]['value'] = $values;
1194 } else if (t3lib_div::inList('IN,NOT IN', $stack[$level][$pnt[$level]]['comparator']) && preg_match('/^[(][[:space:]]*SELECT[[:space:]]+/', $parseString)) {
1195 $this->nextPart($parseString, '^([(])');
1196 $stack[$level][$pnt[$level]]['subquery'] = $this->parseSELECT($parseString);
1197 // Seek to new position in parseString after parsing of the subquery
1198 $parseString = $stack[$level][$pnt[$level]]['subquery']['parseString'];
1199 unset($stack[$level][$pnt[$level]]['subquery']['parseString']);
1200 if (!$this->nextPart($parseString, '^([)])')) {
1201 return 'No ) parenthesis at end of subquery';
1202 }
1203 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $stack[$level][$pnt[$level]]['comparator'])) {
1204 $stack[$level][$pnt[$level]]['values'] = array();
1205 $stack[$level][$pnt[$level]]['values'][0] = $this->getValue($parseString);
1206 if (!$this->nextPart($parseString, '^(AND)')) {
1207 return $this->parseError('No AND operator found as expected in parseWhereClause()', $parseString);
1208 }
1209 $stack[$level][$pnt[$level]]['values'][1] = $this->getValue($parseString);
1210 } else {
1211 // Finding value for comparator:
1212 $stack[$level][$pnt[$level]]['value'] = $this->getValue($parseString, $stack[$level][$pnt[$level]]['comparator']);
1213 if ($this->parse_error) {
1214 return $this->parse_error;
1215 }
1216 }
1217 }
1218 }
1219
1220 // Finished, increase pointer:
1221 $pnt[$level]++;
1222
1223 // Checking if we are back to level 0 and we should still decrease level,
1224 // meaning we were probably parsing as subquery and should return here:
1225 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1226 // Return the stacks lowest level:
1227 return $stack[0];
1228 }
1229
1230 // Checking if we are back to level 0 and we should still decrease level,
1231 // meaning we were probably parsing a subquery and should return here:
1232 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1233 // Return the stacks lowest level:
1234 return $stack[0];
1235 }
1236
1237 // Checking if the current level is ended, in that case do stack management:
1238 while ($this->nextPart($parseString,'^([)])')) {
1239 $level--; // Decrease level:
1240 $stack[$level][$pnt[$level]]['sub'] = $stack[$level+1]; // Copy stack
1241 $pnt[$level]++; // Increase pointer of the new level
1242
1243 // Make recursivity check:
1244 $loopExit++;
1245 if ($loopExit > 500) {
1246 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely in parseWhereClause()...', $parseString);
1247 }
1248 }
1249
1250 // Detecting the operator for the next level:
1251 $op = $this->nextPart($parseString, '^(AND[[:space:]]+NOT|&&[[:space:]]+NOT|OR[[:space:]]+NOT|OR[[:space:]]+NOT|\|\|[[:space:]]+NOT|AND|&&|OR|\|\|)(\(|[[:space:]]+)');
1252 if ($op) {
1253 // Normalize boolean operator
1254 $op = str_replace(array('&&', '||'), array('AND', 'OR'), $op);
1255 $stack[$level][$pnt[$level]]['operator'] = $op;
1256 } elseif (strlen($parseString)) {
1257
1258 // Looking for stop-keywords:
1259 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
1260 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
1261 return $stack[0];
1262 } else {
1263 return $this->parseError('No operator, but parsing not finished in parseWhereClause().', $parseString);
1264 }
1265 }
1266 }
1267
1268 // Make recursivity check:
1269 $loopExit++;
1270 if ($loopExit > 500) {
1271 return $this->parseError('More than 500 loops, exiting prematurely in parseWhereClause()...', $parseString);
1272 }
1273 }
1274
1275 // Return the stacks lowest level:
1276 return $stack[0];
1277 }
1278
1279 /**
1280 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1281 * The success of this parsing determines if that part of the query is supported by TYPO3.
1282 *
1283 * @param string WHERE clause to parse. NOTICE: passed by reference!
1284 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1285 * @return mixed If successful parsing, returns an array, otherwise an error string.
1286 */
1287 public function parseFieldDef(&$parseString, $stopRegex = '') {
1288 // Prepare variables:
1289 $parseString = $this->trimSQL($parseString);
1290 $this->lastStopKeyWord = '';
1291 $this->parse_error = '';
1292
1293 $result = array();
1294
1295 // Field type:
1296 if ($result['fieldType'] = $this->nextPart($parseString,'^(int|smallint|tinyint|mediumint|bigint|double|numeric|decimal|float|varchar|char|text|tinytext|mediumtext|longtext|blob|tinyblob|mediumblob|longblob)([[:space:],]+|\()')) {
1297
1298 // Looking for value:
1299 if (substr($parseString,0,1)=='(') {
1300 $parseString = substr($parseString,1);
1301 if ($result['value'] = $this->nextPart($parseString,'^([^)]*)')) {
1302 $parseString = ltrim(substr($parseString,1));
1303 } else return $this->parseError('No end-parenthesis for value found in parseFieldDef()!',$parseString);
1304 }
1305
1306 // Looking for keywords
1307 while($keyword = $this->nextPart($parseString,'^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\))')) {
1308 $keywordCmp = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$keyword));
1309
1310 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
1311
1312 switch($keywordCmp) {
1313 case 'DEFAULT':
1314 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
1315 break;
1316 }
1317 }
1318 } else {
1319 return $this->parseError('Field type unknown in parseFieldDef()!',$parseString);
1320 }
1321
1322 return $result;
1323 }
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335 /************************************
1336 *
1337 * Parsing: Helper functions
1338 *
1339 ************************************/
1340
1341 /**
1342 * Strips off a part of the parseString and returns the matching part.
1343 * Helper function for the parsing methods.
1344 *
1345 * @param string Parse string; if $regex finds anything the value of the first () level will be stripped of the string in the beginning. Further $parseString is left-trimmed (on success). Notice; parsestring is passed by reference.
1346 * @param string Regex to find a matching part in the beginning of the string. Rules: You MUST start the regex with "^" (finding stuff in the beginning of string) and the result of the first parenthesis is what will be returned to you (and stripped of the string). Eg. '^(AND|OR|&&)[[:space:]]+' will return AND, OR or && if found and having one of more whitespaces after it, plus shorten $parseString with that match and any space after (by ltrim())
1347 * @param boolean If set the full match of the regex is stripped of the beginning of the string!
1348 * @return string The value of the first parenthesis level of the REGEX.
1349 */
1350 protected function nextPart(&$parseString, $regex, $trimAll = FALSE) {
1351 $reg = array();
1352 if (preg_match('/'.$regex.'/i',$parseString.' ', $reg)) { // Adding space char because [[:space:]]+ is often a requirement in regex's
1353 $parseString = ltrim(substr($parseString,strlen($reg[$trimAll?0:1])));
1354 return $reg[1];
1355 }
1356 // No match found
1357 return '';
1358 }
1359
1360 /**
1361 * Finds value in beginning of $parseString, returns result and strips it of parseString
1362 *
1363 * @param string The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ..."
1364 * @param string The comparator used before. If "NOT IN" or "IN" then the value is expected to be a list of values. Otherwise just an integer (un-quoted) or string (quoted)
1365 * @param string The mode, eg. "INDEX"
1366 * @return mixed The value (string/integer). Otherwise an array with error message in first key (0)
1367 */
1368 protected function getValue(&$parseString, $comparator = '', $mode = '') {
1369 $value = '';
1370
1371 if (t3lib_div::inList('NOTIN,IN,_LIST',strtoupper(str_replace(array(' ',LF,CR,TAB),'',$comparator)))) { // List of values:
1372 if ($this->nextPart($parseString,'^([(])')) {
1373 $listValues = array();
1374 $comma=',';
1375
1376 while($comma==',') {
1377 $listValues[] = $this->getValue($parseString);
1378 if ($mode === 'INDEX') {
1379 // Remove any length restriction on INDEX definition
1380 $this->nextPart($parseString, '^([(]\d+[)])');
1381 }
1382 $comma = $this->nextPart($parseString,'^([,])');
1383 }
1384
1385 $out = $this->nextPart($parseString,'^([)])');
1386 if ($out) {
1387 if ($comparator=='_LIST') {
1388 $kVals = array();
1389 foreach ($listValues as $vArr) {
1390 $kVals[] = $vArr[0];
1391 }
1392 return $kVals;
1393 } else {
1394 return $listValues;
1395 }
1396 } else return array($this->parseError('No ) parenthesis in list',$parseString));
1397 } else return array($this->parseError('No ( parenthesis starting the list',$parseString));
1398
1399 } else { // Just plain string value, in quotes or not:
1400
1401 // Quote?
1402 $firstChar = substr($parseString,0,1);
1403 switch($firstChar) {
1404 case '"':
1405 $value = array($this->getValueInQuotes($parseString,'"'),'"');
1406 break;
1407 case "'":
1408 $value = array($this->getValueInQuotes($parseString,"'"),"'");
1409 break;
1410 default:
1411 $reg = array();
1412 if (preg_match('/^([[:alnum:]._-]+)/i',$parseString, $reg)) {
1413 $parseString = ltrim(substr($parseString,strlen($reg[0])));
1414 $value = array($reg[1]);
1415 }
1416 break;
1417 }
1418 }
1419 return $value;
1420 }
1421
1422 /**
1423 * Get value in quotes from $parseString.
1424 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1425 *
1426 * @param string String from which to find value in quotes. Notice that $parseString is passed by reference and is shortend by the output of this function.
1427 * @param string The quote used; input either " or '
1428 * @return string The value, passed through stripslashes() !
1429 */
1430 protected function getValueInQuotes(&$parseString, $quote) {
1431
1432 $parts = explode($quote,substr($parseString,1));
1433 $buffer = '';
1434 foreach($parts as $k => $v) {
1435 $buffer.=$v;
1436
1437 $reg = array();
1438 preg_match('/\\\\$/', $v, $reg);
1439 if ($reg AND strlen($reg[0])%2) {
1440 $buffer.=$quote;
1441 } else {
1442 $parseString = ltrim(substr($parseString,strlen($buffer)+2));
1443 return $this->parseStripslashes($buffer);
1444 }
1445 }
1446 }
1447
1448 /**
1449 * Strip slashes function used for parsing
1450 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1451 *
1452 * @param string Input string
1453 * @return string Output string
1454 */
1455 protected function parseStripslashes($str) {
1456 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1457 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1458
1459 return str_replace($search, $replace, $str);
1460 }
1461
1462 /**
1463 * Add slashes function used for compiling queries
1464 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1465 *
1466 * @param string Input string
1467 * @return string Output string
1468 */
1469 protected function compileAddslashes($str) {
1470 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1471 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1472
1473 return str_replace($search, $replace, $str);
1474 }
1475
1476 /**
1477 * Setting the internal error message value, $this->parse_error and returns that value.
1478 *
1479 * @param string Input error message
1480 * @param string Remaining query to parse.
1481 * @return string Error message.
1482 */
1483 protected function parseError($msg, $restQuery) {
1484 $this->parse_error = 'SQL engine parse ERROR: '.$msg.': near "'.substr($restQuery,0,50).'"';
1485 return $this->parse_error;
1486 }
1487
1488 /**
1489 * Trimming SQL as preparation for parsing.
1490 * ";" in the end is stripped of.
1491 * White space is trimmed away around the value
1492 * A single space-char is added in the end
1493 *
1494 * @param string Input string
1495 * @return string Output string
1496 */
1497 protected function trimSQL($str) {
1498 return trim(rtrim($str, "; \r\n\t")).' ';
1499 }
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512 /*************************
1513 *
1514 * Compiling queries
1515 *
1516 *************************/
1517
1518 /**
1519 * Compiles an SQL query from components
1520 *
1521 * @param array Array of SQL query components
1522 * @return string SQL query
1523 * @see parseSQL()
1524 */
1525 public function compileSQL($components) {
1526 switch($components['type']) {
1527 case 'SELECT':
1528 $query = $this->compileSELECT($components);
1529 break;
1530 case 'UPDATE':
1531 $query = $this->compileUPDATE($components);
1532 break;
1533 case 'INSERT':
1534 $query = $this->compileINSERT($components);
1535 break;
1536 case 'DELETE':
1537 $query = $this->compileDELETE($components);
1538 break;
1539 case 'EXPLAIN':
1540 $query = 'EXPLAIN '.$this->compileSELECT($components);
1541 break;
1542 case 'DROPTABLE':
1543 $query = 'DROP TABLE'.($components['ifExists']?' IF EXISTS':'').' '.$components['TABLE'];
1544 break;
1545 case 'CREATETABLE':
1546 $query = $this->compileCREATETABLE($components);
1547 break;
1548 case 'ALTERTABLE':
1549 $query = $this->compileALTERTABLE($components);
1550 break;
1551 case 'TRUNCATETABLE':
1552 $query = $this->compileTRUNCATETABLE($components);
1553 break;
1554 }
1555
1556 return $query;
1557 }
1558
1559 /**
1560 * Compiles a SELECT statement from components array
1561 *
1562 * @param array Array of SQL query components
1563 * @return string SQL SELECT query
1564 * @see parseSELECT()
1565 */
1566 protected function compileSELECT($components) {
1567
1568 // Initialize:
1569 $where = $this->compileWhereClause($components['WHERE']);
1570 $groupBy = $this->compileFieldList($components['GROUPBY']);
1571 $orderBy = $this->compileFieldList($components['ORDERBY']);
1572 $limit = $components['LIMIT'];
1573
1574 // Make query:
1575 $query = 'SELECT '.($components['STRAIGHT_JOIN'] ? $components['STRAIGHT_JOIN'].'' : '').'
1576 '.$this->compileFieldList($components['SELECT']).'
1577 FROM '.$this->compileFromTables($components['FROM']).
1578 (strlen($where)?'
1579 WHERE '.$where : '').
1580 (strlen($groupBy)?'
1581 GROUP BY '.$groupBy : '').
1582 (strlen($orderBy)?'
1583 ORDER BY '.$orderBy : '').
1584 (strlen($limit)?'
1585 LIMIT '.$limit : '');
1586
1587 return $query;
1588 }
1589
1590 /**
1591 * Compiles an UPDATE statement from components array
1592 *
1593 * @param array Array of SQL query components
1594 * @return string SQL UPDATE query
1595 * @see parseUPDATE()
1596 */
1597 protected function compileUPDATE($components) {
1598
1599 // Where clause:
1600 $where = $this->compileWhereClause($components['WHERE']);
1601
1602 // Fields
1603 $fields = array();
1604 foreach($components['FIELDS'] as $fN => $fV) {
1605 $fields[]=$fN.'='.$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1606 }
1607
1608 // Make query:
1609 $query = 'UPDATE '.$components['TABLE'].' SET
1610 '.implode(',
1611 ',$fields).'
1612 '.(strlen($where)?'
1613 WHERE '.$where : '');
1614
1615 return $query;
1616 }
1617
1618 /**
1619 * Compiles an INSERT statement from components array
1620 *
1621 * @param array Array of SQL query components
1622 * @return string SQL INSERT query
1623 * @see parseINSERT()
1624 */
1625 protected function compileINSERT($components) {
1626 $values = array();
1627
1628 if (isset($components['VALUES_ONLY']) && is_array($components['VALUES_ONLY'])) {
1629 $valuesComponents = $components['EXTENDED'] === '1' ? $components['VALUES_ONLY'] : array($components['VALUES_ONLY']);
1630 $tableFields = array();
1631 } else {
1632 $valuesComponents = $components['EXTENDED'] === '1' ? $components['FIELDS'] : array($components['FIELDS']);
1633 $tableFields = array_keys($valuesComponents[0]);
1634 }
1635
1636 foreach ($valuesComponents as $valuesComponent) {
1637 $fields = array();
1638 foreach ($valuesComponent as $fV) {
1639 $fields[] = $fV[1] . $this->compileAddslashes($fV[0]) . $fV[1];
1640 }
1641 $values[] = '(' . implode(',
1642 ', $fields) . ')';
1643 }
1644
1645 // Make query:
1646 $query = 'INSERT INTO ' . $components['TABLE'];
1647 if (count($tableFields)) {
1648 $query .= '
1649 (' . implode(',
1650 ', $tableFields) . ')';
1651 }
1652 $query .= '
1653 VALUES
1654 ' . implode(',
1655 ', $values);
1656
1657 return $query;
1658 }
1659
1660 /**
1661 * Compiles an DELETE statement from components array
1662 *
1663 * @param array Array of SQL query components
1664 * @return string SQL DELETE query
1665 * @see parseDELETE()
1666 */
1667 protected function compileDELETE($components) {
1668
1669 // Where clause:
1670 $where = $this->compileWhereClause($components['WHERE']);
1671
1672 // Make query:
1673 $query = 'DELETE FROM '.$components['TABLE'].
1674 (strlen($where)?'
1675 WHERE '.$where : '');
1676
1677 return $query;
1678 }
1679
1680 /**
1681 * Compiles a CREATE TABLE statement from components array
1682 *
1683 * @param array Array of SQL query components
1684 * @return string SQL CREATE TABLE query
1685 * @see parseCREATETABLE()
1686 */
1687 protected function compileCREATETABLE($components) {
1688
1689 // Create fields and keys:
1690 $fieldsKeys = array();
1691 foreach($components['FIELDS'] as $fN => $fCfg) {
1692 $fieldsKeys[]=$fN.' '.$this->compileFieldCfg($fCfg['definition']);
1693 }
1694 foreach($components['KEYS'] as $kN => $kCfg) {
1695 if ($kN == 'PRIMARYKEY') {
1696 $fieldsKeys[]='PRIMARY KEY ('.implode(',', $kCfg).')';
1697 } elseif ($kN == 'UNIQUE') {
1698 $fieldsKeys[]='UNIQUE '.$kN.' ('.implode(',', $kCfg).')';
1699 } else {
1700 $fieldsKeys[]='KEY '.$kN.' ('.implode(',', $kCfg).')';
1701 }
1702 }
1703
1704 // Make query:
1705 $query = 'CREATE TABLE '.$components['TABLE'].' (
1706 '.implode(',
1707 ', $fieldsKeys).'
1708 )'.($components['tableType'] ? ' TYPE='.$components['tableType'] : '');
1709
1710 return $query;
1711 }
1712
1713 /**
1714 * Compiles an ALTER TABLE statement from components array
1715 *
1716 * @param array Array of SQL query components
1717 * @return string SQL ALTER TABLE query
1718 * @see parseALTERTABLE()
1719 */
1720 protected function compileALTERTABLE($components) {
1721
1722 // Make query:
1723 $query = 'ALTER TABLE '.$components['TABLE'].' '.$components['action'].' '.($components['FIELD']?$components['FIELD']:$components['KEY']);
1724
1725 // Based on action, add the final part:
1726 switch(strtoupper(str_replace(array(' ',TAB,CR,LF),'',$components['action']))) {
1727 case 'ADD':
1728 $query.=' '.$this->compileFieldCfg($components['definition']);
1729 break;
1730 case 'CHANGE':
1731 $query.=' '.$components['newField'].' '.$this->compileFieldCfg($components['definition']);
1732 break;
1733 case 'DROP':
1734 case 'DROPKEY':
1735 break;
1736 case 'ADDKEY':
1737 case 'ADDPRIMARYKEY':
1738 case 'ADDUNIQUE':
1739 $query.=' ('.implode(',',$components['fields']).')';
1740 break;
1741 case 'DEFAULTCHARACTERSET':
1742 $query .= $components['charset'];
1743 break;
1744 case 'ENGINE':
1745 $query .= '= ' . $components['engine'];
1746 break;
1747 }
1748
1749 // Return query
1750 return $query;
1751 }
1752
1753 /**
1754 * Compiles a TRUNCATE TABLE statement from components array
1755 *
1756 * @param array Array of SQL query components
1757 * @return string SQL TRUNCATE TABLE query
1758 * @see parseTRUNCATETABLE()
1759 */
1760 protected function compileTRUNCATETABLE(array $components) {
1761
1762 // Make query:
1763 $query = 'TRUNCATE TABLE ' . $components['TABLE'];
1764
1765 // Return query
1766 return $query;
1767 }
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782 /**************************************
1783 *
1784 * Compiling queries, helper functions for parts of queries
1785 *
1786 **************************************/
1787
1788 /**
1789 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1790 * Can also compile field lists for ORDER BY and GROUP BY.
1791 *
1792 * @param array Array of select fields, (made with ->parseFieldList())
1793 * @param boolean Whether comments should be compiled
1794 * @return string Select field string
1795 * @see parseFieldList()
1796 */
1797 public function compileFieldList($selectFields, $compileComments = TRUE) {
1798
1799 // Prepare buffer variable:
1800 $fields = '';
1801
1802 // Traverse the selectFields if any:
1803 if (is_array($selectFields)) {
1804 $outputParts = array();
1805 foreach($selectFields as $k => $v) {
1806
1807 // Detecting type:
1808 switch($v['type']) {
1809 case 'function':
1810 $outputParts[$k] = $v['function'].'('.$v['func_content'].')';
1811 break;
1812 case 'flow-control':
1813 if ($v['flow-control']['type'] === 'CASE') {
1814 $outputParts[$k] = $this->compileCaseStatement($v['flow-control']);
1815 }
1816 break;
1817 case 'field':
1818 $outputParts[$k] = ($v['distinct']?$v['distinct']:'').($v['table']?$v['table'].'.':'').$v['field'];
1819 break;
1820 }
1821
1822 // Alias:
1823 if ($v['as']) {
1824 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1825 }
1826
1827 // Specifically for ORDER BY and GROUP BY field lists:
1828 if ($v['sortDir']) {
1829 $outputParts[$k].= ' '.$v['sortDir'];
1830 }
1831 }
1832 if ($compileComments && $selectFields[0]['comments']) {
1833 $fields = $selectFields[0]['comments'] . ' ';
1834 }
1835 $fields .= implode(', ', $outputParts);
1836 }
1837
1838 return $fields;
1839 }
1840
1841 /**
1842 * Compiles a CASE ... WHEN flow-control construct based on input array (made with ->parseCaseStatement())
1843 *
1844 * @param array Array of case components, (made with ->parseCaseStatement())
1845 * @return string case when string
1846 * @see parseCaseStatement()
1847 */
1848 protected function compileCaseStatement(array $components) {
1849 $statement = 'CASE';
1850 if (isset($components['case_field'])) {
1851 $statement .= ' ' . $components['case_field'];
1852 } elseif (isset($components['case_value'])) {
1853 $statement .= ' ' . $components['case_value'][1] . $components['case_value'][0] . $components['case_value'][1];
1854 }
1855 foreach ($components['when'] as $when) {
1856 $statement .= ' WHEN ';
1857 $statement .= $this->compileWhereClause($when['when_value']);
1858 $statement .= ' THEN ';
1859 $statement .= $when['then_value'][1] . $when['then_value'][0] . $when['then_value'][1];
1860 }
1861 if (isset($components['else'])) {
1862 $statement .= ' ELSE ';
1863 $statement .= $components['else'][1] . $components['else'][0] . $components['else'][1];
1864 }
1865 $statement .= ' END';
1866 return $statement;
1867 }
1868
1869 /**
1870 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1871 *
1872 * @param array Array of table names, (made with ->parseFromTables())
1873 * @return string Table name string
1874 * @see parseFromTables()
1875 */
1876 public function compileFromTables($tablesArray) {
1877
1878 // Prepare buffer variable:
1879 $outputParts = array();
1880
1881 // Traverse the table names:
1882 if (is_array($tablesArray)) {
1883 foreach ($tablesArray as $k => $v) {
1884
1885 // Set table name:
1886 $outputParts[$k] = $v['table'];
1887
1888 // Add alias AS if there:
1889 if ($v['as']) {
1890 $outputParts[$k] .= ' ' . $v['as_keyword'] . ' ' . $v['as'];
1891 }
1892
1893 if (is_array($v['JOIN'])) {
1894 foreach ($v['JOIN'] as $join) {
1895 $outputParts[$k] .= ' ' . $join['type'] . ' ' . $join['withTable'];
1896 // Add alias AS if there:
1897 if (isset($join['as']) && $join['as']) {
1898 $outputParts[$k] .= ' ' . $join['as_keyword'] . ' ' . $join['as'];
1899 }
1900 $outputParts[$k] .= ' ON ';
1901 foreach ($join['ON'] as $condition) {
1902 if ($condition['operator'] !== '') {
1903 $outputParts[$k] .= ' ' . $condition['operator'] . ' ';
1904 }
1905 $outputParts[$k] .= ($condition['left']['table']) ? $condition['left']['table'] . '.' : '';
1906 $outputParts[$k] .= $condition['left']['field'];
1907 $outputParts[$k] .= $condition['comparator'];
1908 $outputParts[$k] .= ($condition['right']['table']) ? $condition['right']['table'] . '.' : '';
1909 $outputParts[$k] .= $condition['right']['field'];
1910 }
1911 }
1912 }
1913 }
1914 }
1915
1916 // Return imploded buffer:
1917 return implode(', ', $outputParts);
1918 }
1919
1920 /**
1921 * Implodes an array of WHERE clause configuration into a WHERE clause.
1922 *
1923 * @param array WHERE clause configuration
1924 * @return string WHERE clause as string.
1925 * @see explodeWhereClause()
1926 */
1927 public function compileWhereClause($clauseArray) {
1928
1929 // Prepare buffer variable:
1930 $output = '';
1931
1932 // Traverse clause array:
1933 if (is_array($clauseArray)) {
1934 foreach ($clauseArray as $k => $v) {
1935
1936 // Set operator:
1937 $output .= $v['operator'] ? ' ' . $v['operator'] : '';
1938
1939 // Look for sublevel:
1940 if (is_array($v['sub'])) {
1941 $output .= ' (' . trim($this->compileWhereClause($v['sub'])) . ')';
1942 } elseif (isset($v['func']) && $v['func']['type'] === 'EXISTS') {
1943 $output .= ' ' . trim($v['modifier']) . ' EXISTS (' . $this->compileSELECT($v['func']['subquery']) . ')';
1944 } else {
1945
1946 if (isset($v['func']) && $v['func']['type'] === 'LOCATE') {
1947 $output .= ' ' . trim($v['modifier']) . ' LOCATE(';
1948 $output .= $v['func']['substr'][1] . $v['func']['substr'][0] . $v['func']['substr'][1];
1949 $output .= ', ' . ($v['func']['table'] ? $v['func']['table'] . '.' : '') . $v['func']['field'];
1950 $output .= isset($v['func']['pos']) ? ', ' . $v['func']['pos'][0] : '';
1951 $output .= ')';
1952 } elseif (isset($v['func']) && $v['func']['type'] === 'IFNULL') {
1953 $output = ' ' . trim($v['modifier']) . ' IFNULL(';
1954 $output .= ($v['func']['table'] ? $v['func']['table'] . '.' : '') . $v['func']['field'];
1955 $output .= ', ' . $v['func']['default'][1] . $this->compileAddslashes($v['func']['default'][0]) . $v['func']['default'][1];
1956 $output .= ')';
1957 } else {
1958
1959 // Set field/table with modifying prefix if any:
1960 $output .= ' ' . trim($v['modifier'] . ' ' . ($v['table'] ? $v['table'] . '.' : '') . $v['field']);
1961
1962 // Set calculation, if any:
1963 if ($v['calc']) {
1964 $output .= $v['calc'] . $v['calc_value'][1] . $this->compileAddslashes($v['calc_value'][0]) . $v['calc_value'][1];
1965 }
1966 }
1967
1968 // Set comparator:
1969 if ($v['comparator']) {
1970 $output .= ' ' . $v['comparator'];
1971
1972 // Detecting value type; list or plain:
1973 if (t3lib_div::inList('NOTIN,IN', strtoupper(str_replace(array(' ', TAB, CR, LF), '', $v['comparator'])))) {
1974 if (isset($v['subquery'])) {
1975 $output .= ' (' . $this->compileSELECT($v['subquery']) . ')';
1976 } else {
1977 $valueBuffer = array();
1978 foreach ($v['value'] as $realValue) {
1979 $valueBuffer[] = $realValue[1] . $this->compileAddslashes($realValue[0]) . $realValue[1];
1980 }
1981 $output .= ' (' . trim(implode(',', $valueBuffer)) . ')';
1982 }
1983 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $v['comparator'])) {
1984 $lbound = $v['values'][0];
1985 $ubound = $v['values'][1];
1986 $output .= ' ' . $lbound[1] . $this->compileAddslashes($lbound[0]) . $lbound[1];
1987 $output .= ' AND ';
1988 $output .= $ubound[1] . $this->compileAddslashes($ubound[0]) . $ubound[1];
1989 } else if (isset($v['value']['operator'])) {
1990 $values = array();
1991 foreach ($v['value']['args'] as $fieldDef) {
1992 $values[] = ($fieldDef['table'] ? $fieldDef['table'] . '.' : '') . $fieldDef['field'];
1993 }
1994 $output .= ' ' . $v['value']['operator'] . '(' . implode(',', $values) . ')';
1995 } else {
1996 $output .= ' ' . $v['value'][1] . $this->compileAddslashes($v['value'][0]) . $v['value'][1];
1997 }
1998 }
1999 }
2000 }
2001 }
2002
2003 // Return output buffer:
2004 return $output;
2005 }
2006
2007 /**
2008 * Compile field definition
2009 *
2010 * @param array Field definition parts
2011 * @return string Field definition string
2012 */
2013 public function compileFieldCfg($fieldCfg) {
2014
2015 // Set type:
2016 $cfg = $fieldCfg['fieldType'];
2017
2018 // Add value, if any:
2019 if (strlen($fieldCfg['value'])) {
2020 $cfg.='('.$fieldCfg['value'].')';
2021 }
2022
2023 // Add additional features:
2024 if (is_array($fieldCfg['featureIndex'])) {
2025 foreach($fieldCfg['featureIndex'] as $featureDef) {
2026 $cfg.=' '.$featureDef['keyword'];
2027
2028 // Add value if found:
2029 if (is_array($featureDef['value'])) {
2030 $cfg.=' '.$featureDef['value'][1].$this->compileAddslashes($featureDef['value'][0]).$featureDef['value'][1];
2031 }
2032 }
2033 }
2034
2035 // Return field definition string:
2036 return $cfg;
2037 }
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049 /*************************
2050 *
2051 * Debugging
2052 *
2053 *************************/
2054
2055 /**
2056 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
2057 *
2058 * @param string Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
2059 * @param string SQL string to verify parsability of
2060 * @return mixed Returns array with string 1 and 2 if error, otherwise false
2061 */
2062 public function debug_parseSQLpart($part, $str) {
2063 $retVal = false;
2064
2065 switch($part) {
2066 case 'SELECT':
2067 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFieldList($this->parseFieldList($str)));
2068 break;
2069 case 'FROM':
2070 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFromTables($this->parseFromTables($str)));
2071 break;
2072 case 'WHERE':
2073 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileWhereClause($this->parseWhereClause($str)));
2074 break;
2075 }
2076 return $retVal;
2077 }
2078
2079 /**
2080 * Compare two query strins by stripping away whitespace.
2081 *
2082 * @param string SQL String 1
2083 * @param string SQL string 2
2084 * @param boolean If true, the strings are compared insensitive to case
2085 * @return mixed Returns array with string 1 and 2 if error, otherwise false
2086 */
2087 public function debug_parseSQLpartCompare($str, $newStr, $caseInsensitive = FALSE) {
2088 if ($caseInsensitive) {
2089 $str1 = strtoupper($str);
2090 $str2 = strtoupper($newStr);
2091 } else {
2092 $str1 = $str;
2093 $str2 = $newStr;
2094 }
2095
2096 // Fixing escaped chars:
2097 $search = array('\0', '\n', '\r', '\Z');
2098 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
2099 $str1 = str_replace($search, $replace, $str1);
2100 $str2 = str_replace($search, $replace, $str2);
2101
2102 # Normally, commented out since they are needed only in tricky cases...
2103 # $str1 = stripslashes($str1);
2104 # $str2 = stripslashes($str2);
2105
2106 if (strcmp(str_replace(array(' ',TAB,CR,LF),'',$this->trimSQL($str1)),str_replace(array(' ',TAB,CR,LF),'',$this->trimSQL($str2)))) {
2107 return array(
2108 str_replace(array(' ',TAB,CR,LF),' ',$str),
2109 str_replace(array(' ',TAB,CR,LF),' ',$newStr),
2110 );
2111 }
2112 }
2113
2114 /**
2115 * Performs the ultimate test of the parser: Direct a SQL query in; You will get it back (through the parsed and re-compiled) if no problems, otherwise the script will print the error and exit
2116 *
2117 * @param string SQL query
2118 * @return string Query if all is well, otherwise exit.
2119 */
2120 public function debug_testSQL($SQLquery) {
2121
2122 // Getting result array:
2123 $parseResult = $this->parseSQL($SQLquery);
2124
2125 // If result array was returned, proceed. Otherwise show error and exit.
2126 if (is_array($parseResult)) {
2127
2128 // Re-compile query:
2129 $newQuery = $this->compileSQL($parseResult);
2130
2131 // TEST the new query:
2132 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
2133
2134 // Return new query if OK, otherwise show error and exit:
2135 if (!is_array($testResult)) {
2136 return $newQuery;
2137 } else {
2138 debug(array('ERROR MESSAGE'=>'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult),'SQL parsing failed:');
2139 exit;
2140 }
2141 } else {
2142 debug(array('query' => $SQLquery, 'ERROR MESSAGE'=>$parseResult),'SQL parsing failed:');
2143 exit;
2144 }
2145 }
2146 }
2147
2148
2149 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']) {
2150 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']);
2151 }
2152
2153 ?>