c82c461c6edc0ec46c8bc04c471937312dbe0c24
[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(' ',"\t","\r","\n"),'',$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(' ',"\t","\r","\n"),'',$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(' ',"\t","\r","\n"),'',$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');
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(' ',"\t","\r","\n"),'',$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(' ',"\t","\r","\n"), '', $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(' ',"\t","\r","\n"), '', $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 } else {
1071
1072 // Support calculated value only for:
1073 // - "&" (boolean AND)
1074 // - "+" (addition)
1075 // - "-" (substraction)
1076 // - "*" (multiplication)
1077 // - "/" (division)
1078 // - "%" (modulo)
1079 $calcOperators = '&|\+|-|\*|\/|%';
1080
1081 // Fieldname:
1082 if (($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)([[:space:]]+|' . $calcOperators . '|<=|>=|<|>|=|!=|IS)')) !== '') {
1083
1084 // Parse field name into field and table:
1085 $tableField = explode('.', $fieldName, 2);
1086 if (count($tableField) == 2) {
1087 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
1088 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
1089 } else {
1090 $stack[$level][$pnt[$level]]['table'] = '';
1091 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
1092 }
1093 } else {
1094 return $this->parseError('No field name found as expected in parseWhereClause()', $parseString);
1095 }
1096
1097 // See if the value is calculated:
1098 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString, '^(' . $calcOperators . ')');
1099 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
1100 // Finding value for calculation:
1101 $calc_value = $this->getValue($parseString);
1102 $stack[$level][$pnt[$level]]['calc_value'] = $calc_value;
1103 if (count($calc_value) == 1 && is_string($calc_value[0])) {
1104 // Value is a field, store it to allow DBAL to post-process it (quoting, remapping)
1105 $tableField = explode('.', $calc_value[0], 2);
1106 if (count($tableField) == 2) {
1107 $stack[$level][$pnt[$level]]['calc_table'] = $tableField[0];
1108 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[1];
1109 } else {
1110 $stack[$level][$pnt[$level]]['calc_table'] = '';
1111 $stack[$level][$pnt[$level]]['calc_field'] = $tableField[0];
1112 }
1113 }
1114 }
1115 }
1116
1117 // Find "comparator":
1118 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString, '^(<=|>=|<|>|=|!=|NOT[[:space:]]+IN|IN|NOT[[:space:]]+LIKE|LIKE|IS[[:space:]]+NOT|IS|BETWEEN|NOT[[:space]]+BETWEEN)');
1119 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
1120 if (preg_match('/^CONCAT[[:space:]]*\(/', $parseString)) {
1121 $this->nextPart($parseString, '^(CONCAT[[:space:]]?[(])');
1122 $values = array(
1123 'operator' => 'CONCAT',
1124 'args' => array(),
1125 );
1126 $cnt = 0;
1127 while ($fieldName = $this->nextPart($parseString, '^([[:alnum:]._]+)')) {
1128 // Parse field name into field and table:
1129 $tableField = explode('.', $fieldName, 2);
1130 if (count($tableField) == 2) {
1131 $values['args'][$cnt]['table'] = $tableField[0];
1132 $values['args'][$cnt]['field'] = $tableField[1];
1133 } else {
1134 $values['args'][$cnt]['table'] = '';
1135 $values['args'][$cnt]['field'] = $tableField[0];
1136 }
1137 // Looking for comma:
1138 $this->nextPart($parseString, '^(,)');
1139 $cnt++;
1140 }
1141 // Look for ending parenthesis:
1142 $this->nextPart($parseString, '([)])');
1143 $stack[$level][$pnt[$level]]['value'] = $values;
1144 } else if (t3lib_div::inList('IN,NOT IN', $stack[$level][$pnt[$level]]['comparator']) && preg_match('/^[(][[:space:]]*SELECT[[:space:]]+/', $parseString)) {
1145 $this->nextPart($parseString, '^([(])');
1146 $stack[$level][$pnt[$level]]['subquery'] = $this->parseSELECT($parseString);
1147 // Seek to new position in parseString after parsing of the subquery
1148 $parseString = $stack[$level][$pnt[$level]]['subquery']['parseString'];
1149 unset($stack[$level][$pnt[$level]]['subquery']['parseString']);
1150 if (!$this->nextPart($parseString, '^([)])')) {
1151 return 'No ) parenthesis at end of subquery';
1152 }
1153 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $stack[$level][$pnt[$level]]['comparator'])) {
1154 $stack[$level][$pnt[$level]]['values'] = array();
1155 $stack[$level][$pnt[$level]]['values'][0] = $this->getValue($parseString);
1156 if (!$this->nextPart($parseString, '^(AND)')) {
1157 return $this->parseError('No AND operator found as expected in parseWhereClause()', $parseString);
1158 }
1159 $stack[$level][$pnt[$level]]['values'][1] = $this->getValue($parseString);
1160 } else {
1161 // Finding value for comparator:
1162 $stack[$level][$pnt[$level]]['value'] = $this->getValue($parseString, $stack[$level][$pnt[$level]]['comparator']);
1163 if ($this->parse_error) {
1164 return $this->parse_error;
1165 }
1166 }
1167 }
1168 }
1169
1170 // Finished, increase pointer:
1171 $pnt[$level]++;
1172
1173 // Checking if we are back to level 0 and we should still decrease level,
1174 // meaning we were probably parsing as subquery and should return here:
1175 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1176 // Return the stacks lowest level:
1177 return $stack[0];
1178 }
1179
1180 // Checking if we are back to level 0 and we should still decrease level,
1181 // meaning we were probably parsing a subquery and should return here:
1182 if ($level === 0 && preg_match('/^[)]/', $parseString)) {
1183 // Return the stacks lowest level:
1184 return $stack[0];
1185 }
1186
1187 // Checking if the current level is ended, in that case do stack management:
1188 while ($this->nextPart($parseString,'^([)])')) {
1189 $level--; // Decrease level:
1190 $stack[$level][$pnt[$level]]['sub'] = $stack[$level+1]; // Copy stack
1191 $pnt[$level]++; // Increase pointer of the new level
1192
1193 // Make recursivity check:
1194 $loopExit++;
1195 if ($loopExit > 500) {
1196 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely in parseWhereClause()...', $parseString);
1197 }
1198 }
1199
1200 // Detecting the operator for the next level:
1201 $op = $this->nextPart($parseString, '^(AND[[:space:]]+NOT|&&[[:space:]]+NOT|OR[[:space:]]+NOT|OR[[:space:]]+NOT|\|\|[[:space:]]+NOT|AND|&&|OR|\|\|)(\(|[[:space:]]+)');
1202 if ($op) {
1203 // Normalize boolean operator
1204 $op = str_replace(array('&&', '||'), array('AND', 'OR'), $op);
1205 $stack[$level][$pnt[$level]]['operator'] = $op;
1206 } elseif (strlen($parseString)) {
1207
1208 // Looking for stop-keywords:
1209 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
1210 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',"\t","\r","\n"), '', $this->lastStopKeyWord));
1211 return $stack[0];
1212 } else {
1213 return $this->parseError('No operator, but parsing not finished in parseWhereClause().', $parseString);
1214 }
1215 }
1216 }
1217
1218 // Make recursivity check:
1219 $loopExit++;
1220 if ($loopExit > 500) {
1221 return $this->parseError('More than 500 loops, exiting prematurely in parseWhereClause()...', $parseString);
1222 }
1223 }
1224
1225 // Return the stacks lowest level:
1226 return $stack[0];
1227 }
1228
1229 /**
1230 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
1231 * The success of this parsing determines if that part of the query is supported by TYPO3.
1232 *
1233 * @param string WHERE clause to parse. NOTICE: passed by reference!
1234 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
1235 * @return mixed If successful parsing, returns an array, otherwise an error string.
1236 */
1237 public function parseFieldDef(&$parseString, $stopRegex = '') {
1238 // Prepare variables:
1239 $parseString = $this->trimSQL($parseString);
1240 $this->lastStopKeyWord = '';
1241 $this->parse_error = '';
1242
1243 $result = array();
1244
1245 // Field type:
1246 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:],]+|\()')) {
1247
1248 // Looking for value:
1249 if (substr($parseString,0,1)=='(') {
1250 $parseString = substr($parseString,1);
1251 if ($result['value'] = $this->nextPart($parseString,'^([^)]*)')) {
1252 $parseString = ltrim(substr($parseString,1));
1253 } else return $this->parseError('No end-parenthesis for value found in parseFieldDef()!',$parseString);
1254 }
1255
1256 // Looking for keywords
1257 while($keyword = $this->nextPart($parseString,'^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\))')) {
1258 $keywordCmp = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$keyword));
1259
1260 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
1261
1262 switch($keywordCmp) {
1263 case 'DEFAULT':
1264 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
1265 break;
1266 }
1267 }
1268 } else {
1269 return $this->parseError('Field type unknown in parseFieldDef()!',$parseString);
1270 }
1271
1272 return $result;
1273 }
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285 /************************************
1286 *
1287 * Parsing: Helper functions
1288 *
1289 ************************************/
1290
1291 /**
1292 * Strips off a part of the parseString and returns the matching part.
1293 * Helper function for the parsing methods.
1294 *
1295 * @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.
1296 * @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())
1297 * @param boolean If set the full match of the regex is stripped of the beginning of the string!
1298 * @return string The value of the first parenthesis level of the REGEX.
1299 */
1300 protected function nextPart(&$parseString, $regex, $trimAll = FALSE) {
1301 $reg = array();
1302 if (preg_match('/'.$regex.'/i',$parseString.' ', $reg)) { // Adding space char because [[:space:]]+ is often a requirement in regex's
1303 $parseString = ltrim(substr($parseString,strlen($reg[$trimAll?0:1])));
1304 return $reg[1];
1305 }
1306 }
1307
1308 /**
1309 * Finds value in beginning of $parseString, returns result and strips it of parseString
1310 *
1311 * @param string The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ..."
1312 * @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)
1313 * @param string The mode, eg. "INDEX"
1314 * @return mixed The value (string/integer). Otherwise an array with error message in first key (0)
1315 */
1316 protected function getValue(&$parseString, $comparator = '', $mode = '') {
1317 $value = '';
1318
1319 if (t3lib_div::inList('NOTIN,IN,_LIST',strtoupper(str_replace(array(' ',"\n","\r","\t"),'',$comparator)))) { // List of values:
1320 if ($this->nextPart($parseString,'^([(])')) {
1321 $listValues = array();
1322 $comma=',';
1323
1324 while($comma==',') {
1325 $listValues[] = $this->getValue($parseString);
1326 if ($mode === 'INDEX') {
1327 // Remove any length restriction on INDEX definition
1328 $this->nextPart($parseString, '^([(]\d+[)])');
1329 }
1330 $comma = $this->nextPart($parseString,'^([,])');
1331 }
1332
1333 $out = $this->nextPart($parseString,'^([)])');
1334 if ($out) {
1335 if ($comparator=='_LIST') {
1336 $kVals = array();
1337 foreach ($listValues as $vArr) {
1338 $kVals[] = $vArr[0];
1339 }
1340 return $kVals;
1341 } else {
1342 return $listValues;
1343 }
1344 } else return array($this->parseError('No ) parenthesis in list',$parseString));
1345 } else return array($this->parseError('No ( parenthesis starting the list',$parseString));
1346
1347 } else { // Just plain string value, in quotes or not:
1348
1349 // Quote?
1350 $firstChar = substr($parseString,0,1);
1351 switch($firstChar) {
1352 case '"':
1353 $value = array($this->getValueInQuotes($parseString,'"'),'"');
1354 break;
1355 case "'":
1356 $value = array($this->getValueInQuotes($parseString,"'"),"'");
1357 break;
1358 default:
1359 $reg = array();
1360 if (preg_match('/^([[:alnum:]._-]+)/i',$parseString, $reg)) {
1361 $parseString = ltrim(substr($parseString,strlen($reg[0])));
1362 $value = array($reg[1]);
1363 }
1364 break;
1365 }
1366 }
1367 return $value;
1368 }
1369
1370 /**
1371 * Get value in quotes from $parseString.
1372 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1373 *
1374 * @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.
1375 * @param string The quote used; input either " or '
1376 * @return string The value, passed through stripslashes() !
1377 */
1378 protected function getValueInQuotes(&$parseString, $quote) {
1379
1380 $parts = explode($quote,substr($parseString,1));
1381 $buffer = '';
1382 foreach($parts as $k => $v) {
1383 $buffer.=$v;
1384
1385 $reg = array();
1386 preg_match('/\\\\$/', $v, $reg);
1387 if ($reg AND strlen($reg[0])%2) {
1388 $buffer.=$quote;
1389 } else {
1390 $parseString = ltrim(substr($parseString,strlen($buffer)+2));
1391 return $this->parseStripslashes($buffer);
1392 }
1393 }
1394 }
1395
1396 /**
1397 * Strip slashes function used for parsing
1398 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1399 *
1400 * @param string Input string
1401 * @return string Output string
1402 */
1403 protected function parseStripslashes($str) {
1404 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1405 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1406
1407 return str_replace($search, $replace, $str);
1408 }
1409
1410 /**
1411 * Add slashes function used for compiling queries
1412 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1413 *
1414 * @param string Input string
1415 * @return string Output string
1416 */
1417 protected function compileAddslashes($str) {
1418 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1419 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1420
1421 return str_replace($search, $replace, $str);
1422 }
1423
1424 /**
1425 * Setting the internal error message value, $this->parse_error and returns that value.
1426 *
1427 * @param string Input error message
1428 * @param string Remaining query to parse.
1429 * @return string Error message.
1430 */
1431 protected function parseError($msg, $restQuery) {
1432 $this->parse_error = 'SQL engine parse ERROR: '.$msg.': near "'.substr($restQuery,0,50).'"';
1433 return $this->parse_error;
1434 }
1435
1436 /**
1437 * Trimming SQL as preparation for parsing.
1438 * ";" in the end is stripped of.
1439 * White space is trimmed away around the value
1440 * A single space-char is added in the end
1441 *
1442 * @param string Input string
1443 * @return string Output string
1444 */
1445 protected function trimSQL($str) {
1446 return trim(rtrim($str, "; \r\n\t")).' ';
1447 }
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460 /*************************
1461 *
1462 * Compiling queries
1463 *
1464 *************************/
1465
1466 /**
1467 * Compiles an SQL query from components
1468 *
1469 * @param array Array of SQL query components
1470 * @return string SQL query
1471 * @see parseSQL()
1472 */
1473 public function compileSQL($components) {
1474 switch($components['type']) {
1475 case 'SELECT':
1476 $query = $this->compileSELECT($components);
1477 break;
1478 case 'UPDATE':
1479 $query = $this->compileUPDATE($components);
1480 break;
1481 case 'INSERT':
1482 $query = $this->compileINSERT($components);
1483 break;
1484 case 'DELETE':
1485 $query = $this->compileDELETE($components);
1486 break;
1487 case 'EXPLAIN':
1488 $query = 'EXPLAIN '.$this->compileSELECT($components);
1489 break;
1490 case 'DROPTABLE':
1491 $query = 'DROP TABLE'.($components['ifExists']?' IF EXISTS':'').' '.$components['TABLE'];
1492 break;
1493 case 'CREATETABLE':
1494 $query = $this->compileCREATETABLE($components);
1495 break;
1496 case 'ALTERTABLE':
1497 $query = $this->compileALTERTABLE($components);
1498 break;
1499 case 'TRUNCATETABLE':
1500 $query = $this->compileTRUNCATETABLE($components);
1501 break;
1502 }
1503
1504 return $query;
1505 }
1506
1507 /**
1508 * Compiles a SELECT statement from components array
1509 *
1510 * @param array Array of SQL query components
1511 * @return string SQL SELECT query
1512 * @see parseSELECT()
1513 */
1514 protected function compileSELECT($components) {
1515
1516 // Initialize:
1517 $where = $this->compileWhereClause($components['WHERE']);
1518 $groupBy = $this->compileFieldList($components['GROUPBY']);
1519 $orderBy = $this->compileFieldList($components['ORDERBY']);
1520 $limit = $components['LIMIT'];
1521
1522 // Make query:
1523 $query = 'SELECT '.($components['STRAIGHT_JOIN'] ? $components['STRAIGHT_JOIN'].'' : '').'
1524 '.$this->compileFieldList($components['SELECT']).'
1525 FROM '.$this->compileFromTables($components['FROM']).
1526 (strlen($where)?'
1527 WHERE '.$where : '').
1528 (strlen($groupBy)?'
1529 GROUP BY '.$groupBy : '').
1530 (strlen($orderBy)?'
1531 ORDER BY '.$orderBy : '').
1532 (strlen($limit)?'
1533 LIMIT '.$limit : '');
1534
1535 return $query;
1536 }
1537
1538 /**
1539 * Compiles an UPDATE statement from components array
1540 *
1541 * @param array Array of SQL query components
1542 * @return string SQL UPDATE query
1543 * @see parseUPDATE()
1544 */
1545 protected function compileUPDATE($components) {
1546
1547 // Where clause:
1548 $where = $this->compileWhereClause($components['WHERE']);
1549
1550 // Fields
1551 $fields = array();
1552 foreach($components['FIELDS'] as $fN => $fV) {
1553 $fields[]=$fN.'='.$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1554 }
1555
1556 // Make query:
1557 $query = 'UPDATE '.$components['TABLE'].' SET
1558 '.implode(',
1559 ',$fields).'
1560 '.(strlen($where)?'
1561 WHERE '.$where : '');
1562
1563 return $query;
1564 }
1565
1566 /**
1567 * Compiles an INSERT statement from components array
1568 *
1569 * @param array Array of SQL query components
1570 * @return string SQL INSERT query
1571 * @see parseINSERT()
1572 */
1573 protected function compileINSERT($components) {
1574 $values = array();
1575
1576 if (isset($components['VALUES_ONLY']) && is_array($components['VALUES_ONLY'])) {
1577 $valuesComponents = $components['EXTENDED'] === '1' ? $components['VALUES_ONLY'] : array($components['VALUES_ONLY']);
1578 $tableFields = array();
1579 } else {
1580 $valuesComponents = $components['EXTENDED'] === '1' ? $components['FIELDS'] : array($components['FIELDS']);
1581 $tableFields = array_keys($valuesComponents[0]);
1582 }
1583
1584 foreach ($valuesComponents as $valuesComponent) {
1585 $fields = array();
1586 foreach ($valuesComponent as $fV) {
1587 $fields[] = $fV[1] . $this->compileAddslashes($fV[0]) . $fV[1];
1588 }
1589 $values[] = '(' . implode(',
1590 ', $fields) . ')';
1591 }
1592
1593 // Make query:
1594 $query = 'INSERT INTO ' . $components['TABLE'];
1595 if (count($tableFields)) {
1596 $query .= '
1597 (' . implode(',
1598 ', $tableFields) . ')';
1599 }
1600 $query .= '
1601 VALUES
1602 ' . implode(',
1603 ', $values);
1604
1605 return $query;
1606 }
1607
1608 /**
1609 * Compiles an DELETE statement from components array
1610 *
1611 * @param array Array of SQL query components
1612 * @return string SQL DELETE query
1613 * @see parseDELETE()
1614 */
1615 protected function compileDELETE($components) {
1616
1617 // Where clause:
1618 $where = $this->compileWhereClause($components['WHERE']);
1619
1620 // Make query:
1621 $query = 'DELETE FROM '.$components['TABLE'].
1622 (strlen($where)?'
1623 WHERE '.$where : '');
1624
1625 return $query;
1626 }
1627
1628 /**
1629 * Compiles a CREATE TABLE statement from components array
1630 *
1631 * @param array Array of SQL query components
1632 * @return string SQL CREATE TABLE query
1633 * @see parseCREATETABLE()
1634 */
1635 protected function compileCREATETABLE($components) {
1636
1637 // Create fields and keys:
1638 $fieldsKeys = array();
1639 foreach($components['FIELDS'] as $fN => $fCfg) {
1640 $fieldsKeys[]=$fN.' '.$this->compileFieldCfg($fCfg['definition']);
1641 }
1642 foreach($components['KEYS'] as $kN => $kCfg) {
1643 if ($kN == 'PRIMARYKEY') {
1644 $fieldsKeys[]='PRIMARY KEY ('.implode(',', $kCfg).')';
1645 } elseif ($kN == 'UNIQUE') {
1646 $fieldsKeys[]='UNIQUE '.$kN.' ('.implode(',', $kCfg).')';
1647 } else {
1648 $fieldsKeys[]='KEY '.$kN.' ('.implode(',', $kCfg).')';
1649 }
1650 }
1651
1652 // Make query:
1653 $query = 'CREATE TABLE '.$components['TABLE'].' (
1654 '.implode(',
1655 ', $fieldsKeys).'
1656 )'.($components['tableType'] ? ' TYPE='.$components['tableType'] : '');
1657
1658 return $query;
1659 }
1660
1661 /**
1662 * Compiles an ALTER TABLE statement from components array
1663 *
1664 * @param array Array of SQL query components
1665 * @return string SQL ALTER TABLE query
1666 * @see parseALTERTABLE()
1667 */
1668 protected function compileALTERTABLE($components) {
1669
1670 // Make query:
1671 $query = 'ALTER TABLE '.$components['TABLE'].' '.$components['action'].' '.($components['FIELD']?$components['FIELD']:$components['KEY']);
1672
1673 // Based on action, add the final part:
1674 switch(strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$components['action']))) {
1675 case 'ADD':
1676 $query.=' '.$this->compileFieldCfg($components['definition']);
1677 break;
1678 case 'CHANGE':
1679 $query.=' '.$components['newField'].' '.$this->compileFieldCfg($components['definition']);
1680 break;
1681 case 'DROP':
1682 case 'DROPKEY':
1683 break;
1684 case 'ADDKEY':
1685 case 'ADDPRIMARYKEY':
1686 $query.=' ('.implode(',',$components['fields']).')';
1687 break;
1688 }
1689
1690 // Return query
1691 return $query;
1692 }
1693
1694 /**
1695 * Compiles a TRUNCATE TABLE statement from components array
1696 *
1697 * @param array Array of SQL query components
1698 * @return string SQL TRUNCATE TABLE query
1699 * @see parseTRUNCATETABLE()
1700 */
1701 protected function compileTRUNCATETABLE(array $components) {
1702
1703 // Make query:
1704 $query = 'TRUNCATE TABLE ' . $components['TABLE'];
1705
1706 // Return query
1707 return $query;
1708 }
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723 /**************************************
1724 *
1725 * Compiling queries, helper functions for parts of queries
1726 *
1727 **************************************/
1728
1729 /**
1730 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1731 * Can also compile field lists for ORDER BY and GROUP BY.
1732 *
1733 * @param array Array of select fields, (made with ->parseFieldList())
1734 * @param boolean Whether comments should be compiled
1735 * @return string Select field string
1736 * @see parseFieldList()
1737 */
1738 public function compileFieldList($selectFields, $compileComments = TRUE) {
1739
1740 // Prepare buffer variable:
1741 $fields = '';
1742
1743 // Traverse the selectFields if any:
1744 if (is_array($selectFields)) {
1745 $outputParts = array();
1746 foreach($selectFields as $k => $v) {
1747
1748 // Detecting type:
1749 switch($v['type']) {
1750 case 'function':
1751 $outputParts[$k] = $v['function'].'('.$v['func_content'].')';
1752 break;
1753 case 'flow-control':
1754 if ($v['flow-control']['type'] === 'CASE') {
1755 $outputParts[$k] = $this->compileCaseStatement($v['flow-control']);
1756 }
1757 break;
1758 case 'field':
1759 $outputParts[$k] = ($v['distinct']?$v['distinct']:'').($v['table']?$v['table'].'.':'').$v['field'];
1760 break;
1761 }
1762
1763 // Alias:
1764 if ($v['as']) {
1765 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1766 }
1767
1768 // Specifically for ORDER BY and GROUP BY field lists:
1769 if ($v['sortDir']) {
1770 $outputParts[$k].= ' '.$v['sortDir'];
1771 }
1772 }
1773 if ($compileComments && $selectFields[0]['comments']) {
1774 $fields = $selectFields[0]['comments'] . ' ';
1775 }
1776 $fields .= implode(', ', $outputParts);
1777 }
1778
1779 return $fields;
1780 }
1781
1782 /**
1783 * Compiles a CASE ... WHEN flow-control construct based on input array (made with ->parseCaseStatement())
1784 *
1785 * @param array Array of case components, (made with ->parseCaseStatement())
1786 * @return string case when string
1787 * @see parseCaseStatement()
1788 */
1789 protected function compileCaseStatement(array $components) {
1790 $statement = 'CASE';
1791 if (isset($components['case_field'])) {
1792 $statement .= ' ' . $components['case_field'];
1793 } elseif (isset($components['case_value'])) {
1794 $statement .= ' ' . $components['case_value'][1] . $components['case_value'][0] . $components['case_value'][1];
1795 }
1796 foreach ($components['when'] as $when) {
1797 $statement .= ' WHEN ';
1798 $statement .= $this->compileWhereClause($when['when_value']);
1799 $statement .= ' THEN ';
1800 $statement .= $when['then_value'][1] . $when['then_value'][0] . $when['then_value'][1];
1801 }
1802 if (isset($components['else'])) {
1803 $statement .= ' ELSE ';
1804 $statement .= $components['else'][1] . $components['else'][0] . $components['else'][1];
1805 }
1806 $statement .= ' END';
1807 return $statement;
1808 }
1809
1810 /**
1811 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1812 *
1813 * @param array Array of table names, (made with ->parseFromTables())
1814 * @return string Table name string
1815 * @see parseFromTables()
1816 */
1817 public function compileFromTables($tablesArray) {
1818
1819 // Prepare buffer variable:
1820 $outputParts = array();
1821
1822 // Traverse the table names:
1823 if (is_array($tablesArray)) {
1824 foreach ($tablesArray as $k => $v) {
1825
1826 // Set table name:
1827 $outputParts[$k] = $v['table'];
1828
1829 // Add alias AS if there:
1830 if ($v['as']) {
1831 $outputParts[$k] .= ' ' . $v['as_keyword'] . ' ' . $v['as'];
1832 }
1833
1834 if (is_array($v['JOIN'])) {
1835 foreach ($v['JOIN'] as $join) {
1836 $outputParts[$k] .= ' ' . $join['type'] . ' ' . $join['withTable'];
1837 // Add alias AS if there:
1838 if (isset($join['as']) && $join['as']) {
1839 $outputParts[$k] .= ' ' . $join['as_keyword'] . ' ' . $join['as'];
1840 }
1841 $outputParts[$k] .= ' ON ';
1842 $outputParts[$k] .= ($join['ON'][0]['table']) ? $join['ON'][0]['table'] . '.' : '';
1843 $outputParts[$k] .= $join['ON'][0]['field'];
1844 $outputParts[$k] .= '=';
1845 $outputParts[$k] .= ($join['ON'][1]['table']) ? $join['ON'][1]['table'] . '.' : '';
1846 $outputParts[$k] .= $join['ON'][1]['field'];
1847 }
1848 }
1849 }
1850 }
1851
1852 // Return imploded buffer:
1853 return implode(', ', $outputParts);
1854 }
1855
1856 /**
1857 * Implodes an array of WHERE clause configuration into a WHERE clause.
1858 *
1859 * @param array WHERE clause configuration
1860 * @return string WHERE clause as string.
1861 * @see explodeWhereClause()
1862 */
1863 public function compileWhereClause($clauseArray) {
1864
1865 // Prepare buffer variable:
1866 $output = '';
1867
1868 // Traverse clause array:
1869 if (is_array($clauseArray)) {
1870 foreach ($clauseArray as $k => $v) {
1871
1872 // Set operator:
1873 $output .= $v['operator'] ? ' ' . $v['operator'] : '';
1874
1875 // Look for sublevel:
1876 if (is_array($v['sub'])) {
1877 $output .= ' (' . trim($this->compileWhereClause($v['sub'])) . ')';
1878 } elseif (isset($v['func']) && $v['func']['type'] === 'EXISTS') {
1879 $output .= ' ' . trim($v['modifier']) . ' EXISTS (' . $this->compileSELECT($v['func']['subquery']) . ')';
1880 } else {
1881
1882 if (isset($v['func']) && $v['func']['type'] === 'LOCATE') {
1883 $output .= ' ' . trim($v['modifier']) . ' LOCATE(';
1884 $output .= $v['func']['substr'][1] . $v['func']['substr'][0] . $v['func']['substr'][1];
1885 $output .= ', ' . ($v['func']['table'] ? $v['func']['table'] . '.' : '') . $v['func']['field'];
1886 $output .= isset($v['func']['pos']) ? ', ' . $v['func']['pos'][0] : '';
1887 $output .= ')';
1888 } else {
1889
1890 // Set field/table with modifying prefix if any:
1891 $output .= ' ' . trim($v['modifier'] . ' ' . ($v['table'] ? $v['table'] . '.' : '') . $v['field']);
1892
1893 // Set calculation, if any:
1894 if ($v['calc']) {
1895 $output .= $v['calc'] . $v['calc_value'][1] . $this->compileAddslashes($v['calc_value'][0]) . $v['calc_value'][1];
1896 }
1897 }
1898
1899 // Set comparator:
1900 if ($v['comparator']) {
1901 $output .= ' ' . $v['comparator'];
1902
1903 // Detecting value type; list or plain:
1904 if (t3lib_div::inList('NOTIN,IN', strtoupper(str_replace(array(' ', "\t", "\r", "\n"), '', $v['comparator'])))) {
1905 if (isset($v['subquery'])) {
1906 $output .= ' (' . $this->compileSELECT($v['subquery']) . ')';
1907 } else {
1908 $valueBuffer = array();
1909 foreach ($v['value'] as $realValue) {
1910 $valueBuffer[] = $realValue[1] . $this->compileAddslashes($realValue[0]) . $realValue[1];
1911 }
1912 $output .= ' (' . trim(implode(',', $valueBuffer)) . ')';
1913 }
1914 } else if (t3lib_div::inList('BETWEEN,NOT BETWEEN', $v['comparator'])) {
1915 $lbound = $v['values'][0];
1916 $ubound = $v['values'][1];
1917 $output .= ' ' . $lbound[1] . $this->compileAddslashes($lbound[0]) . $lbound[1];
1918 $output .= ' AND ';
1919 $output .= $ubound[1] . $this->compileAddslashes($ubound[0]) . $ubound[1];
1920 } else if (isset($v['value']['operator'])) {
1921 $values = array();
1922 foreach ($v['value']['args'] as $fieldDef) {
1923 $values[] = ($fieldDef['table'] ? $fieldDef['table'] . '.' : '') . $fieldDef['field'];
1924 }
1925 $output .= ' ' . $v['value']['operator'] . '(' . implode(',', $values) . ')';
1926 } else {
1927 $output .= ' ' . $v['value'][1] . $this->compileAddslashes($v['value'][0]) . $v['value'][1];
1928 }
1929 }
1930 }
1931 }
1932 }
1933
1934 // Return output buffer:
1935 return $output;
1936 }
1937
1938 /**
1939 * Compile field definition
1940 *
1941 * @param array Field definition parts
1942 * @return string Field definition string
1943 */
1944 public function compileFieldCfg($fieldCfg) {
1945
1946 // Set type:
1947 $cfg = $fieldCfg['fieldType'];
1948
1949 // Add value, if any:
1950 if (strlen($fieldCfg['value'])) {
1951 $cfg.='('.$fieldCfg['value'].')';
1952 }
1953
1954 // Add additional features:
1955 if (is_array($fieldCfg['featureIndex'])) {
1956 foreach($fieldCfg['featureIndex'] as $featureDef) {
1957 $cfg.=' '.$featureDef['keyword'];
1958
1959 // Add value if found:
1960 if (is_array($featureDef['value'])) {
1961 $cfg.=' '.$featureDef['value'][1].$this->compileAddslashes($featureDef['value'][0]).$featureDef['value'][1];
1962 }
1963 }
1964 }
1965
1966 // Return field definition string:
1967 return $cfg;
1968 }
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980 /*************************
1981 *
1982 * Debugging
1983 *
1984 *************************/
1985
1986 /**
1987 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
1988 *
1989 * @param string Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
1990 * @param string SQL string to verify parsability of
1991 * @return mixed Returns array with string 1 and 2 if error, otherwise false
1992 */
1993 public function debug_parseSQLpart($part, $str) {
1994 $retVal = false;
1995
1996 switch($part) {
1997 case 'SELECT':
1998 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFieldList($this->parseFieldList($str)));
1999 break;
2000 case 'FROM':
2001 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileFromTables($this->parseFromTables($str)));
2002 break;
2003 case 'WHERE':
2004 $retVal = $this->debug_parseSQLpartCompare($str,$this->compileWhereClause($this->parseWhereClause($str)));
2005 break;
2006 }
2007 return $retVal;
2008 }
2009
2010 /**
2011 * Compare two query strins by stripping away whitespace.
2012 *
2013 * @param string SQL String 1
2014 * @param string SQL string 2
2015 * @param boolean If true, the strings are compared insensitive to case
2016 * @return mixed Returns array with string 1 and 2 if error, otherwise false
2017 */
2018 public function debug_parseSQLpartCompare($str, $newStr, $caseInsensitive = FALSE) {
2019 if ($caseInsensitive) {
2020 $str1 = strtoupper($str);
2021 $str2 = strtoupper($newStr);
2022 } else {
2023 $str1 = $str;
2024 $str2 = $newStr;
2025 }
2026
2027 // Fixing escaped chars:
2028 $search = array('\0', '\n', '\r', '\Z');
2029 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
2030 $str1 = str_replace($search, $replace, $str1);
2031 $str2 = str_replace($search, $replace, $str2);
2032
2033 # Normally, commented out since they are needed only in tricky cases...
2034 # $str1 = stripslashes($str1);
2035 # $str2 = stripslashes($str2);
2036
2037 if (strcmp(str_replace(array(' ',"\t","\r","\n"),'',$this->trimSQL($str1)),str_replace(array(' ',"\t","\r","\n"),'',$this->trimSQL($str2)))) {
2038 return array(
2039 str_replace(array(' ',"\t","\r","\n"),' ',$str),
2040 str_replace(array(' ',"\t","\r","\n"),' ',$newStr),
2041 );
2042 }
2043 }
2044
2045 /**
2046 * 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
2047 *
2048 * @param string SQL query
2049 * @return string Query if all is well, otherwise exit.
2050 */
2051 public function debug_testSQL($SQLquery) {
2052
2053 // Getting result array:
2054 $parseResult = $this->parseSQL($SQLquery);
2055
2056 // If result array was returned, proceed. Otherwise show error and exit.
2057 if (is_array($parseResult)) {
2058
2059 // Re-compile query:
2060 $newQuery = $this->compileSQL($parseResult);
2061
2062 // TEST the new query:
2063 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
2064
2065 // Return new query if OK, otherwise show error and exit:
2066 if (!is_array($testResult)) {
2067 return $newQuery;
2068 } else {
2069 debug(array('ERROR MESSAGE'=>'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult),'SQL parsing failed:');
2070 exit;
2071 }
2072 } else {
2073 debug(array('query' => $SQLquery, 'ERROR MESSAGE'=>$parseResult),'SQL parsing failed:');
2074 exit;
2075 }
2076 }
2077 }
2078
2079
2080 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']) {
2081 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']);
2082 }
2083
2084 ?>