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