Committed DBAL-related changes, see RFC mail from Dec 24th.
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_sqlparser.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2004-2005 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 * 507: function parseALTERTABLE($parseString)
50 * 576: function parseDROPTABLE($parseString)
51 * 609: function parseCREATEDATABASE($parseString)
52 *
53 * SECTION: SQL Parsing, helper functions for parts of queries
54 * 663: function parseFieldList(&$parseString, $stopRegex='')
55 * 781: function parseFromTables(&$parseString, $stopRegex='')
56 * 844: function parseWhereClause(&$parseString, $stopRegex='')
57 * 952: function parseFieldDef(&$parseString, $stopRegex='')
58 *
59 * SECTION: Parsing: Helper functions
60 * 1013: function nextPart(&$parseString,$regex,$trimAll=FALSE)
61 * 1028: function getValue(&$parseString,$comparator='')
62 * 1084: function getValueInQuotes(&$parseString,$quote)
63 * 1110: function parseStripslashes($str)
64 * 1124: function compileAddslashes($str)
65 * 1139: function parseError($msg,$restQuery)
66 * 1153: function trimSQL($str)
67 *
68 * SECTION: Compiling queries
69 * 1182: function compileSQL($components)
70 * 1220: function compileSELECT($components)
71 * 1251: function compileUPDATE($components)
72 * 1279: function compileINSERT($components)
73 * 1319: function compileDELETE($components)
74 * 1339: function compileCREATETABLE($components)
75 * 1370: function compileALTERTABLE($components)
76 *
77 * SECTION: Compiling queries, helper functions for parts of queries
78 * 1423: function compileFieldList($selectFields)
79 * 1465: function compileFromTables($tablesArray)
80 * 1502: function compileWhereClause($clauseArray)
81 * 1556: function compileFieldCfg($fieldCfg)
82 *
83 * SECTION: Debugging
84 * 1605: function debug_parseSQLpart($part,$str)
85 * 1627: function debug_parseSQLpartCompare($str,$newStr,$caseInsensitive=FALSE)
86 * 1660: 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 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)[[:space:]]+');
138 $keyword = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$keyword));
139
140 switch($keyword) {
141 case 'SELECT':
142 // Parsing SELECT query:
143 $result = $this->parseSELECT($parseString);
144 break;
145 case 'UPDATE':
146 // Parsing UPDATE query:
147 $result = $this->parseUPDATE($parseString);
148 break;
149 case 'INSERTINTO':
150 // Parsing INSERT query:
151 $result = $this->parseINSERT($parseString);
152 break;
153 case 'DELETEFROM':
154 // Parsing DELETE query:
155 $result = $this->parseDELETE($parseString);
156 break;
157 case 'EXPLAIN':
158 // Parsing EXPLAIN SELECT query:
159 $result = $this->parseEXPLAIN($parseString);
160 break;
161 case 'DROPTABLE':
162 // Parsing DROP TABLE query:
163 $result = $this->parseDROPTABLE($parseString);
164 break;
165 case 'ALTERTABLE':
166 // Parsing ALTER TABLE query:
167 $result = $this->parseALTERTABLE($parseString);
168 break;
169 case 'CREATETABLE':
170 // Parsing CREATE TABLE query:
171 $result = $this->parseCREATETABLE($parseString);
172 break;
173 case 'CREATEDATABASE':
174 // Parsing CREATE DATABASE query:
175 $result = $this->parseCREATEDATABASE($parseString);
176 break;
177 default:
178 return $this->parseError('"'.$keyword.'" is not a keyword',$parseString);
179 break;
180 }
181
182 return $result;
183 }
184
185 /**
186 * Parsing SELECT query
187 *
188 * @param string SQL string with SELECT query to parse
189 * @return mixed Returns array with components of SELECT query on success, otherwise an error message string.
190 * @see compileSELECT()
191 */
192 function parseSELECT($parseString) {
193
194 // Removing SELECT:
195 $parseString = $this->trimSQL($parseString);
196 $parseString = ltrim(substr($parseString,6)); // REMOVE eregi_replace('^SELECT[[:space:]]+','',$parseString);
197
198 // Init output variable:
199 $result = array();
200 $result['type'] = 'SELECT';
201
202 // Looking for STRAIGHT_JOIN keyword:
203 $result['STRAIGHT_JOIN'] = $this->nextPart($parseString, '^(STRAIGHT_JOIN)[[:space:]]+');
204
205 // Select fields:
206 $result['SELECT'] = $this->parseFieldList($parseString, '^(FROM)[[:space:]]+');
207 if ($this->parse_error) { return $this->parse_error; }
208
209 // Continue if string is not ended:
210 if ($parseString) {
211
212 // Get table list:
213 $result['FROM'] = $this->parseFromTables($parseString, '^(WHERE)[[:space:]]+');
214 if ($this->parse_error) { return $this->parse_error; }
215
216 // If there are more than just the tables (a WHERE clause that would be...)
217 if ($parseString) {
218
219 // Get WHERE clause:
220 $result['WHERE'] = $this->parseWhereClause($parseString, '^(GROUP[[:space:]]+BY|ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
221 if ($this->parse_error) { return $this->parse_error; }
222
223 // If the WHERE clause parsing was stopped by GROUP BY, ORDER BY or LIMIT, then proceed with parsing:
224 if ($this->lastStopKeyWord) {
225
226 // GROUP BY parsing:
227 if ($this->lastStopKeyWord == 'GROUPBY') {
228 $result['GROUPBY'] = $this->parseFieldList($parseString, '^(ORDER[[:space:]]+BY|LIMIT)[[:space:]]+');
229 if ($this->parse_error) { return $this->parse_error; }
230 }
231
232 // ORDER BY parsing:
233 if ($this->lastStopKeyWord == 'ORDERBY') {
234 $result['ORDERBY'] = $this->parseFieldList($parseString, '^(LIMIT)[[:space:]]+');
235 if ($this->parse_error) { return $this->parse_error; }
236 }
237
238 // LIMIT parsing:
239 if ($this->lastStopKeyWord == 'LIMIT') {
240 if (preg_match('/^([0-9]+|[0-9]+[[:space:]]*,[[:space:]]*[0-9]+)$/',trim($parseString))) {
241 $result['LIMIT'] = $parseString;
242 } else {
243 return $this->parseError('No value for limit!',$parseString);
244 }
245 }
246 }
247 }
248 } else return $this->parseError('No table to select from!',$parseString);
249
250 // Return result:
251 return $result;
252 }
253
254 /**
255 * Parsing UPDATE query
256 *
257 * @param string SQL string with UPDATE query to parse
258 * @return mixed Returns array with components of UPDATE query on success, otherwise an error message string.
259 * @see compileUPDATE()
260 */
261 function parseUPDATE($parseString) {
262
263 // Removing UPDATE
264 $parseString = $this->trimSQL($parseString);
265 $parseString = ltrim(substr($parseString,6)); // REMOVE eregi_replace('^UPDATE[[:space:]]+','',$parseString);
266
267 // Init output variable:
268 $result = array();
269 $result['type'] = 'UPDATE';
270
271 // Get table:
272 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
273
274 // Continue if string is not ended:
275 if ($result['TABLE']) {
276 if ($parseString && $this->nextPart($parseString, '^(SET)[[:space:]]+')) {
277
278 $comma = TRUE;
279
280 // Get field/value pairs:
281 while($comma) {
282 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*=')) {
283 $this->nextPart($parseString,'^(=)'); // Strip of "=" sign.
284 $value = $this->getValue($parseString);
285 $result['FIELDS'][$fieldName] = $value;
286 } else return $this->parseError('No fieldname found',$parseString);
287
288 $comma = $this->nextPart($parseString,'^(,)');
289 }
290
291 // WHERE
292 if ($this->nextPart($parseString,'^(WHERE)')) {
293 $result['WHERE'] = $this->parseWhereClause($parseString);
294 if ($this->parse_error) { return $this->parse_error; }
295 }
296 } else return $this->parseError('Query missing SET...',$parseString);
297 } else return $this->parseError('No table found!',$parseString);
298
299 // Should be no more content now:
300 if ($parseString) {
301 return $this->parseError('Still content in clause after parsing!',$parseString);
302 }
303
304 // Return result:
305 return $result;
306 }
307
308 /**
309 * Parsing INSERT query
310 *
311 * @param string SQL string with INSERT query to parse
312 * @return mixed Returns array with components of INSERT query on success, otherwise an error message string.
313 * @see compileINSERT()
314 */
315 function parseINSERT($parseString) {
316
317 // Removing INSERT
318 $parseString = $this->trimSQL($parseString);
319 $parseString = ltrim(substr(ltrim(substr($parseString,6)),4)); // REMOVE eregi_replace('^INSERT[[:space:]]+INTO[[:space:]]+','',$parseString);
320
321 // Init output variable:
322 $result = array();
323 $result['type'] = 'INSERT';
324
325 // Get table:
326 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()');
327
328 if ($result['TABLE']) {
329
330 if ($this->nextPart($parseString,'^(VALUES)[[:space:]]+')) { // In this case there are no field names mentioned in the SQL!
331 // Get values/fieldnames (depending...)
332 $result['VALUES_ONLY'] = $this->getValue($parseString,'IN');
333 if ($this->parse_error) { return $this->parse_error; }
334 } else { // There are apparently fieldnames listed:
335 $fieldNames = $this->getValue($parseString,'_LIST');
336 if ($this->parse_error) { return $this->parse_error; }
337
338 if ($this->nextPart($parseString,'^(VALUES)[[:space:]]+')) { // "VALUES" keyword binds the fieldnames to values:
339
340 $values = $this->getValue($parseString,'IN'); // Using the "getValue" function to get the field list...
341 if ($this->parse_error) { return $this->parse_error; }
342
343 foreach($fieldNames as $k => $fN) {
344 if (preg_match('/^[[:alnum:]_]+$/',$fN)) {
345 if (isset($values[$k])) {
346 if (!isset($result['FIELDS'][$fN])) {
347 $result['FIELDS'][$fN] = $values[$k];
348 } else return $this->parseError('Fieldname ("'.$fN.'") already found in list!',$parseString);
349 } else return $this->parseError('No value set!',$parseString);
350 } else return $this->parseError('Invalid fieldname ("'.$fN.'")',$parseString);
351 }
352 if (isset($values[$k+1])) {
353 return $this->parseError('Too many values in list!',$parseString);
354 }
355 } else return $this->parseError('VALUES keyword expected',$parseString);
356 }
357 } else return $this->parseError('No table found!',$parseString);
358
359 // Should be no more content now:
360 if ($parseString) {
361 return $this->parseError('Still content after parsing!',$parseString);
362 }
363
364 // Return result
365 return $result;
366 }
367
368 /**
369 * Parsing DELETE query
370 *
371 * @param string SQL string with DELETE query to parse
372 * @return mixed Returns array with components of DELETE query on success, otherwise an error message string.
373 * @see compileDELETE()
374 */
375 function parseDELETE($parseString) {
376
377 // Removing DELETE
378 $parseString = $this->trimSQL($parseString);
379 $parseString = ltrim(substr(ltrim(substr($parseString,6)),4)); // REMOVE eregi_replace('^DELETE[[:space:]]+FROM[[:space:]]+','',$parseString);
380
381 // Init output variable:
382 $result = array();
383 $result['type'] = 'DELETE';
384
385 // Get table:
386 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
387
388 if ($result['TABLE']) {
389
390 // WHERE
391 if ($this->nextPart($parseString,'^(WHERE)')) {
392 $result['WHERE'] = $this->parseWhereClause($parseString);
393 if ($this->parse_error) { return $this->parse_error; }
394 }
395 } else return $this->parseError('No table found!',$parseString);
396
397 // Should be no more content now:
398 if ($parseString) {
399 return $this->parseError('Still content in clause after parsing!',$parseString);
400 }
401
402 // Return result:
403 return $result;
404 }
405
406 /**
407 * Parsing EXPLAIN query
408 *
409 * @param string SQL string with EXPLAIN query to parse
410 * @return mixed Returns array with components of EXPLAIN query on success, otherwise an error message string.
411 * @see parseSELECT()
412 */
413 function parseEXPLAIN($parseString) {
414
415 // Removing EXPLAIN
416 $parseString = $this->trimSQL($parseString);
417 $parseString = ltrim(substr($parseString,6)); // REMOVE eregi_replace('^EXPLAIN[[:space:]]+','',$parseString);
418
419 // Init output variable:
420 $result = $this->parseSELECT($parseString);
421 if (is_array($result)) {
422 $result['type'] = 'EXPLAIN';
423 }
424
425 return $result;
426 }
427
428 /**
429 * Parsing CREATE TABLE query
430 *
431 * @param string SQL string starting with CREATE TABLE
432 * @return mixed Returns array with components of CREATE TABLE query on success, otherwise an error message string.
433 * @see compileCREATETABLE()
434 */
435 function parseCREATETABLE($parseString) {
436
437 // Removing CREATE TABLE
438 $parseString = $this->trimSQL($parseString);
439 $parseString = ltrim(substr(ltrim(substr($parseString,6)),5)); // REMOVE eregi_replace('^CREATE[[:space:]]+TABLE[[:space:]]+','',$parseString);
440
441 // Init output variable:
442 $result = array();
443 $result['type'] = 'CREATETABLE';
444
445 // Get table:
446 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]*\(',TRUE);
447
448 if ($result['TABLE']) {
449
450 // While the parseString is not yet empty:
451 while(strlen($parseString)>0) {
452 if ($key = $this->nextPart($parseString, '^(KEY|PRIMARY KEY)([[:space:]]+|\()')) { // Getting key
453 $key = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$key));
454
455 switch($key) {
456 case 'PRIMARYKEY':
457 $result['KEYS'][$key] = $this->getValue($parseString,'_LIST');
458 if ($this->parse_error) { return $this->parse_error; }
459 break;
460 case 'KEY':
461 if ($keyName = $this->nextPart($parseString, '^([[:alnum:]_]+)([[:space:]]+|\()')) {
462 $result['KEYS'][$keyName] = $this->getValue($parseString,'_LIST');
463 if ($this->parse_error) { return $this->parse_error; }
464 } else return $this->parseError('No keyname found',$parseString);
465 break;
466 }
467 } elseif ($fieldName = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) { // Getting field:
468 $result['FIELDS'][$fieldName]['definition'] = $this->parseFieldDef($parseString);
469 if ($this->parse_error) { return $this->parse_error; }
470 }
471
472 // Finding delimiter:
473 $delim = $this->nextPart($parseString, '^(,|\))');
474 if (!$delim) {
475 return $this->parseError('No delimiter found',$parseString);
476 } elseif ($delim==')') {
477 break;
478 }
479 }
480
481 // Finding what is after the table definition - table type in MySQL
482 if ($delim==')') {
483 if ($this->nextPart($parseString, '^(TYPE[[:space:]]*=)')) {
484 $result['tableType'] = $parseString;
485 $parseString = '';
486 }
487 } else return $this->parseError('No fieldname found!',$parseString);
488
489 // Getting table type
490 } else return $this->parseError('No table found!',$parseString);
491
492 // Should be no more content now:
493 if ($parseString) {
494 return $this->parseError('Still content in clause after parsing!',$parseString);
495 }
496
497 return $result;
498 }
499
500 /**
501 * Parsing ALTER TABLE query
502 *
503 * @param string SQL string starting with ALTER TABLE
504 * @return mixed Returns array with components of ALTER TABLE query on success, otherwise an error message string.
505 * @see compileALTERTABLE()
506 */
507 function parseALTERTABLE($parseString) {
508
509 // Removing ALTER TABLE
510 $parseString = $this->trimSQL($parseString);
511 $parseString = ltrim(substr(ltrim(substr($parseString,5)),5)); // REMOVE eregi_replace('^ALTER[[:space:]]+TABLE[[:space:]]+','',$parseString);
512
513 // Init output variable:
514 $result = array();
515 $result['type'] = 'ALTERTABLE';
516
517 // Get table:
518 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
519
520 if ($result['TABLE']) {
521 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:]]+|\()')) {
522 $actionKey = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$result['action']));
523
524 // Getting field:
525 if (t3lib_div::inList('ADDPRIMARYKEY,DROPPRIMARYKEY',$actionKey) || $fieldKey = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
526
527 switch($actionKey) {
528 case 'ADD':
529 $result['FIELD'] = $fieldKey;
530 $result['definition'] = $this->parseFieldDef($parseString);
531 if ($this->parse_error) { return $this->parse_error; }
532 break;
533 case 'DROP':
534 case 'RENAME':
535 $result['FIELD'] = $fieldKey;
536 break;
537 case 'CHANGE':
538 $result['FIELD'] = $fieldKey;
539 if ($result['newField'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+')) {
540 $result['definition'] = $this->parseFieldDef($parseString);
541 if ($this->parse_error) { return $this->parse_error; }
542 } else return $this->parseError('No NEW field name found',$parseString);
543 break;
544
545 case 'ADDKEY':
546 case 'ADDPRIMARYKEY':
547 $result['KEY'] = $fieldKey;
548 $result['fields'] = $this->getValue($parseString,'_LIST');
549 if ($this->parse_error) { return $this->parse_error; }
550 break;
551 case 'DROPKEY':
552 $result['KEY'] = $fieldKey;
553 break;
554 case 'DROPPRIMARYKEY':
555 // ??? todo!
556 break;
557 }
558 } else return $this->parseError('No field name found',$parseString);
559 } else return $this->parseError('No action CHANGE, DROP or ADD found!',$parseString);
560 } else return $this->parseError('No table found!',$parseString);
561
562 // Should be no more content now:
563 if ($parseString) {
564 return $this->parseError('Still content in clause after parsing!',$parseString);
565 }
566
567 return $result;
568 }
569
570 /**
571 * Parsing DROP TABLE query
572 *
573 * @param string SQL string starting with DROP TABLE
574 * @return mixed Returns array with components of DROP TABLE query on success, otherwise an error message string.
575 */
576 function parseDROPTABLE($parseString) {
577
578 // Removing DROP TABLE
579 $parseString = $this->trimSQL($parseString);
580 $parseString = ltrim(substr(ltrim(substr($parseString,4)),5)); // eregi_replace('^DROP[[:space:]]+TABLE[[:space:]]+','',$parseString);
581
582 // Init output variable:
583 $result = array();
584 $result['type'] = 'DROPTABLE';
585
586 // IF EXISTS
587 $result['ifExists'] = $this->nextPart($parseString, '^(IF[[:space:]]+EXISTS[[:space:]]+)');
588
589 // Get table:
590 $result['TABLE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
591
592 if ($result['TABLE']) {
593
594 // Should be no more content now:
595 if ($parseString) {
596 return $this->parseError('Still content in clause after parsing!',$parseString);
597 }
598
599 return $result;
600 } else return $this->parseError('No table found!',$parseString);
601 }
602
603 /**
604 * Parsing CREATE DATABASE query
605 *
606 * @param string SQL string starting with CREATE DATABASE
607 * @return mixed Returns array with components of CREATE DATABASE query on success, otherwise an error message string.
608 */
609 function parseCREATEDATABASE($parseString) {
610
611 // Removing CREATE DATABASE
612 $parseString = $this->trimSQL($parseString);
613 $parseString = ltrim(substr(ltrim(substr($parseString,6)),8)); // eregi_replace('^CREATE[[:space:]]+DATABASE[[:space:]]+','',$parseString);
614
615 // Init output variable:
616 $result = array();
617 $result['type'] = 'CREATEDATABASE';
618
619 // Get table:
620 $result['DATABASE'] = $this->nextPart($parseString, '^([[:alnum:]_]+)[[:space:]]+');
621
622 if ($result['DATABASE']) {
623
624 // Should be no more content now:
625 if ($parseString) {
626 return $this->parseError('Still content in clause after parsing!',$parseString);
627 }
628
629 return $result;
630 } else return $this->parseError('No database found!',$parseString);
631 }
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647 /**************************************
648 *
649 * SQL Parsing, helper functions for parts of queries
650 *
651 **************************************/
652
653 /**
654 * Parsing the fields in the "SELECT [$selectFields] FROM" part of a query into an array.
655 * The output from this function can be compiled back into a field list with ->compileFieldList()
656 * 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!
657 *
658 * @param string The string with fieldnames, eg. "title, uid AS myUid, max(tstamp), count(*)" etc. NOTICE: passed by reference!
659 * @param string Regular expressing to STOP parsing, eg. '^(FROM)([[:space:]]*)'
660 * @return array If successful parsing, returns an array, otherwise an error string.
661 * @see compileFieldList()
662 */
663 function parseFieldList(&$parseString, $stopRegex='') {
664
665 $stack = array(); // Contains the parsed content
666
667 if(strlen($parseString)==0) return $stack; // FIXME - should never happen, why does it?
668
669 $pnt = 0; // Pointer to positions in $stack
670 $level = 0; // Indicates the parenthesis level we are at.
671 $loopExit = 0; // Recursivity brake.
672
673 // Prepare variables:
674 $parseString = $this->trimSQL($parseString);
675 $this->lastStopKeyWord = '';
676 $this->parse_error = '';
677
678 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
679 while (strlen($parseString)) {
680
681 // Checking if we are inside / outside parenthesis (in case of a function like count(), max(), min() etc...):
682 if ($level>0) { // Inside parenthesis here (does NOT detect if values in quotes are used, the only token is ")" or "("):
683
684 // Accumulate function content until next () parenthesis:
685 $funcContent = $this->nextPart($parseString,'^([^()]*.)');
686 $stack[$pnt]['func_content.'][] = array(
687 'level' => $level,
688 'func_content' => substr($funcContent,0,-1)
689 );
690 $stack[$pnt]['func_content'].= $funcContent;
691
692 // Detecting ( or )
693 switch(substr($stack[$pnt]['func_content'],-1)) {
694 case '(':
695 $level++;
696 break;
697 case ')':
698 $level--;
699 if (!$level) { // If this was the last parenthesis:
700 $stack[$pnt]['func_content'] = substr($stack[$pnt]['func_content'],0,-1);
701 $parseString = ltrim($parseString); // Remove any whitespace after the parenthesis.
702 }
703 break;
704 }
705 } else { // Outside parenthesis, looking for next field:
706
707 // Looking for a known function (only known functions supported)
708 $func = $this->nextPart($parseString,'^(count|max|min|floor|sum|avg)[[:space:]]*\(');
709 if ($func) {
710 $parseString = trim(substr($parseString,1)); // Strip of "("
711 $stack[$pnt]['type'] = 'function';
712 $stack[$pnt]['function'] = $func;
713 $level++; // increse parenthesis level counter.
714 } else {
715 $stack[$pnt]['distinct'] = $this->nextPart($parseString,'^(distinct[[:space:]]+)');
716 // Otherwise, look for regular fieldname:
717 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]\*._]+)(,|[[:space:]]+)')) {
718 $stack[$pnt]['type'] = 'field';
719
720 // Explode fieldname into field and table:
721 $tableField = explode('.',$fieldName,2);
722 if (count($tableField)==2) {
723 $stack[$pnt]['table'] = $tableField[0];
724 $stack[$pnt]['field'] = $tableField[1];
725 } else {
726 $stack[$pnt]['table'] = '';
727 $stack[$pnt]['field'] = $tableField[0];
728 }
729 } else {
730 return $this->parseError('No field name found as expected in parseFieldList()',$parseString);
731 }
732 }
733 }
734
735 // After a function or field we look for "AS" alias and a comma to separate to the next field in the list:
736 if (!$level) {
737
738 // Looking for "AS" alias:
739 if ($as = $this->nextPart($parseString,'^(AS)[[:space:]]+')) {
740 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)');
741 $stack[$pnt]['as_keyword'] = $as;
742 }
743
744 // Looking for "ASC" or "DESC" keywords (for ORDER BY)
745 if ($sDir = $this->nextPart($parseString,'^(ASC|DESC)([[:space:]]+|,)')) {
746 $stack[$pnt]['sortDir'] = $sDir;
747 }
748
749 // Looking for stop-keywords:
750 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
751 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$this->lastStopKeyWord));
752 return $stack;
753 }
754
755 // Looking for comma (since the stop-keyword did not trigger a return...)
756 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
757 return $this->parseError('No comma found as expected in parseFieldList()',$parseString);
758 }
759
760 // Increasing pointer:
761 $pnt++;
762 }
763
764 // Check recursivity brake:
765 $loopExit++;
766 if ($loopExit>500) {
767 return $this->parseError('More than 500 loops, exiting prematurely in parseFieldList()...',$parseString);
768 }
769 }
770
771 // Return result array:
772 return $stack;
773 }
774
775 /**
776 * Parsing the tablenames in the "FROM [$parseString] WHERE" part of a query into an array.
777 * The success of this parsing determines if that part of the query is supported by TYPO3.
778 *
779 * @param string list of tables, eg. "pages, tt_content" or "pages A, pages B". NOTICE: passed by reference!
780 * @param string Regular expressing to STOP parsing, eg. '^(WHERE)([[:space:]]*)'
781 * @return array If successful parsing, returns an array, otherwise an error string.
782 * @see compileFromTables()
783 */
784 function parseFromTables(&$parseString, $stopRegex='') {
785
786 // Prepare variables:
787 $parseString = $this->trimSQL($parseString);
788 $this->lastStopKeyWord = '';
789 $this->parse_error = '';
790
791 $stack = array(); // Contains the parsed content
792 $pnt = 0; // Pointer to positions in $stack
793 $loopExit = 0; // Recursivity brake.
794
795 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
796 while (strlen($parseString)) {
797 // Looking for the table:
798 if ($stack[$pnt]['table'] = $this->nextPart($parseString,'^([[:alnum:]_]+)(,|[[:space:]]+)')) {
799 // Looking for stop-keywords before fetching potential table alias:
800 if ($stopRegex && ($this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex))) {
801 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$this->lastStopKeyWord));
802 return $stack;
803 }
804 if(!preg_match('/^(LEFT|JOIN)[[:space:]]+/i',$parseString)) {
805 $stack[$pnt]['as_keyword'] = $this->nextPart($parseString,'^(AS[[:space:]]+)');
806 $stack[$pnt]['as'] = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]*');
807 }
808 } else return $this->parseError('No table name found as expected in parseFromTables()!',$parseString);
809
810 // Looking for JOIN
811 if ($join = $this->nextPart($parseString,'^(LEFT[[:space:]]+JOIN|JOIN)[[:space:]]+')) {
812 $stack[$pnt]['JOIN']['type'] = $join;
813 if ($stack[$pnt]['JOIN']['withTable'] = $this->nextPart($parseString,'^([[:alnum:]_]+)[[:space:]]+ON[[:space:]]+',1)) {
814 $field1 = $this->nextPart($parseString,'^([[:alnum:]_.]+)[[:space:]]*=[[:space:]]*',1);
815 $field2 = $this->nextPart($parseString,'^([[:alnum:]_.]+)[[:space:]]+');
816 if ($field1 && $field2) {
817
818 // Explode fields into field and table:
819 $tableField = explode('.',$field1,2);
820 $field1 = array();
821 if (count($tableField)!=2) {
822 $field1['table'] = '';
823 $field1['field'] = $tableField[0];
824 } else {
825 $field1['table'] = $tableField[0];
826 $field1['field'] = $tableField[1];
827 }
828 $tableField = explode('.',$field2,2);
829 $field2 = array();
830 if (count($tableField)!=2) {
831 $field2['table'] = '';
832 $field2['field'] = $tableField[0];
833 } else {
834 $field2['table'] = $tableField[0];
835 $field2['field'] = $tableField[1];
836 }
837 $stack[$pnt]['JOIN']['ON'] = array($field1,$field2);
838 } else return $this->parseError('No join fields found in parseFromTables()!',$parseString);
839 } else return $this->parseError('No join table found in parseFromTables()!',$parseString);
840 }
841
842 // Looking for stop-keywords:
843 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
844 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$this->lastStopKeyWord));
845 return $stack;
846 }
847
848 // Looking for comma:
849 if (strlen($parseString) && !$this->nextPart($parseString,'^(,)')) {
850 return $this->parseError('No comma found as expected in parseFromTables()',$parseString);
851 }
852
853 // Increasing pointer:
854 $pnt++;
855
856 // Check recursivity brake:
857 $loopExit++;
858 if ($loopExit>500) {
859 return $this->parseError('More than 500 loops, exiting prematurely in parseFromTables()...',$parseString);
860 }
861 }
862
863 // Return result array:
864 return $stack;
865 }
866
867 /**
868 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
869 * The success of this parsing determines if that part of the query is supported by TYPO3.
870 *
871 * @param string WHERE clause to parse. NOTICE: passed by reference!
872 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
873 * @return mixed If successful parsing, returns an array, otherwise an error string.
874 */
875 function parseWhereClause(&$parseString, $stopRegex='') {
876
877 // Prepare variables:
878 $parseString = $this->trimSQL($parseString);
879 $this->lastStopKeyWord = '';
880 $this->parse_error = '';
881
882 $stack = array(0 => array()); // Contains the parsed content
883 $pnt = array(0 => 0); // Pointer to positions in $stack
884 $level = 0; // Determines parenthesis level
885 $loopExit = 0; // Recursivity brake.
886
887 // $parseString is continously shortend by the process and we keep parsing it till it is zero:
888 while (strlen($parseString)) {
889
890 // Look for next parenthesis level:
891 $newLevel = $this->nextPart($parseString,'^([(])');
892 if ($newLevel=='(') { // If new level is started, manage stack/pointers:
893 $level++; // Increase level
894 $pnt[$level] = 0; // Reset pointer for this level
895 $stack[$level] = array(); // Reset stack for this level
896 } else { // If no new level is started, just parse the current level:
897
898 // Find "modifyer", eg. "NOT or !"
899 $stack[$level][$pnt[$level]]['modifier'] = trim($this->nextPart($parseString,'^(!|NOT[[:space:]]+)'));
900
901 // Fieldname:
902 if ($fieldName = $this->nextPart($parseString,'^([[:alnum:]._]+)([[:space:]]+|&|<=|>=|<|>|=|!=|IS)')) {
903
904 // Parse field name into field and table:
905 $tableField = explode('.',$fieldName,2);
906 if (count($tableField)==2) {
907 $stack[$level][$pnt[$level]]['table'] = $tableField[0];
908 $stack[$level][$pnt[$level]]['field'] = $tableField[1];
909 } else {
910 $stack[$level][$pnt[$level]]['table'] = '';
911 $stack[$level][$pnt[$level]]['field'] = $tableField[0];
912 }
913 } else {
914 return $this->parseError('No field name found as expected in parseWhereClause()',$parseString);
915 }
916
917 // See if the value is calculated. Support only for "&" (boolean AND) at the moment:
918 $stack[$level][$pnt[$level]]['calc'] = $this->nextPart($parseString,'^(&)');
919 if (strlen($stack[$level][$pnt[$level]]['calc'])) {
920 // Finding value for calculation:
921 $stack[$level][$pnt[$level]]['calc_value'] = $this->getValue($parseString);
922 }
923
924 // Find "comparator":
925 $stack[$level][$pnt[$level]]['comparator'] = $this->nextPart($parseString,'^(<=|>=|<|>|=|!=|NOT[[:space:]]+IN|IN|NOT[[:space:]]+LIKE|LIKE|IS)');
926 if (strlen($stack[$level][$pnt[$level]]['comparator'])) {
927 // Finding value for comparator:
928 $stack[$level][$pnt[$level]]['value'] = $this->getValue($parseString,$stack[$level][$pnt[$level]]['comparator']);
929 if ($this->parse_error) { return $this->parse_error; }
930 }
931
932 // Finished, increase pointer:
933 $pnt[$level]++;
934
935 // Checking if the current level is ended, in that case do stack management:
936 while ($this->nextPart($parseString,'^([)])')) {
937 $level--; // Decrease level:
938 $stack[$level][$pnt[$level]]['sub'] = $stack[$level+1]; // Copy stack
939 $pnt[$level]++; // Increase pointer of the new level
940
941 // Make recursivity check:
942 $loopExit++;
943 if ($loopExit>500) {
944 return $this->parseError('More than 500 loops (in search for exit parenthesis), exiting prematurely in parseWhereClause()...',$parseString);
945 }
946 }
947
948 // Detecting the operator for the next level; support for AND, OR and &&):
949 $op = $this->nextPart($parseString,'^(AND[[:space:]]+NOT|OR[[:space:]]+NOT|AND|OR)(\(|[[:space:]]+)');
950 if ($op) {
951 $stack[$level][$pnt[$level]]['operator'] = $op;
952 } elseif (strlen($parseString)) {
953
954 // Looking for stop-keywords:
955 if ($stopRegex && $this->lastStopKeyWord = $this->nextPart($parseString, $stopRegex)) {
956 $this->lastStopKeyWord = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$this->lastStopKeyWord));
957 return $stack[0];
958 } else {
959 return $this->parseError('No operator, but parsing not finished in parseWhereClause().',$parseString);
960 }
961 }
962 }
963
964 // Make recursivity check:
965 $loopExit++;
966 if ($loopExit>500) {
967 return $this->parseError('More than 500 loops, exiting prematurely in parseWhereClause()...',$parseString);
968 }
969 }
970
971 // Return the stacks lowest level:
972 return $stack[0];
973 }
974
975 /**
976 * Parsing the WHERE clause fields in the "WHERE [$parseString] ..." part of a query into a multidimensional array.
977 * The success of this parsing determines if that part of the query is supported by TYPO3.
978 *
979 * @param string WHERE clause to parse. NOTICE: passed by reference!
980 * @param string Regular expressing to STOP parsing, eg. '^(GROUP BY|ORDER BY|LIMIT)([[:space:]]*)'
981 * @return mixed If successful parsing, returns an array, otherwise an error string.
982 */
983 function parseFieldDef(&$parseString, $stopRegex='') {
984 // Prepare variables:
985 $parseString = $this->trimSQL($parseString);
986 $this->lastStopKeyWord = '';
987 $this->parse_error = '';
988
989 $result = array();
990
991 // Field type:
992 if ($result['fieldType'] = $this->nextPart($parseString,'^(int|smallint|tinyint|mediumint|bigint|double|numeric|decimal|varchar|char|text|tinytext|mediumtext|longtext|blob|tinyblob|mediumblob|longblob)([[:space:],]+|\()')) {
993
994 // Looking for value:
995 if (substr($parseString,0,1)=='(') {
996 $parseString = substr($parseString,1);
997 if ($result['value'] = $this->nextPart($parseString,'^([^)]*)')) {
998 $parseString = ltrim(substr($parseString,1));
999 } else return $this->parseError('No end-parenthesis for value found in parseFieldDef()!',$parseString);
1000 }
1001
1002 // Looking for keywords
1003 while($keyword = $this->nextPart($parseString,'^(DEFAULT|NOT[[:space:]]+NULL|AUTO_INCREMENT|UNSIGNED)([[:space:]]+|,|\))')) {
1004 $keywordCmp = strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$keyword));
1005
1006 $result['featureIndex'][$keywordCmp]['keyword'] = $keyword;
1007
1008 switch($keywordCmp) {
1009 case 'DEFAULT':
1010 $result['featureIndex'][$keywordCmp]['value'] = $this->getValue($parseString);
1011 break;
1012 }
1013 }
1014 } else {
1015 return $this->parseError('Field type unknown in parseFieldDef()!',$parseString);
1016 }
1017
1018 return $result;
1019 }
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031 /************************************
1032 *
1033 * Parsing: Helper functions
1034 *
1035 ************************************/
1036
1037 /**
1038 * Strips off a part of the parseString and returns the matching part.
1039 * Helper function for the parsing methods.
1040 *
1041 * @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.
1042 * @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())
1043 * @param boolean If set the full match of the regex is stripped of the beginning of the string!
1044 * @return string The value of the first parenthesis level of the REGEX.
1045 */
1046 function nextPart(&$parseString,$regex,$trimAll=FALSE) {
1047 if (preg_match('/'.$regex.'/i',$parseString.' ', $reg)) { // Adding space char because [[:space:]]+ is often a requirement in regex's
1048 $parseString = ltrim(substr($parseString,strlen($reg[$trimAll?0:1])));
1049 return $reg[1];
1050 }
1051 }
1052
1053 /**
1054 * Finds value in beginning of $parseString, returns result and strips it of parseString
1055 *
1056 * @param string The parseString, eg. "(0,1,2,3) ..." or "('asdf','qwer') ..." or "1234 ..." or "'My string value here' ..."
1057 * @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)
1058 * @return string The value (string/integer). Otherwise an array with error message in first key (0)
1059 */
1060 function getValue(&$parseString,$comparator='') {
1061 if (t3lib_div::inList('NOTIN,IN,_LIST',strtoupper(str_replace(array(' ',"\n","\r","\t"),'',$comparator)))) { // List of values:
1062 if ($this->nextPart($parseString,'^([(])')) {
1063 $listValues = array();
1064 $comma=',';
1065
1066 while($comma==',') {
1067 $listValues[] = $this->getValue($parseString);
1068 $comma = $this->nextPart($parseString,'^([,])');
1069 }
1070
1071 $out = $this->nextPart($parseString,'^([)])');
1072 if ($out) {
1073 if ($comparator=='_LIST') {
1074 $kVals = array();
1075 foreach ($listValues as $vArr) {
1076 $kVals[] = $vArr[0];
1077 }
1078 return $kVals;
1079 } else {
1080 return $listValues;
1081 }
1082 } else return array($this->parseError('No ) parenthesis in list',$parseString));
1083 } else return array($this->parseError('No ( parenthesis starting the list',$parseString));
1084
1085 } else { // Just plain string value, in quotes or not:
1086
1087 // Quote?
1088 $firstChar = substr($parseString,0,1);
1089
1090 switch($firstChar) {
1091 case '"':
1092 return array($this->getValueInQuotes($parseString,'"'),'"');
1093 break;
1094 case "'":
1095 return array($this->getValueInQuotes($parseString,"'"),"'");
1096 break;
1097 default:
1098 if (preg_match('/^([[:alnum:]._-]+)/i',$parseString, $reg)) {
1099 $parseString = ltrim(substr($parseString,strlen($reg[0])));
1100 return array($reg[1]);
1101 }
1102 break;
1103 }
1104 }
1105 }
1106
1107 /**
1108 * Get value in quotes from $parseString.
1109 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1110 *
1111 * @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.
1112 * @param string The quote used; input either " or '
1113 * @return string The value, passed through stripslashes() !
1114 */
1115 function getValueInQuotes(&$parseString,$quote) {
1116
1117 $parts = explode($quote,substr($parseString,1));
1118 $buffer = '';
1119 foreach($parts as $k => $v) {
1120 $buffer.=$v;
1121
1122 unset($reg);
1123 //preg_match('/[\]*$/',$v,$reg); // does not work. what is the *exact* meaning of the next line?
1124 ereg('[\]*$',$v,$reg);
1125 if (strlen($reg[0])%2) {
1126 $buffer.=$quote;
1127 } else {
1128 $parseString = ltrim(substr($parseString,strlen($buffer)+2));
1129 return $this->parseStripslashes($buffer);
1130 }
1131 }
1132 }
1133
1134 /**
1135 * Strip slashes function used for parsing
1136 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1137 *
1138 * @param string Input string
1139 * @return string Output string
1140 */
1141 function parseStripslashes($str) {
1142 $search = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1143 $replace = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1144
1145 return str_replace($search, $replace, $str);
1146 }
1147
1148 /**
1149 * Add slashes function used for compiling queries
1150 * NOTICE: If a query being parsed was prepared for another database than MySQL this function should probably be changed
1151 *
1152 * @param string Input string
1153 * @return string Output string
1154 */
1155 function compileAddslashes($str) {
1156 return $str;
1157 $search = array('\\', '\'', '"', "\x00", "\x0a", "\x0d", "\x1a");
1158 $replace = array('\\\\', '\\\'', '\\"', '\0', '\n', '\r', '\Z');
1159
1160 return str_replace($search, $replace, $str);
1161 }
1162
1163 /**
1164 * Setting the internal error message value, $this->parse_error and returns that value.
1165 *
1166 * @param string Input error message
1167 * @param string Remaining query to parse.
1168 * @return string Error message.
1169 */
1170 function parseError($msg,$restQuery) {
1171 $this->parse_error = 'SQL engine parse ERROR: '.$msg.': near "'.substr($restQuery,0,50).'"';
1172 return $this->parse_error;
1173 }
1174
1175 /**
1176 * Trimming SQL as preparation for parsing.
1177 * ";" in the end is stripped of.
1178 * White space is trimmed away around the value
1179 * A single space-char is added in the end
1180 *
1181 * @param string Input string
1182 * @return string Output string
1183 */
1184 function trimSQL($str) {
1185 return trim(rtrim($str, "; \r\n\t")).' ';
1186 //return trim(ereg_replace('[[:space:];]*$','',$str)).' ';
1187 }
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200 /*************************
1201 *
1202 * Compiling queries
1203 *
1204 *************************/
1205
1206 /**
1207 * Compiles an SQL query from components
1208 *
1209 * @param array Array of SQL query components
1210 * @return string SQL query
1211 * @see parseSQL()
1212 */
1213 function compileSQL($components) {
1214 switch($components['type']) {
1215 case 'SELECT':
1216 $query = $this->compileSELECT($components);
1217 break;
1218 case 'UPDATE':
1219 $query = $this->compileUPDATE($components);
1220 break;
1221 case 'INSERT':
1222 $query = $this->compileINSERT($components);
1223 break;
1224 case 'DELETE':
1225 $query = $this->compileDELETE($components);
1226 break;
1227 case 'EXPLAIN':
1228 $query = 'EXPLAIN '.$this->compileSELECT($components);
1229 break;
1230 case 'DROPTABLE':
1231 $query = 'DROP TABLE'.($components['ifExists']?' IF EXISTS':'').' '.$components['TABLE'];
1232 break;
1233 case 'CREATETABLE':
1234 $query = $this->compileCREATETABLE($components);
1235 break;
1236 case 'ALTERTABLE':
1237 $query = $this->compileALTERTABLE($components);
1238 break;
1239 }
1240
1241 return $query;
1242 }
1243
1244 /**
1245 * Compiles a SELECT statement from components array
1246 *
1247 * @param array Array of SQL query components
1248 * @return string SQL SELECT query
1249 * @see parseSELECT()
1250 */
1251 function compileSELECT($components) {
1252
1253 // Initialize:
1254 $where = $this->compileWhereClause($components['WHERE']);
1255 $groupBy = $this->compileFieldList($components['GROUPBY']);
1256 $orderBy = $this->compileFieldList($components['ORDERBY']);
1257 $limit = $components['LIMIT'];
1258
1259 // Make query:
1260 $query = 'SELECT '.($components['STRAIGHT_JOIN'] ? $components['STRAIGHT_JOIN'].'' : '').'
1261 '.$this->compileFieldList($components['SELECT']).'
1262 FROM '.$this->compileFromTables($components['FROM']).
1263 (strlen($where)?'
1264 WHERE '.$where : '').
1265 (strlen($groupBy)?'
1266 GROUP BY '.$groupBy : '').
1267 (strlen($orderBy)?'
1268 ORDER BY '.$orderBy : '').
1269 (strlen($limit)?'
1270 LIMIT '.$limit : '');
1271
1272 return $query;
1273 }
1274
1275 /**
1276 * Compiles an UPDATE statement from components array
1277 *
1278 * @param array Array of SQL query components
1279 * @return string SQL UPDATE query
1280 * @see parseUPDATE()
1281 */
1282 function compileUPDATE($components) {
1283
1284 // Where clause:
1285 $where = $this->compileWhereClause($components['WHERE']);
1286
1287 // Fields
1288 $fields = array();
1289 foreach($components['FIELDS'] as $fN => $fV) {
1290 $fields[]=$fN.'='.$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1291 }
1292
1293 // Make query:
1294 $query = 'UPDATE '.$components['TABLE'].' SET
1295 '.implode(',
1296 ',$fields).'
1297 '.(strlen($where)?'
1298 WHERE '.$where : '');
1299
1300 return $query;
1301 }
1302
1303 /**
1304 * Compiles an INSERT statement from components array
1305 *
1306 * @param array Array of SQL query components
1307 * @return string SQL INSERT query
1308 * @see parseINSERT()
1309 */
1310 function compileINSERT($components) {
1311
1312 if ($components['VALUES_ONLY']) {
1313 // Initialize:
1314 $fields = array();
1315 foreach($components['VALUES_ONLY'] as $fV) {
1316 $fields[]=$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1317 }
1318
1319 // Make query:
1320 $query = 'INSERT INTO '.$components['TABLE'].'
1321 VALUES
1322 ('.implode(',
1323 ',$fields).')';
1324 } else {
1325 // Initialize:
1326 $fields = array();
1327 foreach($components['FIELDS'] as $fN => $fV) {
1328 $fields[$fN]=$fV[1].$this->compileAddslashes($fV[0]).$fV[1];
1329 }
1330
1331 // Make query:
1332 $query = 'INSERT INTO '.$components['TABLE'].'
1333 ('.implode(',
1334 ',array_keys($fields)).')
1335 VALUES
1336 ('.implode(',
1337 ',$fields).')';
1338 }
1339
1340 return $query;
1341 }
1342
1343 /**
1344 * Compiles an DELETE statement from components array
1345 *
1346 * @param array Array of SQL query components
1347 * @return string SQL DELETE query
1348 * @see parseDELETE()
1349 */
1350 function compileDELETE($components) {
1351
1352 // Where clause:
1353 $where = $this->compileWhereClause($components['WHERE']);
1354
1355 // Make query:
1356 $query = 'DELETE FROM '.$components['TABLE'].
1357 (strlen($where)?'
1358 WHERE '.$where : '');
1359
1360 return $query;
1361 }
1362
1363 /**
1364 * Compiles a CREATE TABLE statement from components array
1365 *
1366 * @param array Array of SQL query components
1367 * @return string SQL CREATE TABLE query
1368 * @see parseCREATETABLE()
1369 */
1370 function compileCREATETABLE($components) {
1371
1372 // Create fields and keys:
1373 $fieldsKeys = array();
1374 foreach($components['FIELDS'] as $fN => $fCfg) {
1375 $fieldsKeys[]=$fN.' '.$this->compileFieldCfg($fCfg['definition']);
1376 }
1377 foreach($components['KEYS'] as $kN => $kCfg) {
1378 if ($kN == 'PRIMARYKEY') {
1379 $fieldsKeys[]='PRIMARY KEY ('.implode(',', $kCfg).')';
1380 } else {
1381 $fieldsKeys[]='KEY '.$kN.' ('.implode(',', $kCfg).')';
1382 }
1383 }
1384
1385 // Make query:
1386 $query = 'CREATE TABLE '.$components['TABLE'].' (
1387 '.implode(',
1388 ', $fieldsKeys).'
1389 )'.($components['tableType'] ? ' TYPE='.$components['tableType'] : '');
1390
1391 return $query;
1392 }
1393
1394 /**
1395 * Compiles an ALTER TABLE statement from components array
1396 *
1397 * @param array Array of SQL query components
1398 * @return string SQL ALTER TABLE query
1399 * @see parseALTERTABLE()
1400 */
1401 function compileALTERTABLE($components) {
1402
1403 // Make query:
1404 $query = 'ALTER TABLE '.$components['TABLE'].' '.$components['action'].' '.($components['FIELD']?$components['FIELD']:$components['KEY']);
1405
1406 // Based on action, add the final part:
1407 switch(strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$components['action']))) {
1408 case 'ADD':
1409 $query.=' '.$this->compileFieldCfg($components['definition']);
1410 break;
1411 case 'CHANGE':
1412 $query.=' '.$components['newField'].' '.$this->compileFieldCfg($components['definition']);
1413 break;
1414 case 'DROP':
1415 case 'DROPKEY':
1416 break;
1417 case 'ADDKEY':
1418 case 'ADDPRIMARYKEY':
1419 $query.=' ('.implode(',',$components['fields']).')';
1420 break;
1421 }
1422
1423 // Return query
1424 return $query;
1425 }
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440 /**************************************
1441 *
1442 * Compiling queries, helper functions for parts of queries
1443 *
1444 **************************************/
1445
1446 /**
1447 * Compiles a "SELECT [output] FROM..:" field list based on input array (made with ->parseFieldList())
1448 * Can also compile field lists for ORDER BY and GROUP BY.
1449 *
1450 * @param array Array of select fields, (made with ->parseFieldList())
1451 * @return string Select field string
1452 * @see parseFieldList()
1453 */
1454 function compileFieldList($selectFields) {
1455
1456 // Prepare buffer variable:
1457 $outputParts = array();
1458
1459 // Traverse the selectFields if any:
1460 if (is_array($selectFields)) {
1461 foreach($selectFields as $k => $v) {
1462
1463 // Detecting type:
1464 switch($v['type']) {
1465 case 'function':
1466 $outputParts[$k] = $v['function'].'('.$v['func_content'].')';
1467 break;
1468 case 'field':
1469 $outputParts[$k] = ($v['distinct']?$v['distinct']:'').($v['table']?$v['table'].'.':'').$v['field'];
1470 break;
1471 }
1472
1473 // Alias:
1474 if ($v['as']) {
1475 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1476 }
1477
1478 // Specifically for ORDER BY and GROUP BY field lists:
1479 if ($v['sortDir']) {
1480 $outputParts[$k].= ' '.$v['sortDir'];
1481 }
1482 }
1483 }
1484
1485 // Return imploded buffer:
1486 return implode(', ',$outputParts);
1487 }
1488
1489 /**
1490 * Compiles a "FROM [output] WHERE..:" table list based on input array (made with ->parseFromTables())
1491 *
1492 * @param array Array of table names, (made with ->parseFromTables())
1493 * @return string Table name string
1494 * @see parseFromTables()
1495 */
1496 function compileFromTables($tablesArray) {
1497
1498 // Prepare buffer variable:
1499 $outputParts = array();
1500
1501 // Traverse the table names:
1502 if (is_array($tablesArray)) {
1503 foreach($tablesArray as $k => $v) {
1504
1505 // Set table name:
1506 $outputParts[$k] = $v['table'];
1507
1508 // Add alias AS if there:
1509 if ($v['as']) {
1510 $outputParts[$k].= ' '.$v['as_keyword'].' '.$v['as'];
1511 }
1512
1513 if (is_array($v['JOIN'])) {
1514 $outputParts[$k] .= ' '.$v['JOIN']['type'].' '.$v['JOIN']['withTable'].' ON ';
1515 $outputParts[$k] .= ($v['JOIN']['ON'][0]['table']) ? $v['JOIN']['ON'][0]['table'].'.' : '';
1516 $outputParts[$k] .= $v['JOIN']['ON'][0]['field'];
1517 $outputParts[$k] .= '=';
1518 $outputParts[$k] .= ($v['JOIN']['ON'][1]['table']) ? $v['JOIN']['ON'][0]['table'].'.' : '';
1519 $outputParts[$k] .= $v['JOIN']['ON'][1]['field'];
1520 }
1521 }
1522 }
1523
1524 // Return imploded buffer:
1525 return implode(', ',$outputParts);
1526 }
1527
1528 /**
1529 * Implodes an array of WHERE clause configuration into a WHERE clause.
1530 * NOTICE: MIGHT BY A TEMPORARY FUNCTION. Use for debugging only!
1531 * BUT IT IS NEEDED FOR DBAL - MAKE IT PERMANENT?!?!
1532 *
1533 * @param array WHERE clause configuration
1534 * @return string WHERE clause as string.
1535 * @see explodeWhereClause()
1536 */
1537 function compileWhereClause($clauseArray) {
1538
1539 // Prepare buffer variable:
1540 $output='';
1541
1542 // Traverse clause array:
1543 if (is_array($clauseArray)) {
1544 foreach($clauseArray as $k => $v) {
1545
1546 // Set operator:
1547 $output.=$v['operator'] ? ' '.$v['operator'] : '';
1548
1549 // Look for sublevel:
1550 if (is_array($v['sub'])) {
1551 $output.=' ('.trim($this->compileWhereClause($v['sub'])).')';
1552 } else {
1553
1554 // Set field/table with modifying prefix if any:
1555 $output.=' '.trim($v['modifier'].' '.($v['table']?$v['table'].'.':'').$v['field']);
1556
1557 // Set calculation, if any:
1558 if ($v['calc']) {
1559 $output.=$v['calc'].$v['calc_value'][1].$this->compileAddslashes($v['calc_value'][0]).$v['calc_value'][1];
1560 }
1561
1562 // Set comparator:
1563 if ($v['comparator']) {
1564 $output.=' '.$v['comparator'];
1565
1566 // Detecting value type; list or plain:
1567 if (t3lib_div::inList('NOTIN,IN',strtoupper(str_replace(array(' ',"\t","\r","\n"),'',$v['comparator'])))) {
1568 $valueBuffer = array();
1569 foreach($v['value'] as $realValue) {
1570 $valueBuffer[]=$realValue[1].$this->compileAddslashes($realValue[0]).$realValue[1];
1571 }
1572 $output.=' ('.trim(implode(',',$valueBuffer)).')';
1573 } else {
1574 $output.=' '.$v['value'][1].$this->compileAddslashes($v['value'][0]).$v['value'][1];
1575 }
1576 }
1577 }
1578 }
1579 }
1580
1581 // Return output buffer:
1582 return $output;
1583 }
1584
1585 /**
1586 * Compile field definition
1587 *
1588 * @param array Field definition parts
1589 * @return string Field definition string
1590 */
1591 function compileFieldCfg($fieldCfg) {
1592
1593 // Set type:
1594 $cfg = $fieldCfg['fieldType'];
1595
1596 // Add value, if any:
1597 if (strlen($fieldCfg['value'])) {
1598 $cfg.='('.$fieldCfg['value'].')';
1599 }
1600
1601 // Add additional features:
1602 if (is_array($fieldCfg['featureIndex'])) {
1603 foreach($fieldCfg['featureIndex'] as $featureDef) {
1604 $cfg.=' '.$featureDef['keyword'];
1605
1606 // Add value if found:
1607 if (is_array($featureDef['value'])) {
1608 $cfg.=' '.$featureDef['value'][1].$this->compileAddslashes($featureDef['value'][0]).$featureDef['value'][1];
1609 }
1610 }
1611 }
1612
1613 // Return field definition string:
1614 return $cfg;
1615 }
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627 /*************************
1628 *
1629 * Debugging
1630 *
1631 *************************/
1632
1633 /**
1634 * Check parsability of input SQL part string; Will parse and re-compile after which it is compared
1635 *
1636 * @param string Part definition of string; "SELECT" = fieldlist (also ORDER BY and GROUP BY), "FROM" = table list, "WHERE" = Where clause.
1637 * @param string SQL string to verify parsability of
1638 * @return mixed Returns array with string 1 and 2 if error, otherwise false
1639 */
1640 function debug_parseSQLpart($part,$str) {
1641 switch($part) {
1642 case 'SELECT':
1643 return $this->debug_parseSQLpartCompare($str,$this->compileFieldList($this->parseFieldList($str)));
1644 break;
1645 case 'FROM':
1646 return $this->debug_parseSQLpartCompare($str,$this->compileFromTables($this->parseFromTables($str)));
1647 break;
1648 case 'WHERE':
1649 return $this->debug_parseSQLpartCompare($str,$this->compileWhereClause($this->parseWhereClause($str)));
1650 break;
1651 }
1652 }
1653
1654 /**
1655 * Compare two query strins by stripping away whitespace.
1656 *
1657 * @param string SQL String 1
1658 * @param string SQL string 2
1659 * @param boolean If true, the strings are compared insensitive to case
1660 * @return mixed Returns array with string 1 and 2 if error, otherwise false
1661 */
1662 function debug_parseSQLpartCompare($str,$newStr,$caseInsensitive=FALSE) {
1663 if ($caseInsensitive) {
1664 $str1 = strtoupper($str);
1665 $str2 = strtoupper($newStr);
1666 } else {
1667 $str1 = $str;
1668 $str2 = $newStr;
1669 }
1670
1671 // Fixing escaped chars:
1672 $search = array('\0', '\n', '\r', '\Z');
1673 $replace = array("\x00", "\x0a", "\x0d", "\x1a");
1674 $str1 = str_replace($search, $replace, $str1);
1675 $str2 = str_replace($search, $replace, $str2);
1676
1677 # Normally, commented out since they are needed only in tricky cases...
1678 # $str1 = stripslashes($str1);
1679 # $str2 = stripslashes($str2);
1680
1681 if (strcmp(str_replace(array(' ',"\t","\r","\n"),'',$this->trimSQL($str1)),str_replace(array(' ',"\t","\r","\n"),'',$this->trimSQL($str2)))) {
1682 return array(
1683 str_replace(array(' ',"\t","\r","\n"),' ',$str),
1684 str_replace(array(' ',"\t","\r","\n"),' ',$newStr),
1685 );
1686 }
1687 }
1688
1689 /**
1690 * 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
1691 *
1692 * @param string SQL query
1693 * @return string Query if all is well, otherwise exit.
1694 */
1695 function debug_testSQL($SQLquery) {
1696
1697 // Getting result array:
1698 $parseResult = $this->parseSQL($SQLquery);
1699
1700 // If result array was returned, proceed. Otherwise show error and exit.
1701 if (is_array($parseResult)) {
1702
1703 // Re-compile query:
1704 $newQuery = $this->compileSQL($parseResult);
1705
1706 // TEST the new query:
1707 $testResult = $this->debug_parseSQLpartCompare($SQLquery, $newQuery);
1708
1709 // Return new query if OK, otherwise show error and exit:
1710 if (!is_array($testResult)) {
1711 return $newQuery;
1712 } else {
1713 debug(array('ERROR MESSAGE'=>'Input query did not match the parsed and recompiled query exactly (not observing whitespace)', 'TEST result' => $testResult),'SQL parsing failed:');
1714 exit;
1715 }
1716 } else {
1717 debug(array('query' => $SQLquery, 'ERROR MESSAGE'=>$parseResult),'SQL parsing failed:');
1718 exit;
1719 }
1720 }
1721 }
1722
1723
1724 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']) {
1725 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_sqlparser.php']);
1726 }
1727 ?>