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