* 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 } // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
319
320 // Set the collation, if specified
321 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
322 $total[$table]['extra']['COLLATE'] = $tcollation[2];
323 } else {
324 // 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)
325 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
326 $charset = $tcharset[2];
327 } else {
328 $charset = $GLOBALS['TYPO3_DB']->default_charset; // Fallback to default charset
329 }
330 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
331 }
332
333 $table = ''; // Remove table marker and start looking for the next "CREATE TABLE" statement
334 } else {
335 $lineV = preg_replace('/,$/','',$value); // Strip trailing commas
336 $lineV = str_replace('`', '', $lineV);
337 $lineV = str_replace(' ', ' ', $lineV); // Remove double blanks
338
339 $parts = explode(' ', $lineV, 2);
340 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/',$parts[0])) { // Field definition
341
342 // Make sure there is no default value when auto_increment is set
343 if (stristr($parts[1],'auto_increment')) {
344 $parts[1] = preg_replace('/ default \'0\'/i','',$parts[1]);
345 }
346 // "default" is always lower-case
347 if (stristr($parts[1], ' DEFAULT ')) {
348 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
349 }
350
351 // Change order of "default" and "null" statements
352 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
353 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
354
355 $key = $parts[0];
356 $total[$table]['fields'][$key] = $parts[1];
357
358 } else { // Key definition
359 $search = array('/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/INDEX/');
360 $replace = array('UNIQUE', 'FULLTEXT', 'KEY');
361 $lineV = preg_replace($search, $replace, $lineV);
362
363 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
364 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
365 }
366
367 $newParts = explode(' ',$parts[1],2);
368 $key = $parts[0]=='PRIMARY' ? $parts[0] : $newParts[0];
369 $total[$table]['keys'][$key] = $lineV;
370 }
371 }
372 }
373 }
374
375 $this->getFieldDefinitions_sqlContent_parseTypes($total);
376 return $total;
377 }
378
379 /**
380 * Multiplies varchars/tinytext fields in size according to $this->multiplySize
381 * 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.
382 *
383 * @param array Total array (from getFieldDefinitions_fileContent())
384 * @return void
385 * @access private
386 * @see getFieldDefinitions_fileContent()
387 */
388 function getFieldDefinitions_sqlContent_parseTypes(&$total) {
389
390 $mSize = (double)$this->multiplySize;
391 if ($mSize > 1) {
392
393 // Init SQL parser:
394 $sqlParser = t3lib_div::makeInstance('t3lib_sqlparser');
395 foreach($total as $table => $cfg) {
396 if (is_array($cfg['fields'])) {
397 foreach($cfg['fields'] as $fN => $fType) {
398 $orig_fType = $fType;
399 $fInfo = $sqlParser->parseFieldDef($fType);
400
401 switch($fInfo['fieldType']) {
402 case 'char':
403 case 'varchar':
404 $newSize = round($fInfo['value']*$mSize);
405
406 if ($newSize <= 255) {
407 $fInfo['value'] = $newSize;
408 } else {
409 $fInfo = array(
410 'fieldType' => 'text',
411 'featureIndex' => array(
412 'NOTNULL' => array(
413 'keyword' => 'NOT NULL'
414 )
415 )
416 );
417 // Change key definition if necessary (must use "prefix" on TEXT columns)
418 if (is_array($cfg['keys'])) {
419 foreach ($cfg['keys'] as $kN => $kType) {
420 $match = array();
421 preg_match('/^([^(]*)\(([^)]+)\)(.*)/', $kType, $match);
422 $keys = array();
423 foreach (t3lib_div::trimExplode(',',$match[2]) as $kfN) {
424 if ($fN == $kfN) {
425 $kfN .= '('.$newSize.')';
426 }
427 $keys[] = $kfN;
428 }
429 $total[$table]['keys'][$kN] = $match[1].'('.join(',',$keys).')'.$match[3];
430 }
431 }
432 }
433 break;
434 case 'tinytext':
435 $fInfo['fieldType'] = 'text';
436 break;
437 }
438
439 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
440 if ($sqlParser->parse_error) die($sqlParser->parse_error);
441 }
442 }
443 }
444 }
445 }
446
447 /**
448 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
449 *
450 * @param string Character set
451 * @return string Corresponding default collation
452 */
453 function getCollationForCharset($charset) {
454 // Load character sets, if not cached already
455 if (!count($this->character_sets)) {
456 $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
457 }
458
459 if (isset($this->character_sets[$charset]['Default collation'])) {
460 $collation = $this->character_sets[$charset]['Default collation'];
461 }
462
463 return $collation;
464 }
465
466 /**
467 * Reads the field definitions for the current database
468 *
469 * @return array Array with information about table.
470 */
471 function getFieldDefinitions_database() {
472 $total = array();
473 $tempKeys = array();
474 $tempKeysPrefix = array();
475
476 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db);
477 echo $GLOBALS['TYPO3_DB']->sql_error();
478
479 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
480 foreach ($tables as $tableName => $tableStatus) {
481
482 // Fields:
483 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
484 foreach ($fieldInformation as $fN => $fieldRow) {
485 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
486 }
487
488 // Keys:
489 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
490
491 foreach ($keyInformation as $keyRow) {
492 $keyName = $keyRow['Key_name'];
493 $colName = $keyRow['Column_name'];
494 if ($keyRow['Sub_part']) {
495 $colName.= '('.$keyRow['Sub_part'].')';
496 }
497 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
498 if ($keyName=='PRIMARY') {
499 $prefix = 'PRIMARY KEY';
500 } else {
501 if ($keyRow['Index_type']=='FULLTEXT') {
502 $prefix = 'FULLTEXT';
503 } elseif ($keyRow['Non_unique']) {
504 $prefix = 'KEY';
505 } else {
506 $prefix = 'UNIQUE';
507 }
508 $prefix.= ' '.$keyName;
509 }
510 $tempKeysPrefix[$tableName][$keyName] = $prefix;
511 }
512
513 // Table status (storage engine, collaction, etc.)
514 if (is_array($tableStatus)) {
515 $tableExtraFields = array(
516 'Engine' => 'ENGINE',
517 'Collation' => 'COLLATE',
518 );
519
520 foreach ($tableExtraFields as $mysqlKey=>$internalKey) {
521 if (isset($tableStatus[$mysqlKey])) {
522 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
523 }
524 }
525 }
526 }
527
528 // Compile key information:
529 if (count($tempKeys)) {
530 foreach ($tempKeys as $table => $keyInf) {
531 foreach ($keyInf as $kName => $index) {
532 ksort($index);
533 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName].' ('.implode(',',$index).')';
534 }
535 }
536 }
537
538 return $total;
539 }
540
541 /**
542 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
543 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
544 *
545 * @param array Field definitions, source (from getFieldDefinitions_fileContent())
546 * @param array Field definitions, comparison. (from getFieldDefinitions_database())
547 * @param string Table names (in list) which is the ONLY one observed.
548 * @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.
549 * @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
550 */
551 function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='',$ignoreNotNullWhenComparing=true) {
552 $extraArr = array();
553 $diffArr = array();
554
555 if (is_array($FDsrc)) {
556 foreach ($FDsrc as $table => $info) {
557 if (!strlen($onlyTableList) || t3lib_div::inList($onlyTableList, $table)) {
558 if (!isset($FDcomp[$table])) {
559 $extraArr[$table] = $info; // If the table was not in the FDcomp-array, the result array is loaded with that table.
560 $extraArr[$table]['whole_table']=1;
561 } else {
562 $keyTypes = explode(',','extra,fields,keys');
563 foreach ($keyTypes as $theKey) {
564 if (is_array($info[$theKey])) {
565 foreach ($info[$theKey] as $fieldN => $fieldC) {
566 $fieldN = str_replace('`','',$fieldN);
567 if ($fieldN=='COLLATE') {
568 continue; // TODO: collation support is currently disabled (needs more testing)
569 }
570
571 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
572 $extraArr[$table][$theKey][$fieldN] = $fieldC;
573 } else {
574 $fieldC = trim($fieldC);
575 if ($ignoreNotNullWhenComparing) {
576 $fieldC = str_replace(' NOT NULL', '', $fieldC);
577 $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
578 }
579 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
580 $diffArr[$table][$theKey][$fieldN] = $fieldC;
581 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
582 }
583 }
584 }
585 }
586 }
587 }
588 }
589 }
590 }
591
592 $output = array(
593 'extra' => $extraArr,
594 'diff' => $diffArr,
595 'diff_currentValues' => $diffArr_cur
596 );
597
598 return $output;
599 }
600
601 /**
602 * Returns an array with SQL-statements that is needed to update according to the diff-array
603 *
604 * @param array Array with differences of current and needed DB settings. (from getDatabaseExtra())
605 * @param string List of fields in diff array to take notice of.
606 * @return array Array of SQL statements (organized in keys depending on type)
607 */
608 function getUpdateSuggestions($diffArr,$keyList='extra,diff') {
609 $statements = array();
610 $deletedPrefixKey = $this->deletedPrefixKey;
611 $remove = 0;
612 if ($keyList == 'remove') {
613 $remove = 1;
614 $keyList = 'extra';
615 }
616 $keyList = explode(',',$keyList);
617 foreach ($keyList as $theKey) {
618 if (is_array($diffArr[$theKey])) {
619 foreach ($diffArr[$theKey] as $table => $info) {
620 $whole_table = array();
621 if (is_array($info['fields'])) {
622 foreach ($info['fields'] as $fN => $fV) {
623 if ($info['whole_table']) {
624 $whole_table[]=$fN.' '.$fV;
625 } else {
626 if ($theKey=='extra') {
627 if ($remove) {
628 if (substr($fN,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
629 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$deletedPrefixKey.$fN.' '.$fV.';';
630 $statements['change'][md5($statement)] = $statement;
631 } else {
632 $statement = 'ALTER TABLE '.$table.' DROP '.$fN.';';
633 $statements['drop'][md5($statement)] = $statement;
634 }
635 } else {
636 $statement = 'ALTER TABLE '.$table.' ADD '.$fN.' '.$fV.';';
637 $statements['add'][md5($statement)] = $statement;
638 }
639 } elseif ($theKey=='diff') {
640 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$fN.' '.$fV.';';
641 $statements['change'][md5($statement)] = $statement;
642 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
643 }
644 }
645 }
646 }
647 if (is_array($info['keys'])) {
648 foreach ($info['keys'] as $fN => $fV) {
649 if ($info['whole_table']) {
650 $whole_table[] = $fV;
651 } else {
652 if ($theKey=='extra') {
653 if ($remove) {
654 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
655 $statements['drop'][md5($statement)] = $statement;
656 } else {
657 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
658 $statements['add'][md5($statement)] = $statement;
659 }
660 } elseif ($theKey=='diff') {
661 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
662 $statements['change'][md5($statement)] = $statement;
663 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
664 $statements['change'][md5($statement)] = $statement;
665 }
666 }
667 }
668 }
669 if (is_array($info['extra'])) {
670 $extras = array();
671 $extras_currentValue = array();
672 foreach ($info['extra'] as $fN => $fV) {
673
674 // Only consider statements which are missing in the database but don't remove existing properties
675 if (!$remove) {
676 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']
677 $extras[] = $fN.'='.$fV;
678 $extras_currentValue[] = $fN.'='.$diffArr['diff_currentValues'][$table]['extra'][$fN];
679 }
680 }
681 }
682 if (count($extras)) {
683 $statement = 'ALTER TABLE '.$table.' '.implode(' ',$extras).';';
684 $statements['change'][md5($statement)] = $statement;
685 $statements['change_currentValue'][md5($statement)] = implode(' ',$extras_currentValue);
686 }
687 }
688 if ($info['whole_table']) {
689 if ($remove) {
690 if (substr($table,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
691 $statement = 'ALTER TABLE '.$table.' RENAME '.$deletedPrefixKey.$table.';';
692 $statements['change_table'][md5($statement)] = $statement;
693 } else {
694 $statement = 'DROP TABLE '.$table.';';
695 $statements['drop_table'][md5($statement)] = $statement;
696 }
697 // count:
698 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, '');
699 list($count) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
700 $statements['tables_count'][md5($statement)] = $count?'Records in table: '.$count:'';
701 } else {
702 $statement = 'CREATE TABLE '.$table." (\n".implode(",\n",$whole_table)."\n)";
703 if ($info['extra']) {
704 foreach ($info['extra'] as $k=>$v) {
705 $statement.= ' '.$k.'='.$v; // Add extra attributes like ENGINE, CHARSET, etc.
706 }
707 }
708 $statement.= ';';
709 $statements['create_table'][md5($statement)] = $statement;
710 }
711 }
712 }
713 }
714 }
715
716 return $statements;
717 }
718
719 /**
720 * Converts a result row with field information into the SQL field definition string
721 *
722 * @param array MySQL result row
723 * @return string Field definition
724 */
725 function assembleFieldDefinition($row) {
726 $field = array($row['Type']);
727
728 if ($row['Null']=='NO') {
729 $field[] = 'NOT NULL';
730 }
731 if (!strstr($row['Type'],'blob') && !strstr($row['Type'],'text')) {
732 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
733 if (!stristr($row['Extra'],'auto_increment')) {
734 $field[] = 'default \''.addslashes($row['Default']).'\'';
735 }
736 }
737 if ($row['Extra']) {
738 $field[] = $row['Extra'];
739 }
740
741 return implode(' ',$field);
742 }
743
744 /**
745 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
746 *
747 * @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.
748 * @param boolean If set, non-SQL content (like comments and blank lines) is not included in the final output
749 * @param string Regex to filter SQL lines to include
750 * @return array Array of SQL statements
751 */
752 function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='') {
753 $sqlcodeArr = explode(chr(10), $sqlcode);
754
755 // Based on the assumption that the sql-dump has
756 $statementArray = array();
757 $statementArrayPointer = 0;
758
759 foreach ($sqlcodeArr as $line => $lineContent) {
760 $is_set = 0;
761
762 // auto_increment fields cannot have a default value!
763 if (stristr($lineContent,'auto_increment')) {
764 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
765 }
766
767 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
768 $statementArray[$statementArrayPointer].= $lineContent;
769 $is_set = 1;
770 }
771 if (substr(trim($lineContent),-1)==';') {
772 if (isset($statementArray[$statementArrayPointer])) {
773 if (!trim($statementArray[$statementArrayPointer]) || ($query_regex && !eregi($query_regex,trim($statementArray[$statementArrayPointer])))) {
774 unset($statementArray[$statementArrayPointer]);
775 }
776 }
777 $statementArrayPointer++;
778
779 } elseif ($is_set) {
780 $statementArray[$statementArrayPointer].= chr(10);
781 }
782 }
783
784 return $statementArray;
785 }
786
787 /**
788 * Returns tables to create and how many records in each
789 *
790 * @param array Array of SQL statements to analyse.
791 * @param boolean If set, will count number of INSERT INTO statements following that table definition
792 * @return array Array with table definitions in index 0 and count in index 1
793 */
794 function getCreateTables($statements, $insertCountFlag=0) {
795 $crTables = array();
796 $insertCount = array();
797 foreach ($statements as $line => $lineContent) {
798 $reg = array();
799 if (eregi('^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($lineContent,0,100),$reg)) {
800 $table = trim($reg[1]);
801 if ($table) {
802 // table names are always lowercase on Windows!
803 if (TYPO3_OS == 'WIN') {
804 $table = strtolower($table);
805 }
806 $sqlLines = explode(chr(10), $lineContent);
807 foreach ($sqlLines as $k=>$v) {
808 if (stristr($v,'auto_increment')) {
809 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
810 }
811 }
812 $lineContent = implode(chr(10), $sqlLines);
813 $crTables[$table] = $lineContent;
814 }
815 } elseif ($insertCountFlag && eregi('^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($lineContent,0,100),$reg)) {
816 $nTable = trim($reg[1]);
817 $insertCount[$nTable]++;
818 }
819 }
820
821 return array($crTables,$insertCount);
822 }
823
824 /**
825 * Extracts all insert statements from $statement array where content is inserted into $table
826 *
827 * @param array Array of SQL statements
828 * @param string Table name
829 * @return array Array of INSERT INTO statements where table match $table
830 */
831 function getTableInsertStatements($statements, $table) {
832 $outStatements=array();
833 foreach($statements as $line => $lineContent) {
834 $reg = array();
835 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($lineContent,0,100),$reg)) {
836 $nTable = trim($reg[1]);
837 if ($nTable && !strcmp($table,$nTable)) {
838 $outStatements[] = $lineContent;
839 }
840 }
841 }
842 return $outStatements;
843 }
844
845 /**
846 * Performs the queries passed from the input array.
847 *
848 * @param array Array of SQL queries to execute.
849 * @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)
850 * @return mixed Array with error message from database if any occured. Otherwise true if everything was executed successfully.
851 */
852 function performUpdateQueries($arr,$keyArr) {
853 $result = array();
854 if (is_array($arr)) {
855 foreach($arr as $key => $string) {
856 if (isset($keyArr[$key]) && $keyArr[$key]) {
857 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
858 if ($res === false) {
859 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
860 } elseif (is_resource($res)) {
861 $GLOBALS['TYPO3_DB']->sql_free_result($res);
862 }
863 }
864 }
865 }
866 if (count($result) > 0) {
867 return $result;
868 } else {
869 return true;
870 }
871 }
872
873 /**
874 * Returns list of tables in the database
875 *
876 * @return array List of tables.
877 * @see t3lib_db::admin_get_tables()
878 */
879 function getListOfTables() {
880 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
881 return array_keys($whichTables);
882 }
883
884 /**
885 * Creates a table which checkboxes for updating database.
886 *
887 * @param array Array of statements (key / value pairs where key is used for the checkboxes)
888 * @param string Label for the table.
889 * @param boolean If set, then checkboxes are set by default.
890 * @param boolean If set, then icons are shown.
891 * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
892 * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
893 * @return string HTML table with checkboxes for update. Must be wrapped in a form.
894 */
895 function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0) {
896 $out = array();
897 if (is_array($arr)) {
898 foreach($arr as $key => $string) {
899 $ico = '';
900 if ($iconDis) {
901 if (stristr($string,' user_')) {
902 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
903 }
904 if (stristr($string,' app_')) {
905 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
906 }
907 if (stristr($string,' ttx_') || stristr($string,' tx_')) {
908 $ico.= '<img src="'.$this->backPath.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
909 }
910 }
911 $out[]='
912 <tr>
913 <td valign="top"><input type="checkbox" id="db-'.$key.'" name="'.$this->dbUpdateCheckboxPrefix.'['.$key.']" value="1"'.($checked?' checked="checked"':'').' /></td>
914 <td nowrap="nowrap"><label for="db-'.$key.'">'.nl2br($ico.htmlspecialchars($string)).'</label></td>
915 </tr>';
916 if (isset($currentValue[$key])) {
917 $out[]='
918 <tr>
919 <td valign="top"></td>
920 <td nowrap="nowrap" style="color : #666666;">'.nl2br((!$cVfullMsg?"Current value: ":"").'<em>'.$currentValue[$key].'</em>').'</td>
921 </tr>';
922 }
923 }
924
925 // Compile rows:
926 $content = '
927 <!-- Update database fields / tables -->
928 <h3>'.$label.'</h3>
929 <table border="0" cellpadding="2" cellspacing="2" class="update-db-fields">'.implode('',$out).'
930 </table>';
931 }
932
933 return $content;
934 }
935
936 /**
937 * Reads the field definitions for the input SQL-file string
938 *
939 * @param string Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
940 * @return array Array with information about table.
941 * @deprecated since TYPO3 4.2 Use ->getFieldDefinitions_fileContent() instead!
942 */
943 function getFieldDefinitions_sqlContent($fileContent) {
944 return $this->getFieldDefinitions_fileContent($fileContent);
945 }
946 }
947
948 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']) {
949 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']);
950 }
951 ?>