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