[TASK] Clean up phpDoc comments in t3lib classes
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_install_sql.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2011 Christian Kuhn <lolli@schwarzbu.ch>
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 /**
29 * Verify TYPO3 DB table structure. Mainly used in install tool
30 * compare wizard and extension manager.
31 *
32 * @author Christian Kuhn <lolli@schwarzbu.ch>
33 * @package TYPO3
34 * @subpackage t3lib
35 */
36 class t3lib_install_Sql {
37
38 /**
39 * @var string Prefix of deleted tables
40 */
41 protected $deletedPrefixKey = 'zzz_deleted_'; // Prefix used for tables/fields when deleted/renamed.
42
43 /**
44 * @var float|int Multiplier of SQL field size (for char, varchar and text fields)
45 */
46 protected $multiplySize = 1;
47
48 /**
49 * @var array Caching output of $GLOBALS['TYPO3_DB']->admin_get_charsets()
50 */
51 protected $character_sets = array();
52
53 /**
54 * Constructor function
55 */
56 public function __construct() {
57 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'] >= 1 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'] <= 5) {
58 $this->multiplySize = (double) $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'];
59 }
60 }
61
62 /**
63 * Set prefix of deleted tables
64 *
65 * @param string $prefix Prefix string
66 */
67 public function setDeletedPrefixKey($prefix) {
68 $this->deletedPrefixKey = $prefix;
69 }
70
71 /**
72 * Get prefix of deleted tables
73 *
74 * @return string
75 */
76 public function getDeletedPrefixKey() {
77 return $this->deletedPrefixKey;
78 }
79
80 /**
81 * Reads the field definitions for the input SQL-file string
82 *
83 * @param string $fileContent Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
84 * @return array Array with information about table.
85 */
86 public function getFieldDefinitions_fileContent($fileContent) {
87 $lines = t3lib_div::trimExplode(LF, $fileContent, 1);
88 $table = '';
89 $total = array();
90
91 foreach ($lines as $value) {
92 if (substr($value, 0, 1) == '#') {
93 // Ignore comments
94 continue;
95 }
96
97 if (!strlen($table)) {
98 $parts = t3lib_div::trimExplode(' ', $value, TRUE);
99 if (strtoupper($parts[0]) === 'CREATE' && strtoupper($parts[1]) === 'TABLE') {
100 $table = str_replace('`', '', $parts[2]);
101 // tablenames are always lowercase on windows!
102 if (TYPO3_OS == 'WIN') {
103 $table = strtolower($table);
104 }
105 }
106 } else {
107 if (substr($value, 0, 1) == ')' && substr($value, -1) == ';') {
108 $ttype = array();
109 if (preg_match('/(ENGINE|TYPE)[ ]*=[ ]*([a-zA-Z]*)/', $value, $ttype)) {
110 $total[$table]['extra']['ENGINE'] = $ttype[2];
111 } // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
112
113 // Set the collation, if specified
114 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
115 $total[$table]['extra']['COLLATE'] = $tcollation[2];
116 } else {
117 // Otherwise, get the CHARACTER SET and try to find the default collation for it as returned by "SHOW CHARACTER SET" query (for details, see http://dev.mysql.com/doc/refman/5.1/en/charset-table.html)
118 if (preg_match('/(CHARSET|CHARACTER SET)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcharset)) { // Note: Keywords "DEFAULT CHARSET" and "CHARSET" are the same, so "DEFAULT" can just be ignored
119 $charset = $tcharset[2];
120 } else {
121 $charset = $GLOBALS['TYPO3_DB']->default_charset; // Fallback to default charset
122 }
123 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
124 }
125
126 // Remove table marker and start looking for the next "CREATE TABLE" statement
127 $table = '';
128 } else {
129 // Strip trailing commas
130 $lineV = preg_replace('/,$/', '', $value);
131 $lineV = str_replace('`', '', $lineV);
132 // Remove double blanks
133 $lineV = str_replace(' ', ' ', $lineV);
134
135 $parts = explode(' ', $lineV, 2);
136 // Field definition
137 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/', $parts[0])) {
138
139 // Make sure there is no default value when auto_increment is set
140 if (stristr($parts[1], 'auto_increment')) {
141 $parts[1] = preg_replace('/ default \'0\'/i', '', $parts[1]);
142 }
143 // "default" is always lower-case
144 if (stristr($parts[1], ' DEFAULT ')) {
145 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
146 }
147
148 // Change order of "default" and "NULL" statements
149 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
150 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
151
152 $key = $parts[0];
153 $total[$table]['fields'][$key] = $parts[1];
154
155 } else { // Key definition
156 $search = array('/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/INDEX/');
157 $replace = array('UNIQUE', 'FULLTEXT', 'KEY');
158 $lineV = preg_replace($search, $replace, $lineV);
159
160 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
161 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
162 }
163
164 $newParts = explode(' ', $parts[1], 2);
165 $key = $parts[0] == 'PRIMARY' ? $parts[0] : $newParts[0];
166
167 $total[$table]['keys'][$key] = $lineV;
168
169 // This is a protection against doing something stupid: Only allow clearing of cache_* and index_* tables.
170 if (preg_match('/^(cache|index)_/', $table)) {
171 // Suggest to truncate (clear) this table
172 $total[$table]['extra']['CLEAR'] = 1;
173 }
174 }
175 }
176 }
177 }
178
179 $this->getFieldDefinitions_sqlContent_parseTypes($total);
180 return $total;
181 }
182
183 /**
184 * Multiplies varchars/tinytext fields in size according to $this->multiplySize
185 * Useful if you want to use UTF-8 in the database and needs to extend the field sizes in the database so UTF-8 chars are not discarded. For most charsets available as single byte sets, multiplication with 2 should be enough. For chinese, use 3.
186 *
187 * @param array $total Total array (from getFieldDefinitions_fileContent())
188 * @return void
189 * @access private
190 * @see getFieldDefinitions_fileContent()
191 */
192 protected function getFieldDefinitions_sqlContent_parseTypes(&$total) {
193
194 $mSize = (double) $this->multiplySize;
195 if ($mSize > 1) {
196
197 /** @var $sqlParser t3lib_sqlparser */
198 $sqlParser = t3lib_div::makeInstance('t3lib_sqlparser');
199 foreach ($total as $table => $cfg) {
200 if (is_array($cfg['fields'])) {
201 foreach ($cfg['fields'] as $fN => $fType) {
202 $orig_fType = $fType;
203 $fInfo = $sqlParser->parseFieldDef($fType);
204
205 switch ($fInfo['fieldType']) {
206 case 'char':
207 case 'varchar':
208 $newSize = round($fInfo['value'] * $mSize);
209
210 if ($newSize <= 255) {
211 $fInfo['value'] = $newSize;
212 } else {
213 $fInfo = array(
214 'fieldType' => 'text',
215 'featureIndex' => array(
216 'NOTNULL' => array(
217 'keyword' => 'NOT NULL'
218 )
219 )
220 );
221 // Change key definition if necessary (must use "prefix" on TEXT columns)
222 if (is_array($cfg['keys'])) {
223 foreach ($cfg['keys'] as $kN => $kType) {
224 $match = array();
225 preg_match('/^([^(]*)\(([^)]+)\)(.*)/', $kType, $match);
226 $keys = array();
227 foreach (t3lib_div::trimExplode(',', $match[2]) as $kfN) {
228 if ($fN == $kfN) {
229 $kfN .= '(' . $newSize . ')';
230 }
231 $keys[] = $kfN;
232 }
233 $total[$table]['keys'][$kN] = $match[1] . '(' . implode(',', $keys) . ')' . $match[3];
234 }
235 }
236 }
237 break;
238 case 'tinytext':
239 $fInfo['fieldType'] = 'text';
240 break;
241 }
242
243 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
244 if ($sqlParser->parse_error) {
245 throw new RuntimeException(
246 'TYPO3 Fatal Error: ' . $sqlParser->parse_error,
247 1270853961
248 );
249 }
250 }
251 }
252 }
253 }
254 }
255
256 /**
257 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
258 *
259 * @param string $charset Character set
260 * @return string Corresponding default collation
261 */
262 public function getCollationForCharset($charset) {
263 // Load character sets, if not cached already
264 if (!count($this->character_sets)) {
265 if (method_exists($GLOBALS['TYPO3_DB'], 'admin_get_charsets')) {
266 $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
267 } else {
268 // Add empty element to avoid that the check will be repeated
269 $this->character_sets[$charset] = array();
270 }
271 }
272
273 $collation = '';
274 if (isset($this->character_sets[$charset]['Default collation'])) {
275 $collation = $this->character_sets[$charset]['Default collation'];
276 }
277
278 return $collation;
279 }
280
281 /**
282 * Reads the field definitions for the current database
283 *
284 * @return array Array with information about table.
285 */
286 public function getFieldDefinitions_database() {
287 $total = array();
288 $tempKeys = array();
289 $tempKeysPrefix = array();
290
291 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db);
292 echo $GLOBALS['TYPO3_DB']->sql_error();
293
294 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
295 foreach ($tables as $tableName => $tableStatus) {
296
297 // Fields
298 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
299 foreach ($fieldInformation as $fN => $fieldRow) {
300 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
301 }
302
303 // Keys
304 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
305
306 foreach ($keyInformation as $keyRow) {
307 $keyName = $keyRow['Key_name'];
308 $colName = $keyRow['Column_name'];
309 if ($keyRow['Sub_part']) {
310 $colName .= '(' . $keyRow['Sub_part'] . ')';
311 }
312 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
313 if ($keyName == 'PRIMARY') {
314 $prefix = 'PRIMARY KEY';
315 } else {
316 if ($keyRow['Index_type'] == 'FULLTEXT') {
317 $prefix = 'FULLTEXT';
318 } elseif ($keyRow['Non_unique']) {
319 $prefix = 'KEY';
320 } else {
321 $prefix = 'UNIQUE';
322 }
323 $prefix .= ' ' . $keyName;
324 }
325 $tempKeysPrefix[$tableName][$keyName] = $prefix;
326 }
327
328 // Table status (storage engine, collaction, etc.)
329 if (is_array($tableStatus)) {
330 $tableExtraFields = array(
331 'Engine' => 'ENGINE',
332 'Collation' => 'COLLATE',
333 );
334
335 foreach ($tableExtraFields as $mysqlKey => $internalKey) {
336 if (isset($tableStatus[$mysqlKey])) {
337 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
338 }
339 }
340 }
341 }
342
343 // Compile key information:
344 if (count($tempKeys)) {
345 foreach ($tempKeys as $table => $keyInf) {
346 foreach ($keyInf as $kName => $index) {
347 ksort($index);
348 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName] . ' (' . implode(',', $index) . ')';
349 }
350 }
351 }
352
353 return $total;
354 }
355
356 /**
357 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
358 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
359 *
360 * @param array $FDsrc Field definitions, source (from getFieldDefinitions_fileContent())
361 * @param array $FDcomp Field definitions, comparison. (from getFieldDefinitions_database())
362 * @param string $onlyTableList Table names (in list) which is the ONLY one observed.
363 * @param boolean $ignoreNotNullWhenComparing If set, this function ignores NOT NULL statements of the SQL file field definition when comparing current field definition from database with field definition from SQL file. This way, NOT NULL statements will be executed when the field is initially created, but the SQL parser will never complain about missing NOT NULL statements afterwards.
364 * @return array Returns an array with 1) all elements from $FDsrc that is not in $FDcomp (in key 'extra') and 2) all elements from $FDsrc that is different from the ones in $FDcomp
365 */
366 public function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList = '', $ignoreNotNullWhenComparing = TRUE) {
367 $extraArr = array();
368 $diffArr = array();
369
370 if (is_array($FDsrc)) {
371 foreach ($FDsrc as $table => $info) {
372 if (!strlen($onlyTableList) || t3lib_div::inList($onlyTableList, $table)) {
373 if (!isset($FDcomp[$table])) {
374 // If the table was not in the FDcomp-array, the result array is loaded with that table.
375 $extraArr[$table] = $info;
376 $extraArr[$table]['whole_table'] = 1;
377 } else {
378 $keyTypes = explode(',', 'extra,fields,keys');
379 foreach ($keyTypes as $theKey) {
380 if (is_array($info[$theKey])) {
381 foreach ($info[$theKey] as $fieldN => $fieldC) {
382 $fieldN = str_replace('`', '', $fieldN);
383 if ($fieldN == 'COLLATE') {
384 // TODO: collation support is currently disabled (needs more testing)
385 continue;
386 }
387
388 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
389 $extraArr[$table][$theKey][$fieldN] = $fieldC;
390 } else {
391 $fieldC = trim($fieldC);
392 if ($ignoreNotNullWhenComparing) {
393 $fieldC = str_replace(' NOT NULL', '', $fieldC);
394 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
395 }
396 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
397 $diffArr[$table][$theKey][$fieldN] = $fieldC;
398 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
399 }
400 }
401 }
402 }
403 }
404 }
405 }
406 }
407 }
408
409 $output = array(
410 'extra' => $extraArr,
411 'diff' => $diffArr,
412 'diff_currentValues' => $diffArr_cur
413 );
414
415 return $output;
416 }
417
418 /**
419 * Returns an array with SQL-statements that is needed to update according to the diff-array
420 *
421 * @param array $diffArr Array with differences of current and needed DB settings. (from getDatabaseExtra())
422 * @param string $keyList List of fields in diff array to take notice of.
423 * @return array Array of SQL statements (organized in keys depending on type)
424 */
425 public function getUpdateSuggestions($diffArr, $keyList = 'extra,diff') {
426 $statements = array();
427 $deletedPrefixKey = $this->deletedPrefixKey;
428 $remove = 0;
429 if ($keyList == 'remove') {
430 $remove = 1;
431 $keyList = 'extra';
432 }
433 $keyList = explode(',', $keyList);
434 foreach ($keyList as $theKey) {
435 if (is_array($diffArr[$theKey])) {
436 foreach ($diffArr[$theKey] as $table => $info) {
437 $whole_table = array();
438 if (is_array($info['fields'])) {
439 foreach ($info['fields'] as $fN => $fV) {
440 if ($info['whole_table']) {
441 $whole_table[] = $fN . ' ' . $fV;
442 } else {
443 // Special case to work around MySQL problems when adding auto_increment fields:
444 if (stristr($fV, 'auto_increment')) {
445 // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
446 // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
447 if (isset($diffArr['extra'][$table]['keys']['PRIMARY'])) {
448 // Remove "auto_increment" from the statement - it will be suggested in a 2nd step after the primary key was created
449 $fV = str_replace(' auto_increment', '', $fV);
450 } else {
451 // In the next step, attempt to clear the table once again (2 = force)
452 $info['extra']['CLEAR'] = 2;
453 }
454 }
455 if ($theKey == 'extra') {
456 if ($remove) {
457 if (substr($fN, 0, strlen($deletedPrefixKey)) != $deletedPrefixKey) {
458 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $deletedPrefixKey . $fN . ' ' . $fV . ';';
459 $statements['change'][md5($statement)] = $statement;
460 } else {
461 $statement = 'ALTER TABLE ' . $table . ' DROP ' . $fN . ';';
462 $statements['drop'][md5($statement)] = $statement;
463 }
464 } else {
465 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fN . ' ' . $fV . ';';
466 $statements['add'][md5($statement)] = $statement;
467 }
468 } elseif ($theKey == 'diff') {
469 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $fN . ' ' . $fV . ';';
470 $statements['change'][md5($statement)] = $statement;
471 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
472 }
473 }
474 }
475 }
476 if (is_array($info['keys'])) {
477 foreach ($info['keys'] as $fN => $fV) {
478 if ($info['whole_table']) {
479 $whole_table[] = $fV;
480 } else {
481 if ($theKey == 'extra') {
482 if ($remove) {
483 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
484 $statements['drop'][md5($statement)] = $statement;
485 } else {
486 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
487 $statements['add'][md5($statement)] = $statement;
488 }
489 } elseif ($theKey == 'diff') {
490 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
491 $statements['change'][md5($statement)] = $statement;
492 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
493 $statements['change'][md5($statement)] = $statement;
494 }
495 }
496 }
497 }
498 if (is_array($info['extra'])) {
499 $extras = array();
500 $extras_currentValue = array();
501 $clear_table = FALSE;
502
503 foreach ($info['extra'] as $fN => $fV) {
504
505 // Only consider statements which are missing in the database but don't remove existing properties
506 if (!$remove) {
507 if (!$info['whole_table']) { // If the whole table is created at once, we take care of this later by imploding all elements of $info['extra']
508 if ($fN == 'CLEAR') {
509 // Truncate table must happen later, not now
510 // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
511 if (count($info['keys']) || $fV == 2) {
512 $clear_table = TRUE;
513 }
514 continue;
515 } else {
516 $extras[] = $fN . '=' . $fV;
517 $extras_currentValue[] = $fN . '=' . $diffArr['diff_currentValues'][$table]['extra'][$fN];
518 }
519 }
520 }
521 }
522 if ($clear_table) {
523 $statement = 'TRUNCATE TABLE ' . $table . ';';
524 $statements['clear_table'][md5($statement)] = $statement;
525 }
526 if (count($extras)) {
527 $statement = 'ALTER TABLE ' . $table . ' ' . implode(' ', $extras) . ';';
528 $statements['change'][md5($statement)] = $statement;
529 $statements['change_currentValue'][md5($statement)] = implode(' ', $extras_currentValue);
530 }
531 }
532 if ($info['whole_table']) {
533 if ($remove) {
534 if (substr($table, 0, strlen($deletedPrefixKey)) != $deletedPrefixKey) {
535 $statement = 'ALTER TABLE ' . $table . ' RENAME ' . $deletedPrefixKey . $table . ';';
536 $statements['change_table'][md5($statement)] = $statement;
537 } else {
538 $statement = 'DROP TABLE ' . $table . ';';
539 $statements['drop_table'][md5($statement)] = $statement;
540 }
541 // Count
542 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', $table);
543 $statements['tables_count'][md5($statement)] = $count ? 'Records in table: ' . $count : '';
544 } else {
545 $statement = 'CREATE TABLE ' . $table . " (\n" . implode(",\n", $whole_table) . "\n)";
546 if ($info['extra']) {
547 foreach ($info['extra'] as $k => $v) {
548 if ($k == 'COLLATE' || $k == 'CLEAR') {
549 // Skip these special statements. TODO: collation support is currently disabled (needs more testing)
550 continue;
551 }
552 // Add extra attributes like ENGINE, CHARSET, etc.
553 $statement .= ' ' . $k . '=' . $v;
554 }
555 }
556 $statement .= ';';
557 $statements['create_table'][md5($statement)] = $statement;
558 }
559 }
560 }
561 }
562 }
563
564 return $statements;
565 }
566
567 /**
568 * Converts a result row with field information into the SQL field definition string
569 *
570 * @param array $row MySQL result row
571 * @return string Field definition
572 */
573 public function assembleFieldDefinition($row) {
574 $field = array($row['Type']);
575
576 if ($row['Null'] == 'NO') {
577 $field[] = 'NOT NULL';
578 }
579 if (!strstr($row['Type'], 'blob') && !strstr($row['Type'], 'text')) {
580 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
581 if (!stristr($row['Extra'], 'auto_increment')) {
582 if ($row['Default'] === NULL) {
583 $field[] = 'default NULL';
584 } else {
585 $field[] = 'default \'' . addslashes($row['Default']) . '\'';
586 }
587 }
588 }
589 if ($row['Extra']) {
590 $field[] = $row['Extra'];
591 }
592
593 return implode(' ', $field);
594 }
595
596 /**
597 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
598 *
599 * @param string $sqlcode The SQL-file content. Provided that 1) every query in the input is ended with ';' and that a line in the file contains only one query or a part of a query.
600 * @param boolean $removeNonSQL If set, non-SQL content (like comments and blank lines) is not included in the final output
601 * @param string $query_regex Regex to filter SQL lines to include
602 * @return array Array of SQL statements
603 */
604 public function getStatementArray($sqlcode, $removeNonSQL = FALSE, $query_regex = '') {
605 $sqlcodeArr = explode(LF, $sqlcode);
606
607 // Based on the assumption that the sql-dump has
608 $statementArray = array();
609 $statementArrayPointer = 0;
610
611 foreach ($sqlcodeArr as $line => $lineContent) {
612 $is_set = 0;
613
614 // Auto_increment fields cannot have a default value!
615 if (stristr($lineContent, 'auto_increment')) {
616 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
617 }
618
619 if (!$removeNonSQL || (strcmp(trim($lineContent), '') && substr(trim($lineContent), 0, 1) != '#' && substr(trim($lineContent), 0, 2) != '--')) { // '--' is seen as mysqldump comments from server version 3.23.49
620 $statementArray[$statementArrayPointer] .= $lineContent;
621 $is_set = 1;
622 }
623 if (substr(trim($lineContent), -1) == ';') {
624 if (isset($statementArray[$statementArrayPointer])) {
625 if (!trim($statementArray[$statementArrayPointer]) || ($query_regex && !preg_match('/' . $query_regex . '/i', trim($statementArray[$statementArrayPointer])))) {
626 unset($statementArray[$statementArrayPointer]);
627 }
628 }
629 $statementArrayPointer++;
630
631 } elseif ($is_set) {
632 $statementArray[$statementArrayPointer] .= LF;
633 }
634 }
635
636 return $statementArray;
637 }
638
639 /**
640 * Returns tables to create and how many records in each
641 *
642 * @param array $statements Array of SQL statements to analyse.
643 * @param boolean $insertCountFlag If set, will count number of INSERT INTO statements following that table definition
644 * @return array Array with table definitions in index 0 and count in index 1
645 */
646 public function getCreateTables($statements, $insertCountFlag = FALSE) {
647 $crTables = array();
648 $insertCount = array();
649 foreach ($statements as $line => $lineContent) {
650 $reg = array();
651 if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
652 $table = trim($reg[1]);
653 if ($table) {
654 // Table names are always lowercase on Windows!
655 if (TYPO3_OS == 'WIN') {
656 $table = strtolower($table);
657 }
658 $sqlLines = explode(LF, $lineContent);
659 foreach ($sqlLines as $k => $v) {
660 if (stristr($v, 'auto_increment')) {
661 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
662 }
663 }
664 $lineContent = implode(LF, $sqlLines);
665 $crTables[$table] = $lineContent;
666 }
667 } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
668 $nTable = trim($reg[1]);
669 $insertCount[$nTable]++;
670 }
671 }
672
673 return array($crTables, $insertCount);
674 }
675
676 /**
677 * Extracts all insert statements from $statement array where content is inserted into $table
678 *
679 * @param array $statements Array of SQL statements
680 * @param string $table Table name
681 * @return array Array of INSERT INTO statements where table match $table
682 */
683 public function getTableInsertStatements($statements, $table) {
684 $outStatements = array();
685 foreach ($statements as $line => $lineContent) {
686 $reg = array();
687 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
688 $nTable = trim($reg[1]);
689 if ($nTable && !strcmp($table, $nTable)) {
690 $outStatements[] = $lineContent;
691 }
692 }
693 }
694 return $outStatements;
695 }
696
697 /**
698 * Performs the queries passed from the input array.
699 *
700 * @param array $arr Array of SQL queries to execute.
701 * @param array $keyArr Array with keys that must match keys in $arr. Only where a key in this array is set and TRUE will the query be executed (meant to be passed from a form checkbox)
702 * @return mixed Array with error message from database if any occured. Otherwise TRUE if everything was executed successfully.
703 */
704 public function performUpdateQueries($arr, $keyArr) {
705 $result = array();
706 if (is_array($arr)) {
707 foreach ($arr as $key => $string) {
708 if (isset($keyArr[$key]) && $keyArr[$key]) {
709 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
710 if ($res === FALSE) {
711 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
712 } elseif (is_resource($res)) {
713 $GLOBALS['TYPO3_DB']->sql_free_result($res);
714 }
715 }
716 }
717 }
718 if (count($result) > 0) {
719 return $result;
720 } else {
721 return TRUE;
722 }
723 }
724
725 /**
726 * Returns list of tables in the database
727 *
728 * @return array List of tables.
729 * @see t3lib_db::admin_get_tables()
730 */
731 public function getListOfTables() {
732 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
733 foreach ($whichTables as $key => &$value) {
734 $value = $key;
735 }
736 unset($value);
737 return $whichTables;
738 }
739 }
740
741 ?>