Corrected wrong parameter order for some implode function calls.
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_install.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@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 <kasper@typo3.com>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 80: class t3lib_install
40 *
41 * SECTION: Writing to localconf.php
42 * 118: function setValueInLocalconfFile(&$line_array, $variable, $value)
43 * 168: function writeToLocalconf_control($inlines='')
44 * 220: function checkForBadString($string)
45 * 233: function slashValueForSingleDashes($value)
46 *
47 * SECTION: SQL
48 * 258: function getFieldDefinitions_sqlContent($sqlContent)
49 * 296: function getFieldDefinitions_database()
50 * 340: function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='')
51 * 385: function getUpdateSuggestions($diffArr,$keyList='extra,diff')
52 * 481: function assembleFieldDefinition($row)
53 * 510: function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='')
54 * 550: function getCreateTables($statements, $insertCountFlag=0)
55 * 574: function getTableInsertStatements($statements, $table)
56 * 594: function performUpdateQueries($arr,$keyArr)
57 * 610: function getListOfTables()
58 * 626: function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0)
59 *
60 * TOTAL FUNCTIONS: 15
61 * (This index is automatically created/updated by the extension "extdeveval")
62 *
63 */
64
65
66
67
68
69
70
71
72 require_once(PATH_t3lib.'class.t3lib_sqlparser.php');
73
74 /**
75 * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
76 *
77 * @author Kasper Skaarhoj <kasper@typo3.com>
78 * @package TYPO3
79 * @subpackage t3lib
80 */
81 class t3lib_install {
82
83 // External, Static
84 var $updateIdentity = ''; // Set to string which identifies the script using this class.
85 var $deletedPrefixKey = 'zzz_deleted_'; // Prefix used for tables/fields when deleted/renamed.
86 var $dbUpdateCheckboxPrefix = 'TYPO3_INSTALL[database_update]'; // Prefix for checkbox fields when updating database.
87 var $mysqlVersion = '3.22'; // 3.22 or 3.23. If set to 3.23, then the expected format of the incoming sql-dump files are changed. 'DEFAULT' and 'NOT NULL' are reversed in order and 'DEFAULT' is lowercase. Also auto_incremented fields are without default definitions.
88 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.
89 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
90 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.
91 var $backPath = '../'; // Backpath (used for icons etc.)
92
93 var $multiplySize = 1; // Multiplier of SQL field size (for char, varchar and text fields)
94
95 // Internal, dynamic:
96 var $setLocalconf = 0; // Used to indicate that a value is change in the line-array of localconf and that it should be written.
97 var $messages = array(); // Used to set (error)messages from the executing functions like mail-sending, writing Localconf and such
98 var $touchedLine = 0; // updated with line in localconf.php file that was changed.
99
100
101
102
103
104
105
106 /**************************************
107 *
108 * Writing to localconf.php
109 *
110 **************************************/
111
112 /**
113 * This functions takes an array with lines from localconf.php, finds a variable and inserts the new value.
114 *
115 * @param array $line_array the localconf.php file exploded into an array by linebreaks. (see writeToLocalconf_control())
116 * @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.
117 * @param string $value Is the value to be insert for the variable
118 * @return void
119 * @see writeToLocalconf_control()
120 */
121 function setValueInLocalconfFile(&$line_array, $variable, $value) {
122 if (!$this->checkForBadString($value)) return 0;
123
124 // Initialize:
125 $found = 0;
126 $this->touchedLine = '';
127 $commentKey = '## ';
128 $inArray = in_array($commentKey.$this->localconf_editPointToken,$line_array);
129 $tokenSet = ($this->localconf_editPointToken && !$inArray); // Flag is set if the token should be set but is not yet...
130 $stopAtToken = ($this->localconf_editPointToken && $inArray);
131 $comment = ' Modified or inserted by '.$this->updateIdentity.'.';
132
133 // Search for variable name:
134 if (!$this->localconf_addLinesOnly && !$tokenSet) {
135 $line_array = array_reverse($line_array);
136 foreach($line_array as $k => $v) {
137 $v2 = trim($v);
138 if ($stopAtToken && !strcmp($v2,$commentKey.$this->localconf_editPointToken)) break; // If stopAtToken and token found, break out of the loop..
139 if (!strcmp(substr($v2,0,strlen($variable.' ')),$variable.' ')) {
140 $mainparts = explode($variable,$v,2);
141 if (count($mainparts)==2) { // should ALWAYS be....
142 $subparts = explode('//',$mainparts[1],2);
143 $line_array[$k] = $mainparts[0].$variable." = '".$this->slashValueForSingleDashes($value)."'; ".('//'.$comment.str_replace($comment,'',$subparts[1]));
144 $this->touchedLine = count($line_array)-$k-1;
145 $found = 1;
146 break;
147 }
148 }
149 }
150 $line_array = array_reverse($line_array);
151 }
152 if (!$found) {
153 if ($tokenSet) {
154 $line_array[] = $commentKey.$this->localconf_editPointToken;
155 $line_array[] = '';
156 }
157 $line_array[] = $variable." = '".$this->slashValueForSingleDashes($value)."'; // ".$comment;
158 $this->touchedLine = -1;
159 }
160 $this->messages[] = $variable." = '".htmlspecialchars($value)."'";
161 $this->setLocalconf = 1;
162 }
163
164 /**
165 * Writes or returns lines from localconf.php
166 *
167 * @param array Array of lines to write back to localconf.php. Possibly
168 * @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)
169 * @see setValueInLocalconfFile()
170 */
171 function writeToLocalconf_control($inlines='') {
172 $writeToLocalconf_dat['file'] = PATH_typo3conf.'localconf.php';
173
174 // Checking write state of localconf.php:
175 if (!$this->allowUpdateLocalConf) {
176 die("->allowUpdateLocalConf flag in the install object is not set and therefore 'localconf.php' cannot be altered.");
177 }
178 if (!@is_writeable($writeToLocalconf_dat['file'])) {
179 die($writeToLocalconf_dat['file'].' is not writeable!');
180 }
181
182 // Splitting localconf.php file into lines:
183 $lines = explode(chr(10),trim(t3lib_div::getUrl($writeToLocalconf_dat['file'])));
184 $writeToLocalconf_dat['endLine'] = array_pop($lines); // Getting "? >" ending.
185
186 // Checking if "updated" line was set by this tool - if so remove old line.
187 $updatedLine = array_pop($lines);
188 $writeToLocalconf_dat['updatedText'] = '// Updated by '.$this->updateIdentity.' ';
189 if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
190 array_push($lines,$updatedLine);
191 }
192
193 if (is_array($inlines)) { // Setting a line and write:
194 // Setting configuration
195 $updatedLine = $writeToLocalconf_dat['updatedText'].date('d-m-Y H:i:s');
196 array_push($inlines,$updatedLine);
197 array_push($inlines,$writeToLocalconf_dat['endLine']);
198
199 if ($this->setLocalconf) {
200 t3lib_div::writeFile($writeToLocalconf_dat['file'],implode(chr(10),$inlines));
201
202 if (strcmp(t3lib_div::getUrl($writeToLocalconf_dat['file']), implode(chr(10),$inlines))) {
203 die('typo3temp/localconf.php was NOT updated properly (written content didn\'t match file content) - maybe write access problem?');
204 }
205
206 $this->messages[]= 'Configuration written to typo3conf/localconf.php';
207 return 'continue';
208 } else {
209 return 'nochange';
210 }
211 } else { // Return lines found in localconf.php
212 return $lines;
213 }
214 }
215
216 /**
217 * Checking for linebreaks in the string
218 *
219 * @param string String to test
220 * @return boolean Returns TRUE if string is OK
221 * @see setValueInLocalconfFile()
222 */
223 function checkForBadString($string) {
224 if (ereg('['.chr(10).chr(13).']',$string)){
225 return FALSE;
226 } else return TRUE;
227 }
228
229 /**
230 * Replaces ' with \' and \ with \\
231 *
232 * @param string Input value
233 * @return string Output value
234 * @see setValueInLocalconfFile()
235 */
236 function slashValueForSingleDashes($value) {
237 return str_replace("'","\'",str_replace('\\','\\\\',$value));
238 }
239
240
241
242
243
244
245
246
247
248
249 /*************************************
250 *
251 * SQL
252 *
253 *************************************/
254
255 /**
256 * Reads the field definitions for the input sql-file string
257 *
258 * @param string $sqlContent: Should be a string read from an sql-file made with 'mysqldump [database_name] -d'
259 * @return array Array with information about table.
260 */
261 function getFieldDefinitions_sqlContent($sqlContent) {
262 $lines = t3lib_div::trimExplode(chr(10), $sqlContent,1);
263 $isTable = '';
264
265 foreach($lines as $value) {
266 if ($value[0]!='#') {
267 if (!$isTable) {
268 $parts = explode(' ',$value);
269 if ($parts[0]=='CREATE' && $parts[1]=='TABLE') {
270 $isTable = $parts[2];
271 if (TYPO3_OS=='WIN') { // tablenames are always lowercase on windows!
272 $isTable = strtolower($isTable);
273 }
274 }
275 } else {
276 if (substr($value,0,1)==')' && substr($value,-1)==';') {
277 $isTable = '';
278 } else {
279 $lineV = ereg_replace(',$','',$value);
280 $parts = explode(' ',$lineV,2);
281 if ($parts[0]!='PRIMARY' && $parts[0]!='KEY' && $parts[0]!='UNIQUE') {
282 $total[$isTable]['fields'][$parts[0]] = $parts[1];
283 } else {
284 $newParts = explode(' ',$parts[1],2);
285 $total[$isTable]['keys'][($parts[0]=='PRIMARY'?$parts[0]:$newParts[0])] = $lineV;
286 }
287 }
288 }
289 }
290 }
291
292 $this->getFieldDefinitions_sqlContent_parseTypes($total);
293 return $total;
294 }
295
296 /**
297 * Multiplies varchars/tinytext fields in size according to $this->multiplySize
298 * 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.
299 *
300 * @param array Total array (from getFieldDefinitions_sqlContent())
301 * @return void
302 * @see getFieldDefinitions_sqlContent()
303 * @access private
304 */
305 function getFieldDefinitions_sqlContent_parseTypes(&$total) {
306
307 $mSize = (double)$this->multiplySize;
308 if ($mSize > 1) {
309
310 // Init SQL parser:
311 $sqlParser = t3lib_div::makeInstance('t3lib_sqlparser');
312 foreach($total as $table => $cfg) {
313 foreach($cfg['fields'] as $fN => $fType) {
314 $orig_fType = $fType;
315 $fInfo = $sqlParser->parseFieldDef($fType);
316
317 switch($fInfo['fieldType']) {
318 case 'char':
319 case 'varchar':
320 $newSize = round($fInfo['value']*$mSize);
321
322 if ($newSize <= 255) {
323 $fInfo['value'] = $newSize;
324 } else {
325 $fInfo = array(
326 'fieldType' => 'text',
327 'featureIndex' => array(
328 'NOTNULL' => array(
329 'keyword' => 'NOT NULL'
330 )
331 )
332 );
333 }
334 break;
335 case 'tinytext':
336 $fInfo['fieldType'] = 'text';
337 break;
338 }
339
340 $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
341 if ($sqlParser->parse_error) die($sqlParser->parse_error);
342 }
343 }
344 }
345 }
346
347 /**
348 * Reads the field definitions for the current database
349 *
350 * @return array Array with information about table.
351 */
352 function getFieldDefinitions_database() {
353 $total = array();
354 $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db);
355 echo $GLOBALS['TYPO3_DB']->sql_error();
356
357 $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
358 foreach($tables as $tableName) {
359
360 // Fields:
361 $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
362 foreach($fieldInformation as $fN => $fieldRow) {
363 $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
364 }
365
366 // Keys:
367 $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
368 foreach($keyInformation as $kN => $keyRow) {
369 $tempKeys[$tableName][$keyRow['Key_name']][$keyRow['Seq_in_index']] = $keyRow['Column_name'];
370 $tempKeysPrefix[$tableName][$keyRow['Key_name']]= ($keyRow['Key_name']=='PRIMARY'?'PRIMARY KEY':($keyRow['Non_unique']?'KEY':'UNIQUE').' '.$keyRow['Key_name']);
371 }
372 }
373
374 // Compile information:
375 if (is_array($tempKeys)) {
376 foreach($tempKeys as $table => $keyInf) {
377 foreach($keyInf as $kName => $index) {
378 ksort($index);
379 $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName].' ('.implode(',',$index).')';
380 }
381 }
382 }
383
384 return $total;
385 }
386
387 /**
388 * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
389 * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
390 *
391 * @param array Field definitions, source (from getFieldDefinitions_sqlContent())
392 * @param array Field definitions, comparison. (from getFieldDefinitions_database())
393 * @param string Table names (in list) which is the ONLY one observed.
394 * @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
395 */
396 function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='') {
397 $extraArr = array();
398 $diffArr = array();
399
400 if (is_array($FDsrc)) {
401 foreach($FDsrc as $table => $info) {
402 if (!strlen($onlyTableList) || t3lib_div::inList($onlyTableList, $table)) {
403 if (!isset($FDcomp[$table])) {
404 $extraArr[$table] = $info; // If the table was not in the FDcomp-array, the result array is loaded with that table.
405 $extraArr[$table]['whole_table']=1;
406 } else {
407 $keyTypes = explode(',','fields,keys');
408 foreach($keyTypes as $theKey) {
409 if (is_array($info[$theKey])) {
410 foreach($info[$theKey] as $fieldN => $fieldC) {
411 if (!isset($FDcomp[$table][$theKey][$fieldN])) {
412 $extraArr[$table][$theKey][$fieldN] = $fieldC;
413 } elseif (strcmp($FDcomp[$table][$theKey][$fieldN], $fieldC)){
414 $diffArr[$table][$theKey][$fieldN] = $fieldC;
415 $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
416 }
417 }
418 }
419 }
420 }
421 }
422 }
423 }
424
425 $output = array(
426 'extra' => $extraArr,
427 'diff' => $diffArr,
428 'diff_currentValues' => $diffArr_cur
429 );
430
431 return $output;
432 }
433
434 /**
435 * Returns an array with SQL-statements that is needed to update according to the diff-array
436 *
437 * @param array Array with differences of current and needed DB settings. (from getDatabaseExtra())
438 * @param string List of fields in diff array to take notice of.
439 * @return array Array of SQL statements (organized in keys depending on type)
440 */
441 function getUpdateSuggestions($diffArr,$keyList='extra,diff') {
442 $statements = array();
443 $deletedPrefixKey = $this->deletedPrefixKey;
444 $remove = 0;
445 if ($keyList == 'remove') {
446 $remove = 1;
447 $keyList = 'extra';
448 }
449 $keyList = explode(',',$keyList);
450 foreach($keyList as $theKey) {
451 if (is_array($diffArr[$theKey])) {
452 foreach($diffArr[$theKey] as $table => $info) {
453 $whole_table = array();
454 if (is_array($info['fields'])) {
455 foreach($info['fields'] as $fN => $fV) {
456 if ($info['whole_table']) {
457 $whole_table[]=$fN.' '.$fV;
458 } else {
459 if ($theKey=='extra') {
460 if ($remove) {
461 if (substr($fN,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
462 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$deletedPrefixKey.$fN.' '.$fV.';';
463 $statements['change'][md5($statement)] = $statement;
464 } else {
465 $statement = 'ALTER TABLE '.$table.' DROP '.$fN.';';
466 $statements['drop'][md5($statement)] = $statement;
467 }
468 } else {
469 $statement = 'ALTER TABLE '.$table.' ADD '.$fN.' '.$fV.';';
470 $statements['add'][md5($statement)] = $statement;
471 }
472 } elseif ($theKey=='diff') {
473 $statement = 'ALTER TABLE '.$table.' CHANGE '.$fN.' '.$fN.' '.$fV.';';
474 $statements['change'][md5($statement)] = $statement;
475 $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
476 }
477 }
478 }
479 }
480 if (is_array($info['keys'])) {
481 foreach($info['keys'] as $fN => $fV) {
482 if ($info['whole_table']) {
483 if ($fN=='PRIMARY') {
484 $whole_table[] = $fV;
485 } else {
486 $whole_table[] = $fV;
487 }
488 } else {
489 if ($theKey=='extra') {
490 if ($remove) {
491 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
492 $statements['drop'][md5($statement)] = $statement;
493 } else {
494 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
495 $statements['add'][md5($statement)] = $statement;
496 }
497 } elseif ($theKey=='diff') {
498 $statement = 'ALTER TABLE '.$table.($fN=='PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY '.$fN).';';
499 $statements['change'][md5($statement)] = $statement;
500 $statement = 'ALTER TABLE '.$table.' ADD '.$fV.';';
501 $statements['change'][md5($statement)] = $statement;
502 }
503 }
504 }
505 }
506 if ($info['whole_table']) {
507 if ($remove) {
508 if (substr($table,0,strlen($deletedPrefixKey))!=$deletedPrefixKey) {
509 $statement = 'ALTER TABLE '.$table.' RENAME '.$deletedPrefixKey.$table.';';
510 $statements['change_table'][md5($statement)]=$statement;
511 } else {
512 $statement = 'DROP TABLE '.$table.';';
513 $statements['drop_table'][md5($statement)]=$statement;
514 }
515 // count:
516 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, '');
517 list($count) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
518 $statements['tables_count'][md5($statement)] = $count?'Records in table: '.$count:'';
519 } else {
520 $statement = 'CREATE TABLE '.$table." (\n".implode(",\n",$whole_table)."\n) TYPE=MyISAM;";
521 $statements['create_table'][md5($statement)]=$statement;
522 }
523 }
524 }
525 }
526 }
527
528 return $statements;
529 }
530
531 /**
532 * Converts a result row with field information into the SQL field definition string
533 *
534 * @param array MySQL result row.
535 * @return string Field definition
536 */
537 function assembleFieldDefinition($row) {
538 $field[] = $row['Type'];
539 if ($this->mysqlVersion=='3.23' && !$row['Null']) {
540 $field[] = 'NOT NULL';
541 }
542 if (!strstr($row['Type'],'blob') && !strstr($row['Type'],'text')) {
543 // This code will return a default value if the sql-file version is not 3.23 and the field is not auto-incremented. In 3.23 files, the auto-incremented fields do not have a default definition.
544 // Furthermore if the file is 3.22 the default value of auto-incremented fields are expected to always be zero which is why the default value is passed through intval(). Thus it should work on 3.23 MySQL servers.
545 if ($this->mysqlVersion!='3.23' || !stristr($row['Extra'],'auto_increment')) {
546 $field[] = ($this->mysqlVersion=='3.23'?'default':'DEFAULT')." '".(stristr($row['Extra'],'auto_increment')?intval($row['Default']):addslashes($row['Default']))."'";
547 }
548 }
549 if ($this->mysqlVersion!='3.23' && !$row['Null']) {
550 $field[] = 'NOT NULL';
551 }
552 if ($row['Extra']) {
553 $field[] = $row['Extra'];
554 }
555 return implode(' ',$field);
556 }
557
558 /**
559 * Returns an array where every entry is a single sql-statement. Input must be formatted like an ordinary MySQL-dump files
560 *
561 * @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.
562 * @param boolean If set, non-sql (like comments and blank lines) are not included in the final product)
563 * @param string Regex to filter SQL lines to include.
564 * @return array Array of SQL statements.
565 */
566 function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='') {
567 $sqlcodeArr = explode(chr(10),$sqlcode);
568
569 // Based on the assumption that the sql-dump has
570 $statementArray = array();
571 $statementArrayPointer = 0;
572
573 foreach($sqlcodeArr as $line => $linecontent) {
574
575 // Setting MySQL Version if necessary.
576 if (substr(trim($linecontent),0,16)=='# Server version') {
577 $this->mysqlVersion = doubleval(substr(trim($linecontent),16));
578 }
579 $is_set = 0;
580
581 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
582 $statementArray[$statementArrayPointer].= $linecontent;
583 $is_set = 1;
584 }
585 if (substr(trim($linecontent),-1)==';') {
586 if (isset($statementArray[$statementArrayPointer])) {
587 if (!trim($statementArray[$statementArrayPointer]) || ($query_regex && !eregi($query_regex,trim($statementArray[$statementArrayPointer])))) {
588 unset($statementArray[$statementArrayPointer]);
589 }
590 }
591 $statementArrayPointer++;
592 } elseif ($is_set) {
593 $statementArray[$statementArrayPointer].=chr(10);
594 }
595 }
596 return $statementArray;
597 }
598
599 /**
600 * Returns tables to create and how many records in each
601 *
602 * @param array Array of SQL statements to analyse.
603 * @param boolean If set, will count number of INSERT INTO statements following that table definition
604 * @return array Array with table definitions in index 0 and count in index 1
605 */
606 function getCreateTables($statements, $insertCountFlag=0) {
607 $crTables = array();
608 foreach($statements as $line => $linecontent) {
609 if (eregi('^create[[:space:]]*table[[:space:]]*([[:alnum:]_]*)',substr($linecontent,0,100),$reg)) {
610 $table = trim($reg[1]);
611 if ($table) {
612 if (TYPO3_OS=='WIN') {$table=strtolower($table);} // tablenames are always lowercase on windows!
613 $crTables[$table] = $linecontent;
614 }
615 } elseif ($insertCountFlag && eregi('^insert[[:space:]]*into[[:space:]]*([[:alnum:]_]*)',substr($linecontent,0,100),$reg)) {
616 $nTable = trim($reg[1]);
617 $insertCount[$nTable]++;
618 }
619 }
620 return array($crTables,$insertCount);
621 }
622
623 /**
624 * Extracts all insert statements from $statement array where content is inserted into $table
625 *
626 * @param array Array of SQL statements
627 * @param string Table name
628 * @return array Array of INSERT INTO statements where table match $table
629 */
630 function getTableInsertStatements($statements, $table) {
631 $outStatements=array();
632 foreach($statements as $line => $linecontent) {
633 if (eregi('^insert[[:space:]]*into[[:space:]]*([[:alnum:]_]*)',substr($linecontent,0,100),$reg)) {
634 $nTable = trim($reg[1]);
635 if ($nTable && !strcmp($table,$nTable)) {
636 $outStatements[]=$linecontent;
637 }
638 }
639 }
640 return $outStatements;
641 }
642
643 /**
644 * Performs the queries passed from the input array.
645 *
646 * @param array Array of SQL queries to execute.
647 * @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)
648 * @return void
649 */
650 function performUpdateQueries($arr,$keyArr) {
651 if (is_array($arr)) {
652 foreach($arr as $key => $string) {
653 if (isset($keyArr[$key]) && $keyArr[$key]) {
654 $GLOBALS['TYPO3_DB']->admin_query($string);
655 }
656 }
657 }
658 }
659
660 /**
661 * Returns list of tables in the database
662 *
663 * @return array List of tables.
664 * @see t3lib_db::admin_get_tables()
665 */
666 function getListOfTables() {
667 $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
668 return $whichTables;
669 }
670
671 /**
672 * Creates a table which checkboxes for updating database.
673 *
674 * @param array Array of statements (key / value pairs where key is used for the checkboxes)
675 * @param string Label for the table.
676 * @param boolean If set, then checkboxes are set by default.
677 * @param boolean If set, then icons are shown.
678 * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
679 * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
680 * @return string HTML table with checkboxes for update. Must be wrapped in a form.
681 */
682 function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0) {
683 $out = array();
684 if (is_array($arr)) {
685 foreach($arr as $key => $string) {
686 $ico = '';
687 if ($iconDis) {
688 if (stristr($string,' user_')) {
689 $ico.= '<img src="'.$this->backPath.'t3lib/gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
690 }
691 if (stristr($string,' app_')) {
692 $ico.= '<img src="'.$this->backPath.'t3lib/gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
693 }
694 if (stristr($string,' ttx_') || stristr($string,' tx_')) {
695 $ico.= '<img src="'.$this->backPath.'t3lib/gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
696 }
697 }
698 $out[]='
699 <tr>
700 <td valign="top"><input type="checkbox" name="'.$this->dbUpdateCheckboxPrefix.'['.$key.']" value="1"'.($checked?' checked="checked"':'').' /></td>
701 <td nowrap="nowrap">'.nl2br($ico.htmlspecialchars($string)).'</td>
702 </tr>';
703 if (isset($currentValue[$key])) {
704 $out[]='
705 <tr>
706 <td valign="top"></td>
707 <td nowrap="nowrap" style="color : #666666;">'.nl2br((!$cVfullMsg?"Current value: ":"").'<em>'.$currentValue[$key].'</em>').'</td>
708 </tr>';
709 }
710 }
711
712 // Compile rows:
713 $content = '
714 <!-- Update database fields / tables -->
715 <h3>'.$label.'</h3>
716 <table border="0" cellpadding="2" cellspacing="2" class="update-db-fields">'.implode('',$out).'
717 </table>';
718 }
719
720 return $content;
721 }
722 }
723
724 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']) {
725 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']);
726 }
727 ?>