[ Index ]
 

Code source de Typo3 4.1.3

Accédez au Source d'autres logiciels libres

Classes | Fonctions | Variables | Constantes | Tables

title

Body

[fermer]

/t3lib/ -> class.t3lib_install.php (source)

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


Généré le : Sun Nov 25 17:13:16 2007 par Balluche grâce à PHPXref 0.7
  Clicky Web Analytics