PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/t3lib/class.t3lib_install.php

https://github.com/andreaswolf/typo3-tceforms
PHP | 1179 lines | 791 code | 105 blank | 283 comment | 206 complexity | 331dac57b05fb0a9a4178bf14f16f3e6 MD5 | raw file
Possible License(s): Apache-2.0, BSD-2-Clause, LGPL-3.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2011 Kasper Skårhøj (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 Skårhøj <kasperYYYY@typo3.com>
  33. */
  34. /**
  35. * [CLASS/FUNCTION INDEX of SCRIPT]
  36. *
  37. *
  38. *
  39. * 83: class t3lib_install
  40. * 108: function t3lib_install()
  41. *
  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)
  47. *
  48. * SECTION: SQL
  49. * 291: function getFieldDefinitions_fileContent($fileContent)
  50. * 359: function getFieldDefinitions_sqlContent_parseTypes(&$total)
  51. * 406: function getFieldDefinitions_database()
  52. * 450: function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList='')
  53. * 496: function getUpdateSuggestions($diffArr,$keyList='extra,diff')
  54. * 589: function assembleFieldDefinition($row)
  55. * 611: function getStatementArray($sqlcode,$removeNonSQL=0,$query_regex='')
  56. * 649: function getCreateTables($statements, $insertCountFlag=0)
  57. * 683: function getTableInsertStatements($statements, $table)
  58. * 704: function performUpdateQueries($arr,$keyArr)
  59. * 720: function getListOfTables()
  60. * 736: function generateUpdateDatabaseForm_checkboxes($arr,$label,$checked=1,$iconDis=0,$currentValue=array(),$cVfullMsg=0)
  61. *
  62. * TOTAL FUNCTIONS: 17
  63. * (This index is automatically created/updated by the extension "extdeveval")
  64. *
  65. */
  66. /**
  67. * Class to setup values in localconf.php and verify the TYPO3 DB tables/fields
  68. *
  69. * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  70. * @package TYPO3
  71. * @subpackage t3lib
  72. */
  73. class t3lib_install {
  74. // External, Static
  75. var $updateIdentity = ''; // Set to string which identifies the script using this class.
  76. var $deletedPrefixKey = 'zzz_deleted_'; // Prefix used for tables/fields when deleted/renamed.
  77. var $dbUpdateCheckboxPrefix = 'TYPO3_INSTALL[database_update]'; // Prefix for checkbox fields when updating database.
  78. 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.
  79. 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
  80. 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.
  81. var $backPath = '../'; // Backpath (used for icons etc.)
  82. var $multiplySize = 1; // Multiplier of SQL field size (for char, varchar and text fields)
  83. var $character_sets = array(); // Caching output of $GLOBALS['TYPO3_DB']->admin_get_charsets()
  84. // Internal, dynamic:
  85. var $setLocalconf = 0; // Used to indicate that a value is change in the line-array of localconf and that it should be written.
  86. var $messages = array(); // Used to set (error)messages from the executing functions like mail-sending, writing Localconf and such
  87. var $touchedLine = 0; // updated with line in localconf.php file that was changed.
  88. /**
  89. * Constructor function
  90. *
  91. * @return void
  92. */
  93. function t3lib_install() {
  94. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'] >= 1 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'] <= 5) {
  95. $this->multiplySize = (double) $GLOBALS['TYPO3_CONF_VARS']['SYS']['multiplyDBfieldSize'];
  96. }
  97. }
  98. /**************************************
  99. *
  100. * Writing to localconf.php
  101. *
  102. **************************************/
  103. /**
  104. * This functions takes an array with lines from localconf.php, finds a variable and inserts the new value.
  105. *
  106. * @param array $line_array the localconf.php file exploded into an array by linebreaks. (see writeToLocalconf_control())
  107. * @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.
  108. * @param string $value Is the value to be insert for the variable
  109. * @param boolean $quoteValue Whether the given value should be quoted before being written
  110. * @return void
  111. * @see writeToLocalconf_control()
  112. */
  113. public function setValueInLocalconfFile(&$line_array, $variable, $value, $quoteValue = TRUE) {
  114. if (!$this->checkForBadString($value)) {
  115. return 0;
  116. }
  117. // Initialize:
  118. $found = 0;
  119. $this->touchedLine = '';
  120. $commentKey = '## ';
  121. $inArray = in_array($commentKey . $this->localconf_editPointToken, $line_array);
  122. $tokenSet = ($this->localconf_editPointToken && !$inArray); // Flag is set if the token should be set but is not yet...
  123. $stopAtToken = ($this->localconf_editPointToken && $inArray);
  124. $comment = ' Modified or inserted by ' . $this->updateIdentity . '.';
  125. $replace = array('["', '"]');
  126. $search = array('[\'', '\']');
  127. $varDoubleQuotes = str_replace($search, $replace, $variable);
  128. // Search for variable name:
  129. if (!$this->localconf_addLinesOnly && !$tokenSet) {
  130. $line_array = array_reverse($line_array);
  131. foreach ($line_array as $k => $v) {
  132. $v2 = trim($v);
  133. if ($stopAtToken && !strcmp($v2, $commentKey . $this->localconf_editPointToken)) {
  134. break;
  135. } // If stopAtToken and token found, break out of the loop..
  136. if (!strcmp(substr($v2, 0, strlen($variable . ' ')), $variable . ' ')) {
  137. $mainparts = explode($variable, $v, 2);
  138. if (count($mainparts) == 2) { // should ALWAYS be....
  139. $subparts = explode('//', $mainparts[1], 2);
  140. if ($quoteValue) {
  141. $value = '\'' . $this->slashValueForSingleDashes($value) . '\'';
  142. }
  143. $line_array[$k] = $mainparts[0] . $variable . " = " . $value . "; " . ('//' . $comment . str_replace($comment, '', $subparts[1]));
  144. $this->touchedLine = count($line_array) - $k - 1;
  145. $found = 1;
  146. break;
  147. }
  148. } elseif (!strcmp(substr($v2, 0, strlen($varDoubleQuotes . ' ')), $varDoubleQuotes . ' ')) {
  149. // Due to a bug in the update wizard (fixed in TYPO3 4.1.7) it is possible
  150. // that $TYPO3_CONF_VARS['SYS']['compat_version'] was enclosed by "" (double
  151. // quotes) instead of the expected '' (single quotes) when is was written to
  152. // localconf.php. The following code was added to make sure that values with
  153. // double quotes are updated, too.
  154. $mainparts = explode($varDoubleQuotes, $v, 2);
  155. if (count($mainparts) == 2) { // should ALWAYS be....
  156. $subparts = explode('//', $mainparts[1], 2);
  157. if ($quoteValue) {
  158. $value = '\'' . $this->slashValueForSingleDashes($value) . '\'';
  159. }
  160. $line_array[$k] = $mainparts[0] . $variable . " = " . $value . "; " . ('//' . $comment . str_replace($comment, '', $subparts[1]));
  161. $this->touchedLine = count($line_array) - $k - 1;
  162. $found = 1;
  163. break;
  164. }
  165. }
  166. }
  167. $line_array = array_reverse($line_array);
  168. }
  169. if (!$found) {
  170. if ($tokenSet) {
  171. $line_array[] = $commentKey . $this->localconf_editPointToken;
  172. $line_array[] = '';
  173. }
  174. if ($quoteValue) {
  175. $value = '\'' . $this->slashValueForSingleDashes($value) . '\'';
  176. }
  177. $line_array[] = $variable . " = " . $value . "; // " . $comment;
  178. $this->touchedLine = -1;
  179. }
  180. if ($variable == '$typo_db_password') {
  181. $this->messages[] = 'Updated ' . $variable;
  182. } else {
  183. $this->messages[] = $variable . " = " . htmlspecialchars($value);
  184. }
  185. $this->setLocalconf = 1;
  186. }
  187. /**
  188. * Takes an array with lines from localconf.php, finds a variable and inserts the new array value.
  189. *
  190. * @param array $lines the localconf.php file exploded into an array by line breaks. {@see writeToLocalconf_control()}
  191. * @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.
  192. * @param array $value value to be assigned to the variable
  193. * @return void
  194. * @see writeToLocalconf_control()
  195. */
  196. public function setArrayValueInLocalconfFile(array &$lines, $variable, array $value) {
  197. $commentKey = '## ';
  198. $inArray = in_array($commentKey . $this->localconf_editPointToken, $lines);
  199. $tokenSet = $this->localconf_editPointToken && !$inArray; // Flag is set if the token should be set but is not yet
  200. $stopAtToken = $this->localconf_editPointToken && $inArray;
  201. $comment = 'Modified or inserted by ' . $this->updateIdentity . '.';
  202. $format = "%s = %s;\t// " . $comment;
  203. $insertPos = count($lines);
  204. $startPos = 0;
  205. if (!($this->localconf_addLinesOnly || $tokenSet)) {
  206. for ($i = count($lines) - 1; $i > 0; $i--) {
  207. $line = trim($lines[$i]);
  208. if ($stopAtToken && t3lib_div::isFirstPartOfStr($line, $this->localconf_editPointToken)) {
  209. break;
  210. }
  211. if (t3lib_div::isFirstPartOfStr($line, '?>')) {
  212. $insertPos = $i;
  213. }
  214. if (t3lib_div::isFirstPartOfStr($line, $variable)) {
  215. $startPos = $i;
  216. break;
  217. }
  218. }
  219. }
  220. if ($startPos) {
  221. $this->touchedLine = $startPos;
  222. $endPos = $startPos;
  223. for ($i = $startPos; $i < count($lines); $i++) {
  224. $line = trim($lines[$i]);
  225. if (t3lib_div::isFirstPartOfStr($line, ');')) {
  226. $endPos = $i;
  227. break;
  228. }
  229. }
  230. $startLines = array_slice($lines, 0, $startPos);
  231. $endLines = array_slice($lines, $endPos + 1);
  232. $lines = $startLines;
  233. $definition = $this->array_export($value);
  234. $lines[] = sprintf($format, $variable, $definition);
  235. foreach ($endLines as $line) {
  236. $lines[] = $line;
  237. }
  238. } else {
  239. $lines[$insertPos] = sprintf($format, $variable, $this->array_export($value));
  240. $lines[] = '?>';
  241. $this->touchedLine = -1;
  242. }
  243. }
  244. /**
  245. * Returns a parsable string representation of an array variable. This methods enhances
  246. * standard method var_export from PHP to take TYPO3's CGL into account.
  247. *
  248. * @param array $variable
  249. * @return string
  250. */
  251. protected function array_export(array $variable) {
  252. $lines = explode("\n", var_export($variable, TRUE));
  253. $out = 'array(';
  254. for ($i = 1; $i < count($lines); $i++) {
  255. $out .= "\n";
  256. // Make the space-indented declaration tab-indented instead
  257. while (substr($lines[$i], 0, 2) === ' ') {
  258. $out .= "\t";
  259. $lines[$i] = substr($lines[$i], 2);
  260. }
  261. $out .= $lines[$i];
  262. // Array declaration should be next to the assignment and no space between
  263. // "array" and its opening parenthesis should exist
  264. if (preg_match('/\s=>\s$/', $lines[$i])) {
  265. $out .= preg_replace('/^\s*array \(/', 'array(', $lines[$i + 1]);
  266. $i++;
  267. }
  268. }
  269. return $out;
  270. }
  271. /**
  272. * Writes or returns lines from localconf.php
  273. *
  274. * @param array Array of lines to write back to localconf.php. Possibly
  275. * @param string Absolute path of alternative file to use (Notice: this path is not validated in terms of being inside 'TYPO3 space')
  276. * @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)
  277. * @see setValueInLocalconfFile()
  278. */
  279. function writeToLocalconf_control($inlines = '', $absFullPath = '') {
  280. $tmpExt = '.TMP.php';
  281. $writeToLocalconf_dat = array();
  282. $writeToLocalconf_dat['file'] = $absFullPath ? $absFullPath : PATH_typo3conf . 'localconf.php';
  283. $writeToLocalconf_dat['tmpfile'] = $writeToLocalconf_dat['file'] . $tmpExt;
  284. // Checking write state of localconf.php:
  285. if (!$this->allowUpdateLocalConf) {
  286. throw new RuntimeException(
  287. 'TYPO3 Fatal Error: ->allowUpdateLocalConf flag in the install object is not set and therefore "localconf.php" cannot be altered.',
  288. 1270853915
  289. );
  290. }
  291. if (!@is_writable($writeToLocalconf_dat['file'])) {
  292. throw new RuntimeException(
  293. 'TYPO3 Fatal Error: ' . $writeToLocalconf_dat['file'] . ' is not writable!',
  294. 1270853916
  295. );
  296. }
  297. // Splitting localconf.php file into lines:
  298. $lines = explode(LF, str_replace(CR, '', trim(t3lib_div::getUrl($writeToLocalconf_dat['file']))));
  299. $writeToLocalconf_dat['endLine'] = array_pop($lines); // Getting "? >" ending.
  300. // Checking if "updated" line was set by this tool - if so remove old line.
  301. $updatedLine = array_pop($lines);
  302. $writeToLocalconf_dat['updatedText'] = '// Updated by ' . $this->updateIdentity . ' ';
  303. if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
  304. array_push($lines, $updatedLine);
  305. }
  306. if (is_array($inlines)) { // Setting a line and write:
  307. // Setting configuration
  308. $updatedLine = $writeToLocalconf_dat['updatedText'] . date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' H:i:s');
  309. array_push($inlines, $updatedLine);
  310. array_push($inlines, $writeToLocalconf_dat['endLine']);
  311. if ($this->setLocalconf) {
  312. $success = $this->writeToLocalconf($inlines, $absFullPath);
  313. if ($success) {
  314. return 'continue';
  315. } else {
  316. return 'nochange';
  317. }
  318. } else {
  319. return 'nochange';
  320. }
  321. } else { // Return lines found in localconf.php
  322. return $lines;
  323. }
  324. }
  325. /**
  326. * Writes lines to localconf.php.
  327. *
  328. * @param array Array of lines to write back to localconf.php
  329. * @param string Absolute path of alternative file to use (Notice: this path is not validated in terms of being inside 'TYPO3 space')
  330. * @return boolean TRUE if method succeeded, otherwise FALSE
  331. */
  332. public function writeToLocalconf(array $lines, $absFullPath = '') {
  333. $tmpExt = '.TMP.php';
  334. $writeToLocalconf_dat = array();
  335. $writeToLocalconf_dat['file'] = $absFullPath ? $absFullPath : PATH_typo3conf . 'localconf.php';
  336. $writeToLocalconf_dat['tmpfile'] = $writeToLocalconf_dat['file'] . $tmpExt;
  337. // Checking write state of localconf.php:
  338. if (!$this->allowUpdateLocalConf) {
  339. throw new RuntimeException(
  340. 'TYPO3 Fatal Error: ->allowUpdateLocalConf flag in the install object is not set and therefore "localconf.php" cannot be altered.',
  341. 1270853915
  342. );
  343. }
  344. if (!@is_writable($writeToLocalconf_dat['file'])) {
  345. throw new RuntimeException(
  346. 'TYPO3 Fatal Error: ' . $writeToLocalconf_dat['file'] . ' is not writable!',
  347. 1270853916
  348. );
  349. }
  350. $writeToLocalconf_dat['endLine'] = array_pop($lines); // Getting "? >" ending.
  351. if (!strstr('?' . '>', $writeToLocalconf_dat['endLine'])) {
  352. $lines[] = $writeToLocalconf_dat['endLine'];
  353. $writeToLocalconf_dat['endLine'] = '?' . '>';
  354. }
  355. // Checking if "updated" line was set by this tool - if so remove old line.
  356. $updatedLine = array_pop($lines);
  357. $writeToLocalconf_dat['updatedText'] = '// Updated by ' . $this->updateIdentity . ' ';
  358. if (!strstr($updatedLine, $writeToLocalconf_dat['updatedText'])) {
  359. $lines[] = $updatedLine;
  360. }
  361. $updatedLine = $writeToLocalconf_dat['updatedText'] . date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' H:i:s');
  362. $lines[] = $updatedLine;
  363. $lines[] = $writeToLocalconf_dat['endLine'];
  364. $success = FALSE;
  365. if (!t3lib_div::writeFile($writeToLocalconf_dat['tmpfile'], implode(LF, $lines))) {
  366. $msg = 'typo3conf/localconf.php' . $tmpExt . ' could not be written - maybe a write access problem?';
  367. }
  368. elseif (strcmp(t3lib_div::getUrl($writeToLocalconf_dat['tmpfile']), implode(LF, $lines))) {
  369. @unlink($writeToLocalconf_dat['tmpfile']);
  370. $msg = 'typo3conf/localconf.php' . $tmpExt . ' was NOT written properly (written content didn\'t match file content) - maybe a disk space problem?';
  371. }
  372. elseif (!@copy($writeToLocalconf_dat['tmpfile'], $writeToLocalconf_dat['file'])) {
  373. $msg = 'typo3conf/localconf.php could not be replaced by typo3conf/localconf.php' . $tmpExt . ' - maybe a write access problem?';
  374. }
  375. else {
  376. @unlink($writeToLocalconf_dat['tmpfile']);
  377. $success = TRUE;
  378. $msg = 'Configuration written to typo3conf/localconf.php';
  379. }
  380. $this->messages[] = $msg;
  381. if (!$success) {
  382. t3lib_div::sysLog($msg, 'Core', 3);
  383. }
  384. return $success;
  385. }
  386. /**
  387. * Checking for linebreaks in the string
  388. *
  389. * @param string String to test
  390. * @return boolean Returns TRUE if string is OK
  391. * @see setValueInLocalconfFile()
  392. */
  393. function checkForBadString($string) {
  394. return preg_match('/[' . LF . CR . ']/', $string) ? FALSE : TRUE;
  395. }
  396. /**
  397. * Replaces ' with \' and \ with \\
  398. *
  399. * @param string Input value
  400. * @return string Output value
  401. * @see setValueInLocalconfFile()
  402. */
  403. function slashValueForSingleDashes($value) {
  404. $value = str_replace("'.LF.'", '###INSTALL_TOOL_LINEBREAK###', $value);
  405. $value = str_replace("'", "\'", str_replace('\\', '\\\\', $value));
  406. $value = str_replace('###INSTALL_TOOL_LINEBREAK###', "'.LF.'", $value);
  407. return $value;
  408. }
  409. /*************************************
  410. *
  411. * SQL
  412. *
  413. *************************************/
  414. /**
  415. * Reads the field definitions for the input SQL-file string
  416. *
  417. * @param string Should be a string read from an SQL-file made with 'mysqldump [database_name] -d'
  418. * @return array Array with information about table.
  419. */
  420. function getFieldDefinitions_fileContent($fileContent) {
  421. $lines = t3lib_div::trimExplode(LF, $fileContent, 1);
  422. $table = '';
  423. $total = array();
  424. foreach ($lines as $value) {
  425. if (substr($value, 0, 1) == '#') {
  426. continue; // Ignore comments
  427. }
  428. if (!strlen($table)) {
  429. $parts = t3lib_div::trimExplode(' ', $value, TRUE);
  430. if (strtoupper($parts[0]) === 'CREATE' && strtoupper($parts[1]) === 'TABLE') {
  431. $table = str_replace('`', '', $parts[2]);
  432. if (TYPO3_OS == 'WIN') { // tablenames are always lowercase on windows!
  433. $table = strtolower($table);
  434. }
  435. }
  436. } else {
  437. if (substr($value, 0, 1) == ')' && substr($value, -1) == ';') {
  438. $ttype = array();
  439. if (preg_match('/(ENGINE|TYPE)[ ]*=[ ]*([a-zA-Z]*)/', $value, $ttype)) {
  440. $total[$table]['extra']['ENGINE'] = $ttype[2];
  441. } // Otherwise, just do nothing: If table engine is not defined, just accept the system default.
  442. // Set the collation, if specified
  443. if (preg_match('/(COLLATE)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcollation)) {
  444. $total[$table]['extra']['COLLATE'] = $tcollation[2];
  445. } else {
  446. // Otherwise, get the CHARACTER SET and try to find the default collation for it as returned by "SHOW CHARACTER SET" query (for details, see http://dev.mysql.com/doc/refman/5.1/en/charset-table.html)
  447. if (preg_match('/(CHARSET|CHARACTER SET)[ ]*=[ ]*([a-zA-z0-9_-]+)/', $value, $tcharset)) { // Note: Keywords "DEFAULT CHARSET" and "CHARSET" are the same, so "DEFAULT" can just be ignored
  448. $charset = $tcharset[2];
  449. } else {
  450. $charset = $GLOBALS['TYPO3_DB']->default_charset; // Fallback to default charset
  451. }
  452. $total[$table]['extra']['COLLATE'] = $this->getCollationForCharset($charset);
  453. }
  454. $table = ''; // Remove table marker and start looking for the next "CREATE TABLE" statement
  455. } else {
  456. $lineV = preg_replace('/,$/', '', $value); // Strip trailing commas
  457. $lineV = str_replace('`', '', $lineV);
  458. $lineV = str_replace(' ', ' ', $lineV); // Remove double blanks
  459. $parts = explode(' ', $lineV, 2);
  460. if (!preg_match('/(PRIMARY|UNIQUE|FULLTEXT|INDEX|KEY)/', $parts[0])) { // Field definition
  461. // Make sure there is no default value when auto_increment is set
  462. if (stristr($parts[1], 'auto_increment')) {
  463. $parts[1] = preg_replace('/ default \'0\'/i', '', $parts[1]);
  464. }
  465. // "default" is always lower-case
  466. if (stristr($parts[1], ' DEFAULT ')) {
  467. $parts[1] = str_ireplace(' DEFAULT ', ' default ', $parts[1]);
  468. }
  469. // Change order of "default" and "null" statements
  470. $parts[1] = preg_replace('/(.*) (default .*) (NOT NULL)/', '$1 $3 $2', $parts[1]);
  471. $parts[1] = preg_replace('/(.*) (default .*) (NULL)/', '$1 $3 $2', $parts[1]);
  472. $key = $parts[0];
  473. $total[$table]['fields'][$key] = $parts[1];
  474. } else { // Key definition
  475. $search = array('/UNIQUE (INDEX|KEY)/', '/FULLTEXT (INDEX|KEY)/', '/INDEX/');
  476. $replace = array('UNIQUE', 'FULLTEXT', 'KEY');
  477. $lineV = preg_replace($search, $replace, $lineV);
  478. if (preg_match('/PRIMARY|UNIQUE|FULLTEXT/', $parts[0])) {
  479. $parts[1] = preg_replace('/^(KEY|INDEX) /', '', $parts[1]);
  480. }
  481. $newParts = explode(' ', $parts[1], 2);
  482. $key = $parts[0] == 'PRIMARY' ? $parts[0] : $newParts[0];
  483. $total[$table]['keys'][$key] = $lineV;
  484. // This is a protection against doing something stupid: Only allow clearing of cache_* and index_* tables.
  485. if (preg_match('/^(cache|index)_/', $table)) {
  486. // Suggest to truncate (clear) this table
  487. $total[$table]['extra']['CLEAR'] = 1;
  488. }
  489. }
  490. }
  491. }
  492. }
  493. $this->getFieldDefinitions_sqlContent_parseTypes($total);
  494. return $total;
  495. }
  496. /**
  497. * Multiplies varchars/tinytext fields in size according to $this->multiplySize
  498. * 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.
  499. *
  500. * @param array Total array (from getFieldDefinitions_fileContent())
  501. * @return void
  502. * @access private
  503. * @see getFieldDefinitions_fileContent()
  504. */
  505. function getFieldDefinitions_sqlContent_parseTypes(&$total) {
  506. $mSize = (double) $this->multiplySize;
  507. if ($mSize > 1) {
  508. // Init SQL parser:
  509. $sqlParser = t3lib_div::makeInstance('t3lib_sqlparser');
  510. foreach ($total as $table => $cfg) {
  511. if (is_array($cfg['fields'])) {
  512. foreach ($cfg['fields'] as $fN => $fType) {
  513. $orig_fType = $fType;
  514. $fInfo = $sqlParser->parseFieldDef($fType);
  515. switch ($fInfo['fieldType']) {
  516. case 'char':
  517. case 'varchar':
  518. $newSize = round($fInfo['value'] * $mSize);
  519. if ($newSize <= 255) {
  520. $fInfo['value'] = $newSize;
  521. } else {
  522. $fInfo = array(
  523. 'fieldType' => 'text',
  524. 'featureIndex' => array(
  525. 'NOTNULL' => array(
  526. 'keyword' => 'NOT NULL'
  527. )
  528. )
  529. );
  530. // Change key definition if necessary (must use "prefix" on TEXT columns)
  531. if (is_array($cfg['keys'])) {
  532. foreach ($cfg['keys'] as $kN => $kType) {
  533. $match = array();
  534. preg_match('/^([^(]*)\(([^)]+)\)(.*)/', $kType, $match);
  535. $keys = array();
  536. foreach (t3lib_div::trimExplode(',', $match[2]) as $kfN) {
  537. if ($fN == $kfN) {
  538. $kfN .= '(' . $newSize . ')';
  539. }
  540. $keys[] = $kfN;
  541. }
  542. $total[$table]['keys'][$kN] = $match[1] . '(' . implode(',', $keys) . ')' . $match[3];
  543. }
  544. }
  545. }
  546. break;
  547. case 'tinytext':
  548. $fInfo['fieldType'] = 'text';
  549. break;
  550. }
  551. $total[$table]['fields'][$fN] = $sqlParser->compileFieldCfg($fInfo);
  552. if ($sqlParser->parse_error) {
  553. throw new RuntimeException(
  554. 'TYPO3 Fatal Error: ' . $sqlParser->parse_error,
  555. 1270853961
  556. );
  557. }
  558. }
  559. }
  560. }
  561. }
  562. }
  563. /**
  564. * Look up the default collation for specified character set based on "SHOW CHARACTER SET" output
  565. *
  566. * @param string Character set
  567. * @return string Corresponding default collation
  568. */
  569. function getCollationForCharset($charset) {
  570. // Load character sets, if not cached already
  571. if (!count($this->character_sets)) {
  572. if (method_exists($GLOBALS['TYPO3_DB'], 'admin_get_charsets')) {
  573. $this->character_sets = $GLOBALS['TYPO3_DB']->admin_get_charsets();
  574. } else {
  575. $this->character_sets[$charset] = array(); // Add empty element to avoid that the check will be repeated
  576. }
  577. }
  578. $collation = '';
  579. if (isset($this->character_sets[$charset]['Default collation'])) {
  580. $collation = $this->character_sets[$charset]['Default collation'];
  581. }
  582. return $collation;
  583. }
  584. /**
  585. * Reads the field definitions for the current database
  586. *
  587. * @return array Array with information about table.
  588. */
  589. function getFieldDefinitions_database() {
  590. $total = array();
  591. $tempKeys = array();
  592. $tempKeysPrefix = array();
  593. $GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db);
  594. echo $GLOBALS['TYPO3_DB']->sql_error();
  595. $tables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
  596. foreach ($tables as $tableName => $tableStatus) {
  597. // Fields:
  598. $fieldInformation = $GLOBALS['TYPO3_DB']->admin_get_fields($tableName);
  599. foreach ($fieldInformation as $fN => $fieldRow) {
  600. $total[$tableName]['fields'][$fN] = $this->assembleFieldDefinition($fieldRow);
  601. }
  602. // Keys:
  603. $keyInformation = $GLOBALS['TYPO3_DB']->admin_get_keys($tableName);
  604. foreach ($keyInformation as $keyRow) {
  605. $keyName = $keyRow['Key_name'];
  606. $colName = $keyRow['Column_name'];
  607. if ($keyRow['Sub_part']) {
  608. $colName .= '(' . $keyRow['Sub_part'] . ')';
  609. }
  610. $tempKeys[$tableName][$keyName][$keyRow['Seq_in_index']] = $colName;
  611. if ($keyName == 'PRIMARY') {
  612. $prefix = 'PRIMARY KEY';
  613. } else {
  614. if ($keyRow['Index_type'] == 'FULLTEXT') {
  615. $prefix = 'FULLTEXT';
  616. } elseif ($keyRow['Non_unique']) {
  617. $prefix = 'KEY';
  618. } else {
  619. $prefix = 'UNIQUE';
  620. }
  621. $prefix .= ' ' . $keyName;
  622. }
  623. $tempKeysPrefix[$tableName][$keyName] = $prefix;
  624. }
  625. // Table status (storage engine, collaction, etc.)
  626. if (is_array($tableStatus)) {
  627. $tableExtraFields = array(
  628. 'Engine' => 'ENGINE',
  629. 'Collation' => 'COLLATE',
  630. );
  631. foreach ($tableExtraFields as $mysqlKey => $internalKey) {
  632. if (isset($tableStatus[$mysqlKey])) {
  633. $total[$tableName]['extra'][$internalKey] = $tableStatus[$mysqlKey];
  634. }
  635. }
  636. }
  637. }
  638. // Compile key information:
  639. if (count($tempKeys)) {
  640. foreach ($tempKeys as $table => $keyInf) {
  641. foreach ($keyInf as $kName => $index) {
  642. ksort($index);
  643. $total[$table]['keys'][$kName] = $tempKeysPrefix[$table][$kName] . ' (' . implode(',', $index) . ')';
  644. }
  645. }
  646. }
  647. return $total;
  648. }
  649. /**
  650. * Compares two arrays with field information and returns information about fields that are MISSING and fields that have CHANGED.
  651. * FDsrc and FDcomp can be switched if you want the list of stuff to remove rather than update.
  652. *
  653. * @param array Field definitions, source (from getFieldDefinitions_fileContent())
  654. * @param array Field definitions, comparison. (from getFieldDefinitions_database())
  655. * @param string Table names (in list) which is the ONLY one observed.
  656. * @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.
  657. * @return array Returns an array with 1) all elements from $FDsrc that is not in $FDcomp (in key 'extra') and 2) all elements from $FDsrc that is different from the ones in $FDcomp
  658. */
  659. function getDatabaseExtra($FDsrc, $FDcomp, $onlyTableList = '', $ignoreNotNullWhenComparing = TRUE) {
  660. $extraArr = array();
  661. $diffArr = array();
  662. if (is_array($FDsrc)) {
  663. foreach ($FDsrc as $table => $info) {
  664. if (!strlen($onlyTableList) || t3lib_div::inList($onlyTableList, $table)) {
  665. if (!isset($FDcomp[$table])) {
  666. $extraArr[$table] = $info; // If the table was not in the FDcomp-array, the result array is loaded with that table.
  667. $extraArr[$table]['whole_table'] = 1;
  668. } else {
  669. $keyTypes = explode(',', 'extra,fields,keys');
  670. foreach ($keyTypes as $theKey) {
  671. if (is_array($info[$theKey])) {
  672. foreach ($info[$theKey] as $fieldN => $fieldC) {
  673. $fieldN = str_replace('`', '', $fieldN);
  674. if ($fieldN == 'COLLATE') {
  675. continue; // TODO: collation support is currently disabled (needs more testing)
  676. }
  677. if (!isset($FDcomp[$table][$theKey][$fieldN])) {
  678. $extraArr[$table][$theKey][$fieldN] = $fieldC;
  679. } else {
  680. $fieldC = trim($fieldC);
  681. if ($ignoreNotNullWhenComparing) {
  682. $fieldC = str_replace(' NOT NULL', '', $fieldC);
  683. $FDcomp[$table][$theKey][$fieldN] = str_replace(' NOT NULL', '', $FDcomp[$table][$theKey][$fieldN]);
  684. }
  685. if ($fieldC !== $FDcomp[$table][$theKey][$fieldN]) {
  686. $diffArr[$table][$theKey][$fieldN] = $fieldC;
  687. $diffArr_cur[$table][$theKey][$fieldN] = $FDcomp[$table][$theKey][$fieldN];
  688. }
  689. }
  690. }
  691. }
  692. }
  693. }
  694. }
  695. }
  696. }
  697. $output = array(
  698. 'extra' => $extraArr,
  699. 'diff' => $diffArr,
  700. 'diff_currentValues' => $diffArr_cur
  701. );
  702. return $output;
  703. }
  704. /**
  705. * Returns an array with SQL-statements that is needed to update according to the diff-array
  706. *
  707. * @param array Array with differences of current and needed DB settings. (from getDatabaseExtra())
  708. * @param string List of fields in diff array to take notice of.
  709. * @return array Array of SQL statements (organized in keys depending on type)
  710. */
  711. function getUpdateSuggestions($diffArr, $keyList = 'extra,diff') {
  712. $statements = array();
  713. $deletedPrefixKey = $this->deletedPrefixKey;
  714. $remove = 0;
  715. if ($keyList == 'remove') {
  716. $remove = 1;
  717. $keyList = 'extra';
  718. }
  719. $keyList = explode(',', $keyList);
  720. foreach ($keyList as $theKey) {
  721. if (is_array($diffArr[$theKey])) {
  722. foreach ($diffArr[$theKey] as $table => $info) {
  723. $whole_table = array();
  724. if (is_array($info['fields'])) {
  725. foreach ($info['fields'] as $fN => $fV) {
  726. if ($info['whole_table']) {
  727. $whole_table[] = $fN . ' ' . $fV;
  728. } else {
  729. // Special case to work around MySQL problems when adding auto_increment fields:
  730. if (stristr($fV, 'auto_increment')) {
  731. // The field can only be set "auto_increment" if there exists a PRIMARY key of that field already.
  732. // The check does not look up which field is primary but just assumes it must be the field with the auto_increment value...
  733. if (isset($diffArr['extra'][$table]['keys']['PRIMARY'])) {
  734. // Remove "auto_increment" from the statement - it will be suggested in a 2nd step after the primary key was created
  735. $fV = str_replace(' auto_increment', '', $fV);
  736. } else {
  737. // In the next step, attempt to clear the table once again (2 = force)
  738. $info['extra']['CLEAR'] = 2;
  739. }
  740. }
  741. if ($theKey == 'extra') {
  742. if ($remove) {
  743. if (substr($fN, 0, strlen($deletedPrefixKey)) != $deletedPrefixKey) {
  744. $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $deletedPrefixKey . $fN . ' ' . $fV . ';';
  745. $statements['change'][md5($statement)] = $statement;
  746. } else {
  747. $statement = 'ALTER TABLE ' . $table . ' DROP ' . $fN . ';';
  748. $statements['drop'][md5($statement)] = $statement;
  749. }
  750. } else {
  751. $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fN . ' ' . $fV . ';';
  752. $statements['add'][md5($statement)] = $statement;
  753. }
  754. } elseif ($theKey == 'diff') {
  755. $statement = 'ALTER TABLE ' . $table . ' CHANGE ' . $fN . ' ' . $fN . ' ' . $fV . ';';
  756. $statements['change'][md5($statement)] = $statement;
  757. $statements['change_currentValue'][md5($statement)] = $diffArr['diff_currentValues'][$table]['fields'][$fN];
  758. }
  759. }
  760. }
  761. }
  762. if (is_array($info['keys'])) {
  763. foreach ($info['keys'] as $fN => $fV) {
  764. if ($info['whole_table']) {
  765. $whole_table[] = $fV;
  766. } else {
  767. if ($theKey == 'extra') {
  768. if ($remove) {
  769. $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
  770. $statements['drop'][md5($statement)] = $statement;
  771. } else {
  772. $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
  773. $statements['add'][md5($statement)] = $statement;
  774. }
  775. } elseif ($theKey == 'diff') {
  776. $statement = 'ALTER TABLE ' . $table . ($fN == 'PRIMARY' ? ' DROP PRIMARY KEY' : ' DROP KEY ' . $fN) . ';';
  777. $statements['change'][md5($statement)] = $statement;
  778. $statement = 'ALTER TABLE ' . $table . ' ADD ' . $fV . ';';
  779. $statements['change'][md5($statement)] = $statement;
  780. }
  781. }
  782. }
  783. }
  784. if (is_array($info['extra'])) {
  785. $extras = array();
  786. $extras_currentValue = array();
  787. $clear_table = FALSE;
  788. foreach ($info['extra'] as $fN => $fV) {
  789. // Only consider statements which are missing in the database but don't remove existing properties
  790. if (!$remove) {
  791. if (!$info['whole_table']) { // If the whole table is created at once, we take care of this later by imploding all elements of $info['extra']
  792. if ($fN == 'CLEAR') {
  793. // Truncate table must happen later, not now
  794. // Valid values for CLEAR: 1=only clear if keys are missing, 2=clear anyway (force)
  795. if (count($info['keys']) || $fV == 2) {
  796. $clear_table = TRUE;
  797. }
  798. continue;
  799. } else {
  800. $extras[] = $fN . '=' . $fV;
  801. $extras_currentValue[] = $fN . '=' . $diffArr['diff_currentValues'][$table]['extra'][$fN];
  802. }
  803. }
  804. }
  805. }
  806. if ($clear_table) {
  807. $statement = 'TRUNCATE TABLE ' . $table . ';';
  808. $statements['clear_table'][md5($statement)] = $statement;
  809. }
  810. if (count($extras)) {
  811. $statement = 'ALTER TABLE ' . $table . ' ' . implode(' ', $extras) . ';';
  812. $statements['change'][md5($statement)] = $statement;
  813. $statements['change_currentValue'][md5($statement)] = implode(' ', $extras_currentValue);
  814. }
  815. }
  816. if ($info['whole_table']) {
  817. if ($remove) {
  818. if (substr($table, 0, strlen($deletedPrefixKey)) != $deletedPrefixKey) {
  819. $statement = 'ALTER TABLE ' . $table . ' RENAME ' . $deletedPrefixKey . $table . ';';
  820. $statements['change_table'][md5($statement)] = $statement;
  821. } else {
  822. $statement = 'DROP TABLE ' . $table . ';';
  823. $statements['drop_table'][md5($statement)] = $statement;
  824. }
  825. // count:
  826. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', $table);
  827. $statements['tables_count'][md5($statement)] = $count ? 'Records in table: ' . $count : '';
  828. } else {
  829. $statement = 'CREATE TABLE ' . $table . " (\n" . implode(",\n", $whole_table) . "\n)";
  830. if ($info['extra']) {
  831. foreach ($info['extra'] as $k => $v) {
  832. if ($k == 'COLLATE' || $k == 'CLEAR') {
  833. continue; // Skip these special statements. TODO: collation support is currently disabled (needs more testing)
  834. }
  835. $statement .= ' ' . $k . '=' . $v; // Add extra attributes like ENGINE, CHARSET, etc.
  836. }
  837. }
  838. $statement .= ';';
  839. $statements['create_table'][md5($statement)] = $statement;
  840. }
  841. }
  842. }
  843. }
  844. }
  845. return $statements;
  846. }
  847. /**
  848. * Converts a result row with field information into the SQL field definition string
  849. *
  850. * @param array MySQL result row
  851. * @return string Field definition
  852. */
  853. function assembleFieldDefinition($row) {
  854. $field = array($row['Type']);
  855. if ($row['Null'] == 'NO') {
  856. $field[] = 'NOT NULL';
  857. }
  858. if (!strstr($row['Type'], 'blob') && !strstr($row['Type'], 'text')) {
  859. // Add a default value if the field is not auto-incremented (these fields never have a default definition)
  860. if (!stristr($row['Extra'], 'auto_increment')) {
  861. $field[] = 'default \'' . addslashes($row['Default']) . '\'';
  862. }
  863. }
  864. if ($row['Extra']) {
  865. $field[] = $row['Extra'];
  866. }
  867. return implode(' ', $field);
  868. }
  869. /**
  870. * Returns an array where every entry is a single SQL-statement. Input must be formatted like an ordinary MySQL-dump files.
  871. *
  872. * @param string The SQL-file content. Provided that 1) every query in the input is ended with ';' and that a line in the file contains only one query or a part of a query.
  873. * @param boolean If set, non-SQL content (like comments and blank lines) is not included in the final output
  874. * @param string Regex to filter SQL lines to include
  875. * @return array Array of SQL statements
  876. */
  877. function getStatementArray($sqlcode, $removeNonSQL = 0, $query_regex = '') {
  878. $sqlcodeArr = explode(LF, $sqlcode);
  879. // Based on the assumption that the sql-dump has
  880. $statementArray = array();
  881. $statementArrayPointer = 0;
  882. foreach ($sqlcodeArr as $line => $lineContent) {
  883. $is_set = 0;
  884. // auto_increment fields cannot have a default value!
  885. if (stristr($lineContent, 'auto_increment')) {
  886. $lineContent = preg_replace('/ default \'0\'/i', '', $lineContent);
  887. }
  888. 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
  889. $statementArray[$statementArrayPointer] .= $lineContent;
  890. $is_set = 1;
  891. }
  892. if (substr(trim($lineContent), -1) == ';') {
  893. if (isset($statementArray[$statementArrayPointer])) {
  894. if (!trim($statementArray[$statementArrayPointer]) || ($query_regex && !preg_match('/' . $query_regex . '/i', trim($statementArray[$statementArrayPointer])))) {
  895. unset($statementArray[$statementArrayPointer]);
  896. }
  897. }
  898. $statementArrayPointer++;
  899. } elseif ($is_set) {
  900. $statementArray[$statementArrayPointer] .= LF;
  901. }
  902. }
  903. return $statementArray;
  904. }
  905. /**
  906. * Returns tables to create and how many records in each
  907. *
  908. * @param array Array of SQL statements to analyse.
  909. * @param boolean If set, will count number of INSERT INTO statements following that table definition
  910. * @return array Array with table definitions in index 0 and count in index 1
  911. */
  912. function getCreateTables($statements, $insertCountFlag = 0) {
  913. $crTables = array();
  914. $insertCount = array();
  915. foreach ($statements as $line => $lineContent) {
  916. $reg = array();
  917. if (preg_match('/^create[[:space:]]*table[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
  918. $table = trim($reg[1]);
  919. if ($table) {
  920. // table names are always lowercase on Windows!
  921. if (TYPO3_OS == 'WIN') {
  922. $table = strtolower($table);
  923. }
  924. $sqlLines = explode(LF, $lineContent);
  925. foreach ($sqlLines as $k => $v) {
  926. if (stristr($v, 'auto_increment')) {
  927. $sqlLines[$k] = preg_replace('/ default \'0\'/i', '', $v);
  928. }
  929. }
  930. $lineContent = implode(LF, $sqlLines);
  931. $crTables[$table] = $lineContent;
  932. }
  933. } elseif ($insertCountFlag && preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
  934. $nTable = trim($reg[1]);
  935. $insertCount[$nTable]++;
  936. }
  937. }
  938. return array($crTables, $insertCount);
  939. }
  940. /**
  941. * Extracts all insert statements from $statement array where content is inserted into $table
  942. *
  943. * @param array Array of SQL statements
  944. * @param string Table name
  945. * @return array Array of INSERT INTO statements where table match $table
  946. */
  947. function getTableInsertStatements($statements, $table) {
  948. $outStatements = array();
  949. foreach ($statements as $line => $lineContent) {
  950. $reg = array();
  951. if (preg_match('/^insert[[:space:]]*into[[:space:]]*[`]?([[:alnum:]_]*)[`]?/i', substr($lineContent, 0, 100), $reg)) {
  952. $nTable = trim($reg[1]);
  953. if ($nTable && !strcmp($table, $nTable)) {
  954. $outStatements[] = $lineContent;
  955. }
  956. }
  957. }
  958. return $outStatements;
  959. }
  960. /**
  961. * Performs the queries passed from the input array.
  962. *
  963. * @param array Array of SQL queries to execute.
  964. * @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)
  965. * @return mixed Array with error message from database if any occured. Otherwise true if everything was executed successfully.
  966. */
  967. function performUpdateQueries($arr, $keyArr) {
  968. $result = array();
  969. if (is_array($arr)) {
  970. foreach ($arr as $key => $string) {
  971. if (isset($keyArr[$key]) && $keyArr[$key]) {
  972. $res = $GLOBALS['TYPO3_DB']->admin_query($string);
  973. if ($res === FALSE) {
  974. $result[$key] = $GLOBALS['TYPO3_DB']->sql_error();
  975. } elseif (is_resource($res)) {
  976. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  977. }
  978. }
  979. }
  980. }
  981. if (count($result) > 0) {
  982. return $result;
  983. } else {
  984. return TRUE;
  985. }
  986. }
  987. /**
  988. * Returns list of tables in the database
  989. *
  990. * @return array List of tables.
  991. * @see t3lib_db::admin_get_tables()
  992. */
  993. function getListOfTables() {
  994. $whichTables = $GLOBALS['TYPO3_DB']->admin_get_tables(TYPO3_db);
  995. foreach ($whichTables as $key => &$value) {
  996. $value = $key;
  997. }
  998. return $whichTables;
  999. }
  1000. /**
  1001. * Creates a table which checkboxes for updating database.
  1002. *
  1003. * @param array Array of statements (key / value pairs where key is used for the checkboxes)
  1004. * @param string Label for the table.
  1005. * @param boolean If set, then checkboxes are set by default.
  1006. * @param boolean If set, then icons are shown.
  1007. * @param array Array of "current values" for each key/value pair in $arr. Shown if given.
  1008. * @param boolean If set, will show the prefix "Current value" if $currentValue is given.
  1009. * @return string HTML table with checkboxes for update. Must be wrapped in a form.
  1010. */
  1011. function generateUpdateDatabaseForm_checkboxes($arr, $label, $checked = 1, $iconDis = 0, $currentValue = array(), $cVfullMsg = 0) {
  1012. $out = array();
  1013. if (is_array($arr)) {
  1014. $tableId = uniqid('table');
  1015. if (count($arr) > 1) {
  1016. $out[] = '
  1017. <tr class="update-db-fields-batch">
  1018. <td valign="top">
  1019. <input type="checkbox" id="' . $tableId . '-checkbox"' . ($checked ? ' checked="checked"' : '') . '
  1020. onclick="$(\'' . $tableId . '\').select(\'input[type=checkbox]\').invoke(\'setValue\', $(this).checked);" />
  1021. </td>
  1022. <td nowrap="nowrap"><label for="' . $tableId . '-checkbox" style="cursor:pointer"><strong>select/deselect all</strong></label></td>
  1023. </tr>';
  1024. }
  1025. foreach ($arr as $key => $string) {
  1026. $ico = '';
  1027. $warnings = array();
  1028. if ($iconDis) {
  1029. if (preg_match('/^TRUNCATE/i', $string)) {
  1030. $ico .= '<img src="' . $this->backPath . 'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong> </strong>';
  1031. $warnings['clear_table_info'] = 'Clearing the table is sometimes neccessary when adding new keys. In case of cache_* tables this should not hurt at all. However, use it with care.';
  1032. } elseif (stristr($string, ' user_')) {
  1033. $ico .= '<img src="' . $this->backPath . 'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(USER) </strong>';
  1034. } elseif (stristr($string, ' app_')) {
  1035. $ico .= '<img src="' . $this->backPath . 'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(APP) </strong>';
  1036. } elseif (stristr($string, ' ttx_') || stristr($string, ' tx_')) {
  1037. $ico .= '<img src="' . $this->backPath . 'gfx/icon_warning.gif" width="18" height="16" align="top" alt="" /><strong>(EXT) </strong>';
  1038. }
  1039. }
  1040. $out[] = '
  1041. <tr>
  1042. <td valign="top"><input type="checkbox" id="db-' . $key . '" name="' . $this->dbUpdateCheckboxPrefix . '[' . $key . ']" value="1"' . ($checked ? ' checked="checked"' : '') . ' /></td>
  1043. <td nowrap="nowrap"><label for="db-' . $key . '">' . nl2br($ico . htmlspecialchars($string)) . '</label></td>
  1044. </tr>';
  1045. if (isset($currentValue[$key])) {
  1046. $out[] = '
  1047. <tr>
  1048. <td valign="top"></td>
  1049. <td nowrap="nowrap" style="color:#666666;">' . nl2br((!$cVfullMsg ? "Current value: " : "") . '<em>' . $currentValue[$key] . '</em>') . '</td>
  1050. </tr>';
  1051. }
  1052. }
  1053. if (count($warnings)) {
  1054. $out[] = '
  1055. <tr>
  1056. <td valign="top"></td>
  1057. <td style="color:#666666;"><em>' . implode('<br />', $warnings) . '</em></td>
  1058. </tr>';
  1059. }
  1060. // Compile rows:
  1061. $content = '
  1062. <!-- Update database fields / tables -->
  1063. <h3>' . $label . '</h3>
  1064. <table border="0" cellpadding="2" cellspacing="2" id="' . $tableId . '" class="update-db-fields">' . implode('', $out) . '
  1065. </table>';
  1066. }
  1067. return $content;
  1068. }
  1069. }
  1070. if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php'])) {
  1071. include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_install.php']);
  1072. }
  1073. ?>