2 /***************************************************************
5 * (c) 1999-2006 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_sqlContent($sqlContent)
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)
98 var $setLocalconf = 0; // Used to indicate that a value is change in the line-array of localconf and that it should be written.
99 var $messages = array(); // Used to set (error)messages from the executing functions like mail-sending, writing Localconf and such
100 var $touchedLine = 0; // updated with line in localconf.php file that was changed.
104 * Constructor function
108 function t3lib_install() {
109 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize']>= 1 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize']<=5) {
110 $this->multiplySize
= (double)$GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'];
116 /**************************************
118 * Writing to localconf.php
121 **************************************/
124 * This functions takes an array with lines from localconf.php, finds a variable and inserts the new value.
126 * @param array $line_array the localconf.php file exploded into an array by linebreaks. (see writeToLocalconf_control())
127 * @param string $variable The variable name to find and substitute. This string must match the first part of a trimmed line in the line-array. Matching is done backwards so the last appearing line will be substituted.
128 * @param string $value Is the value to be insert for the variable
130 * @see writeToLocalconf_control()
132 function setValueInLocalconfFile(&$line_array, $variable, $value) {
133 if (!$this->checkForBadString($value)) return 0;
137 $this->touchedLine
= '';
139 $inArray = in_array($commentKey.$this->localconf_editPointToken
,$line_array);
140 $tokenSet = ($this->localconf_editPointToken
&& !$inArray); // Flag is set if the token should be set but is not yet...
141 $stopAtToken = ($this->localconf_editPointToken
&& $inArray);
142 $comment = ' Modified or inserted by '.$this->updateIdentity
.'.';
144 // Search for variable name:
145 if (!$this->localconf_addLinesOnly
&& !$tokenSet) {
146 $line_array = array_reverse($line_array);
147 foreach($line_array as $k => $v) {
149 if ($stopAtToken && !strcmp($v2,$commentKey.$this->localconf_editPointToken
)) break; // If stopAtToken and token found, break out of the loop..
150 if (!strcmp(substr($v2,0,strlen($variable.' ')),$variable.' ')) {
151 $mainparts = explode($variable,$v,2);
152 if (count($mainparts)==2) { // should ALWAYS be....
153 $subparts = explode('//',$mainparts[1],2);
154 $line_array[$k] = $mainparts[0].$variable." = '".$this->slashValueForSingleDashes($value)."'; ".('//'.$comment.str_replace($comment,'',$subparts[1]));
155 $this->touchedLine
= count($line_array)-$k-1;
161 $line_array = array_reverse($line_array);
165 $line_array[] = $commentKey.$this->localconf_editPointToken
;
168 $line_array[] = $variable." = '".$this->slashValueForSingleDashes($value)."'; // ".$comment;
169 $this->touchedLine
= -1;
171 $this->messages
[] = $variable." = '".htmlspecialchars($value)."'";
172 $this->setLocalconf
= 1;
176 * Writes or returns lines from localconf.php
178 * @param array Array of lines to write back to localconf.php. Possibly
179 * @param string Absolute path of alternative file to use (Notice: this path is not validated in terms of being inside 'TYPO3 space')
180 * @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)
181 * @see setValueInLocalconfFile()
183 function writeToLocalconf_control($inlines='',$absFullPath='') {
184 $tmpExt = '.TMP.php';
185 $writeToLocalconf_dat['file'] = $absFullPath ?
$absFullPath : PATH_typo3conf
.'localconf.php';
186 $writeToLocalconf_dat['tmpfile'] = $writeToLocalconf_dat['file'].$tmpExt;
188 // Checking write state of localconf.php:
189 if (!$this->allowUpdateLocalConf
) {
190 die("->allowUpdateLocalConf flag in the install object is not set and therefore 'localconf.php' cannot be altered.");
192 if (!@is_writable
($writeToLocalconf_dat['file'])) {
193 die($writeToLocalconf_dat['file'].' is not writable!');
196 // Splitting localconf.php file into lines:
197 $lines = explode(chr(10),str_replace(chr(13),'',trim(t3lib_div
::getUrl($writeToLocalconf_dat['file']))));
198 $writeToLocalconf_dat['endLine'] = array_pop($lines); // Getting "? >" ending.
200 // Checking if "updated" line was set by this tool - if so remove old line.
201 $updatedLine = array_pop($lines);
202 $writeToLocalconf_dat['updatedText'] = '// Updated by '.$this->updateIdentity
.' ';
203 if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
204 array_push($lines,$updatedLine);
207 if (is_array($inlines)) { // Setting a line and write:
208 // Setting configuration
209 $updatedLine = $writeToLocalconf_dat['updatedText'].date('d-m-Y H:i:s');
210 array_push($inlines,$updatedLine);
211 array_push($inlines,$writeToLocalconf_dat['endLine']);
213 if ($this->setLocalconf
) {
215 if (!t3lib_div
::writeFile($writeToLocalconf_dat['tmpfile'],implode(chr(10),$inlines))) {
216 $msg = 'typo3conf/localconf.php'.$tmpExt.' could not be written - maybe a write access problem?';
218 elseif (strcmp(t3lib_div
::getUrl($writeToLocalconf_dat['tmpfile']), implode(chr(10),$inlines))) {
219 @unlink
($writeToLocalconf_dat['tmpfile']);
220 $msg = 'typo3conf/localconf.php'.$tmpExt.' was NOT written properly (written content didn\'t match file content) - maybe a disk space problem?';
222 elseif (!@copy
($writeToLocalconf_dat['tmpfile'],$writeToLocalconf_dat['file'])) {
223 $msg = 'typo3conf/localconf.php could not be replaced by typo3conf/localconf.php'.$tmpExt.' - maybe a write access problem?';
226 @unlink
($writeToLocalconf_dat['tmpfile']);
228 $msg = 'Configuration written to typo3conf/localconf.php';
230 $this->messages
[]= $msg;
235 t3lib_div
::sysLog($msg, 'Core', 3);
241 } else { // Return lines found in localconf.php
247 * Checking for linebreaks in the string
249 * @param string String to test
250 * @return boolean Returns TRUE if string is OK
251 * @see setValueInLocalconfFile()
253 function checkForBadString($string) {
254 return preg_match('/['.chr(10).chr(13).']/',$string) ?
FALSE : TRUE;
258 * Replaces ' with \' and \ with \\
260 * @param string Input value
261 * @return string Output value
262 * @see setValueInLocalconfFile()
264 function slashValueForSingleDashes($value) {
265 $value = str_replace("'.chr(10).'", '###INSTALL_TOOL_LINEBREAK###', $value);
266 $value = str_replace("'","\'",str_replace('\\','\\\\',$value));
267 $value = str_replace('###INSTALL_TOOL_LINEBREAK###', "'.chr(10).'", $value);
281 /*************************************
285 *************************************/
288 * Reads the field definitions for the input sql-file string
290 * @param string $sqlContent: Should be a string read from an sql-file made with 'mysqldump [database_name] -d'
291 * @return array Array with information about table.
293 function getFieldDefinitions_sqlContent($sqlContent) {
294 $lines = t3lib_div
::trimExplode(chr(10), $sqlContent,1);
298 foreach($lines as $value) {
299 if ($value[0]!='#') {
301 $parts = explode(' ',$value);
302 if ($parts[0]=='CREATE' && $parts[1]=='TABLE') {
303 $isTable = str_replace( '`', '', $parts[2]);
304 if (TYPO3_OS
=='WIN') { // tablenames are always lowercase on windows!
305 $isTable = strtolower($isTable);
309 if (substr($value,0,1)==')' && substr($value,-1)==';') {
311 preg_match('/(ENGINE|TYPE)=([a-zA-Z]*)/',$value,$ttype);
312 $total[$isTable]['extra']['ttype'] = $ttype[2];
315 $lineV = preg_replace('/,$/','',$value);
316 $lineV = str_replace('UNIQUE KEY', 'UNIQUE', $lineV);
317 $parts = explode(' ',$lineV,2);
319 // Make sure there is no default value when auto_increment is set
320 if(stristr($parts[1],'auto_increment')) {
321 $parts[1] = preg_replace('/ default \'0\'/i','',$parts[1]);
323 // "default" is always lower-case
324 if(strstr($parts[1], ' DEFAULT ')) {
325 $parts[1] = str_replace(' DEFAULT ', ' default ', $parts[1]);
328 // Change order of "default" and "null" statements
329 $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
330 $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
332 // Remove double blanks
333 $parts[1] = preg_replace('/([^ ]+)[ ]+([^ ]+)/', '$1 $2', $parts[1]);
335 if ($parts[0]!='PRIMARY' && $parts[0]!='KEY' && $parts[0]!='UNIQUE') {
336 $key = str_replace('`', '', $parts[0]);
337 $total[$isTable]['fields'][$key] = $parts[1];
338 } else { // Process keys
339 $newParts = explode(' ',$parts[1],2);
340 $key = str_replace('`', '', ($parts[0]=='PRIMARY'?
$parts[0]:$newParts[0]));
341 $lineV = str_replace('`', '', $lineV);
342 $total[$isTable]['keys'][$key] = $lineV;
349 $this->getFieldDefinitions_sqlContent_parseTypes($total);
354 * Multiplies varchars/tinytext fields in size according to $this->multiplySize
355 * 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.
357 * @param array Total array (from getFieldDefinitions_sqlContent())
360 * @see getFieldDefinitions_sqlContent()
362 function getFieldDefinitions_sqlContent_parseTypes(&$total) {
364 $mSize = (double)$this->multiplySize
;
368 $sqlParser = t3lib_div
::makeInstance('t3lib_sqlparser');
369 foreach($total as $table => $cfg) {
370 if (is_array($cfg['fields'])) {
371 foreach($cfg['fields'] as $fN => $fType) {
372 $orig_fType = $fType;
373 $fInfo = $sqlParser->parseFieldDef($fType);
375 switch($fInfo['fieldType']) {
378 $newSize = round($fInfo['value']*$mSize);
380 if ($newSize <= 255) {
381 $fInfo['value'] = $newSize;
384 'fieldType' => 'text',
385 'featureIndex' => array(
387 'keyword' => 'NOT NULL'
394 $fInfo['fieldType'] = 'text';
398 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
399 if ($sqlParser->parse_error
) die($sqlParser->parse_error
);
407 * Reads the field definitions for the current database
409 * @return array Array with information about table.
411 function getFieldDefinitions_database() {
413 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db
);
414 echo $GLOBALS['TYPO3_DB']->sql_error();
416 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db
);
417 foreach($tables as $tableName) {
420 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
421 foreach($fieldInformation as $fN => $fieldRow) {
422 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
426 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
427 foreach($keyInformation as $kN => $keyRow) {
428 $tempKeys[$tableName][$keyRow['Key_name']][$keyRow['Seq_in_index']] = $keyRow['Column_name'];
429 if ($keyRow['Sub_part']) {
430 $tempKeys[$tableName][$keyRow['Key_name']][$keyRow['Seq_in_index']].= '('.$keyRow['Sub_part'].')';
432 if ($keyRow['Key_name']=='PRIMARY') {
433 $tempKeysPrefix[$tableName][$keyRow['Key_name']] = 'PRIMARY KEY';
435 if ($keyRow['Non_unique']) {
436 $tempKeysPrefix[$tableName][$keyRow['Key_name']] = 'KEY';
438 $tempKeysPrefix[$tableName][$keyRow['Key_name']] = 'UNIQUE';
440 $tempKeysPrefix[$tableName][$keyRow['Key_name']].= ' '.$keyRow['Key_name'];
445 // Compile information:
446 if (is_array($tempKeys)) {
447 foreach($tempKeys as $table => $keyInf) {
448 foreach($keyInf as $kName => $index) {
450 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName].' ('.implode(',',$index).')';
459 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
460 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
462 * @param array Field definitions, source (from getFieldDefinitions_sqlContent())
463 * @param array Field definitions, comparison. (from getFieldDefinitions_database())
464 * @param string Table names (in list) which is the ONLY one observed.
465 * @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.
466 * @return array Returns an array with 1) all elements from $FSsrc that is not in $FDcomp (in key 'extra') and 2) all elements from $FSsrc that is difference from the ones in $FDcomp
468 function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='',$ignoreNotNullWhenComparing=true) {
472 if (is_array($FDsrc)) {
473 foreach($FDsrc as $table => $info) {
474 if (!strlen($onlyTableList) || t3lib_div
::inList($onlyTableList, $table)) {
475 if (!isset($FDcomp[$table])) {
476 $extraArr[$table] = $info; // If the table was not in the FDcomp-array, the result array is loaded with that table.
477 $extraArr[$table]['whole_table']=1;
479 $keyTypes = explode(',','fields,keys');
480 foreach($keyTypes as $theKey) {
481 if (is_array($info[$theKey])) {
482 foreach($info[$theKey] as $fieldN => $fieldC) {
483 $fieldN = str_replace('`','',$fieldN);
484 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
485 $extraArr[$table][$theKey][$fieldN] = $fieldC;
486 } elseif (strcmp($FDcomp[$table][$theKey][$fieldN], $ignoreNotNullWhenComparing?
str_replace(' NOT NULL', '', $fieldC):$fieldC)) {
487 $diffArr[$table][$theKey][$fieldN] = $fieldC;
488 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
499 'extra' => $extraArr,
501 'diff_currentValues' => $diffArr_cur
508 * Returns an array with SQL-statements that is needed to update according to the diff-array
510 * @param array Array with differences of current and needed DB settings. (from getDatabaseExtra())
511 * @param string List of fields in diff array to take notice of.
512 * @return array Array of SQL statements (organized in keys depending on type)
514 function getUpdateSuggestions($diffArr,$keyList='extra,diff') {
515 $statements = array();
516 $deletedPrefixKey = $this->deletedPrefixKey
;
518 if ($keyList == 'remove') {
522 $keyList = explode(',',$keyList);
523 foreach($keyList as $theKey) {
524 if (is_array($diffArr[$theKey])) {
525 foreach($diffArr[$theKey] as $table => $info) {
526 $whole_table = array();
527 if (is_array($info['fields'])) {
528 foreach($info['fields'] as $fN => $fV) {
529 if ($info['whole_table']) {
530 $whole_table[]=$fN.' '.$fV;
532 if ($theKey=='extra') {
534 if (substr($fN,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
535 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$deletedPrefixKey.$fN.' '.$fV.';';
536 $statements['change'][md5($statement)] = $statement;
538 $statement = 'ALTER TABLE '.$table.' DROP '.$fN.';';
539 $statements['drop'][md5($statement)] = $statement;
542 $statement = 'ALTER TABLE '.$table.' ADD '.$fN.' '.$fV.';';
543 $statements['add'][md5($statement)] = $statement;
545 } elseif ($theKey=='diff') {
546 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$fN.' '.$fV.';';
547 $statements['change'][md5($statement)] = $statement;
548 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
553 if (is_array($info['keys'])) {
554 foreach($info['keys'] as $fN => $fV) {
555 if ($info['whole_table']) {
556 $whole_table[] = $fV;
558 if ($theKey=='extra') {
560 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ?
' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
561 $statements['drop'][md5($statement)] = $statement;
563 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
564 $statements['add'][md5($statement)] = $statement;
566 } elseif ($theKey=='diff') {
567 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ?
' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
568 $statements['change'][md5($statement)] = $statement;
569 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
570 $statements['change'][md5($statement)] = $statement;
575 if ($info['whole_table']) {
577 if (substr($table,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
578 $statement = 'ALTER TABLE '.$table.' RENAME '.$deletedPrefixKey.$table.';';
579 $statements['change_table'][md5($statement)]=$statement;
581 $statement = 'DROP TABLE '.$table.';';
582 $statements['drop_table'][md5($statement)]=$statement;
585 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, '');
586 list($count) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
587 $statements['tables_count'][md5($statement)] = $count?
'Records in table: '.$count:'';
589 $statement = 'CREATE TABLE '.$table." (\n".implode(",\n",$whole_table)."\n)";
590 $statement .= ($info['extra']['ttype']) ?
' TYPE='.$info['extra']['ttype'].';' : ';';
591 $statements['create_table'][md5($statement)]=$statement;
602 * Converts a result row with field information into the SQL field definition string
604 * @param array MySQL result row.
605 * @return string Field definition
607 function assembleFieldDefinition($row) {
608 $field[] = $row['Type'];
609 // if (!$row['Null']) { $field[] = 'NOT NULL'; }
610 if (!strstr($row['Type'],'blob') && !strstr($row['Type'],'text')) {
611 // Add a default value if the field is not auto-incremented (these fields never have a default definition).
612 if (!stristr($row['Extra'],'auto_increment')) {
613 $field[] = 'default '."'".(addslashes($row['Default']))."'";
616 if ($row['Extra']) { $field[] = $row['Extra']; }
618 return implode(' ',$field);
622 * Returns an array where every entry is a single sql-statement. Input must be formatted like an ordinary MySQL-dump files
624 * @param string $sqlcode The sql-file content. Provided that 1) every query in the input is ended with ';' and that a line in the file contains only one query or a part of a query.
625 * @param boolean If set, non-sql (like comments and blank lines) are not included in the final product)
626 * @param string Regex to filter SQL lines to include.
627 * @return array Array of SQL statements.
629 function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='') {
630 $sqlcodeArr = explode(chr(10),$sqlcode);
632 // Based on the assumption that the sql-dump has
633 $statementArray = array();
634 $statementArrayPointer = 0;
636 foreach($sqlcodeArr as $line => $linecontent) {
638 if(stristr($linecontent,'auto_increment')) {
639 $linecontent = eregi_replace(' default \'0\'','',$linecontent);
642 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
643 $statementArray[$statementArrayPointer].= $linecontent;
646 if (substr(trim($linecontent),-1)==';') {
647 if (isset($statementArray[$statementArrayPointer])) {
648 if (!trim($statementArray[$statementArrayPointer]) ||
($query_regex && !eregi($query_regex,trim($statementArray[$statementArrayPointer])))) {
649 unset($statementArray[$statementArrayPointer]);
652 $statementArrayPointer++
;
654 $statementArray[$statementArrayPointer].=chr(10);
657 return $statementArray;
661 * Returns tables to create and how many records in each
663 * @param array Array of SQL statements to analyse.
664 * @param boolean If set, will count number of INSERT INTO statements following that table definition
665 * @return array Array with table definitions in index 0 and count in index 1
667 function getCreateTables($statements, $insertCountFlag=0) {
669 $insertCount = array();
670 foreach($statements as $line => $linecontent) {
672 if (eregi('^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($linecontent,0,100),$reg)) {
673 $table = trim($reg[1]);
675 if (TYPO3_OS
=='WIN') { $table=strtolower($table); } // table names are always lowercase on Windows!
676 $sqlLines = explode(chr(10), $linecontent);
677 foreach($sqlLines as $k=>$v) {
678 if(stristr($v,'auto_increment')) {
679 $sqlLines[$k] = eregi_replace(' default \'0\'','',$v);
682 $linecontent = implode(chr(10), $sqlLines);
683 $crTables[$table] = $linecontent;
685 } elseif ($insertCountFlag && eregi('^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?',substr($linecontent,0,100),$reg)) {
686 $nTable = trim($reg[1]);
687 $insertCount[$nTable]++
;
691 return array($crTables,$insertCount);
695 * Extracts all insert statements from $statement array where content is inserted into $table
697 * @param array Array of SQL statements
698 * @param string Table name
699 * @return array Array of INSERT INTO statements where table match $table
701 function getTableInsertStatements($statements, $table) {
702 $outStatements=array();
703 foreach($statements as $line => $linecontent) {
705 if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i',substr($linecontent,0,100),$reg)) {
706 $nTable = trim($reg[1]);
707 if ($nTable && !strcmp($table,$nTable)) {
708 $outStatements[]=$linecontent;
712 return $outStatements;
716 * Performs the queries passed from the input array.
718 * @param array Array of SQL queries to execute.
719 * @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)
722 function performUpdateQueries($arr,$keyArr) {
723 if (is_array($arr)) {
724 foreach($arr as $key => $string) {
725 if (isset($keyArr[$key]) && $keyArr[$key]) {
726 $GLOBALS['TYPO3_DB']->admin_query($string);
733 * Returns list of tables in the database
735 * @return array List of tables.
736 * @see t3lib_db::admin_get_tables()
738 function getListOfTables() {
739 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db
);
744 * Creates a table which checkboxes for updating database.
746 * @param array Array of statements (key / value pairs where key is used for the checkboxes)
747 * @param string Label for the table.
748 * @param boolean If set, then checkboxes are set by default.
749 * @param boolean If set, then icons are shown.
750 * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
751 * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
752 * @return string HTML table with checkboxes for update. Must be wrapped in a form.
754 function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0) {
756 if (is_array($arr)) {
757 foreach($arr as $key => $string) {
760 if (stristr($string,' user_')) {
761 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
763 if (stristr($string,' app_')) {
764 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
766 if (stristr($string,' ttx_') ||
stristr($string,' tx_')) {
767 $ico.= '<img src="'.$this->backPath
.'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
772 <td valign="top"><input type="checkbox" id="db-'.$key.'" name="'.$this->dbUpdateCheckboxPrefix
.'['.$key.']" value="1"'.($checked?
' checked="checked"':'').' /></td>
773 <td nowrap="nowrap"><label for="db-'.$key.'">'.nl2br($ico.htmlspecialchars($string)).'</label></td>
775 if (isset($currentValue[$key])) {
778 <td valign="top"></td>
779 <td nowrap="nowrap" style="color : #666666;">'.nl2br((!$cVfullMsg?
"Current value: ":"").'<em>'.$currentValue[$key].'</em>').'</td>
786 <!-- Update database fields / tables -->
788 <table border="0" cellpadding="2" cellspacing="2" class="update-db-fields">'.implode('',$out).'
796 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_install.php']) {
797 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['t3lib/class.t3lib_install.php']);