PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_install.php

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