[TASK] Use $x[n] instead of substr($x, n, 1)
[Packages/TYPO3.CMS.git] / typo3 / sysext / install / Classes / Service / SqlSchemaMigrationService.php
1 <?php
2 namespace TYPO3\CMS\Install\Service;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2011-2013 Christian Kuhn <lolli@schwarzbu.ch>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 /**
31 * Verify TYPO3 DB table structure. Mainly used in install tool
32 * compare wizard and extension manager.
33 */
34 class SqlSchemaMigrationService {
35
36 /**
37 * @constant Maximum field width of MySQL
38 */
39 const MYSQL_MAXIMUM_FIELD_WIDTH = 64;
40
41 /**
42 * @var string Prefix of deleted tables
43 */
44 protected $deletedPrefixKey = 'zzz_deleted_';
45
46 /**
47 * @var array Caching output of $GLOBALS['TYPO3_DB']->admin_get_charsets()
48 */
49 protected $character_sets = array();
50
51 /**
52 * Set prefix of deleted tables
53 *
54 * @param string $prefix Prefix string
55 */
56 public function setDeletedPrefixKey($prefix) {
57 $this->deletedPrefixKey = $prefix;
58 }
59
60 /**
61 * Get prefix of deleted tables
62 *
63 * @return string
64 */
65 public function getDeletedPrefixKey() {
66 return $this->deletedPrefixKey;
67 }
68
69 /**
70 * Reads the field definitions for the input SQL-file string
71 *
72 * @param string $fileContent Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
73 * @return array Array with information about table.
74 */
75 public function getFieldDefinitions_fileContent($fileContent) {
76 $lines = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(LF, $fileContent, TRUE);
77 $table = '';
78 $total = array();
79 foreach ($lines as $value) {
80 if ($value[0] === '#') {
81 // Ignore comments
82 continue;
83 }
84 if (!strlen($table)) {
85 $parts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $value, TRUE);
86 if (strtoupper($parts[0]) === 'CREATE' && strtoupper($parts[1]) === 'TABLE') {
87 $table = str_replace('`', '', $parts[2]);
88 // tablenames are always lowercase on windows!
89 if (TYPO3_OS == 'WIN') {
90 $table = strtolower($table);
91 }
92 }
93 } else {
94 if ($value[0] === ')' && substr($value, -1) === ';') {
95 $ttype = array();
96 if (preg_match('/(ENGINE|TYPE)[ ]*=[ ]*([a-zA-Z]*)/', $value, $ttype)) {
97 $total[$table]['extra']['ENGINE'] = $ttype[2];
98 }
99 // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
100 // Set the collation, if specified
101 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
102 $total[$table]['extra']['COLLATE'] = $tcollation[2];
103 } else {
104 // 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)
105 if (preg_match('/(CHARSET|CHARACTER SET)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcharset)) {
106 // Note: Keywords "DEFAULT CHARSET" and "CHARSET" are the same, so "DEFAULT" can just be ignored
107 $charset = $tcharset[2];
108 } else {
109 $charset = $GLOBALS['TYPO3_DB']->default_charset;
110 }
111 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
112 }
113 // Remove table marker and start looking for the next "CREATE TABLE" statement
114 $table = '';
115 } else {
116 // Strip trailing commas
117 $lineV = preg_replace('/,$/', '', $value);
118 $lineV = str_replace('`', '', $lineV);
119 // Remove double blanks
120 $lineV = str_replace(' ', ' ', $lineV);
121 $parts = explode(' ', $lineV, 2);
122 // Field definition
123 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/', $parts[0])) {
124 // Make sure there is no default value when auto_increment is set
125 if (stristr($parts[1], 'auto_increment')) {
126 $parts[1] = preg_replace('/ default \'0\'/i', '', $parts[1]);
127 }
128 // "default" is always lower-case
129 if (stristr($parts[1], ' DEFAULT ')) {
130 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
131 }
132 // Change order of "default" and "NULL" statements
133 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
134 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
135 $key = $parts[0];
136 $total[$table]['fields'][$key] = $parts[1];
137 } else {
138 // Key definition
139 $search = array('/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/INDEX/');
140 $replace = array('UNIQUE', 'FULLTEXT', 'KEY');
141 $lineV = preg_replace($search, $replace, $lineV);
142 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
143 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
144 }
145 $newParts = explode(' ', $parts[1], 2);
146 $key = $parts[0] == 'PRIMARY' ? $parts[0] : $newParts[0];
147 $total[$table]['keys'][$key] = $lineV;
148 // This is a protection against doing something stupid: Only allow clearing of cache_* and index_* tables.
149 if (preg_match('/^(cache|index)_/', $table)) {
150 // Suggest to truncate (clear) this table
151 $total[$table]['extra']['CLEAR'] = 1;
152 }
153 }
154 }
155 }
156 }
157 return $total;
158 }
159
160 /**
161 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
162 *
163 * @param string $charset Character set
164 * @return string Corresponding default collation
165 */
166 public function getCollationForCharset($charset) {
167 // Load character sets, if not cached already
168 if (!count($this->character_sets)) {
169 if (method_exists($GLOBALS['TYPO3_DB'], 'admin_get_charsets')) {
170 $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
171 } else {
172 // Add empty element to avoid that the check will be repeated
173 $this->character_sets[$charset] = array();
174 }
175 }
176 $collation = '';
177 if (isset($this->character_sets[$charset]['Default collation'])) {
178 $collation = $this->character_sets[$charset]['Default collation'];
179 }
180 return $collation;
181 }
182
183 /**
184 * Reads the field definitions for the current database
185 *
186 * @return array Array with information about table.
187 */
188 public function getFieldDefinitions_database() {
189 $total = array();
190 $tempKeys = array();
191 $tempKeysPrefix = array();
192 $GLOBALS['TYPO3_DB']->sql_select_db();
193 echo $GLOBALS['TYPO3_DB']->sql_error();
194 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables();
195 foreach ($tables as $tableName => $tableStatus) {
196 // Fields
197 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
198 foreach ($fieldInformation as $fN => $fieldRow) {
199 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
200 }
201 // Keys
202 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
203 foreach ($keyInformation as $keyRow) {
204 $keyName = $keyRow['Key_name'];
205 $colName = $keyRow['Column_name'];
206 if ($keyRow['Sub_part']) {
207 $colName .= '(' . $keyRow['Sub_part'] . ')';
208 }
209 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
210 if ($keyName == 'PRIMARY') {
211 $prefix = 'PRIMARY KEY';
212 } else {
213 if ($keyRow['Index_type'] == 'FULLTEXT') {
214 $prefix = 'FULLTEXT';
215 } elseif ($keyRow['Non_unique']) {
216 $prefix = 'KEY';
217 } else {
218 $prefix = 'UNIQUE';
219 }
220 $prefix .= ' ' . $keyName;
221 }
222 $tempKeysPrefix[$tableName][$keyName] = $prefix;
223 }
224 // Table status (storage engine, collaction, etc.)
225 if (is_array($tableStatus)) {
226 $tableExtraFields = array(
227 'Engine' => 'ENGINE',
228 'Collation' => 'COLLATE'
229 );
230 foreach ($tableExtraFields as $mysqlKey => $internalKey) {
231 if (isset($tableStatus[$mysqlKey])) {
232 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
233 }
234 }
235 }
236 }
237 // Compile key information:
238 if (count($tempKeys)) {
239 foreach ($tempKeys as $table => $keyInf) {
240 foreach ($keyInf as $kName => $index) {
241 ksort($index);
242 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName] . ' (' . implode(',', $index) . ')';
243 }
244 }
245 }
246 return $total;
247 }
248
249 /**
250 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
251 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
252 *
253 * @param array $FDsrc Field definitions, source (from getFieldDefinitions_fileContent())
254 * @param array $FDcomp Field definitions, comparison. (from getFieldDefinitions_database())
255 * @param string $onlyTableList Table names (in list) which is the ONLY one observed.
256 * @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.
257 * @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
258 */
259 public function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList = '', $ignoreNotNullWhenComparing = TRUE) {
260 $extraArr = array();
261 $diffArr = array();
262 if (is_array($FDsrc)) {
263 foreach ($FDsrc as $table => $info) {
264 if (!strlen($onlyTableList) || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($onlyTableList, $table)) {
265 if (!isset($FDcomp[$table])) {
266 // If the table was not in the FDcomp-array, the result array is loaded with that table.
267 $extraArr[$table] = $info;
268 $extraArr[$table]['whole_table'] = 1;
269 } else {
270 $keyTypes = explode(',', 'extra,fields,keys');
271 foreach ($keyTypes as $theKey) {
272 if (is_array($info[$theKey])) {
273 foreach ($info[$theKey] as $fieldN => $fieldC) {
274 $fieldN = str_replace('`', '', $fieldN);
275 if ($fieldN == 'COLLATE') {
276 // TODO: collation support is currently disabled (needs more testing)
277 continue;
278 }
279 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
280 $extraArr[$table][$theKey][$fieldN] = $fieldC;
281 } else {
282 $fieldC = trim($fieldC);
283
284 // Lowercase the field type to surround false-positive schema changes to be
285 // reported just because of different caseing of characters
286 // The regex does just trigger for the first word followed by round brackets
287 // that contain a length. It does not trigger for e.g. "PRIMARY KEY" because
288 // "PRIMARY KEY" is being returned from the DB in upper case.
289 $fieldC = preg_replace_callback(
290 '/^([a-zA-Z0-9]+\(.*\))(\s)(.*)/',
291 create_function(
292 '$matches',
293 'return strtolower($matches[1]) . $matches[2] . $matches[3];'
294 ),
295 $fieldC
296 );
297
298 if ($ignoreNotNullWhenComparing) {
299 $fieldC = str_replace(' NOT NULL', '', $fieldC);
300 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
301 }
302 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
303 $diffArr[$table][$theKey][$fieldN] = $fieldC;
304 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
305 }
306 }
307 }
308 }
309 }
310 }
311 }
312 }
313 }
314 $output = array(
315 'extra' => $extraArr,
316 'diff' => $diffArr,
317 'diff_currentValues' => $diffArr_cur
318 );
319 return $output;
320 }
321
322 /**
323 * Returns an array with SQL-statements that is needed to update according to the diff-array
324 *
325 * @param array $diffArr Array with differences of current and needed DB settings. (from getDatabaseExtra())
326 * @param string $keyList List of fields in diff array to take notice of.
327 * @return array Array of SQL statements (organized in keys depending on type)
328 */
329 public function getUpdateSuggestions($diffArr, $keyList = 'extra,diff') {
330 $statements = array();
331 $deletedPrefixKey = $this->deletedPrefixKey;
332 $deletedPrefixLength = strlen($deletedPrefixKey);
333 $remove = 0;
334 if ($keyList == 'remove') {
335 $remove = 1;
336 $keyList = 'extra';
337 }
338 $keyList = explode(',', $keyList);
339 foreach ($keyList as $theKey) {
340 if (is_array($diffArr[$theKey])) {
341 foreach ($diffArr[$theKey] as $table => $info) {
342 $whole_table = array();
343 if (is_array($info['fields'])) {
344 foreach ($info['fields'] as $fN => $fV) {
345 if ($info['whole_table']) {
346 $whole_table[] = $fN . ' ' . $fV;
347 } else {
348 // Special case to work around MySQL problems when adding auto_increment fields:
349 if (stristr($fV, 'auto_increment')) {
350 // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
351 // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
352 if (isset($diffArr['extra'][$table]['keys']['PRIMARY'])) {
353 // Remove "auto_increment" from the statement - it will be suggested in a 2nd step after the primary key was created
354 $fV = str_replace(' auto_increment', '', $fV);
355 } else {
356 // In the next step, attempt to clear the table once again (2 = force)
357 $info['extra']['CLEAR'] = 2;
358 }
359 }
360 if ($theKey == 'extra') {
361 if ($remove) {
362 if (substr($fN, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
363 // we've to make sure we don't exceed the maximal length
364 $prefixedFieldName = $deletedPrefixKey . substr($fN, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
365 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $prefixedFieldName . ' ' . $fV . ';';
366 $statements['change'][md5($statement)] = $statement;
367 } else {
368 $statement = 'ALTER TABLE ' . $table . ' DROP ' . $fN . ';';
369 $statements['drop'][md5($statement)] = $statement;
370 }
371 } else {
372 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fN . ' ' . $fV . ';';
373 $statements['add'][md5($statement)] = $statement;
374 }
375 } elseif ($theKey == 'diff') {
376 $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $fN . ' ' . $fV . ';';
377 $statements['change'][md5($statement)] = $statement;
378 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
379 }
380 }
381 }
382 }
383 if (is_array($info['keys'])) {
384 foreach ($info['keys'] as $fN => $fV) {
385 if ($info['whole_table']) {
386 $whole_table[] = $fV;
387 } else {
388 if ($theKey == 'extra') {
389 if ($remove) {
390 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
391 $statements['drop'][md5($statement)] = $statement;
392 } else {
393 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
394 $statements['add'][md5($statement)] = $statement;
395 }
396 } elseif ($theKey == 'diff') {
397 $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
398 $statements['change'][md5($statement)] = $statement;
399 $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
400 $statements['change'][md5($statement)] = $statement;
401 }
402 }
403 }
404 }
405 if (is_array($info['extra'])) {
406 $extras = array();
407 $extras_currentValue = array();
408 $clear_table = FALSE;
409 foreach ($info['extra'] as $fN => $fV) {
410 // Only consider statements which are missing in the database but don't remove existing properties
411 if (!$remove) {
412 if (!$info['whole_table']) {
413 // If the whole table is created at once, we take care of this later by imploding all elements of $info['extra']
414 if ($fN == 'CLEAR') {
415 // Truncate table must happen later, not now
416 // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
417 if (count($info['keys']) || $fV == 2) {
418 $clear_table = TRUE;
419 }
420 continue;
421 } else {
422 $extras[] = $fN . '=' . $fV;
423 $extras_currentValue[] = $fN . '=' . $diffArr['diff_currentValues'][$table]['extra'][$fN];
424 }
425 }
426 }
427 }
428 if ($clear_table) {
429 $statement = 'TRUNCATE TABLE ' . $table . ';';
430 $statements['clear_table'][md5($statement)] = $statement;
431 }
432 if (count($extras)) {
433 $statement = 'ALTER TABLE ' . $table . ' ' . implode(' ', $extras) . ';';
434 $statements['change'][md5($statement)] = $statement;
435 $statements['change_currentValue'][md5($statement)] = implode(' ', $extras_currentValue);
436 }
437 }
438 if ($info['whole_table']) {
439 if ($remove) {
440 if (substr($table, 0, $deletedPrefixLength) !== $deletedPrefixKey) {
441 // we've to make sure we don't exceed the maximal length
442 $prefixedTableName = $deletedPrefixKey . substr($table, ($deletedPrefixLength - self::MYSQL_MAXIMUM_FIELD_WIDTH));
443 $statement = 'ALTER TABLE ' . $table . ' RENAME ' . $prefixedTableName . ';';
444 $statements['change_table'][md5($statement)] = $statement;
445 } else {
446 $statement = 'DROP TABLE ' . $table . ';';
447 $statements['drop_table'][md5($statement)] = $statement;
448 }
449 // Count
450 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', $table);
451 $statements['tables_count'][md5($statement)] = $count ? 'Records in table: ' . $count : '';
452 } else {
453 $statement = 'CREATE TABLE ' . $table . ' (
454 ' . implode(',
455 ', $whole_table) . '
456 )';
457 if ($info['extra']) {
458 foreach ($info['extra'] as $k => $v) {
459 if ($k == 'COLLATE' || $k == 'CLEAR') {
460 // Skip these special statements. TODO: collation support is currently disabled (needs more testing)
461 continue;
462 }
463 // Add extra attributes like ENGINE, CHARSET, etc.
464 $statement .= ' ' . $k . '=' . $v;
465 }
466 }
467 $statement .= ';';
468 $statements['create_table'][md5($statement)] = $statement;
469 }
470 }
471 }
472 }
473 }
474 return $statements;
475 }
476
477 /**
478 * Converts a result row with field information into the SQL field definition string
479 *
480 * @param array $row MySQL result row
481 * @return string Field definition
482 */
483 public function assembleFieldDefinition($row) {
484 $field = array($row['Type']);
485 if ($row['Null'] == 'NO') {
486 $field[] = 'NOT NULL';
487 }
488 if (!strstr($row['Type'], 'blob') && !strstr($row['Type'], 'text')) {
489 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
490 if (!stristr($row['Extra'], 'auto_increment')) {
491 if ($row['Default'] === NULL) {
492 $field[] = 'default NULL';
493 } else {
494 $field[] = 'default \'' . addslashes($row['Default']) . '\'';
495 }
496 }
497 }
498 if ($row['Extra']) {
499 $field[] = $row['Extra'];
500 }
501 return implode(' ', $field);
502 }
503
504 /**
505 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
506 *
507 * @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.
508 * @param boolean $removeNonSQL If set, non-SQL content (like comments and blank lines) is not included in the final output
509 * @param string $query_regex Regex to filter SQL lines to include
510 * @return array Array of SQL statements
511 */
512 public function getStatementArray($sqlcode, $removeNonSQL = FALSE, $query_regex = '') {
513 $sqlcodeArr = explode(LF, $sqlcode);
514 // Based on the assumption that the sql-dump has
515 $statementArray = array();
516 $statementArrayPointer = 0;
517 foreach ($sqlcodeArr as $line => $lineContent) {
518 $lineContent = trim($lineContent);
519 $is_set = 0;
520 // Auto_increment fields cannot have a default value!
521 if (stristr($lineContent, 'auto_increment')) {
522 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
523 }
524 if (!$removeNonSQL || $lineContent !== '' && $lineContent[0] !== '#' && substr($lineContent, 0, 2) !== '--') {
525 // '--' is seen as mysqldump comments from server version 3.23.49
526 $statementArray[$statementArrayPointer] .= $lineContent;
527 $is_set = 1;
528 }
529 if (substr($lineContent, -1) === ';') {
530 if (isset($statementArray[$statementArrayPointer])) {
531 if (!trim($statementArray[$statementArrayPointer]) || $query_regex && !preg_match(('/' . $query_regex . '/i'), trim($statementArray[$statementArrayPointer]))) {
532 unset($statementArray[$statementArrayPointer]);
533 }
534 }
535 $statementArrayPointer++;
536 } elseif ($is_set) {
537 $statementArray[$statementArrayPointer] .= LF;
538 }
539 }
540 return $statementArray;
541 }
542
543 /**
544 * Returns tables to create and how many records in each
545 *
546 * @param array $statements Array of SQL statements to analyse.
547 * @param boolean $insertCountFlag If set, will count number of INSERT INTO statements following that table definition
548 * @return array Array with table definitions in index 0 and count in index 1
549 */
550 public function getCreateTables($statements, $insertCountFlag = FALSE) {
551 $crTables = array();
552 $insertCount = array();
553 foreach ($statements as $line => $lineContent) {
554 $reg = array();
555 if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
556 $table = trim($reg[1]);
557 if ($table) {
558 // Table names are always lowercase on Windows!
559 if (TYPO3_OS == 'WIN') {
560 $table = strtolower($table);
561 }
562 $sqlLines = explode(LF, $lineContent);
563 foreach ($sqlLines as $k => $v) {
564 if (stristr($v, 'auto_increment')) {
565 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
566 }
567 }
568 $lineContent = implode(LF, $sqlLines);
569 $crTables[$table] = $lineContent;
570 }
571 } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
572 $nTable = trim($reg[1]);
573 $insertCount[$nTable]++;
574 }
575 }
576 return array($crTables, $insertCount);
577 }
578
579 /**
580 * Extracts all insert statements from $statement array where content is inserted into $table
581 *
582 * @param array $statements Array of SQL statements
583 * @param string $table Table name
584 * @return array Array of INSERT INTO statements where table match $table
585 */
586 public function getTableInsertStatements($statements, $table) {
587 $outStatements = array();
588 foreach ($statements as $line => $lineContent) {
589 $reg = array();
590 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
591 $nTable = trim($reg[1]);
592 if ($nTable && $table === $nTable) {
593 $outStatements[] = $lineContent;
594 }
595 }
596 }
597 return $outStatements;
598 }
599
600 /**
601 * Performs the queries passed from the input array.
602 *
603 * @param array $arr Array of SQL queries to execute.
604 * @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)
605 * @return mixed Array with error message from database if any occurred. Otherwise TRUE if everything was executed successfully.
606 */
607 public function performUpdateQueries($arr, $keyArr) {
608 $result = array();
609 if (is_array($arr)) {
610 foreach ($arr as $key => $string) {
611 if (isset($keyArr[$key]) && $keyArr[$key]) {
612 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
613 if ($res === FALSE) {
614 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
615 } elseif (is_resource($res) || is_a($res, '\\mysqli_result')) {
616 $GLOBALS['TYPO3_DB']->sql_free_result($res);
617 }
618 }
619 }
620 }
621 if (count($result) > 0) {
622 return $result;
623 } else {
624 return TRUE;
625 }
626 }
627
628 /**
629 * Returns list of tables in the database
630 *
631 * @return array List of tables.
632 * @see \TYPO3\CMS\Core\Database\DatabaseConnection::admin_get_tables()
633 */
634 public function getListOfTables() {
635 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
636 foreach ($whichTables as $key => &$value) {
637 $value = $key;
638 }
639 unset($value);
640 return $whichTables;
641 }
642 }