2 /***************************************************************
5 * (c) 1999-2008 Kasper Skaarhoj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
32 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
35 * [CLASS/FUNCTION INDEX of SCRIPT]
39 * 83: class t3lib_install
40 * 108: function t3lib_install()
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)
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)
63 * (This index is automatically created/updated by the extension "extdeveval")
74 require_once(PATH_t3lib
.'class.t3lib_sqlparser.php');
77 * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
79 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
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.)
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()
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.
105 * Constructor function
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'];
117 /**************************************
119 * Writing to localconf.php
122 **************************************/
125 * This functions takes an array with lines from localconf.php, finds a variable and inserts the new value.
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
131 * @see writeToLocalconf_control()
133 function setValueInLocalconfFile(&$line_array, $variable, $value) {
134 if (!$this->checkForBadString($value)) return 0;
138 $this->touchedLine
= '';
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
.'.';
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) {
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;
162 $line_array = array_reverse($line_array);
166 $line_array[] = $commentKey.$this->localconf_editPointToken
;
169 $line_array[] = $variable." = '".$this->slashValueForSingleDashes($value)."'; // ".$comment;
170 $this->touchedLine
= -1;
172 $this->messages
[] = $variable." = '".htmlspecialchars($value)."'";
173 $this->setLocalconf
= 1;
177 * Writes or returns lines from localconf.php
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()
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;
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.');
193 if (!@is_writable
($writeToLocalconf_dat['file'])) {
194 die($writeToLocalconf_dat['file'].' is not writable!');
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.
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
.' ';
205 if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
206 array_push($lines,$updatedLine);
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']);
215 if ($this->setLocalconf
) {
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?';
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?';
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?';
228 @unlink
($writeToLocalconf_dat['tmpfile']);
230 $msg = 'Configuration written to typo3conf/localconf.php';
232 $this->messages
[] = $msg;
237 t3lib_div
::sysLog($msg, 'Core', 3);
243 } else { // Return lines found in localconf.php
249 * Checking for linebreaks in the string
251 * @param string String to test
252 * @return boolean Returns TRUE if string is OK
253 * @see setValueInLocalconfFile()
255 function checkForBadString($string) {
256 return preg_match('/['.chr(10).chr(13).']/',$string) ?
FALSE : TRUE;
260 * Replaces ' with \' and \ with \\
262 * @param string Input value
263 * @return string Output value
264 * @see setValueInLocalconfFile()
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);
283 /*************************************
287 *************************************/
290 * Reads the field definitions for the input SQL-file string
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.
295 function getFieldDefinitions_fileContent($fileContent) {
296 $lines = t3lib_div
::trimExplode(chr(10), $fileContent, 1);
300 foreach ($lines as $value) {
301 if (substr($value,0,1)=='#') {
302 continue; // Ignore comments
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);
314 if (substr($value,0,1)==')' && substr($value,-1)==';') {
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.
320 // Set the collation, if specified
321 if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
322 $total[$table]['extra']['COLLATE'] = $tcollation[2];
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];
328 $charset = $GLOBALS['TYPO3_DB']->default_charset
; // Fallback to default charset
330 $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
333 $table = ''; // Remove table marker and start looking for the next "CREATE TABLE" statement
335 $lineV = preg_replace('/,$/','',$value); // Strip trailing commas
336 $lineV = str_replace('`', '', $lineV);
337 $lineV = str_replace(' ', ' ', $lineV); // Remove double blanks
339 $parts = explode(' ', $lineV, 2);
340 if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/',$parts[0])) { // Field definition
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]);
346 // "default" is always lower-case
347 if (stristr($parts[1], ' DEFAULT ')) {
348 $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
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]);
356 $total[$table]['fields'][$key] = $parts[1];
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);
363 if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
364 $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
367 $newParts = explode(' ',$parts[1],2);
368 $key = $parts[0]=='PRIMARY' ?
$parts[0] : $newParts[0];
369 $total[$table]['keys'][$key] = $lineV;
375 $this->getFieldDefinitions_sqlContent_parseTypes($total);
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.
383 * @param array Total array (from getFieldDefinitions_fileContent())
386 * @see getFieldDefinitions_fileContent()
388 function getFieldDefinitions_sqlContent_parseTypes(&$total) {
390 $mSize = (double)$this->multiplySize
;
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);
401 switch($fInfo['fieldType']) {
404 $newSize = round($fInfo['value']*$mSize);
406 if ($newSize <= 255) {
407 $fInfo['value'] = $newSize;
410 'fieldType' => 'text',
411 'featureIndex' => array(
413 'keyword' => 'NOT NULL'
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) {
421 preg_match('/^([^(]*)\(([^)]+)\)(.*)/', $kType, $match);
423 foreach (t3lib_div
::trimExplode(',',$match[2]) as $kfN) {
425 $kfN .= '('.$newSize.')';
429 $total[$table]['keys'][$kN] = $match[1].'('.join(',',$keys).')'.$match[3];
435 $fInfo['fieldType'] = 'text';
439 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
440 if ($sqlParser->parse_error
) die($sqlParser->parse_error
);
448 * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
450 * @param string Character set
451 * @return string Corresponding default collation
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();
459 if (isset($this->character_sets
[$charset]['Default collation'])) {
460 $collation = $this->character_sets
[$charset]['Default collation'];
467 * Reads the field definitions for the current database
469 * @return array Array with information about table.
471 function getFieldDefinitions_database() {
474 $tempKeysPrefix = array();
476 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db
);
477 echo $GLOBALS['TYPO3_DB']->sql_error();
479 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db
);
480 foreach ($tables as $tableName => $tableStatus) {
483 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
484 foreach ($fieldInformation as $fN => $fieldRow) {
485 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
489 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
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'].')';
497 $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
498 if ($keyName=='PRIMARY') {
499 $prefix = 'PRIMARY KEY';
501 if ($keyRow['Index_type']=='FULLTEXT') {
502 $prefix = 'FULLTEXT';
503 } elseif ($keyRow['Non_unique']) {
508 $prefix.= ' '.$keyName;
510 $tempKeysPrefix[$tableName][$keyName] = $prefix;
513 // Table status (storage engine, collaction, etc.)
514 if (is_array($tableStatus)) {
515 $tableExtraFields = array(
516 'Engine' => 'ENGINE',
517 'Collation' => 'COLLATE',
520 foreach ($tableExtraFields as $mysqlKey=>$internalKey) {
521 if (isset($tableStatus[$mysqlKey])) {
522 $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
528 // Compile key information:
529 if (count($tempKeys)) {
530 foreach ($tempKeys as $table => $keyInf) {
531 foreach ($keyInf as $kName => $index) {
533 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName].' ('.implode(',',$index).')';
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.
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
551 function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='',$ignoreNotNullWhenComparing=true) {
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;
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)
571 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
572 $extraArr[$table][$theKey][$fieldN] = $fieldC;
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]);
579 if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
580 $diffArr[$table][$theKey][$fieldN] = $fieldC;
581 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
593 'extra' => $extraArr,
595 'diff_currentValues' => $diffArr_cur
602 * Returns an array with SQL-statements that is needed to update according to the diff-array
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)
608 function getUpdateSuggestions($diffArr,$keyList='extra,diff') {
609 $statements = array();
610 $deletedPrefixKey = $this->deletedPrefixKey
;
612 if ($keyList == 'remove') {
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;
626 if ($theKey=='extra') {
628 if (substr($fN,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
629 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$deletedPrefixKey.$fN.' '.$fV.';';
630 $statements['change'][md5($statement)] = $statement;
632 $statement = 'ALTER TABLE '.$table.' DROP '.$fN.';';
633 $statements['drop'][md5($statement)] = $statement;
636 $statement = 'ALTER TABLE '.$table.' ADD '.$fN.' '.$fV.';';
637 $statements['add'][md5($statement)] = $statement;
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];
647 if (is_array($info['keys'])) {
648 foreach ($info['keys'] as $fN => $fV) {
649 if ($info['whole_table']) {
650 $whole_table[] = $fV;
652 if ($theKey=='extra') {
654 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ?
' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
655 $statements['drop'][md5($statement)] = $statement;
657 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
658 $statements['add'][md5($statement)] = $statement;
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;
669 if (is_array($info['extra'])) {
671 $extras_currentValue = array();
672 foreach ($info['extra'] as $fN => $fV) {
674 // Only consider statements which are missing in the database but don't remove existing properties
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];
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);
688 if ($info['whole_table']) {
690 if (substr($table,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
691 $statement = 'ALTER TABLE '.$table.' RENAME '.$deletedPrefixKey.$table.';';
692 $statements['change_table'][md5($statement)] = $statement;
694 $statement = 'DROP TABLE '.$table.';';
695 $statements['drop_table'][md5($statement)] = $statement;
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:'';
702 $statement = 'CREATE TABLE '.$table." (\n".implode(",\n",$whole_table)."\n)";
703 if ($info['extra']) {
704 foreach ($info['extra'] as $k=>$v) {
706 continue; // TODO: collation support is currently disabled (needs more testing)
708 $statement.= ' '.$k.'='.$v; // Add extra attributes like ENGINE, CHARSET, etc.
712 $statements['create_table'][md5($statement)] = $statement;
723 * Converts a result row with field information into the SQL field definition string
725 * @param array MySQL result row
726 * @return string Field definition
728 function assembleFieldDefinition($row) {
729 $field = array($row['Type']);
731 if ($row['Null']=='NO') {
732 $field[] = 'NOT NULL';
734 if (!strstr($row['Type'],'blob') && !strstr($row['Type'],'text')) {
735 // Add a default value if the field is not auto-incremented (these fields never have a default definition)
736 if (!stristr($row['Extra'],'auto_increment')) {
737 $field[] = 'default \''.addslashes($row['Default']).'\'';
741 $field[] = $row['Extra'];
744 return implode(' ',$field);
748 * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
750 * @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.
751 * @param boolean If set, non-SQL content (like comments and blank lines) is not included in the final output
752 * @param string Regex to filter SQL lines to include
753 * @return array Array of SQL statements
755 function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='') {
756 $sqlcodeArr = explode(chr(10), $sqlcode);
758 // Based on the assumption that the sql-dump has
759 $statementArray = array();
760 $statementArrayPointer = 0;
762 foreach ($sqlcodeArr as $line => $lineContent) {
765 // auto_increment fields cannot have a default value!
766 if (stristr($lineContent,'auto_increment')) {
767 $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
770 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
771 $statementArray[$statementArrayPointer].= $lineContent;
774 if (substr(trim($lineContent),-1)==';') {
775 if (isset($statementArray[$statementArrayPointer])) {
776 if (!trim($statementArray[$statementArrayPointer]) ||
($query_regex && !eregi($query_regex,trim($statementArray[$statementArrayPointer])))) {
777 unset($statementArray[$statementArrayPointer]);
780 $statementArrayPointer++
;
783 $statementArray[$statementArrayPointer].= chr(10);
787 return $statementArray;
791 * Returns tables to create and how many records in each
793 * @param array Array of SQL statements to analyse.
794 * @param boolean If set, will count number of INSERT INTO statements following that table definition
795 * @return array Array with table definitions in index 0 and count in index 1
797 function getCreateTables($statements, $insertCountFlag=0) {
799 $insertCount = array();
800 foreach ($statements as $line => $lineContent) {
802 if (eregi('^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($lineContent,0,100),$reg)) {
803 $table = trim($reg[1]);
805 // table names are always lowercase on Windows!
806 if (TYPO3_OS
== 'WIN') {
807 $table = strtolower($table);
809 $sqlLines = explode(chr(10), $lineContent);
810 foreach ($sqlLines as $k=>$v) {
811 if (stristr($v,'auto_increment')) {
812 $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
815 $lineContent = implode(chr(10), $sqlLines);
816 $crTables[$table] = $lineContent;
818 } elseif ($insertCountFlag && eregi('^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($lineContent,0,100),$reg)) {
819 $nTable = trim($reg[1]);
820 $insertCount[$nTable]++
;
824 return array($crTables,$insertCount);
828 * Extracts all insert statements from $statement array where content is inserted into $table
830 * @param array Array of SQL statements
831 * @param string Table name
832 * @return array Array of INSERT INTO statements where table match $table
834 function getTableInsertStatements($statements, $table) {
835 $outStatements=array();
836 foreach($statements as $line => $lineContent) {
838 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($lineContent,0,100),$reg)) {
839 $nTable = trim($reg[1]);
840 if ($nTable && !strcmp($table,$nTable)) {
841 $outStatements[] = $lineContent;
845 return $outStatements;
849 * Performs the queries passed from the input array.
851 * @param array Array of SQL queries to execute.
852 * @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)
853 * @return mixed Array with error message from database if any occured. Otherwise true if everything was executed successfully.
855 function performUpdateQueries($arr,$keyArr) {
857 if (is_array($arr)) {
858 foreach($arr as $key => $string) {
859 if (isset($keyArr[$key]) && $keyArr[$key]) {
860 $res = $GLOBALS['TYPO3_DB']->admin_query($string);
861 if ($res === false) {
862 $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
863 } elseif (is_resource($res)) {
864 $GLOBALS['TYPO3_DB']->sql_free_result($res);
869 if (count($result) > 0) {
877 * Returns list of tables in the database
879 * @return array List of tables.
880 * @see t3lib_db::admin_get_tables()
882 function getListOfTables() {
883 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db
);
884 foreach ($whichTables as $key=>&$value) {
891 * Creates a table which checkboxes for updating database.
893 * @param array Array of statements (key / value pairs where key is used for the checkboxes)
894 * @param string Label for the table.
895 * @param boolean If set, then checkboxes are set by default.
896 * @param boolean If set, then icons are shown.
897 * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
898 * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
899 * @return string HTML table with checkboxes for update. Must be wrapped in a form.
901 function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0) {
903 if (is_array($arr)) {
904 foreach($arr as $key => $string) {
907 if (stristr($string,' user_')) {
908 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
910 if (stristr($string,' app_')) {
911 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
913 if (stristr($string,' ttx_') ||
stristr($string,' tx_')) {
914 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
919 <td valign="top"><input type="checkbox" id="db-'.$key.'" name="'.$this->dbUpdateCheckboxPrefix
.'['.$key.']" value="1"'.($checked?
' checked="checked"':'').' /></td>
920 <td nowrap="nowrap"><label for="db-'.$key.'">'.nl2br($ico.htmlspecialchars($string)).'</label></td>
922 if (isset($currentValue[$key])) {
925 <td valign="top"></td>
926 <td nowrap="nowrap" style="color : #666666;">'.nl2br((!$cVfullMsg?
"Current value: ":"").'<em>'.$currentValue[$key].'</em>').'</td>
933 <!-- Update database fields / tables -->
935 <table border="0" cellpadding="2" cellspacing="2" class="update-db-fields">'.implode('',$out).'
943 * Reads the field definitions for the input SQL-file string
945 * @param string Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
946 * @return array Array with information about table.
947 * @deprecated since TYPO3 4.2 Use ->getFieldDefinitions_fileContent() instead!
949 function getFieldDefinitions_sqlContent($fileContent) {
950 return $this->getFieldDefinitions_fileContent($fileContent);
954 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_install.php']) {
955 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_install.php']);