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