b2evolution PHP Cross Reference Blogging Systems

Source: /install/_functions_evoupgrade.php - 4692 lines - 187926 bytes - Summary - Text - Print

Description: This file implements upgrading of DB tables b2evolution - {@link http://b2evolution.net/} Released under GNU GPL License - {@link http://b2evolution.net/about/license.html}

   1  <?php
   2  /**
   3   * This file implements upgrading of DB tables
   4   *
   5   * b2evolution - {@link http://b2evolution.net/}
   6   * Released under GNU GPL License - {@link http://b2evolution.net/about/license.html}
   7   * @copyright (c)2003-2014 by Francois Planque - {@link http://fplanque.com/}
   8   *
   9   * {@internal Open Source relicensing agreement:
  10   * Daniel HAHLER grants Francois PLANQUE the right to license
  11   * Daniel HAHLER's contributions to this file and the b2evolution project
  12   * under any OSI approved OSS license (http://www.opensource.org/licenses/).
  13   * }}
  14   *
  15   * @package install
  16   *
  17   * @version $Id: _functions_evoupgrade.php 6320 2014-03-25 04:37:43Z fplanque $
  18   */
  19  if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
  20  
  21  load_funcs('_core/_param.funcs.php');
  22  
  23  
  24  /**
  25   * Create a DB version checkpoint
  26   *
  27   * This is useful when the next operation might timeout or fail!
  28   * The checkpoint will allow to restart the script and continue where it stopped
  29   *
  30   * @param string version of DB at checkpoint
  31   */
  32  function set_upgrade_checkpoint( $version )
  33  {
  34      global $DB, $script_start_time, $locale, $action;
  35  
  36      echo "Creating DB schema version checkpoint at $version... ";
  37  
  38      if( $version < 8060 )
  39      {
  40          $query = 'UPDATE T_settings SET db_version = '.$version;
  41      }
  42      else
  43      {
  44          $query = "UPDATE T_settings
  45                                  SET set_value = '$version'
  46                                  WHERE set_name = 'db_version'";
  47      }
  48      $DB->query( $query );
  49  
  50  
  51      $elapsed_time = time() - $script_start_time;
  52  
  53      echo "OK. (Elapsed upgrade time: $elapsed_time seconds)<br />\n";
  54      evo_flush();
  55  
  56      $max_exe_time = ini_get( 'max_execution_time' );
  57      if( $max_exe_time && ( $elapsed_time > ( $max_exe_time - 20 ) ) )
  58      { // Max exe time not disabled and we're recahing the end
  59          $upgrade_action = ( ( $action == 'svn_upgrade' ) || ( $action == 'auto_upgrade' ) ) ? $action : 'evoupgrade';
  60          echo 'We are reaching the time limit for this script. Please click <a href="index.php?locale='.$locale.'&amp;action='.$upgrade_action.'">continue</a>...';
  61          // Dirty temporary solution:
  62          exit(0);
  63      }
  64  }
  65  
  66  
  67  /**
  68   * @return boolean Does a given index key name exist in DB?
  69   */
  70  function db_index_exists( $table, $index_name )
  71  {
  72      global $DB;
  73  
  74      $index_name = strtolower($index_name);
  75  
  76      $DB->query('SHOW INDEX FROM '.$table);
  77      while( $row = $DB->get_row() )
  78      {
  79          if( strtolower($row->Key_name) == $index_name )
  80          {
  81              return true;
  82          }
  83      }
  84  
  85      return false;
  86  }
  87  
  88  
  89  /**
  90   * @param string Table name
  91   * @param array Column names
  92   * @return boolean Does a list of given column names exist in DB?
  93   */
  94  function db_cols_exist( $table, $col_names )
  95  {
  96      global $DB;
  97  
  98      foreach( $col_names as $k => $v )
  99          $col_names[$k] = strtolower($v);
 100  
 101      foreach( $DB->get_results('SHOW COLUMNS FROM '.$table) as $row )
 102          if( ($key = array_search(strtolower($row->Field), $col_names)) !== false )
 103              unset( $col_names[$key] );
 104  
 105      return count($col_names) == 0;
 106  }
 107  
 108  /**
 109   * Drops a column, if it exists.
 110   */
 111  function db_drop_col( $table, $col_name )
 112  {
 113      global $DB;
 114  
 115      if( ! db_col_exists($table, $col_name) )
 116          return false;
 117  
 118      $DB->query( 'ALTER TABLE '.$table.' DROP COLUMN '.$col_name );
 119  }
 120  
 121  /**
 122   * Add a column, if it does not already exist.
 123   * If it exists already, a "ALTER TABLE" statement will get executed instead.
 124   *
 125   * @return boolean True if the column has been added, False if not.
 126   */
 127  function db_add_col( $table, $col_name, $col_desc )
 128  {
 129      global $DB;
 130  
 131      if( db_col_exists($table, $col_name) )
 132      { // Column exists already, make sure it's the same.
 133          $DB->query( 'ALTER TABLE '.$table.' MODIFY COLUMN '.$col_name.' '.$col_desc );
 134          return false;
 135      }
 136  
 137      $DB->query( 'ALTER TABLE '.$table.' ADD COLUMN '.$col_name.' '.$col_desc );
 138  }
 139  
 140  
 141  /**
 142   * Add an INDEX. If another index with the same name already exists, it will
 143   * get dropped before.
 144   */
 145  function db_add_index( $table, $name, $def, $type = 'INDEX' )
 146  {
 147      global $DB;
 148      if( db_index_exists($table, $name) )
 149      {
 150          $DB->query( 'ALTER TABLE '.$table.' DROP INDEX '.$name );
 151      }
 152      $DB->query( 'ALTER TABLE '.$table.' ADD '.$type.' '.$name.' ('.$def.')' );
 153  }
 154  
 155  
 156  /**
 157   * Check if a key item value already exists on database
 158   */
 159  function db_key_exists( $table, $field_name, $field_value )
 160  {
 161      global $DB;
 162      return $DB->get_var( '
 163          SELECT COUNT('.$field_name.')
 164          FROM '.$table.'
 165          WHERE '.$field_name.' = '.$field_value );
 166  }
 167  
 168  /**
 169   * Add a Foreign Key constraint.
 170   * If another foreign key exists between these two fields then the old FK will be deleted and a new will be created.
 171   * If the table engine is not InnoDB, then it will be changed automatically.
 172   * If the FK table contains data which would prevent foreign key creation then these records will be deleted.
 173   *
 174   * @param string foreign key table
 175   * @param string foreing key column name
 176   * @param string foreign key refrence table name
 177   * @param string reference column name in the reference table
 178   * @param string foreign key definition ( e.g. "ON DELETE CASCADE" or "ON UPDATE RESTRICT" )
 179   */
 180  function db_add_foreign_key( $table, $field_name, $reference_table, $reference_field_name, $definition )
 181  {
 182      global $DB;
 183      $table = preg_replace( $DB->dbaliases, $DB->dbreplaces, $table );
 184      $reference_table = preg_replace( $DB->dbaliases, $DB->dbreplaces, $reference_table );
 185      $foreign_key_fields = array( array(
 186              'fk_fields' => $field_name,
 187              'reference_table' => $reference_table,
 188              'reference_columns' => $reference_field_name,
 189              'fk_definition' => $definition,
 190              'create' => true, // This FK should be created if not exists
 191          ) );
 192      db_delta_foreign_keys( $foreign_key_fields, $table, true, 'add' );
 193  }
 194  
 195  /**
 196   * Drop a Foreign Key constraint.
 197   * If this foreign key not exists the function won't give error.
 198   *
 199   * @param string foreign key table
 200   * @param string foreing key column name
 201   * @param string foreign key refrence table name
 202   * @param string reference column name in the reference table
 203   */
 204  function db_drop_foreign_key( $table, $field_name, $reference_table, $reference_field_name )
 205  {
 206      global $DB;
 207      $table = preg_replace( $DB->dbaliases, $DB->dbreplaces, $table );
 208      $reference_table = preg_replace( $DB->dbaliases, $DB->dbreplaces, $reference_table );
 209      $foreign_key_fields = array( array(
 210              'fk_fields' => $field_name,
 211              'reference_table' => $reference_table,
 212              'reference_columns' => $reference_field_name,
 213              'fk_definition' => '',
 214              'create' => false, // This FK shouldn't be created if not exists
 215          ) );
 216      db_delta_foreign_keys( $foreign_key_fields, $table, true, 'drop' );
 217  }
 218  
 219  /**
 220   * Converts languages in a given table into according locales
 221   *
 222   * @param string name of the table
 223   * @param string name of the column where lang is stored
 224   * @param string name of the table's ID column
 225   */
 226  function convert_lang_to_locale( $table, $columnlang, $columnID )
 227  {
 228      global $DB, $locales, $default_locale;
 229  
 230      if( !preg_match('/[a-z]{2}-[A-Z]{2}(-.{1,14})?/', $default_locale) )
 231      { // we want a valid locale
 232          $default_locale = 'en-EU';
 233      }
 234  
 235      echo 'Converting langs to locales for '. $table. '...<br />';
 236  
 237      // query given languages in $table
 238      $query = "SELECT $columnID, $columnlang FROM $table";
 239      $languagestoconvert = array();
 240      foreach( $DB->get_results( $query, ARRAY_A ) as $row )
 241      {
 242          // remember the ID for that locale
 243          $languagestoconvert[ $row[ $columnlang ] ][] = $row[ $columnID ];
 244      }
 245  
 246      foreach( $languagestoconvert as $lkey => $lIDs)
 247      { // converting the languages we've found
 248          $converted = false;
 249          echo '&nbsp; Converting lang \''. $lkey. '\' '; // (with IDs: '. implode( ', ', $lIDs ). ').. ';
 250  
 251          if( preg_match('/[a-z]{2}-[A-Z]{2}(-.{1,14})?/', $lkey) )
 252          { // Already valid
 253              echo 'nothing to update, already valid!<br />';
 254              continue;
 255          }
 256  
 257          if( (strlen($lkey) == 2) && ( substr( $default_locale, 0, 2 ) != $lkey ) )
 258          { // we have an old two letter lang code to convert
 259              // and it doesn't match the default locale
 260              foreach( $locales as $newlkey => $v )
 261              {  // loop given locales
 262                  if( substr($newlkey, 0, 2) == strtolower($lkey) ) # TODO: check if valid/suitable
 263                  {  // if language matches, update
 264                      $converted = $DB->query( "
 265                          UPDATE $table
 266                             SET $columnlang = '$newlkey'
 267                           WHERE $columnlang = '$lkey'" );
 268                      echo 'to locale \''. $newlkey. '\'<br />';
 269                      break;
 270                  }
 271              }
 272          }
 273  
 274          if( !$converted )
 275          { // we have nothing converted yet, setting default:
 276              $DB->query( "UPDATE $table
 277                                              SET $columnlang = '$default_locale'
 278                                          WHERE $columnlang = '$lkey'" );
 279              echo 'forced to default locale \''. $default_locale. '\'<br />';
 280          }
 281      }
 282      echo "\n";
 283  }  // convert_lang_to_locale(-)
 284  
 285  
 286  /**
 287   * upgrade_b2evo_tables(-)
 288   *
 289   * @param string the action param value corresponding the current upgrade process ( evoupgrade, svn_upgrade, auto_upgrade )
 290   */
 291  function upgrade_b2evo_tables( $upgrade_action = 'evoupgrade' )
 292  {
 293      global $db_config, $tableprefix;
 294      global $baseurl, $old_db_version, $new_db_version;
 295      global $Group_Admins, $Group_Privileged, $Group_Bloggers, $Group_Users;
 296      global $locales, $locale;
 297      global $DB;
 298      global $admin_url;
 299      global $Settings, $Plugins;
 300  
 301      // used for defaults, when upgrading to 1.6
 302      global $use_fileupload, $fileupload_allowedtypes, $fileupload_maxk, $doubleCheckReferers;
 303  
 304      // new DB-delta functionality
 305      global $schema_queries, $inc_path;
 306  
 307      // used to check script time before starting to create db delta
 308      global $script_start_time;
 309  
 310      // Load DB schema from modules
 311      load_db_schema();
 312  
 313      load_funcs('_core/model/db/_upgrade.funcs.php');
 314  
 315  
 316      echo '<p>'.T_('Checking DB schema version...').' ';
 317      $old_db_version = get_db_version();
 318  
 319      if( empty($old_db_version) )
 320      {
 321          echo '<p><strong>OOPS! b2evolution doesn\'t seem to be installed yet.</strong></p>';
 322          return;
 323      }
 324  
 325      echo $old_db_version, ' : ';
 326  
 327      if( $old_db_version < 8000 ) debug_die( T_('This version is too old!') );
 328      if( $old_db_version > $new_db_version ) debug_die( T_('This version is too recent! We cannot downgrade to the version you are trying to install...') );
 329      echo "OK.<br />\n";
 330  
 331      if( $old_db_version < 8010 )
 332      {
 333          echo 'Upgrading users table... ';
 334          $query = "ALTER TABLE T_users
 335                              MODIFY COLUMN user_pass CHAR(32) NOT NULL";
 336          $DB->query( $query );
 337          echo "OK.<br />\n";
 338  
 339          echo 'Upgrading blogs table... ';
 340          $query = "ALTER TABLE T_blogs
 341                              MODIFY COLUMN blog_lang VARCHAR(20) NOT NULL DEFAULT 'en_US',
 342                              MODIFY COLUMN blog_longdesc TEXT NULL DEFAULT NULL";
 343          $DB->query( $query );
 344          echo "OK.<br />\n";
 345  
 346          echo 'Upgrading categories table... ';
 347          $query = "ALTER TABLE T_categories
 348                              ADD COLUMN cat_description VARCHAR(250) NULL DEFAULT NULL,
 349                              ADD COLUMN cat_longdesc TEXT NULL DEFAULT NULL,
 350                              ADD COLUMN cat_icon VARCHAR(30) NULL DEFAULT NULL";
 351          $DB->query( $query );
 352          echo "OK.<br />\n";
 353  
 354          echo 'Upgrading posts table... ';
 355          $query = "ALTER TABLE {$tableprefix}posts
 356                              MODIFY COLUMN post_lang VARCHAR(20) NOT NULL DEFAULT 'en_US',
 357                              ADD COLUMN post_urltitle VARCHAR(50) NULL DEFAULT NULL AFTER post_title,
 358                              ADD COLUMN post_url VARCHAR(250) NULL DEFAULT NULL AFTER post_urltitle,
 359                              ADD COLUMN post_comments ENUM('disabled', 'open', 'closed') NOT NULL DEFAULT 'open' AFTER post_wordcount";
 360          $DB->query( $query );
 361          echo "OK.<br />\n";
 362  
 363          echo 'Generating wordcounts... ';
 364          load_funcs('items/model/_item.funcs.php');
 365          $query = "SELECT ID, post_content FROM {$tableprefix}posts WHERE post_wordcount IS NULL";
 366          $i = 0;
 367          foreach( $DB->get_results( $query, ARRAY_A ) as $row )
 368          {
 369              $query_update_wordcount = "UPDATE {$tableprefix}posts
 370                                                                  SET post_wordcount = " . bpost_count_words($row['post_content']) . "
 371                                                                  WHERE ID = " . $row['ID'];
 372              $DB->query($query_update_wordcount);
 373              $i++;
 374          }
 375          echo "OK. ($i rows updated)<br />\n";
 376  
 377          set_upgrade_checkpoint( '8010' );
 378      }
 379  
 380  
 381      if( $old_db_version < 8020 )
 382      {
 383          echo 'Encoding passwords... ';
 384          $query = "UPDATE T_users
 385                              SET user_pass = MD5(user_pass)";
 386          $DB->query( $query );
 387          echo "OK.<br />\n";
 388  
 389          set_upgrade_checkpoint( '8020' );
 390      }
 391  
 392  
 393      if( $old_db_version < 8030 )
 394      {
 395          echo 'Deleting unecessary logs... ';
 396          $query = "DELETE FROM T_hitlog
 397                              WHERE hit_ignore = 'badchar'";
 398          $DB->query( $query );
 399          echo "OK.<br />\n";
 400  
 401          echo 'Updating blog urls... ';
 402          $query = "SELECT blog_ID, blog_siteurl FROM T_blogs";
 403          $i = 0;
 404          foreach( $DB->get_results( $query, ARRAY_A ) as $row )
 405          {
 406              $blog_ID = $row['blog_ID'];
 407              $blog_siteurl = $row['blog_siteurl'];
 408              // echo $blog_ID.':'.$blog_siteurl;
 409              if( strpos( $blog_siteurl.'/', $baseurl ) !== 0 )
 410              { // If not found at position 0
 411                  echo ' <strong>WARNING: please check blog #', $blog_ID, ' manually.</strong><br /> ';
 412                  continue;
 413              }
 414              // crop off the baseurl:
 415              $blog_siteurl = evo_substr( $blog_siteurl.'/', evo_strlen($baseurl) );
 416              // echo ' -> ', $blog_siteurl,'<br />';
 417  
 418              $query_update_blog = "UPDATE T_blogs SET blog_siteurl = '$blog_siteurl' WHERE blog_ID = $blog_ID";
 419              // echo $query_update_blog, '<br />';
 420              $DB->query( $query_update_blog );
 421              $i++;
 422          }
 423          echo "OK. ($i rows updated)<br />\n";
 424  
 425          set_upgrade_checkpoint( '8030' );
 426      }
 427  
 428  
 429      if( $old_db_version < 8040 )
 430      { // upgrade to 0.8.7
 431          echo 'Creating table for Antispam Blackist... ';
 432          $query = "CREATE TABLE T_antispam (
 433              aspm_ID bigint(11) NOT NULL auto_increment,
 434              aspm_string varchar(80) NOT NULL,
 435              aspm_source enum( 'local','reported','central' ) NOT NULL default 'reported',
 436              PRIMARY KEY aspm_ID (aspm_ID),
 437              UNIQUE aspm_string (aspm_string)
 438          )";
 439          $DB->query( $query );
 440          echo "OK.<br />\n";
 441  
 442          echo 'Creating default blacklist entries... ';
 443          // This string contains antispam information that is obfuscated because some hosting
 444          // companies prevent uploading PHP files containing "spam" strings.
 445          // pre_dump(get_antispam_query());
 446          $query = get_antispam_query();
 447          $DB->query( $query );
 448          echo "OK.<br />\n";
 449  
 450          echo 'Upgrading Settings table... ';
 451          $query = "ALTER TABLE T_settings
 452                              ADD COLUMN last_antispam_update datetime NOT NULL default '2000-01-01 00:00:00'";
 453          $DB->query( $query );
 454          echo "OK.<br />\n";
 455  
 456          set_upgrade_checkpoint( '8040' );
 457      }
 458  
 459  
 460      if( $old_db_version < 8050 )
 461      { // upgrade to 0.8.9
 462          echo 'Upgrading blogs table... ';
 463          $query = "ALTER TABLE T_blogs
 464                              ADD COLUMN blog_allowtrackbacks tinyint(1) NOT NULL default 1,
 465                              ADD COLUMN blog_allowpingbacks tinyint(1) NOT NULL default 0,
 466                              ADD COLUMN blog_pingb2evonet tinyint(1) NOT NULL default 0,
 467                              ADD COLUMN blog_pingtechnorati tinyint(1) NOT NULL default 0,
 468                              ADD COLUMN blog_pingweblogs tinyint(1) NOT NULL default 0,
 469                              ADD COLUMN blog_pingblodotgs tinyint(1) NOT NULL default 0,
 470                              ADD COLUMN blog_disp_bloglist tinyint NOT NULL DEFAULT 1";
 471          $DB->query( $query );
 472          echo "OK.<br />\n";
 473  
 474          // Create User Groups
 475          global $Group_Admins, $Group_Privileged, $Group_Bloggers, $Group_Users;
 476          echo 'Creating table for Groups... ';
 477          $query = "CREATE TABLE T_groups (
 478              grp_ID int(11) NOT NULL auto_increment,
 479              grp_name varchar(50) NOT NULL default '',
 480              grp_perm_admin enum('none','hidden','visible') NOT NULL default 'visible',
 481              grp_perm_blogs enum('user','viewall','editall') NOT NULL default 'user',
 482              grp_perm_stats enum('none','view','edit') NOT NULL default 'none',
 483              grp_perm_spamblacklist enum('none','view','edit') NOT NULL default 'none',
 484              grp_perm_options enum('none','view','edit') NOT NULL default 'none',
 485              grp_perm_users enum('none','view','edit') NOT NULL default 'none',
 486              grp_perm_templates TINYINT NOT NULL DEFAULT 0,
 487              grp_perm_files enum('none','view','add','edit','all') NOT NULL default 'none',
 488              PRIMARY KEY grp_ID (grp_ID)
 489          )";
 490          $DB->query( $query );
 491          echo "OK.<br />\n";
 492  
 493          // This table needs to be created here for proper group insertion
 494          task_begin( 'Creating table for Group Settings... ' );
 495          $DB->query( "CREATE TABLE T_groups__groupsettings (
 496              gset_grp_ID INT(11) UNSIGNED NOT NULL,
 497              gset_name VARCHAR(30) NOT NULL,
 498              gset_value VARCHAR(255) NULL,
 499              PRIMARY KEY (gset_grp_ID, gset_name)
 500          ) ENGINE = innodb" );
 501          task_end();
 502  
 503          echo 'Creating default groups... ';
 504          $Group_Admins = new Group(); // COPY !
 505          $Group_Admins->set( 'name', 'Administrators' );
 506          $Group_Admins->set( 'perm_admin', 'visible' );
 507          $Group_Admins->set( 'perm_blogs', 'editall' );
 508          $Group_Admins->set( 'perm_stats', 'edit' );
 509          $Group_Admins->set( 'perm_spamblacklist', 'edit' );
 510          $Group_Admins->set( 'perm_files', 'all' );
 511          $Group_Admins->set( 'perm_options', 'edit' );
 512          $Group_Admins->set( 'perm_templates', 1 );
 513          $Group_Admins->set( 'perm_users', 'edit' );
 514          $Group_Admins->dbinsert();
 515  
 516          $Group_Privileged = new Group(); // COPY !
 517          $Group_Privileged->set( 'name', 'Privileged Bloggers' );
 518          $Group_Privileged->set( 'perm_admin', 'visible' );
 519          $Group_Privileged->set( 'perm_blogs', 'viewall' );
 520          $Group_Privileged->set( 'perm_stats', 'view' );
 521          $Group_Privileged->set( 'perm_spamblacklist', 'edit' );
 522          $Group_Privileged->set( 'perm_files', 'add' );
 523          $Group_Privileged->set( 'perm_options', 'view' );
 524          $Group_Privileged->set( 'perm_templates', 0 );
 525          $Group_Privileged->set( 'perm_users', 'view' );
 526          $Group_Privileged->dbinsert();
 527  
 528          $Group_Bloggers = new Group(); // COPY !
 529          $Group_Bloggers->set( 'name', 'Bloggers' );
 530          $Group_Bloggers->set( 'perm_admin', 'visible' );
 531          $Group_Bloggers->set( 'perm_blogs', 'user' );
 532          $Group_Bloggers->set( 'perm_stats', 'none' );
 533          $Group_Bloggers->set( 'perm_spamblacklist', 'view' );
 534          $Group_Bloggers->set( 'perm_files', 'view' );
 535          $Group_Bloggers->set( 'perm_options', 'none' );
 536          $Group_Bloggers->set( 'perm_templates', 0 );
 537          $Group_Bloggers->set( 'perm_users', 'none' );
 538          $Group_Bloggers->dbinsert();
 539  
 540          $Group_Users = new Group(); // COPY !
 541          $Group_Users->set( 'name', 'Basic Users' );
 542          $Group_Users->set( 'perm_admin', 'none' );
 543          $Group_Users->set( 'perm_blogs', 'user' );
 544          $Group_Users->set( 'perm_stats', 'none' );
 545          $Group_Users->set( 'perm_spamblacklist', 'none' );
 546          $Group_Users->set( 'perm_files', 'none' );
 547          $Group_Users->set( 'perm_options', 'none' );
 548          $Group_Users->set( 'perm_templates', 0 );
 549          $Group_Users->set( 'perm_users', 'none' );
 550          $Group_Users->dbinsert();
 551          echo "OK.<br />\n";
 552  
 553  
 554          echo 'Creating table for Blog-User permissions... ';
 555          $query = "CREATE TABLE T_coll_user_perms (
 556              bloguser_blog_ID int(11) unsigned NOT NULL default 0,
 557              bloguser_user_ID int(11) unsigned NOT NULL default 0,
 558              bloguser_ismember tinyint NOT NULL default 0,
 559              bloguser_perm_poststatuses set('published','deprecated','protected','private','draft') NOT NULL default '',
 560              bloguser_perm_delpost tinyint NOT NULL default 0,
 561              bloguser_perm_comments tinyint NOT NULL default 0,
 562              bloguser_perm_cats tinyint NOT NULL default 0,
 563              bloguser_perm_properties tinyint NOT NULL default 0,
 564              bloguser_perm_media_upload tinyint NOT NULL default 0,
 565              bloguser_perm_media_browse tinyint NOT NULL default 0,
 566              bloguser_perm_media_change tinyint NOT NULL default 0,
 567              PRIMARY KEY bloguser_pk (bloguser_blog_ID,bloguser_user_ID)
 568          )";
 569          $DB->query( $query );
 570          echo "OK.<br />\n";
 571          $tablegroups_isuptodate = true;
 572          $tableblogusers_isuptodate = true;
 573  
 574          echo 'Creating user blog permissions... ';
 575          // Admin: full rights for all blogs (look 'ma, doing a natural join! :>)
 576          $query = "INSERT INTO T_coll_user_perms( bloguser_blog_ID, bloguser_user_ID, bloguser_ismember,
 577                                  bloguser_perm_poststatuses, bloguser_perm_delpost, bloguser_perm_comments,
 578                                  bloguser_perm_cats, bloguser_perm_properties)
 579                              SELECT blog_ID, ID, 1, 'published,deprecated,protected,private,draft', 1, 1, 1, 1
 580                              FROM T_users, T_blogs
 581                              WHERE user_level = 10";
 582          $DB->query( $query );
 583  
 584          // Normal users: basic rights for all blogs (can't stop doing joins :P)
 585          $query = "INSERT INTO T_coll_user_perms( bloguser_blog_ID, bloguser_user_ID, bloguser_ismember,
 586                                  bloguser_perm_poststatuses, bloguser_perm_delpost, bloguser_perm_comments,
 587                                  bloguser_perm_cats, bloguser_perm_properties)
 588                              SELECT blog_ID, ID, 1, 'published,protected,private,draft', 0, 1, 0, 0
 589                              FROM T_users, T_blogs
 590                              WHERE user_level > 0 AND user_level < 10";
 591          $DB->query( $query );
 592          echo "OK.<br />\n";
 593  
 594          echo 'Upgrading users table... ';
 595          $DB->query( 'UPDATE T_users
 596                                        SET dateYMDhour = \'2000-01-01 00:00:00\'
 597                                      WHERE ( dateYMDhour = \'0000-00-00 00:00:00\' OR dateYMDhour = \'2000-00-00 00:00:01\' )' );
 598          $DB->query( 'ALTER TABLE T_users
 599                              MODIFY COLUMN dateYMDhour DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\'' );
 600          $query = "ALTER TABLE T_users
 601                              ADD COLUMN user_notify tinyint(1) NOT NULL default 1,
 602                              ADD COLUMN user_grp_ID int(4) NOT NULL default 1,
 603                              MODIFY COLUMN user_idmode varchar(20) NOT NULL DEFAULT 'login',
 604                              ADD KEY user_grp_ID (user_grp_ID)";
 605          $DB->query( $query );
 606          echo "OK.<br />\n";
 607  
 608          echo 'Assigning user groups... ';
 609  
 610          // Default is 1, so admins are already set.
 611  
 612          // Basic Users:
 613          $query = "UPDATE T_users
 614                              SET user_grp_ID = $Group_Users->ID
 615                              WHERE user_level = 0";
 616          $DB->query( $query );
 617  
 618          // Bloggers:
 619          $query = "UPDATE T_users
 620                              SET user_grp_ID = $Group_Bloggers->ID
 621                              WHERE user_level > 0 AND user_level < 10";
 622          $DB->query( $query );
 623  
 624          echo "OK.<br />\n";
 625  
 626          echo 'Upgrading settings table... ';
 627          $query = "ALTER TABLE T_settings
 628                              DROP COLUMN time_format,
 629                              DROP COLUMN date_format,
 630                              ADD COLUMN pref_newusers_grp_ID int unsigned DEFAULT 4 NOT NULL,
 631                              ADD COLUMN pref_newusers_level tinyint unsigned DEFAULT 1 NOT NULL,
 632                              ADD COLUMN pref_newusers_canregister tinyint unsigned DEFAULT 0 NOT NULL";
 633          $DB->query( $query );
 634          echo "OK.<br />\n";
 635  
 636          set_upgrade_checkpoint( '8050' );
 637      }
 638  
 639  
 640      if( $old_db_version < 8060 )
 641      { // upgrade to 0.9
 642          // Important check:
 643          $stub_list = $DB->get_col( "
 644              SELECT blog_stub
 645                FROM T_blogs
 646               GROUP BY blog_stub
 647              HAVING COUNT(*) > 1" );
 648          if( !empty($stub_list) )
 649          {
 650              echo '<div class="error"><p class="error">';
 651              printf( T_("It appears that the following blog stub names are used more than once: ['%s']" ), implode( "','", $stub_list ) );
 652              echo '</p><p>';
 653              printf( T_("I can't upgrade until you make them unique. DB field: [%s]" ), $db_config['aliases']['T_blogs'].'.blog_stub' );
 654              echo '</p></div>';
 655              return false;
 656          }
 657  
 658          // Create locales
 659          echo 'Creating table for Locales... ';
 660          $query = "CREATE TABLE T_locales (
 661                  loc_locale varchar(20) NOT NULL default '',
 662                  loc_charset varchar(15) NOT NULL default 'iso-8859-1',
 663                  loc_datefmt varchar(10) NOT NULL default 'y-m-d',
 664                  loc_timefmt varchar(10) NOT NULL default 'H:i:s',
 665                  loc_name varchar(40) NOT NULL default '',
 666                  loc_messages varchar(20) NOT NULL default '',
 667                  loc_priority tinyint(4) UNSIGNED NOT NULL default '0',
 668                  loc_enabled tinyint(4) NOT NULL default '1',
 669                  PRIMARY KEY loc_locale( loc_locale )
 670              ) COMMENT='saves available locales'";
 671          $DB->query( $query );
 672          echo "OK.<br />\n";
 673  
 674          echo 'Upgrading posts table... ';
 675          $query = "UPDATE {$tableprefix}posts
 676                              SET post_urltitle = NULL";
 677          $DB->query( $query );
 678  
 679          $query = "ALTER TABLE {$tableprefix}posts
 680                              CHANGE COLUMN post_date post_issue_date datetime NOT NULL default '1000-01-01 00:00:00',
 681                              ADD COLUMN post_mod_date datetime NOT NULL default '1000-01-01 00:00:00'
 682                                          AFTER post_issue_date,
 683                              CHANGE COLUMN post_lang post_locale varchar(20) NOT NULL default 'en-EU',
 684                              DROP COLUMN post_url,
 685                              CHANGE COLUMN post_trackbacks post_url varchar(250) NULL default NULL,
 686                              ADD COLUMN post_renderers VARCHAR(179) NOT NULL default 'default',
 687                              DROP INDEX post_date,
 688                              ADD INDEX post_issue_date( post_issue_date ),
 689                              ADD UNIQUE post_urltitle( post_urltitle )";
 690          $DB->query( $query );
 691  
 692          $query = "UPDATE {$tableprefix}posts
 693                              SET post_mod_date = post_issue_date";
 694          $DB->query( $query );
 695          echo "OK.<br />\n";
 696  
 697          // convert given languages to locales
 698          convert_lang_to_locale( "{$tableprefix}posts", 'post_locale', 'ID' );
 699  
 700          echo 'Upgrading blogs table... ';
 701          $query = "ALTER TABLE T_blogs
 702                              CHANGE blog_lang blog_locale varchar(20) NOT NULL default 'en-EU',
 703                              CHANGE blog_roll blog_notes TEXT NULL,
 704                              MODIFY COLUMN blog_default_skin VARCHAR(30) NOT NULL DEFAULT 'custom',
 705                              DROP COLUMN blog_filename,
 706                              ADD COLUMN blog_access_type VARCHAR(10) NOT NULL DEFAULT 'index.php' AFTER blog_locale,
 707                              ADD COLUMN blog_force_skin tinyint(1) NOT NULL default 0 AFTER blog_default_skin,
 708                              ADD COLUMN blog_in_bloglist tinyint(1) NOT NULL DEFAULT 1 AFTER blog_disp_bloglist,
 709                              ADD COLUMN blog_links_blog_ID INT(4) NOT NULL DEFAULT 0,
 710                              ADD UNIQUE KEY blog_stub (blog_stub)";
 711          $DB->query( $query );
 712  
 713          $query = "UPDATE T_blogs
 714                              SET blog_access_type = 'stub',
 715                                      blog_default_skin = 'custom'";
 716          $DB->query( $query );
 717  
 718          echo "OK.<br />\n";
 719  
 720          // convert given languages to locales
 721          convert_lang_to_locale( 'T_blogs', 'blog_locale', 'blog_ID' );
 722  
 723  
 724          echo 'Converting settings table... ';
 725  
 726          // get old settings
 727          $query = 'SELECT * FROM T_settings';
 728          $row = $DB->get_row( $query, ARRAY_A );
 729  
 730          #echo 'oldrow:<br />'; pre_dump($row);
 731          $transform = array(
 732              'posts_per_page' => array(5),      // note: moved to blogsettings in 2.0
 733              'what_to_show' => array('posts'),  // note: moved to blogsettings in 2.0
 734              'archive_mode' => array('monthly'),// note: moved to blogsettings in 2.0
 735              'time_difference' => array(0),
 736              'AutoBR' => array(0),
 737              'last_antispam_update' => array('2000-01-01 00:00:00', 'antispam_last_update'),
 738              'pref_newusers_grp_ID' => array($Group_Users->ID, 'newusers_grp_ID'),
 739              'pref_newusers_level'  => array(1, 'newusers_level'),
 740              'pref_newusers_canregister' => array(0, 'newusers_canregister'),
 741          );
 742  
 743          $_trans = array();
 744          foreach( $transform as $oldkey => $newarr )
 745          {
 746              $newname = ( isset($newarr[1]) ? $newarr[1] : $oldkey );
 747              if( !isset( $row[$oldkey] ) )
 748              {
 749                  echo '&nbsp;&middot;Setting '.$oldkey.' not found, using defaults.<br />';
 750                  $_trans[ $newname ] = $newarr[0];
 751              }
 752              else
 753              {
 754                  $_trans[ $newname ] = $row[$oldkey];
 755              }
 756          }
 757  
 758          // drop old table
 759          $DB->query( 'DROP TABLE IF EXISTS T_settings' );
 760  
 761          // create new table
 762          $DB->query(
 763              'CREATE TABLE T_settings (
 764                  set_name VARCHAR( 30 ) NOT NULL ,
 765                  set_value VARCHAR( 255 ) NULL ,
 766                  PRIMARY KEY ( set_name )
 767              )');
 768  
 769          // insert defaults and use transformed settings
 770          create_default_settings( $_trans );
 771  
 772          if( !isset( $tableblogusers_isuptodate ) )
 773          {
 774              echo 'Upgrading Blog-User permissions table... ';
 775              $query = "ALTER TABLE T_coll_user_perms
 776                                  ADD COLUMN bloguser_ismember tinyint NOT NULL default 0 AFTER bloguser_user_ID";
 777              $DB->query( $query );
 778  
 779              // Any row that is created holds at least one permission,
 780              // minimum permsission is to be a member, so we add that one too, to all existing rows.
 781              $DB->query( "UPDATE T_coll_user_perms
 782                                              SET bloguser_ismember = 1" );
 783              echo "OK.<br />\n";
 784          }
 785  
 786          echo 'Upgrading Comments table... ';
 787          $DB->query( 'UPDATE T_comments
 788                                        SET comment_date = \'2000-01-01 00:00:00\'
 789                                      WHERE comment_date = \'0000-00-00 00:00:00\'' );
 790          $DB->query( 'ALTER TABLE T_comments
 791                              MODIFY COLUMN comment_date DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\'' );
 792          $query = "ALTER TABLE T_comments
 793                              ADD COLUMN comment_author_ID int unsigned NULL default NULL AFTER comment_status,
 794                              MODIFY COLUMN comment_author varchar(100) NULL,
 795                              MODIFY COLUMN comment_author_email varchar(100) NULL,
 796                              MODIFY COLUMN comment_author_url varchar(100) NULL,
 797                              MODIFY COLUMN comment_author_IP varchar(23) NOT NULL default ''";
 798          $DB->query( $query );
 799          echo "OK.<br />\n";
 800  
 801          echo 'Upgrading Users table... ';
 802          $query = "ALTER TABLE T_users ADD user_locale VARCHAR( 20 ) DEFAULT 'en-EU' NOT NULL AFTER user_yim";
 803          $DB->query( $query );
 804          echo "OK.<br />\n";
 805  
 806          set_upgrade_checkpoint( '8060' );
 807      }
 808  
 809  
 810      if( $old_db_version < 8062 )
 811      { // upgrade to 0.9.0.4
 812          echo "Checking for extra quote escaping in posts... ";
 813          $query = "SELECT ID, post_title, post_content
 814                                  FROM {$tableprefix}posts
 815                               WHERE post_title LIKE '%\\\\\\\\\'%'
 816                                      OR post_title LIKE '%\\\\\\\\\"%'
 817                                      OR post_content LIKE '%\\\\\\\\\'%'
 818                                      OR post_content LIKE '%\\\\\\\\\"%' ";
 819          /* FP: the above looks overkill, but MySQL is really full of surprises...
 820                          tested on 4.0.14-nt */
 821          // echo $query;
 822          $rows = $DB->get_results( $query, ARRAY_A );
 823          if( $DB->num_rows )
 824          {
 825              echo 'Updating '.$DB->num_rows.' posts... ';
 826              foreach( $rows as $row )
 827              {
 828                  // echo '<br />'.$row['post_title'];
 829                  $query = "UPDATE {$tableprefix}posts
 830                                      SET post_title = ".$DB->quote( stripslashes( $row['post_title'] ) ).",
 831                                              post_content = ".$DB->quote( stripslashes( $row['post_content'] ) )."
 832                                      WHERE ID = ".$row['ID'];
 833                  // echo '<br />'.$query;
 834                  $DB->query( $query );
 835              }
 836          }
 837          echo "OK.<br />\n";
 838  
 839          set_upgrade_checkpoint( '8062' );
 840      }
 841  
 842  
 843      if( $old_db_version < 8064 )
 844      { // upgrade to 0.9.0.6
 845          cleanup_comment_quotes();
 846  
 847          set_upgrade_checkpoint( '8064' );
 848      }
 849  
 850  
 851      if( $old_db_version < 8066 )
 852      {    // upgrade to 0.9.1
 853          echo 'Adding catpost index... ';
 854          $DB->query( 'ALTER TABLE T_postcats ADD UNIQUE catpost ( postcat_cat_ID, postcat_post_ID )' );
 855          echo "OK.<br />\n";
 856  
 857          set_upgrade_checkpoint( '8066' );
 858      }
 859  
 860  
 861      if( $old_db_version < 8800 )
 862      { // ---------------------------------- upgrade to 1.6 "phoenix ALPHA"
 863  
 864          echo 'Dropping old Hitlog table... ';
 865          $DB->query( 'DROP TABLE IF EXISTS T_hitlog' );
 866          echo "OK.<br />\n";
 867  
 868          // New tables:
 869              echo 'Creating table for active sessions... ';
 870              $DB->query( "CREATE TABLE T_sessions (
 871                                              sess_ID        INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
 872                                              sess_key       CHAR(32) NULL,
 873                                              sess_lastseen  DATETIME NOT NULL,
 874                                              sess_ipaddress VARCHAR(15) NOT NULL DEFAULT '',
 875                                              sess_user_ID   INT(10) DEFAULT NULL,
 876                                              sess_agnt_ID   INT UNSIGNED NULL,
 877                                              sess_data      TEXT DEFAULT NULL,
 878                                              PRIMARY KEY( sess_ID )
 879                                          )" );
 880              echo "OK.<br />\n";
 881  
 882  
 883              echo 'Creating user settings table... ';
 884              $DB->query( "CREATE TABLE {$tableprefix}usersettings (
 885                                              uset_user_ID INT(11) UNSIGNED NOT NULL,
 886                                              uset_name    VARCHAR( 30 ) NOT NULL,
 887                                              uset_value   VARCHAR( 255 ) NULL,
 888                                              PRIMARY KEY ( uset_user_ID, uset_name )
 889                                          )");
 890              echo "OK.<br />\n";
 891  
 892  
 893              echo 'Creating plugins table... ';
 894              $DB->query( "CREATE TABLE T_plugins (
 895                                              plug_ID        INT(11) UNSIGNED NOT NULL auto_increment,
 896                                              plug_priority  INT(11) NOT NULL default 50,
 897                                              plug_classname VARCHAR(40) NOT NULL default '',
 898                                              PRIMARY KEY ( plug_ID )
 899                                          )");
 900              echo "OK.<br />\n";
 901  
 902  
 903              echo 'Creating table for Post Statuses... ';
 904              $query="CREATE TABLE {$tableprefix}poststatuses (
 905                                              pst_ID   int(11) unsigned not null AUTO_INCREMENT,
 906                                              pst_name varchar(30)      not null,
 907                                              primary key ( pst_ID )
 908                                          )";
 909              $DB->query( $query );
 910              echo "OK.<br />\n";
 911  
 912  
 913              echo 'Creating table for Post Types... ';
 914              $query="CREATE TABLE {$tableprefix}posttypes (
 915                                              ptyp_ID   int(11) unsigned not null AUTO_INCREMENT,
 916                                              ptyp_name varchar(30)      not null,
 917                                              primary key (ptyp_ID)
 918                                          )";
 919              $DB->query( $query );
 920              echo "OK.<br />\n";
 921  
 922  
 923              echo 'Creating table for File Meta Data... ';
 924              $DB->query( "CREATE TABLE T_files (
 925                                           file_ID        int(11) unsigned  not null AUTO_INCREMENT,
 926                                           file_root_type enum('absolute','user','group','collection') not null default 'absolute',
 927                                           file_root_ID   int(11) unsigned  not null default 0,
 928                                           file_path      varchar(255)      not null default '',
 929                                           file_title     varchar(255),
 930                                           file_alt       varchar(255),
 931                                           file_desc      text,
 932                                           primary key (file_ID),
 933                                           unique file (file_root_type, file_root_ID, file_path)
 934                                      )" );
 935              echo "OK.<br />\n";
 936  
 937  
 938              echo 'Creating table for base domains... ';
 939              $DB->query( "CREATE TABLE T_basedomains (
 940                                          dom_ID     INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
 941                                          dom_name   VARCHAR(250) NOT NULL DEFAULT '',
 942                                          dom_status ENUM('unknown','whitelist','blacklist') NOT NULL DEFAULT 'unknown',
 943                                          dom_type   ENUM('unknown','normal','searcheng','aggregator') NOT NULL DEFAULT 'unknown',
 944                                          PRIMARY KEY (dom_ID),
 945                                          UNIQUE dom_name (dom_name)
 946                                      )" );    // fp> the unique key was only named in version 1.9. Crap. Put the name back here to save as many souls as possible. bulk has not upgraded from 0.9 yet :/
 947              echo "OK.<br />\n";
 948  
 949          set_upgrade_checkpoint( '8820' );
 950      }
 951  
 952  
 953      if( $old_db_version < 8840 )
 954      {
 955  
 956              echo 'Creating table for user agents... ';
 957              $DB->query( "CREATE TABLE {$tableprefix}useragents (
 958                                          agnt_ID        INT UNSIGNED NOT NULL AUTO_INCREMENT,
 959                                          agnt_signature VARCHAR(250) NOT NULL,
 960                                          agnt_type      ENUM('rss','robot','browser','unknown') DEFAULT 'unknown' NOT NULL,
 961                                          PRIMARY KEY (agnt_ID) )" );
 962              echo "OK.<br />\n";
 963  
 964  
 965              echo 'Creating table for Hit-Logs... ';
 966              $query = "CREATE TABLE T_hitlog (
 967                                      hit_ID             INT(11) NOT NULL AUTO_INCREMENT,
 968                                      hit_sess_ID        INT UNSIGNED,
 969                                      hit_datetime       DATETIME NOT NULL,
 970                                      hit_uri            VARCHAR(250) DEFAULT NULL,
 971                                      hit_referer_type   ENUM('search','blacklist','referer','direct','spam') NOT NULL,
 972                                      hit_referer        VARCHAR(250) DEFAULT NULL,
 973                                      hit_referer_dom_ID INT UNSIGNED DEFAULT NULL,
 974                                      hit_blog_ID        int(11) UNSIGNED NULL DEFAULT NULL,
 975                                      hit_remote_addr    VARCHAR(40) DEFAULT NULL,
 976                                      PRIMARY KEY (hit_ID),
 977                                      INDEX hit_datetime ( hit_datetime ),
 978                                      INDEX hit_blog_ID (hit_blog_ID)
 979                                  )";
 980              $DB->query( $query );
 981              echo "OK.<br />\n";
 982  
 983  
 984              echo 'Creating table for subscriptions... ';
 985              $DB->query( "CREATE TABLE T_subscriptions (
 986                                           sub_coll_ID     int(11) unsigned    not null,
 987                                           sub_user_ID     int(11) unsigned    not null,
 988                                           sub_items       tinyint(1)          not null,
 989                                           sub_comments    tinyint(1)          not null,
 990                                           primary key (sub_coll_ID, sub_user_ID)
 991                                          )" );
 992              echo "OK.<br />\n";
 993  
 994  
 995              echo 'Creating table for blog-group permissions... ';
 996              $DB->query( "CREATE TABLE T_coll_group_perms (
 997                                              bloggroup_blog_ID int(11) unsigned NOT NULL default 0,
 998                                              bloggroup_group_ID int(11) unsigned NOT NULL default 0,
 999                                              bloggroup_ismember tinyint NOT NULL default 0,
1000                                              bloggroup_perm_poststatuses set('published','deprecated','protected','private','draft') NOT NULL default '',
1001                                              bloggroup_perm_delpost tinyint NOT NULL default 0,
1002                                              bloggroup_perm_comments tinyint NOT NULL default 0,
1003                                              bloggroup_perm_cats tinyint NOT NULL default 0,
1004                                              bloggroup_perm_properties tinyint NOT NULL default 0,
1005                                              bloggroup_perm_media_upload tinyint NOT NULL default 0,
1006                                              bloggroup_perm_media_browse tinyint NOT NULL default 0,
1007                                              bloggroup_perm_media_change tinyint NOT NULL default 0,
1008                                              PRIMARY KEY bloggroup_pk (bloggroup_blog_ID,bloggroup_group_ID) )" );
1009              echo "OK.<br />\n";
1010  
1011  
1012          echo 'Upgrading blogs table... ';
1013          $query = "ALTER TABLE T_blogs
1014                              MODIFY COLUMN blog_ID int(11) unsigned NOT NULL auto_increment,
1015                              MODIFY COLUMN blog_links_blog_ID INT(11) NULL DEFAULT NULL,
1016                              CHANGE COLUMN blog_stub blog_urlname VARCHAR(255) NOT NULL DEFAULT 'urlname',
1017                              ADD COLUMN blog_allowcomments VARCHAR(20) NOT NULL default 'post_by_post' AFTER blog_keywords,
1018                              ADD COLUMN blog_allowblogcss TINYINT(1) NOT NULL default 1 AFTER blog_allowpingbacks,
1019                              ADD COLUMN blog_allowusercss TINYINT(1) NOT NULL default 1 AFTER blog_allowblogcss,
1020                              ADD COLUMN blog_stub VARCHAR(255) NOT NULL DEFAULT 'stub' AFTER blog_staticfilename,
1021                              ADD COLUMN blog_commentsexpire INT(4) NOT NULL DEFAULT 0 AFTER blog_links_blog_ID,
1022                              ADD COLUMN blog_media_location ENUM( 'default', 'subdir', 'custom', 'none' ) DEFAULT 'default' NOT NULL AFTER blog_commentsexpire,
1023                              ADD COLUMN blog_media_subdir VARCHAR( 255 ) NOT NULL AFTER blog_media_location,
1024                              ADD COLUMN blog_media_fullpath VARCHAR( 255 ) NOT NULL AFTER blog_media_subdir,
1025                              ADD COLUMN blog_media_url VARCHAR(255) NOT NULL AFTER blog_media_fullpath,
1026                              DROP INDEX blog_stub,
1027                              ADD UNIQUE blog_urlname ( blog_urlname )";
1028          $DB->query( $query );
1029          echo "OK.<br />\n";
1030  
1031          set_upgrade_checkpoint( '8840' );
1032      }
1033  
1034  
1035      // sam2kb>fp: We need to make sure there are no values like "blog_a.php" in blog_urlname,
1036      //            after this upgrade blog URLs look like $baseurl.'blog_a.php' which might be OK in 0.x version,
1037      //            but this config will not work in b2evo 4. Blog URLs will be broken!
1038      if( $old_db_version < 8850 )
1039      {
1040          echo 'Updating relative URLs... ';
1041          // We need to move the slashes to the end:
1042          $query = "UPDATE T_blogs
1043                                   SET blog_siteurl = CONCAT( SUBSTRING(blog_siteurl,2) , '/' )
1044                               WHERE blog_siteurl LIKE '/%'";
1045          $DB->query( $query );
1046          echo "OK.<br />\n";
1047  
1048          echo 'Copying urlnames to stub names... ';
1049          $query = 'UPDATE T_blogs
1050                              SET blog_stub = blog_urlname';
1051          $DB->query( $query );
1052          echo "OK.<br />\n";
1053  
1054          set_upgrade_checkpoint( '8850' );
1055      }
1056  
1057  
1058      if( $old_db_version < 8855 )
1059      {
1060          echo 'Upgrading posts table... ';
1061          $query = "ALTER TABLE {$tableprefix}posts
1062                              DROP COLUMN post_karma,
1063                              DROP COLUMN post_autobr,
1064                              DROP INDEX post_author,
1065                              DROP INDEX post_issue_date,
1066                              DROP INDEX post_category,
1067                              CHANGE COLUMN ID post_ID int(11) unsigned NOT NULL auto_increment,
1068                              CHANGE COLUMN post_author    post_creator_user_ID int(11) unsigned NOT NULL,
1069                              CHANGE COLUMN post_issue_date    post_datestart datetime NOT NULL,
1070                              CHANGE COLUMN post_mod_date    post_datemodified datetime NOT NULL,
1071                              CHANGE COLUMN post_category post_main_cat_ID int(11) unsigned NOT NULL,
1072                              ADD post_parent_ID                int(11) unsigned NULL AFTER post_ID,
1073                              ADD post_lastedit_user_ID    int(11) unsigned NULL AFTER post_creator_user_ID,
1074                              ADD post_assigned_user_ID    int(11) unsigned NULL AFTER post_lastedit_user_ID,
1075                              ADD post_datedeadline         datetime NULL AFTER post_datestart,
1076                              ADD post_datecreated            datetime NULL AFTER post_datedeadline,
1077                              ADD post_pst_ID                        int(11) unsigned NULL AFTER post_status,
1078                              ADD post_ptyp_ID                    int(11) unsigned NULL AFTER post_pst_ID,
1079                              ADD post_views                        int(11) unsigned NOT NULL DEFAULT 0 AFTER post_flags,
1080                              ADD post_commentsexpire        datetime DEFAULT NULL AFTER post_comments,
1081                              ADD post_priority                    int(11) unsigned null,
1082                              ADD INDEX post_creator_user_ID( post_creator_user_ID ),
1083                              ADD INDEX post_parent_ID( post_parent_ID ),
1084                              ADD INDEX post_assigned_user_ID( post_assigned_user_ID ),
1085                              ADD INDEX post_datestart( post_datestart ),
1086                              ADD INDEX post_main_cat_ID( post_main_cat_ID ),
1087                              ADD INDEX post_ptyp_ID( post_ptyp_ID ),
1088                              ADD INDEX post_pst_ID( post_pst_ID ) ";
1089          $DB->query( $query );
1090          echo "OK.<br />\n";
1091  
1092          set_upgrade_checkpoint( '8855' );
1093      }
1094  
1095  
1096      if( $old_db_version < 8860 )
1097      {
1098          echo 'Updating post data... ';
1099          $query = "UPDATE {$tableprefix}posts
1100                              SET post_lastedit_user_ID = post_creator_user_ID,
1101                                      post_datecreated = post_datestart";
1102          $DB->query( $query );
1103          echo "OK.<br />\n";
1104  
1105  
1106          task_begin( 'Upgrading users table... ' );
1107          $DB->query( 'UPDATE T_users
1108                                        SET dateYMDhour = \'2000-01-01 00:00:00\'
1109                                      WHERE dateYMDhour = \'0000-00-00 00:00:00\'' );
1110          $DB->query( 'ALTER TABLE T_users
1111                              MODIFY COLUMN dateYMDhour DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\',
1112                              CHANGE COLUMN ID user_ID int(11) unsigned NOT NULL auto_increment,
1113                              MODIFY COLUMN user_icq int(11) unsigned DEFAULT 0 NOT NULL,
1114                              ADD COLUMN user_showonline tinyint(1) NOT NULL default 1 AFTER user_notify' );
1115          task_end();
1116  
1117  
1118          set_upgrade_checkpoint( '8860' );
1119      }
1120  
1121  
1122      if( $old_db_version < 8900 )
1123      {
1124  
1125          echo 'Setting new defaults... ';
1126          $query = 'INSERT INTO T_settings (set_name, set_value)
1127                              VALUES
1128                                  ( "reloadpage_timeout", "300" ),
1129                                  ( "upload_enabled", "'.(isset($use_fileupload) ? (int)$use_fileupload : '1').'" ),
1130                                  ( "upload_allowedext", "'.(isset($fileupload_allowedtypes) ? $fileupload_allowedtypes : 'jpg gif png').'" ),
1131                                  ( "upload_maxkb", "'.(isset($fileupload_maxk) ? (int)$fileupload_maxk : '96').'" )
1132                              ';
1133          $DB->query( $query );
1134          // Replace "paged" mode with "posts" // note: moved to blogsettings in 2.0
1135          $DB->query( 'UPDATE T_settings
1136                                          SET set_value = "posts"
1137                                      WHERE set_name = "what_to_show"
1138                                        AND set_value = "paged"' );
1139          echo "OK.<br />\n";
1140  
1141  
1142          if( !isset( $tableblogusers_isuptodate ) )
1143          {    // We have created the blogusers table before and it's already clean!
1144              echo 'Altering table for Blog-User permissions... ';
1145              $DB->query( 'ALTER TABLE T_coll_user_perms
1146                                          MODIFY COLUMN bloguser_blog_ID int(11) unsigned NOT NULL default 0,
1147                                          MODIFY COLUMN bloguser_user_ID int(11) unsigned NOT NULL default 0,
1148                                          ADD COLUMN bloguser_perm_media_upload tinyint NOT NULL default 0,
1149                                          ADD COLUMN bloguser_perm_media_browse tinyint NOT NULL default 0,
1150                                          ADD COLUMN bloguser_perm_media_change tinyint NOT NULL default 0' );
1151              echo "OK.<br />\n";
1152          }
1153  
1154  
1155          task_begin( 'Altering comments table...' );
1156          $DB->query( 'UPDATE T_comments
1157                                        SET comment_date = \'2000-01-01 00:00:00\'
1158                                      WHERE comment_date = \'0000-00-00 00:00:00\'' );
1159          $DB->query( 'ALTER TABLE T_comments
1160                                      MODIFY COLUMN comment_date DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\',
1161                                      MODIFY COLUMN comment_post_ID        int(11) unsigned NOT NULL default 0' );
1162          task_end();
1163  
1164          set_upgrade_checkpoint( '8900' );
1165      }
1166  
1167      if( $old_db_version < 9000 )
1168      {
1169          echo 'Altering Posts to Categories table... ';
1170          $DB->query( "ALTER TABLE T_postcats
1171                                      MODIFY COLUMN postcat_post_ID int(11) unsigned NOT NULL,
1172                                      MODIFY COLUMN postcat_cat_ID int(11) unsigned NOT NULL" );
1173          echo "OK.<br />\n";
1174  
1175  
1176          echo 'Altering Categories table... ';
1177          $DB->query( "ALTER TABLE T_categories
1178                                      MODIFY COLUMN cat_ID int(11) unsigned NOT NULL auto_increment,
1179                                      MODIFY COLUMN cat_parent_ID int(11) unsigned NULL,
1180                                      MODIFY COLUMN cat_blog_ID int(11) unsigned NOT NULL default 2" );
1181          echo "OK.<br />\n";
1182  
1183  
1184          echo 'Altering Locales table... ';
1185          $DB->query( 'ALTER TABLE T_locales
1186                                      ADD loc_startofweek TINYINT UNSIGNED NOT NULL DEFAULT 1 AFTER loc_timefmt' );
1187          echo "OK.<br />\n";
1188  
1189  
1190          if( !isset( $tablegroups_isuptodate ) )
1191          {    // We have created the groups table before and it's already clean!
1192              echo 'Altering Groups table... ';
1193              $DB->query( "ALTER TABLE T_groups
1194                                          ADD COLUMN grp_perm_admin enum('none','hidden','visible') NOT NULL default 'visible' AFTER grp_name,
1195                                          ADD COLUMN grp_perm_files enum('none','view','add','edit') NOT NULL default 'none'" );
1196              echo "OK.<br />\n";
1197          }
1198  
1199  
1200          echo 'Creating table for Post Links... ';
1201          $DB->query( "CREATE TABLE T_links (
1202                                      link_ID               int(11) unsigned  not null AUTO_INCREMENT,
1203                                      link_datecreated      datetime          not null,
1204                                      link_datemodified     datetime          not null,
1205                                      link_creator_user_ID  int(11) unsigned  not null,
1206                                      link_lastedit_user_ID int(11) unsigned  not null,
1207                                      link_item_ID          int(11) unsigned  NOT NULL,
1208                                      link_dest_item_ID     int(11) unsigned  NULL,
1209                                      link_file_ID          int(11) unsigned  NULL,
1210                                      link_ltype_ID         int(11) unsigned  NOT NULL default 1,
1211                                      link_external_url     VARCHAR(255)      NULL,
1212                                      link_title            TEXT              NULL,
1213                                      PRIMARY KEY (link_ID),
1214                                      INDEX link_item_ID( link_item_ID ),
1215                                      INDEX link_dest_item_ID (link_dest_item_ID),
1216                                      INDEX link_file_ID (link_file_ID)
1217                                  )" );
1218          echo "OK.<br />\n";
1219  
1220  
1221          echo 'Creating default Post Types... ';
1222          $DB->query( "
1223              INSERT INTO {$tableprefix}posttypes ( ptyp_ID, ptyp_name )
1224              VALUES ( 1, 'Post' ),
1225                     ( 2, 'Link' )" );
1226          echo "OK.<br />\n";
1227  
1228  
1229          set_upgrade_checkpoint( '9000' );
1230      }
1231  
1232  
1233      if( $old_db_version < 9100 )
1234      {    // 1.8 ALPHA
1235  
1236          echo 'Creating table for plugin events... ';
1237          $DB->query( '
1238              CREATE TABLE T_pluginevents(
1239                      pevt_plug_ID INT(11) UNSIGNED NOT NULL,
1240                      pevt_event VARCHAR(40) NOT NULL,
1241                      pevt_enabled TINYINT NOT NULL DEFAULT 1,
1242                      PRIMARY KEY( pevt_plug_ID, pevt_event )
1243                  )' );
1244          echo "OK.<br />\n";
1245  
1246  
1247          echo 'Altering Links table... ';
1248          $DB->query( 'ALTER TABLE T_links
1249                       CHANGE link_item_ID link_itm_ID INT( 11 ) UNSIGNED NOT NULL,
1250                       CHANGE link_dest_item_ID link_dest_itm_ID INT( 11 ) UNSIGNED NULL' );
1251          echo "OK.<br />\n";
1252  
1253  
1254          if( $old_db_version >= 9000 )
1255          { // sess_agnt_ID used in Phoenix-Alpha
1256              echo 'Altering sessions table... ';
1257              $query = "
1258                      ALTER TABLE T_sessions
1259                       DROP COLUMN sess_agnt_ID";
1260              $DB->query( $query );
1261              echo "OK.<br />\n";
1262          }
1263  
1264          echo 'Creating table for file types... ';
1265          $DB->query( '
1266                  CREATE TABLE T_filetypes (
1267                      ftyp_ID int(11) unsigned NOT NULL auto_increment,
1268                      ftyp_extensions varchar(30) NOT NULL,
1269                      ftyp_name varchar(30) NOT NULL,
1270                      ftyp_mimetype varchar(50) NOT NULL,
1271                      ftyp_icon varchar(20) default NULL,
1272                      ftyp_viewtype varchar(10) NOT NULL,
1273                      ftyp_allowed tinyint(1) NOT NULL default 0,
1274                      PRIMARY KEY (ftyp_ID)
1275                  )' );
1276          echo "OK.<br />\n";
1277  
1278          echo 'Creating default file types... ';
1279          $DB->query( "INSERT INTO T_filetypes
1280                  (ftyp_ID, ftyp_extensions, ftyp_name, ftyp_mimetype, ftyp_icon, ftyp_viewtype, ftyp_allowed)
1281              VALUES
1282                  (1, 'gif', 'GIF image', 'image/gif', 'image2.png', 'image', 1),
1283                  (2, 'png', 'PNG image', 'image/png', 'image2.png', 'image', 1),
1284                  (3, 'jpg jpeg', 'JPEG image', 'image/jpeg', 'image2.png', 'image', 1),
1285                  (4, 'txt', 'Text file', 'text/plain', 'document.png', 'text', 1),
1286                  (5, 'htm html', 'HTML file', 'text/html', 'html.png', 'browser', 0),
1287                  (6, 'pdf', 'PDF file', 'application/pdf', 'pdf.png', 'browser', 1),
1288                  (7, 'doc', 'Microsoft Word file', 'application/msword', 'doc.gif', 'external', 1),
1289                  (8, 'xls', 'Microsoft Excel file', 'application/vnd.ms-excel', 'xls.gif', 'external', 1),
1290                  (9, 'ppt', 'Powerpoint', 'application/vnd.ms-powerpoint', 'ppt.gif', 'external', 1),
1291                  (10, 'pps', 'Slideshow', 'pps', 'pps.gif', 'external', 1),
1292                  (11, 'zip', 'ZIP archive', 'application/zip', 'zip.gif', 'external', 1),
1293                  (12, 'php php3 php4 php5 php6', 'PHP script', 'application/x-httpd-php', 'php.gif', 'text', 0),
1294                  (13, 'css', 'Style sheet', 'text/css', '', 'text', 1)
1295              " );
1296          echo "OK.<br />\n";
1297  
1298          echo 'Giving Administrator Group edit perms on files... ';
1299          $DB->query( 'UPDATE T_groups
1300                       SET grp_perm_files = "edit"
1301                       WHERE grp_ID = 1' );
1302           // Later versions give 'all' on install, but we won't upgrade to that for security.
1303          echo "OK.<br />\n";
1304  
1305          echo 'Giving Administrator Group full perms on media for all blogs... ';
1306          $DB->query( 'UPDATE T_coll_group_perms
1307                       SET bloggroup_perm_media_upload = 1,
1308                           bloggroup_perm_media_browse = 1,
1309                           bloggroup_perm_media_change = 1
1310                       WHERE bloggroup_group_ID = 1' );
1311          echo "OK.<br />\n";
1312  
1313  
1314          if( $old_db_version >= 9000 )
1315          { // Uninstall all ALPHA (potentially incompatible) plugins
1316              echo 'Uninstalling all existing plugins... ';
1317              $DB->query( 'DELETE FROM T_plugins WHERE 1=1' );
1318              echo "OK.<br />\n";
1319          }
1320  
1321          // NOTE: basic plugins get installed separatly for upgrade and install..
1322  
1323  
1324          set_upgrade_checkpoint( '9100' );
1325      }
1326  
1327  
1328      if( $old_db_version < 9190 ) // Note: changed from 9200, to include the block below, if DB is not yet on 1.8
1329      {    // 1.8 ALPHA (block #2)
1330          echo 'Altering Posts table... ';
1331          $DB->query( "ALTER TABLE {$tableprefix}posts
1332                       CHANGE post_comments post_comment_status ENUM('disabled', 'open', 'closed') NOT NULL DEFAULT 'open'" );
1333          echo "OK.<br />\n";
1334  
1335  
1336          set_upgrade_checkpoint( '9190' );
1337      }
1338  
1339  
1340      if( $old_db_version < 9192 )
1341      { // 1.8 ALPHA (block #3) - The payload that db_delta() handled before
1342  
1343          // This is a fix, which broke upgrade to 1.8 (from 1.6) in MySQL strict mode (inserted after 1.8 got released!):
1344          if( $DB->get_row( 'SHOW COLUMNS FROM T_hitlog LIKE "hit_referer_type"' ) )
1345          { // a niiiiiiiice extra check :p
1346              task_begin( 'Deleting all "spam" hitlog entries... ' );
1347              $DB->query( '
1348                      DELETE FROM T_hitlog
1349                       WHERE hit_referer_type = "spam"' );
1350              task_end();
1351          }
1352  
1353          task_begin( 'Upgrading users table... ' );
1354          $DB->query( 'ALTER TABLE T_users
1355                                          CHANGE COLUMN user_firstname user_firstname varchar(50) NULL,
1356                                          CHANGE COLUMN user_lastname user_lastname varchar(50) NULL,
1357                                          CHANGE COLUMN user_nickname user_nickname varchar(50) NULL,
1358                                          CHANGE COLUMN user_icq user_icq int(11) unsigned NULL,
1359                                          CHANGE COLUMN user_email user_email varchar(255) NOT NULL,
1360                                          CHANGE COLUMN user_url user_url varchar(255) NULL,
1361                                          CHANGE COLUMN user_ip user_ip varchar(15) NULL,
1362                                          CHANGE COLUMN user_domain user_domain varchar(200) NULL,
1363                                          CHANGE COLUMN user_browser user_browser varchar(200) NULL,
1364                                          CHANGE COLUMN user_aim user_aim varchar(50) NULL,
1365                                          CHANGE COLUMN user_msn user_msn varchar(100) NULL,
1366                                          CHANGE COLUMN user_yim user_yim varchar(50) NULL,
1367                                          ADD COLUMN user_allow_msgform TINYINT NOT NULL DEFAULT \'1\' AFTER user_idmode,
1368                                          ADD COLUMN user_validated TINYINT(1) NOT NULL DEFAULT 0 AFTER user_grp_ID' );
1369          task_end();
1370  
1371          task_begin( 'Creating blog settings...' );
1372          $DB->query( 'CREATE TABLE T_coll_settings (
1373                                                              cset_coll_ID INT(11) UNSIGNED NOT NULL,
1374                                                              cset_name    VARCHAR( 30 ) NOT NULL,
1375                                                              cset_value   VARCHAR( 255 ) NULL,
1376                                                              PRIMARY KEY ( cset_coll_ID, cset_name )
1377                                              )' );
1378          task_end();
1379          set_upgrade_checkpoint( '9192' );
1380      }
1381  
1382  
1383      if( $old_db_version < 9195 )
1384      {
1385          task_begin( 'Upgrading posts table... ' );
1386          $DB->query( 'ALTER TABLE '.$tableprefix.'posts
1387                                          CHANGE COLUMN post_content post_content         text NULL,
1388                                          CHANGE COLUMN post_url post_url                      VARCHAR(255) NULL DEFAULT NULL,
1389                                          CHANGE COLUMN post_renderers post_renderers     TEXT NOT NULL' );
1390          task_end();
1391  
1392          task_begin( 'Upgrading comments table... ' );
1393          $DB->query( 'ALTER TABLE T_comments
1394                                          CHANGE COLUMN comment_author_email comment_author_email varchar(255) NULL,
1395                                          CHANGE COLUMN comment_author_url comment_author_url varchar(255) NULL,
1396                                          ADD COLUMN comment_spam_karma TINYINT NULL AFTER comment_karma,
1397                                          ADD COLUMN comment_allow_msgform TINYINT NOT NULL DEFAULT 0 AFTER comment_spam_karma' );
1398          task_end();
1399  
1400          set_upgrade_checkpoint( '9195' );
1401      }
1402  
1403  
1404      if( $old_db_version < 9200 )
1405      {
1406          task_begin( 'Upgrading hitlog table... ' );
1407          $DB->query( 'ALTER TABLE T_hitlog
1408                                          CHANGE COLUMN hit_referer_type hit_referer_type   ENUM(\'search\',\'blacklist\',\'referer\',\'direct\') NOT NULL,
1409                                          ADD COLUMN hit_agnt_ID        INT UNSIGNED NULL AFTER hit_remote_addr' );
1410          task_end();
1411  
1412          task_begin( 'Upgrading post links table... ' );
1413          $DB->query( 'ALTER TABLE T_links
1414                                          ADD INDEX link_itm_ID( link_itm_ID ),
1415                                          ADD INDEX link_dest_itm_ID (link_dest_itm_ID)' );
1416          task_end();
1417  
1418          task_begin( 'Upgrading plugins table... ' );
1419          $DB->query( 'ALTER TABLE T_plugins
1420                                          CHANGE COLUMN plug_priority plug_priority        TINYINT NOT NULL default 50,
1421                                          ADD COLUMN plug_code            VARCHAR(32) NULL AFTER plug_classname,
1422                                          ADD COLUMN plug_apply_rendering ENUM( \'stealth\', \'always\', \'opt-out\', \'opt-in\', \'lazy\', \'never\' ) NOT NULL DEFAULT \'never\' AFTER plug_code,
1423                                          ADD COLUMN plug_version         VARCHAR(42) NOT NULL default \'0\' AFTER plug_apply_rendering,
1424                                          ADD COLUMN plug_status          ENUM( \'enabled\', \'disabled\', \'needs_config\', \'broken\' ) NOT NULL AFTER plug_version,
1425                                          ADD COLUMN plug_spam_weight     TINYINT UNSIGNED NOT NULL DEFAULT 1 AFTER plug_status,
1426                                          ADD UNIQUE plug_code( plug_code ),
1427                                          ADD INDEX plug_status( plug_status )' );
1428          task_end();
1429  
1430          task_begin( 'Creating plugin settings table... ' );
1431          $DB->query( 'CREATE TABLE T_pluginsettings (
1432                                                              pset_plug_ID INT(11) UNSIGNED NOT NULL,
1433                                                              pset_name VARCHAR( 30 ) NOT NULL,
1434                                                              pset_value TEXT NULL,
1435                                                              PRIMARY KEY ( pset_plug_ID, pset_name )
1436                                              )' );
1437          task_end();
1438  
1439          task_begin( 'Creating plugin user settings table... ' );
1440          $DB->query( 'CREATE TABLE T_pluginusersettings (
1441                                                              puset_plug_ID INT(11) UNSIGNED NOT NULL,
1442                                                              puset_user_ID INT(11) UNSIGNED NOT NULL,
1443                                                              puset_name VARCHAR( 30 ) NOT NULL,
1444                                                              puset_value TEXT NULL,
1445                                                              PRIMARY KEY ( puset_plug_ID, puset_user_ID, puset_name )
1446                                              )' );
1447          task_end();
1448  
1449          task_begin( 'Creating scheduled tasks table... ' );
1450          $DB->query( 'CREATE TABLE T_cron__task(
1451                                                   ctsk_ID              int(10) unsigned      not null AUTO_INCREMENT,
1452                                                   ctsk_start_datetime  datetime              not null,
1453                                                   ctsk_repeat_after    int(10) unsigned,
1454                                                   ctsk_name            varchar(50)           not null,
1455                                                   ctsk_controller      varchar(50)           not null,
1456                                                   ctsk_params          text,
1457                                                   primary key (ctsk_ID)
1458                                              )' );
1459          task_end();
1460  
1461          task_begin( 'Creating cron log table... ' );
1462          $DB->query( 'CREATE TABLE T_cron__log(
1463                                                               clog_ctsk_ID              int(10) unsigned   not null,
1464                                                               clog_realstart_datetime   datetime           not null,
1465                                                               clog_realstop_datetime    datetime,
1466                                                               clog_status               enum(\'started\',\'finished\',\'error\',\'timeout\') not null default \'started\',
1467                                                               clog_messages             text,
1468                                                               primary key (clog_ctsk_ID)
1469                                              )' );
1470          task_end();
1471  
1472          task_begin( 'Upgrading blogs table... ' );
1473          // blog_allowpingbacks is "DEFAULT 1" in the 0.9.0.11 dump.. - changed in 0.9.2?!
1474          $DB->query( 'ALTER TABLE T_blogs
1475                                          ALTER COLUMN blog_allowpingbacks SET DEFAULT 0,
1476                                      CHANGE COLUMN blog_media_subdir blog_media_subdir VARCHAR( 255 ) NULL,
1477                                          CHANGE COLUMN blog_media_fullpath blog_media_fullpath VARCHAR( 255 ) NULL,
1478                                          CHANGE COLUMN blog_media_url blog_media_url VARCHAR( 255 ) NULL' );
1479          task_end();
1480  
1481  
1482          set_upgrade_checkpoint( '9200' ); // at 1.8 "Summer Beta" release
1483      }
1484  
1485  
1486      // ____________________________ 1.9: ____________________________
1487  
1488      if( $old_db_version < 9290 )
1489      {
1490          echo 'Post-fix hit_referer_type == NULL... ';
1491          // If you've upgraded from 1.6 to 1.8 and it did not break because of strict mode, there are now NULL values for what "spam" was:
1492          $DB->query( '
1493                      DELETE FROM T_hitlog
1494                       WHERE hit_referer_type IS NULL' );
1495          echo "OK.<br />\n";
1496  
1497          echo 'Marking administrator accounts as validated... ';
1498          $DB->query( '
1499                  UPDATE T_users
1500                     SET user_validated = 1
1501                   WHERE user_grp_ID = 1' );
1502          echo "OK.<br />\n";
1503  
1504          echo 'Converting auto_prune_stats setting... ';
1505          $old_auto_prune_stats = $DB->get_var( '
1506                  SELECT set_value
1507                    FROM T_settings
1508                   WHERE set_name = "auto_prune_stats"' );
1509          if( ! is_null($old_auto_prune_stats) && $old_auto_prune_stats < 1 )
1510          { // This means it has been disabled before, so set auto_prune_stats_mode to "off"!
1511              $DB->query( '
1512                      REPLACE INTO T_settings ( set_name, set_value )
1513                       VALUES ( "auto_prune_stats_mode", "off" )' );
1514          }
1515          echo "OK.<br />\n";
1516  
1517          echo 'Converting time_difference from hours to seconds... ';
1518          $DB->query( 'UPDATE T_settings SET set_value = set_value*3600 WHERE set_name = "time_difference"' );
1519          echo "OK.<br />\n";
1520  
1521  
1522          echo 'Updating hitlog capabilities... ';
1523          $DB->query( '
1524                  ALTER TABLE '.$tableprefix.'useragents ADD INDEX agnt_type ( agnt_type )' );
1525          $DB->query( '
1526                  ALTER TABLE T_hitlog
1527                    CHANGE COLUMN hit_referer_type hit_referer_type ENUM(\'search\',\'blacklist\',\'referer\',\'direct\',\'self\',\'admin\') NOT NULL' );
1528          echo "OK.<br />\n";
1529  
1530          echo 'Updating plugin capabilities... ';
1531          $DB->query( '
1532                  ALTER TABLE T_plugins
1533                      MODIFY COLUMN plug_status ENUM( \'enabled\', \'disabled\', \'needs_config\', \'broken\' ) NOT NULL' );
1534          echo "OK.<br />\n";
1535  
1536          set_upgrade_checkpoint( '9290' );
1537      }
1538  
1539  
1540      if( $old_db_version < 9300 )
1541      {
1542          // This can be so long, it needs its own checkpoint protected block in case of failure
1543          echo 'Updating hitlog indexes... ';
1544          $DB->query( '
1545                  ALTER TABLE T_hitlog
1546                    ADD INDEX hit_agnt_ID        ( hit_agnt_ID ),
1547                    ADD INDEX hit_uri            ( hit_uri ),
1548                    ADD INDEX hit_referer_dom_ID ( hit_referer_dom_ID )
1549                  ' );
1550          echo "OK.<br />\n";
1551  
1552          set_upgrade_checkpoint( '9300' );
1553      }
1554  
1555  
1556      if( $old_db_version < 9310 )
1557      {
1558          echo 'Updating basedomains... ';
1559          $DB->query( '
1560                  UPDATE T_basedomains
1561                     SET dom_status = "unknown"' );        // someone has filled this up with junk blacklists before
1562          $DB->query( '
1563                  ALTER TABLE T_basedomains  ADD INDEX dom_type (dom_type)' );
1564          echo "OK.<br />\n";
1565  
1566          set_upgrade_checkpoint( '9310' );
1567      }
1568  
1569  
1570      if( $old_db_version < 9315 )
1571      {
1572          echo 'Altering locales table... ';
1573          $DB->query( "ALTER TABLE T_locales CHANGE COLUMN loc_datefmt loc_datefmt varchar(20) NOT NULL default 'y-m-d'" );
1574          $DB->query( "ALTER TABLE T_locales CHANGE COLUMN loc_timefmt loc_timefmt varchar(20) NOT NULL default 'H:i:s'" );
1575          echo "OK.<br />\n";
1576  
1577          echo 'Creating item prerendering cache table... ';
1578          $DB->query( "
1579                  CREATE TABLE {$tableprefix}item__prerendering(
1580                      itpr_itm_ID                   INT(11) UNSIGNED NOT NULL,
1581                      itpr_format                   ENUM('htmlbody', 'entityencoded', 'xml', 'text') NOT NULL,
1582                      itpr_renderers                TEXT NOT NULL,
1583                      itpr_content_prerendered      TEXT NULL,
1584                      itpr_datemodified             TIMESTAMP NOT NULL,
1585                      PRIMARY KEY (itpr_itm_ID, itpr_format)
1586                  )" );
1587          echo "OK.<br />\n";
1588  
1589          echo 'Altering plugins table... ';
1590          $DB->query( "ALTER TABLE T_plugins ADD COLUMN plug_name            VARCHAR(255) NULL default NULL AFTER plug_version" );
1591          $DB->query( "ALTER TABLE T_plugins ADD COLUMN plug_shortdesc       VARCHAR(255) NULL default NULL AFTER plug_name" );
1592          echo "OK.<br />\n";
1593  
1594          set_upgrade_checkpoint( '9315' );
1595      }
1596  
1597  
1598      if( $old_db_version < 9320 )
1599      { // Dropping hit_datetime because it's very slow on INSERT (dh)
1600          // This can be so long, it needs its own checkpoint protected block in case of failure
1601          if( db_index_exists( 'T_hitlog', 'hit_datetime' ) )
1602          { // only drop, if it still exists (may have been removed manually)
1603              echo 'Updating hitlog indexes... ';
1604              $DB->query( '
1605                      ALTER TABLE T_hitlog
1606                          DROP INDEX hit_datetime
1607                      ' );
1608              echo "OK.<br />\n";
1609          }
1610  
1611          set_upgrade_checkpoint( '9320' );
1612      }
1613  
1614  
1615      if( $old_db_version < 9326 )
1616      {
1617          echo 'Removing obsolete settings... ';
1618          $DB->query( 'DELETE FROM T_settings WHERE set_name = "upload_allowedext"' );
1619          echo "OK.<br />\n";
1620  
1621          echo 'Updating blogs... ';
1622          db_drop_col( 'T_blogs', 'blog_allowpingbacks' );
1623  
1624          // Remove and transform obsolete fields blog_pingb2evonet, blog_pingtechnorati, blog_pingweblogs, blog_pingblodotgs
1625          if( db_cols_exist( 'T_blogs', array('blog_pingb2evonet', 'blog_pingtechnorati', 'blog_pingweblogs', 'blog_pingblodotgs') ) )
1626          {
1627              foreach( $DB->get_results( '
1628                      SELECT blog_ID, blog_pingb2evonet, blog_pingtechnorati, blog_pingweblogs, blog_pingblodotgs
1629                          FROM T_blogs' ) as $row )
1630              {
1631                  $ping_plugins = $DB->get_var( 'SELECT cset_value FROM T_coll_settings WHERE cset_coll_ID = '.$row->blog_ID.' AND cset_name = "ping_plugins"' );
1632                  $ping_plugins = explode(',', $ping_plugins);
1633                  if( $row->blog_pingb2evonet )
1634                  {
1635                      $ping_plugins[] = 'ping_b2evonet';
1636                  }
1637                  if( $row->blog_pingtechnorati || $row->blog_pingweblogs || $row->blog_pingblodotgs )
1638                  { // if either one of the previous pingers was enabled, add ping-o-matic:
1639                      $ping_plugins[] = 'ping_pingomatic';
1640                  }
1641  
1642                  // Insert transformed/generated ping plugins collection setting:
1643                  $ping_plugins = array_unique($ping_plugins);
1644                  $DB->query( 'REPLACE INTO T_coll_settings
1645                          ( cset_coll_ID, cset_name, cset_value )
1646                          VALUES ( '.$row->blog_ID.', "ping_plugins", "'.implode( ',', $ping_plugins ).'" )' );
1647              }
1648              $DB->query( 'ALTER TABLE T_blogs
1649                      DROP COLUMN blog_pingb2evonet,
1650                      DROP COLUMN blog_pingtechnorati,
1651                      DROP COLUMN blog_pingweblogs,
1652                      DROP COLUMN blog_pingblodotgs' );
1653          }
1654          echo "OK.<br />\n";
1655  
1656  
1657          set_upgrade_checkpoint( '9326' );
1658      }
1659  
1660  
1661      if( $old_db_version < 9328 )
1662      {
1663          echo 'Updating posts... ';
1664          db_add_col( "{$tableprefix}posts", 'post_notifications_status',  'ENUM("noreq","todo","started","finished") NOT NULL DEFAULT "noreq" AFTER post_flags' );
1665          db_add_col( "{$tableprefix}posts", 'post_notifications_ctsk_ID', 'INT(10) unsigned NULL DEFAULT NULL AFTER post_notifications_status' );
1666          echo "OK.<br />\n";
1667          set_upgrade_checkpoint( '9328' );
1668      }
1669  
1670  
1671      if( $old_db_version < 9330 )
1672      {
1673          if( db_col_exists( "{$tableprefix}posts", 'post_flags') )
1674          {
1675              echo 'Updating post notifications... ';
1676              $DB->query( "
1677                  UPDATE {$tableprefix}posts
1678                       SET post_notifications_status = 'finished'
1679                   WHERE post_flags LIKE '%pingsdone%'" );
1680              db_drop_col( "{$tableprefix}posts", 'post_flags' );
1681              echo "OK.<br />\n";
1682          }
1683          set_upgrade_checkpoint( '9330' );
1684      }
1685  
1686  
1687      if( $old_db_version < 9340 )
1688      {
1689          echo 'Removing duplicate post link indexes... ';
1690          if( db_index_exists( 'T_links', 'link_item_ID' ) )
1691          { // only drop, if it still exists (may have been removed manually)
1692              $DB->query( '
1693                      ALTER TABLE T_links
1694                          DROP INDEX link_item_ID
1695                      ' );
1696          }
1697          if( db_index_exists( 'T_links', 'link_dest_item_ID' ) )
1698          { // only drop, if it still exists (may have been removed manually)
1699              $DB->query( '
1700                      ALTER TABLE T_links
1701                          DROP INDEX link_dest_item_ID
1702                      ' );
1703          }
1704          echo "OK.<br />\n";
1705  
1706          set_upgrade_checkpoint( '9340' );
1707      }
1708  
1709      // ____________________________ 1.10: ____________________________
1710  
1711      if( $old_db_version < 9345 )
1712      {
1713          echo 'Updating post table... ';
1714          $DB->query( "ALTER TABLE {$tableprefix}posts CHANGE COLUMN post_content post_content MEDIUMTEXT NULL" );
1715          echo "OK.<br />\n";
1716          set_upgrade_checkpoint( '9345' );
1717      }
1718  
1719      if( $old_db_version < 9346 )
1720      {
1721          echo 'Updating prerendering table... ';
1722          $DB->query( "ALTER TABLE {$tableprefix}item__prerendering CHANGE COLUMN itpr_content_prerendered itpr_content_prerendered MEDIUMTEXT NULL" );
1723          echo "OK.<br />\n";
1724          set_upgrade_checkpoint( '9346' );
1725      }
1726  
1727      if( $old_db_version < 9348 )
1728      {
1729          echo 'Updating sessions table... ';
1730          $DB->query( 'ALTER TABLE T_sessions CHANGE COLUMN sess_data sess_data MEDIUMBLOB DEFAULT NULL' );
1731          echo "OK.<br />\n";
1732          set_upgrade_checkpoint( '9348' );
1733      }
1734  
1735      if( $old_db_version < 9350 )
1736      {
1737          echo 'Updating hitlog table... ';
1738          $DB->query( 'ALTER TABLE T_hitlog CHANGE COLUMN hit_referer_type hit_referer_type   ENUM(\'search\',\'blacklist\',\'spam\',\'referer\',\'direct\',\'self\',\'admin\') NOT NULL' );
1739          echo "OK.<br />\n";
1740  
1741          set_upgrade_checkpoint( '9350' );
1742      }
1743  
1744  
1745      // TODO: "If a user has permission to edit a blog, he should be able to put files in the media folder for that blog." - see http://forums.b2evolution.net/viewtopic.php?p=36417#36417
1746      /*
1747      // blueyed>> I've came up with the following, but it's too generic IMHO
1748      if( $old_db_version < 9300 )
1749      {
1750          echo 'Setting automatic media perms on blogs (members can upload)... ';
1751          $users = $DB->query( '
1752                  UPDATE T_users
1753                     SET bloguser_perm_media_upload = 1
1754                   WHERE bloguser_ismember = 1' );
1755          echo "OK.<br />\n";
1756      }
1757      */
1758  
1759  
1760      // ____________________________ 2.0: ____________________________
1761  
1762      if( $old_db_version < 9406 )
1763      {
1764          echo 'Updating chapter url names... ';
1765          $DB->query( '
1766              ALTER TABLE T_categories
1767                  ADD COLUMN cat_urlname VARCHAR(255) NOT NULL' );
1768  
1769          // Create cat_urlname from cat_name:
1770          // TODO: Also use it for cafelog upgrade.
1771          load_funcs('locales/_charset.funcs.php');
1772          foreach( $DB->get_results('SELECT cat_ID, cat_name FROM T_categories') as $cat )
1773          {
1774              $cat_name = trim($cat->cat_name);
1775              if( strlen($cat_name) )
1776              {
1777                  // TODO: dh> pass locale (useful for transliteration). From main blog?
1778                  $cat_urlname = urltitle_validate('', $cat_name, $cat->cat_ID, false, 'cat_urlname', 'cat_ID', 'T_categories');
1779              }
1780              else
1781              {
1782                  $cat_urlname = 'c'.$cat->cat_ID;
1783              }
1784  
1785              $DB->query( '
1786                  UPDATE T_categories
1787                       SET cat_urlname = '.$DB->quote($cat_urlname).'
1788                   WHERE cat_ID = '.$cat->cat_ID );
1789          }
1790  
1791          $DB->query( '
1792              ALTER TABLE T_categories
1793                  ADD UNIQUE cat_urlname ( cat_urlname )' );
1794          echo "OK.<br />\n";
1795  
1796          echo 'Updating Settings... ';
1797          $DB->query( '
1798        UPDATE T_settings
1799           SET set_value = "disabled"
1800         WHERE set_name = "links_extrapath"
1801           AND set_value = 0' );
1802          $DB->query( '
1803        UPDATE T_settings
1804           SET set_value = "ymd"
1805         WHERE set_name = "links_extrapath"
1806           AND set_value <> 0' );
1807          echo "OK.<br />\n";
1808  
1809          set_upgrade_checkpoint( '9406' );
1810      }
1811  
1812  
1813      if( $old_db_version < 9407 )
1814      {
1815          echo 'Moving general settings to blog settings... ';
1816          $DB->query( 'REPLACE INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
1817                       SELECT blog_ID, set_name, set_value
1818                                       FROM T_blogs, T_settings
1819                                      WHERE set_name = "posts_per_page"
1820                                         OR set_name = "what_to_show"
1821                                         OR set_name = "archive_mode"' );
1822          $DB->query( 'DELETE FROM T_settings
1823                                      WHERE set_name = "posts_per_page"
1824                                         OR set_name = "what_to_show"
1825                                         OR set_name = "archive_mode"' );
1826          echo "OK.<br />\n";
1827  
1828          echo 'Upgrading blogs table... ';
1829          $query = "ALTER TABLE T_blogs
1830                              DROP COLUMN blog_force_skin";
1831          $DB->query( $query );
1832          echo "OK.<br />\n";
1833  
1834          echo 'Upgrading groups table... ';
1835          $query = "ALTER TABLE T_groups
1836                              CHANGE COLUMN grp_perm_files grp_perm_files enum('none','view','add','edit','all') NOT NULL default 'none'";
1837          $DB->query( $query );
1838          echo "OK.<br />\n";
1839  
1840          echo 'Upgrading files table... ';
1841          $query = "ALTER TABLE T_files
1842                              CHANGE COLUMN file_root_type file_root_type enum('absolute','user','group','collection','skins') not null default 'absolute'";
1843          $DB->query( $query );
1844          echo "OK.<br />\n";
1845  
1846          echo 'Updating file types... ';
1847          // Only change this if it's close enough to a default install (non customized)
1848          $DB->query( "UPDATE T_filetypes
1849                                          SET ftyp_viewtype = 'text'
1850                                      WHERE ftyp_ID = 12
1851                                          AND ftyp_extensions = 'php php3 php4 php5 php6'
1852                                          AND ftyp_mimetype ='application/x-httpd-php'
1853                                          AND ftyp_icon = 'php.gif'" );
1854          echo "OK.<br />\n";
1855  
1856          echo 'Remove obsolete user settings... ';
1857          $DB->query( 'DELETE FROM '.$tableprefix.'usersettings
1858                                      WHERE uset_name = "plugins_disp_avail"' );
1859          echo "OK.<br />\n";
1860  
1861          set_upgrade_checkpoint( '9407' );
1862      }
1863  
1864  
1865      if( $old_db_version < 9408 )
1866      {
1867          echo 'Creating skins table... ';
1868          $DB->query( 'CREATE TABLE T_skins__skin (
1869                skin_ID      int(10) unsigned      NOT NULL auto_increment,
1870                skin_name    varchar(32)           NOT NULL,
1871                skin_type    enum(\'normal\',\'feed\') NOT NULL default \'normal\',
1872                skin_folder  varchar(32)           NOT NULL,
1873                PRIMARY KEY skin_ID (skin_ID),
1874                UNIQUE skin_folder( skin_folder ),
1875                KEY skin_name( skin_name )
1876              )' );
1877          echo "OK.<br />\n";
1878  
1879          echo 'Creating skin containers table... ';
1880          $DB->query( 'CREATE TABLE T_skins__container (
1881                sco_skin_ID   int(10) unsigned      NOT NULL,
1882                sco_name      varchar(40)           NOT NULL,
1883                PRIMARY KEY (sco_skin_ID, sco_name)
1884              )' );
1885          echo "OK.<br />\n";
1886  
1887          echo 'Creating widgets table... ';
1888          $DB->query( 'CREATE TABLE T_widget (
1889                           wi_ID                    INT(10) UNSIGNED auto_increment,
1890                          wi_coll_ID    INT(11) UNSIGNED NOT NULL,
1891                          wi_sco_name   VARCHAR( 40 ) NOT NULL,
1892                          wi_order            INT(10) UNSIGNED NOT NULL,
1893                          wi_type       ENUM( \'core\', \'plugin\' ) NOT NULL DEFAULT \'core\',
1894                          wi_code       VARCHAR(32) NOT NULL,
1895                          wi_params     TEXT NULL,
1896                          PRIMARY KEY ( wi_ID ),
1897                          UNIQUE wi_order( wi_coll_ID, wi_sco_name, wi_order )
1898            )' );
1899          echo "OK.<br />\n";
1900  
1901          install_basic_skins( false );
1902  
1903          echo 'Updating blogs table... ';
1904          $DB->query( 'ALTER TABLE T_blogs
1905                                   ALTER COLUMN blog_allowtrackbacks SET DEFAULT 0,
1906                                      DROP COLUMN blog_default_skin,
1907                                       ADD COLUMN blog_owner_user_ID   int(11) unsigned NOT NULL default 1 AFTER blog_name,
1908                                       ADD COLUMN blog_skin_ID INT(10) UNSIGNED NOT NULL DEFAULT 1 AFTER blog_allowusercss' );
1909          echo "OK.<br />\n";
1910  
1911  
1912          install_basic_widgets( $old_db_version );
1913  
1914          set_upgrade_checkpoint( '9408' );
1915      }
1916  
1917  
1918      if( $old_db_version < 9409 )
1919      {
1920          // Upgrade the blog access types:
1921          echo 'Updating blogs access types... ';
1922          $DB->query( 'UPDATE T_blogs
1923                                          SET blog_access_type = "absolute"
1924                                      WHERE blog_siteurl LIKE "http://%"
1925                                         OR blog_siteurl LIKE "https://%"' );
1926  
1927          $DB->query( 'UPDATE T_blogs
1928                                          SET blog_access_type = "relative",
1929                                                  blog_siteurl = CONCAT( blog_siteurl, blog_stub )
1930                                      WHERE blog_access_type = "stub"' );
1931  
1932          db_drop_col( 'T_blogs', 'blog_stub' );
1933  
1934          echo "OK.<br />\n";
1935  
1936  
1937           echo 'Updating columns... ';
1938          $DB->query( "ALTER TABLE T_groups CHANGE COLUMN grp_perm_stats grp_perm_stats enum('none','user','view','edit') NOT NULL default 'none'" );
1939  
1940          $DB->query( "ALTER TABLE T_coll_user_perms CHANGE COLUMN bloguser_perm_poststatuses bloguser_perm_poststatuses set('published','deprecated','protected','private','draft','redirected') NOT NULL default ''" );
1941  
1942          $DB->query( "ALTER TABLE T_coll_group_perms CHANGE COLUMN bloggroup_perm_poststatuses bloggroup_perm_poststatuses set('published','deprecated','protected','private','draft','redirected') NOT NULL default ''" );
1943  
1944          $DB->query( "ALTER TABLE {$tableprefix}posts CHANGE COLUMN post_status post_status enum('published','deprecated','protected','private','draft','redirected') NOT NULL default 'published'" );
1945          echo "OK.<br />\n";
1946  
1947          set_upgrade_checkpoint( '9409' );
1948      }
1949  
1950  
1951      if( $old_db_version < 9410 )
1952      {
1953           echo 'Updating columns... ';
1954          $DB->query( "ALTER TABLE T_comments CHANGE COLUMN comment_status comment_status ENUM('published','deprecated','protected','private','draft','redirected') DEFAULT 'published' NOT NULL" );
1955  
1956          $DB->query( "ALTER TABLE T_sessions CHANGE COLUMN sess_data sess_data MEDIUMBLOB DEFAULT NULL" );
1957  
1958          $DB->query( "ALTER TABLE T_hitlog CHANGE COLUMN hit_referer_type hit_referer_type ENUM('search','blacklist','spam','referer','direct','self','admin') NOT NULL" );
1959  
1960          echo "OK.<br />\n";
1961  
1962          set_upgrade_checkpoint( '9410' );
1963      }
1964  
1965  
1966      if( $old_db_version < 9411 )
1967      {
1968          echo 'Adding default Post Types... ';
1969          $DB->query( "
1970              REPLACE INTO {$tableprefix}posttypes ( ptyp_ID, ptyp_name )
1971              VALUES ( 1000, 'Page' ),
1972                           ( 2000, 'Reserved' ),
1973                           ( 3000, 'Reserved' ),
1974                           ( 4000, 'Reserved' ),
1975                           ( 5000, 'Reserved' ) " );
1976          echo "OK.<br />\n";
1977          set_upgrade_checkpoint( '9411' );
1978      }
1979  
1980  
1981      if( $old_db_version < 9412 )
1982      {
1983          echo 'Adding field for post excerpts... ';
1984          $DB->query( "ALTER TABLE {$tableprefix}posts ADD COLUMN post_excerpt  text NULL AFTER post_content" );
1985          echo "OK.<br />\n";
1986          set_upgrade_checkpoint( '9412' );
1987      }
1988  
1989      if( $old_db_version < 9414 )
1990      {
1991          echo "Renaming tables...";
1992          $DB->query( "RENAME TABLE {$tableprefix}item__prerendering TO T_items__prerendering" );
1993          $DB->query( "RENAME TABLE {$tableprefix}poststatuses TO T_items__status" );
1994          $DB->query( "RENAME TABLE {$tableprefix}posttypes TO T_items__type" );
1995          $DB->query( "RENAME TABLE {$tableprefix}posts TO T_items__item" );
1996          echo "OK.<br />\n";
1997  
1998          echo "Creating Tag tables...";
1999          $DB->query( "CREATE TABLE T_items__tag (
2000                tag_ID   int(11) unsigned not null AUTO_INCREMENT,
2001                tag_name varchar(50) not null,
2002                primary key (tag_ID),
2003                UNIQUE tag_name( tag_name )
2004              )" );
2005  
2006          $DB->query( "CREATE TABLE T_items__itemtag (
2007                itag_itm_ID int(11) unsigned NOT NULL,
2008                itag_tag_ID int(11) unsigned NOT NULL,
2009                PRIMARY KEY (itag_itm_ID, itag_tag_ID),
2010                UNIQUE tagitem ( itag_tag_ID, itag_itm_ID )
2011              )" );
2012          echo "OK.<br />\n";
2013  
2014          set_upgrade_checkpoint( '9414' );
2015      }
2016  
2017  
2018      if( $old_db_version < 9416 )
2019      {
2020          echo "Updating blogs table...";
2021          $DB->query( "ALTER TABLE T_blogs
2022                                      ADD COLUMN blog_advanced_perms  TINYINT(1) NOT NULL default 0 AFTER blog_owner_user_ID,
2023                                      DROP COLUMN blog_staticfilename" );
2024          $DB->query( "UPDATE T_blogs
2025                                        SET blog_advanced_perms = 1" );
2026          echo "OK.<br />\n";
2027  
2028          echo "Additionnal blog permissions...";
2029          $DB->query( "ALTER TABLE T_coll_user_perms
2030                                      ADD COLUMN bloguser_perm_admin tinyint NOT NULL default 0 AFTER bloguser_perm_properties,
2031                                      ADD COLUMN bloguser_perm_edit  ENUM('no','own','lt','le','all','redirected') NOT NULL default 'no' AFTER bloguser_perm_poststatuses" );
2032  
2033          $DB->query( "ALTER TABLE T_coll_group_perms
2034                                      ADD COLUMN bloggroup_perm_admin tinyint NOT NULL default 0 AFTER bloggroup_perm_properties,
2035                                      ADD COLUMN bloggroup_perm_edit  ENUM('no','own','lt','le','all','redirected') NOT NULL default 'no' AFTER bloggroup_perm_poststatuses" );
2036  
2037          // Preserve full admin perms:
2038          $DB->query( "UPDATE T_coll_user_perms
2039                                          SET bloguser_perm_admin = 1
2040                                      WHERE bloguser_perm_properties <> 0" );
2041          $DB->query( "UPDATE T_coll_group_perms
2042                                          SET bloggroup_perm_admin = 1
2043                                      WHERE bloggroup_perm_properties <> 0" );
2044  
2045          // Preserve full edit perms:
2046          $DB->query( "UPDATE T_coll_user_perms
2047                                          SET bloguser_perm_edit = 'all'" );
2048          $DB->query( "UPDATE T_coll_group_perms
2049                                          SET bloggroup_perm_edit = 'all'" );
2050  
2051          echo "OK.<br />\n";
2052  
2053          set_upgrade_checkpoint( '9416' );
2054      }
2055  
2056  
2057      if( $old_db_version < 9500 )
2058      {
2059          task_begin( 'Normalizing columns...' );
2060          $DB->query( 'ALTER TABLE T_blogs
2061                                          ALTER COLUMN blog_shortname SET DEFAULT \'\',
2062                                          ALTER COLUMN blog_tagline SET DEFAULT \'\',
2063                                          CHANGE COLUMN blog_description blog_description     varchar(250) NULL default \'\',
2064                                          ALTER COLUMN blog_siteurl SET DEFAULT \'\'' );
2065          task_end();
2066  
2067          task_begin( 'Normalizing dates...' );
2068          $DB->query( 'UPDATE T_users
2069                                          SET dateYMDhour = \'2000-01-01 00:00:00\'
2070                                      WHERE dateYMDhour = \'0000-00-00 00:00:00\'' );
2071          $DB->query( 'ALTER TABLE T_users
2072                                      MODIFY COLUMN dateYMDhour DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\'' );
2073          $DB->query( 'UPDATE T_comments
2074                                          SET comment_date = \'2000-01-01 00:00:00\'
2075                                      WHERE comment_date = \'0000-00-00 00:00:00\'' );
2076          $DB->query( 'ALTER TABLE T_comments
2077                                      MODIFY COLUMN comment_date DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\'' );
2078          task_end();
2079  
2080          task_begin( 'Normalizing cron jobs...' );
2081          $DB->query( 'UPDATE T_cron__task
2082                                          SET ctsk_controller = REPLACE(ctsk_controller, "cron/_", "cron/jobs/_" )
2083                                      WHERE ctsk_controller LIKE "cron/_%"' );
2084          task_end();
2085  
2086          task_begin( 'Extending comments table...' );
2087          $DB->query( 'ALTER TABLE T_comments
2088                                      ADD COLUMN comment_rating     TINYINT(1) NULL DEFAULT NULL AFTER comment_content,
2089                                      ADD COLUMN comment_featured   TINYINT(1) NOT NULL DEFAULT 0 AFTER comment_rating,
2090                                      ADD COLUMN comment_nofollow   TINYINT(1) NOT NULL DEFAULT 1 AFTER comment_featured;');
2091          task_end();
2092  
2093          set_upgrade_checkpoint( '9500' );
2094      }
2095  
2096  
2097      if( $old_db_version < 9600 )
2098      {    // 2.2.0
2099          task_begin( 'Creating global cache table...' );
2100          $DB->query( 'CREATE TABLE T_global__cache (
2101                                    cach_name VARCHAR( 30 ) NOT NULL ,
2102                                    cach_cache MEDIUMBLOB NULL ,
2103                                    PRIMARY KEY ( cach_name )
2104                                  )' );
2105          task_end();
2106  
2107          task_begin( 'Altering posts table...' );
2108          $DB->query( 'ALTER TABLE T_items__item
2109                                          MODIFY COLUMN post_datestart DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\',
2110                                          MODIFY COLUMN post_datemodified DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\',
2111                                          ADD COLUMN post_order    float NULL AFTER post_priority,
2112                                          ADD COLUMN post_featured tinyint(1) NOT NULL DEFAULT 0 AFTER post_order,
2113                                          ADD INDEX post_order( post_order )' );
2114          task_end();
2115  
2116          set_upgrade_checkpoint( '9600' );
2117      }
2118  
2119  
2120      if( $old_db_version < 9700 )
2121      {    // 2.3.2
2122        echo 'Creating PodCast Post Type... ';
2123          $DB->query( "
2124              REPLACE INTO T_items__type ( ptyp_ID, ptyp_name )
2125              VALUES ( 2000, 'Podcast' )" );
2126          echo "OK.<br />\n";
2127  
2128          // 2.4.0
2129        echo 'Adding additional group permissions... ';
2130          $DB->query( "
2131            ALTER TABLE T_groups
2132                      ADD COLUMN grp_perm_bypass_antispam         TINYINT(1)  NOT NULL DEFAULT 0        AFTER grp_perm_blogs,
2133                      ADD COLUMN grp_perm_xhtmlvalidation         VARCHAR(10) NOT NULL default 'always' AFTER grp_perm_bypass_antispam,
2134                      ADD COLUMN grp_perm_xhtmlvalidation_xmlrpc  VARCHAR(10) NOT NULL default 'always' AFTER grp_perm_xhtmlvalidation,
2135                      ADD COLUMN grp_perm_xhtml_css_tweaks        TINYINT(1)  NOT NULL DEFAULT 0        AFTER grp_perm_xhtmlvalidation_xmlrpc,
2136                ADD COLUMN grp_perm_xhtml_iframes           TINYINT(1)  NOT NULL DEFAULT 0        AFTER grp_perm_xhtml_css_tweaks,
2137                ADD COLUMN grp_perm_xhtml_javascript        TINYINT(1)  NOT NULL DEFAULT 0        AFTER grp_perm_xhtml_iframes,
2138                      ADD COLUMN grp_perm_xhtml_objects           TINYINT(1)  NOT NULL DEFAULT 0        AFTER grp_perm_xhtml_javascript " );
2139          echo "OK.<br />\n";
2140  
2141          set_upgrade_checkpoint( '9700' );
2142      }
2143  
2144  
2145      if( $old_db_version < 9800 )
2146      {    // 2.5.0
2147          echo 'Upgrading blogs table... ';
2148          db_drop_col( 'T_blogs', 'blog_commentsexpire' );
2149          echo "OK.<br />\n";
2150  
2151          echo 'Upgrading items table... ';
2152          $DB->query( "ALTER TABLE T_items__item
2153              CHANGE COLUMN post_urltitle post_urltitle VARCHAR(210) NULL DEFAULT NULL,
2154              CHANGE COLUMN post_order    post_order DOUBLE NULL,
2155              ADD COLUMN post_titletag  VARCHAR(255) NULL DEFAULT NULL AFTER post_urltitle,
2156              ADD COLUMN post_double1   DOUBLE NULL COMMENT 'Custom double value 1' AFTER post_priority,
2157              ADD COLUMN post_double2   DOUBLE NULL COMMENT 'Custom double value 2' AFTER post_double1,
2158              ADD COLUMN post_double3   DOUBLE NULL COMMENT 'Custom double value 3' AFTER post_double2,
2159              ADD COLUMN post_double4   DOUBLE NULL COMMENT 'Custom double value 4' AFTER post_double3,
2160              ADD COLUMN post_double5   DOUBLE NULL COMMENT 'Custom double value 5' AFTER post_double4,
2161              ADD COLUMN post_varchar1  VARCHAR(255) NULL COMMENT 'Custom varchar value 1' AFTER post_double5,
2162              ADD COLUMN post_varchar2  VARCHAR(255) NULL COMMENT 'Custom varchar value 2' AFTER post_varchar1,
2163              ADD COLUMN post_varchar3  VARCHAR(255) NULL COMMENT 'Custom varchar value 3' AFTER post_varchar2" );
2164          echo "OK.<br />\n";
2165  
2166          echo 'Creating keyphrase table... ';
2167          $query = "CREATE TABLE T_track__keyphrase (
2168              keyp_ID      INT UNSIGNED NOT NULL AUTO_INCREMENT,
2169              keyp_phrase  VARCHAR( 255 ) NOT NULL,
2170              PRIMARY KEY        ( keyp_ID ),
2171              UNIQUE keyp_phrase ( keyp_phrase )
2172            )";
2173          $DB->query( $query );
2174          echo "OK.<br />\n";
2175  
2176          echo 'Upgrading hitlog table... ';
2177          evo_flush();
2178          $query = "ALTER TABLE T_hitlog
2179               CHANGE COLUMN hit_ID hit_ID              INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
2180               CHANGE COLUMN hit_datetime hit_datetime  DATETIME NOT NULL DEFAULT '2000-01-01 00:00:00',
2181               ADD COLUMN hit_keyphrase_keyp_ID         INT UNSIGNED DEFAULT NULL AFTER hit_referer_dom_ID,
2182               ADD INDEX hit_remote_addr ( hit_remote_addr ),
2183               ADD INDEX hit_sess_ID        ( hit_sess_ID )";
2184          $DB->query( $query );
2185          echo "OK.<br />\n";
2186  
2187          echo 'Upgrading sessions table... ';
2188          $DB->query( "ALTER TABLE T_sessions
2189              ALTER COLUMN sess_lastseen SET DEFAULT '2000-01-01 00:00:00',
2190              ADD COLUMN sess_hitcount  INT(10) UNSIGNED NOT NULL DEFAULT 1 AFTER sess_key,
2191              ADD KEY sess_user_ID (sess_user_ID)" );
2192          echo "OK.<br />\n";
2193  
2194          echo 'Creating goal tracking table... ';
2195      $DB->query( "CREATE TABLE T_track__goal(
2196                        goal_ID int(10) unsigned NOT NULL auto_increment,
2197                        goal_name varchar(50) default NULL,
2198                        goal_key varchar(32) default NULL,
2199                        goal_redir_url varchar(255) default NULL,
2200                        goal_default_value double default NULL,
2201                        PRIMARY KEY (goal_ID),
2202                        UNIQUE KEY goal_key (goal_key)
2203            )" );
2204  
2205      $DB->query( "CREATE TABLE T_track__goalhit (
2206                        ghit_ID int(10) unsigned NOT NULL auto_increment,
2207                        ghit_goal_ID    int(10) unsigned NOT NULL,
2208                        ghit_hit_ID     int(10) unsigned NOT NULL,
2209                        ghit_params     TEXT default NULL,
2210                        PRIMARY KEY  (ghit_ID),
2211                        KEY ghit_goal_ID (ghit_goal_ID),
2212                        KEY ghit_hit_ID (ghit_hit_ID)
2213           )" );
2214          echo "OK.<br />\n";
2215  
2216          set_upgrade_checkpoint( '9800' );
2217      }
2218  
2219  
2220      if( $old_db_version < 9900 )
2221      {    // 3.0 part 1
2222          task_begin( 'Updating keyphrases in hitlog table... ' );
2223          load_class( 'sessions/model/_hit.class.php', 'Hit' );
2224          // New Hit object creation was added later, to fix upgrades from very old versions.
2225          // We create a new temp Hit object to be able to call the Hit::extract_params_from_referer() function which was static when this upgrade block was created.
2226          $tempHit = new Hit();
2227          $sql = 'SELECT SQL_NO_CACHE hit_ID, hit_referer
2228                      FROM T_hitlog
2229                      WHERE hit_referer_type = "search"
2230                     AND hit_keyphrase_keyp_ID IS NULL'; // this line just in case we crashed in the middle, so we restart where we stopped
2231          $rows = $DB->get_results( $sql, OBJECT, 'get all search hits' );
2232          foreach( $rows as $row )
2233          {
2234              $params = $tempHit->extract_params_from_referer( $row->hit_referer );
2235              if( empty( $params['keyphrase'] ) )
2236              {
2237                  continue;
2238              }
2239  
2240              $DB->begin();
2241  
2242              $sql = 'SELECT keyp_ID
2243                        FROM T_track__keyphrase
2244                       WHERE keyp_phrase = '.$DB->quote($params['keyphrase']);
2245              $keyp_ID = $DB->get_var( $sql, 0, 0, 'Get keyphrase ID' );
2246  
2247              if( empty( $keyp_ID ) )
2248              {
2249                  $sql = 'INSERT INTO T_track__keyphrase( keyp_phrase )
2250                          VALUES ('.$DB->quote($params['keyphrase']).')';
2251                  $DB->query( $sql, 'Add new keyphrase' );
2252                  $keyp_ID = $DB->insert_id;
2253              }
2254  
2255              $DB->query( 'UPDATE T_hitlog
2256                              SET hit_keyphrase_keyp_ID = '.$keyp_ID.'
2257                            WHERE hit_ID = '.$row->hit_ID, 'Update hit' );
2258  
2259              $DB->commit();
2260              echo ". \n";
2261          }
2262          task_end();
2263  
2264          task_begin( 'Upgrading widgets table... ' );
2265          $DB->query( "ALTER TABLE T_widget
2266              CHANGE COLUMN wi_order wi_order INT(10) NOT NULL" );
2267          task_end();
2268  
2269          task_begin( 'Upgrading Files table... ' );
2270          $DB->query( "ALTER TABLE T_files
2271                                  CHANGE COLUMN file_root_type file_root_type enum('absolute','user','collection','shared','skins') not null default 'absolute'" );
2272          task_end();
2273  
2274          set_upgrade_checkpoint( '9900' );
2275      }
2276  
2277      if( $old_db_version < 9910 )
2278      {    // 3.0 part 2
2279  
2280          task_begin( 'Upgrading Blogs table... ' );
2281          $DB->query( "ALTER TABLE T_blogs CHANGE COLUMN blog_name blog_name varchar(255) NOT NULL default ''" );
2282          task_end();
2283  
2284          task_begin( 'Adding new Post Types...' );
2285          $DB->query( "
2286              REPLACE INTO T_items__type( ptyp_ID, ptyp_name )
2287              VALUES ( 1500, 'Intro-Main' ),
2288                           ( 1520, 'Intro-Cat' ),
2289                           ( 1530, 'Intro-Tag' ),
2290                           ( 1570, 'Intro-Sub' ),
2291                           ( 1600, 'Intro-All' ) " );
2292          task_end();
2293  
2294          task_begin( 'Updating User table' );
2295          $DB->query( "ALTER TABLE T_users
2296                                      ADD COLUMN user_avatar_file_ID int(10) unsigned default NULL AFTER user_validated" );
2297          task_end();
2298  
2299          task_begin( 'Creating table for User field definitions' );
2300          $DB->query( "CREATE TABLE T_users__fielddefs (
2301                  ufdf_ID int(10) unsigned NOT NULL,
2302                  ufdf_type char(8) NOT NULL,
2303                  ufdf_name varchar(255) collate latin1_general_ci NOT NULL,
2304                  PRIMARY KEY  (ufdf_ID)
2305              )" );
2306          task_end();
2307  
2308          task_begin( 'Creating default field definitions...' );
2309          $DB->query( "
2310          INSERT INTO T_users__fielddefs (ufdf_ID, ufdf_type, ufdf_name)
2311               VALUES ( 10000, 'email',    'MSN/Live IM'),
2312                              ( 10100, 'word',     'Yahoo IM'),
2313                              ( 10200, 'word',     'AOL AIM'),
2314                              ( 10300, 'number',   'ICQ ID'),
2315                              ( 40000, 'phone',    'Skype'),
2316                              ( 50000, 'phone',    'Main phone'),
2317                              ( 50100, 'phone',    'Cell phone'),
2318                              ( 50200, 'phone',    'Office phone'),
2319                              ( 50300, 'phone',    'Home phone'),
2320                              ( 60000, 'phone',    'Office FAX'),
2321                              ( 60100, 'phone',    'Home FAX'),
2322                              (100000, 'url',      'Website'),
2323                              (100100, 'url',      'Blog'),
2324                              (110000, 'url',      'Linkedin'),
2325                              (120000, 'url',      'Twitter'),
2326                              (130100, 'url',      'Facebook'),
2327                              (130200, 'url',      'Myspace'),
2328                              (140000, 'url',      'Flickr'),
2329                              (150000, 'url',      'YouTube'),
2330                              (160000, 'url',      'Digg'),
2331                              (160100, 'url',      'StumbleUpon'),
2332                              (200000, 'text',     'Role'),
2333                              (200100, 'text',     'Company/Org.'),
2334                              (200200, 'text',     'Division'),
2335                              (211000, 'text',     'VAT ID'),
2336                              (300000, 'text',     'Main address'),
2337                              (300300, 'text',     'Home address');" );
2338          task_end();
2339  
2340          task_begin( 'Creating table for User fields...' );
2341          $DB->query( "CREATE TABLE {$tableprefix}users_fields (
2342                  uf_ID      int(10) unsigned NOT NULL auto_increment,
2343                uf_user_ID int(10) unsigned NOT NULL,
2344                uf_ufdf_ID int(10) unsigned NOT NULL,
2345                uf_varchar varchar(255) NOT NULL,
2346                PRIMARY KEY (uf_ID)
2347              )" );
2348          task_end();
2349  
2350          set_upgrade_checkpoint( '9910' );
2351      }
2352  
2353      if( $old_db_version < 9920 )
2354      {    // 3.1
2355          task_begin( 'Upgrading Posts table... ' );
2356          // This is for old posts that may have a post type of NULL which should never happen. ptyp 1 is for regular posts
2357          $DB->query( "UPDATE T_items__item
2358                                          SET post_ptyp_ID = 1
2359                                      WHERE post_ptyp_ID IS NULL" );
2360          $DB->query( "ALTER TABLE T_items__item
2361                              CHANGE COLUMN post_ptyp_ID post_ptyp_ID int(10) unsigned NOT NULL DEFAULT 1" );
2362          task_end();
2363  
2364          task_begin( 'Upgrading Categories table... ' );
2365          $DB->query( "ALTER TABLE T_categories
2366              CHANGE COLUMN cat_name cat_name varchar(255) NOT NULL,
2367              CHANGE COLUMN cat_description cat_description varchar(255) NULL DEFAULT NULL" );
2368          db_add_col( 'T_categories', 'cat_order', 'int(11) NULL DEFAULT NULL AFTER cat_description' );
2369          db_add_index( 'T_categories', 'cat_order', 'cat_order' );
2370  
2371          $DB->query( "UPDATE T_categories
2372                      SET cat_order = cat_ID" );
2373          task_end();
2374  
2375          task_begin( 'Upgrading widgets table... ' );
2376          db_add_col( 'T_widget', 'wi_enabled', 'tinyint(1) NOT NULL DEFAULT 1 AFTER wi_order' );
2377          task_end();
2378      }
2379      if( $old_db_version < 9930 )
2380      {    // 3.1 continued
2381          task_begin( 'Updating item types...' );
2382          $DB->query( "
2383              REPLACE INTO T_items__type ( ptyp_ID, ptyp_name )
2384              VALUES ( 3000, 'Sidebar link' )" );
2385          echo "OK.<br />\n";
2386          task_end();
2387  
2388          task_begin( 'Updating items table...' );
2389          $DB->query( "ALTER TABLE T_items__item ENGINE=innodb" );    // fp> hum... this originally was a test :)
2390          task_end();
2391  
2392          task_begin( 'Creating versions table...' );
2393          $DB->query( "CREATE TABLE T_items__version (
2394                  iver_itm_ID        INT UNSIGNED NOT NULL ,
2395                  iver_edit_user_ID  INT UNSIGNED NOT NULL ,
2396                  iver_edit_datetime DATETIME NOT NULL ,
2397                  iver_status        ENUM('published','deprecated','protected','private','draft','redirected') NULL ,
2398                  iver_title         TEXT NULL ,
2399                  iver_content       MEDIUMTEXT NULL ,
2400                  INDEX iver_itm_ID ( iver_itm_ID )
2401                  ) ENGINE = innodb" );
2402          task_end();
2403  
2404          task_begin( 'Updating group permissions...' );
2405          $DB->query( "UPDATE T_groups
2406                                          SET grp_perm_xhtml_css_tweaks = 1
2407                                      WHERE grp_ID <= 3" );
2408          task_end();
2409  
2410          set_upgrade_checkpoint( '9930' );
2411      }
2412  
2413      if( $old_db_version < 9940 )
2414      {    // 3.2
2415          task_begin( 'Updating hitlog table...' );
2416          $DB->query( "ALTER TABLE T_hitlog ADD COLUMN hit_serprank INT UNSIGNED DEFAULT NULL AFTER hit_keyphrase_keyp_ID" );
2417          task_end();
2418  
2419          task_begin( 'Updating versions table...' );
2420          $DB->query( "ALTER TABLE T_items__version
2421                                  CHANGE COLUMN iver_edit_user_ID iver_edit_user_ID  INT UNSIGNED NULL" );
2422          task_end();
2423      }
2424  
2425      if( $old_db_version < 9950 )
2426      {    // 3.3
2427          task_begin( 'Altering Blogs table... ' );
2428          $DB->query( "ALTER TABLE T_blogs CHANGE COLUMN blog_shortname blog_shortname varchar(255) default ''" );
2429          task_end();
2430  
2431          task_begin( 'Altering default dates... ' );
2432          $DB->query( "ALTER TABLE T_links
2433        ALTER COLUMN link_datecreated SET DEFAULT '2000-01-01 00:00:00',
2434        ALTER COLUMN link_datemodified SET DEFAULT '2000-01-01 00:00:00'" );
2435          $DB->query( "ALTER TABLE T_cron__task
2436        ALTER COLUMN ctsk_start_datetime SET DEFAULT '2000-01-01 00:00:00'" );
2437          $DB->query( "ALTER TABLE T_cron__log
2438        ALTER COLUMN clog_realstart_datetime SET DEFAULT '2000-01-01 00:00:00'" );
2439          task_end();
2440  
2441           task_begin( 'Altering Items table... ' );
2442          $DB->query( "ALTER TABLE T_items__item
2443              ADD COLUMN post_metadesc VARCHAR(255) NULL DEFAULT NULL AFTER post_titletag,
2444              ADD COLUMN post_metakeywords VARCHAR(255) NULL DEFAULT NULL AFTER post_metadesc,
2445              ADD COLUMN post_editor_code VARCHAR(32) NULL COMMENT 'Plugin code of the editor used to edit this post' AFTER post_varchar3" );
2446          task_end();
2447  
2448          task_begin( 'Forcing AutoP posts to html editor...' );
2449          $DB->query( 'UPDATE T_items__item
2450                                              SET post_editor_code = "html"
2451                                          WHERE post_renderers = "default"
2452                                               OR post_renderers LIKE "%b2WPAutP%"' );
2453          task_end();
2454  
2455          set_upgrade_checkpoint( '9950' );
2456      }
2457  
2458      if( $old_db_version < 9960 )
2459      {    // 3.3
2460  
2461          echo "Renaming tables...";
2462          $DB->save_error_state();
2463          $DB->halt_on_error = false;
2464          $DB->show_errors = false;
2465          $DB->query( "ALTER TABLE {$tableprefix}users_fields RENAME TO T_users__fields" );
2466          $DB->restore_error_state();
2467          echo "OK.<br />\n";
2468  
2469          // fp> The following is more tricky to do with CHARACTER SET. During upgrade, we don't know what the admin actually wants.
2470          task_begin( 'Making sure all tables use desired storage ENGINE as specified in the b2evo schema...' );
2471          foreach( $schema_queries as $table_name=>$table_def )
2472          {
2473              if( $DB->query( 'SHOW TABLES LIKE \''.$table_name.'\'' )
2474                  && preg_match( '/\sENGINE\s*=\s*([a-z]+)/is', $table_def[1], $matches ) )
2475              {    // If the table exists and has an ENGINE definition:
2476                  echo $table_name.':'.$matches[1].'<br />';
2477                  $DB->query( "ALTER TABLE $table_name ENGINE = ".$matches[1] );
2478              }
2479          }
2480          task_end();
2481  
2482          set_upgrade_checkpoint( '9960' );
2483      }
2484  
2485      if( $old_db_version < 9970 )
2486      {    // 4.0 part 1
2487  
2488          // For create_default_currencies() and create_default_countries():
2489          require_once dirname(__FILE__).'/_functions_create.php';
2490  
2491          task_begin( 'Creating table for default currencies... ' );
2492          $DB->query( 'CREATE TABLE '.$tableprefix.'currency (
2493                  curr_ID int(10) unsigned NOT NULL auto_increment,
2494                  curr_code char(3) NOT NULL,
2495                  curr_shortcut varchar(30) NOT NULL,
2496                  curr_name varchar(40) NOT NULL,
2497                  PRIMARY KEY curr_ID (curr_ID),
2498                  UNIQUE curr_code (curr_code)
2499              ) ENGINE = innodb' );
2500          task_end();
2501  
2502          create_default_currencies( $tableprefix.'currency' );
2503  
2504          task_begin( 'Creating table for default countries... ' );
2505          $DB->query( 'CREATE TABLE '.$tableprefix.'country (
2506                  ctry_ID int(10) unsigned NOT NULL auto_increment,
2507                  ctry_code char(2) NOT NULL,
2508                  ctry_name varchar(40) NOT NULL,
2509                  ctry_curr_ID int(10) unsigned,
2510                  PRIMARY KEY ctry_ID (ctry_ID),
2511                  UNIQUE ctry_code (ctry_code)
2512              ) ENGINE = innodb' );
2513          task_end();
2514  
2515          create_default_countries( $tableprefix.'country', false );
2516  
2517          task_begin( 'Upgrading user permissions table... ' );
2518          $DB->query( "ALTER TABLE T_coll_user_perms
2519              ADD COLUMN bloguser_perm_page        tinyint NOT NULL default 0 AFTER bloguser_perm_media_change,
2520              ADD COLUMN bloguser_perm_intro        tinyint NOT NULL default 0 AFTER bloguser_perm_page,
2521              ADD COLUMN bloguser_perm_podcast    tinyint NOT NULL default 0 AFTER bloguser_perm_intro,
2522              ADD COLUMN bloguser_perm_sidebar    tinyint NOT NULL default 0 AFTER bloguser_perm_podcast" );
2523          task_end();
2524  
2525          task_begin( 'Upgrading group permissions table... ' );
2526          $DB->query( "ALTER TABLE T_coll_group_perms
2527              ADD COLUMN bloggroup_perm_page        tinyint NOT NULL default 0 AFTER bloggroup_perm_media_change,
2528              ADD COLUMN bloggroup_perm_intro        tinyint NOT NULL default 0 AFTER bloggroup_perm_page,
2529              ADD COLUMN bloggroup_perm_podcast    tinyint NOT NULL default 0 AFTER bloggroup_perm_intro,
2530              ADD COLUMN bloggroup_perm_sidebar    tinyint NOT NULL default 0 AFTER bloggroup_perm_podcast" );
2531          task_end();
2532  
2533          task_begin( 'Upgrading users table... ' );
2534          $DB->query( "ALTER TABLE T_users
2535              ADD COLUMN user_ctry_ID int(10) unsigned NULL AFTER user_avatar_file_ID" );
2536          task_end();
2537  
2538          // Creating tables for messaging module
2539  
2540          task_begin( 'Creating table for message threads... ' );
2541          $DB->query( "CREATE TABLE T_messaging__thread (
2542              thrd_ID int(10) unsigned NOT NULL auto_increment,
2543              thrd_title varchar(255) NOT NULL,
2544              thrd_datemodified datetime NOT NULL,
2545              PRIMARY KEY thrd_ID (thrd_ID)
2546          ) ENGINE = innodb" );
2547          task_end();
2548  
2549          task_begin( 'Creating table for messagee... ' );
2550          $DB->query( "CREATE TABLE T_messaging__message (
2551              msg_ID int(10) unsigned NOT NULL auto_increment,
2552              msg_author_user_ID int(10) unsigned NOT NULL,
2553              msg_datetime datetime NOT NULL,
2554              msg_thread_ID int(10) unsigned NOT NULL,
2555              msg_text text NULL,
2556              PRIMARY KEY msg_ID (msg_ID)
2557          ) ENGINE = innodb" );
2558          task_end();
2559  
2560          task_begin( 'Creating table for message thread statuses... ' );
2561          $DB->query( "CREATE TABLE T_messaging__threadstatus (
2562              tsta_thread_ID int(10) unsigned NOT NULL,
2563              tsta_user_ID int(10) unsigned NOT NULL,
2564              tsta_first_unread_msg_ID int(10) unsigned NULL,
2565              INDEX(tsta_user_ID)
2566          ) ENGINE = innodb" );
2567          task_end();
2568  
2569          task_begin( 'Creating table for messaging contacts... ' );
2570          $DB->query( "CREATE TABLE T_messaging__contact (
2571              mct_from_user_ID int(10) unsigned NOT NULL,
2572              mct_to_user_ID int(10) unsigned NOT NULL,
2573              mct_blocked tinyint(1) default 0,
2574              mct_last_contact_datetime datetime NOT NULL,
2575              PRIMARY KEY mct_PK (mct_from_user_ID, mct_to_user_ID)
2576          ) ENGINE = innodb" );
2577          task_end();
2578  
2579          task_begin( 'Upgrading skins table... ' );
2580          $DB->query( "ALTER TABLE T_skins__skin
2581                          MODIFY skin_type enum('normal','feed','sitemap') NOT NULL default 'normal'" );
2582          task_end();
2583  
2584          task_begin( 'Setting skin type of sitemap skin to "sitemap"... ' );
2585          $DB->query( "UPDATE T_skins__skin
2586                          SET skin_type = 'sitemap'
2587                          WHERE skin_folder = '_sitemap'" );
2588          task_end();
2589  
2590          // Creating table for pluggable permissions
2591  
2592          // This table gets created during upgrade to v0.8.9 at checkpoint 8050
2593          task_begin( 'Creating table for Group Settings... ' );
2594          $DB->query( "CREATE TABLE IF NOT EXISTS T_groups__groupsettings (
2595              gset_grp_ID INT(11) UNSIGNED NOT NULL,
2596              gset_name VARCHAR(30) NOT NULL,
2597              gset_value VARCHAR(255) NULL,
2598              PRIMARY KEY (gset_grp_ID, gset_name)
2599          ) ENGINE = innodb" );
2600          task_end();
2601  
2602          // Rename T_usersettings table to T_users__usersettings
2603          task_begin( 'Rename T_usersettings table to T_users__usersettings... ' );
2604          $DB->query( 'ALTER TABLE '.$tableprefix.'usersettings RENAME TO T_users__usersettings' );
2605          task_end();
2606  
2607          set_upgrade_checkpoint( '9970' );
2608      }
2609  
2610  
2611      if( $old_db_version < 9980 )
2612      {    // 4.0 part 2
2613  
2614          task_begin( 'Upgrading posts... ' );
2615          $DB->query( '
2616              UPDATE T_items__item
2617                 SET post_datestart = FROM_UNIXTIME( FLOOR(UNIX_TIMESTAMP(post_datestart)/60)*60 )
2618               WHERE post_datestart > NOW()' );
2619          db_add_col( 'T_items__item', 'post_excerpt_autogenerated', 'TINYINT NULL DEFAULT NULL AFTER post_excerpt' );
2620          db_add_col( 'T_items__item', 'post_dateset', 'tinyint(1) NOT NULL DEFAULT 1 AFTER post_assigned_user_ID' );
2621          task_end();
2622  
2623          task_begin( 'Upgrading countries... ' );
2624          db_add_col( $tableprefix.'country', 'ctry_enabled', 'tinyint(1) NOT NULL DEFAULT 1 AFTER ctry_curr_ID' );
2625          task_end();
2626  
2627  
2628          task_begin( 'Upgrading links... ' );
2629  
2630          // Add link_position. Temporary allow NULL, set compatibility default, then do not allow NULL.
2631          // TODO: dh> actually, using "teaser" for the first link and "aftermore" for the rest would make more sense (and "aftermore" should get displayed with "no-more" posts anyway).
2632          //           Opinions? Could be heavy to transform this though..
2633          // fp> no, don't change past posts unexpectedly.
2634          db_add_col( 'T_links', 'link_position', "varchar(10) NULL AFTER link_title" );
2635          $DB->query( "UPDATE T_links SET link_position = 'teaser' WHERE link_position IS NULL" );
2636          db_add_col( 'T_links', 'link_position', "varchar(10) NOT NULL AFTER link_title" ); // change to NOT NULL
2637  
2638          // Add link_order. Temporary allow NULL, use order from ID, then do not allow NULL and add UNIQUE index.
2639          db_add_col( 'T_links', 'link_order', 'int(11) unsigned NULL AFTER link_position' );
2640          $DB->query( "UPDATE T_links SET link_order = link_ID WHERE link_order IS NULL" );
2641          db_add_col( 'T_links', 'link_order', 'int(11) unsigned NOT NULL AFTER link_position' ); // change to NOT NULL
2642          db_add_index( 'T_links', 'link_itm_ID_order', 'link_itm_ID, link_order', 'UNIQUE' );
2643  
2644          task_end();
2645  
2646          task_begin( 'Upgrading sessions... ' );
2647          $DB->query( "ALTER TABLE T_sessions CHANGE COLUMN sess_ipaddress sess_ipaddress VARCHAR(39) NOT NULL DEFAULT ''" );
2648          task_end();
2649  
2650          set_upgrade_checkpoint( '9980' );
2651      }
2652  
2653      if( $old_db_version < 9990 )
2654      {    // 4.0 part 3
2655  
2656          task_begin( 'Upgrading hitlog... ' );
2657  
2658          db_add_col( 'T_hitlog', 'hit_agent_type', "ENUM('rss','robot','browser','unknown') DEFAULT 'unknown' NOT NULL AFTER hit_remote_addr" );
2659  
2660          if( db_col_exists('T_hitlog', 'hit_agnt_ID') )
2661          {
2662              $DB->query( 'UPDATE T_hitlog, '.$tableprefix.'useragents
2663                              SET hit_agent_type = agnt_type
2664                            WHERE hit_agnt_ID = agnt_ID
2665                              AND agnt_type <> "unknown"' ); // We already have the unknown as default
2666              db_drop_col( 'T_hitlog', 'hit_agnt_ID' );
2667          }
2668          $DB->query( 'DROP TABLE IF EXISTS '.$tableprefix.'useragents' );
2669  
2670          task_end();
2671  
2672          set_upgrade_checkpoint( '9990' );
2673      }
2674  
2675      if( $old_db_version < 10000 )
2676      {    // 4.0 part 4
2677          // Integrate comment_secret
2678          task_begin( 'Extending Comment table... ' );
2679          db_add_col( 'T_comments', 'comment_secret', 'varchar(32) NULL default NULL' );
2680          task_end();
2681  
2682          // Create T_slug table and, Insert all slugs from T_items
2683          task_begin( 'Create Slugs table... ' );
2684          $DB->query( 'CREATE TABLE IF NOT EXISTS T_slug (
2685                          slug_ID int(10) unsigned NOT NULL auto_increment,
2686                          slug_title varchar(255) NOT NULL COLLATE ascii_bin,
2687                          slug_type char(6) NOT NULL DEFAULT "item",
2688                          slug_itm_ID int(11) unsigned,
2689                          PRIMARY KEY slug_ID (slug_ID),
2690                          UNIQUE    slug_title (slug_title)
2691                      ) ENGINE = innodb' );
2692          task_end();
2693  
2694          task_begin( 'Making sure all posts have a slug...' );
2695          // Get posts with empty urltitle:
2696          $sql = 'SELECT post_ID, post_title
2697                        FROM T_items__item
2698                       WHERE post_urltitle IS NULL OR post_urltitle = ""';
2699          $rows = $DB->get_results( $sql, OBJECT, 'Get posts with empty urltitle' );
2700          // Create URL titles when non existent:
2701          foreach( $rows as $row )
2702          {
2703              // TODO: dh> pass locale (useful for transliteration).
2704              $DB->query( 'UPDATE T_items__item
2705                                SET post_urltitle = "'.urltitle_validate( '', $row->post_title, 0 ).'"
2706                          WHERE post_ID = '.$row->post_ID, 'Set posts urltitle' );
2707          }
2708          task_end();
2709  
2710          task_begin( 'Populating Slugs table... ' );
2711          $DB->query( 'REPLACE INTO T_slug( slug_title, slug_type, slug_itm_ID)
2712                        SELECT post_urltitle, "item", post_ID
2713                                    FROM T_items__item' );
2714          task_end();
2715  
2716          task_begin( 'Add canonical and tiny slug IDs to post table...' );
2717          // modify post_urltitle column -> Not allow NULL value
2718          db_add_col( 'T_items__item', 'post_urltitle', 'VARCHAR(210) NOT NULL' );
2719          db_add_col( 'T_items__item', 'post_canonical_slug_ID', 'int(10) unsigned NULL default NULL after post_urltitle' );
2720          db_add_col( 'T_items__item', 'post_tiny_slug_ID', 'int(10) unsigned NULL default NULL after post_canonical_slug_ID' );
2721          task_end();
2722  
2723          task_begin( 'Upgrading posts...' );
2724          $DB->query( 'UPDATE T_items__item, T_slug
2725                            SET post_canonical_slug_ID = slug_ID
2726                          WHERE CONVERT( post_urltitle USING ASCII ) COLLATE ascii_bin = slug_title' );
2727          task_end();
2728  
2729          task_begin( 'Adding "help" slug...' );
2730          if( db_key_exists( 'T_slug', 'slug_title', '"help"' ) )
2731          {
2732              echo '<strong>Warning: "help" slug already exists!</strong><br /> ';
2733          }
2734          else
2735          {
2736              $DB->query( 'INSERT INTO T_slug( slug_title, slug_type )
2737                           VALUES( "help", "help" )', 'Add "help" slug' );
2738              task_end();
2739          }
2740  
2741          // fp> Next time we should use pluggable permissions instead.
2742          task_begin( 'Updgrading groups: Giving Administrators Group edit perms on slugs...' );
2743          db_add_col( 'T_groups', 'grp_perm_slugs', "enum('none','view','edit') NOT NULL default 'none'" );
2744          $DB->query( 'UPDATE T_groups
2745                       SET grp_perm_slugs = "edit"
2746                       WHERE grp_ID = 1' );
2747          task_end();
2748  
2749          task_begin( 'Upgrading settings table... ');
2750          $DB->query( 'UPDATE T_settings
2751                          SET set_value = 1
2752                        WHERE set_name = "fm_enable_roots_user"
2753                              AND set_value = 0' );
2754          task_end();
2755  
2756          // New perms for comment moderation depending on status:
2757          task_begin( 'Upgrading Blog-User permissions...' );
2758          db_add_col( 'T_coll_user_perms', 'bloguser_perm_draft_cmts', 'tinyint NOT NULL default 0 AFTER bloguser_perm_comments' );
2759          db_add_col( 'T_coll_user_perms', 'bloguser_perm_publ_cmts', 'tinyint NOT NULL default 0 AFTER bloguser_perm_comments' );
2760          db_add_col( 'T_coll_user_perms', 'bloguser_perm_depr_cmts', 'tinyint NOT NULL default 0 AFTER bloguser_perm_comments' );
2761  
2762          if( db_col_exists( 'T_coll_user_perms', 'bloguser_perm_comments' ) )
2763          { // if user had perm_comments he now gets all 3 new perms also:
2764              $DB->query( 'UPDATE T_coll_user_perms
2765                          SET bloguser_perm_draft_cmts = bloguser_perm_comments,
2766                              bloguser_perm_publ_cmts = bloguser_perm_comments,
2767                              bloguser_perm_depr_cmts = bloguser_perm_comments');
2768              db_drop_col( 'T_coll_user_perms', 'bloguser_perm_comments' );
2769          }
2770          task_end();
2771  
2772          task_begin( 'Upgrading Blog-Group permissions...' );
2773          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_draft_cmts', 'tinyint NOT NULL default 0 AFTER bloggroup_perm_comments' );
2774          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_publ_cmts', 'tinyint NOT NULL default 0 AFTER bloggroup_perm_comments' );
2775          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_depr_cmts', 'tinyint NOT NULL default 0 AFTER bloggroup_perm_comments' );
2776  
2777          if( db_col_exists( 'T_coll_group_perms', 'bloggroup_perm_comments' ) )
2778          { // if group had perm_comments he now gets all 3 new perms also:
2779              $DB->query( 'UPDATE T_coll_group_perms
2780                          SET bloggroup_perm_draft_cmts = bloggroup_perm_comments,
2781                              bloggroup_perm_publ_cmts = bloggroup_perm_comments,
2782                              bloggroup_perm_depr_cmts = bloggroup_perm_comments');
2783              db_drop_col( 'T_coll_group_perms', 'bloggroup_perm_comments' );
2784          }
2785          task_end();
2786  
2787          task_begin( 'Upgrading messaging permissions...' );
2788          $DB->query( 'ALTER TABLE T_users ALTER COLUMN user_allow_msgform SET DEFAULT "2"' );
2789          $DB->query( 'UPDATE T_users
2790                      SET user_allow_msgform = 3
2791                      WHERE user_allow_msgform = 1');
2792          task_end();
2793  
2794          task_begin( 'Upgrading currency table...' );
2795          $DB->query( 'ALTER TABLE '.$tableprefix.'currency ADD COLUMN curr_enabled tinyint(1) NOT NULL DEFAULT 1 AFTER curr_name' );
2796          task_end();
2797  
2798          task_begin( 'Upgrading default blog access type for new blogs...' );
2799          $DB->query( 'ALTER TABLE T_blogs ALTER COLUMN blog_access_type SET DEFAULT "extrapath"' );
2800          task_end();
2801  
2802          task_begin( 'Upgrading tags table...' );
2803          $DB->query( 'ALTER TABLE T_items__tag CHANGE COLUMN tag_name tag_name varbinary(50) not null' );
2804          task_end();
2805  
2806          // fp> I don't understand why we need to carry this out "again" but I observed the installer barking on
2807          // this setting missing when upgrading from older 2.x versions. I figured it would be no big deal to do it twice...
2808          task_begin( 'Makin sure usersettings table is InnoDB...' );
2809          $DB->query( 'ALTER TABLE T_users__usersettings ENGINE=innodb' );
2810          task_end();
2811  
2812          set_upgrade_checkpoint( '10000' );
2813      }
2814  
2815      if( $old_db_version < 10100 )
2816      {    // 4.1
2817          task_begin( 'Convert group permissions to pluggable permissions...' );
2818          // asimo>This delete query needs just in case if this version of b2evo was used, before upgrade process call
2819          $DB->query( 'DELETE FROM T_groups__groupsettings
2820                          WHERE gset_name = "perm_files" OR gset_name = "perm_options" OR gset_name = "perm_templates"' );
2821          // Get current permission values from groups table
2822          $sql = 'SELECT grp_ID, grp_perm_spamblacklist, grp_perm_slugs, grp_perm_files, grp_perm_options, grp_perm_templates
2823                        FROM T_groups';
2824          $rows = $DB->get_results( $sql, OBJECT, 'Get groups converted permissions' );
2825          // Insert values into groupsettings table
2826          foreach( $rows as $row )
2827          {    // "IGNORE" is needed if we already created T_groups__groupsettings during upgrade to v0.8.9 at checkpoint 8050
2828              $DB->query( 'INSERT IGNORE INTO T_groups__groupsettings( gset_grp_ID, gset_name, gset_value )
2829                              VALUES( '.$row->grp_ID.', "perm_spamblacklist", "'.$row->grp_perm_spamblacklist.'" ),
2830                                  ( '.$row->grp_ID.', "perm_slugs", "'.$row->grp_perm_slugs.'" ),
2831                                  ( '.$row->grp_ID.', "perm_files", "'.$row->grp_perm_files.'" ),
2832                                  ( '.$row->grp_ID.', "perm_options", "'.$row->grp_perm_options.'" ),
2833                                  ( '.$row->grp_ID.', "perm_templates", "'.$row->grp_perm_templates.'" )' );
2834          }
2835  
2836          // Drop all converted permissin colums from groups table
2837          db_drop_col( 'T_groups', 'grp_perm_spamblacklist' );
2838          db_drop_col( 'T_groups', 'grp_perm_slugs' );
2839          db_drop_col( 'T_groups', 'grp_perm_files' );
2840          db_drop_col( 'T_groups', 'grp_perm_options' );
2841          db_drop_col( 'T_groups', 'grp_perm_templates' );
2842          task_end();
2843  
2844          task_begin( 'Upgrading users table, adding user gender...' );
2845          db_add_col( 'T_users', 'user_gender', 'char(1) NULL DEFAULT NULL AFTER user_showonline' );
2846          task_end();
2847  
2848          task_begin( 'Upgrading edit timpestamp blog-user permission...' );
2849          db_add_col( 'T_coll_user_perms', 'bloguser_perm_edit_ts', 'tinyint NOT NULL default 0 AFTER bloguser_perm_delpost' );
2850          $DB->query( 'UPDATE T_coll_user_perms, T_users
2851                              SET bloguser_perm_edit_ts = 1
2852                              WHERE bloguser_user_ID = user_ID  AND user_level > 4' );
2853          task_end();
2854  
2855          task_begin( 'Upgrading edit timpestamp blog-group permission...' );
2856          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_edit_ts', 'tinyint NOT NULL default 0 AFTER bloggroup_perm_delpost' );
2857          $DB->query( 'UPDATE T_coll_group_perms
2858                              SET bloggroup_perm_edit_ts = 1
2859                              WHERE bloggroup_group_ID = 1' );
2860          task_end();
2861  
2862          task_begin( 'Upgrading comments table, add trash status...' );
2863          $DB->query( "ALTER TABLE T_comments MODIFY COLUMN comment_status ENUM('published','deprecated','draft', 'trash') DEFAULT 'published' NOT NULL");
2864          task_end();
2865  
2866          task_begin( 'Upgrading groups admin access permission...' );
2867          $sql = 'SELECT grp_ID, grp_perm_admin
2868                      FROM T_groups';
2869          $rows = $DB->get_results( $sql, OBJECT, 'Get groups admin perms' );
2870          foreach( $rows as $row )
2871          {
2872              switch( $row->grp_perm_admin )
2873              {
2874                  case 'visible':
2875                      $value = 'normal';
2876                      break;
2877                  case 'hidden':
2878                      $value = 'restricted';
2879                      break;
2880                  default:
2881                      $value = 'none';
2882              }
2883              // "IGNORE" is needed if we already created T_groups__groupsettings during upgrade to v0.8.9 at checkpoint 8050
2884              $DB->query( 'INSERT IGNORE INTO T_groups__groupsettings( gset_grp_ID, gset_name, gset_value )
2885                              VALUES( '.$row->grp_ID.', "perm_admin", "'.$value.'" )' );
2886          }
2887          db_drop_col( 'T_groups', 'grp_perm_admin' );
2888          task_end();
2889  
2890          task_begin( 'Upgrading users table, add users source...' );
2891          db_add_col( 'T_users', 'user_source', 'varchar(30) NULL' );
2892          task_end();
2893  
2894          task_begin( 'Upgrading blogs table: more granularity for comment allowing...' );
2895          $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
2896                          SELECT blog_ID, "allow_comments", "never"
2897                              FROM T_blogs
2898                              WHERE blog_allowcomments = "never"' );
2899          db_drop_col( 'T_blogs', 'blog_allowcomments' );
2900          task_end();
2901  
2902          task_begin( 'Upgrading blogs table: allow_rating fields...' );
2903          $DB->query( 'UPDATE T_coll_settings
2904                          SET cset_value = "any"
2905                          WHERE cset_value = "always" AND cset_name = "allow_rating"' );
2906          task_end();
2907  
2908          task_begin( 'Upgrading links table, add link_cmt_ID...' );
2909          $DB->query( 'ALTER TABLE T_links
2910                          MODIFY COLUMN link_itm_ID int(11) unsigned NULL,
2911                          MODIFY COLUMN link_creator_user_ID int(11) unsigned NULL,
2912                          MODIFY COLUMN link_lastedit_user_ID int(11) unsigned NULL,
2913                          ADD COLUMN link_cmt_ID int(11) unsigned NULL COMMENT "Used for linking files to comments (comment attachments)" AFTER link_itm_ID,
2914                          ADD INDEX link_cmt_ID ( link_cmt_ID )' );
2915          task_end();
2916  
2917          task_begin( 'Upgrading filetypes table...' );
2918          // get allowed filetype ids
2919          $sql = 'SELECT ftyp_ID
2920                      FROM T_filetypes
2921                      WHERE ftyp_allowed != 0';
2922          $allowed_ids = implode( ',', $DB->get_col( $sql, 0, 'Get allowed filetypes' ) );
2923  
2924          // update table column  -- this column is about who can edit the filetype: any user, registered users or only admins.
2925          $DB->query( 'ALTER TABLE T_filetypes
2926                          MODIFY COLUMN ftyp_allowed enum("any","registered","admin") NOT NULL default "admin"' );
2927  
2928          // update ftyp_allowed column content
2929          $DB->query( 'UPDATE T_filetypes
2930                          SET ftyp_allowed = "registered"
2931                          WHERE ftyp_ID IN ('.$allowed_ids.')' );
2932          $DB->query( 'UPDATE T_filetypes
2933                          SET ftyp_allowed = "admin"
2934                          WHERE ftyp_ID NOT IN ('.$allowed_ids.')' );
2935          $DB->query( 'UPDATE T_filetypes
2936                          SET ftyp_allowed = "any"
2937                          WHERE ftyp_extensions = "gif" OR ftyp_extensions = "png" OR ftyp_extensions LIKE "%jpg%"' );
2938  
2939          // Add m4v file type if not exists
2940          if( !db_key_exists( 'T_filetypes', 'ftyp_extensions', '"m4v"' ) )
2941          {
2942              $DB->query( 'INSERT INTO T_filetypes (ftyp_extensions, ftyp_name, ftyp_mimetype, ftyp_icon, ftyp_viewtype, ftyp_allowed)
2943                               VALUES ("m4v", "MPEG video file", "video/x-m4v", "", "browser", "registered")', 'Add "m4v" file type' );
2944          }
2945          task_end();
2946  
2947          // The AdSense plugin needs to store quite long strings of data...
2948          task_begin( 'Upgrading collection settings table, change cset_value type...' );
2949          $DB->query( 'ALTER TABLE T_coll_settings
2950                                   MODIFY COLUMN cset_name VARCHAR(50) NOT NULL,
2951                                   MODIFY COLUMN cset_value VARCHAR(10000) NULL' );
2952          task_end();
2953  
2954          set_upgrade_checkpoint( '10100' );
2955      }
2956  
2957      if( $old_db_version < 10200 )
2958      {    // 4.1b
2959          task_begin( 'Creating table for a specific blog post subscriptions...' );
2960          $DB->query( "CREATE TABLE T_items__subscriptions (
2961                          isub_item_ID  int(11) unsigned NOT NULL,
2962                          isub_user_ID  int(11) unsigned NOT NULL,
2963                          isub_comments tinyint(1) NOT NULL default 0 COMMENT 'The user wants to receive notifications for new comments on this post',
2964                          PRIMARY KEY (isub_item_ID, isub_user_ID )
2965                      ) ENGINE = innodb" );
2966          task_end();
2967  
2968          task_begin( 'Upgrading comments table, add subscription fields...' );
2969          db_add_col( 'T_comments', 'comment_notif_status', 'ENUM("noreq","todo","started","finished") NOT NULL DEFAULT "noreq" COMMENT "Have notifications been sent for this comment? How far are we in the process?" AFTER comment_secret' );
2970          db_add_col( 'T_comments', 'comment_notif_ctsk_ID', 'INT(10) unsigned NULL DEFAULT NULL COMMENT "When notifications for this comment are sent through a scheduled job, what is the job ID?" AFTER comment_notif_status' );
2971          task_end();
2972  
2973          task_begin( 'Upgrading users table...' );
2974          db_add_col( 'T_users', 'user_notify_moderation', 'tinyint(1) NOT NULL default 0 COMMENT "Notify me by email whenever a comment is awaiting moderation on one of my blogs" AFTER user_notify' );
2975          db_add_col( 'T_users', 'user_unsubscribe_key', 'varchar(32) NOT NULL default "" COMMENT "A specific key, it is used when a user wants to unsubscribe from a post comments without signing in" AFTER user_notify_moderation' );
2976          // Set unsubscribe keys for existing users with no unsubscribe key
2977          $sql = 'SELECT user_ID
2978                              FROM T_users
2979                           WHERE user_unsubscribe_key = ""';
2980          $rows = $DB->get_results( $sql, OBJECT, 'Get users with no unsubscribe key' );
2981          foreach( $rows as $row )
2982          {
2983              $DB->query( 'UPDATE T_users
2984                              SET user_unsubscribe_key = "'.generate_random_key().'"
2985                              WHERE user_ID = '.$row->user_ID );
2986          }
2987          task_end();
2988  
2989          task_begin( 'Upgrading settings table... ');
2990          // This query was removed later, to avoid performance issue because of the smart view counting
2991          /*$DB->query( 'INSERT INTO T_settings (set_name, set_value)
2992                          VALUES ( "smart_hit_count", 1 )' );*/
2993          $DB->query( 'ALTER TABLE T_coll_settings
2994                                      CHANGE COLUMN cset_value cset_value   VARCHAR( 10000 ) NULL COMMENT "The AdSense plugin wants to store very long snippets of HTML"' );
2995            task_end();
2996  
2997            // The following two upgrade task were created subsequently to "Make sure DB schema is up to date".
2998            // Note: These queries don't modify the correct databases
2999          task_begin( 'Upgrading users table, no notification by default...');
3000          $DB->query( 'ALTER TABLE T_users ALTER COLUMN user_notify SET DEFAULT 0' );
3001          task_end();
3002  
3003          task_begin( 'Upgrading items table...');
3004          $DB->query( 'ALTER TABLE T_items__item CHANGE COLUMN post_priority post_priority int(11) unsigned null COMMENT "Task priority in workflow"' );
3005          task_end();
3006  
3007          set_upgrade_checkpoint( '10200' );
3008      }
3009  
3010  
3011      if( $old_db_version < 10300 )
3012      {    // 4.2
3013          task_begin( 'Upgrading user fields...' );
3014          $DB->query( 'ALTER TABLE T_users__fielddefs
3015                                      ADD COLUMN ufdf_required enum("hidden","optional","recommended","require") NOT NULL default "optional"');
3016          $DB->query( 'UPDATE T_users__fielddefs
3017                                          SET ufdf_required = "recommended"
3018                                      WHERE ufdf_name in ("Website", "Twitter", "Facebook") ' );
3019          $DB->query( "REPLACE INTO T_users__fielddefs (ufdf_ID, ufdf_type, ufdf_name, ufdf_required)
3020                                       VALUES (400000, 'text', 'About me', 'recommended');" );
3021          task_end();
3022  
3023          task_begin( 'Moving data to user fields...' );
3024          $DB->query( 'INSERT INTO T_users__fields( uf_user_ID, uf_ufdf_ID, uf_varchar )
3025                                   SELECT user_ID, 10300, user_icq
3026                                       FROM T_users
3027                                    WHERE user_icq IS NOT NULL AND TRIM(user_icq) <> ""' );
3028          $DB->query( 'INSERT INTO T_users__fields( uf_user_ID, uf_ufdf_ID, uf_varchar )
3029                                   SELECT user_ID, 10200, user_aim
3030                                       FROM T_users
3031                                    WHERE user_aim IS NOT NULL AND TRIM(user_aim) <> ""' );
3032          $DB->query( 'INSERT INTO T_users__fields( uf_user_ID, uf_ufdf_ID, uf_varchar )
3033                                   SELECT user_ID, 10000, user_msn
3034                                       FROM T_users
3035                                    WHERE user_msn IS NOT NULL AND TRIM(user_msn) <> ""' );
3036          $DB->query( 'INSERT INTO T_users__fields( uf_user_ID, uf_ufdf_ID, uf_varchar )
3037                                   SELECT user_ID, 10100, user_yim
3038                                       FROM T_users
3039                                    WHERE user_yim IS NOT NULL AND TRIM(user_yim) <> ""' );
3040          task_end();
3041  
3042          task_begin( 'Dropping obsolete user columns...' );
3043          $DB->query( 'ALTER TABLE T_users
3044                                      DROP COLUMN user_icq,
3045                                      DROP COLUMN user_aim,
3046                                      DROP COLUMN user_msn,
3047                                      DROP COLUMN user_yim' );
3048          task_end();
3049  
3050          // ---
3051  
3052          task_begin( 'Adding new user columns...' );
3053          $DB->query( 'ALTER TABLE T_users
3054                                      ADD COLUMN user_postcode varchar(12) NULL AFTER user_ID,
3055                                      ADD COLUMN user_age_min int unsigned NULL AFTER user_postcode,
3056                                      ADD COLUMN user_age_max int unsigned NULL AFTER user_age_min' );
3057          task_end();
3058  
3059          task_begin( 'Upgrading item table for hide teaser...' );
3060          $DB->query( 'ALTER TABLE T_items__item
3061                          ADD COLUMN post_hideteaser tinyint(1) NOT NULL DEFAULT 0 AFTER post_featured');
3062          $DB->query( 'UPDATE T_items__item
3063                                          SET post_hideteaser = 1
3064                                      WHERE post_content LIKE "%<!--noteaser-->%"' );
3065          task_end();
3066  
3067          task_begin( 'Creating table for a specific post settings...' );
3068          $DB->query( "CREATE TABLE T_items__item_settings (
3069                          iset_item_ID  int(10) unsigned NOT NULL,
3070                          iset_name     varchar( 50 ) NOT NULL,
3071                          iset_value    varchar( 2000 ) NULL,
3072                          PRIMARY KEY ( iset_item_ID, iset_name )
3073                      ) ENGINE = innodb" );
3074          task_end();
3075  
3076          task_begin( 'Adding new column to comments...' );
3077          $DB->query( 'ALTER TABLE T_comments
3078                                      ADD COLUMN comment_in_reply_to_cmt_ID INT(10) unsigned NULL AFTER comment_status' );
3079          task_end();
3080  
3081          task_begin( 'Create table for internal searches...' );
3082          $DB->query( 'CREATE TABLE T_logs__internal_searches (
3083                          isrch_ID bigint(20) NOT NULL auto_increment,
3084                          isrch_coll_ID bigint(20) NOT NULL,
3085                          isrch_hit_ID bigint(20) NOT NULL,
3086                          isrch_keywords varchar(255) NOT NULL,
3087                          PRIMARY KEY (isrch_ID)
3088                      ) ENGINE = MyISAM' );
3089          task_end();
3090  
3091          task_begin( 'Create table for comments votes...' );
3092          $DB->query( 'CREATE TABLE T_comments__votes (
3093                          cmvt_cmt_ID  int(10) unsigned NOT NULL,
3094                          cmvt_user_ID int(10) unsigned NOT NULL,
3095                          cmvt_helpful TINYINT(1) NULL DEFAULT NULL,
3096                          cmvt_spam    TINYINT(1) NULL DEFAULT NULL,
3097                          PRIMARY KEY (cmvt_cmt_ID, cmvt_user_ID),
3098                          KEY cmvt_cmt_ID (cmvt_cmt_ID),
3099                          KEY cmvt_user_ID (cmvt_user_ID)
3100                      ) ENGINE = innodb' );
3101          task_end();
3102  
3103          task_begin( 'Adding new comments columns...' );
3104          $DB->query( 'ALTER TABLE T_comments
3105                                      ADD comment_helpful_addvotes INT NOT NULL DEFAULT 0 AFTER comment_nofollow ,
3106                                      ADD comment_helpful_countvotes INT UNSIGNED NOT NULL DEFAULT 0 AFTER comment_helpful_addvotes ,
3107                                      ADD comment_spam_addvotes INT NOT NULL DEFAULT 0 AFTER comment_helpful_countvotes ,
3108                                      ADD comment_spam_countvotes INT UNSIGNED NOT NULL DEFAULT 0 AFTER comment_spam_addvotes ,
3109                                      CHANGE COLUMN comment_notif_ctsk_ID comment_notif_ctsk_ID      INT(10) unsigned NULL DEFAULT NULL COMMENT "When notifications for this comment are sent through a scheduled job, what is the job ID?"');
3110          task_end();
3111  
3112          task_begin( 'Adding new user permission for spam voting...' );
3113          $DB->query( 'ALTER TABLE T_coll_user_perms
3114                                      ADD bloguser_perm_vote_spam_cmts tinyint NOT NULL default 0 AFTER bloguser_perm_edit_ts' );
3115          task_end();
3116  
3117          task_begin( 'Adding new group permission for spam voting...' );
3118          $DB->query( 'ALTER TABLE T_coll_group_perms
3119                                      ADD bloggroup_perm_vote_spam_cmts tinyint NOT NULL default 0 AFTER bloggroup_perm_edit_ts' );
3120          task_end();
3121  
3122          task_begin( 'Upgrading countries table...' );
3123          $DB->query( 'ALTER TABLE '.$tableprefix.'country ADD COLUMN ctry_preferred tinyint(1) NOT NULL DEFAULT 0 AFTER ctry_enabled' );
3124          task_end();
3125  
3126          $DB->query( 'ALTER TABLE T_items__subscriptions CHANGE COLUMN isub_comments isub_comments   tinyint(1) NOT NULL DEFAULT 0 COMMENT "The user wants to receive notifications for new comments on this post"' );
3127  
3128          set_upgrade_checkpoint( '10300' );
3129      }
3130  
3131  
3132      if( $old_db_version < 10400 )
3133      {    // 4.2 part 2
3134          task_begin( 'Updating "Post by Email" settings...' );
3135          $DB->query( 'UPDATE T_settings SET set_name = "eblog_autobr" WHERE set_name = "AutoBR"' );
3136          task_end();
3137  
3138          if( $DB->get_var('SELECT set_value FROM T_settings WHERE set_name = "eblog_enabled"') )
3139          {    // eblog enabled, let's create a scheduled job for it
3140              task_begin( 'Creating "Post by Email" scheduled job...' );
3141              $start_date = form_date( date2mysql($GLOBALS['localtimenow'] + 86400), '05:00:00' ); // start tomorrow
3142              $DB->query( '
3143                  INSERT INTO T_cron__task ( ctsk_start_datetime, ctsk_repeat_after, ctsk_name, ctsk_controller, ctsk_params )
3144                  VALUES ( '.$DB->quote( $start_date ).', 86400, '.$DB->quote( T_('Create posts by email') ).', '.$DB->quote( 'cron/jobs/_post_by_email.job.php' ).', '.$DB->quote( 'N;' ).' )' );
3145              task_end();
3146          }
3147  
3148          task_begin( 'Upgrading hitlog table...' );
3149          $DB->query( 'ALTER TABLE T_hitlog
3150                                  ADD COLUMN hit_disp        VARCHAR(30) DEFAULT NULL AFTER hit_uri,
3151                                  ADD COLUMN hit_ctrl        VARCHAR(30) DEFAULT NULL AFTER hit_disp,
3152                                  ADD COLUMN hit_response_code     INT DEFAULT NULL AFTER hit_agent_type ' );
3153          task_end();
3154  
3155          task_begin( 'Upgrading file types...' );
3156          // Update ftyp_icon column
3157          // Previous versions used a image file name for this field,
3158          // but from now we should use a icon name from the file /conf/_icons.php
3159          $DB->query( 'UPDATE T_filetypes
3160                          SET ftyp_icon = "file_image"
3161                          WHERE ftyp_extensions IN ( "gif", "png", "jpg jpeg" )' );
3162          $DB->query( 'UPDATE T_filetypes
3163                          SET ftyp_icon = "file_document"
3164                          WHERE ftyp_extensions = "txt"' );
3165          $DB->query( 'UPDATE T_filetypes
3166                          SET ftyp_icon = "file_www"
3167                          WHERE ftyp_extensions = "htm html"' );
3168          $DB->query( 'UPDATE T_filetypes
3169                          SET ftyp_icon = "file_pdf"
3170                          WHERE ftyp_extensions = "pdf"' );
3171          $DB->query( 'UPDATE T_filetypes
3172                          SET ftyp_icon = "file_doc"
3173                          WHERE ftyp_extensions = "doc"' );
3174          $DB->query( 'UPDATE T_filetypes
3175                          SET ftyp_icon = "file_xls"
3176                          WHERE ftyp_extensions = "xls"' );
3177          $DB->query( 'UPDATE T_filetypes
3178                          SET ftyp_icon = "file_ppt"
3179                          WHERE ftyp_extensions = "ppt"' );
3180          $DB->query( 'UPDATE T_filetypes
3181                          SET ftyp_icon = "file_pps"
3182                          WHERE ftyp_extensions = "pps"' );
3183          $DB->query( 'UPDATE T_filetypes
3184                          SET ftyp_icon = "file_zip"
3185                          WHERE ftyp_extensions = "zip"' );
3186          $DB->query( 'UPDATE T_filetypes
3187                          SET ftyp_icon = "file_php"
3188                          WHERE ftyp_extensions = "php php3 php4 php5 php6"' );
3189          $DB->query( 'UPDATE T_filetypes
3190                          SET ftyp_icon = ""
3191                          WHERE ftyp_extensions = "css"' );
3192          $DB->query( 'UPDATE T_filetypes
3193                          SET ftyp_icon = "file_sound"
3194                          WHERE ftyp_extensions IN ( "mp3", "m4a" )' );
3195          $DB->query( 'UPDATE T_filetypes
3196                          SET ftyp_icon = "file_video"
3197                          WHERE ftyp_extensions IN ( "mp4", "mov", "m4v" )' );
3198          task_end();
3199  
3200          set_upgrade_checkpoint( '10400' );
3201      }
3202  
3203  
3204      if( $old_db_version < 10500 )
3205      {    //  part 3
3206          task_begin( 'Upgrading hitlog table...' );
3207          $DB->query( "ALTER TABLE T_hitlog
3208                                  CHANGE COLUMN hit_referer_type  hit_referer_type ENUM(  'search',  'special',  'spam',  'referer',  'direct',  'self',  'admin', 'blacklist' ) NOT NULL,
3209                                  ADD COLUMN hit_type ENUM('standard','rss','admin','ajax', 'service') DEFAULT 'standard' NOT NULL AFTER hit_ctrl,
3210                                  ADD COLUMN hit_action VARCHAR(30) DEFAULT NULL AFTER hit_ctrl" );
3211          $DB->query( 'UPDATE T_hitlog SET hit_referer_type = "special" WHERE hit_referer_type = "blacklist"' );
3212          $DB->query( 'UPDATE T_hitlog SET hit_type = "admin", hit_referer_type = "direct"  WHERE hit_referer_type = "admin"' );
3213          $DB->query( "ALTER TABLE T_hitlog
3214                                  CHANGE COLUMN hit_referer_type  hit_referer_type ENUM(  'search',  'special',  'spam',  'referer',  'direct',  'self' ) NOT NULL");
3215          task_end();
3216  
3217          task_begin( 'Creating table for Groups of user field definitions...' );
3218          $DB->query( 'CREATE TABLE T_users__fieldgroups (
3219                  ufgp_ID int(10) unsigned NOT NULL auto_increment,
3220                  ufgp_name varchar(255) NOT NULL,
3221                  ufgp_order int(11) NOT NULL,
3222                  PRIMARY KEY (ufgp_ID)
3223              ) ENGINE = innodb' );
3224          $DB->query( 'INSERT INTO T_users__fieldgroups ( ufgp_name, ufgp_order )
3225                  VALUES ( "Instant Messaging", "1" ),
3226                               ( "Phone", "2" ),
3227                               ( "Web", "3" ),
3228                               ( "Organization", "4" ),
3229                               ( "Address", "5" ),
3230                               ( "Other", "6" ) ' );
3231          task_end();
3232  
3233          task_begin( 'Upgrading user field definitions...' );
3234          // Add new fields:
3235          //         "ufdf_options" to save a values of the Option list
3236          //         "ufdf_duplicated" to add a several instances
3237          //         "ufdf_ufgp_ID" - Group ID
3238          //         "ufdf_order" - Order number
3239          //         "ufdf_suggest" - Suggest values
3240          $DB->query( 'ALTER TABLE T_users__fielddefs
3241                          ADD ufdf_options    TEXT NOT NULL AFTER ufdf_name,
3242                          ADD ufdf_duplicated enum("forbidden","allowed","list") NOT NULL default "allowed",
3243                          ADD ufdf_ufgp_ID    int(10) unsigned NOT NULL AFTER ufdf_ID,
3244                          ADD ufdf_order      int(11) NOT NULL,
3245                          ADD ufdf_suggest    tinyint(1) NOT NULL DEFAULT 0,
3246                          CHANGE ufdf_ID ufdf_ID int(10) UNSIGNED NOT NULL AUTO_INCREMENT' );
3247          // Set default values of the field "ufdf_duplicated"
3248          $DB->query( 'UPDATE T_users__fielddefs
3249                          SET ufdf_duplicated = "allowed"
3250                          WHERE ufdf_ID IN ( 10000, 10100, 10200, 10300, 50100, 50200, 100000, 100100 )' );
3251          // Group fields by default
3252          $DB->query( 'UPDATE T_users__fielddefs
3253                          SET ufdf_ufgp_ID = "1"
3254                          WHERE ufdf_ID <= 40000 ' );
3255          $DB->query( 'UPDATE T_users__fielddefs
3256                          SET ufdf_ufgp_ID = "2"
3257                          WHERE ufdf_ID > 40000 AND ufdf_ID <= 60100' );
3258          $DB->query( 'UPDATE T_users__fielddefs
3259                          SET ufdf_ufgp_ID = "3"
3260                          WHERE ufdf_ID > 60100 AND ufdf_ID <= 160100' );
3261          $DB->query( 'UPDATE T_users__fielddefs
3262                          SET ufdf_ufgp_ID = "4"
3263                          WHERE ufdf_ID > 160100 AND ufdf_ID <= 211000' );
3264          $DB->query( 'UPDATE T_users__fielddefs
3265                          SET ufdf_ufgp_ID = "5"
3266                          WHERE ufdf_ID > 211000 AND ufdf_ID <= 300300' );
3267          $DB->query( 'UPDATE T_users__fielddefs
3268                          SET ufdf_ufgp_ID = "6"
3269                          WHERE ufdf_ID > 300300' );
3270          // Set order field
3271          $userfields = $DB->get_results( 'SELECT ufdf_ID, ufdf_ufgp_ID
3272                  FROM T_users__fielddefs
3273                  ORDER BY ufdf_ufgp_ID, ufdf_ID' );
3274          $userfield_order = 1;
3275          foreach( $userfields as $uf => $userfield )
3276          {
3277              if( $uf > 0 )
3278              {
3279                  if( $userfields[$uf-1]->ufdf_ufgp_ID != $userfield->ufdf_ufgp_ID )
3280                  {    // New group is starting, reset $userfield_order
3281                      $userfield_order = 1;
3282                  }
3283              }
3284              $DB->query( 'UPDATE T_users__fielddefs
3285                          SET ufdf_order = "'.$userfield_order.'"
3286                          WHERE ufdf_ID = '.$userfield->ufdf_ID );
3287              $userfield_order++;
3288          }
3289          // Change field type for Group 'Organization' (group_ID=4)
3290          $DB->query( 'UPDATE T_users__fielddefs
3291                      SET ufdf_type = "word"
3292                      WHERE ufdf_ufgp_ID = "4"' );
3293          // Create a default additional info for administrator (user_ID=1)
3294          $DB->query( 'INSERT INTO T_users__fields ( uf_user_ID, uf_ufdf_ID, uf_varchar )
3295              VALUES ( 1, 200000, "Site administrator" ),
3296                           ( 1, 200000, "Moderator" ),
3297                           ( 1, 100000, "'.$baseurl.'" )' );
3298          // Add Indexes
3299          $DB->query( 'ALTER TABLE T_users__fields
3300                          ADD INDEX uf_ufdf_ID ( uf_ufdf_ID ),
3301                          ADD INDEX uf_varchar ( uf_varchar ) ' );
3302          task_end();
3303  
3304          task_begin( 'Upgrading permissions...' );
3305          // Group permissions
3306          $DB->query( 'ALTER TABLE T_coll_group_perms
3307                          ADD bloggroup_perm_own_cmts tinyint NOT NULL default 0 AFTER bloggroup_perm_edit_ts' );
3308          // Set default values for Administrators & Privileged Bloggers groups
3309          $DB->query( 'UPDATE T_coll_group_perms
3310                          SET bloggroup_perm_own_cmts = "1"
3311                          WHERE bloggroup_group_ID IN ( 1, 2 )' );
3312          // User permissions
3313          $DB->query( 'ALTER TABLE T_coll_user_perms
3314                          ADD bloguser_perm_own_cmts tinyint NOT NULL default 0 AFTER bloguser_perm_edit_ts' );
3315          task_end();
3316  
3317  
3318          set_upgrade_checkpoint( '10500' );
3319      }
3320  
3321  
3322      if( $old_db_version < 10600 )
3323      {    //  part 4
3324  
3325          // For create_default_regions() and create_default_subregions():
3326          require_once dirname(__FILE__).'/_functions_create.php';
3327  
3328          task_begin( 'Renaming Countries table...' );
3329          $DB->query( 'RENAME TABLE '.$tableprefix.'country TO T_regional__country' );
3330          task_end();
3331  
3332          task_begin( 'Renaming Currencies table...' );
3333          $DB->query( 'RENAME TABLE '.$tableprefix.'currency TO T_regional__currency' );
3334          task_end();
3335  
3336          task_begin( 'Creating Regions table...' );
3337          $DB->query( 'CREATE TABLE T_regional__region (
3338              rgn_ID        int(10) unsigned NOT NULL auto_increment,
3339              rgn_ctry_ID   int(10) unsigned NOT NULL,
3340              rgn_code      char(6) NOT NULL,
3341              rgn_name      varchar(40) NOT NULL,
3342              rgn_enabled   tinyint(1) NOT NULL DEFAULT 1,
3343              rgn_preferred tinyint(1) NOT NULL DEFAULT 0,
3344              PRIMARY KEY rgn_ID (rgn_ID),
3345              UNIQUE rgn_ctry_ID_code (rgn_ctry_ID, rgn_code)
3346          ) ENGINE = innodb' );
3347          task_end();
3348  
3349          create_default_regions();
3350  
3351          task_begin( 'Creating Sub-regions table...' );
3352          $DB->query( 'CREATE TABLE T_regional__subregion (
3353              subrg_ID        int(10) unsigned NOT NULL auto_increment,
3354              subrg_rgn_ID    int(10) unsigned NOT NULL,
3355              subrg_code      char(6) NOT NULL,
3356              subrg_name      varchar(40) NOT NULL,
3357              subrg_enabled   tinyint(1) NOT NULL DEFAULT 1,
3358              subrg_preferred tinyint(1) NOT NULL DEFAULT 0,
3359              PRIMARY KEY subrg_ID (subrg_ID),
3360              UNIQUE subrg_rgn_ID_code (subrg_rgn_ID, subrg_code)
3361          ) ENGINE = innodb' );
3362          task_end();
3363  
3364          create_default_subregions();
3365  
3366          task_begin( 'Creating Cities table...' );
3367          $DB->query( 'CREATE TABLE T_regional__city (
3368              city_ID         int(10) unsigned NOT NULL auto_increment,
3369              city_ctry_ID    int(10) unsigned NOT NULL,
3370              city_rgn_ID     int(10) unsigned NULL,
3371              city_subrg_ID   int(10) unsigned NULL,
3372              city_postcode   char(12) NOT NULL,
3373              city_name       varchar(40) NOT NULL,
3374              city_enabled    tinyint(1) NOT NULL DEFAULT 1,
3375              city_preferred  tinyint(1) NOT NULL DEFAULT 0,
3376              PRIMARY KEY city_ID (city_ID),
3377              INDEX city_ctry_ID_postcode ( city_ctry_ID, city_postcode ),
3378              INDEX city_rgn_ID_postcode ( city_rgn_ID, city_postcode ),
3379              INDEX city_subrg_ID_postcode ( city_subrg_ID, city_postcode )
3380          ) ENGINE = innodb' );
3381          task_end();
3382  
3383          task_begin( 'Update Item Settings...' );
3384          // Admin: full rights for all blogs (look 'ma, doing a natural join! :>)
3385          $query = "INSERT INTO T_items__item_settings( iset_item_ID, iset_name, iset_value )
3386                          SELECT post_ID, 'hide_teaser', post_hideteaser
3387                              FROM T_items__item";
3388          $DB->query( $query );
3389  
3390          db_drop_col( 'T_items__item', 'post_hideteaser' );
3391          task_end();
3392  
3393          task_begin( 'Upgrading hitlog table...' );
3394          $DB->query( "ALTER TABLE T_hitlog
3395                          ADD COLUMN hit_keyphrase VARCHAR(255) DEFAULT NULL AFTER hit_keyphrase_keyp_ID" );
3396          task_end();
3397  
3398          task_begin( 'Upgrading track__keyphrase...' );
3399          $DB->query( "ALTER TABLE T_track__keyphrase
3400                          ADD COLUMN keyp_count_refered_searches INT UNSIGNED DEFAULT 0 AFTER keyp_phrase,
3401                          ADD COLUMN keyp_count_internal_searches INT UNSIGNED DEFAULT 0 AFTER keyp_count_refered_searches" );
3402          task_end();
3403  
3404  
3405  
3406          task_begin( 'Droping table internal searches...' );
3407  
3408          $DB->query( "DROP TABLE T_logs__internal_searches" );
3409          task_end();
3410  
3411  
3412          task_begin( 'Upgrading users table...' );
3413          db_add_col( 'T_users', 'user_rgn_ID', 'int(10) unsigned NULL AFTER user_ctry_ID' );
3414          db_add_col( 'T_users', 'user_subrg_ID', 'int(10) unsigned NULL AFTER user_rgn_ID' );
3415          db_add_col( 'T_users', 'user_city_ID', 'int(10) unsigned NULL AFTER user_subrg_ID' );
3416          task_end();
3417  
3418          task_begin( 'Upgrading hitlog table...' );
3419          $DB->query( 'UPDATE T_hitlog
3420                          SET hit_type = "rss",
3421                              hit_agent_type = "unknown"
3422                          WHERE hit_agent_type = "rss"' );
3423  
3424          $DB->query( "ALTER TABLE T_hitlog
3425                                  CHANGE COLUMN hit_agent_type hit_agent_type ENUM('robot','browser','unknown') DEFAULT 'unknown' NOT NULL" );
3426          task_end();
3427  
3428          task_begin( 'Creating mail log table...' );
3429          $DB->query( 'CREATE TABLE '.$tableprefix.'mail__log (
3430            emlog_ID        INT(10) UNSIGNED NOT NULL auto_increment,
3431            emlog_timestamp TIMESTAMP NOT NULL,
3432            emlog_to        VARCHAR(255) DEFAULT NULL,
3433            emlog_success   TINYINT(1) NOT NULL DEFAULT 0,
3434            emlog_subject   VARCHAR(255) DEFAULT NULL,
3435            emlog_headers   TEXT DEFAULT NULL,
3436            emlog_message   TEXT DEFAULT NULL,
3437            PRIMARY KEY     (emlog_ID)
3438          ) ENGINE = myisam' );
3439          task_end();
3440  
3441          set_upgrade_checkpoint( '10600' );
3442      }
3443  
3444  
3445      if( $old_db_version < 10700 )
3446      {    // part 5
3447  
3448          task_begin( 'Upgrading user notifications settings...' );
3449          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3450                          SELECT user_ID, "notify_published_comments", user_notify
3451                              FROM T_users', 'Move notify settings from users to users_usersettings' );
3452          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3453                          SELECT user_ID, "notify_comment_moderation", user_notify_moderation
3454                              FROM T_users', 'Move notify moderation settings from users to users_usersettings' );
3455          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3456                          SELECT user_ID, "enable_PM", 1
3457                              FROM T_users
3458                                  WHERE user_allow_msgform = 1 OR user_allow_msgform = 3', 'Set enable PM on users_usersettings' );
3459          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3460                          SELECT user_ID, "enable_PM", 0
3461                              FROM T_users
3462                                  WHERE user_allow_msgform = 0 OR user_allow_msgform = 2', 'Set enable PM on users_usersettings' );
3463          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3464                          SELECT user_ID, "enable_email", 1
3465                              FROM T_users
3466                                  WHERE user_allow_msgform > 1', 'Set enable email true on users_usersettings' );
3467          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3468                          SELECT user_ID, "enable_email", 0
3469                              FROM T_users
3470                                  WHERE user_allow_msgform < 2', 'Set enable email false on users_usersettings' );
3471          db_drop_col( 'T_users', 'user_notify' );
3472          db_drop_col( 'T_users', 'user_notify_moderation' );
3473          db_drop_col( 'T_users', 'user_allow_msgform' );
3474          task_end();
3475  
3476          task_begin( 'Upgrading Item table...' );
3477          db_add_col( 'T_items__item', 'post_ctry_ID', 'INT(10) UNSIGNED NULL' );
3478          db_add_col( 'T_items__item', 'post_rgn_ID', 'INT(10) UNSIGNED NULL' );
3479          db_add_col( 'T_items__item', 'post_subrg_ID', 'INT(10) UNSIGNED NULL' );
3480          db_add_col( 'T_items__item', 'post_city_ID', 'INT(10) UNSIGNED NULL' );
3481          task_end();
3482  
3483          task_begin( 'Upgrading users table...' );
3484          db_drop_col( 'T_users', 'user_postcode' );    // Previously obsoleted
3485          db_drop_col( 'T_users', 'user_idmode' );
3486          task_end();
3487  
3488          task_begin( 'Upgrading users fields table...' );
3489          db_add_col( 'T_users__fielddefs', 'ufdf_bubbletip', 'varchar(2000) NULL' );
3490          task_end();
3491  
3492  
3493          task_begin( 'Creating table for groups of messaging contacts...' );
3494          $DB->query( "CREATE TABLE IF NOT EXISTS T_messaging__contact_groups (
3495              cgr_ID      int(10) unsigned NOT NULL auto_increment,
3496              cgr_user_ID int(10) unsigned NOT NULL,
3497              cgr_name    varchar(50) NOT NULL,
3498              PRIMARY KEY cgr_ID (cgr_ID)
3499          ) ENGINE = innodb" );
3500          task_end();
3501  
3502          task_begin( 'Creating table for group users of messaging contacts...' );
3503          $DB->query( "CREATE TABLE T_messaging__contact_groupusers (
3504              cgu_user_ID int(10) unsigned NOT NULL,
3505              cgu_cgr_ID  int(10) unsigned NOT NULL,
3506              PRIMARY KEY cgu_PK (cgu_user_ID, cgu_cgr_ID)
3507          ) ENGINE = innodb" );
3508          task_end();
3509  
3510          task_begin( 'Upgrading mail log table...' );
3511          db_add_col( $tableprefix.'mail__log', 'emlog_user_ID', 'INT(10) UNSIGNED DEFAULT NULL AFTER emlog_timestamp' );
3512          task_end();
3513  
3514          set_upgrade_checkpoint( '10700' );
3515      }
3516  
3517      if( $old_db_version < 10800 )
3518      {    // part 6 aka between "i1-i2" and "i2"
3519  
3520          task_begin( 'Upgrading users table, add user status...' );
3521          db_add_col( 'T_users', 'user_status', 'enum( "activated", "autoactivated", "closed", "deactivated", "emailchanged", "new" ) NOT NULL default "new" AFTER user_validated' );
3522          $update_user_status_query = 'UPDATE T_users SET user_status = ';
3523          // check if new users must activate their account. If users are not required to activate their account, then all existing users will be considerated as activated user.
3524          $new_users_must_validate = $DB->get_var( 'SELECT set_value FROM T_settings WHERE set_name = '.$DB->quote( 'newusers_mustvalidate' ) );
3525          if( $new_users_must_validate || ( $new_users_must_validate == NULL ) )
3526          { // newusers_mustvalidate setting is set to true, or it is not set at all. If it is not set, we know that the default value is true!
3527              // set activated status only for validated users
3528              $update_user_status_query .= $DB->quote( 'activated' );
3529              $update_user_status_query .= ' WHERE user_validated = 1';
3530          }
3531          else
3532          {
3533              $update_user_status_query .= $DB->quote( 'autoactivated' );
3534          }
3535          // set activated status for corresponding users
3536          $DB->query( $update_user_status_query );
3537          db_drop_col( 'T_users', 'user_validated' );
3538          task_end();
3539  
3540          set_upgrade_checkpoint( '10800' );
3541      }
3542  
3543      if( $old_db_version < 10900 )
3544      {    // part 7 aka "i3"
3545  
3546          task_begin( 'Upgrading user settings table...' );
3547          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3548                          SELECT user_ID, "show_online", 0
3549                              FROM T_users
3550                                  WHERE user_showonline = 0', 'Set show online on users_usersettings' );
3551          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3552                          SELECT user_ID, "user_ip", user_ip
3553                              FROM T_users
3554                                  WHERE user_ip IS NOT NULL', 'Set user ip on users_usersettings' );
3555          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3556                          SELECT user_ID, "user_domain", user_domain
3557                              FROM T_users
3558                                  WHERE user_domain IS NOT NULL', 'Set user domain on users_usersettings' );
3559          $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
3560                          SELECT user_ID, "user_browser", user_browser
3561                              FROM T_users
3562                                  WHERE user_browser IS NOT NULL', 'Set user browser on users_usersettings' );
3563          db_drop_col( 'T_users', 'user_showonline' );
3564          db_drop_col( 'T_users', 'user_ip' );
3565          db_drop_col( 'T_users', 'user_domain' );
3566          db_drop_col( 'T_users', 'user_browser' );
3567          task_end();
3568  
3569          task_begin( 'Upgrading user activation settings...' );
3570          // Remove all last_activation_email timestamps because we will use date instead of them
3571          $DB->query( 'DELETE FROM T_users__usersettings WHERE uset_name = "last_activation_email"' );
3572          task_end();
3573  
3574          task_begin( 'Upgrading Users table...' );
3575          // Update user_status column add 'failedactivation' status
3576          $DB->query( 'ALTER TABLE T_users CHANGE user_status
3577                      user_status enum( "activated", "autoactivated", "closed", "deactivated", "emailchanged", "failedactivation", "new" ) NOT NULL default "new"' );
3578          db_add_col( 'T_users', 'user_created_fromIPv4', 'int(10) unsigned NOT NULL' );
3579          db_add_col( 'T_users', 'user_email_dom_ID', 'int(10) unsigned NULL' );
3580          $DB->query( 'ALTER TABLE T_users CHANGE dateYMDhour user_created_datetime DATETIME NOT NULL DEFAULT \'2000-01-01 00:00:00\'' );
3581          db_add_col( 'T_users', 'user_reg_ctry_ID', 'int(10) unsigned NULL AFTER user_age_max' );
3582          db_add_col( 'T_users', 'user_profileupdate_ts', 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP' );
3583          $DB->query( 'ALTER TABLE T_users ADD INDEX user_email ( user_email )' );
3584          task_end();
3585  
3586          task_begin( 'Renaming Email log table...' );
3587          $DB->query( 'RENAME TABLE '.$tableprefix.'mail__log TO T_email__log' );
3588          task_end();
3589  
3590          task_begin( 'Creating email returns table...' );
3591          $DB->query( "CREATE TABLE T_email__returns (
3592                emret_ID        INT(10) UNSIGNED NOT NULL auto_increment,
3593                emret_address   VARCHAR(255) DEFAULT NULL,
3594                emret_errormsg  VARCHAR(255) DEFAULT NULL,
3595                emret_timestamp TIMESTAMP NOT NULL,
3596                emret_headers   TEXT DEFAULT NULL,
3597                emret_message   TEXT DEFAULT NULL,
3598                emret_errtype   CHAR(1) NOT NULL DEFAULT 'U',
3599                PRIMARY KEY     (emret_ID)
3600              ) ENGINE = myisam" );
3601          task_end();
3602  
3603          task_begin( 'Upgrading general settings table...' );
3604          $DB->query( 'ALTER TABLE T_settings CHANGE set_value set_value VARCHAR( 5000 ) NULL' );
3605          task_end();
3606  
3607          task_begin( 'Upgrading sessions table...' );
3608          db_add_col( 'T_sessions', 'sess_device', 'VARCHAR(8) NOT NULL DEFAULT \'\'' );
3609          task_end();
3610  
3611          task_begin( 'Creating table for Antispam IP Ranges...' );
3612          $DB->query( "CREATE TABLE T_antispam__iprange (
3613              aipr_ID         int(10) unsigned NOT NULL auto_increment,
3614              aipr_IPv4start  int(10) unsigned NOT NULL,
3615              aipr_IPv4end    int(10) unsigned NOT NULL,
3616              aipr_user_count int(10) unsigned DEFAULT 0,
3617              PRIMARY KEY aipr_ID (aipr_ID)
3618          ) ENGINE = innodb" );
3619          task_end();
3620  
3621          task_begin( 'Upgrading base domains table...' );
3622          $DB->query( "ALTER TABLE T_basedomains CHANGE dom_type dom_type ENUM( 'unknown', 'normal', 'searcheng', 'aggregator', 'email' ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'unknown'" );
3623          $DB->query( 'ALTER TABLE T_basedomains DROP INDEX dom_name' );
3624          $DB->query( 'ALTER TABLE T_basedomains DROP INDEX dom_type' );
3625          $DB->query( 'ALTER TABLE T_basedomains ADD UNIQUE dom_type_name ( dom_type, dom_name )' );
3626          task_end();
3627  
3628          /*** Update user_email_dom_ID for all already existing users ***/
3629          task_begin( 'Upgrading users email domains...' );
3630          $DB->begin();
3631          // Get the users
3632          $uemails_SQL = new SQL();
3633          $uemails_SQL->SELECT( 'user_ID, user_email' );
3634          $uemails_SQL->FROM( 'T_users' );
3635          $users_emails = $DB->get_assoc( $uemails_SQL->get() );
3636  
3637          if( count( $users_emails ) > 0 )
3638          {
3639              // Get all email domains
3640              $edoms_SQL = new SQL();
3641              $edoms_SQL->SELECT( 'dom_ID, dom_name' );
3642              $edoms_SQL->FROM( 'T_basedomains' );
3643              $edoms_SQL->WHERE( 'dom_type = \'email\'' );
3644              $email_domains = $DB->get_assoc( $edoms_SQL->get() );
3645              // pre_dump( $email_domains );
3646  
3647              foreach( $users_emails as $user_ID => $user_email )
3648              {
3649                  if( preg_match( '#@(.+)#i', strtolower($user_email), $ematch ) )
3650                  {    // Get email domain from user's email address
3651                      $email_domain = $ematch[1];
3652                      $dom_ID = array_search( $email_domain, $email_domains );
3653  
3654                      if( ! $dom_ID )
3655                      {    // Insert new email domain
3656                          $DB->query( 'INSERT INTO T_basedomains ( dom_type, dom_name )
3657                              VALUES ( \'email\', '.$DB->quote( $email_domain ).' )' );
3658                          $dom_ID = $DB->insert_id;
3659  
3660                          // Memorize inserted domain to prevent duplicates
3661                          $email_domains[$dom_ID] = $email_domain;
3662                          // pre_dump( $dom_ID, $email_domain );
3663                      }
3664  
3665                      // Update user_email_dom_ID
3666                      $DB->query( 'UPDATE T_users
3667                          SET user_email_dom_ID = '.$DB->quote( $dom_ID ).'
3668                          WHERE user_ID = '.$DB->quote( $user_ID ) );
3669                  }
3670              }
3671          }
3672          $DB->commit();
3673          task_end();
3674  
3675          task_begin( 'Upgrading users fields table...' );
3676          $DB->query( 'ALTER TABLE T_users__fields CHANGE uf_varchar uf_varchar VARCHAR( 10000 ) NOT NULL' );
3677          // Modify Indexes
3678          $DB->query( 'ALTER TABLE T_users__fields
3679                          DROP INDEX uf_varchar,
3680                          ADD INDEX uf_varchar ( uf_varchar(255) )' );
3681          task_end();
3682  
3683          task_begin( 'Upgrading cron tasks table...' );
3684          $DB->query( 'ALTER TABLE T_cron__task CHANGE ctsk_name ctsk_name VARCHAR(255) NOT NULL' );
3685          task_end();
3686  
3687          task_begin( 'Upgrading comments table...' );
3688          db_add_col( 'T_comments', 'comment_IP_ctry_ID', 'int(10) unsigned NULL AFTER comment_author_IP' );
3689          task_end();
3690  
3691          task_begin( 'Creating table for Blocked Email Addreses...' );
3692          $DB->query( "CREATE TABLE {$tableprefix}email__blocked (
3693              emblk_ID                    INT(10) UNSIGNED NOT NULL auto_increment,
3694              emblk_address               VARCHAR(255) DEFAULT NULL,
3695              emblk_status                ENUM ( 'unknown', 'warning', 'suspicious1', 'suspicious2', 'suspicious3', 'prmerror', 'spammer' ) NOT NULL DEFAULT 'unknown',
3696              emblk_sent_count            INT(10) UNSIGNED NOT NULL DEFAULT 0,
3697              emblk_sent_last_returnerror INT(10) UNSIGNED NOT NULL DEFAULT 0,
3698              emblk_prmerror_count        INT(10) UNSIGNED NOT NULL DEFAULT 0,
3699              emblk_tmperror_count        INT(10) UNSIGNED NOT NULL DEFAULT 0,
3700              emblk_spamerror_count       INT(10) UNSIGNED NOT NULL DEFAULT 0,
3701              emblk_othererror_count      INT(10) UNSIGNED NOT NULL DEFAULT 0,
3702              emblk_last_sent_ts          TIMESTAMP NULL,
3703              emblk_last_error_ts         TIMESTAMP NULL,
3704              PRIMARY KEY                 (emblk_ID),
3705              UNIQUE                      emblk_address (emblk_address)
3706          ) ENGINE = myisam" );
3707          task_end();
3708  
3709          task_begin( 'Upgrading email log table...' );
3710          // Get old values of emlog_success field
3711          $SQL = new SQL();
3712          $SQL->SELECT( 'emlog_ID' );
3713          $SQL->FROM( 'T_email__log' );
3714          $SQL->WHERE( 'emlog_success = 0' );
3715          $email_failed_logs = $DB->get_col( $SQL->get() );
3716          // Change a field emlog_success to new format
3717          $DB->query( 'ALTER TABLE T_email__log CHANGE emlog_success emlog_result ENUM ( "ok", "error", "blocked" ) NOT NULL DEFAULT "ok"' );
3718          if( !empty( $email_failed_logs ) )
3719          {    // Update only the failed email logs to new values
3720              // Do NOT update the success email logs, because we already have a result type 'ok' as default
3721              $DB->query( 'UPDATE T_email__log
3722                      SET emlog_result = '.$DB->quote( 'error' ).'
3723                  WHERE emlog_ID IN ( '.$DB->quote( $email_failed_logs ).' )' );
3724          }
3725          task_end();
3726  
3727          /*
3728           * ADD UPGRADES FOR i3 BRANCH __ABOVE__ IN THIS BLOCK.
3729           *
3730           * This part will be included in trunk and i3 branches
3731           */
3732  
3733          set_upgrade_checkpoint( '10900' );
3734      }
3735  
3736      if( $old_db_version < 10970 )
3737      {    // part 8/a trunk aka first part of "i4"
3738  
3739          global $db_storage_charset;
3740  
3741          task_begin( 'Upgrading Locales table...' );
3742          db_add_col( 'T_locales', 'loc_transliteration_map', 'VARCHAR(10000) NOT NULL default \'\' AFTER loc_priority' );
3743          task_end();
3744  
3745          task_begin( 'Upgrading general settings table...' );
3746          $DB->query( 'UPDATE T_settings SET set_name = '.$DB->quote( 'smart_view_count' ).' WHERE set_name = '.$DB->quote( 'smart_hit_count' ) );
3747          // This query below was added later to turn OFF smart view counting on upgrade from v4 to v5 for better performance
3748          $DB->query( 'DELETE FROM T_settings WHERE set_name = '.$DB->quote( 'smart_view_count' ) );
3749          task_end();
3750  
3751          task_begin( 'Upgrading sessions table...' );
3752          $DB->query( "UPDATE T_sessions SET sess_lastseen = concat( '2000-01-01 ', time( sess_lastseen ) )
3753                          WHERE date( sess_lastseen ) = '1970-01-01'" );
3754          $DB->query( "ALTER TABLE T_sessions CHANGE COLUMN sess_lastseen sess_lastseen_ts TIMESTAMP NOT NULL DEFAULT '2000-01-01 00:00:00' COMMENT 'User last logged activation time. Value may be off by up to 60 seconds'" );
3755          db_add_col( 'T_sessions', 'sess_start_ts', "TIMESTAMP NOT NULL DEFAULT '2000-01-01 00:00:00' AFTER sess_hitcount" );
3756          $DB->query( 'UPDATE T_sessions SET sess_start_ts = TIMESTAMPADD( SECOND, -1, sess_lastseen_ts )' );
3757          db_drop_col( 'T_sessions', 'sess_hitcount' );
3758          task_end();
3759  
3760          task_begin( 'Upgrading users table...' );
3761          db_add_col( 'T_users', 'user_lastseen_ts', 'TIMESTAMP NULL AFTER user_created_datetime' );
3762          $DB->query( 'UPDATE T_users SET user_lastseen_ts = ( SELECT MAX( sess_lastseen_ts ) FROM T_sessions WHERE sess_user_ID = user_ID )' );
3763          $DB->query( 'UPDATE T_users SET user_profileupdate_ts = user_created_datetime WHERE user_profileupdate_ts < user_created_datetime' );
3764          $DB->query( "ALTER TABLE T_users CHANGE COLUMN user_profileupdate_ts user_profileupdate_date DATE NOT NULL DEFAULT '2000-01-01' COMMENT 'Last day when the user has updated some visible field in his profile.'" );
3765          task_end();
3766  
3767          task_begin( 'Updating versions table...' );
3768          db_add_col( 'T_items__version', 'iver_ID', 'INT UNSIGNED NOT NULL FIRST' );
3769          $DB->query( 'ALTER TABLE T_items__version DROP INDEX iver_itm_ID, ADD INDEX iver_ID_itm_ID ( iver_ID , iver_itm_ID )' );
3770          task_end();
3771  
3772          task_begin( 'Upgrading messaging contact group users...' );
3773          db_add_foreign_key( 'T_messaging__contact_groupusers', 'cgu_cgr_ID', 'T_messaging__contact_groups', 'cgr_ID', 'ON DELETE CASCADE' );
3774          task_end();
3775  
3776          task_begin( 'Creating table for a latest version of the POT file...' );
3777          $DB->query( "CREATE TABLE T_i18n_original_string (
3778              iost_ID        int(10) unsigned NOT NULL auto_increment,
3779              iost_string    varchar(10000) NOT NULL default '',
3780              iost_inpotfile tinyint(1) NOT NULL DEFAULT 0,
3781              PRIMARY KEY (iost_ID)
3782          ) ENGINE = innodb" );
3783          task_end();
3784  
3785          task_begin( 'Creating table for a latest versions of the PO files...' );
3786          $DB->query( "CREATE TABLE T_i18n_translated_string (
3787              itst_ID       int(10) unsigned NOT NULL auto_increment,
3788              itst_iost_ID  int(10) unsigned NOT NULL,
3789              itst_locale   varchar(20) NOT NULL default '',
3790              itst_standard varchar(10000) NOT NULL default '',
3791              itst_custom   varchar(10000) NULL,
3792              itst_inpofile tinyint(1) NOT NULL DEFAULT 0,
3793              PRIMARY KEY (itst_ID)
3794          ) ENGINE = innodb DEFAULT CHARSET = utf8" );
3795          task_end();
3796  
3797          task_begin( 'Updating Antispam IP Ranges table...' );
3798          db_add_col( 'T_antispam__iprange', 'aipr_status', 'enum( \'trusted\', \'suspect\', \'blocked\' ) NULL DEFAULT NULL' );
3799          db_add_col( 'T_antispam__iprange', 'aipr_block_count', 'int(10) unsigned DEFAULT 0' );
3800          $DB->query( "ALTER TABLE T_antispam__iprange CHANGE COLUMN aipr_user_count aipr_user_count int(10) unsigned DEFAULT 0" );
3801          task_end();
3802  
3803          set_upgrade_checkpoint( '10970' );
3804      }
3805  
3806      if( $old_db_version < 10975 )
3807      {    // part 8/b trunk aka first part of "i4"
3808  
3809          task_begin( 'Creating default antispam IP ranges... ' );
3810          $DB->query( '
3811              INSERT INTO T_antispam__iprange ( aipr_IPv4start, aipr_IPv4end, aipr_status )
3812              VALUES ( '.$DB->quote( ip2int( '127.0.0.0' ) ).', '.$DB->quote( ip2int( '127.0.0.255' ) ).', "trusted" ),
3813                  ( '.$DB->quote( ip2int( '10.0.0.0' ) ).', '.$DB->quote( ip2int( '10.255.255.255' ) ).', "trusted" ),
3814                  ( '.$DB->quote( ip2int( '172.16.0.0' ) ).', '.$DB->quote( ip2int( '172.31.255.255' ) ).', "trusted" ),
3815                  ( '.$DB->quote( ip2int( '192.168.0.0' ) ).', '.$DB->quote( ip2int( '192.168.255.255' ) ).', "trusted" )
3816              ' );
3817          task_end();
3818  
3819          set_upgrade_checkpoint( '10975' );
3820      }
3821  
3822      if( $old_db_version < 11000 )
3823      {    // part 8/c trunk aka first part of "i4"
3824  
3825          task_begin( 'Adding new countries...' );
3826          // IGNORE is needed for upgrades from DB version 9970 or later
3827          $DB->query( 'INSERT IGNORE INTO T_regional__country ( ctry_code, ctry_name, ctry_curr_ID ) VALUES ( \'ct\', \'Catalonia\', \'2\' )' );
3828          task_end();
3829  
3830          task_begin( 'Upgrading message thread statuses table...' );
3831          db_add_col( 'T_messaging__threadstatus', 'tsta_thread_leave_msg_ID', 'int(10) unsigned NULL DEFAULT NULL' );
3832          task_end();
3833  
3834          task_begin( 'Upgrading Item Settings...' );
3835          // Convert item custom fields to custom item settings ( move custom fields from T_items__item table to T_items__item_settings table )
3836          $query = "INSERT INTO T_items__item_settings( iset_item_ID, iset_name, iset_value ) ";
3837          for( $i = 1; $i <= 8; $i++ )
3838          { // For each custom fields:
3839              if( $i > 1 )
3840              {
3841                  $query .= ' UNION';
3842              }
3843              $field_name = ( $i > 5 ) ? 'varchar'.( $i - 5 ) : 'double'.$i;
3844              $query .= " SELECT post_ID, 'custom_".$field_name."', post_".$field_name."
3845                              FROM T_items__item WHERE post_".$field_name." IS NOT NULL";
3846          }
3847          $DB->query( $query );
3848  
3849          for( $i = 1; $i <= 5; $i++ )
3850          { // drop custom double columns from items tabe
3851              db_drop_col( 'T_items__item', 'post_double'.$i );
3852          }
3853          for( $i = 1; $i <= 3; $i++ )
3854          { // drop custom varchar columns from items tabe
3855              db_drop_col( 'T_items__item', 'post_varchar'.$i );
3856          }
3857  
3858          // Convert post_editor_code item field to item settings
3859          $DB->query( 'INSERT INTO T_items__item_settings ( iset_item_ID, iset_name, iset_value )
3860                          SELECT post_ID, "editor_code", post_editor_code
3861                              FROM T_items__item
3862                              WHERE post_editor_code IS NOT NULL' );
3863          db_drop_col( 'T_items__item', 'post_editor_code' );
3864  
3865          // Convert post_metadesc item field to item settings
3866          $DB->query( 'INSERT INTO T_items__item_settings ( iset_item_ID, iset_name, iset_value )
3867                          SELECT post_ID, "post_metadesc", post_metadesc
3868                              FROM T_items__item
3869                              WHERE post_metadesc IS NOT NULL' );
3870          db_drop_col( 'T_items__item', 'post_metadesc' );
3871  
3872          // Convert and rename post_metakeywords item field to post_custom_headers item settings
3873          $DB->query( 'INSERT INTO T_items__item_settings ( iset_item_ID, iset_name, iset_value )
3874                          SELECT post_ID, "post_custom_headers", post_metakeywords
3875                              FROM T_items__item
3876                              WHERE post_metakeywords IS NOT NULL' );
3877          db_drop_col( 'T_items__item', 'post_metakeywords' );
3878          task_end();
3879  
3880          task_begin( 'Upgrading items table...' );
3881          // Drop not used column
3882          db_drop_col( 'T_items__item', 'post_commentsexpire' );
3883          task_end();
3884  
3885          task_begin( 'Adding new video file types...' );
3886          $ftyp = $DB->get_row('SELECT ftyp_ID, ftyp_extensions
3887                                      FROM T_filetypes
3888                                      WHERE ftyp_mimetype = "video/mp4"
3889                                      AND ftyp_extensions NOT LIKE "%f4v%"
3890                                      LIMIT 1');
3891  
3892          if( $ftyp )
3893          {    // Add f4v extension to mp4 file type, if not exists
3894              $DB->query( 'UPDATE T_filetypes SET ftyp_extensions = "'.$DB->escape($ftyp->ftyp_extensions.' f4v').'"
3895                              WHERE ftyp_ID = '.$DB->quote($ftyp->ftyp_ID) );
3896          }
3897          // Add flv file type if not exists
3898          if( !db_key_exists( 'T_filetypes', 'ftyp_extensions', '"flv"' ) )
3899          {
3900              $DB->query( 'INSERT INTO T_filetypes (ftyp_extensions, ftyp_name, ftyp_mimetype, ftyp_icon, ftyp_viewtype, ftyp_allowed)
3901                               VALUES ("flv", "Flash video file", "video/x-flv", "", "browser", "registered")', 'Add "flv" file type' );
3902          }
3903          // Add swf file type if not exists
3904          if( !db_key_exists( 'T_filetypes', 'ftyp_extensions', '"swf"' ) )
3905          {
3906              $DB->query( 'INSERT INTO T_filetypes (ftyp_extensions, ftyp_name, ftyp_mimetype, ftyp_icon, ftyp_viewtype, ftyp_allowed)
3907                               VALUES ("swf", "Flash video file", "application/x-shockwave-flash", "", "browser", "registered")', 'Add "swf" file type' );
3908          }
3909          task_end();
3910  
3911          task_begin( 'Upgrading custom item settings...' );
3912          $DB->begin();
3913          // Convert latitude and longitude from custom setting to normal item settings
3914          // Get those blog ids where Latitude and Longitude are both set
3915          $result = $DB->get_col( 'SELECT cs_left.cset_coll_ID
3916                                      FROM T_coll_settings as cs_left
3917                                      INNER JOIN T_coll_settings as cs_right ON cs_left.cset_coll_ID = cs_right.cset_coll_ID
3918                                      WHERE cs_left.cset_name = "custom_double3" AND cs_left.cset_value = "Latitude" AND
3919                                          cs_right.cset_name = "custom_double4" AND cs_right.cset_value = "Longitude"' );
3920          if( $result )
3921          { // blogs were found where Latitude and Longitude custom fields were set for google maps plugin
3922              // Set "Show location coordinates" on where Latitude and Longitude were set
3923              $query_values = '( '.implode( ', "show_location_coordinates", 1 ), ( ', $result ).', "show_location_coordinates", 1 )';
3924              $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
3925                              VALUES '.$query_values );
3926  
3927              $coll_ids = implode( ', ', $result );
3928              // Update latitude Item settings
3929              $DB->query( 'UPDATE T_items__item_settings SET iset_name = "latitude"
3930                              WHERE iset_name = "custom_double3" AND iset_item_ID IN (
3931                                  SELECT post_ID FROM T_items__item
3932                                  INNER JOIN T_categories ON post_main_cat_ID = cat_ID
3933                                  WHERE cat_blog_ID IN ( '.$coll_ids.' )
3934                              )' );
3935              // Update longitude Item settings
3936              $DB->query( 'UPDATE T_items__item_settings SET iset_name = "longitude"
3937                              WHERE iset_name = "custom_double4" AND iset_item_ID IN (
3938                                  SELECT post_ID FROM T_items__item
3939                                  INNER JOIN T_categories ON post_main_cat_ID = cat_ID
3940                                  WHERE cat_blog_ID IN ( '.$coll_ids.' )
3941                              )' );
3942              // Delete proessed latitude & longitude custom fields from collection settings
3943              $DB->query( 'DELETE FROM T_coll_settings
3944                          WHERE ( cset_name = "custom_double3" OR cset_name = "custom_double4" ) AND
3945                              cset_coll_ID IN ( '.$coll_ids.' )' );
3946          }
3947          $DB->commit(); // End convert latitude and longitude
3948  
3949          $DB->begin(); // Convert custom fields
3950          // Delete not used custom fields
3951          $DB->query( 'DELETE FROM T_coll_settings WHERE ( cset_value IS NULL OR cset_value = "" ) AND cset_name LIKE "custom\_%"' );
3952          // Set custom double fields count
3953          $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
3954                          SELECT cset_coll_ID, "count_custom_double", COUNT( cset_name )
3955                          FROM T_coll_settings
3956                          WHERE cset_name LIKE "custom\_double%"
3957                          GROUP BY cset_coll_ID' );
3958          // Set custom varchar fields count
3959          $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
3960                          SELECT cset_coll_ID, "count_custom_varchar", COUNT( cset_name )
3961                          FROM T_coll_settings
3962                          WHERE cset_name LIKE "custom\_varchar%"
3963                          GROUP BY cset_coll_ID' );
3964          // Select all custom fields from all blog, to create converted field values
3965          $result = $DB->get_results( 'SELECT cset_coll_ID as coll_ID, cset_name as name, cset_value as value
3966                                          FROM T_coll_settings
3967                                          WHERE cset_name LIKE "custom\_%"
3968                                          ORDER BY cset_coll_ID, cset_name' );
3969          if( !empty( $result ) )
3970          { // There are custom fields in blog settings
3971              $convert_field_values = '';
3972              $reorder_field_values = '';
3973              $old_prefix = "";
3974              $old_coll_ID = "";
3975              foreach( $result as $row )
3976              { // process each custom field
3977                  $custom_id = uniqid( '' );
3978                  $prefix = ( substr( $row->name, 7, 6 ) === 'double' ) ? 'custom_double' : 'custom_varchar';
3979                  // replace custom_double{N} and custom_varchar{N} values with a custom_id where N is number
3980                  $convert_field_values .= '( '.$row->coll_ID.', "'.$row->name.'", "'.$custom_id.'" ), ';
3981                  // add new custom_double_{customid} and custom_varchar_{customid} entries with the old correspinding custom field values
3982                  $convert_field_values .= '( '.$row->coll_ID.', "'.$prefix.'_'.$custom_id.'", "'.$row->value.'" ), ';
3983  
3984                  // create reorder values to replace e.g. custom_double2 to custom_double1 if custom_double1 doesn't exists yet
3985                  $index = ( ( $old_prefix == $prefix ) && ( $old_coll_ID == $row->coll_ID ) ) ? $index + 1 : 1;
3986                  $reorder_field_values .= '( '.$row->coll_ID.', "'.$prefix.$index.'", "'.$custom_id.'" ), ';
3987                  $old_prefix = $prefix;
3988                  $old_coll_ID = $row->coll_ID;
3989              }
3990              $convert_field_values = substr( $convert_field_values, 0, -2 );
3991              $reorder_field_values = substr( $reorder_field_values, 0, -2 );
3992              // Convert custom fields in collection setting
3993              $DB->query( 'REPLACE INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
3994                              VALUES '.$convert_field_values );
3995              // Update double custom field name_ids in item settings table
3996              $DB->query( 'UPDATE T_items__item_settings SET iset_name = (
3997                                  SELECT CONCAT( "custom_double_", cset_value ) FROM T_coll_settings
3998                                      INNER JOIN T_categories ON cset_coll_ID = cat_blog_ID
3999                                      INNER JOIN T_items__item ON cat_ID = post_main_cat_ID
4000                                      WHERE cset_name = iset_name AND post_ID  = iset_item_ID )
4001                              WHERE iset_name LIKE "custom\_double%"' );
4002              // Update varchar custom field name_ids in item settings table
4003              $DB->query( 'UPDATE T_items__item_settings SET iset_name = (
4004                                  SELECT CONCAT( "custom_varchar_", cset_value ) FROM T_coll_settings
4005                                      INNER JOIN T_categories ON cset_coll_ID = cat_blog_ID
4006                                      INNER JOIN T_items__item ON cat_ID = post_main_cat_ID
4007                                      WHERE cset_name = iset_name AND post_ID  = iset_item_ID )
4008                              WHERE iset_name LIKE "custom\_varchar%"' );
4009              // Reorder custom fields in collection settings
4010              $DB->query( 'REPLACE INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
4011                              VALUES '.$reorder_field_values );
4012          }
4013          $DB->commit(); // End convert custom fields
4014          task_end();
4015  
4016          task_begin( 'Convert group users permissions to pluggable permissions...' );
4017          $DB->query( 'REPLACE INTO T_groups__groupsettings( gset_grp_ID, gset_name, gset_value )
4018                          SELECT grp_ID, "perm_users", grp_perm_users
4019                              FROM T_groups' );
4020          db_drop_col( 'T_groups', 'grp_perm_users' );
4021          task_end();
4022  
4023          task_begin( 'Update Post Types... ' );
4024          $DB->query( "REPLACE INTO T_items__type ( ptyp_ID, ptyp_name )
4025              VALUES ( 4000, 'Advertisement' )" );
4026          task_end();
4027  
4028          task_begin( 'Update files table... ' );
4029          db_add_col( 'T_files', 'file_hash', 'char(32) default NULL' );
4030          task_end();
4031  
4032          task_begin( 'Create table for files voting...' );
4033          $DB->query( 'CREATE TABLE T_files__vote (
4034                  fvot_file_ID       int(11) UNSIGNED NOT NULL,
4035                  fvot_user_ID       int(11) UNSIGNED NOT NULL,
4036                  fvot_like          tinyint(1),
4037                  fvot_inappropriate tinyint(1),
4038                  fvot_spam          tinyint(1),
4039                  primary key (fvot_file_ID, fvot_user_ID)
4040              ) ENGINE = innodb' );
4041          task_end();
4042  
4043          task_begin( 'Create table for users reporting...' );
4044          $DB->query( "CREATE TABLE T_users__reports (
4045              urep_target_user_ID int(11) unsigned NOT NULL,
4046              urep_reporter_ID    int(11) unsigned NOT NULL,
4047              urep_status         enum( 'fake', 'guidelines', 'harass', 'spam', 'other' ),
4048              urep_info           varchar(240),
4049              urep_datetime        datetime NOT NULL,
4050              PRIMARY KEY ( urep_target_user_ID, urep_reporter_ID )
4051          ) ENGINE = innodb" );
4052          task_end();
4053  
4054          task_begin( 'Upgrading skins type...' );
4055          $DB->query( "ALTER TABLE T_skins__skin MODIFY COLUMN skin_type enum('normal','feed','sitemap','mobile','tablet') NOT NULL default 'normal'" );
4056          task_end();
4057  
4058          task_begin( 'Upgrading blogs skins...' );
4059          // Convert blog skin ID to blog settings
4060          $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
4061                          SELECT blog_ID, "normal_skin_ID", blog_skin_ID
4062                          FROM T_blogs' );
4063          db_drop_col( 'T_blogs', 'blog_skin_ID' );
4064          task_end();
4065  
4066          task_begin( 'Update categories table... ' );
4067          db_add_col( 'T_categories', 'cat_meta', 'tinyint(1) NOT NULL DEFAULT 0' );
4068          db_add_col( 'T_categories', 'cat_lock', 'tinyint(1) NOT NULL DEFAULT 0' );
4069          task_end();
4070  
4071          task_begin( 'Plugin settings update...' );
4072          $all_blog_ids = $DB->get_col( 'SELECT blog_ID FROM T_blogs' );
4073          $plugin_ids = $DB->get_assoc( 'SELECT pset_plug_ID, pset_value FROM T_pluginsettings WHERE pset_name = "render_comments"' );
4074          $insert_values = '';
4075          foreach( $all_blog_ids as $blog_ID )
4076          {
4077              foreach( $plugin_ids as $plugin_ID => $setting_value )
4078              {
4079                  $apply_comment_rendering = $setting_value ? 'stealth' : 'never';
4080                  $insert_values .= '( '.$blog_ID.', "plugin'.$plugin_ID.'_coll_apply_comment_rendering", "'.$apply_comment_rendering.'" ),';
4081              }
4082          }
4083          if( !empty( $insert_values ) )
4084          {
4085              $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
4086                              VALUES '.substr( $insert_values, 0, strlen( $insert_values ) - 1 ) );
4087          }
4088          $DB->query( 'DELETE FROM T_pluginsettings WHERE pset_name = "render_comments"' );
4089          task_end();
4090  
4091          task_begin( 'Creating comment prerendering cache table...' );
4092          $DB->query( "CREATE TABLE T_comments__prerendering (
4093              cmpr_cmt_ID INT(11) UNSIGNED NOT NULL,
4094              cmpr_format ENUM('htmlbody','entityencoded','xml','text') NOT NULL,
4095              cmpr_renderers TEXT NOT NULL,
4096              cmpr_content_prerendered MEDIUMTEXT NULL,
4097              cmpr_datemodified TIMESTAMP NOT NULL,
4098              PRIMARY KEY (cmpr_cmt_ID, cmpr_format)
4099          ) ENGINE = innodb" );
4100          db_add_col( 'T_comments', 'comment_renderers', "TEXT NOT NULL AFTER comment_content" );
4101          $DB->query( 'UPDATE T_comments SET comment_renderers = "default"' );
4102          task_end();
4103  
4104          task_begin( 'Upgrading plugins table...' );
4105          db_drop_col( 'T_plugins', 'plug_apply_rendering' );
4106          task_end();
4107  
4108          task_begin( 'Upgrading Auto_P plugin...' );
4109          $blog_settings = $DB->get_assoc( 'SELECT cset_coll_ID, cset_value FROM T_coll_settings WHERE cset_name = "comment_autobr"' );
4110          $insert_values = array();
4111          $plugin_ids = $DB->get_col( 'SELECT plug_ID FROM T_plugins WHERE plug_code = "b2WPAutP"' );
4112          foreach( $blog_settings as $blog_ID => $blog_setting_value )
4113          {
4114              foreach( $plugin_ids as $plugin_ID )
4115              {
4116                  switch( $blog_setting_value )
4117                  {
4118                      case 'never':
4119                          $apply_comment_rendering = 'never';
4120                          break;
4121                      case 'optional':
4122                          $apply_comment_rendering = 'opt-out';
4123                          break;
4124                      case 'always':
4125                          $apply_comment_rendering = 'stealth';
4126                          break;
4127                      default:
4128                          break 2;
4129                  }
4130                  $insert_values[] = '( '.$blog_ID.', "plugin'.$plugin_ID.'_coll_apply_comment_rendering", "'.$apply_comment_rendering.'" )';
4131              }
4132          }
4133          if( count( $insert_values ) > 0 )
4134          {
4135              $DB->query( 'REPLACE INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
4136                          VALUES '.implode( ',', $insert_values ) );
4137          }
4138          $DB->query( 'DELETE FROM T_coll_settings WHERE cset_name = "comment_autobr"' );
4139          $DB->query( 'UPDATE T_comments SET comment_content = REPLACE( REPLACE( comment_content, "<br>\n", "\n" ), "<br />\n", "\n" )' );
4140          task_end();
4141  
4142          set_upgrade_checkpoint( '11000' );
4143      }
4144  
4145      if( $old_db_version < 11010 )
4146      {    // part 9 trunk aka second part of "i4"
4147  
4148          task_begin( 'Upgrading post statuses...' );
4149          $DB->query( "ALTER TABLE T_items__item CHANGE COLUMN post_status post_status enum('published','community','deprecated','protected','private','review','draft','redirected') NOT NULL default 'published'" );
4150          $DB->query( "ALTER TABLE T_items__version CHANGE COLUMN iver_status iver_status ENUM('published','community','deprecated','protected','private','review','draft','redirected') NULL" );
4151          $DB->query( "ALTER TABLE T_coll_user_perms CHANGE COLUMN bloguser_perm_poststatuses bloguser_perm_poststatuses set('review','draft','private','protected','deprecated','community','published','redirected') NOT NULL default ''" );
4152          $DB->query( "ALTER TABLE T_coll_group_perms CHANGE COLUMN bloggroup_perm_poststatuses bloggroup_perm_poststatuses set('review','draft','private','protected','deprecated','community','published','redirected') NOT NULL default ''" );
4153          task_end();
4154  
4155          task_begin( 'Upgrading groups table...' );
4156          $pbloggers_renamed_to_moderators = $DB->query( 'UPDATE T_groups SET grp_name = "Moderators" WHERE grp_ID = 2 AND grp_name = "Privileged Bloggers"' );
4157          // Update administrators and moderators users coll setting permissions with new permissions
4158          // Note we can change moderators permission if the group name and ID was not changed after the original install
4159          $moderators_condition = $pbloggers_renamed_to_moderators ? ' OR bloggroup_group_ID = 2' : '';
4160          $DB->query( "UPDATE T_coll_group_perms SET bloggroup_perm_poststatuses = 'published,community,deprecated,protected,private,review,draft' WHERE bloggroup_group_ID = 1".$moderators_condition );
4161          // Change groups name
4162          $DB->query( 'UPDATE T_groups SET grp_name = "Trusted Users" WHERE grp_ID = 3 AND grp_name = "Bloggers"' );
4163          $DB->query( 'UPDATE T_groups SET grp_name = "Normal Users" WHERE grp_ID = 4 AND grp_name = "Basic Users"' );
4164  
4165          // Get "Misbehaving/Suspect Users" group ID
4166          $suspect_query = 'SELECT grp_ID
4167                          FROM T_groups
4168                          WHERE grp_name = "Misbehaving/Suspect Users"
4169                          ORDER BY grp_ID DESC
4170                          LIMIT 1';
4171          $suspect_group_ID = $DB->get_var( $suspect_query );
4172          if( empty( $suspect_group_ID ) )
4173          { // suspect group doesn't exists, check spammers because probably it does not exists either
4174              $insert_values = '( "Misbehaving/Suspect Users" )';
4175              // Get "Spammers/Restricted Users" group ID
4176              $query = 'SELECT grp_ID
4177                      FROM T_groups
4178                      WHERE grp_name = "Spammers/Restricted Users"
4179                      ORDER BY grp_ID DESC
4180                      LIMIT 1';
4181              $spammers_group_ID = $DB->get_var( $query );
4182              if( empty( $spammers_group_ID ) )
4183              {
4184                  $insert_values .= ', ( "Spammers/Restricted Users" )';
4185              }
4186              // Insert two new group
4187              $DB->query( 'INSERT INTO T_groups ( grp_name )
4188                          VALUES '.$insert_values );
4189  
4190              $suspect_group_ID = $DB->get_var( $suspect_query );
4191              if( $suspect_group_ID )
4192              { // Set coll setting permissions for Misbehaving/Suspect Users in Forums
4193                  $query = "
4194                      INSERT INTO T_coll_group_perms( bloggroup_blog_ID, bloggroup_group_ID, bloggroup_ismember,
4195                          bloggroup_perm_poststatuses, bloggroup_perm_delpost, bloggroup_perm_edit_ts,
4196                          bloggroup_perm_own_cmts, bloggroup_perm_vote_spam_cmts, bloggroup_perm_draft_cmts, bloggroup_perm_publ_cmts, bloggroup_perm_depr_cmts,
4197                          bloggroup_perm_cats, bloggroup_perm_properties,
4198                          bloggroup_perm_media_upload, bloggroup_perm_media_browse, bloggroup_perm_media_change )
4199                      SELECT blog_ID, ".$suspect_group_ID.", 1, 'review,draft', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
4200                          FROM T_blogs WHERE blog_ID = 5 AND blog_shortname = 'Forums'";
4201                  $DB->query( $query );
4202              }
4203          }
4204          task_end();
4205  
4206          task_begin( 'Upgrading blogs table...' );
4207          db_add_col( 'T_blogs', 'blog_type', 'ENUM( "std", "photo", "group", "forum", "manual" ) DEFAULT "std" NOT NULL' );
4208          task_end();
4209  
4210          task_begin( 'Upgrading comment statuses...' );
4211          $DB->query( "ALTER TABLE T_comments CHANGE COLUMN comment_status comment_status ENUM('published','community','deprecated','protected','private','review','draft','trash') DEFAULT 'published' NOT NULL" );
4212          task_end();
4213  
4214          task_begin( 'Updating collection user/group permissions...' );
4215          db_add_col( 'T_coll_user_perms', 'bloguser_perm_cmtstatuses', "set('review','draft','private','protected','deprecated','community','published') NOT NULL default '' AFTER bloguser_perm_vote_spam_cmts" );
4216          db_add_col( 'T_coll_user_perms', 'bloguser_perm_edit_cmt', "ENUM('no','own','anon','lt','le','all') NOT NULL default 'no' AFTER bloguser_perm_cmtstatuses" );
4217          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_cmtstatuses', "set('review','draft','private','protected','deprecated','community','published') NOT NULL default '' AFTER bloggroup_perm_vote_spam_cmts" );
4218          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_edit_cmt', "ENUM('no','own','anon','lt','le','all') NOT NULL default 'no' AFTER bloggroup_perm_cmtstatuses" );
4219  
4220          // Add access to those comment statuses for what user had before
4221          $DB->query( 'UPDATE T_coll_user_perms
4222                      SET bloguser_perm_cmtstatuses = ( bloguser_perm_publ_cmts * 1 ) | ( bloguser_perm_depr_cmts * 4 ) | ( bloguser_perm_draft_cmts * 64 )' );
4223          // Add access to all cmt statuses for those users which had edit permission on all comment statuses
4224          $DB->query( 'UPDATE T_coll_user_perms
4225                      SET bloguser_perm_cmtstatuses = "published,community,deprecated,protected,private,review,draft", bloguser_perm_edit_cmt = "all"
4226                      WHERE bloguser_perm_publ_cmts <> 0 AND bloguser_perm_depr_cmts <> 0 AND bloguser_perm_draft_cmts <> 0' );
4227          // Add "lower then" edit permission to those users who had permission to edit published or draft comments
4228          $DB->query( 'UPDATE T_coll_user_perms
4229                      SET bloguser_perm_edit_cmt = "lt"
4230                      WHERE ( bloguser_perm_cmtstatuses & 65 ) != 0 AND bloguser_perm_edit_cmt = "no"' );
4231  
4232          // Add access to those comment statuses for what group had before
4233          $DB->query( 'UPDATE T_coll_group_perms
4234                      SET bloggroup_perm_cmtstatuses = ( bloggroup_perm_publ_cmts * 1 ) | ( bloggroup_perm_depr_cmts * 4 ) | ( bloggroup_perm_draft_cmts * 64 )' );
4235          // Add access to all cmt statuses for those groups which had edit permission on all comment statuses
4236          $DB->query( 'UPDATE T_coll_group_perms
4237                      SET bloggroup_perm_cmtstatuses = "published,community,deprecated,protected,private,review,draft", bloggroup_perm_edit_cmt = "all"
4238                      WHERE bloggroup_perm_publ_cmts <> 0 AND bloggroup_perm_depr_cmts <> 0 AND bloggroup_perm_draft_cmts <> 0' );
4239          // Add "lower then" edit permission to those groups who had permission to edit published or draft comments
4240          $DB->query( 'UPDATE T_coll_group_perms
4241                      SET bloggroup_perm_edit_cmt = "lt"
4242                      WHERE ( bloggroup_perm_cmtstatuses & 65 ) != 0 AND bloggroup_perm_edit_cmt = "no"' );
4243  
4244          db_drop_col( 'T_coll_user_perms', 'bloguser_perm_draft_cmts' );
4245          db_drop_col( 'T_coll_user_perms', 'bloguser_perm_publ_cmts' );
4246          db_drop_col( 'T_coll_user_perms', 'bloguser_perm_depr_cmts' );
4247          db_drop_col( 'T_coll_group_perms', 'bloggroup_perm_draft_cmts' );
4248          db_drop_col( 'T_coll_group_perms', 'bloggroup_perm_publ_cmts' );
4249          db_drop_col( 'T_coll_group_perms', 'bloggroup_perm_depr_cmts' );
4250  
4251          db_add_col( 'T_coll_user_perms', 'bloguser_perm_delcmts', 'tinyint NOT NULL default 0 AFTER bloguser_perm_edit_ts' );
4252          db_add_col( 'T_coll_group_perms', 'bloggroup_perm_delcmts', 'tinyint NOT NULL default 0 AFTER bloggroup_perm_edit_ts' );
4253          // GRANT delete comment perms for moderators
4254          $DB->query( 'UPDATE T_coll_group_perms
4255                      SET bloggroup_perm_delcmts = 1
4256                      WHERE bloggroup_perm_edit_cmt = "le" OR bloggroup_perm_edit_cmt = "all"' );
4257  
4258          $DB->query( "ALTER TABLE T_coll_user_perms CHANGE COLUMN bloguser_perm_own_cmts bloguser_perm_recycle_owncmts tinyint NOT NULL default 0" );
4259          $DB->query( "ALTER TABLE T_coll_group_perms CHANGE COLUMN bloggroup_perm_own_cmts bloggroup_perm_recycle_owncmts tinyint NOT NULL default 0" );
4260          task_end();
4261  
4262          task_begin( 'Updating blogs settings...' );
4263          $DB->query( 'UPDATE T_coll_settings SET cset_value = "blog" WHERE cset_name = "enable_goto_blog" AND cset_value = "1"' );
4264          $DB->query( 'UPDATE T_coll_settings SET cset_value = "no" WHERE cset_name = "enable_goto_blog" AND cset_value = "0"' );
4265          task_end();
4266  
4267          /*
4268           * ADD UPGRADES FOR i4 BRANCH __ABOVE__ IN THIS BLOCK.
4269           *
4270           * This part will be included in trunk and i4 branches
4271           */
4272  
4273          set_upgrade_checkpoint( '11010' );
4274      }
4275  
4276      if( $old_db_version < 11020 )
4277      {    // part 10 trunk aka third part of "i4"
4278  
4279          task_begin( 'Upgrading users table...' );
4280          // Get all users with defined IPs
4281          $users_SQL = new SQL();
4282          $users_SQL->SELECT( 'user_ID, user_created_fromIPv4' );
4283          $users_SQL->FROM( 'T_users' );
4284          $users_SQL->WHERE( 'user_created_fromIPv4 IS NOT NULL' );
4285          $users_SQL->WHERE_and( 'user_created_fromIPv4 != '.$DB->quote( ip2int( '0.0.0.0' ) ) );
4286          $users_SQL->WHERE_and( 'user_created_fromIPv4 != '.$DB->quote( ip2int( '127.0.0.1' ) ) );
4287          $users = $DB->get_assoc( $users_SQL->get() );
4288          // Get user's IPs from settings table
4289          $settings_SQL = new SQL();
4290          $settings_SQL->SELECT( 'uset_user_ID, uset_value' );
4291          $settings_SQL->FROM( 'T_users__usersettings' );
4292          $settings_SQL->WHERE( 'uset_name = "user_ip"' );
4293          if( count( $users ) > 0 )
4294          {    // Get IPs only for users which have not IP in T_users table
4295              $settings_SQL->WHERE_and( 'uset_user_ID NOT IN ('.$DB->quote( array_keys( $users ) ).')' );
4296          }
4297          $settings = $DB->get_assoc( $settings_SQL->get() );
4298          if( count( $users ) > 0 || count( $settings ) > 0 )
4299          {
4300              $users_settings_insert_sql = array();
4301              foreach( $users as $user_ID => $user_IP )
4302              {
4303                  $users_settings_insert_sql[] = '( '.$DB->quote( $user_ID ).', "created_fromIPv4", '.$DB->quote( $user_IP ).' )';
4304              }
4305              foreach( $settings as $user_ID => $user_IP )
4306              {
4307                  $users_settings_insert_sql[] = '( '.$DB->quote( $user_ID ).', "created_fromIPv4", '.$DB->quote( ip2int( $user_IP ) ).' )';
4308              }
4309              // Insert IPs values into settings table
4310              $DB->query( 'INSERT INTO T_users__usersettings ( uset_user_ID, uset_name, uset_value )
4311                  VALUES '.implode( ', ', $users_settings_insert_sql ) );
4312          }
4313          // Remove old IPs from settings table
4314          $DB->query( 'DELETE FROM T_users__usersettings
4315              WHERE uset_name = "user_ip"' );
4316          db_drop_col( 'T_users', 'user_created_fromIPv4' );
4317          task_end();
4318  
4319          /*
4320           * ADD UPGRADES FOR i4 BRANCH __ABOVE__ IN THIS BLOCK.
4321           *
4322           * This part will be included in trunk and i4 branches
4323           */
4324  
4325          set_upgrade_checkpoint( '11020' );
4326      }
4327  
4328      if( $old_db_version < 11025 )
4329      {    // part 11 trunk aka fourth part of "i4"
4330  
4331          task_begin( 'Upgrading items table...' );
4332          $DB->query( "UPDATE T_items__item SET post_datecreated = concat( '2000-01-01 ', time( post_datecreated ) )
4333                          WHERE date( post_datecreated ) = '1970-01-01'" );
4334          $DB->query( "UPDATE T_items__item SET post_datemodified = concat( '2000-01-01 ', time( post_datemodified ) )
4335                          WHERE date( post_datemodified ) = '1970-01-01'" );
4336          $DB->query( "ALTER TABLE T_items__item CHANGE COLUMN post_datecreated post_datecreated TIMESTAMP NOT NULL DEFAULT '2000-01-01 00:00:00'" );
4337          $DB->query( "ALTER TABLE T_items__item CHANGE COLUMN post_datemodified post_datemodified TIMESTAMP NOT NULL DEFAULT '2000-01-01 00:00:00'" );
4338          db_add_col( 'T_items__item', 'post_last_touched_ts', "TIMESTAMP NOT NULL DEFAULT '2000-01-01 00:00:00' AFTER post_datemodified" );
4339          $DB->query( 'UPDATE T_items__item SET post_last_touched_ts = post_datemodified' );
4340          task_end();
4341  
4342          /*
4343           * ADD UPGRADES FOR i4 BRANCH __ABOVE__ IN THIS BLOCK.
4344           *
4345           * This part will be included in trunk and i4 branches
4346           */
4347  
4348          set_upgrade_checkpoint( '11025' );
4349      }
4350  
4351      // In some upgrade versions ( currently only in "i5" ) we would like to create profile pictures links from the user's files in the profile pictures folder
4352      // To be able to do that we need an up to date database version, so we will create profile pictures after the ugrade script run successfully.
4353      // Set this $create_profile_picture_links to true only in those upgrade block where it's required.
4354      $create_profile_picture_links = false;
4355  
4356      if( $old_db_version < 11100 )
4357      {    // part 12 trunk aka "i5"
4358  
4359          task_begin( 'Update links table...' );
4360          db_add_col( 'T_links', 'link_usr_ID', 'int(11) unsigned  NULL COMMENT "Used for linking files to users (user profile picture)" AFTER link_cmt_ID' );
4361          db_add_index( 'T_links', 'link_usr_ID', 'link_usr_ID' );
4362          task_end();
4363  
4364          task_begin( 'Creating links for users profile pictures...' );
4365          // Create links for main profile pictures
4366          $link_create_date = date2mysql( time() );
4367          $DB->query( 'INSERT INTO T_links( link_datecreated, link_datemodified, link_usr_ID, link_file_ID, link_position, link_order )
4368                          SELECT '.$DB->quote( $link_create_date ).', '.$DB->quote( $link_create_date ).', user_ID, user_avatar_file_ID, "", 1
4369                          FROM T_users
4370                          WHERE user_avatar_file_ID IS NOT NULL' );
4371          // Set $create_profile_picture_links to true to create links for all files from the users profile_pictures folder
4372          $create_profile_picture_links = true;
4373          task_end();
4374  
4375          task_begin( 'Upgrading categories table...' );
4376          $DB->query( "ALTER TABLE T_categories CHANGE COLUMN cat_urlname cat_urlname varchar(255) NOT NULL COLLATE ascii_bin" );
4377          task_end();
4378  
4379          task_begin( 'Upgrading items table...' );
4380          $DB->query( "ALTER TABLE T_items__item CHANGE COLUMN post_urltitle post_urltitle VARCHAR(210) NOT NULL COLLATE ascii_bin" );
4381          task_end();
4382  
4383          task_begin( 'Upgrading custom item settings...' );
4384          $DB->begin(); // Add names for custom fields
4385          // Select all custom fields from all blogs, to create field names
4386          $result = $DB->get_results( 'SELECT cset_coll_ID as coll_ID, cset_name as name, cset_value as value
4387                                          FROM T_coll_settings
4388                                          WHERE cset_name LIKE "custom\_double\_%"
4389                                             OR cset_name LIKE "custom\_varchar\_%"
4390                                          ORDER BY cset_coll_ID, cset_name' );
4391          if( !empty( $result ) )
4392          { // There are custom fields in blog settings
4393              $insert_field_names = '';
4394              foreach( $result as $row )
4395              { // process each custom field
4396                  $field_guid = preg_replace( '/^custom_(double|varchar)_([a-f0-9\-]+)$/', '$2', $row->name );
4397                  // Replace special chars/umlauts, if we can convert charsets:
4398                  load_funcs('locales/_charset.funcs.php');
4399                  $field_name = strtolower( preg_replace( '/[^a-z0-9\-_]+/i', '_', $row->value ) );
4400                  $field_name = replace_special_chars( $field_name );
4401  
4402                  $insert_field_names .= '( '.$row->coll_ID.', "custom_fname_'.$field_guid.'", "'.$field_name.'" ), ';
4403              }
4404              // Insert names for custom fields in collection settings
4405              $DB->query( 'INSERT INTO T_coll_settings( cset_coll_ID, cset_name, cset_value )
4406                              VALUES '.substr( $insert_field_names, 0, -2 ) );
4407          }
4408          $DB->commit(); // End adding of names for custom fields
4409          task_end();
4410  
4411          task_begin( 'Upgrading comments table...' );
4412          db_add_index( 'T_comments', 'comment_status', 'comment_status' );
4413          task_end();
4414  
4415          /*
4416           * ADD UPGRADES FOR i5 BRANCH __ABOVE__ IN THIS BLOCK.
4417           *
4418           * This part will be included in trunk and i5 branches
4419           */
4420  
4421          set_upgrade_checkpoint( '11100' );
4422      }
4423  
4424      if( $old_db_version < 11110 )
4425      { // part 13 trunk aka second part of "i5"
4426  
4427          // Add new settings for antispam groups
4428          $antispam_group_settings = $DB->get_assoc( 'SELECT set_name, set_value
4429               FROM T_settings
4430              WHERE set_name IN ( '.$DB->quote( array( 'antispam_suspicious_group', 'antispam_trust_groups' ) ).')' );
4431          if( count( $antispam_group_settings ) < 2 )
4432          { // Insert new settings only if don't exist in DB
4433              task_begin( 'Updating general settings...' );
4434              // Set antispam suspicious group
4435              if( !isset( $antispam_group_settings['antispam_suspicious_group'] ) )
4436              { // Insert new value, Don't rewrite value if it already defined before
4437                  $suspect_group_SQL = new SQL();
4438                  $suspect_group_SQL->SELECT( 'grp_ID' );
4439                  $suspect_group_SQL->FROM( 'T_groups' );
4440                  $suspect_group_SQL->WHERE( 'grp_name = '.$DB->quote( 'Misbehaving/Suspect Users' ) );
4441                  $suspect_group_ID = $DB->get_var( $suspect_group_SQL->get() );
4442                  if( !empty( $suspect_group_ID ) )
4443                  { // Save setting value
4444                      $DB->query( 'INSERT INTO T_settings ( set_name, set_value ) VALUES
4445                              ( '.$DB->quote( 'antispam_suspicious_group' ).', '.$DB->quote( $suspect_group_ID ).' )' );
4446                  }
4447              }
4448              // Set antispam trust groups
4449              if( !isset( $antispam_group_settings['antispam_trust_groups'] ) )
4450              { // Insert new value, Don't rewrite value if it already defined before
4451                  $trust_groups = array( 'Administrators', 'Moderators', 'Trusted Users', 'Spammers/Restricted Users' );
4452                  $trust_groups_SQL = new SQL();
4453                  $trust_groups_SQL->SELECT( 'grp_ID' );
4454                  $trust_groups_SQL->FROM( 'T_groups' );
4455                  $trust_groups_SQL->WHERE( 'grp_name IN ( '.$DB->quote( $trust_groups ).')' );
4456                  $trust_groups_IDs = $DB->get_col( $trust_groups_SQL->get() );
4457                  if( !empty( $trust_groups_IDs ) )
4458                  { // Save setting value
4459                      $DB->query( 'INSERT INTO T_settings ( set_name, set_value ) VALUES
4460                              ( '.$DB->quote( 'antispam_trust_groups' ).', '.$DB->quote( implode( ',', $trust_groups_IDs ) ).' )' );
4461                  }
4462              }
4463              task_end();
4464          }
4465  
4466          /*
4467           * ADD UPGRADES FOR i5 BRANCH __ABOVE__ IN THIS BLOCK.
4468           *
4469           * This part will be included in trunk and i5 branches
4470           */
4471  
4472          //set_upgrade_checkpoint( '11110' );
4473      }
4474  
4475      // Execute general upgrade tasks.
4476      // These tasks needs to be called after every upgrade process, except if they were already executed but the upgrade was not finished because of the max execution time check.
4477      if( param( 'exec_general_tasks', 'boolean', 1 ) )
4478      {    // We haven't executed these general tasks yet:
4479  
4480          // Update modules own b2evo tables
4481          echo "Calling modules for individual upgrades...<br>\n";
4482          evo_flush();
4483          modules_call_method( 'upgrade_b2evo_tables' );
4484  
4485          // Just in case, make sure the db schema version is up to date at the end.
4486          if( $old_db_version != $new_db_version )
4487          { // Update DB schema version to $new_db_version
4488              set_upgrade_checkpoint( $new_db_version );
4489          }
4490  
4491          // We're going to need some environment in order to init caches and create profile picture links...
4492          if( ! is_object( $Settings ) )
4493          { // create Settings object
4494              load_class( 'settings/model/_generalsettings.class.php', 'GeneralSettings' );
4495              $Settings = new GeneralSettings();
4496          }
4497          if( ! is_object( $Plugins ) )
4498          { // create Plugins object
4499              load_class( 'plugins/model/_plugins.class.php', 'Plugins' );
4500              $Plugins = new Plugins();
4501          }
4502  
4503          // Init Caches: (it should be possible to do this with each upgrade)
4504          task_begin( '(Re-)Initializing caches...' );
4505          load_funcs('tools/model/_system.funcs.php');
4506          if( system_init_caches() )
4507          { // cache was initialized successfully
4508              // Check all cache folders if exist and work properly. Try to repair cache folders if they aren't ready for operation.
4509              system_check_caches();
4510          }
4511          else
4512          {
4513              echo "<strong>".T_('The /cache folder could not be created/written to. b2evolution will still work but without caching, which will make it operate slower than optimal.')."</strong><br />\n";
4514          }
4515          task_end();
4516  
4517          // Check if profile picture links should be recreated. It won't be executed in each upgrade, but only in those cases when it is required.
4518          // This requires an up to date database, and also $Plugins and $GeneralSettings objects must be initialized before this.
4519          // Note: Check $create_profile_picture_links intialization and usage above to get more information.
4520          if( $create_profile_picture_links )
4521          { // Create links for all files from the users profile_pictures folder
4522              task_begin( 'Creating profile picture links...' );
4523              create_profile_picture_links();
4524              task_end();
4525          }
4526  
4527          // Invalidate all page caches after every upgrade.
4528          // A new version of b2evolution may not use the same links to access special pages.
4529          // We want to play it safe here so that people don't think that upgrading broke their blog!
4530          task_begin( 'Invalidating all page caches to make sure they don\'t contain old action links...' );
4531          invalidate_pagecaches();
4532          task_end();
4533  
4534  
4535          // Reload plugins after every upgrade, to detect even those changes on plugins which didn't require db modifications
4536          task_begin( 'Reloading installed plugins to make sure their config is up to date...' );
4537          $Plugins_admin = & get_Plugins_admin();
4538          $Plugins_admin->reload_plugins();
4539          task_end();
4540  
4541  
4542          // This has to be at the end because plugin install may fail if the DB schema is not current (matching Plugins class).
4543          // Only new default plugins will be installed, based on $old_db_version.
4544          // dh> NOTE: if this fails (e.g. fatal error in one of the plugins), it will not get repeated
4545          task_begin( 'Installing new default plugins (if any)...' );
4546          install_basic_plugins( $old_db_version );
4547          task_end();
4548  
4549  
4550          // Create default cron jobs (this can be done at each upgrade):
4551          echo "Checking if some default cron jobs need to be installed...<br/>\n";
4552          evo_flush();
4553          require_once dirname(__FILE__).'/_functions_create.php';
4554          create_default_jobs( true );
4555  
4556          // "Time running low" test: Check if the upgrade script elapsed time is close to the max execution time.
4557          // Note: This should not really happen except the case when many plugins must be installed.
4558          task_begin( 'Checking timing of upgrade...' );
4559          $elapsed_time = time() - $script_start_time;
4560          $max_exe_time = ini_get( 'max_execution_time' );
4561          if( $max_exe_time && ( $elapsed_time > ( $max_exe_time - 20 ) ) )
4562          { // Max exe time not disabled and we're recahing the end
4563              // URL to continue the upgrade process from install folder
4564              $upgrade_continue_url = $baseurl.'install/index.php?locale='.$locale.'&amp;action='.$upgrade_action.'&amp;exec_general_tasks=0';
4565              echo 'We are reaching the time limit for this script. Please click <a href="'.$upgrade_continue_url.'">continue</a>...';
4566              // Dirty temporary solution:
4567              exit(0);
4568          }
4569          task_end();
4570      }
4571  
4572  
4573      /*
4574       * -----------------------------------------------
4575       * Check to make sure the DB schema is up to date:
4576       * -----------------------------------------------
4577       */
4578      echo "Starting to check DB...<br/>\n";
4579      evo_flush();
4580  
4581      $upgrade_db_deltas = array(); // This holds changes to make, if any (just all queries)
4582  
4583      global $debug;
4584  
4585      foreach( $schema_queries as $table => $query_info )
4586      {    // For each table in the schema, check diffs...
4587          if( $debug )
4588          {
4589              echo '<br />Checking table: '.$table.': ';
4590          }
4591          $updates = db_delta( $query_info[1], array('drop_column', 'drop_index'), false, true );
4592          if( empty($updates) )
4593          {
4594              if( $debug ) echo 'ok';
4595          }
4596          else
4597          {
4598              if( $debug ) echo 'NEEDS UPDATE!';
4599              foreach( $updates as $table => $queries )
4600              {
4601                  foreach( $queries as $qinfo )
4602                  {
4603                      foreach( $qinfo['queries'] as $query )
4604                      { // subqueries for this query (usually one, but may include required other queries)
4605                          $upgrade_db_deltas[] = $query;
4606                      }
4607                  }
4608              }
4609          }
4610      }
4611  
4612      if( $debug )
4613      {
4614          echo '<br />';
4615      }
4616  
4617      if( empty($upgrade_db_deltas) )
4618      {    // no upgrades needed:
4619          echo '<p>'.T_('The database schema is up to date.').'</p>';
4620      }
4621      else
4622      {    // Upgrades are needed:
4623  
4624          $confirmed_db_upgrade = param('confirmed', 'integer', 0); // force confirmation
4625          $upgrade_db_deltas_confirm_md5 = param( 'upgrade_db_deltas_confirm_md5', 'string', '' );
4626  
4627          if( ! $confirmed_db_upgrade )
4628          {
4629              if( ! empty($upgrade_db_deltas_confirm_md5) )
4630              { // received confirmation from form
4631                  if( $upgrade_db_deltas_confirm_md5 != md5( implode('', $upgrade_db_deltas) ) )
4632                  { // unlikely to happen
4633                      echo '<p class="error">'
4634                          .T_('The DB schema has been changed since confirmation.')
4635                          .'</p>';
4636                  }
4637                  else
4638                  {
4639                      $confirmed_db_upgrade = true;
4640                  }
4641              }
4642          }
4643  
4644          if( ! $confirmed_db_upgrade )
4645          {
4646              global $action, $form_action;
4647              load_class( '_core/ui/forms/_form.class.php', 'Form' );
4648  
4649              if( !empty( $form_action ) )
4650              {
4651                  $Form = new Form( $form_action, '', 'post' );
4652              }
4653              else
4654              {
4655                  $Form = new Form( NULL, '', 'post' );
4656              }
4657  
4658              $Form->begin_form( 'fform', T_('Upgrade database') );
4659  
4660              $Form->begin_fieldset();
4661              $Form->hidden( 'upgrade_db_deltas_confirm_md5', md5(implode( '', $upgrade_db_deltas )) );
4662              $Form->hidden( 'action', $action );
4663              $Form->hidden( 'locale', $locale );
4664  
4665  
4666              echo '<p>'.T_('The version number is correct, but we have detected changes in the database schema. This can happen with CVS versions...').'</p>';
4667  
4668              echo '<p>'.T_('The following database changes will be carried out. If you are not sure what this means, it will probably be alright.').'</p>';
4669  
4670              echo '<ul>';
4671              foreach( $upgrade_db_deltas as $l_delta )
4672              {
4673                  #echo '<li><code>'.nl2br($l_delta).'</code></li>';
4674                  echo '<li><pre>'.str_replace( "\t", '  ', $l_delta ).'</pre></li>';
4675              }
4676              echo '</ul>';
4677              $Form->submit( array( '', T_('Upgrade database!'), 'ActionButton' ) );
4678              $Form->end_form();
4679  
4680              return false;
4681          }
4682  
4683          // Alter DB to match DB schema:
4684          install_make_db_schema_current( true );
4685      }
4686  
4687      track_step( 'upgrade-success' );
4688  
4689      return true;
4690  }
4691  
4692  ?>

title

Description

title

Description

title

Description

title

title

Body