Fixed bug #14005: Moving a page with IRRE records misplaces IRRE records
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_install.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
29 *
30 * $Id$
31 *
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 83: class t3lib_install
40 * 108: function t3lib_install()
41 *
42 * SECTION: Writing to localconf.php
43 * 132: function setValueInLocalconfFile(&$line_array, $variable, $value)
44 * 183: function writeToLocalconf_control($inlines='',$absFullPath='')
45 * 253: function checkForBadString($string)
46 * 266: function slashValueForSingleDashes($value)
47 *
48 * SECTION: SQL
49 * 291: function getFieldDefinitions_fileContent($fileContent)
50 * 359: function getFieldDefinitions_sqlContent_parseTypes(&$total)
51 * 406: function getFieldDefinitions_database()
52 * 450: function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='')
53 * 496: function getUpdateSuggestions($diffArr,$keyList='extra,diff')
54 * 589: function assembleFieldDefinition($row)
55 * 611: function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='')
56 * 649: function getCreateTables($statements, $insertCountFlag=0)
57 * 683: function getTableInsertStatements($statements, $table)
58 * 704: function performUpdateQueries($arr,$keyArr)
59 * 720: function getListOfTables()
60 * 736: function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0)
61 *
62 * TOTAL FUNCTIONS: 17
63 * (This index is automatically created/updated by the extension "extdeveval")
64 *
65 */
66
67
68
69
70
71
72
73
74
75 /**
76 * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
77 *
78 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
79 * @package TYPO3
80 * @subpackage t3lib
81 */
82 class t3lib_install {
83
84
85 // External, Static
86 var $updateIdentity = ''; // Set to string which identifies the script using this class.
87 var $deletedPrefixKey = 'zzz_deleted_'; // Prefix used for tables/fields when deleted/renamed.
88 var $dbUpdateCheckboxPrefix = 'TYPO3_INSTALL[database_update]'; // Prefix for checkbox fields when updating database.
89 var $localconf_addLinesOnly = 0; // If this is set, modifications to localconf.php is done by adding new lines to the array only. If unset, existing values are recognized and changed.
90 var $localconf_editPointToken = 'INSTALL SCRIPT EDIT POINT TOKEN - all lines after this points may be changed by the install script!'; // If set and addLinesOnly is disabled, lines will be change only if they are after this token (on a single line!) in the file
91 var $allowUpdateLocalConf = 0; // If true, this class will allow the user to update the localconf.php file. Is set true in the init.php file.
92 var $backPath = '../'; // Backpath (used for icons etc.)
93
94 var $multiplySize = 1; // Multiplier of SQL field size (for char, varchar and text fields)
95 var $character_sets = array(); // Caching output of $GLOBALS['TYPO3_DB']->admin_get_charsets()
96
97 // Internal, dynamic:
98 var $setLocalconf = 0; // Used to indicate that a value is change in the line-array of localconf and that it should be written.
99 var $messages = array(); // Used to set (error)messages from the executing functions like mail-sending, writing Localconf and such
100 var $touchedLine = 0; // updated with line in localconf.php file that was changed.
101
102
103 /**
104 * Constructor function
105 *
106 * @return void
107 */
108 function t3lib_install() {
109 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize']>= 1 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize']<=5) {
110 $this->multiplySize = (double)$GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'];
111 }
112 }
113
114
115
116 /**************************************
117 *
118 * Writing to localconf.php
119 *
120
121 **************************************/
122
123 /**
124 * This functions takes an array with lines from localconf.php, finds a variable and inserts the new value.
125 *
126 * @param array $line_array the localconf.php file exploded into an array by linebreaks. (see writeToLocalconf_control())
127 * @param string $variable The variable name to find and substitute. This string must match the first part of a trimmed line in the line-array. Matching is done backwards so the last appearing line will be substituted.
128 * @param string $value Is the value to be insert for the variable
129 * @return void
130 * @see writeToLocalconf_control()
131 */
132 function setValueInLocalconfFile(&$line_array, $variable, $value) {
133 if (!$this->checkForBadString($value)) return 0;
134
135 // Initialize:
136 $found = 0;
137 $this->touchedLine = '';
138 $commentKey = '## ';
139 $inArray = in_array($commentKey.$this->localconf_editPointToken,$line_array);
140 $tokenSet = ($this->localconf_editPointToken && !$inArray); // Flag is set if the token should be set but is not yet...
141 $stopAtToken = ($this->localconf_editPointToken && $inArray);
142 $comment = ' Modified or inserted by '.$this->updateIdentity.'.';
143 $replace = array('["', '"]');
144 $search = array('[\'', '\']');
145 $varDoubleQuotes = str_replace($search, $replace, $variable);
146
147 // Search for variable name:
148 if (!$this->localconf_addLinesOnly && !$tokenSet) {
149 $line_array = array_reverse($line_array);
150 foreach($line_array as $k => $v) {
151 $v2 = trim($v);
152 if ($stopAtToken && !strcmp($v2,$commentKey.$this->localconf_editPointToken)) break; // If stopAtToken and token found, break out of the loop..
153 if (!strcmp(substr($v2,0,strlen($variable.' ')),$variable.' ')) {
154 $mainparts = explode($variable,$v,2);
155 if (count($mainparts)==2) { // should ALWAYS be....
156 $subparts = explode('//',$mainparts[1],2);
157 $line_array[$k] = $mainparts[0].$variable." = '".$this->slashValueForSingleDashes($value)."'; ".('//'.$comment.str_replace($comment,'',$subparts[1]));
158 $this->touchedLine = count($line_array)-$k-1;
159 $found = 1;
160 break;
161 }
162 } elseif (!strcmp(substr($v2, 0, strlen($varDoubleQuotes . ' ')), $varDoubleQuotes . ' ')) {
163 // Due to a bug in the update wizard (fixed in TYPO3 4.1.7) it is possible
164 // that $TYPO3_CONF_VARS['SYS']['compat_version'] was enclosed by "" (double
165 // quotes) instead of the expected '' (single quotes) when is was written to
166 // localconf.php. The following code was added to make sure that values with
167 // double quotes are updated, too.
168 $mainparts = explode($varDoubleQuotes, $v, 2);
169 if (count($mainparts) == 2) { // should ALWAYS be....
170 $subparts = explode('//', $mainparts[1], 2);
171 $line_array[$k] = $mainparts[0] . $variable . " = '" . $this->slashValueForSingleDashes($value) . "'; " . ('//' . $comment . str_replace($comment, '', $subparts[1]));
172 $this->touchedLine = count($line_array) - $k - 1;
173 $found = 1;
174 break;
175 }
176 }
177 }
178 $line_array = array_reverse($line_array);
179 }
180 if (!$found) {
181 if ($tokenSet) {
182 $line_array[] = $commentKey.$this->localconf_editPointToken;
183 $line_array[] = '';
184 }
185 $line_array[] = $variable." = '".$this->slashValueForSingleDashes($value)."'; // ".$comment;
186 $this->touchedLine = -1;
187 }
188 if ($variable == '$typo_db_password') {
189 $this->messages[] = 'Updated ' . $variable;
190 } else {
191 $this->messages[] = $variable . " = '" . htmlspecialchars($value) . "'";
192 }
193 $this->setLocalconf = 1;
194 }
195
196 /**
197 * Writes or returns lines from localconf.php
198 *
199 * @param array Array of lines to write back to localconf.php. Possibly
200 * @param string Absolute path of alternative file to use (Notice: this path is not validated in terms of being inside 'TYPO3 space')
201 * @return mixed If $inlines is not an array it will return an array with the lines from localconf.php. Otherwise it will return a status string, either "continue" (updated) or "nochange" (not updated)
202 * @see setValueInLocalconfFile()
203 */
204 function writeToLocalconf_control($inlines='',$absFullPath='') {
205 $tmpExt = '.TMP.php';
206 $writeToLocalconf_dat = array();
207 $writeToLocalconf_dat['file'] = $absFullPath ? $absFullPath : PATH_typo3conf.'localconf.php';
208 $writeToLocalconf_dat['tmpfile'] = $writeToLocalconf_dat['file'].$tmpExt;
209
210 // Checking write state of localconf.php:
211 if (!$this->allowUpdateLocalConf) {
212 die('->allowUpdateLocalConf flag in the install object is not set and therefore "localconf.php" cannot be altered.');
213 }
214 if (!@is_writable($writeToLocalconf_dat['file'])) {
215 die($writeToLocalconf_dat['file'].' is not writable!');
216 }
217
218 // Splitting localconf.php file into lines:
219 $lines = explode(chr(10),str_replace(chr(13),'',trim(t3lib_div::getUrl($writeToLocalconf_dat['file']))));
220 $writeToLocalconf_dat['endLine'] = array_pop($lines); // Getting "? >" ending.
221
222 // Checking if "updated" line was set by this tool - if so remove old line.
223 $updatedLine = array_pop($lines);
224 $writeToLocalconf_dat['updatedText'] = '// Updated by '.$this->updateIdentity.' ';
225
226 if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
227 array_push($lines,$updatedLine);
228 }
229
230 if (is_array($inlines)) { // Setting a line and write:
231 // Setting configuration
232 $updatedLine = $writeToLocalconf_dat['updatedText'].date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' H:i:s');
233 array_push($inlines,$updatedLine);
234 array_push($inlines,$writeToLocalconf_dat['endLine']);
235
236 if ($this->setLocalconf) {
237 $success = FALSE;
238 if (!t3lib_div::writeFile($writeToLocalconf_dat['tmpfile'],implode(chr(10),$inlines))) {
239 $msg = 'typo3conf/localconf.php'.$tmpExt.' could not be written - maybe a write access problem?';
240 }
241 elseif (strcmp(t3lib_div::getUrl($writeToLocalconf_dat['tmpfile']), implode(chr(10),$inlines))) {
242 @unlink($writeToLocalconf_dat['tmpfile']);
243 $msg = 'typo3conf/localconf.php'.$tmpExt.' was NOT written properly (written content didn\'t match file content) - maybe a disk space problem?';
244 }
245 elseif (!@copy($writeToLocalconf_dat['tmpfile'],$writeToLocalconf_dat['file'])) {
246 $msg = 'typo3conf/localconf.php could not be replaced by typo3conf/localconf.php'.$tmpExt.' - maybe a write access problem?';
247 }
248 else {
249 @unlink($writeToLocalconf_dat['tmpfile']);
250 $success = TRUE;
251 $msg = 'Configuration written to typo3conf/localconf.php';
252 }
253 $this->messages[] = $msg;
254
255 if ($success) {
256 return 'continue';
257 } else {
258 t3lib_div::sysLog($msg, 'Core', 3);
259 return 'nochange';
260 }
261 } else {
262 return 'nochange';
263 }
264 } else { // Return lines found in localconf.php
265 return $lines;
266 }
267 }
268
269 /**
270 * Checking for linebreaks in the string
271 *
272 * @param string String to test
273 * @return boolean Returns TRUE if string is OK
274 * @see setValueInLocalconfFile()
275 */
276 function checkForBadString($string) {
277 return preg_match('/['.chr(10).chr(13).']/',$string) ? FALSE : TRUE;
278 }
279
280 /**
281 * Replaces ' with \' and \ with \\
282 *
283 * @param string Input value
284 * @return string Output value
285 * @see setValueInLocalconfFile()
286 */
287 function slashValueForSingleDashes($value) {
288 $value = str_replace("'.chr(10).'", '###INSTALL_TOOL_LINEBREAK###', $value);
289 $value = str_replace("'","\'",str_replace('\\','\\\\',$value));
290 $value = str_replace('###INSTALL_TOOL_LINEBREAK###', "'.chr(10).'", $value);
291
292 return $value;
293 }
294
295
296
297
298
299
300
301
302
303
304 /*************************************
305 *
306 * SQL
307 *
308 *************************************/
309
310 /**
311 * Reads the field definitions for the input SQL-file string
312 *
313 * @param string Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
314 * @return array Array with information about table.
315 */
316 function getFieldDefinitions_fileContent($fileContent) {
317 $lines = t3lib_div::trimExplode(chr(10), $fileContent, 1);
318 $table = '';
319 $total = array();
320
321 foreach ($lines as $value) {
322 if (substr($value,0,1)=='#') {
323 continue; // Ignore comments
324 }
325
326 if (!strlen($table)) {
327 $parts = t3lib_div::trimExplode(' ', $value, TRUE);
328 if (strtoupper($parts[0]) === 'CREATE' && strtoupper($parts[1]) === 'TABLE') {
329 $table = str_replace( '`', '', $parts[2]);
330 if (TYPO3_OS=='WIN') { // tablenames are always lowercase on windows!
331 $table = strtolower($table);
332 }
333 }
334 } else {
335 if (substr($value,0,1)==')' && substr($value,-1)==';') {
336 $ttype = array();
337 if (preg_match('/(ENGINE|TYPE)[ ]*=[ ]*([a-zA-Z]*)/',$value,$ttype)) {
338 $total[$table]['extra']['ENGINE'] = $ttype[2];
339 } // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
340
341 // Set the collation, if specified
342 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
343 $total[$table]['extra']['COLLATE'] = $tcollation[2];
344 } else {
345 // 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)
346 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
347 $charset = $tcharset[2];
348 } else {
349 $charset = $GLOBALS['TYPO3_DB']->default_charset; // Fallback to default charset
350 }
351 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
352 }
353
354 $table = ''; // Remove table marker and start looking for the next "CREATE TABLE" statement
355 } else {
356 $lineV = preg_replace('/,$/','',$value); // Strip trailing commas
357 $lineV = str_replace('`', '', $lineV);
358 $lineV = str_replace(' ', ' ', $lineV); // Remove double blanks
359
360 $parts = explode(' ', $lineV, 2);
361 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/',$parts[0])) { // Field definition
362
363 // Make sure there is no default value when auto_increment is set
364 if (stristr($parts[1],'auto_increment')) {
365 $parts[1] = preg_replace('/ default \'0\'/i','',$parts[1]);
366 }
367 // "default" is always lower-case
368 if (stristr($parts[1], ' DEFAULT ')) {
369 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
370 }
371
372 // Change order of "default" and "null" statements
373 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
374 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
375
376 $key = $parts[0];
377 $total[$table]['fields'][$key] = $parts[1];
378
379 } else { // Key definition
380 $search = array('/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/INDEX/');
381 $replace = array('UNIQUE', 'FULLTEXT', 'KEY');
382 $lineV = preg_replace($search, $replace, $lineV);
383
384 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
385 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
386 }
387
388 $newParts = explode(' ',$parts[1],2);
389 $key = $parts[0]=='PRIMARY' ? $parts[0] : $newParts[0];
390
391 $total[$table]['keys'][$key] = $lineV;
392
393 // This is a protection against doing something stupid: Only allow clearing of cache_* and index_* tables.
394 if (preg_match('/^(cache|index)_/',$table)) {
395 // Suggest to truncate (clear) this table
396 $total[$table]['extra']['CLEAR'] = 1;
397 }
398 }
399 }
400 }
401 }
402
403 $this->getFieldDefinitions_sqlContent_parseTypes($total);
404 return $total;
405 }
406
407 /**
408 * Multiplies varchars/tinytext fields in size according to $this->multiplySize
409 * 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.
410 *
411 * @param array Total array (from getFieldDefinitions_fileContent())
412 * @return void
413 * @access private
414 * @see getFieldDefinitions_fileContent()
415 */
416 function getFieldDefinitions_sqlContent_parseTypes(&$total) {
417
418 $mSize = (double)$this->multiplySize;
419 if ($mSize > 1) {
420
421 // Init SQL parser:
422 $sqlParser = t3lib_div::makeInstance('t3lib_sqlparser');
423 foreach($total as $table => $cfg) {
424 if (is_array($cfg['fields'])) {
425 foreach($cfg['fields'] as $fN => $fType) {
426 $orig_fType = $fType;
427 $fInfo = $sqlParser->parseFieldDef($fType);
428
429 switch($fInfo['fieldType']) {
430 case 'char':
431 case 'varchar':
432 $newSize = round($fInfo['value']*$mSize);
433
434 if ($newSize <= 255) {
435 $fInfo['value'] = $newSize;
436 } else {
437 $fInfo = array(
438 'fieldType' => 'text',
439 'featureIndex' => array(
440 'NOTNULL' => array(
441 'keyword' => 'NOT NULL'
442 )
443 )
444 );
445 // Change key definition if necessary (must use "prefix" on TEXT columns)
446 if (is_array($cfg['keys'])) {
447 foreach ($cfg['keys'] as $kN => $kType) {
448 $match = array();
449 preg_match('/^([^(]*)\(([^)]+)\)(.*)/', $kType, $match);
450 $keys = array();
451 foreach (t3lib_div::trimExplode(',',$match[2]) as $kfN) {
452 if ($fN == $kfN) {
453 $kfN .= '('.$newSize.')';
454 }
455 $keys[] = $kfN;
456 }
457 $total[$table]['keys'][$kN] = $match[1].'('.implode(',',$keys).')'.$match[3];
458 }
459 }
460 }
461 break;
462 case 'tinytext':
463 $fInfo['fieldType'] = 'text';
464 break;
465 }
466
467 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
468 if ($sqlParser->parse_error) die($sqlParser->parse_error);
469 }
470 }
471 }
472 }
473 }
474
475 /**
476 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
477 *
478 * @param string Character set
479 * @return string Corresponding default collation
480 */
481 function getCollationForCharset($charset) {
482 // Load character sets, if not cached already
483 if (!count($this->character_sets)) {
484 if (method_exists($GLOBALS['TYPO3_DB'],'admin_get_charsets')) {
485 $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
486 } else {
487 $this->character_sets[$charset] = array(); // Add empty element to avoid that the check will be repeated
488 }
489 }
490
491 $collation = '';
492 if (isset($this->character_sets[$charset]['Default collation'])) {
493 $collation = $this->character_sets[$charset]['Default collation'];
494 }
495
496 return $collation;
497 }
498
499 /**
500 * Reads the field definitions for the current database
501 *
502 * @return array Array with information about table.
503 */
504 function getFieldDefinitions_database() {
505 $total = array();
506 $tempKeys = array();
507 $tempKeysPrefix = array();
508
509 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db);
510 echo $GLOBALS['TYPO3_DB']->sql_error();
511
512 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
513 foreach ($tables as $tableName => $tableStatus) {
514
515 // Fields:
516 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
517 foreach ($fieldInformation as $fN => $fieldRow) {
518 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
519 }
520
521 // Keys:
522 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
523
524 foreach ($keyInformation as $keyRow) {
525 $keyName = $keyRow['Key_name'];
526 $colName = $keyRow['Column_name'];
527 if ($keyRow['Sub_part']) {
528 $colName.= '('.$keyRow['Sub_part'].')';
529 }
530 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
531 if ($keyName=='PRIMARY') {
532 $prefix = 'PRIMARY KEY';
533 } else {
534 if ($keyRow['Index_type']=='FULLTEXT') {
535 $prefix = 'FULLTEXT';
536 } elseif ($keyRow['Non_unique']) {
537 $prefix = 'KEY';
538 } else {
539 $prefix = 'UNIQUE';
540 }
541 $prefix.= ' '.$keyName;
542 }
543 $tempKeysPrefix[$tableName][$keyName] = $prefix;
544 }
545
546 // Table status (storage engine, collaction, etc.)
547 if (is_array($tableStatus)) {
548 $tableExtraFields = array(
549 'Engine' => 'ENGINE',
550 'Collation' => 'COLLATE',
551 );
552
553 foreach ($tableExtraFields as $mysqlKey=>$internalKey) {
554 if (isset($tableStatus[$mysqlKey])) {
555 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
556 }
557 }
558 }
559 }
560
561 // Compile key information:
562 if (count($tempKeys)) {
563 foreach ($tempKeys as $table => $keyInf) {
564 foreach ($keyInf as $kName => $index) {
565 ksort($index);
566 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName].' ('.implode(',',$index).')';
567 }
568 }
569 }
570
571 return $total;
572 }
573
574 /**
575 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
576 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
577 *
578 * @param array Field definitions, source (from getFieldDefinitions_fileContent())
579 * @param array Field definitions, comparison. (from getFieldDefinitions_database())
580 * @param string Table names (in list) which is the ONLY one observed.
581 * @param boolean 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.
582 * @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
583 */
584 function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='',$ignoreNotNullWhenComparing=true) {
585 $extraArr = array();
586 $diffArr = array();
587
588 if (is_array($FDsrc)) {
589 foreach ($FDsrc as $table => $info) {
590 if (!strlen($onlyTableList) || t3lib_div::inList($onlyTableList, $table)) {
591 if (!isset($FDcomp[$table])) {
592 $extraArr[$table] = $info; // If the table was not in the FDcomp-array, the result array is loaded with that table.
593 $extraArr[$table]['whole_table']=1;
594 } else {
595 $keyTypes = explode(',','extra,fields,keys');
596 foreach ($keyTypes as $theKey) {
597 if (is_array($info[$theKey])) {
598 foreach ($info[$theKey] as $fieldN => $fieldC) {
599 $fieldN = str_replace('`','',$fieldN);
600 if ($fieldN=='COLLATE') {
601 continue; // TODO: collation support is currently disabled (needs more testing)
602 }
603
604 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
605 $extraArr[$table][$theKey][$fieldN] = $fieldC;
606 } else {
607 $fieldC = trim($fieldC);
608 if ($ignoreNotNullWhenComparing) {
609 $fieldC = str_replace(' NOT NULL', '', $fieldC);
610 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
611 }
612 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
613 $diffArr[$table][$theKey][$fieldN] = $fieldC;
614 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
615 }
616 }
617 }
618 }
619 }
620 }
621 }
622 }
623 }
624
625 $output = array(
626 'extra' => $extraArr,
627 'diff' => $diffArr,
628 'diff_currentValues' => $diffArr_cur
629 );
630
631 return $output;
632 }
633
634 /**
635 * Returns an array with SQL-statements that is needed to update according to the diff-array
636 *
637 * @param array Array with differences of current and needed DB settings. (from getDatabaseExtra())
638 * @param string List of fields in diff array to take notice of.
639 * @return array Array of SQL statements (organized in keys depending on type)
640 */
641 function getUpdateSuggestions($diffArr,$keyList='extra,diff') {
642 $statements = array();
643 $deletedPrefixKey = $this->deletedPrefixKey;
644 $remove = 0;
645 if ($keyList == 'remove') {
646 $remove = 1;
647 $keyList = 'extra';
648 }
649 $keyList = explode(',',$keyList);
650 foreach ($keyList as $theKey) {
651 if (is_array($diffArr[$theKey])) {
652 foreach ($diffArr[$theKey] as $table => $info) {
653 $whole_table = array();
654 if (is_array($info['fields'])) {
655 foreach ($info['fields'] as $fN => $fV) {
656 if ($info['whole_table']) {
657 $whole_table[]=$fN.' '.$fV;
658 } else {
659 // Special case to work around MySQL problems when adding auto_increment fields:
660 if (stristr($fV, 'auto_increment')) {
661 // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
662 // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
663 if (isset($diffArr['extra'][$table]['keys']['PRIMARY'])) {
664 // Remove "auto_increment" from the statement - it will be suggested in a 2nd step after the primary key was created
665 $fV = str_replace(' auto_increment', '', $fV);
666 } else {
667 // In the next step, attempt to clear the table once again (2 = force)
668 $info['extra']['CLEAR'] = 2;
669 }
670 }
671 if ($theKey=='extra') {
672 if ($remove) {
673 if (substr($fN,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
674 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$deletedPrefixKey.$fN.' '.$fV.';';
675 $statements['change'][md5($statement)] = $statement;
676 } else {
677 $statement = 'ALTER TABLE '.$table.' DROP '.$fN.';';
678 $statements['drop'][md5($statement)] = $statement;
679 }
680 } else {
681 $statement = 'ALTER TABLE '.$table.' ADD '.$fN.' '.$fV.';';
682 $statements['add'][md5($statement)] = $statement;
683 }
684 } elseif ($theKey=='diff') {
685 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$fN.' '.$fV.';';
686 $statements['change'][md5($statement)] = $statement;
687 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
688 }
689 }
690 }
691 }
692 if (is_array($info['keys'])) {
693 foreach ($info['keys'] as $fN => $fV) {
694 if ($info['whole_table']) {
695 $whole_table[] = $fV;
696 } else {
697 if ($theKey=='extra') {
698 if ($remove) {
699 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
700 $statements['drop'][md5($statement)] = $statement;
701 } else {
702 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
703 $statements['add'][md5($statement)] = $statement;
704 }
705 } elseif ($theKey=='diff') {
706 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
707 $statements['change'][md5($statement)] = $statement;
708 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
709 $statements['change'][md5($statement)] = $statement;
710 }
711 }
712 }
713 }
714 if (is_array($info['extra'])) {
715 $extras = array();
716 $extras_currentValue = array();
717 $clear_table = false;
718
719 foreach ($info['extra'] as $fN => $fV) {
720
721 // Only consider statements which are missing in the database but don't remove existing properties
722 if (!$remove) {
723 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']
724 if ($fN=='CLEAR') {
725 // Truncate table must happen later, not now
726 // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
727 if (count($info['keys']) || $fV==2) {
728 $clear_table = true;
729 }
730 continue;
731 } else {
732 $extras[] = $fN.'='.$fV;
733 $extras_currentValue[] = $fN.'='.$diffArr['diff_currentValues'][$table]['extra'][$fN];
734 }
735 }
736 }
737 }
738 if ($clear_table) {
739 $statement = 'TRUNCATE TABLE '.$table.';';
740 $statements['clear_table'][md5($statement)] = $statement;
741 }
742 if (count($extras)) {
743 $statement = 'ALTER TABLE '.$table.' '.implode(' ',$extras).';';
744 $statements['change'][md5($statement)] = $statement;
745 $statements['change_currentValue'][md5($statement)] = implode(' ',$extras_currentValue);
746 }
747 }
748 if ($info['whole_table']) {
749 if ($remove) {
750 if (substr($table,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
751 $statement = 'ALTER TABLE '.$table.' RENAME '.$deletedPrefixKey.$table.';';
752 $statements['change_table'][md5($statement)] = $statement;
753 } else {
754 $statement = 'DROP TABLE '.$table.';';
755 $statements['drop_table'][md5($statement)] = $statement;
756 }
757 // count:
758 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', $table);
759 $statements['tables_count'][md5($statement)] = $count?'Records in table: '.$count:'';
760 } else {
761 $statement = 'CREATE TABLE '.$table." (\n".implode(",\n",$whole_table)."\n)";
762 if ($info['extra']) {
763 foreach ($info['extra'] as $k=>$v) {
764 if ($k=='COLLATE' || $k=='CLEAR') {
765 continue; // Skip these special statements. TODO: collation support is currently disabled (needs more testing)
766 }
767 $statement.= ' '.$k.'='.$v; // Add extra attributes like ENGINE, CHARSET, etc.
768 }
769 }
770 $statement.= ';';
771 $statements['create_table'][md5($statement)] = $statement;
772 }
773 }
774 }
775 }
776 }
777
778 return $statements;
779 }
780
781 /**
782 * Converts a result row with field information into the SQL field definition string
783 *
784 * @param array MySQL result row
785 * @return string Field definition
786 */
787 function assembleFieldDefinition($row) {
788 $field = array($row['Type']);
789
790 if ($row['Null']=='NO') {
791 $field[] = 'NOT NULL';
792 }
793 if (!strstr($row['Type'],'blob') && !strstr($row['Type'],'text')) {
794 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
795 if (!stristr($row['Extra'],'auto_increment')) {
796 $field[] = 'default \''.addslashes($row['Default']).'\'';
797 }
798 }
799 if ($row['Extra']) {
800 $field[] = $row['Extra'];
801 }
802
803 return implode(' ',$field);
804 }
805
806 /**
807 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
808 *
809 * @param string 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.
810 * @param boolean If set, non-SQL content (like comments and blank lines) is not included in the final output
811 * @param string Regex to filter SQL lines to include
812 * @return array Array of SQL statements
813 */
814 function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='') {
815 $sqlcodeArr = explode(chr(10), $sqlcode);
816
817 // Based on the assumption that the sql-dump has
818 $statementArray = array();
819 $statementArrayPointer = 0;
820
821 foreach ($sqlcodeArr as $line => $lineContent) {
822 $is_set = 0;
823
824 // auto_increment fields cannot have a default value!
825 if (stristr($lineContent,'auto_increment')) {
826 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
827 }
828
829 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
830 $statementArray[$statementArrayPointer].= $lineContent;
831 $is_set = 1;
832 }
833 if (substr(trim($lineContent),-1)==';') {
834 if (isset($statementArray[$statementArrayPointer])) {
835 if (!trim($statementArray[$statementArrayPointer]) || ($query_regex && !preg_match('/'.$query_regex.'/i',trim($statementArray[$statementArrayPointer])))) {
836 unset($statementArray[$statementArrayPointer]);
837 }
838 }
839 $statementArrayPointer++;
840
841 } elseif ($is_set) {
842 $statementArray[$statementArrayPointer].= chr(10);
843 }
844 }
845
846 return $statementArray;
847 }
848
849 /**
850 * Returns tables to create and how many records in each
851 *
852 * @param array Array of SQL statements to analyse.
853 * @param boolean If set, will count number of INSERT INTO statements following that table definition
854 * @return array Array with table definitions in index 0 and count in index 1
855 */
856 function getCreateTables($statements, $insertCountFlag=0) {
857 $crTables = array();
858 $insertCount = array();
859 foreach ($statements as $line => $lineContent) {
860 $reg = array();
861 if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($lineContent,0,100),$reg)) {
862 $table = trim($reg[1]);
863 if ($table) {
864 // table names are always lowercase on Windows!
865 if (TYPO3_OS == 'WIN') {
866 $table = strtolower($table);
867 }
868 $sqlLines = explode(chr(10), $lineContent);
869 foreach ($sqlLines as $k=>$v) {
870 if (stristr($v,'auto_increment')) {
871 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
872 }
873 }
874 $lineContent = implode(chr(10), $sqlLines);
875 $crTables[$table] = $lineContent;
876 }
877 } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($lineContent,0,100),$reg)) {
878 $nTable = trim($reg[1]);
879 $insertCount[$nTable]++;
880 }
881 }
882
883 return array($crTables,$insertCount);
884 }
885
886 /**
887 * Extracts all insert statements from $statement array where content is inserted into $table
888 *
889 * @param array Array of SQL statements
890 * @param string Table name
891 * @return array Array of INSERT INTO statements where table match $table
892 */
893 function getTableInsertStatements($statements, $table) {
894 $outStatements=array();
895 foreach($statements as $line => $lineContent) {
896 $reg = array();
897 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($lineContent,0,100),$reg)) {
898 $nTable = trim($reg[1]);
899 if ($nTable && !strcmp($table,$nTable)) {
900 $outStatements[] = $lineContent;
901 }
902 }
903 }
904 return $outStatements;
905 }
906
907 /**
908 * Performs the queries passed from the input array.
909 *
910 * @param array Array of SQL queries to execute.
911 * @param array 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)
912 * @return mixed Array with error message from database if any occured. Otherwise true if everything was executed successfully.
913 */
914 function performUpdateQueries($arr,$keyArr) {
915 $result = array();
916 if (is_array($arr)) {
917 foreach($arr as $key => $string) {
918 if (isset($keyArr[$key]) && $keyArr[$key]) {
919 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
920 if ($res === false) {
921 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
922 } elseif (is_resource($res)) {
923 $GLOBALS['TYPO3_DB']->sql_free_result($res);
924 }
925 }
926 }
927 }
928 if (count($result) > 0) {
929 return $result;
930 } else {
931 return true;
932 }
933 }
934
935 /**
936 * Returns list of tables in the database
937 *
938 * @return array List of tables.
939 * @see t3lib_db::admin_get_tables()
940 */
941 function getListOfTables() {
942 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
943 foreach ($whichTables as $key=>&$value) {
944 $value = $key;
945 }
946 return $whichTables;
947 }
948
949 /**
950 * Creates a table which checkboxes for updating database.
951 *
952 * @param array Array of statements (key / value pairs where key is used for the checkboxes)
953 * @param string Label for the table.
954 * @param boolean If set, then checkboxes are set by default.
955 * @param boolean If set, then icons are shown.
956 * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
957 * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
958 * @return string HTML table with checkboxes for update. Must be wrapped in a form.
959 */
960 function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0) {
961 $out = array();
962 if (is_array($arr)) {
963 $tableId = uniqid('table');
964 if (count($arr) > 1) {
965 $out[] = '
966 <tr class="update-db-fields-batch">
967 <td valign="top">
968 <input type="checkbox" id="' . $tableId . '-checkbox"' . ($checked ? ' checked="checked"' : '') . '
969 onclick="$(\'' . $tableId . '\').select(\'input[type=checkbox]\').invoke(\'setValue\', $(this).checked);" />
970 </td>
971 <td nowrap="nowrap"><label for="' . $tableId . '-checkbox" style="cursor:pointer"><strong>select/deselect all</strong></label></td>
972 </tr>';
973 }
974 foreach($arr as $key => $string) {
975 $ico = '';
976 $warnings = array();
977
978 if ($iconDis) {
979 if (preg_match('/^TRUNCATE/i',$string)) {
980 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong> </strong>';
981 $warnings['clear_table_info'] = 'Clearing the table is sometimes neccessary when adding new keys. In case of cache_* tables this should not hurt at all. However, use it with care.';
982 } elseif (stristr($string,' user_')) {
983 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
984 } elseif (stristr($string,' app_')) {
985 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
986 } elseif (stristr($string,' ttx_') || stristr($string,' tx_')) {
987 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
988 }
989 }
990 $out[]='
991 <tr>
992 <td valign="top"><input type="checkbox" id="db-'.$key.'" name="'.$this->dbUpdateCheckboxPrefix.'['.$key.']" value="1"'.($checked?' checked="checked"':'').' /></td>
993 <td nowrap="nowrap"><label for="db-'.$key.'">'.nl2br($ico.htmlspecialchars($string)).'</label></td>
994 </tr>';
995 if (isset($currentValue[$key])) {
996 $out[]='
997 <tr>
998 <td valign="top"></td>
999 <td nowrap="nowrap" style="color:#666666;">'.nl2br((!$cVfullMsg?"Current value: ":"").'<em>'.$currentValue[$key].'</em>').'</td>
1000 </tr>';
1001 }
1002 }
1003 if (count($warnings)) {
1004 $out[] = '
1005 <tr>
1006 <td valign="top"></td>
1007 <td style="color:#666666;"><em>' . implode('<br />',$warnings) . '</em></td>
1008 </tr>';
1009 }
1010
1011 // Compile rows:
1012 $content = '
1013 <!-- Update database fields / tables -->
1014 <h3>'.$label.'</h3>
1015 <table border="0" cellpadding="2" cellspacing="2" id="' . $tableId . '" class="update-db-fields">' . implode('', $out) . '
1016 </table>';
1017 }
1018
1019 return $content;
1020 }
1021
1022 /**
1023 * Reads the field definitions for the input SQL-file string
1024 *
1025 * @param string Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
1026 * @return array Array with information about table.
1027 * @deprecated since TYPO3 4.2, this function will be removed in TYPO3 4.5, use ->getFieldDefinitions_fileContent() instead!
1028 */
1029 function getFieldDefinitions_sqlContent($fileContent) {
1030 t3lib_div::logDeprecatedFunction();
1031
1032 return $this->getFieldDefinitions_fileContent($fileContent);
1033 }
1034 }
1035
1036 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']) {
1037 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']);
1038 }
1039
1040 ?>