b2evolution PHP Cross Reference Blogging Systems

Source: /inc/tools/model/_phpbb.funcs.php - 2084 lines - 67739 bytes - Summary - Text - Print

Description: This file implements the functions to work with phpBB database importer. b2evolution - {@link http://b2evolution.net/} Released under GNU GPL License - {@link http://b2evolution.net/about/license.html}

   1  <?php
   2  /**

   3   * This file implements the functions to work with phpBB database importer.

   4   *

   5   * b2evolution - {@link http://b2evolution.net/}

   6   * Released under GNU GPL License - {@link http://b2evolution.net/about/license.html}

   7   *

   8   * @copyright (c)2003-2014 by Francois Planque - {@link http://fplanque.com/}

   9   *

  10   * {@internal Open Source relicensing agreement:

  11   * }}

  12   *

  13   * @package admin

  14   *

  15   * {@internal Below is a list of authors who have contributed to design/coding of this file: }}

  16   * @author fplanque: Francois PLANQUE.

  17   *

  18   * @version $Id: _phpbb.funcs.php 78 2011-10-26 16:29:49Z fplanque $

  19   */
  20  if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
  21  
  22  /**

  23   * Get aliases of the tables from the phpBB database

  24   *

  25   * @param string Table prefix

  26   * @return array Aliases

  27   */
  28  function phpbb_tables_aliases( $phpbb_db_prefix )
  29  {
  30      $phpbb_db_aliases = array(
  31              'BB_users'         => $phpbb_db_prefix.'users',
  32              'BB_ranks'         => $phpbb_db_prefix.'ranks',
  33              'BB_categories'    => $phpbb_db_prefix.'categories',
  34              'BB_forums'        => $phpbb_db_prefix.'forums',
  35              'BB_topics'        => $phpbb_db_prefix.'topics',
  36              'BB_posts'         => $phpbb_db_prefix.'posts',
  37              'BB_posts_text'    => $phpbb_db_prefix.'posts_text',
  38              'BB_privmsgs'      => $phpbb_db_prefix.'privmsgs',
  39              'BB_privmsgs_text' => $phpbb_db_prefix.'privmsgs_text',
  40              'BB_sessions_keys' => $phpbb_db_prefix.'sessions_keys',
  41          );
  42  
  43      return $phpbb_db_aliases;
  44  }
  45  
  46  
  47  /**

  48   * Initialize the config variables for phpBB

  49   */
  50  function phpbb_init_config()
  51  {
  52      global $Session;
  53      global $phpbb_db_config, $phpbb_DB;
  54  
  55      $phpbb_db_config = phpbb_get_var( 'db_config' );
  56      if( is_array( $phpbb_db_config ) && count( $phpbb_db_config ) > 0 )
  57      {    // Connect to DB when config is already defined
  58          $phpbb_db_config['show_errors'] = true;
  59          $phpbb_db_config['aliases'] = phpbb_tables_aliases( $phpbb_db_config['prefix'] );
  60          $phpbb_DB = new DB( $phpbb_db_config );
  61      }
  62      else
  63      {    // Default config values
  64          global $db_config, $test_install_all_features;
  65          $phpbb_db_config = array(
  66                  'host'     => $db_config['host'],
  67                  'name'     => '',
  68                  'user'     => $db_config['user'],
  69                  'password' => '',
  70                  'prefix'   => 'phpbb_',
  71              );
  72  
  73          if( $test_install_all_features )
  74          {    // Set maximum default values in test mode
  75              $phpbb_db_config['password'] = $db_config['password'];
  76              phpbb_set_var( 'blog_ID', '5' ); // Forums

  77  
  78              $GroupCache = & get_GroupCache();
  79              if( $normal_Group = & $GroupCache->get_by_name( 'Normal Users', false ) )
  80              {
  81                  phpbb_set_var( 'group_default', $normal_Group->ID ); // Basic Users

  82                  phpbb_set_var( 'all_group_default', $normal_Group->ID ); // Privileged Bloggers

  83              }
  84              if( $invalid_Group = & $GroupCache->get_by_name( 'Misbehaving/Suspect Users', false ) )
  85              {
  86                  phpbb_set_var( 'group_invalid', $invalid_Group->ID ); // Invalid Users

  87              }
  88          }
  89      }
  90  }
  91  
  92  
  93  /**

  94   * Print out the log message on the screen

  95   *

  96   * @param string Message

  97   * @param string Type: message|error|warning

  98   * @param string Text after message

  99   * @param string Text before message

 100   */
 101  function phpbb_log( $message, $type = 'message', $nl = '<br />', $bl = '' )
 102  {
 103      switch( $type )
 104      {
 105          case 'error':
 106              echo $bl.'<span class="red">'.$message.'</span>'.$nl;
 107              break;
 108  
 109          case 'warning':
 110              echo $bl.'<span class="orange">'.T_('WARNING: ').$message.'</span>'.$nl;
 111              break;
 112  
 113          default:
 114              echo $bl.$message.$nl;
 115              break;
 116      }
 117  
 118      evo_flush();
 119  }
 120  
 121  
 122  /**

 123   * Get variable that was saved in the session

 124   *

 125   * @param string Name

 126   * @return mixed Value

 127   */
 128  function phpbb_get_var( $name )
 129  {
 130      global $Session;
 131  
 132      switch( $name )
 133      {
 134          case 'path_avatars':
 135              global $media_path;
 136              $default_value = $media_path.'import/avatars';
 137              break;
 138  
 139          default:
 140              $default_value = NULL;
 141              break;
 142      }
 143  
 144      return $Session->get( 'phpbb.'.$name, $default_value );
 145  }
 146  
 147  
 148  /**

 149   * Set variable to store some phpBB config values

 150   *

 151   * @param string Name

 152   * @param string Value

 153   * @param boolean TRUE - to immediate saving the Sessions

 154   */
 155  function phpbb_set_var( $name, $value, $immediate_save = false )
 156  {
 157      global $Session;
 158  
 159      $Session->set( 'phpbb.'.$name, $value );
 160      if( $immediate_save )
 161      {
 162          $Session->dbsave();
 163      }
 164  }
 165  
 166  
 167  /**

 168   * Delete phpBB config variable

 169   *

 170   * @param string Name

 171   */
 172  function phpbb_unset_var( $name )
 173  {
 174      global $Session;
 175  
 176      $Session->delete( 'phpbb.'.$name );
 177  }
 178  
 179  
 180  /**

 181   * Get table name

 182   *

 183   * @param string Table name

 184   * @param string Table prefix

 185   * @return string Full table name

 186   */
 187  function phpbb_table_name( $table_name, $table_prefix = 'phpbbimporter__' )
 188  {
 189      return $table_prefix.$table_name;
 190  }
 191  
 192  
 193  /**

 194   * Add a temporary table into the DB

 195   *

 196   * @param string Table name

 197   */
 198  function phpbb_table_add( $table_name )
 199  {
 200      global $DB;
 201  
 202      $table_name = phpbb_table_name( $table_name );
 203  
 204      $DB->query( 'DROP TABLE IF EXISTS '.$table_name );
 205  
 206      $DB->query( 'CREATE TABLE IF NOT EXISTS '.$table_name.' (
 207          phpbb_ID INT(11) NULL,
 208          b2evo_ID INT(11) NULL
 209      ) ENGINE = innodb' );
 210  }
 211  
 212  
 213  /**

 214   * Delete a temporary table

 215   *

 216   * @param string Table name

 217   */
 218  function phpbb_table_delete( $table_name )
 219  {
 220      global $DB;
 221  
 222      $table_name = phpbb_table_name( $table_name );
 223  
 224      $DB->query( 'DROP TABLE IF EXISTS '.$table_name );
 225  }
 226  
 227  
 228  /**

 229   * Add the links for IDs from two tables

 230   *

 231   * @param string Table name

 232   * @param array The links between two tables

 233   */
 234  function phpbb_table_insert_links( $table_name, $links )
 235  {
 236      if( empty( $links ) )
 237      {    // No links
 238          return;
 239      }
 240  
 241      global $DB;
 242  
 243      $links_data = array();
 244      $l = 1;
 245      foreach( $links as $phpbb_ID => $b2evo_ID )
 246      {
 247          $links_data[] = '( '.(int)$phpbb_ID.', '.(int)$b2evo_ID.' )';
 248          if( $l == 1000 )
 249          {    // Insert data by 1000 records
 250              mysql_query( 'INSERT INTO '.phpbb_table_name( $table_name ).' ( phpbb_ID, b2evo_ID )
 251                      VALUES '.implode( ', ', $links_data ),
 252                  $DB->dbhandle );
 253              $links_data = array();
 254              $l = 1;
 255          }
 256          $l++;
 257      }
 258  
 259      if( count( $links_data ) > 0 )
 260      {    // Insert the rest records
 261              mysql_query( 'INSERT INTO '.phpbb_table_name( $table_name ).' ( phpbb_ID, b2evo_ID )
 262                      VALUES '.implode( ', ', $links_data ),
 263                  $DB->dbhandle );
 264      }
 265  }
 266  
 267  
 268  /**

 269   * Get the links for IDs from two tables

 270   *

 271   * @param string Table name

 272   * @return array The links between two tables

 273   */
 274  function phpbb_table_get_links( $table_name )
 275  {
 276      /**

 277      * @var array Cache for the links of IDs between phpbb and b2evo tables

 278      */
 279      global $phpbb_cache_links;
 280  
 281      if( !is_array( $phpbb_cache_links ) )
 282      {    // Init cache
 283          $phpbb_cache_links = array();
 284      }
 285  
 286      if( isset( $phpbb_cache_links[ $table_name ] ) )
 287      {    // The links from this table are already defined
 288          return $phpbb_cache_links[ $table_name ];
 289      }
 290  
 291      // Get the links from DB only first time

 292      global $DB;
 293  
 294      $table_exists = $DB->get_row( 'SHOW TABLES LIKE "'.phpbb_table_name( $table_name ).'"' );
 295      if( !empty( $table_exists ) )
 296      {    // Table exists in DB
 297          $SQL = new SQL();
 298          $SQL->SELECT( 'phpbb_ID, b2evo_ID' );
 299          $SQL->FROM( phpbb_table_name( $table_name ) );
 300  
 301          $phpbb_cache_links[ $table_name ] = $DB->get_assoc( $SQL->get() );
 302      }
 303      else
 304      {    // No table found in DB (it can be happened when we interrupt the processing by refreshing of the page)
 305          $phpbb_cache_links[ $table_name ] = array();
 306      }
 307  
 308      return $phpbb_cache_links[ $table_name ];
 309  }
 310  
 311  
 312  /**

 313   * Get user ranks from phpBB

 314   *

 315   * @return array Ranks

 316   */
 317  function phpbb_ranks()
 318  {
 319      global $phpbb_DB;
 320  
 321      $SQL = new SQL();
 322      $SQL->SELECT( 'rank_id, rank_title' );
 323      $SQL->FROM( 'BB_ranks' );
 324      $SQL->ORDER_BY( 'rank_min' );
 325  
 326      $ranks = $phpbb_DB->get_assoc( $SQL->get() );
 327  
 328      return $ranks;
 329  }
 330  
 331  
 332  /**

 333   * Get rank info

 334   *

 335   * @param integer Rank ID

 336   * @param boolean TRUE - to get only a count of users of selected rank

 337   * @return string Rank info (users count and etc.)

 338   */
 339  function phpbb_rank_info( $rank_ID, $get_only_count = false )
 340  {
 341      global $phpbb_DB, $rank_users_count;
 342  
 343      if( !isset( $rank_users_count ) )
 344      {    // Init array only first time
 345          $SQL = new SQL();
 346          $SQL->SELECT( 'rank_id, COUNT( user_id ) AS cnt' );
 347          $SQL->FROM( 'BB_users' );
 348          $SQL->FROM_add( 'INNER JOIN BB_ranks ON user_rank = rank_id' );
 349          $SQL->WHERE( 'user_id IN ( SELECT poster_id FROM phpbb_posts WHERE poster_id = user_id )' );
 350          $SQL->GROUP_BY( 'user_rank' );
 351          $rank_users_count = $phpbb_DB->get_assoc( $SQL->get() );
 352      }
 353  
 354      if( $get_only_count )
 355      {    // Return only a count of users of the rank
 356          return !empty( $rank_users_count[ $rank_ID ] ) ? (int)$rank_users_count[ $rank_ID ] : 0;
 357      }
 358  
 359      if( !empty( $rank_users_count[ $rank_ID ] ) )
 360      {
 361          $users_count = (int)$rank_users_count[ $rank_ID ];
 362          $r = sprintf( '%s users', $users_count );
 363  
 364          // Get the first 10 users of each rank

 365          $SQL = new SQL();
 366          $SQL->SELECT( 'username' );
 367          $SQL->FROM( 'BB_users' );
 368          $SQL->FROM_add( 'INNER JOIN BB_posts ON poster_id = user_id' ); // Get users which have at least one post

 369          $SQL->WHERE( 'user_rank = '.$phpbb_DB->quote( $rank_ID ) );
 370          $SQL->ORDER_BY( 'user_id' );
 371          $SQL->GROUP_BY( 'user_id' );
 372          $SQL->LIMIT( '10' );
 373          $users = $phpbb_DB->get_col( $SQL->get() );
 374  
 375          foreach( $users as $u => $username )
 376          {
 377              $users[ $u ] = $username;
 378          }
 379          $r .= ': '.implode( ', ', $users );
 380          $r .= ( $users_count > 10 ) ? ' ...' : '';
 381  
 382          return $r;
 383      }
 384  }
 385  
 386  
 387  /**

 388   * Get user groups from b2evolution

 389   *

 390   * @return array Groups

 391   */
 392  function b2evo_groups()
 393  {
 394      global $DB;
 395  
 396      $SQL = new SQL();
 397      $SQL->SELECT( 'grp_ID, grp_name' );
 398      $SQL->FROM( 'T_groups' );
 399  
 400      $groups = array( '0' => T_( 'No import' ) );
 401      $groups = array_merge( $groups, $DB->get_assoc( $SQL->get() ) );
 402  
 403      return $groups;
 404  }
 405  
 406  
 407  /**

 408   * Import users from phpbb into b2evo

 409   */
 410  function phpbb_import_users()
 411  {
 412      global $DB, $phpbb_DB, $tableprefix;
 413  
 414      if( !phpbb_check_step( 'users' ) )
 415      {    // Check current step
 416          return; // Exit here if we cannot process this step

 417      }
 418  
 419      phpbb_unset_var( 'users_count_imported' );
 420      phpbb_unset_var( 'users_count_updated' );
 421  
 422      phpbb_log( T_('Importing users...') );
 423  
 424      /**

 425       * @var array IDs of the Users;

 426       *        Key is ID from phpBB

 427       *        Value is new inserted ID from b2evo

 428       */
 429      $users_IDs = array();
 430  
 431      // Get ranks that will be imported ( array( phpbb_rank_ID => b2evo_group_ID ) )

 432      $phpbb_ranks = phpbb_get_var( 'ranks' );
 433  
 434      // Remove ranks that will not be imported

 435      if( count( $phpbb_ranks ) > 0 )
 436      {
 437          foreach( $phpbb_ranks as $rank_ID => $b2evo_group_ID )
 438          {
 439              if( empty( $b2evo_group_ID ) )
 440              {    // Unset this rank, because it selected as no import
 441                  unset( $phpbb_ranks[ $rank_ID ] );
 442              }
 443          }
 444      }
 445  
 446      $phpbb_users_sql_where_ranks = '';
 447      if( count( $phpbb_ranks ) > 0 )
 448      {    // Limit users by the selected ranks
 449          $phpbb_users_sql_where_ranks = ' OR u.user_rank IN ( '.$phpbb_DB->quote( array_keys( $phpbb_ranks ) ).' )';
 450      }
 451  
 452      $DB->begin();
 453  
 454      // Init SQL to get the users data and the count of the users

 455      $phpbb_users_SQL = new SQL();
 456      $phpbb_users_SQL->FROM( 'BB_users u' );
 457      $phpbb_users_SQL->FROM_add( 'INNER JOIN BB_posts p ON p.poster_id = u.user_id' ); // Get users which have at least one post

 458      $phpbb_users_SQL->WHERE( '( u.user_rank IS NULL OR u.user_rank = 0'.$phpbb_users_sql_where_ranks.' )' );
 459      $phpbb_users_SQL->ORDER_BY( 'u.user_id' );
 460  
 461      // Get the count of the topics

 462      $count_SQL = $phpbb_users_SQL;
 463      $count_SQL->SELECT( 'COUNT( DISTINCT u.user_id )' );
 464      $phpbb_users_count = $phpbb_DB->get_var( $count_SQL->get() );
 465  
 466      if( $phpbb_users_count > 0 )
 467      {
 468          phpbb_log( sprintf( T_('%s users have been found in the phpBB database'), $phpbb_users_count ) );
 469      }
 470      else
 471      {    // No users
 472          phpbb_log( T_('No users found in the phpBB database.'), 'error' );
 473          $DB->commit();
 474          return; // Exit here

 475      }
 476  
 477      // Get the duplicated emails

 478      $emails_SQL = new SQL();
 479      $emails_SQL->SELECT( 'user_email, ""' );
 480      $emails_SQL->FROM( 'BB_users' );
 481      $emails_SQL->GROUP_BY( 'user_email' );
 482      $emails_SQL->HAVING( 'COUNT( user_id ) > 1' );
 483      $phpbb_emails_duplicated = $phpbb_DB->get_assoc( $emails_SQL->get() );
 484  
 485      phpbb_log( T_('Start importing <b>users</b> into the b2evolution database...'), 'message', '' );
 486  
 487      // Init SQL to get the users

 488      $users_SQL = $phpbb_users_SQL;
 489      $users_SQL->SELECT( 'u.user_id, u.user_active, u.username, u.user_password, u.user_email, u.user_lang, u.user_level, u.user_regdate,
 490                               u.user_icq, u.user_website, u.user_aim, u.user_yim, u.user_msnm, u.user_interests, u.user_rank,
 491                               u.user_allow_viewonline, u.user_notify_pm, u.user_avatar' );
 492      $users_SQL->GROUP_BY( 'u.user_id' );
 493  
 494      // Get all users IPs in one sql query

 495      $users_ips_SQL = new SQL();
 496      $users_ips_SQL->SELECT( 'user_id, last_ip' );
 497      $users_ips_SQL->FROM( 'BB_sessions_keys' );
 498      $users_ips_SQL->ORDER_BY( 'last_login DESC' );
 499      $users_ips = $phpbb_DB->get_assoc( $users_ips_SQL->get() );
 500  
 501      // Prepare to import avatars

 502      $do_import_avatars = false;
 503      $path_avatars = phpbb_get_var( 'path_avatars' );
 504      if( !empty( $path_avatars ) )
 505      {
 506          $path_avatars = preg_replace( '/(\/|\\\\)$/i', '', $path_avatars).'/';
 507          if( !empty( $path_avatars ) && file_exists( $path_avatars ) && is_dir( $path_avatars ) )
 508          {    // Folder with avatars is correct, we can import avatars
 509              $do_import_avatars = true;
 510          }
 511      }
 512  
 513      $page = 0;
 514      $page_size = 1000;
 515      $phpbb_users_count_imported = 0;
 516      $phpbb_users_count_updated = 0;
 517      do
 518      {    // Split by page to optimize process
 519          // It gives to save the memory rather than if we get all users by one query without LIMIT clause

 520  
 521          // Get the users

 522          $users_SQL->LIMIT( ( $page * $page_size ).', '.$page_size );
 523          $phpbb_users = $phpbb_DB->get_results( $users_SQL->get() );
 524          $phpbb_users_count = count( $phpbb_users );
 525  
 526          // Insert the new users

 527          foreach( $phpbb_users as $p => $phpbb_user )
 528          {
 529              if( $p % 100 == 0 )
 530              {    // Display the processing dots after 100 users
 531                  phpbb_log( ' .', 'message', '' );
 532              }
 533  
 534              if( $phpbb_user->user_id < 1 )
 535              {    // Skip the users with invalid ID
 536                  phpbb_log( sprintf( T_( 'User "%s" with ID %s ignored' ), $phpbb_user->username, $phpbb_user->user_id ), 'error', ' ', '<br />' );
 537                  continue;
 538              }
 539  
 540              if( $phpbb_user->username == '' )
 541              {    // Special rule for this username
 542                  $user_login = 'yabba';
 543              }
 544              else
 545              {    // Replace unauthorized chars from username
 546                  $user_login = preg_replace( '/([^a-z0-9_])/i', '_', $phpbb_user->username );
 547                  $user_login = evo_substr( evo_strtolower( $user_login ), 0, 20 );
 548              }
 549  
 550              $user_has_duplicated_email = false;
 551              if( isset( $phpbb_emails_duplicated[$phpbb_user->user_email] ) )
 552              {    // The user has the duplicate email
 553                  if( !empty( $phpbb_emails_duplicated[$phpbb_user->user_email] ) )
 554                  {    // The other user already was imported with such email
 555                      phpbb_log( '<br />'.sprintf( T_( 'The phbBB users "%s" and "%s" have the same email address "%s" and will be merged in b2evolution as just "%s"' ) ,
 556                              $phpbb_emails_duplicated[$phpbb_user->user_email]['username'], // Username of the first user
 557                              $user_login, // Username of the second user (duplicate)
 558                              $phpbb_user->user_email, // The same email address
 559                              $phpbb_emails_duplicated[$phpbb_user->user_email]['username'] // This username will be used in b2evolution
 560                          ), 'error', ' ' );
 561  
 562                      // Set link between current phpBB user ID and b2evo user ID of first user with this duplicated email address

 563                      // This link will be used to merge the topics, comments and messages from all phpBB users with the same email address for ONE b2evo user

 564                      $users_IDs[$phpbb_user->user_id] = $users_IDs[ $phpbb_emails_duplicated[$phpbb_user->user_email]['user_ID'] ];
 565  
 566                      // Don't import this user

 567                      unset( $phpbb_users[$p] );
 568                      continue;
 569                  }
 570                  $phpbb_emails_duplicated[$phpbb_user->user_email] = array(
 571                          'username' => $user_login,
 572                          'user_ID'  => $phpbb_user->user_id
 573                      );
 574                  $user_has_duplicated_email = true;
 575              }
 576  
 577              // Check if this user already exists with same email address in b2evo DB

 578              $SQL = new SQL();
 579              $SQL->SELECT( 'user_ID, user_login' );
 580              $SQL->FROM( 'T_users' );
 581              $SQL->WHERE( 'user_email = '.$DB->quote( $phpbb_user->user_email ) );
 582              $b2evo_user = $DB->get_row( $SQL->get() );
 583              if( !empty( $b2evo_user ) )
 584              {    // User already exists in DB of b2evo
 585                  // Don't insert this user

 586                  // Update the link between IDs of this user from two databases

 587                  $users_IDs[$phpbb_user->user_id] = $b2evo_user->user_ID;
 588                  unset( $phpbb_users[$p] ); // Unset already existing user from this array to exclude the updating of the fields and settings

 589                  $phpbb_users_count_updated++;
 590  
 591                  if( $do_import_avatars )
 592                  {    // Import user's avatar
 593                      phpbb_import_avatar( $b2evo_user->user_ID, $path_avatars, $phpbb_user->user_avatar );
 594                  }
 595  
 596                  phpbb_log( sprintf( T_( 'The user #%s already exists with E-mail address "%s" in the b2evolution database -- Merging User "%s" with user "%s".' ), $phpbb_user->user_id, $phpbb_user->user_email, $user_login, $b2evo_user->user_login ), 'warning', ' ', '<br />' );
 597                  continue;
 598              }
 599  
 600              // Check if this user already exists with same login in b2evo DB

 601              $user_login_number = 0;
 602              $next_login = $user_login;
 603              do
 604              {
 605                  $SQL = new SQL();
 606                  $SQL->SELECT( 'user_ID' );
 607                  $SQL->FROM( 'T_users' );
 608                  $SQL->WHERE( 'user_login = '.$DB->quote( $next_login ) );
 609                  if( $b2evo_user_ID = $DB->get_var( $SQL->get() ) )
 610                  {    // Duplicated user login, Change to next login by increasing the number at the end
 611                      $next_login = $user_login.( ++$user_login_number );
 612                  }
 613              }
 614              while( $b2evo_user_ID );
 615              if( $user_login != $next_login )
 616              {    // Duplicated login was changed, Display a message about this event
 617                  phpbb_log( sprintf( T_( 'The login "%s" already exists with a different email address. The user "%s" will be imported as "%s"' ), $user_login, $user_login, $next_login ), 'warning', ' ', '<br />' );
 618                  $user_login = $next_login;
 619              }
 620  
 621              if( !empty( $users_ips[ $phpbb_user->user_id ] ) )
 622              {    // Decode user ip from hex format
 623                  $phpbb_user->user_ip = phpbb_decode_ip( $users_ips[ $phpbb_user->user_id ] );
 624              }
 625  
 626              $user_data = array(
 627                      'user_login'              => $user_login,
 628                      'user_pass'               => $phpbb_user->user_password,
 629                      'user_email'              => $phpbb_user->user_email,
 630                      'user_level'              => $phpbb_user->user_level,
 631                      'user_status'             => $phpbb_user->user_active == '1' ? 'autoactivated' : 'closed',
 632                      'user_created_datetime'   => date( 'Y-m-d H:i:s', $phpbb_user->user_regdate ),
 633                      'user_profileupdate_date' => date( 'Y-m-d', $phpbb_user->user_regdate ),
 634                      'user_locale'             => 'en-US'
 635                  );
 636  
 637              if( !empty( $phpbb_user->user_rank ) && !empty( $phpbb_ranks[ $phpbb_user->user_rank ] ) )
 638              {    // Define the user's group
 639                  $user_data['user_grp_ID'] = $phpbb_ranks[ $phpbb_user->user_rank ];
 640              }
 641              if( !isset( $user_data['user_grp_ID'] ) )
 642              {    // Set default group
 643                  $user_data['user_grp_ID'] = phpbb_get_var( 'group_default' );
 644              }
 645  
 646              // Add the DB quotes for the user fields

 647              $import_data = array();
 648              foreach( $user_data as $field_value )
 649              {
 650                  $import_data[] = $phpbb_DB->quote( $field_value );
 651              }
 652  
 653              // *** EXECUTE QUERY TO INSERT NEW USER *** //

 654              $user_insert_result = mysql_query( 'INSERT INTO '.$tableprefix.'users ( '.implode( ', ', array_keys( $user_data ) ).' )
 655                      VALUES ( '.implode( ', ', $import_data ).' )',
 656                  $DB->dbhandle );
 657  
 658              if( !$user_insert_result )
 659              {    // User was not inserted
 660                  phpbb_log( sprintf( T_( 'User "%s" with ID %s cannot be imported. MySQL error: %s.' ) , $phpbb_user->username, $phpbb_user->user_id, mysql_error( $DB->dbhandle ) ), 'error', ' ', '<br />' );
 661                  continue;
 662              }
 663  
 664              $user_ID = mysql_insert_id( $DB->dbhandle );
 665  
 666              if( $do_import_avatars )
 667              {    // Import user's avatar
 668                  phpbb_import_avatar( $user_ID, $path_avatars, $phpbb_user->user_avatar );
 669              }
 670  
 671              // Save new inserted ID of the user

 672              $users_IDs[$phpbb_user->user_id] = $user_ID;
 673              if( $user_has_duplicated_email )
 674              {
 675                  $phpbb_emails_duplicated[$phpbb_user->user_email]['user_ID'] = $phpbb_user->user_id;
 676              }
 677  
 678              // Import the user's fields

 679              phpbb_import_user_fields( $phpbb_user, $user_ID );
 680              // Import user's settings

 681              phpbb_import_user_settings( $phpbb_user, $user_ID );
 682  
 683              $phpbb_users_count_imported++;
 684          }
 685  
 686          $page++;
 687      }
 688      while( $phpbb_users_count > 0 );
 689  
 690      // Add temporary table to store the links between user's IDs from phpbb and b2evo tables

 691      phpbb_table_add( 'users' );
 692      phpbb_table_insert_links( 'users', $users_IDs );
 693  
 694      $DB->commit();
 695  
 696      phpbb_set_var( 'users_count_imported', $phpbb_users_count_imported );
 697      phpbb_set_var( 'users_count_updated', $phpbb_users_count_updated );
 698  }
 699  
 700  
 701  /**

 702   * Import users fields from phpbb into b2evo

 703   *

 704   * @param array User data from phpBB

 705   * @param integer New inserted user ID in the b2evo database

 706   */
 707  function phpbb_import_user_fields( $phpbb_user, $b2evo_user_ID )
 708  {
 709      global $DB, $phpbb_DB, $phpbb_cache_b2evo_users_fields;
 710  
 711      if( !isset( $phpbb_cache_b2evo_users_fields ) )
 712      {    // Get users fields from b2evo database
 713          $SQL = new SQL();
 714          $SQL->SELECT( 'ufdf_ID, ufdf_name' );
 715          $SQL->FROM( 'T_users__fielddefs' );
 716          $phpbb_cache_b2evo_users_fields = $DB->get_assoc( $SQL->get() );
 717      }
 718  
 719      if( empty( $phpbb_cache_b2evo_users_fields ) )
 720      {    // No users fields
 721          return;
 722      }
 723  
 724      $fields_links = array(
 725          'rank'      => 'Role',
 726          'icq'       => 'ICQ ID',
 727          'website'   => 'Website',
 728          'aim'       => 'AOL AIM',
 729          'yim'       => 'Yahoo IM',
 730          'msnm'      => 'MSN/Live IM',
 731          'occ'       => 'Role',
 732          'interests' => 'I like',
 733      );
 734  
 735      $fields_types_IDs = array();
 736      foreach( $phpbb_cache_b2evo_users_fields as $field_ID => $field_name )
 737      {
 738          if( $field_link_key = array_search( $field_name, $fields_links ) )
 739          {
 740              $fields_types_IDs[$field_link_key] = $field_ID;
 741          }
 742      }
 743  
 744      if( empty( $fields_types_IDs ) )
 745      {    // No links between phpBB fields and b2evo fields
 746          return;
 747      }
 748  
 749      global $phpbb_cache_phpbb_ranks;
 750  
 751      if( !isset( $phpbb_cache_phpbb_ranks ) )
 752      {    // Get the titles of the user ranks from phpBB
 753          $SQL = new SQL();
 754          $SQL->SELECT( 'rank_id, rank_title' );
 755          $SQL->FROM( 'BB_ranks' );
 756          $phpbb_cache_phpbb_ranks = $phpbb_DB->get_assoc( $SQL->get() );
 757      }
 758  
 759      $import_data = array();
 760      foreach( $fields_types_IDs as $field_type => $field_ID )
 761      {
 762          $field_value = trim( $phpbb_user->{'user_'.$field_type} );
 763          if( $field_type == 'rank' )
 764          {    // If field is "rank" we should get the value from table "phpbb_ranks" by rank_ID
 765              $field_value = !empty( $phpbb_cache_phpbb_ranks[$field_value] ) ? $phpbb_cache_phpbb_ranks[$field_value] : '';
 766          }
 767  
 768          if( $field_value != '' )
 769          {    // field is filled, we can put it into DB
 770              $import_data[] = '( '.
 771                      $DB->quote( $b2evo_user_ID ).', '.
 772                      $DB->quote( $field_ID ).', '.
 773                      $DB->quote( $field_value ).
 774                  ' )';
 775          }
 776      }
 777  
 778      if( count( $import_data ) == 0 )
 779      {    // No data to insert, Exit here
 780          return;
 781      }
 782  
 783      global $tableprefix;
 784  
 785      mysql_query( 'INSERT INTO '.$tableprefix.'users__fields ( uf_user_ID, uf_ufdf_ID, uf_varchar )
 786              VALUES '.implode( ', ', $import_data ),
 787          $DB->dbhandle );
 788  }
 789  
 790  
 791  /**

 792   * Import users settings from phpbb into b2evo

 793   *

 794   * @param array User data from phpBB

 795   * @param integer New inserted user ID in the b2evo database

 796   */
 797  function phpbb_import_user_settings( $phpbb_user, $b2evo_user_ID )
 798  {
 799      global $DB, $tableprefix;
 800  
 801      $settings_links = array(
 802          'allow_viewonline' => 'show_online',
 803          'notify_pm'        => 'notify_messages',
 804          'ip'               => 'created_fromIPv4',
 805      );
 806  
 807      $import_data = array();
 808      foreach( $settings_links as $phpbb_field => $b2evo_field )
 809      {
 810          if( !isset( $phpbb_user->{'user_'.$phpbb_field} ) )
 811          {    // Skip empty value
 812              continue;
 813          }
 814  
 815          $setting_value = trim( $phpbb_user->{'user_'.$phpbb_field} );
 816          if( $phpbb_field == 'ip' )
 817          {
 818              $setting_value = ip2int( $setting_value );
 819          }
 820          $import_data[] = '( '.
 821                  $DB->quote( $b2evo_user_ID ).', '.
 822                  $DB->quote( $b2evo_field ).', '.
 823                  $DB->quote( $setting_value ).
 824              ' )';
 825      }
 826  
 827      if( !empty( $import_data ) )
 828      {    // *** EXECUTE QUERY TO INSERT NEW USERS SETTINGS *** //
 829          mysql_query( 'INSERT INTO '.$tableprefix.'users__usersettings ( uset_user_ID, uset_name, uset_value )
 830                  VALUES '.implode( ', ', $import_data ) ,
 831              $DB->dbhandle );
 832      }
 833  }
 834  
 835  
 836  /**

 837   * Import invalid user (which doesn't exist in DB)

 838   *

 839   * @param integer User ID in DB of phpBB

 840   * @param array Users IDs (users which already imported)

 841   * @param string Username

 842   * @return boolean TRUE on success

 843   */
 844  function phpbb_import_invalid_user( $phpbb_user_ID, & $users_IDs, $phpbb_username = '' )
 845  {
 846      //return false;

 847      $group_invalid_ID = phpbb_get_var( 'group_invalid' );
 848  
 849      if( empty( $group_invalid_ID ) )
 850      {    // If the invalid group ID is empty it means we shouldn't import the invalid users
 851          return false;
 852      }
 853  
 854      if( !isset( $users_IDs[ (string) $phpbb_user_ID ] ) )
 855      {    // If user is not imported yet
 856          global $DB, $tableprefix;
 857  
 858          $user_email = '';
 859          if( !empty( $phpbb_username ) )
 860          {    // If username is defined
 861              $user_login = $phpbb_username;
 862          }
 863          else
 864          {
 865              if( $phpbb_user_ID == '-1' )
 866              {    // Anonymous user
 867                  $user_login = 'anonymous';
 868                  $user_email = 'ano@nymo.us';
 869              }
 870              else
 871              {    // All other users
 872                  $user_login = 'user_'.$phpbb_user_ID;
 873              }
 874          }
 875  
 876          // Check if this user already exists in b2evo DB

 877          $SQL = new SQL();
 878          $SQL->SELECT( 'user_ID' );
 879          $SQL->FROM( 'T_users' );
 880          $SQL->WHERE( 'user_login = '.$DB->quote( $user_login ) );
 881          $b2evo_user_ID = $DB->get_var( $SQL->get() );
 882          if( empty( $b2evo_user_ID ) )
 883          {    // User doesn't exist in DB of b2evo yet, Insert new user
 884              $user_data = array(
 885                      'user_login'            => $DB->quote( $user_login ),
 886                      'user_grp_ID'           => $DB->quote( $group_invalid_ID ),
 887                      'user_pass'             => $DB->quote( '' ),
 888                      'user_email'            => $DB->quote( $user_email ),
 889                      'user_status'           => $DB->quote( 'closed' ),
 890                      'user_locale'           => $DB->quote( 'en-US' ),
 891                  );
 892  
 893              // *** EXECUTE QUERY TO INSERT NEW INVALID USER *** //

 894              $user_insert_result = mysql_query( 'INSERT INTO '.$tableprefix.'users ( '.implode( ', ', array_keys( $user_data ) ).' )
 895                      VALUES ( '.implode( ', ', $user_data ).' )',
 896                  $DB->dbhandle );
 897  
 898              if( !$user_insert_result )
 899              {    // User was not inserted
 900                  phpbb_log( sprintf( T_( 'User "%s" cannot be imported. MySQL error: %s.' ) , $phpbb_user_ID, mysql_error( $DB->dbhandle ) ), 'error', ' ', '<br />' );
 901                  return false;
 902              }
 903  
 904              $b2evo_user_ID = mysql_insert_id( $DB->dbhandle );
 905  
 906              $GroupCache = & get_GroupCache();
 907              $Group = & $GroupCache->get_by_ID( $group_invalid_ID, false );
 908              if( $Group )
 909              {
 910                  phpbb_log( sprintf( T_( 'Created user "%s" in the "%s" group' ) , $user_login, $Group->get( 'name' ) ), 'message', ' ', '<br />' );
 911              }
 912          }
 913  
 914          $users_IDs[ (string) $phpbb_user_ID ] = $b2evo_user_ID;
 915  
 916          phpbb_table_insert_links( 'users', array( $phpbb_user_ID => $b2evo_user_ID ) );
 917  
 918          return true;
 919      }
 920  }
 921  
 922  
 923  /**

 924   * Import the forums

 925   */
 926  function phpbb_import_forums()
 927  {
 928      global $DB, $phpbb_DB;
 929  
 930      if( !phpbb_check_step( 'forums' ) )
 931      {    // Check current step
 932          return; // Exit here if we cannot process this step

 933      }
 934  
 935      phpbb_unset_var( 'forums_count_imported' );
 936  
 937      phpbb_log( T_('Importing forums...') );
 938  
 939      /**

 940       * @var array IDs of the Forums

 941       *        Key is ID from phpBB

 942       *        Value is new inserted ID from b2evo

 943       */
 944      $forums_IDs = array();
 945  
 946      $DB->begin();
 947  
 948      $import_categories = phpbb_get_var( 'import_categories' );
 949      $import_forums = phpbb_get_var( 'import_forums' );
 950  
 951      // Get the categories from phpbb database

 952      $cat_SQL = new SQL();
 953      $cat_SQL->SELECT( 'cat_id AS forum_id, cat_title AS forum_name, "" AS forum_desc, cat_order AS forum_order, NULL AS forum_parent, cat_order AS forum_order, 1 AS forum_meta, 0 AS cat_id, 0 AS forum_lock' );
 954      $cat_SQL->FROM( 'BB_categories' );
 955      if( !empty( $import_categories ) )
 956      {    // Select only these categories
 957          $cat_SQL->WHERE( 'cat_id IN ( '.$phpbb_DB->quote( $import_categories ).' )' );
 958      }
 959      else
 960      {    // If no categories to import
 961          $cat_SQL->WHERE( 'cat_id = -1' );
 962      }
 963  
 964      // Get the forums from phpbb database

 965      $forum_SQL = new SQL();
 966      $forum_SQL->SELECT( 'f.forum_id, f.forum_name, f.forum_desc, f.forum_order, f.forum_parent, f.forum_order, 0 AS forum_meta, f.cat_id, forum_status AS forum_lock' );
 967      $forum_SQL->FROM( 'BB_forums f' );
 968      $forum_SQL->FROM_add( 'LEFT JOIN BB_categories c ON f.cat_id = c.cat_id' );
 969      $forum_SQL->ORDER_BY( 'c.cat_order, f.forum_order' );
 970      if( !empty( $import_forums ) )
 971      {    // Select only these forums
 972          $forum_SQL->WHERE( 'forum_id IN ( '.$phpbb_DB->quote( $import_forums ).' )' );
 973      }
 974      else
 975      {    // If no forums to import
 976          $forum_SQL->WHERE( 'forum_id = -1' );
 977      }
 978  
 979      $phpbb_forums = $phpbb_DB->get_results( '('.$cat_SQL->get().') UNION ('.$forum_SQL->get().')' );
 980  
 981      if( count( $phpbb_forums ) > 0 )
 982      {
 983          phpbb_log( sprintf( T_('%s forums have been found in the phpBB database'), count( $phpbb_forums ) ) );
 984      }
 985      else
 986      {    // No forums
 987          phpbb_log( T_('No found forums in the phpBB database.'), 'error' );
 988          $DB->commit();
 989          return; // Exit here

 990      }
 991  
 992      phpbb_log( T_('Start importing <b>forums</b> as <b>categories</b> into the b2evolution database...') );
 993  
 994      // Insert the new forums

 995      $phpbb_forums_count_imported = 0;
 996      $forums_parents = array();
 997      foreach( $phpbb_forums as $p => $phpbb_forum )
 998      {
 999          $forum_data = array(
1000              'cat_blog_ID'     => $DB->quote( phpbb_get_var( 'blog_ID' ) ),
1001              'cat_name'        => $DB->quote( $phpbb_forum->forum_name ),
1002              'cat_description' => $DB->quote( $phpbb_forum->forum_desc ),
1003              'cat_order'       => $DB->quote( $phpbb_forum->forum_order ),
1004              'cat_urlname'     => $DB->quote( phpbb_unique_urlname( $phpbb_forum->forum_name, 'T_categories', 'cat_urlname' ) ),
1005              'cat_meta'        => $DB->quote( $phpbb_forum->forum_meta ),
1006              'cat_lock'        => $DB->quote( $phpbb_forum->forum_lock )
1007          );
1008  
1009          $DB->query( 'INSERT INTO T_categories ( '.implode( ', ', array_keys( $forum_data ) ).' )
1010              VALUES ( '.implode( ', ', $forum_data ).' )' );
1011  
1012          if( $phpbb_forum->forum_meta == '1' )
1013          {    // Category
1014              $forums_IDs['cat_'.$phpbb_forum->forum_id] = $DB->insert_id;
1015          }
1016          else
1017          {    // Forum
1018              $forums_IDs[$phpbb_forum->forum_id] = $DB->insert_id;
1019          }
1020  
1021          if( isset( $phpbb_forum->forum_parent ) && $phpbb_forum->forum_parent > 0 )
1022          {    // Save parent ID to update it in the next step
1023              $forums_parents[$phpbb_forum->forum_id] = $phpbb_forum->forum_parent;
1024          }
1025          else if( isset( $phpbb_forum->cat_id ) && $phpbb_forum->cat_id > 0 )
1026          {    // First level forum has category as parent
1027              $forums_parents[$phpbb_forum->forum_id] = 'cat_'.$phpbb_forum->cat_id;
1028          }
1029  
1030          phpbb_log( sprintf( T_('The forum "%s" is imported.'), $phpbb_forum->forum_name ) );
1031          $phpbb_forums_count_imported++;
1032      }
1033  
1034      if( count( $forums_parents ) > 0 )
1035      {    // Update the parents IDs
1036          foreach( $forums_parents as $phpbb_forum_ID => $phpbb_parent_ID )
1037          {
1038              if( isset( $forums_IDs[ (string) $phpbb_forum_ID ], $forums_IDs[ (string) $phpbb_parent_ID ] ) )
1039              {
1040                  $DB->query( 'UPDATE T_categories
1041                        SET cat_parent_ID = '.$DB->quote( $forums_IDs[ (string) $phpbb_parent_ID ] ).'
1042                      WHERE cat_ID = '.$DB->quote( $forums_IDs[ (string) $phpbb_forum_ID ] ) );
1043              }
1044          }
1045      }
1046  
1047      // Add temporary table to store the links between forums's IDs from phpbb and b2evo tables

1048      phpbb_table_add( 'forums' );
1049      phpbb_table_insert_links( 'forums', $forums_IDs );
1050  
1051      $DB->commit();
1052  
1053      phpbb_set_var( 'forums_count_imported', $phpbb_forums_count_imported );
1054  }
1055  
1056  /**

1057   * Get the unique url name

1058   *

1059   * @param string Source text

1060   * @param string Table name

1061   * @param string Field name

1062   * @return string category's url name

1063   */
1064  function phpbb_unique_urlname( $source, $table, $field )
1065  {
1066      global $DB;
1067  
1068      // Replace special chars/umlauts, if we can convert charsets:

1069      load_funcs( 'locales/_charset.funcs.php' );
1070      $url_name = strtolower( replace_special_chars( $source ) );
1071  
1072      $url_number = 1;
1073      $url_name_correct = $url_name;
1074      do
1075      {    // Check for unique url name in DB
1076          $SQL = new SQL();
1077          $SQL->SELECT( $field );
1078          $SQL->FROM( $table );
1079          $SQL->WHERE( $field.' = '.$DB->quote( $url_name_correct ) );
1080          $category = $DB->get_var( $SQL->get() );
1081          if( $category )
1082          {    // Category already exists with such url name; Change it
1083              $url_name_correct = $url_name.'-'.$url_number;
1084              $url_number++;
1085          }
1086      }
1087      while( !empty( $category ) );
1088  
1089      return $url_name_correct;
1090  }
1091  
1092  
1093  /**

1094   * Import the topics

1095   */
1096  function phpbb_import_topics()
1097  {
1098      global $DB, $phpbb_DB, $tableprefix;
1099  
1100      if( !phpbb_check_step( 'topics' ) )
1101      {    // Check current step
1102          return; // Exit here if we cannot process this step

1103      }
1104  
1105      $import_forums = phpbb_get_var( 'import_forums' );
1106  
1107      phpbb_log( T_('Importing topics...') );
1108  
1109      /**

1110       * @var array IDs of the Topics;

1111       *        Key is ID from phpBB

1112       *        Value is new inserted ID from b2evo

1113       */
1114      $topics_IDs = array();
1115  
1116      $DB->begin();
1117  
1118      // Init SQL to get the topics data and the count of the topics

1119      $SQL = new SQL();
1120      $SQL->FROM( 'BB_topics t' );
1121      $SQL->FROM_add( 'INNER JOIN BB_posts p ON t.topic_first_post_id = p.post_id' );
1122      $SQL->FROM_add( 'INNER JOIN BB_posts_text pt ON p.post_id = pt.post_id' );
1123      $SQL->WHERE( 't.topic_status != 2' ); // Don't select MOVIED topics

1124      if( !empty( $import_forums ) )
1125      {    // Select the topics only from these forums
1126          $SQL->WHERE_and( 't.forum_id IN ( '.$phpbb_DB->quote( $import_forums ).' )' );
1127      }
1128      else
1129      {    // If no forums to import
1130          $SQL->WHERE_and( 't.forum_id = -1' );
1131      }
1132  
1133      // Get the count of the topics

1134      $count_SQL = $SQL;
1135      $count_SQL->SELECT( 'COUNT( t.topic_id )' );
1136      $phpbb_topics_count = $phpbb_DB->get_var( $count_SQL->get() );
1137  
1138      if( $phpbb_topics_count > 0 )
1139      {
1140          phpbb_log( sprintf( T_('%s topics have been found in the phpBB database'), $phpbb_topics_count ) );
1141      }
1142      else
1143      {    // No topics
1144          phpbb_log( T_('No found topics in the phpBB database.'), 'error' );
1145          $DB->commit();
1146          return; // Exit here

1147      }
1148  
1149      $forums_IDs = phpbb_table_get_links( 'forums' );
1150      $users_IDs = phpbb_table_get_links( 'users' );
1151  
1152      $topic_fields = array(
1153              'post_creator_user_ID',
1154              'post_lastedit_user_ID',
1155              'post_main_cat_ID',
1156              'post_title',
1157              'post_content',
1158              'post_urltitle',
1159              'post_renderers',
1160              'post_datestart',
1161              'post_datecreated',
1162              'post_datemodified',
1163              'post_locale',
1164              'post_status',
1165              'post_comment_status',
1166              'post_featured',
1167              'post_views',
1168              'post_excerpt',
1169              'post_excerpt_autogenerated',
1170              'post_wordcount'
1171          );
1172  
1173      phpbb_log( T_('Start importing <b>topics</b> as <b>posts</b> into the b2evolution database...'), 'message', '' );
1174  
1175      $BlogCache = & get_BlogCache();
1176      $phpbbBlog = & $BlogCache->get_by_ID( phpbb_get_var( 'blog_ID' ) );
1177  
1178      // Init SQL to get the topics

1179      $topics_SQL = $SQL;
1180      $topics_SQL->SELECT( 't.topic_id, t.forum_id, t.topic_time, t.topic_poster, t.topic_title, t.topic_status, t.topic_type, t.topic_views, t.topic_first_post_id,
1181          pt.post_text, pt.bbcode_uid, p.post_username' );
1182      $topics_SQL->ORDER_BY( 't.topic_id' );
1183  
1184      $page = 0;
1185      $page_size = 1000;
1186      $phpbb_topics_count_imported = 0;
1187      do
1188      {    // Split by page to optimize process
1189          // It gives to save the memory rather than if we get all topics by one query without LIMIT clause

1190  
1191          // Get the topics by page

1192          $topics_SQL->LIMIT( ( $page * $page_size ).', '.$page_size );
1193          $phpbb_topics = $phpbb_DB->get_results( $topics_SQL->get() );
1194  
1195          // Insert the new topics

1196          foreach( $phpbb_topics as $p => $phpbb_topic )
1197          {
1198              if( !isset( $forums_IDs[ (string) $phpbb_topic->forum_id ] ) )
1199              {    // The topic has the incorrect forum's ID by some reason
1200                  phpbb_log( sprintf( '<br />'.T_('Skipped topic: %s. Incorrect forum ID: %s. <b>Content:</b> %s'), $phpbb_topic->topic_id, $phpbb_topic->forum_id, substr( $phpbb_topic->post_text, 0, 250 ).' ...' ), 'error' );
1201                  continue;
1202              }
1203  
1204              if( !isset( $users_IDs[ (string) $phpbb_topic->topic_poster ] ) )
1205              {    // The topic has the incorrect user's ID by some reason
1206                  if( !phpbb_import_invalid_user( $phpbb_topic->topic_poster, $users_IDs, $phpbb_topic->post_username ) )
1207                  {    // We cannot create invalid user
1208                      phpbb_log( sprintf( '<br />'.T_('Skipped topic: %s. Incorrect user ID: %s. <b>Content:</b> %s'), $phpbb_topic->topic_id, $phpbb_topic->topic_poster, substr( $phpbb_topic->post_text, 0, 250 ).' ...' ), 'error' );
1209                      continue;
1210                  }
1211              }
1212  
1213              $author_ID = $users_IDs[ (string) $phpbb_topic->topic_poster ];
1214              $forum_ID = $forums_IDs[ (string) $phpbb_topic->forum_id ];
1215              //$canonical_slug = phpbb_unique_urlname( 'topic-'.$phpbb_topic->topic_id, 'T_slug', 'slug_title' );

1216              $canonical_slug = 'topic-'.$phpbb_topic->topic_id;
1217              //$second_slug = phpbb_unique_urlname( 'forumpost-'.$phpbb_topic->topic_first_post_id, 'T_slug', 'slug_title' );

1218              $second_slug = 'forumpost-'.$phpbb_topic->topic_first_post_id;
1219              $post_content = phpbb_decode_bbcode( $phpbb_topic->post_text, $phpbb_topic->bbcode_uid );
1220              $topic_time = date( 'Y-m-d H:i:s', $phpbb_topic->topic_time );
1221  
1222              if( $phpbb_topic->topic_status == '1' )
1223              {    // If topic is closed set comment status - closed
1224                  $post_comment_status = 'closed';
1225              }
1226              elseif( $phpbb_topic->topic_type == '2' )
1227              {    // If topic is "Announcement" set comment status - disabled
1228                  $post_comment_status = 'disabled';
1229              }
1230              else
1231              {    // Comment status is open for all other topics
1232                  $post_comment_status = 'open';
1233              }
1234  
1235              $topic_data = array(
1236                  'post_creator_user_ID'       => $DB->quote( $author_ID ),
1237                  'post_lastedit_user_ID'      => $DB->quote( $author_ID ),
1238                  'post_main_cat_ID'           => $DB->quote( $forum_ID ),
1239                  'post_title'                 => $DB->quote( $phpbb_topic->topic_title),
1240                  'post_content'               => $DB->quote( $post_content ),
1241                  'post_urltitle'              => $DB->quote( $canonical_slug ),
1242                  'post_renderers'             => $DB->quote( 'b2evBBco.b2evALnk.b2WPAutP.evo_code' ),
1243                  'post_datestart'             => $DB->quote( $topic_time ),
1244                  'post_datecreated'           => $DB->quote( $topic_time ),
1245                  'post_datemodified'          => $DB->quote( $topic_time ),
1246                  'post_locale'                => $DB->quote( $phpbbBlog->get( 'locale' ) ),
1247                  'post_status'                => $DB->quote( 'published' ),
1248                  'post_comment_status'        => $DB->quote( $post_comment_status ),
1249                  'post_featured'              => $DB->quote( $phpbb_topic->topic_type > 0 ? '1' : '0' ),
1250                  'post_views'                 => $DB->quote( $phpbb_topic->topic_views ),
1251                  'post_excerpt'               => $DB->quote( phpbb_generate_excerpt( $post_content ) ),
1252                  'post_excerpt_autogenerated' => $DB->quote( '1' ),
1253                  'post_wordcount'             => $DB->quote( bpost_count_words( $post_content ) ),
1254              );
1255  
1256              // *** EXECUTE QUERY TO INSERT NEW POST *** //

1257              mysql_query( 'INSERT INTO '.$tableprefix.'items__item ( '.implode( ', ', $topic_fields ).' )
1258                      VALUES ( '.implode( ', ', $topic_data ).' )',
1259                  $DB->dbhandle );
1260  
1261              $item_ID = mysql_insert_id( $DB->dbhandle );
1262  
1263              $topics_IDs[$phpbb_topic->topic_id] = $item_ID;
1264  
1265              // Insert a link with a forum(category)

1266              mysql_query( 'INSERT INTO '.$tableprefix.'postcats ( postcat_post_ID, postcat_cat_ID )
1267                      VALUES ( '.$DB->quote( $item_ID ).', '.$DB->quote( $forum_ID ).' )',
1268                  $DB->dbhandle );
1269  
1270              // Insert a canonical and second slugs for the post

1271              mysql_query( 'INSERT INTO '.$tableprefix.'slug ( slug_title, slug_type, slug_itm_ID ) VALUES
1272                      ( '.$DB->quote( $canonical_slug ).', '.$DB->quote( 'item' ).', '.$DB->quote( $item_ID ).' ),
1273                      ( '.$DB->quote( $second_slug ).', '.$DB->quote( 'item' ).', '.$DB->quote( $item_ID ).' )',
1274                  $DB->dbhandle );
1275              $canonical_slug_ID = mysql_insert_id( $DB->dbhandle );
1276  
1277              // Insert a tiny slug for the post

1278              /*

1279              load_funcs( 'slugs/model/_slug.funcs.php' );

1280              $DB->query( 'INSERT INTO T_slug ( slug_title, slug_type, slug_itm_ID )

1281                  VALUES ( '.$DB->quote( getnext_tinyurl() ).', '.$DB->quote( 'item' ).', '.$DB->quote( $item_ID ).' )' );

1282              $tiny_slug_ID = $DB->insert_id;*/
1283  
1284              // Update the slug's IDs of the post

1285              mysql_query( 'UPDATE '.$tableprefix.'items__item
1286                        SET post_canonical_slug_ID = '.$DB->quote( $canonical_slug_ID )/*.', post_tiny_slug_ID = '.$DB->quote( $tiny_slug_ID )*/.'
1287                      WHERE post_ID = '.$DB->quote( $item_ID ),
1288                  $DB->dbhandle );
1289  
1290              $phpbb_topics_count_imported++;
1291  
1292              if( $phpbb_topics_count_imported % 100 == 0 )
1293              {    // Display the processing dots after 500 topics
1294                  phpbb_log( ' .', 'message', '' );
1295              }
1296          }
1297  
1298          $page++;
1299      }
1300      while( count( $phpbb_topics ) > 0 );
1301  
1302      // Add temporary table to store the links between topics's IDs from phpbb and b2evo tables

1303      phpbb_table_add( 'topics' );
1304      phpbb_table_insert_links( 'topics', $topics_IDs );
1305  
1306      $DB->commit();
1307  
1308      phpbb_set_var( 'topics_count_imported', $phpbb_topics_count_imported );
1309  }
1310  
1311  
1312  /**

1313   * Generate the excerpt for post

1314   *

1315   * @param string

1316   * @return string

1317   */
1318  function phpbb_generate_excerpt( $content )
1319  {
1320      $content = trim( strip_tags( $content ) );
1321      return strmaxlen( $content, 254, '&hellip;' );
1322  }
1323  
1324  
1325  /**

1326   * Decode html tags from bbcode string

1327   *

1328   * @param string Encoded string

1329   * @param string bbcode ID

1330   * @return string Decoded string

1331   */
1332  function phpbb_decode_bbcode( $string, $bbcode_uid )
1333  {
1334      /**** These lines were commented after plugin 'BB code' was installed by default ****

1335  

1336      $bbcode_patterns = array(

1337              '[b:'.$bbcode_uid.']', '[/b:'.$bbcode_uid.']',

1338              '[u:'.$bbcode_uid.']', '[/u:'.$bbcode_uid.']',

1339              '[i:'.$bbcode_uid.']', '[/i:'.$bbcode_uid.']',

1340              '[code:1:'.$bbcode_uid.']', '[/code:1:'.$bbcode_uid.']',

1341              '[code:'.$bbcode_uid.']', '[/code:'.$bbcode_uid.']',

1342              '[php:1:'.$bbcode_uid.']', '[/php:1:'.$bbcode_uid.']',

1343              '[quote:'.$bbcode_uid.']', '[/quote:'.$bbcode_uid.']',

1344              '[list:'.$bbcode_uid.'][*:'.$bbcode_uid.']', '[/list:u:'.$bbcode_uid.']',

1345              '[list=([a1]):'.$bbcode_uid.'][*:'.$bbcode_uid.']', '[/list:o:'.$bbcode_uid.']',

1346              '[*:'.$bbcode_uid.']',

1347              '[/color:'.$bbcode_uid.']',

1348              '[/size:'.$bbcode_uid.']'

1349          );

1350      $bbcode_encoded_tags = array(

1351              '<b>', '</b>',

1352              '<u>', '</u>',

1353              '<i>', '</i>',

1354              '<pre>', '</pre>',

1355              '<pre>', '</pre>',

1356              '<pre>', '</pre>',

1357              '<blockquote>', '</blockquote>',

1358              '<ul><li>', '</li></ul>',

1359              '<ol><li>', '</li></ol>',

1360              '</li><li>',

1361              '</span>',

1362              '</span>'

1363          );

1364  

1365      $string = str_replace( $bbcode_patterns, $bbcode_encoded_tags, $string );

1366  

1367      if( strpos( $string, '[' ) !== false )

1368      {    // Replace complex bbcoded tags

1369          $bbcode_patterns = array(

1370                  '/\[quote:'.$bbcode_uid.'="(.+)"\]/si',

1371                  '/\[url=(.+)\](.+)\[\/url\]/si',

1372                  '/\[url\](.+)\[\/url\]/si',

1373                  '/\[img:'.$bbcode_uid.'\](.+)\[\/img:'.$bbcode_uid.'\]/si',

1374                  '/\[color=(\#[0-9A-F]{6}|[a-z]+):'.$bbcode_uid.'\]/si',

1375                  '/\[size=([1-2]?[0-9]):'.$bbcode_uid.'\]/si',

1376                  '/\[email\]([a-z0-9&\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+)\[\/email\]/si',

1377                  '/\[list=([a1]):$uid\]/si'

1378              );

1379          $bbcode_encoded_tags = array(

1380                  '<blockquote><b>$1:</b><br />',

1381                  '<a href="$1" target="_blank">$2</a>',

1382                  '<a href="$1" target="_blank">$1</a>',

1383                  '<img src="$1" />',

1384                  '<span style="color: $1">',

1385                  '<span style="font-size: $1px">',

1386                  '<a href="mailto:$1">$1</a>',

1387                  '<ol type="$1">'

1388              );

1389          $string = preg_replace( $bbcode_patterns, $bbcode_encoded_tags, $string );

1390      }

1391  

1392      ****/
1393  
1394      $bbcode_patterns = array(
1395              '[code:1:'.$bbcode_uid.']', '[/code:1:'.$bbcode_uid.']',
1396              '[code:'.$bbcode_uid.']', '[/code:'.$bbcode_uid.']',
1397              '[php:1:'.$bbcode_uid.']', '[/php:1:'.$bbcode_uid.']',
1398          );
1399      $bbcode_encoded_tags = array(
1400              '<!-- codeblock lang="" line="1" --><pre><code>', '</code></pre><!-- /codeblock -->',
1401              '<!-- codeblock lang="" line="1" --><pre><code>', '</code></pre><!-- /codeblock -->',
1402              '<!-- codeblock lang="php" line="1" --><pre><code>', '</code></pre><!-- /codeblock -->',
1403          );
1404  
1405      $string = str_replace( $bbcode_patterns, $bbcode_encoded_tags, $string );
1406  
1407      if( strpos( $string, '[' ) !== false )
1408      {    // Replace complex bbcoded tags
1409          $bbcode_patterns = array(
1410                  '/\[url\]([^\1]+?)\[\/url\]/si',
1411                  '/\[quote:([a-z0-9]+)="([^"]+)"\]/si',
1412                  '/\[img([:a-z0-9]*?)\]([^\1]+?)\[\/img([:a-z0-9]*?)\]/si',
1413              );
1414          $bbcode_encoded_tags = array(
1415                  '$1',
1416                  '[quote=@$2]',
1417                  '$2'
1418              );
1419          $string = preg_replace( $bbcode_patterns, $bbcode_encoded_tags, $string );
1420      }
1421  
1422      // We should remove bbcode_uid because plugin 'BB code' doesn't work with UID

1423      $string = str_replace( ':'.$bbcode_uid.']', ']', $string );
1424  
1425      // $string = nl2br( $string );

1426  
1427      return $string;
1428  }
1429  
1430  
1431  /**

1432   * Import the replies

1433   */
1434  function phpbb_import_replies()
1435  {
1436      global $DB, $phpbb_DB, $tableprefix;
1437  
1438      if( !phpbb_check_step( 'replies' ) )
1439      {    // Check current step
1440          return; // Exit here if we cannot process this step

1441      }
1442  
1443      $import_forums = phpbb_get_var( 'import_forums' );
1444  
1445      // Reset previous value

1446      phpbb_unset_var( 'replies_count_imported' );
1447  
1448      phpbb_log( T_('Importing replies...') );
1449  
1450      $DB->begin();
1451  
1452      // Init SQL to get the replies data and the count of the replies

1453      $SQL = new SQL();
1454      $SQL->FROM( 'BB_posts p' );
1455      $SQL->FROM_add( 'LEFT JOIN BB_posts_text pt ON p.post_id = pt.post_id' );
1456      //$SQL->FROM_add( 'LEFT JOIN BB_topics t ON p.post_id = t.topic_first_post_id' );

1457      //$SQL->WHERE( 't.topic_id IS NULL' );

1458      if( !empty( $import_forums ) )
1459      {    // Select the replies only from these forums
1460          $SQL->WHERE( 'p.forum_id IN ( '.$phpbb_DB->quote( $import_forums ).' )' );
1461      }
1462      else
1463      {    // If no forums to import
1464          $SQL->WHERE( 'p.forum_id = -1' );
1465      }
1466      //$SQL->WHERE_and( 'p.post_id NOT IN ( SELECT topic_first_post_id FROM BB_topics )' );

1467  
1468      // Get the count of the replies

1469      $count_SQL = $SQL;
1470      $count_SQL->SELECT( 'COUNT( p.post_id )' );
1471      $phpbb_replies_count = $phpbb_DB->get_var( $count_SQL->get() );
1472  
1473      if( $phpbb_replies_count > 0 )
1474      {
1475          phpbb_log( sprintf( T_('%s post have been found in the phpBB database, %s of which are replies'), $phpbb_replies_count, $phpbb_replies_count - (int)phpbb_get_var( 'topics_count_imported' ) ) );
1476      }
1477      else
1478      {    // No replies
1479          phpbb_log( T_('No found replies in the phpBB database.'), 'error' );
1480          $DB->commit();
1481          return; // Exit here

1482      }
1483  
1484      $users_IDs = phpbb_table_get_links( 'users' );
1485      $topics_IDs = phpbb_table_get_links( 'topics' );
1486  
1487      $comment_fields = array(
1488              'comment_post_ID',
1489              'comment_author_ID',
1490              'comment_date',
1491              'comment_author_IP',
1492              'comment_author',
1493              'comment_content',
1494              'comment_renderers',
1495          );
1496  
1497      phpbb_log( T_('Start importing <b>replies</b> as <b>comments</b> into the b2evolution database...'), 'message', '' );
1498  
1499      $BlogCache = & get_BlogCache();
1500      $phpbbBlog = & $BlogCache->get_by_ID( phpbb_get_var( 'blog_ID' ) );
1501  
1502  
1503      // Init SQL to get the replies from phpbb database

1504      $SQL = $SQL;
1505      $SQL->SELECT( 'p.post_id, p.topic_id, p.post_time, p.post_edit_time, p.poster_id, p.poster_ip, p.post_username, pt.post_text, pt.bbcode_uid' );
1506      $SQL->ORDER_BY( 'p.post_id' );
1507  
1508      $page = 0;
1509      $page_size = 1000;
1510      $phpbb_replies_count_imported = 0;
1511      $comments_import_data = array();
1512      $comments_slugs_import_data = array();
1513      do
1514      {    // Split by page to optimize process
1515          // It gives to save the memory rather than if we get all replies by one query without LIMIT clause

1516  
1517          // Get the replies from phpbb database by page

1518          $SQL->LIMIT( ( $page * $page_size ).', '.$page_size );
1519          $phpbb_replies = $phpbb_DB->get_results( $SQL->get() );
1520  
1521          // Insert the new replies

1522          foreach( $phpbb_replies as $p => $phpbb_reply )
1523          {
1524              if( phpbb_post_is_topic( $phpbb_reply->post_id ) )
1525              {    // This post is a content of the topic
1526                  // It is first post; for b2evo this post is Item, not Comment

1527                  // Do NOT import this post as Comment

1528                  //phpbb_log( sprintf( '<br />'.T_('Skipped reply: %s. The reply is first post of the topic. <b>Content:</b> %s'), $phpbb_reply->post_id, substr( $phpbb_reply->post_text, 0, 250 ).' ...' ), 'error' );

1529                  continue;
1530              }
1531  
1532              if( !isset( $topics_IDs[ (string) $phpbb_reply->topic_id ] ) )
1533              {    // The reply has the incorrect topic's ID by some reason
1534                  phpbb_log( sprintf( '<br />'.T_('Skipped reply: %s. Incorrect topic ID: %s. <b>Content:</b> %s'), $phpbb_reply->post_id, $phpbb_reply->topic_id, substr( $phpbb_reply->post_text, 0, 250 ).' ...' ), 'error' );
1535                  continue;
1536              }
1537  
1538              if( $phpbb_reply->poster_id == '-1' )
1539              {    // Comment from anonymous user
1540                  $author_ID = 'NULL';
1541                  $author_name = $DB->quote( $phpbb_reply->post_username );
1542              }
1543              else if( isset( $users_IDs[ (string) $phpbb_reply->poster_id ] ) )
1544              {    // Author is registered user
1545                  $author_ID = $DB->quote( $users_IDs[ (string) $phpbb_reply->poster_id ] );
1546                  $author_name = 'NULL';
1547              }
1548              else
1549              {    // Incorrect user ID, Do NOT import this reply
1550                  if( !phpbb_import_invalid_user( $phpbb_reply->poster_id, $users_IDs, $phpbb_reply->post_username ) )
1551                  {    // We cannot create invalid user
1552                      phpbb_log( sprintf( '<br />'.T_('Skipped reply: %s. Incorrect user ID: %s. <b>Content:</b> %s'), $phpbb_reply->post_id, $phpbb_reply->poster_id, substr( $phpbb_reply->post_text, 0, 250 ).' ...' ), 'error' );
1553                      continue;
1554                  }
1555              }
1556  
1557              $comment_data = array(
1558                  'comment_post_ID'   => $DB->quote( $topics_IDs[ (string) $phpbb_reply->topic_id ] ),
1559                  'comment_author_ID' => $author_ID,
1560                  'comment_date'      => $DB->quote( date( 'Y-m-d H:i:s', $phpbb_reply->post_time ) ),
1561                  'comment_author_IP' => $DB->quote( phpbb_decode_ip( $phpbb_reply->poster_ip ) ),
1562                  'comment_author'    => $author_name,
1563                  'comment_content'   => $DB->quote( phpbb_decode_bbcode( $phpbb_reply->post_text, $phpbb_reply->bbcode_uid ) ),
1564                  'comment_renderers' => $DB->quote( 'b2evBBco.b2evALnk.b2WPAutP.evo_code' ),
1565              );
1566  
1567              $comments_import_data[] = '( '.implode( ', ', $comment_data ).' )';
1568  
1569              $comments_slugs_import_data[] = '( '.$DB->quote( 'forumpost-'.$phpbb_reply->post_id ).', '.$DB->quote( 'item' ).', '.$DB->quote( $topics_IDs[ (string) $phpbb_reply->topic_id ] ).' )';
1570  
1571              if( count( $comments_import_data ) == 100 )
1572              {    // Insert the 100 comments in one query
1573                  // *** EXECUTE QUERY TO INSERT NEW COMMENTS *** //

1574                  $comment_insert_result = mysql_query( 'INSERT INTO '.$tableprefix.'comments ( '.implode( ', ', $comment_fields ).' )
1575                          VALUES '.implode( ', ', $comments_import_data ),
1576                      $DB->dbhandle );
1577                  if( !$comment_insert_result )
1578                  {    // Some errors
1579                      phpbb_log( '<br />'.sprintf( T_( 'MySQL error: %s.' ) , mysql_error( $DB->dbhandle ) ), 'error', ' ' );
1580                  }
1581                  $comments_import_data = array();
1582  
1583                  // Insert the slugs for the replies

1584                  mysql_query( 'INSERT INTO '.$tableprefix.'slug ( slug_title, slug_type, slug_itm_ID )
1585                          VALUES '.implode( ', ', $comments_slugs_import_data ),
1586                      $DB->dbhandle );
1587                  $comments_slugs_import_data = array();
1588              }
1589  
1590              $phpbb_replies_count_imported++;
1591  
1592              if( $phpbb_replies_count_imported % 1000 == 0 )
1593              {    // Display the processing dots after 1000 topics
1594                  phpbb_log( ' .', 'message', '' );
1595              }
1596          }
1597  
1598          $page++;
1599      }
1600      while( count( $phpbb_replies ) > 0 );
1601  
1602      if( count( $comments_import_data ) > 0 )
1603      {    // Insert the rest comments
1604          // *** EXECUTE QUERY TO INSERT NEW COMMENTS *** //

1605          $comment_insert_result = mysql_query( 'INSERT INTO '.$tableprefix.'comments ( '.implode( ', ', $comment_fields ).' )
1606                  VALUES '.implode( ', ', $comments_import_data ),
1607              $DB->dbhandle );
1608          if( !$comment_insert_result )
1609          {    // Some errors
1610              phpbb_log( sprintf( T_( 'MySQL error: %s.' ) , mysql_error( $DB->dbhandle ) ), 'error', ' ', '<br />' );
1611          }
1612  
1613          // Insert the slugs for the replies

1614          mysql_query( 'INSERT INTO '.$tableprefix.'slug ( slug_title, slug_type, slug_itm_ID )
1615                  VALUES '.implode( ', ', $comments_slugs_import_data ),
1616              $DB->dbhandle );
1617      }
1618  
1619      $DB->commit();
1620  
1621      phpbb_set_var( 'replies_count_imported', $phpbb_replies_count_imported );
1622  }
1623  
1624  /**

1625   * Decode IP address from phpBB database

1626   *

1627   * @param string IP encoded

1628   * @return string IP decoded

1629   */
1630  function phpbb_decode_ip( $int_ip )
1631  {
1632      $hexipbang = explode( '.', chunk_split( $int_ip, 2, '.' ) );
1633      return hexdec( $hexipbang[0] ).'.'.hexdec( $hexipbang[1] ).'.'.hexdec( $hexipbang[2] ).'.'.hexdec( $hexipbang[3] );
1634  }
1635  
1636  
1637  /**

1638   * Check if the post is a topic

1639   *

1640   * @param string post ID

1641   * @return boolean TRUE if the post is a topic

1642  */
1643  function phpbb_post_is_topic( $post_id )
1644  {
1645      global $phpbb_cache_topics_posts;
1646  
1647      if( isset( $phpbb_cache_topics_posts ) )
1648      {    // Get result from cache
1649          return isset( $phpbb_cache_topics_posts[ (string) $post_id ] );
1650      }
1651  
1652      global $phpbb_DB;
1653      $phpbb_db_config = phpbb_get_var( 'db_config' );
1654  
1655      // Get result from DB first time

1656      $SQL = new SQL();
1657      $SQL->SELECT( 'topic_first_post_id, topic_id' );
1658      $SQL->FROM( $phpbb_db_config['prefix'].'topics' );
1659      $SQL->WHERE( 'topic_status != 2' ); // Don't select MOVIED topics

1660  
1661      $phpbb_cache_topics_posts = array();
1662      $query = mysql_query( $SQL->get(), $phpbb_DB->dbhandle );
1663      while( $tp_row = mysql_fetch_assoc( $query ) )
1664      {
1665          $phpbb_cache_topics_posts[ $tp_row['topic_first_post_id'] ] = $tp_row['topic_id'];
1666      }
1667  
1668      return isset( $phpbb_cache_topics_posts[ (string) $post_id ] );
1669  }
1670  
1671  
1672  /**

1673   * Import the messages

1674   */
1675  function phpbb_import_messages()
1676  {
1677      global $DB, $phpbb_DB, $tableprefix;
1678  
1679      if( !phpbb_check_step( 'messages' ) )
1680      {    // Check current step
1681          return; // Exit here if we cannot process this step

1682      }
1683  
1684      // Reset previous value

1685      phpbb_unset_var( 'messages_count_imported' );
1686  
1687      phpbb_log( T_('Importing messages...') );
1688  
1689      $DB->begin();
1690  
1691      // Init SQL to get the messages data and the count of the messages

1692      $SQL = new SQL();
1693      $SQL->FROM( 'BB_privmsgs m' );
1694      $SQL->FROM_add( 'LEFT JOIN BB_privmsgs_text mt ON m.privmsgs_id = mt.privmsgs_text_id' );
1695  
1696      // Get the count of the messages

1697      $count_SQL = $SQL;
1698      $count_SQL->SELECT( 'COUNT( m.privmsgs_id )' );
1699      $phpbb_messages_count = $phpbb_DB->get_var( $count_SQL->get() );
1700  
1701      if( $phpbb_messages_count > 0 )
1702      {
1703          phpbb_log( sprintf( T_('%s messages have been found in the phpBB database'), $phpbb_messages_count ) );
1704      }
1705      else
1706      {    // No messages
1707          phpbb_log( T_('No found messages in the phpBB database.'), 'error' );
1708          $DB->commit();
1709          return; // Exit here

1710      }
1711  
1712      $users_IDs = phpbb_table_get_links( 'users' );
1713  
1714      phpbb_log( T_('Start importing <b>private messages</b> into the b2evolution database...'), 'message', '' );
1715  
1716      // Init SQL to get the messages from phpbb database

1717      $SQL->SELECT( 'm.privmsgs_id, m.privmsgs_subject, mt.privmsgs_text, m.privmsgs_date, m.privmsgs_from_userid, m.privmsgs_to_userid, mt.privmsgs_bbcode_uid' );
1718      $SQL->WHERE( 'm.privmsgs_subject NOT LIKE \'Re: %\' ' );
1719      $SQL->ORDER_BY( 'm.privmsgs_date' );
1720      $SQL->GROUP_BY( 'm.privmsgs_from_userid, m.privmsgs_to_userid, m.privmsgs_date' );
1721  
1722      $page = 0;
1723      $page_size = 100;
1724      $phpbb_messages_count_imported = 0;
1725      $phpbb_missing_users = 0;
1726      do
1727      {    // Split by page to optimize process
1728          // It gives to save the memory rather than if we get all replies by one query without LIMIT clause

1729  
1730          // Get the messages from phpbb database

1731          $SQL->LIMIT( ( $page * $page_size ).', '.$page_size );
1732          $phpbb_messages = $phpbb_DB->get_results( $SQL->get() );
1733  
1734          foreach( $phpbb_messages as $message )
1735          {
1736              if( !isset( $users_IDs[ (string) $message->privmsgs_from_userid ] ) )
1737              {    // The message has the incorrect user's ID by some reason
1738                  /*if( !phpbb_import_invalid_user( $message->privmsgs_from_userid, $users_IDs ) )

1739                  {    // We cannot create invalid user

1740                      phpbb_log( sprintf( '<br />'.T_('Skipped message: %s. Incorrect user ID: %s. <b>Content:</b> %s'), $message->privmsgs_id, $message->privmsgs_from_userid, substr( $message->privmsgs_subject, 0, 250 ).' ...' ), 'error' );

1741                      continue;

1742                  }*/
1743                  $phpbb_missing_users++;
1744                  //phpbb_log( sprintf( '<br />'.T_('Skipped message: %s. Incorrect sender user ID: %s. <b>Content:</b> %s'), $message->privmsgs_id, $message->privmsgs_from_userid, substr( $message->privmsgs_subject, 0, 250 ).' ...' ), 'error', ' ' );

1745                  continue;
1746              }
1747              if( !isset( $users_IDs[ (string) $message->privmsgs_to_userid ] ) )
1748              {    // The message has the incorrect user's ID by some reason
1749                  $phpbb_missing_users++;
1750                  //phpbb_log( sprintf( '<br />'.T_('Skipped message: %s. Incorrect reciever user ID: %s. <b>Content:</b> %s'), $message->privmsgs_id, $message->privmsgs_to_userid, substr( $message->privmsgs_subject, 0, 250 ).' ...' ), 'error', ' ' );

1751                  continue;
1752              }
1753  
1754              mysql_query( 'INSERT INTO '.$tableprefix.'messaging__thread ( thrd_title, thrd_datemodified )
1755                      VALUES ( '.$DB->quote( $message->privmsgs_subject ).', '.$DB->quote( date( 'Y-m-d H:i:s', $message->privmsgs_date ) ).' )',
1756                  $DB->dbhandle );
1757  
1758              $thread_ID = mysql_insert_id( $DB->dbhandle );
1759  
1760              // Import all messages from this thread

1761              $count_messages = phpbb_import_messages_texts( $thread_ID, $message );
1762  
1763              $phpbb_messages_count_imported += $count_messages;
1764  
1765              if( $phpbb_messages_count_imported % 1000 == 0 )
1766              {    // Display the processing dots after 1000 topics
1767                  phpbb_log( ' .', 'message', '' );
1768              }
1769          }
1770  
1771          $page++;
1772      }
1773      while( count( $phpbb_messages ) > 0 );
1774  
1775      $DB->commit();
1776  
1777      phpbb_set_var( 'messages_count_imported', $phpbb_messages_count_imported );
1778      phpbb_set_var( 'messages_count_missing_users', $phpbb_missing_users );
1779  }
1780  
1781  
1782  /**

1783   * Import all messages from the thread

1784   *

1785   * @param integer Thread ID

1786   * @param array Message

1787   * @return integer Number of the imported messaqes

1788   */
1789  function phpbb_import_messages_texts( $thread_ID, $message )
1790  {
1791      global $DB, $phpbb_DB, $tableprefix;
1792  
1793      $SQL = new SQL();
1794      $SQL->SELECT( 'm.privmsgs_subject, mt.privmsgs_text, m.privmsgs_date, m.privmsgs_from_userid, m.privmsgs_to_userid, mt.privmsgs_bbcode_uid' );
1795      $SQL->FROM( 'BB_privmsgs m' );
1796      $SQL->FROM_add( 'LEFT JOIN BB_privmsgs_text mt ON m.privmsgs_id = mt.privmsgs_text_id' );
1797      $SQL->WHERE( 'm.privmsgs_subject = '.$DB->quote( 'Re: '.$message->privmsgs_subject ) );
1798      $SQL->WHERE_and( 'm.privmsgs_from_userid IN ( '.$DB->quote( $message->privmsgs_from_userid ).', '.$DB->quote( $message->privmsgs_to_userid ).' )' );
1799      $SQL->WHERE_and( 'm.privmsgs_to_userid IN ( '.$DB->quote( $message->privmsgs_from_userid ).', '.$DB->quote( $message->privmsgs_to_userid ).' )' );
1800      $SQL->ORDER_BY( 'm.privmsgs_date' );
1801      $SQL->GROUP_BY( 'm.privmsgs_from_userid, m.privmsgs_to_userid, m.privmsgs_date' );
1802      $phpbb_messages = $phpbb_DB->get_results( $SQL->get() );
1803  
1804      $phpbb_messages = array_merge( $phpbb_messages, array( $message ) );
1805  
1806      $users_IDs = phpbb_table_get_links( 'users' );
1807  
1808      $message_import_data = array();
1809      $threadstatus_import_data = array();
1810      foreach( $phpbb_messages as $message )
1811      {
1812          if( !isset( $users_IDs[ $message->privmsgs_from_userid ] ) || !isset( $users_IDs[ $message->privmsgs_to_userid ] ) )
1813          {    // No users
1814              continue;
1815          }
1816  
1817          $message_import_data[] = '( '.
1818                  $DB->quote( $users_IDs[ $message->privmsgs_from_userid ] ).', '.
1819                  $DB->quote( date( 'Y-m-d H:i:s', $message->privmsgs_date ) ).', '.
1820                  $DB->quote( $thread_ID ).', '.
1821                  $DB->quote( phpbb_decode_bbcode( $message->privmsgs_text, $message->privmsgs_bbcode_uid ) ).
1822              ' )';
1823          $threadstatus_import_data[ $message->privmsgs_to_userid ] = '( '.
1824                  $DB->quote( $thread_ID ).', '.
1825                  $DB->quote( $users_IDs[ $message->privmsgs_to_userid ] ).', '.
1826                  'NULL'.
1827              ' )';
1828          $threadstatus_import_data[ $message->privmsgs_from_userid ] = '( '.
1829                  $DB->quote( $thread_ID ).', '.
1830                  $DB->quote( $users_IDs[ $message->privmsgs_from_userid ] ).', '.
1831                  'NULL'.
1832              ' )';
1833      }
1834  
1835      mysql_query( 'INSERT INTO '.$tableprefix.'messaging__message ( msg_author_user_ID, msg_datetime, msg_thread_ID, msg_text )
1836              VALUES '.implode( ', ', $message_import_data ),
1837          $DB->dbhandle );
1838  
1839      mysql_query( 'INSERT INTO '.$tableprefix.'messaging__threadstatus ( tsta_thread_ID, tsta_user_ID, tsta_first_unread_msg_ID )
1840              VALUES '.implode( ', ', $threadstatus_import_data ),
1841          $DB->dbhandle );
1842  
1843      return count( $message_import_data );
1844  }
1845  
1846  
1847  /**

1848   * Clear all temporary data which are used during import

1849   */
1850  function phpbb_clear_temporary_data()
1851  {
1852      // Delete DB tables

1853      phpbb_table_delete( 'users' );
1854      phpbb_table_delete( 'forums' );
1855      phpbb_table_delete( 'topics' );
1856  
1857      // Delete the session variables

1858      phpbb_unset_var( 'blog_ID' );
1859      phpbb_unset_var( 'group_default' );
1860      phpbb_unset_var( 'all_group_default' );
1861      phpbb_unset_var( 'users_count_imported' );
1862      phpbb_unset_var( 'users_count_updated' );
1863      phpbb_unset_var( 'forums_count_imported' );
1864      phpbb_unset_var( 'topics_count_imported' );
1865      phpbb_unset_var( 'replies_count_imported' );
1866      phpbb_unset_var( 'messages_count_imported' );
1867  }
1868  
1869  
1870  /**

1871   * Display forums of phpBB to select what to import

1872   *

1873   * @param object Form

1874   */
1875  function phpbb_forums_list( & $Form )
1876  {
1877      global $phpbb_DB, $phpbb_subforums_list_level;
1878  
1879      $phpbb_DB->begin();
1880  
1881      // Get the categories from phpbb database

1882      $cats_SQL = new SQL();
1883      $cats_SQL->SELECT( 'cat_id, cat_title' );
1884      $cats_SQL->FROM( 'BB_categories' );
1885      $cats_SQL->ORDER_BY( 'cat_order' );
1886      $categories = $phpbb_DB->get_results( $cats_SQL->get() );
1887  
1888      $import_categories = phpbb_get_var( 'import_categories' );
1889      foreach( $categories as $category )
1890      {
1891          $Form->checkbox_input( 'phpbb_categories[]', !is_array( $import_categories ) || in_array( $category->cat_id, $import_categories ), '', array(
1892                  'input_prefix' => '<label>',
1893                  'input_suffix' => ' '.$category->cat_title.'</label>',
1894                  'value' => $category->cat_id
1895              ) );
1896  
1897          // Display forums

1898          $phpbb_subforums_list_level = 0;
1899          phpbb_subforums_list( $Form, $category->cat_id );
1900      }
1901  
1902      $phpbb_DB->commit();
1903  
1904      echo '<script type="text/javascript">
1905      /* <![CDATA[ */

1906      jQuery( document ).ready( function()
1907      {
1908          jQuery( "input[name^=phpbb_categories]" ).click( function()
1909          {
1910              if( jQuery( "div.phpbb_forums_" + jQuery( this ).val() + "_0" ).length > 0 )
1911              {    // Check/Uncheck child forums
1912                  if( jQuery( this ).is( ":checked" ) )
1913                  {
1914                      jQuery( "div.phpbb_forums_" + jQuery( this ).val() + "_0 input[type=checkbox]" ).attr( "checked", "checked" );
1915                  }
1916                  else
1917                  {
1918                      jQuery( "div.phpbb_forums_" + jQuery( this ).val() + "_0 input[type=checkbox]" ).removeAttr( "checked" );
1919                  }
1920              }
1921          } );
1922  
1923          jQuery( "input[name^=phpbb_forums]" ).click( function()
1924          {
1925              if( jQuery( "div.phpbb_forums_0_" + jQuery( this ).val() ).length > 0 )
1926              {    // Check/Uncheck child forums
1927                  if( jQuery( this ).is( ":checked" ) )
1928                  {
1929                      jQuery( "div.phpbb_forums_0_" + jQuery( this ).val() + " input[type=checkbox]" ).attr( "checked", "checked" );
1930                  }
1931                  else
1932                  {
1933                      jQuery( "div.phpbb_forums_0_" + jQuery( this ).val() + " input[type=checkbox]" ).removeAttr( "checked" );
1934                  }
1935              }
1936  
1937              if( jQuery( this ).is( ":checked" ) )
1938              {    // Check parent forums
1939                  jQuery( this ).parents( "div[class^=phpbb_forums_]" ).prev().find( "input[type=checkbox]" ).attr( "checked", "checked" );
1940              }
1941          } );
1942      } );
1943      /* ]]> */

1944      </script>';
1945  }
1946  
1947  
1948  /**

1949   * Display subforums to select what to import

1950   *

1951   * @param object Form

1952   * @param integer Category ID

1953   * @param integer Forum parent ID

1954   */
1955  function phpbb_subforums_list( & $Form, $cat_id, $forum_parent_id = 0 )
1956  {
1957      global $phpbb_DB, $phpbb_subforums_list_level;
1958  
1959      // Get the forums from phpbb database

1960      $forums_SQL = new SQL();
1961      $forums_SQL->SELECT( 'f.forum_id, f.forum_name' );
1962      $forums_SQL->FROM( 'BB_forums f' );
1963      $forums_SQL->FROM_add( 'LEFT JOIN BB_categories c ON f.cat_id = c.cat_id' );
1964      if( $cat_id > 0 )
1965      {    // Get all top forums of the category
1966          $forums_SQL->WHERE( 'f.cat_id = '.$phpbb_DB->quote( $cat_id ) );
1967          $forums_SQL->WHERE_AND( 'f.forum_parent = 0' );
1968      }
1969      elseif( $forum_parent_id > 0 )
1970      {    // Get subforums
1971          $forums_SQL->WHERE( 'f.forum_parent = '.$phpbb_DB->quote( $forum_parent_id ) );
1972      }
1973      else
1974      {    // Wrong a call of this function
1975          return;
1976      }
1977      $forums_SQL->ORDER_BY( 'c.cat_order, f.forum_order' );
1978      $forums = $phpbb_DB->get_results( $forums_SQL->get() );
1979  
1980      if( count( $forums ) == 0 )
1981      {
1982          return;
1983      }
1984  
1985      $phpbb_subforums_list_level++;
1986  
1987      // Group all subforums in one div

1988      echo '<div class="phpbb_forums_'.$cat_id.'_'.$forum_parent_id.'">';
1989  
1990      $import_forums = phpbb_get_var( 'import_forums' );
1991      foreach( $forums as $forum )
1992      {    // Display forums
1993          $Form->checkbox_input( 'phpbb_forums[]', !is_array( $import_forums ) || in_array( $forum->forum_id, $import_forums ), '', array(
1994                  'input_prefix' => '<label>',
1995                  'input_suffix' => ' '.$forum->forum_name.'</label>',
1996                  'value' => $forum->forum_id,
1997                  'style' => 'margin-left:'.( $phpbb_subforums_list_level * 20 ).'px',
1998              ) );
1999          phpbb_subforums_list( $Form, 0, $forum->forum_id );
2000      }
2001  
2002      echo '</div>';
2003  
2004      $phpbb_subforums_list_level--;
2005  }
2006  
2007  
2008  /**

2009   * Import user's avatar

2010   *

2011   * @param integer User ID (from b2evo)

2012   * @param string Path avatars

2013   * @param string File name of user's avatar

2014   */
2015  function phpbb_import_avatar( $user_ID, $path_avatars, $user_avatar )
2016  {
2017      global $DB, $tableprefix;
2018  
2019      if( !empty( $user_avatar ) && file_exists( $path_avatars.$user_avatar ) )
2020      {    // Import user's avatar
2021          $FileRootCache = & get_FileRootCache();
2022          $root_ID = FileRoot::gen_ID( 'user', $user_ID );
2023  
2024          $imported_file_ID = copy_file( $path_avatars.$user_avatar, $root_ID, 'profile_pictures', false );
2025          if( !empty( $imported_file_ID ) )
2026          {    // Update user's avatar
2027              mysql_query( 'UPDATE '.$tableprefix.'users
2028                        SET user_avatar_file_ID = '.$DB->quote( $imported_file_ID ).'
2029                      WHERE user_ID = '.$DB->quote( $user_ID ).'
2030                        AND user_avatar_file_ID IS NULL',
2031                  $DB->dbhandle );
2032          }
2033      }
2034  }
2035  
2036  
2037  /**

2038   * Check if we can process current step

2039   *

2040   * @param string Step name

2041   * @return boolean TRUE - step is available to process

2042   */
2043  function phpbb_check_step( $step_name )
2044  {
2045      $steps_levels = array(
2046          'users'    => 1,
2047          'forums'   => 2,
2048          'topics'   => 3,
2049          'replies'  => 4,
2050          'messages' => 5,
2051      );
2052  
2053      if( empty( $steps_levels[ $step_name ] ) )
2054      {    // Invalid step name!
2055          return false;
2056      }
2057  
2058      $current_step = phpbb_get_var( 'current_step' );
2059  
2060      if( empty( $current_step ) )
2061      {    // It is first step
2062          phpbb_set_var( 'current_step', $step_name, true );
2063          return true;
2064      }
2065      else if( empty( $steps_levels[ $current_step ] ) )
2066      {    // Invalid current step name!
2067          return false;
2068      }
2069      else if( $steps_levels[ $step_name ] <= $steps_levels[ $current_step ] )
2070      {    // User tries open previous step that already been processed
2071          phpbb_log( T_('This import step has already been processed.'), 'error', ' ' );
2072          // Continue button

2073          // echo '<input type="submit" class="SaveButton" value="'.( $steps_levels[ $step_name ] < max( $steps_levels ) ? T_('Continue !') : T_('Go to Forum') ).'" name="submit" />';

2074          return false;
2075      }
2076  
2077      // Save step name in the Sessions

2078      phpbb_set_var( 'current_step', $step_name, true );
2079  
2080      return true;
2081  
2082  }
2083  
2084  ?>

title

Description

title

Description

title

Description

title

title

Body