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