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