Fixed bug #2186: Error installing static_info_tables
[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 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
557
558 if ($result['TABLE']) {
559 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)([[:space:]]+|\()')) {
560 $actionKey = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$result['action']));
561
562 // Getting field:
563 if (t3lib_div::inList('ADDPRIMARYKEY,DROPPRIMARYKEY',$actionKey) || $fieldKey = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
564
565 switch($actionKey) {
566 case 'ADD':
567 $result['FIELD'] = $fieldKey;
568 $result['definition'] = $this->parseFieldDef($parseString);
569 if ($this->parse_error) { return $this->parse_error; }
570 break;
571 case 'DROP':
572 case 'RENAME':
573 $result['FIELD'] = $fieldKey;
574 break;
575 case 'CHANGE':
576 $result['FIELD'] = $fieldKey;
577 if ($result['newField'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
578 $result['definition'] = $this->parseFieldDef($parseString);
579 if ($this->parse_error) { return $this->parse_error; }
580 } else return $this->parseError('No NEW field name found',$parseString);
581 break;
582
583 case 'ADDKEY':
584 case 'ADDPRIMARYKEY':
585 case 'ADDUNIQUE':
586 $result['KEY'] = $fieldKey;
587 $result['fields'] = $this->getValue($parseString, '_LIST', 'INDEX');
588 if ($this->parse_error) { return $this->parse_error; }
589 break;
590 case 'DROPKEY':
591 $result['KEY'] = $fieldKey;
592 break;
593 case 'DROPPRIMARYKEY':
594 // ??? todo!
595 break;
596 }
597 } else return $this->parseError('No field name found',$parseString);
598 } else return $this->parseError('No action CHANGE, DROP or ADD found!',$parseString);
599 } else return $this->parseError('No table found!',$parseString);
600
601 // Should be no more content now:
602 if ($parseString) {
603 return $this->parseError('Still content in clause after parsing!',$parseString);
604 }
605
606 return $result;
607 }
608
609 /**
610 * Parsing DROP TABLE query
611 *
612 * @param string SQL string starting with DROP TABLE
613 * @return mixed Returns array with components of DROP TABLE query on success, otherwise an error message string.
614 */
615 protected function parseDROPTABLE($parseString) {
616
617 // Removing DROP TABLE
618 $parseString = $this->trimSQL($parseString);
619 $parseString = ltrim(substr(ltrim(substr($parseString,4)),5));
620
621 // Init output variable:
622 $result = array();
623 $result['type'] = 'DROPTABLE';
624
625 // IF EXISTS
626 $result['ifExists'] = $this->nextPart($parseString, '^(IF[[:space:]]+EXISTS[[:space:]]+)');
627
628 // Get table:
629 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
630
631 if ($result['TABLE']) {
632
633 // Should be no more content now:
634 if ($parseString) {
635 return $this->parseError('Still content in clause after parsing!',$parseString);
636 }
637
638 return $result;
639 } else return $this->parseError('No table found!',$parseString);
640 }
641
642 /**
643 * Parsing CREATE DATABASE query
644 *
645 * @param string SQL string starting with CREATE DATABASE
646 * @return mixed Returns array with components of CREATE DATABASE query on success, otherwise an error message string.
647 */
648 protected function parseCREATEDATABASE($parseString) {
649
650 // Removing CREATE DATABASE
651 $parseString = $this->trimSQL($parseString);
652 $parseString = ltrim(substr(ltrim(substr($parseString,6)),8));
653
654 // Init output variable:
655 $result = array();
656 $result['type'] = 'CREATEDATABASE';
657
658 // Get table:
659 $result['DATABASE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
660
661 if ($result['DATABASE']) {
662
663 // Should be no more content now:
664 if ($parseString) {
665 return $this->parseError('Still content in clause after parsing!',$parseString);
666 }
667
668 return $result;
669 } else return $this->parseError('No database found!',$parseString);
670 }
671
672 /**
673 * Parsing TRUNCATE TABLE query
674 *
675 * @param string SQL string starting with TRUNCATE TABLE
676 * @return mixed Returns array with components of TRUNCATE TABLE query on success, otherwise an error message string.
677 */
678 protected function parseTRUNCATETABLE($parseString) {
679
680 // Removing TRUNCATE TABLE
681 $parseString = $this->trimSQL($parseString);
682 $parseString = ltrim(substr(ltrim(substr($parseString, 8)), 5));
683
684 // Init output variable:
685 $result = array();
686 $result['type'] = 'TRUNCATETABLE';
687
688 // Get table:
689 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
690
691 if ($result['TABLE']) {
692
693 // Should be no more content now:
694 if ($parseString) {
695 return $this->parseError('Still content in clause after parsing!', $parseString);
696 }
697
698 return $result;
699 } else {
700 return $this->parseError('No table found!', $parseString);
701 }
702 }
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718 /**************************************
719 *
720 * SQL Parsing, helper functions for parts of queries
721 *
722 **************************************/
723
724 /**
725 * Parsing the fields in the "SELECT [$selectFields] FROM" part of a query into an array.
726 * The output from this function can be compiled back into a field list with ->compileFieldList()
727 * 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!
728 *
729 * @param string The string with fieldnames, eg. "title, uid AS myUid, max(tstamp), count(*)" etc. NOTICE: passed by reference!
730 * @param string Regular expressing to STOP parsing, eg. '^(FROM)([[:space:]]*)'
731 * @return array If successful parsing, returns an array, otherwise an error string.
732 * @see compileFieldList()
733 */
734 public function parseFieldList(&$parseString, $stopRegex = '') {
735
736 $stack = array(); // Contains the parsed content
737
738 if(strlen($parseString)==0) return $stack; // FIXME - should never happen, why does it?
739
740 $pnt = 0; // Pointer to positions in $stack
741 $level = 0; // Indicates the parenthesis level we are at.
742 $loopExit = 0; // Recursivity brake.
743
744 // Prepare variables:
745 $parseString = $this->trimSQL($parseString);
746 $this->lastStopKeyWord = '';
747 $this->parse_error = '';
748
749 // Parse any SQL hint / comments
750 $stack[$pnt]['comments'] = $this->nextPart($parseString, '^(\/\*.*\*\/)');
751
752 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
753 while (strlen($parseString)) {
754
755 // Checking if we are inside / outside parenthesis (in case of a function like count(), max(), min() etc...):
756 if ($level>0) { // Inside parenthesis here (does NOT detect if values in quotes are used, the only token is ")" or "("):
757
758 // Accumulate function content until next () parenthesis:
759 $funcContent = $this->nextPart($parseString,'^([^()]*.)');
760 $stack[$pnt]['func_content.'][] = array(
761 'level' => $level,
762 'func_content' => substr($funcContent,0,-1)
763 );
764 $stack[$pnt]['func_content'].= $funcContent;
765
766 // Detecting ( or )
767 switch(substr($stack[$pnt]['func_content'],-1)) {
768 case '(':
769 $level++;
770 break;
771 case ')':
772 $level--;
773 if (!$level) { // If this was the last parenthesis:
774 $stack[$pnt]['func_content'] = substr($stack[$pnt]['func_content'],0,-1);
775 $parseString = ltrim($parseString); // Remove any whitespace after the parenthesis.
776 }
777 break;
778 }
779 } else { // Outside parenthesis, looking for next field:
780
781 // Looking for a flow-control construct (only known constructs supported)
782 if (preg_match('/^case([[:space:]][[:alnum:]\*._]+)?[[:space:]]when/i', $parseString)) {
783 $stack[$pnt]['type'] = 'flow-control';
784 $stack[$pnt]['flow-control'] = $this->parseCaseStatement($parseString);
785 // Looking for "AS" alias:
786 if ($as = $this->nextPart($parseString, '^(AS)[[:space:]]+')) {
787 $stack[$pnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)(,|[[:space:]]+)');
788 $stack[$pnt]['as_keyword'] = $as;
789 }
790 } else {
791 // Looking for a known function (only known functions supported)
792 $func = $this->nextPart($parseString,'^(count|max|min|floor|sum|avg)[[:space:]]*\(');
793 if ($func) {
794 $parseString = trim(substr($parseString,1)); // Strip of "("
795 $stack[$pnt]['type'] = 'function';
796 $stack[$pnt]['function'] = $func;
797 $level++; // increse parenthesis level counter.
798 } else {
799 $stack[$pnt]['distinct'] = $this->nextPart($parseString,'^(distinct[[:space:]]+)');
800 // Otherwise, look for regular fieldname:
801 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)(,|[[:space:]]+)')) !== '') {
802 $stack[$pnt]['type'] = 'field';
803
804 // Explode fieldname into field and table:
805 $tableField = explode('.',$fieldName,2);
806 if (count($tableField)==2) {
807 $stack[$pnt]['table'] = $tableField[0];
808 $stack[$pnt]['field'] = $tableField[1];
809 } else {
810 $stack[$pnt]['table'] = '';
811 $stack[$pnt]['field'] = $tableField[0];
812 }
813 } else {
814 return $this->parseError('No field name found as expected in parseFieldList()',$parseString);
815 }
816 }
817 }
818 }
819
820 // After a function or field we look for "AS" alias and a comma to separate to the next field in the list:
821 if (!$level) {
822
823 // Looking for "AS" alias:
824 if ($as = $this->nextPart($parseString,'^(AS)[[:space:]]+')) {
825 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)');
826 $stack[$pnt]['as_keyword'] = $as;
827 }
828
829 // Looking for "ASC" or "DESC" keywords (for ORDER BY)
830 if ($sDir = $this->nextPart($parseString,'^(ASC|DESC)([[:space:]]+|,)')) {
831 $stack[$pnt]['sortDir'] = $sDir;
832 }
833
834 // Looking for stop-keywords:
835 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
836 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$this->lastStopKeyWord));
837 return $stack;
838 }
839
840 // Looking for comma (since the stop-keyword did not trigger a return...)
841 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
842 return $this->parseError('No comma found as expected in parseFieldList()',$parseString);
843 }
844
845 // Increasing pointer:
846 $pnt++;
847 }
848
849 // Check recursivity brake:
850 $loopExit++;
851 if ($loopExit>500) {
852 return $this->parseError('More than 500 loops, exiting prematurely in parseFieldList()...',$parseString);
853 }
854 }
855
856 // Return result array:
857 return $stack;
858 }
859
860 /**
861 * Parsing a CASE ... WHEN flow-control construct.
862 * The output from this function can be compiled back with ->compileCaseStatement()
863 *
864 * @param string The string with the CASE ... WHEN construct, eg. "CASE field WHEN 1 THEN 0 ELSE ..." etc. NOTICE: passed by reference!
865 * @return array If successful parsing, returns an array, otherwise an error string.
866 * @see compileCaseConstruct()
867 */
868 protected function parseCaseStatement(&$parseString) {
869 $result = array();
870 $result['type'] = $this->nextPart($parseString, '^(case)[[:space:]]+');
871 if (!preg_match('/^when[[:space:]]+/i', $parseString)) {
872 $value = $this->getValue($parseString);
873 if (!(isset($value[1]) || is_numeric($value[0]))) {
874 $result['case_field'] = $value[0];
875 } else {
876 $result['case_value'] = $value;
877 }
878 }
879 $result['when'] = array();
880 while ($this->nextPart($parseString, '^(when)[[:space:]]')) {
881 $when = array();
882 $when['when_value'] = $this->parseWhereClause($parseString, '^(then)[[:space:]]+');
883 $when['then_value'] = $this->getValue($parseString);
884 $result['when'][] = $when;
885 }
886 if ($this->nextPart($parseString, '^(else)[[:space:]]+')) {
887 $result['else'] = $this->getValue($parseString);
888 }
889 if (!$this->nextPart($parseString, '^(end)[[:space:]]+')) {
890 return $this->parseError('No "end" keyword found as expected in parseCaseStatement()', $parseString);
891 }
892 return $result;
893 }
894
895 /**
896 * Parsing the tablenames in the "FROM [$parseString] WHERE" part of a query into an array.
897 * The success of this parsing determines if that part of the query is supported by TYPO3.
898 *
899 * @param string list of tables, eg. "pages, tt_content" or "pages A, pages B". NOTICE: passed by reference!
900 * @param string Regular expressing to STOP parsing, eg. '^(WHERE)([[:space:]]*)'
901 * @return array If successful parsing, returns an array, otherwise an error string.
902 * @see compileFromTables()
903 */
904 public function parseFromTables(&$parseString, $stopRegex = '') {
905
906 // Prepare variables:
907 $parseString = $this->trimSQL($parseString);
908 $this->lastStopKeyWord = '';
909 $this->parse_error = '';
910
911 $stack = array(); // Contains the parsed content
912 $pnt = 0; // Pointer to positions in $stack
913 $loopExit = 0; // Recursivity brake.
914
915 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
916 while (strlen($parseString)) {
917 // Looking for the table:
918 if ($stack[$pnt]['table'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)')) {
919 // Looking for stop-keywords before fetching potential table alias:
920 if ($stopRegex && ($this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex))) {
921 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
922 return $stack;
923 }
924 if (!preg_match('/^(LEFT|RIGHT|JOIN|INNER)[[:space:]]+/i', $parseString)) {
925 $stack[$pnt]['as_keyword'] = $this->nextPart($parseString,'^(AS[[:space:]]+)');
926 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*');
927 }
928 } else return $this->parseError('No table name found as expected in parseFromTables()!', $parseString);
929
930 // Looking for JOIN
931 $joinCnt = 0;
932 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:]]+')) {
933 $stack[$pnt]['JOIN'][$joinCnt]['type'] = $join;
934 if ($stack[$pnt]['JOIN'][$joinCnt]['withTable'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+', 1)) {
935 if (!preg_match('/^ON[[:space:]]+/i', $parseString)) {
936 $stack[$pnt]['JOIN'][$joinCnt]['as_keyword'] = $this->nextPart($parseString, '^(AS[[:space:]]+)');
937 $stack[$pnt]['JOIN'][$joinCnt]['as'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
938 }
939 if (!$this->nextPart($parseString, '^(ON[[:space:]]+)')) {
940 return $this->parseError('No join condition found in parseFromTables()!', $parseString);
941 }
942 $stack[$pnt]['JOIN'][$joinCnt]['ON'] = array();
943 $condition = array('operator' => '');
944 $parseCondition = TRUE;
945 while ($parseCondition) {
946 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)[[:space:]]*(<=|>=|<|>|=|!=)')) !== '') {
947 // Parse field name into field and table:
948 $tableField = explode('.', $fieldName, 2);
949 $condition['left'] = array();
950 if (count($tableField) == 2) {
951 $condition['left']['table'] = $tableField[0];
952 $condition['left']['field'] = $tableField[1];
953 } else {
954 $condition['left']['table'] = '';
955 $condition['left']['field'] = $tableField[0];
956 }
957 } else {
958 return $this->parseError('No join field found in parseFromTables()!', $parseString);
959 }
960 // Find "comparator":
961 $condition['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=)');
962 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) !== '') {
963 // Parse field name into field and table:
964 $tableField = explode('.', $fieldName, 2);
965 $condition['right'] = array();
966 if (count($tableField) == 2) {
967 $condition['right']['table'] = $tableField[0];
968 $condition['right']['field'] = $tableField[1];
969 } else {
970 $condition['right']['table'] = '';
971 $condition['right']['field'] = $tableField[0];
972 }
973 } else {
974 return $this->parseError('No join field found in parseFromTables()!', $parseString);
975 }
976 $stack[$pnt]['JOIN'][$joinCnt]['ON'][] = $condition;
977 if (($operator = $this->nextPart($parseString, '^(AND|OR)')) !== '') {
978 $condition = array('operator' => $operator);
979 } else {
980 $parseCondition = FALSE;
981 }
982 }
983 $joinCnt++;
984 } else return $this->parseError('No join table found in parseFromTables()!', $parseString);
985 }
986
987 // Looking for stop-keywords:
988 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
989 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
990 return $stack;
991 }
992
993 // Looking for comma:
994 if (strlen($parseString) && !$this->nextPart($parseString, '^(,)')) {
995 return $this->parseError('No comma found as expected in parseFromTables()', $parseString);
996 }
997
998 // Increasing pointer:
999 $pnt++;
1000
1001 // Check recursivity brake:
1002 $loopExit++;
1003 if ($loopExit > 500) {
1004 return $this->parseError('More than 500 loops, exiting prematurely in parseFromTables()...', $parseString);
1005 }
1006 }
1007
1008 // Return result array:
1009 return $stack;
1010 }
1011
1012 /**
1013 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1014 * The success of this parsing determines if that part of the query is supported by TYPO3.
1015 *
1016 * @param string WHERE clause to parse. NOTICE: passed by reference!
1017 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1018 * @return mixed If successful parsing, returns an array, otherwise an error string.
1019 */
1020 public function parseWhereClause(&$parseString, $stopRegex = '') {
1021
1022 // Prepare variables:
1023 $parseString = $this->trimSQL($parseString);
1024 $this->lastStopKeyWord = '';
1025 $this->parse_error = '';
1026
1027 $stack = array(0 => array()); // Contains the parsed content
1028 $pnt = array(0 => 0); // Pointer to positions in $stack
1029 $level = 0; // Determines parenthesis level
1030 $loopExit = 0; // Recursivity brake.
1031
1032 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
1033 while (strlen($parseString)) {
1034
1035 // Look for next parenthesis level:
1036 $newLevel = $this->nextPart($parseString,'^([(])');
1037 if ($newLevel == '(') { // If new level is started, manage stack/pointers:
1038 $level++; // Increase level
1039 $pnt[$level] = 0; // Reset pointer for this level
1040 $stack[$level] = array(); // Reset stack for this level
1041 } else { // If no new level is started, just parse the current level:
1042
1043 // Find "modifier", eg. "NOT or !"
1044 $stack[$level][$pnt[$level]]['modifier'] = trim($this->nextPart($parseString, '^(!|NOT[[:space:]]+)'));
1045
1046 // See if condition is EXISTS with a subquery
1047 if (preg_match('/^EXISTS[[:space:]]*[(]/i', $parseString)) {
1048 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(EXISTS)[[:space:]]*');
1049 $parseString = trim(substr($parseString, 1)); // Strip of "("
1050 $stack[$level][$pnt[$level]]['func']['subquery'] = $this->parseSELECT($parseString);
1051 // Seek to new position in parseString after parsing of the subquery
1052 $parseString = $stack[$level][$pnt[$level]]['func']['subquery']['parseString'];
1053 unset($stack[$level][$pnt[$level]]['func']['subquery']['parseString']);
1054 if (!$this->nextPart($parseString, '^([)])')) {
1055 return 'No ) parenthesis at end of subquery';
1056 }
1057 } else {
1058
1059 // See if LOCATE function is found
1060 if (preg_match('/^LOCATE[[:space:]]*[(]/i', $parseString)) {
1061 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(LOCATE)[[:space:]]*');
1062 $parseString = trim(substr($parseString, 1)); // Strip of "("
1063 $stack[$level][$pnt[$level]]['func']['substr'] = $this->getValue($parseString);
1064 if (!$this->nextPart($parseString, '^(,)')) {
1065 return $this->parseError('No comma found as expected in parseWhereClause()');
1066 }
1067 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)[[:space:]]*')) {
1068
1069 // Parse field name into field and table:
1070 $tableField = explode('.', $fieldName, 2);
1071 if (count($tableField) == 2) {
1072 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1073 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1074 } else {
1075 $stack[$level][$pnt[$level]]['func']['table'] = '';
1076 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1077 }
1078 } else {
1079 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1080 }
1081 if ($this->nextPart($parseString, '^(,)')) {
1082 $stack[$level][$pnt[$level]]['func']['pos'] = $this->getValue($parseString);
1083 }
1084 if (!$this->nextPart($parseString, '^([)])')) {
1085 return $this->parseError('No ) parenthesis at end of function');
1086 }
1087 } elseif (preg_match('/^IFNULL[[:space:]]*[(]/i', $parseString)) {
1088 $stack[$level][$pnt[$level]]['func']['type'] = $this->nextPart($parseString, '^(IFNULL)[[:space:]]*');
1089 $parseString = trim(substr($parseString, 1)); // Strip of "("
1090 if ($fieldName = $this->nextPart($parseString, '^([[:alnum:]\*._]+)[[:space:]]*')) {
1091
1092 // Parse field name into field and table:
1093 $tableField = explode('.', $fieldName, 2);
1094 if (count($tableField) == 2) {
1095 $stack[$level][$pnt[$level]]['func']['table'] = $tableField[0];
1096 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[1];
1097 } else {
1098 $stack[$level][$pnt[$level]]['func']['table'] = '';
1099 $stack[$level][$pnt[$level]]['func']['field'] = $tableField[0];
1100 }
1101 } else {
1102 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1103 }
1104 if ($this->nextPart($parseString, '^(,)')) {
1105 $stack[$level][$pnt[$level]]['func']['default'] = $this->getValue($parseString);
1106 }
1107 if (!$this->nextPart($parseString, '^([)])')) {
1108 return $this->parseError('No ) parenthesis at end of function');
1109 }
1110 } else {
1111
1112 // Support calculated value only for:
1113 // - "&" (boolean AND)
1114 // - "+" (addition)
1115 // - "-" (substraction)
1116 // - "*" (multiplication)
1117 // - "/" (division)
1118 // - "%" (modulo)
1119 $calcOperators = '&|\+|-|\*|\/|%';
1120
1121 // Fieldname:
1122 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)([[:space:]]+|' . $calcOperators . '|<=|>=|<|>|=|!=|IS)')) !== '') {
1123
1124 // Parse field name into field and table:
1125 $tableField = explode('.', $fieldName, 2);
1126 if (count($tableField) == 2) {
1127 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
1128 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
1129 } else {
1130 $stack[$level][$pnt[$level]]['table'] = '';
1131 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
1132 }
1133 } else {
1134 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1135 }
1136
1137 // See if the value is calculated:
1138 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString, '^(' . $calcOperators . ')');
1139 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
1140 // Finding value for calculation:
1141 $calc_value = $this->getValue($parseString);
1142 $stack[$level][$pnt[$level]]['calc_value'] = $calc_value;
1143 if (count($calc_value) == 1 && is_string($calc_value[0])) {
1144 // Value is a field, store it to allow DBAL to post-process it (quoting, remapping)
1145 $tableField = explode('.', $calc_value[0], 2);
1146 if (count($tableField) == 2) {
1147 $stack[$level][$pnt[$level]]['calc_table'] = $tableField[0];
1148 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[1];
1149 } else {
1150 $stack[$level][$pnt[$level]]['calc_table'] = '';
1151 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[0];
1152 }
1153 }
1154 }
1155 }
1156
1157 // Find "comparator":
1158 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=|NOT[[:space:]]+IN|IN|NOT[[:space:]]+LIKE|LIKE|IS[[:space:]]+NOT|IS|BETWEEN|NOT[[:space]]+BETWEEN)');
1159 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
1160 if (preg_match('/^CONCAT[[:space:]]*\(/', $parseString)) {
1161 $this->nextPart($parseString, '^(CONCAT[[:space:]]?[(])');
1162 $values = array(
1163 'operator' => 'CONCAT',
1164 'args' => array(),
1165 );
1166 $cnt = 0;
1167 while ($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) {
1168 // Parse field name into field and table:
1169 $tableField = explode('.', $fieldName, 2);
1170 if (count($tableField) == 2) {
1171 $values['args'][$cnt]['table'] = $tableField[0];
1172 $values['args'][$cnt]['field'] = $tableField[1];
1173 } else {
1174 $values['args'][$cnt]['table'] = '';
1175 $values['args'][$cnt]['field'] = $tableField[0];
1176 }
1177 // Looking for comma:
1178 $this->nextPart($parseString, '^(,)');
1179 $cnt++;
1180 }
1181 // Look for ending parenthesis:
1182 $this->nextPart($parseString, '([)])');
1183 $stack[$level][$pnt[$level]]['value'] = $values;
1184 } else if (t3lib_div::inList('IN,NOT IN', $stack[$level][$pnt[$level]]['comparator']) && preg_match('/^[(][[:space:]]*SELECT[[:space:]]+/', $parseString)) {
1185 $this->nextPart($parseString, '^([(])');
1186 $stack[$level][$pnt[$level]]['subquery'] = $this->parseSELECT($parseString);
1187 // Seek to new position in parseString after parsing of the subquery
1188 $parseString = $stack[$level][$pnt[$level]]['subquery']['parseString'];
1189 unset($stack[$level][$pnt[$level]]['subquery']['parseString']);
1190 if (!$this->nextPart($parseString, '^([)])')) {
1191 return 'No ) parenthesis at end of subquery';
1192 }
1193 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $stack[$level][$pnt[$level]]['comparator'])) {
1194 $stack[$level][$pnt[$level]]['values'] = array();
1195 $stack[$level][$pnt[$level]]['values'][0] = $this->getValue($parseString);
1196 if (!$this->nextPart($parseString, '^(AND)')) {
1197 return $this->parseError('No AND operator found as expected in parseWhereClause()', $parseString);
1198 }
1199 $stack[$level][$pnt[$level]]['values'][1] = $this->getValue($parseString);
1200 } else {
1201 // Finding value for comparator:
1202 $stack[$level][$pnt[$level]]['value'] = $this->getValue($parseString, $stack[$level][$pnt[$level]]['comparator']);
1203 if ($this->parse_error) {
1204 return $this->parse_error;
1205 }
1206 }
1207 }
1208 }
1209
1210 // Finished, increase pointer:
1211 $pnt[$level]++;
1212
1213 // Checking if we are back to level 0 and we should still decrease level,
1214 // meaning we were probably parsing as subquery and should return here:
1215 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1216 // Return the stacks lowest level:
1217 return $stack[0];
1218 }
1219
1220 // Checking if we are back to level 0 and we should still decrease level,
1221 // meaning we were probably parsing a subquery and should return here:
1222 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1223 // Return the stacks lowest level:
1224 return $stack[0];
1225 }
1226
1227 // Checking if the current level is ended, in that case do stack management:
1228 while ($this->nextPart($parseString,'^([)])')) {
1229 $level--; // Decrease level:
1230 $stack[$level][$pnt[$level]]['sub'] = $stack[$level+1]; // Copy stack
1231 $pnt[$level]++; // Increase pointer of the new level
1232
1233 // Make recursivity check:
1234 $loopExit++;
1235 if ($loopExit > 500) {
1236 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely in parseWhereClause()...', $parseString);
1237 }
1238 }
1239
1240 // Detecting the operator for the next level:
1241 $op = $this->nextPart($parseString, '^(AND[[:space:]]+NOT|&&[[:space:]]+NOT|OR[[:space:]]+NOT|OR[[:space:]]+NOT|\|\|[[:space:]]+NOT|AND|&&|OR|\|\|)(\(|[[:space:]]+)');
1242 if ($op) {
1243 // Normalize boolean operator
1244 $op = str_replace(array('&&', '||'), array('AND', 'OR'), $op);
1245 $stack[$level][$pnt[$level]]['operator'] = $op;
1246 } elseif (strlen($parseString)) {
1247
1248 // Looking for stop-keywords:
1249 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
1250 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',TAB,CR,LF), '', $this->lastStopKeyWord));
1251 return $stack[0];
1252 } else {
1253 return $this->parseError('No operator, but parsing not finished in parseWhereClause().', $parseString);
1254 }
1255 }
1256 }
1257
1258 // Make recursivity check:
1259 $loopExit++;
1260 if ($loopExit > 500) {
1261 return $this->parseError('More than 500 loops, exiting prematurely in parseWhereClause()...', $parseString);
1262 }
1263 }
1264
1265 // Return the stacks lowest level:
1266 return $stack[0];
1267 }
1268
1269 /**
1270 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1271 * The success of this parsing determines if that part of the query is supported by TYPO3.
1272 *
1273 * @param string WHERE clause to parse. NOTICE: passed by reference!
1274 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1275 * @return mixed If successful parsing, returns an array, otherwise an error string.
1276 */
1277 public function parseFieldDef(&$parseString, $stopRegex = '') {
1278 // Prepare variables:
1279 $parseString = $this->trimSQL($parseString);
1280 $this->lastStopKeyWord = '';
1281 $this->parse_error = '';
1282
1283 $result = array();
1284
1285 // Field type:
1286 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:],]+|\()')) {
1287
1288 // Looking for value:
1289 if (substr($parseString,0,1)=='(') {
1290 $parseString = substr($parseString,1);
1291 if ($result['value'] = $this->nextPart($parseString,'^([^)]*)')) {
1292 $parseString = ltrim(substr($parseString,1));
1293 } else return $this->parseError('No end-parenthesis for value found in parseFieldDef()!',$parseString);
1294 }
1295
1296 // Looking for keywords
1297 while($keyword = $this->nextPart($parseString,'^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\))')) {
1298 $keywordCmp = strtoupper(str_replace(array(' ',TAB,CR,LF),'',$keyword));
1299
1300 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
1301
1302 switch($keywordCmp) {
1303 case 'DEFAULT':
1304 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
1305 break;
1306 }
1307 }
1308 } else {
1309 return $this->parseError('Field type unknown in parseFieldDef()!',$parseString);
1310 }
1311
1312 return $result;
1313 }
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325 /************************************
1326 *
1327 * Parsing: Helper functions
1328 *
1329 ************************************/
1330
1331 /**
1332 * Strips off a part of the parseString and returns the matching part.
1333 * Helper function for the parsing methods.
1334 *
1335 * @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.
1336 * @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())
1337 * @param boolean If set the full match of the regex is stripped of the beginning of the string!
1338 * @return string The value of the first parenthesis level of the REGEX.
1339 */
1340 protected function nextPart(&$parseString, $regex, $trimAll = FALSE) {
1341 $reg = array();
1342 if (preg_match('/'.$regex.'/i',$parseString.' ', $reg)) { // Adding space char because [[:space:]]+ is often a requirement in regex's
1343 $parseString = ltrim(substr($parseString,strlen($reg[$trimAll?0:1])));
1344 return $reg[1];
1345 }
1346 // No match found
1347 return '';
1348 }
1349
1350 /**
1351 * Finds value in beginning of $parseString, returns result and strips it of parseString
1352 *
1353 * @param string The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ..."
1354 * @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)
1355 * @param string The mode, eg. "INDEX"
1356 * @return mixed The value (string/integer). Otherwise an array with error message in first key (0)
1357 */
1358 protected function getValue(&$parseString, $comparator = '', $mode = '') {
1359 $value = '';
1360
1361 if (t3lib_div::inList('NOTIN,IN,_LIST',strtoupper(str_replace(array(' ',LF,CR,TAB),'',$comparator)))) { // List of values:
1362 if ($this->nextPart($parseString,'^([(])')) {
1363 $listValues = array();
1364 $comma=',';
1365
1366 while($comma==',') {
1367 $listValues[] = $this->getValue($parseString);
1368 if ($mode === 'INDEX') {
1369 // Remove any length restriction on INDEX definition
1370 $this->nextPart($parseString, '^([(]\d+[)])');
1371 }
1372 $comma = $this->nextPart($parseString,'^([,])');
1373 }
1374
1375 $out = $this->nextPart($parseString,'^([)])');
1376 if ($out) {
1377 if ($comparator=='_LIST') {
1378 $kVals = array();
1379 foreach ($listValues as $vArr) {
1380 $kVals[] = $vArr[0];
1381 }
1382 return $kVals;
1383 } else {
1384 return $listValues;
1385 }
1386 } else return array($this->parseError('No ) parenthesis in list',$parseString));
1387 } else return array($this->parseError('No ( parenthesis starting the list',$parseString));
1388
1389 } else { // Just plain string value, in quotes or not:
1390
1391 // Quote?
1392 $firstChar = substr($parseString,0,1);
1393 switch($firstChar) {
1394 case '"':
1395 $value = array($this->getValueInQuotes($parseString,'"'),'"');
1396 break;
1397 case "'":
1398 $value = array($this->getValueInQuotes($parseString,"'"),"'");
1399 break;
1400 default:
1401 $reg = array();
1402 if (preg_match('/^([[:alnum:]._-]+)/i',$parseString, $reg)) {
1403 $parseString = ltrim(substr($parseString,strlen($reg[0])));
1404 $value = array($reg[1]);
1405 }
1406 break;
1407 }
1408 }
1409 return $value;
1410 }
1411
1412 /**
1413 * Get value in quotes from $parseString.
1414 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1415 *
1416 * @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.
1417 * @param string The quote used; input either " or '
1418 * @return string The value, passed through stripslashes() !
1419 */
1420 protected function getValueInQuotes(&$parseString, $quote) {
1421
1422 $parts = explode($quote,substr($parseString,1));
1423 $buffer = '';
1424 foreach($parts as $k => $v) {
1425 $buffer.=$v;
1426
1427 $reg = array();
1428 preg_match('/\\\\$/', $v, $reg);
1429 if ($reg AND strlen($reg[0])%2) {
1430 $buffer.=$quote;
1431 } else {
1432 $parseString = ltrim(substr($parseString,strlen($buffer)+2));
1433 return $this->parseStripslashes($buffer);
1434 }
1435 }
1436 }
1437
1438 /**
1439 * Strip slashes function used for parsing
1440 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1441 *
1442 * @param string Input string
1443 * @return string Output string
1444 */
1445 protected function parseStripslashes($str) {
1446 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1447 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1448
1449 return str_replace($search, $replace, $str);
1450 }
1451
1452 /**
1453 * Add slashes function used for compiling queries
1454 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1455 *
1456 * @param string Input string
1457 * @return string Output string
1458 */
1459 protected function compileAddslashes($str) {
1460 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1461 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1462
1463 return str_replace($search, $replace, $str);
1464 }
1465
1466 /**
1467 * Setting the internal error message value, $this->parse_error and returns that value.
1468 *
1469 * @param string Input error message
1470 * @param string Remaining query to parse.
1471 * @return string Error message.
1472 */
1473 protected function parseError($msg, $restQuery) {
1474 $this->parse_error = 'SQL engine parse ERROR: '.$msg.': near "'.substr($restQuery,0,50).'"';
1475 return $this->parse_error;
1476 }
1477
1478 /**
1479 * Trimming SQL as preparation for parsing.
1480 * ";" in the end is stripped of.
1481 * White space is trimmed away around the value
1482 * A single space-char is added in the end
1483 *
1484 * @param string Input string
1485 * @return string Output string
1486 */
1487 protected function trimSQL($str) {
1488 return trim(rtrim($str, "; \r\n\t")).' ';
1489 }
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502 /*************************
1503 *
1504 * Compiling queries
1505 *
1506 *************************/
1507
1508 /**
1509 * Compiles an SQL query from components
1510 *
1511 * @param array Array of SQL query components
1512 * @return string SQL query
1513 * @see parseSQL()
1514 */
1515 public function compileSQL($components) {
1516 switch($components['type']) {
1517 case 'SELECT':
1518 $query = $this->compileSELECT($components);
1519 break;
1520 case 'UPDATE':
1521 $query = $this->compileUPDATE($components);
1522 break;
1523 case 'INSERT':
1524 $query = $this->compileINSERT($components);
1525 break;
1526 case 'DELETE':
1527 $query = $this->compileDELETE($components);
1528 break;
1529 case 'EXPLAIN':
1530 $query = 'EXPLAIN '.$this->compileSELECT($components);
1531 break;
1532 case 'DROPTABLE':
1533 $query = 'DROP TABLE'.($components['ifExists']?' IF EXISTS':'').' '.$components['TABLE'];
1534 break;
1535 case 'CREATETABLE':
1536 $query = $this->compileCREATETABLE($components);
1537 break;
1538 case 'ALTERTABLE':
1539 $query = $this->compileALTERTABLE($components);
1540 break;
1541 case 'TRUNCATETABLE':
1542 $query = $this->compileTRUNCATETABLE($components);
1543 break;
1544 }
1545
1546 return $query;
1547 }
1548
1549 /**
1550 * Compiles a SELECT statement from components array
1551 *
1552 * @param array Array of SQL query components
1553 * @return string SQL SELECT query
1554 * @see parseSELECT()
1555 */
1556 protected function compileSELECT($components) {
1557
1558 // Initialize:
1559 $where = $this->compileWhereClause($components['WHERE']);
1560 $groupBy = $this->compileFieldList($components['GROUPBY']);
1561 $orderBy = $this->compileFieldList($components['ORDERBY']);
1562 $limit = $components['LIMIT'];
1563
1564 // Make query:
1565 $query = 'SELECT '.($components['STRAIGHT_JOIN'] ? $components['STRAIGHT_JOIN'].'' : '').'
1566 '.$this->compileFieldList($components['SELECT']).'
1567 FROM '.$this->compileFromTables($components['FROM']).
1568 (strlen($where)?'
1569 WHERE '.$where : '').
1570 (strlen($groupBy)?'
1571 GROUP BY '.$groupBy : '').
1572 (strlen($orderBy)?'
1573 ORDER BY '.$orderBy : '').
1574 (strlen($limit)?'
1575 LIMIT '.$limit : '');
1576
1577 return $query;
1578 }
1579
1580 /**
1581 * Compiles an UPDATE statement from components array
1582 *
1583 * @param array Array of SQL query components
1584 * @return string SQL UPDATE query
1585 * @see parseUPDATE()
1586 */
1587 protected function compileUPDATE($components) {
1588
1589 // Where clause:
1590 $where = $this->compileWhereClause($components['WHERE']);
1591
1592 // Fields
1593 $fields = array();
1594 foreach($components['FIELDS'] as $fN => $fV) {
1595 $fields[]=$fN.'='.$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1596 }
1597
1598 // Make query:
1599 $query = 'UPDATE '.$components['TABLE'].' SET
1600 '.implode(',
1601 ',$fields).'
1602 '.(strlen($where)?'
1603 WHERE '.$where : '');
1604
1605 return $query;
1606 }
1607
1608 /**
1609 * Compiles an INSERT statement from components array
1610 *
1611 * @param array Array of SQL query components
1612 * @return string SQL INSERT query
1613 * @see parseINSERT()
1614 */
1615 protected function compileINSERT($components) {
1616 $values = array();
1617
1618 if (isset($components['VALUES_ONLY']) && is_array($components['VALUES_ONLY'])) {
1619 $valuesComponents = $components['EXTENDED'] === '1' ? $components['VALUES_ONLY'] : array($components['VALUES_ONLY']);
1620 $tableFields = array();
1621 } else {
1622 $valuesComponents = $components['EXTENDED'] === '1' ? $components['FIELDS'] : array($components['FIELDS']);
1623 $tableFields = array_keys($valuesComponents[0]);
1624 }
1625
1626 foreach ($valuesComponents as $valuesComponent) {
1627 $fields = array();
1628 foreach ($valuesComponent as $fV) {
1629 $fields[] = $fV[1] . $this->compileAddslashes($fV[0]) . $fV[1];
1630 }
1631 $values[] = '(' . implode(',
1632 ', $fields) . ')';
1633 }
1634
1635 // Make query:
1636 $query = 'INSERT INTO ' . $components['TABLE'];
1637 if (count($tableFields)) {
1638 $query .= '
1639 (' . implode(',
1640 ', $tableFields) . ')';
1641 }
1642 $query .= '
1643 VALUES
1644 ' . implode(',
1645 ', $values);
1646
1647 return $query;
1648 }
1649
1650 /**
1651 * Compiles an DELETE statement from components array
1652 *
1653 * @param array Array of SQL query components
1654 * @return string SQL DELETE query
1655 * @see parseDELETE()
1656 */
1657 protected function compileDELETE($components) {
1658
1659 // Where clause:
1660 $where = $this->compileWhereClause($components['WHERE']);
1661
1662 // Make query:
1663 $query = 'DELETE FROM '.$components['TABLE'].
1664 (strlen($where)?'
1665 WHERE '.$where : '');
1666
1667 return $query;
1668 }
1669
1670 /**
1671 * Compiles a CREATE TABLE statement from components array
1672 *
1673 * @param array Array of SQL query components
1674 * @return string SQL CREATE TABLE query
1675 * @see parseCREATETABLE()
1676 */
1677 protected function compileCREATETABLE($components) {
1678
1679 // Create fields and keys:
1680 $fieldsKeys = array();
1681 foreach($components['FIELDS'] as $fN => $fCfg) {
1682 $fieldsKeys[]=$fN.' '.$this->compileFieldCfg($fCfg['definition']);
1683 }
1684 foreach($components['KEYS'] as $kN => $kCfg) {
1685 if ($kN == 'PRIMARYKEY') {
1686 $fieldsKeys[]='PRIMARY KEY ('.implode(',', $kCfg).')';
1687 } elseif ($kN == 'UNIQUE') {
1688 $fieldsKeys[]='UNIQUE '.$kN.' ('.implode(',', $kCfg).')';
1689 } else {
1690 $fieldsKeys[]='KEY '.$kN.' ('.implode(',', $kCfg).')';
1691 }
1692 }
1693
1694 // Make query:
1695 $query = 'CREATE TABLE '.$components['TABLE'].' (
1696 '.implode(',
1697 ', $fieldsKeys).'
1698 )'.($components['tableType'] ? ' TYPE='.$components['tableType'] : '');
1699
1700 return $query;
1701 }
1702
1703 /**
1704 * Compiles an ALTER TABLE statement from components array
1705 *
1706 * @param array Array of SQL query components
1707 * @return string SQL ALTER TABLE query
1708 * @see parseALTERTABLE()
1709 */
1710 protected function compileALTERTABLE($components) {
1711
1712 // Make query:
1713 $query = 'ALTER TABLE '.$components['TABLE'].' '.$components['action'].' '.($components['FIELD']?$components['FIELD']:$components['KEY']);
1714
1715 // Based on action, add the final part:
1716 switch(strtoupper(str_replace(array(' ',TAB,CR,LF),'',$components['action']))) {
1717 case 'ADD':
1718 $query.=' '.$this->compileFieldCfg($components['definition']);
1719 break;
1720 case 'CHANGE':
1721 $query.=' '.$components['newField'].' '.$this->compileFieldCfg($components['definition']);
1722 break;
1723 case 'DROP':
1724 case 'DROPKEY':
1725 break;
1726 case 'ADDKEY':
1727 case 'ADDPRIMARYKEY':
1728 case 'ADDUNIQUE':
1729 $query.=' ('.implode(',',$components['fields']).')';
1730 break;
1731 }
1732
1733 // Return query
1734 return $query;
1735 }
1736
1737 /**
1738 * Compiles a TRUNCATE TABLE statement from components array
1739 *
1740 * @param array Array of SQL query components
1741 * @return string SQL TRUNCATE TABLE query
1742 * @see parseTRUNCATETABLE()
1743 */
1744 protected function compileTRUNCATETABLE(array $components) {
1745
1746 // Make query:
1747 $query = 'TRUNCATE TABLE ' . $components['TABLE'];
1748
1749 // Return query
1750 return $query;
1751 }
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766 /**************************************
1767 *
1768 * Compiling queries, helper functions for parts of queries
1769 *
1770 **************************************/
1771
1772 /**
1773 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1774 * Can also compile field lists for ORDER BY and GROUP BY.
1775 *
1776 * @param array Array of select fields, (made with ->parseFieldList())
1777 * @param boolean Whether comments should be compiled
1778 * @return string Select field string
1779 * @see parseFieldList()
1780 */
1781 public function compileFieldList($selectFields, $compileComments = TRUE) {
1782
1783 // Prepare buffer variable:
1784 $fields = '';
1785
1786 // Traverse the selectFields if any:
1787 if (is_array($selectFields)) {
1788 $outputParts = array();
1789 foreach($selectFields as $k => $v) {
1790
1791 // Detecting type:
1792 switch($v['type']) {
1793 case 'function':
1794 $outputParts[$k] = $v['function'].'('.$v['func_content'].')';
1795 break;
1796 case 'flow-control':
1797 if ($v['flow-control']['type'] === 'CASE') {
1798 $outputParts[$k] = $this->compileCaseStatement($v['flow-control']);
1799 }
1800 break;
1801 case 'field':
1802 $outputParts[$k] = ($v['distinct']?$v['distinct']:'').($v['table']?$v['table'].'.':'').$v['field'];
1803 break;
1804 }
1805
1806 // Alias:
1807 if ($v['as']) {
1808 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1809 }
1810
1811 // Specifically for ORDER BY and GROUP BY field lists:
1812 if ($v['sortDir']) {
1813 $outputParts[$k].= ' '.$v['sortDir'];
1814 }
1815 }
1816 if ($compileComments && $selectFields[0]['comments']) {
1817 $fields = $selectFields[0]['comments'] . ' ';
1818 }
1819 $fields .= implode(', ', $outputParts);
1820 }
1821
1822 return $fields;
1823 }
1824
1825 /**
1826 * Compiles a CASE ... WHEN flow-control construct based on input array (made with ->parseCaseStatement())
1827 *
1828 * @param array Array of case components, (made with ->parseCaseStatement())
1829 * @return string case when string
1830 * @see parseCaseStatement()
1831 */
1832 protected function compileCaseStatement(array $components) {
1833 $statement = 'CASE';
1834 if (isset($components['case_field'])) {
1835 $statement .= ' ' . $components['case_field'];
1836 } elseif (isset($components['case_value'])) {
1837 $statement .= ' ' . $components['case_value'][1] . $components['case_value'][0] . $components['case_value'][1];
1838 }
1839 foreach ($components['when'] as $when) {
1840 $statement .= ' WHEN ';
1841 $statement .= $this->compileWhereClause($when['when_value']);
1842 $statement .= ' THEN ';
1843 $statement .= $when['then_value'][1] . $when['then_value'][0] . $when['then_value'][1];
1844 }
1845 if (isset($components['else'])) {
1846 $statement .= ' ELSE ';
1847 $statement .= $components['else'][1] . $components['else'][0] . $components['else'][1];
1848 }
1849 $statement .= ' END';
1850 return $statement;
1851 }
1852
1853 /**
1854 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1855 *
1856 * @param array Array of table names, (made with ->parseFromTables())
1857 * @return string Table name string
1858 * @see parseFromTables()
1859 */
1860 public function compileFromTables($tablesArray) {
1861
1862 // Prepare buffer variable:
1863 $outputParts = array();
1864
1865 // Traverse the table names:
1866 if (is_array($tablesArray)) {
1867 foreach ($tablesArray as $k => $v) {
1868
1869 // Set table name:
1870 $outputParts[$k] = $v['table'];
1871
1872 // Add alias AS if there:
1873 if ($v['as']) {
1874 $outputParts[$k] .= ' ' . $v['as_keyword'] . ' ' . $v['as'];
1875 }
1876
1877 if (is_array($v['JOIN'])) {
1878 foreach ($v['JOIN'] as $join) {
1879 $outputParts[$k] .= ' ' . $join['type'] . ' ' . $join['withTable'];
1880 // Add alias AS if there:
1881 if (isset($join['as']) && $join['as']) {
1882 $outputParts[$k] .= ' ' . $join['as_keyword'] . ' ' . $join['as'];
1883 }
1884 $outputParts[$k] .= ' ON ';
1885 foreach ($join['ON'] as $condition) {
1886 if ($condition['operator'] !== '') {
1887 $outputParts[$k] .= ' ' . $condition['operator'] . ' ';
1888 }
1889 $outputParts[$k] .= ($condition['left']['table']) ? $condition['left']['table'] . '.' : '';
1890 $outputParts[$k] .= $condition['left']['field'];
1891 $outputParts[$k] .= $condition['comparator'];
1892 $outputParts[$k] .= ($condition['right']['table']) ? $condition['right']['table'] . '.' : '';
1893 $outputParts[$k] .= $condition['right']['field'];
1894 }
1895 }
1896 }
1897 }
1898 }
1899
1900 // Return imploded buffer:
1901 return implode(', ', $outputParts);
1902 }
1903
1904 /**
1905 * Implodes an array of WHERE clause configuration into a WHERE clause.
1906 *
1907 * @param array WHERE clause configuration
1908 * @return string WHERE clause as string.
1909 * @see explodeWhereClause()
1910 */
1911 public function compileWhereClause($clauseArray) {
1912
1913 // Prepare buffer variable:
1914 $output = '';
1915
1916 // Traverse clause array:
1917 if (is_array($clauseArray)) {
1918 foreach ($clauseArray as $k => $v) {
1919
1920 // Set operator:
1921 $output .= $v['operator'] ? ' ' . $v['operator'] : '';
1922
1923 // Look for sublevel:
1924 if (is_array($v['sub'])) {
1925 $output .= ' (' . trim($this->compileWhereClause($v['sub'])) . ')';
1926 } elseif (isset($v['func']) && $v['func']['type'] === 'EXISTS') {
1927 $output .= ' ' . trim($v['modifier']) . ' EXISTS (' . $this->compileSELECT($v['func']['subquery']) . ')';
1928 } else {
1929
1930 if (isset($v['func']) && $v['func']['type'] === 'LOCATE') {
1931 $output .= ' ' . trim($v['modifier']) . ' LOCATE(';
1932 $output .= $v['func']['substr'][1] . $v['func']['substr'][0] . $v['func']['substr'][1];
1933 $output .= ', ' . ($v['func']['table'] ? $v['func']['table'] . '.' : '') . $v['func']['field'];
1934 $output .= isset($v['func']['pos']) ? ', ' . $v['func']['pos'][0] : '';
1935 $output .= ')';
1936 } elseif (isset($v['func']) && $v['func']['type'] === 'IFNULL') {
1937 $output = ' ' . trim($v['modifier']) . ' IFNULL(';
1938 $output .= ($v['func']['table'] ? $v['func']['table'] . '.' : '') . $v['func']['field'];
1939 $output .= ', ' . $v['func']['default'][1] . $this->compileAddslashes($v['func']['default'][0]) . $v['func']['default'][1];
1940 $output .= ')';
1941 } else {
1942
1943 // Set field/table with modifying prefix if any:
1944 $output .= ' ' . trim($v['modifier'] . ' ' . ($v['table'] ? $v['table'] . '.' : '') . $v['field']);
1945
1946 // Set calculation, if any:
1947 if ($v['calc']) {
1948 $output .= $v['calc'] . $v['calc_value'][1] . $this->compileAddslashes($v['calc_value'][0]) . $v['calc_value'][1];
1949 }
1950 }
1951
1952 // Set comparator:
1953 if ($v['comparator']) {
1954 $output .= ' ' . $v['comparator'];
1955
1956 // Detecting value type; list or plain:
1957 if (t3lib_div::inList('NOTIN,IN', strtoupper(str_replace(array(' ', TAB, CR, LF), '', $v['comparator'])))) {
1958 if (isset($v['subquery'])) {
1959 $output .= ' (' . $this->compileSELECT($v['subquery']) . ')';
1960 } else {
1961 $valueBuffer = array();
1962 foreach ($v['value'] as $realValue) {
1963 $valueBuffer[] = $realValue[1] . $this->compileAddslashes($realValue[0]) . $realValue[1];
1964 }
1965 $output .= ' (' . trim(implode(',', $valueBuffer)) . ')';
1966 }
1967 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $v['comparator'])) {
1968 $lbound = $v['values'][0];
1969 $ubound = $v['values'][1];
1970 $output .= ' ' . $lbound[1] . $this->compileAddslashes($lbound[0]) . $lbound[1];
1971 $output .= ' AND ';
1972 $output .= $ubound[1] . $this->compileAddslashes($ubound[0]) . $ubound[1];
1973 } else if (isset($v['value']['operator'])) {
1974 $values = array();
1975 foreach ($v['value']['args'] as $fieldDef) {
1976 $values[] = ($fieldDef['table'] ? $fieldDef['table'] . '.' : '') . $fieldDef['field'];
1977 }
1978 $output .= ' ' . $v['value']['operator'] . '(' . implode(',', $values) . ')';
1979 } else {
1980 $output .= ' ' . $v['value'][1] . $this->compileAddslashes($v['value'][0]) . $v['value'][1];
1981 }
1982 }
1983 }
1984 }
1985 }
1986
1987 // Return output buffer:
1988 return $output;
1989 }
1990
1991 /**
1992 * Compile field definition
1993 *
1994 * @param array Field definition parts
1995 * @return string Field definition string
1996 */
1997 public function compileFieldCfg($fieldCfg) {
1998
1999 // Set type:
2000 $cfg = $fieldCfg['fieldType'];
2001
2002 // Add value, if any:
2003 if (strlen($fieldCfg['value'])) {
2004 $cfg.='('.$fieldCfg['value'].')';
2005 }
2006
2007 // Add additional features:
2008 if (is_array($fieldCfg['featureIndex'])) {
2009 foreach($fieldCfg['featureIndex'] as $featureDef) {
2010 $cfg.=' '.$featureDef['keyword'];
2011
2012 // Add value if found:
2013 if (is_array($featureDef['value'])) {
2014 $cfg.=' '.$featureDef['value'][1].$this->compileAddslashes($featureDef['value'][0]).$featureDef['value'][1];
2015 }
2016 }
2017 }
2018
2019 // Return field definition string:
2020 return $cfg;
2021 }
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033 /*************************
2034 *
2035 * Debugging
2036 *
2037 *************************/
2038
2039 /**
2040 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
2041 *
2042 * @param string Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
2043 * @param string SQL string to verify parsability of
2044 * @return mixed Returns array with string 1 and 2 if error, otherwise false
2045 */
2046 public function debug_parseSQLpart($part, $str) {
2047 $retVal = false;
2048
2049 switch($part) {
2050 case 'SELECT':
2051 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFieldList($this->parseFieldList($str)));
2052 break;
2053 case 'FROM':
2054 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFromTables($this->parseFromTables($str)));
2055 break;
2056 case 'WHERE':
2057 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileWhereClause($this->parseWhereClause($str)));
2058 break;
2059 }
2060 return $retVal;
2061 }
2062
2063 /**
2064 * Compare two query strins by stripping away whitespace.
2065 *
2066 * @param string SQL String 1
2067 * @param string SQL string 2
2068 * @param boolean If true, the strings are compared insensitive to case
2069 * @return mixed Returns array with string 1 and 2 if error, otherwise false
2070 */
2071 public function debug_parseSQLpartCompare($str, $newStr, $caseInsensitive = FALSE) {
2072 if ($caseInsensitive) {
2073 $str1 = strtoupper($str);
2074 $str2 = strtoupper($newStr);
2075 } else {
2076 $str1 = $str;
2077 $str2 = $newStr;
2078 }
2079
2080 // Fixing escaped chars:
2081 $search = array('\0', '\n', '\r', '\Z');
2082 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
2083 $str1 = str_replace($search, $replace, $str1);
2084 $str2 = str_replace($search, $replace, $str2);
2085
2086 # Normally, commented out since they are needed only in tricky cases...
2087 # $str1 = stripslashes($str1);
2088 # $str2 = stripslashes($str2);
2089
2090 if (strcmp(str_replace(array(' ',TAB,CR,LF),'',$this->trimSQL($str1)),str_replace(array(' ',TAB,CR,LF),'',$this->trimSQL($str2)))) {
2091 return array(
2092 str_replace(array(' ',TAB,CR,LF),' ',$str),
2093 str_replace(array(' ',TAB,CR,LF),' ',$newStr),
2094 );
2095 }
2096 }
2097
2098 /**
2099 * 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
2100 *
2101 * @param string SQL query
2102 * @return string Query if all is well, otherwise exit.
2103 */
2104 public function debug_testSQL($SQLquery) {
2105
2106 // Getting result array:
2107 $parseResult = $this->parseSQL($SQLquery);
2108
2109 // If result array was returned, proceed. Otherwise show error and exit.
2110 if (is_array($parseResult)) {
2111
2112 // Re-compile query:
2113 $newQuery = $this->compileSQL($parseResult);
2114
2115 // TEST the new query:
2116 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
2117
2118 // Return new query if OK, otherwise show error and exit:
2119 if (!is_array($testResult)) {
2120 return $newQuery;
2121 } else {
2122 debug(array('ERROR MESSAGE'=>'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult),'SQL parsing failed:');
2123 exit;
2124 }
2125 } else {
2126 debug(array('query' => $SQLquery, 'ERROR MESSAGE'=>$parseResult),'SQL parsing failed:');
2127 exit;
2128 }
2129 }
2130 }
2131
2132
2133 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']) {
2134 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']);
2135 }
2136
2137 ?>