MyBB Community Forums

Full Version: jcink database conversion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a partially completed jcink database conversion script and i'm having difficulty getting the forum description to transfer and also making the posts remain with their user once transferred. i'm basing this off of an older script...

<?php
/*
 * JCink ipb1.3 to MyBB 1.6
 * This importer will only do forums, topics, posts, and users (somewhat...)
 *
 * Give me database access....
 *(you will need to place your jcink backup into a database)
 */
$INFO['sql_host']        =    'localhost';
$INFO['sql_database']         =    '';
$INFO['sql_user']        =    '';
$INFO['sql_pass']        =    '';
$source_table_prefix     =  '';
$INFO['sql_port']        =    '';

// include mybb config file
include './inc/config.php';

/*
* NO MORE EDITING!
*/

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>JCink Invasion Power Board 1.3 to MyBB 1.6</title>
  </head>

  <body>
<?php
include 'jcmybb_functions.php';
include 'jcmybb_postfunction.php';
if (isset($_GET['import'])) {
    $import = $_GET['import'];

    switch ($import) {
      case 'start':
          import_start();
          break;
      /*case 'usrgrp':
        import_usergroups();
        break;*/
      case 'users':
        import_users();
        break;
      case 'catgry':
        import_category();
        break;
      case 'forums':
        import_forums();
        break;
      case 'topics':
        import_topics();
        break;
      case 'posts':
        import_posts();
        break;
      case 'polls':
        import_polls();
        break;
      case 'prvms':
        import_pms();
        break;
      case 'fix':
        mport_fixes();
        break;
    }
} else {
    print '<h1>Invision Power Board 1.3.x to MyBB 1.0.x , 1.1.x Converter</h1><br />';
    import_start();
}

function import_start() {
print '    <p>Welcome To Laiam's JCink ipb 1.3 to MyBB 1.6 database conversion engine.</p>
    <p>Each step of the conversion is available below.</p>
    <ul>
      <li><a href="jcink_to_mybb.php?import=users">Users Conversion</a></li>
      <li><a href="jcink_to_mybb.php?import=catgry">Categories Conversion</a></li>
      <li>Forums Conversion <- included with categories</li>
      <li><a href="jcink_to_mybb.php?import=topics">Threads Conversion</a></li>
      <li><a href="jcink_to_mybb.php?import=posts">Posts Conversion</a></li>
      <li><a href="jcink_to_mybb.php?import=polls">Polls Conversion</a></li>
      <li><a href="jcink_to_mybb.php?import=prvms">Private Messages Conversion</a></li>
      <li><a href="jcink_to_mybb.php?import=fix">Final Fix if needed</a></li>
    </ul>
    <p>for debugging purposes the steps are not done automatically.</p>
    <h3>Notes:</h3>
    <ul>
      <li>Your JCink backup must be uploaded into a database</li>
      <li>You must a use a freshly installed MyBB!</li>
      <li>Your MyBB database will be overwritten during conversion.</li>
      <li>Read the readme.txt and edit the Converter Settings correctly.</li>
      <li>When you are ready, start your conversion.</li>
      <li>Delete the record for guest in the jcink database members table</li>
    </ul>';
}

?>
  </body>
</html>

<?php
//All users will be added to the registered group.
/*_95Top3Go*/
function import_users() {
  global $INFO, $config, $source_table_prefix;
  $fcounter = $_GET['fcounter'] ? $_GET['fcounter'] : $fcounter=1;
  //---------------------------
  // Limit rows
  //---------------------------
    
  $end   = 500;
  $start = $_GET['start'] ? $_GET['start'] : 0;
  
  // Get all Users and save it in an array
  $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
  mysql_select_db($INFO['sql_database'], $ipb_db);

  $user_array = array();
  $sql = "SELECT * FROM " .$source_table_prefix."members ORDER BY id LIMIT $start, $end";
  $users = mysql_query($sql,$ipb_db) or die(mysql_error());
  
  /*
   * When user conversion complete
   */
  if ( ! mysql_num_rows($users)) {
    ?>
    <h4>User conversion complete!</h4>
    <script>
    function redirect() {
      window.location.replace("jcink_to_mybb.php?import=start");
    }
      setTimeout("redirect();", 1000);
    </script><?php
    exit();
  }
  if($start == '0')
    {
        // Clean Up Users table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."users");
    }
  while ($user = mysql_fetch_array($users)) {
    $user_array["$user[id]"] = $user;
  }
  // Done, now go to Import Process
  
  $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
  mysql_select_db($config['database'][database], $mybb_db);
  
  
  print "<h4>Importing " . count($user_array) . " users ...";
  
  foreach ($user_array as $user_id => $user) {
    // All users will default to the registered member usergroup.
    $uid                = $fcounter;
    $username           = $user['name'];
    $password           = 'e6b76b82d2b63a845a7c8534a89007e6';
    $salt               = 'NY8gpWuD';
    $loginkey           = 'ElwcVI11qm9KUonfCTucaTiI4IhsadGRpeYM49J4s3ldmwX3cR';
    $email              = $user['email'];
    $postnum            = (int) $user['posts'];
    $avatar             = '';
    $avatardimensions   = '';
    $avatartype         = '';
    $usergroup          = '2'; //registered members
    $additionalgroups   = '';
    $displaygroup       = 0;
    $usertitle          = ($user['title']) ? $user['title'] : '';
    $regdate            = (int) $user['joined'];
    $lastactive         = (int) $user['last_activity'];
    $lastvisit          = (int) $user['last_visit'];
    $lastpost           = (int) $user['last_post'];
    $website            = $user['website'];
    $icq                = $user['icq_number'];
    $aim                = $user['aim_name'];
    $yahoo              = $user['yahoo'];
    $msn                = $user['msnname'];
    $birthday           = ($user['bday_day'] != null AND $user['bday_month'] != null AND $user['bday_year'] != null) ? $user['bday_day'] . "-" . $user['bday_month'] . "-" . $user['bday_year'] : "";
    $birthdayprivacy    = 'all';
    $signature          = addslashes(ipb_html($user['signature']));
    $allownotices       = $user['allow_admin_mails'];
    $hideemail          = $user['hide_email'];
    $subscriptionmethod = 0;
    $invisible          = 0;
    $receivepms         = 1;
    $receivefrombuddy   = 1;
    $pmnotice           = 1;
    $pmnotify           = 0;
    $threadmode         = 'linear';
    $showsigs           = $user['view_sigs'];
    $showavatars        = $user['view_avs'];
    $showquickreply     = 1;
    $showredirect       = 0;
    $ppp                = 0;
    $tpp                = 0;
    $daysprune          = 0;
    $dateformat         = '';
    $timeformat         = '';
    $timezone           = '6';
    $dst                = 0;
    $dstcorrection      = 2;
    $buddylist          = '';
    $ignorelist         = '';
    $style              = 0;
    $away               = 0;
    $awaydate           = 0;
    $returndate         = '0';
    $awayreason         = '';
    $pmfolders          = $user['vdirs'];
    $notepad            = '';
    $referrer           = 4;
    $referrals          = 0;
    $reputation         = 1;
    $regip              = $user['ip_address'];
    $lastip             = $user['ip_address'];
    $longregip          = my_ip2long($user['ip_address']);
    $longlastip         = my_ip2long($user['ip_address']);
    $language           = '';
    $timeonline         = 67500;
    $showcodebuttons    = 1;
    $totalpms           = $user['msg_total'];
    $unreadpms          = $user['new_msg'];
    $warningpoints      = 0;
    $moderateposts      = 0;
    $moderationtime     = 0;
    $suspendposting     = 0;
    $suspensiontime     = 0;
    $suspendsignature   = 0;
    $suspendsigtime     = 0;
    $coppauser          = $user['coppa_user'];
    $classicpostbit     = 0;
    $loginattempts      = 0;
    $failedlogin        = 0;
    $usernotes          = '';
    $fcounter+=1;
      
    mysql_query("INSERT INTO ".$config['database'][table_prefix]."users 
              (uid,username,password,salt,loginkey,email,postnum,avatar,avatardimensions,avatartype,usergroup,additionalgroups,displaygroup,usertitle,regdate,lastactive,lastvisit,lastpost,website,icq,aim,yahoo,msn,birthday,birthdayprivacy,signature,allownotices,hideemail,subscriptionmethod,invisible,receivepms,receivefrombuddy,pmnotice,pmnotify,threadmode,showsigs,showavatars,showquickreply,showredirect,ppp,tpp,daysprune,dateformat,timeformat,timezone,dst,dstcorrection,buddylist,ignorelist,style,away,awaydate,returndate,awayreason,pmfolders,notepad,referrer,referrals,reputation,regip,lastip,longregip,longlastip,language,timeonline,showcodebuttons,totalpms,unreadpms,warningpoints,moderateposts,moderationtime,suspendposting,suspensiontime,suspendsignature,suspendsigtime,coppauser,classicpostbit,loginattempts,failedlogin,usernotes)
            VALUES 
              ('".$uid."', '".$username."', '".$password."', '".$salt."', '".$loginkey."', '".$email."', '".$postnum."', '".$avatar."', '".$avatardimensions."', '".$avatartype."', '".$usergroup."', '".$additionalgroups."', '".$displaygroup."', '".$usertitle."', '".$regdate."', '".$lastactive."', '".$lastvisit."', '".$lastpost."', '".$website."', '".$icq."', '".$aim."', '".$yahoo."', '".$msn."', '".$birthday."', '".$birthdayprivacy."', '".$signature."', '".$allownotices."', '".$hideemail."', '".$subscriptionmethod."', '".$invisible."', '".$receivepms."', '".$receivefrombuddy."', '".$pmnotice."', '".$pmnotify."', '".$threadmode."', '".$showsigs."', '".$showavatars."', '".$showquickreply."', '".$showredirect."', '".$ppp."', '".$tpp."', '".$daysprune."', '".$dateformat."', '".$timeformat."', '".$timezone."', '".$dst."', '".$dstcorrection."', '".$buddylist."', '".$ignorelist."', '".$style."', '".$away."', '".$awaydate."', '".$returndate."', '".$awayreason."', '".$pmfolders."', '".$notepad."', '".$referrer."', '".$referrals."', '".$reputation."', '".$regip."', '".$lastip."', '".$longregip."', '".$longlastip."', '".$language."', '".$timeonline."', '".$showcodebuttons."', '".$totalpms."', '".$unreadpms."', '".$warningpoints."', '".$moderateposts."', '".$moderationtime."', '".$suspendposting."', '".$suspensiontime."', '".$suspendsignature."', '".$suspendsigtime."', '".$coppauser."', '".$classicpostbit."', '".$loginattempts."', '".$failedlogin."', '".$usernotes."')
          ") or die(mysql_error());
    unset($birthday);
  }
  
  // Done?
  // Ok - redirect for the next batch
  $new_start = $start + $end;
  print '  <script>
    function redirect() {
    window.location.replace("jcink_to_mybb.php?import=users&start='.$new_start.'&fcounter='.$fcounter.'");
    }
    setTimeout("redirect();", 1000);
    </script>';
}

// Lets import us some categories
function import_category() {
  global $INFO, $config, $source_table_prefix;
  //---------------------------
  // Limit rows
  //---------------------------
    
  $end   = 500;
  $start = $_GET['start'] ? $_GET['start'] : 0;
  $lfid  = $_GET['lfid'] ? $_GET['lfid'] : 0;
  
  // Get all Categories and save it in an array
  $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
  mysql_select_db($INFO['sql_database'], $ipb_db);

  $categories_array = array();
  $sql = "SELECT * FROM " .$source_table_prefix."categories ORDER BY id LIMIT $start, $end";
  $categories = mysql_query($sql,$ipb_db) or die(mysql_error());
  
  if ( ! mysql_num_rows($categories)) {
  print '    <h4>Category conversion complete!</h4>
    <p>Next Step Forums!</p>
    <script>
    function redirect() {
      window.location.replace("jcink_to_mybb.php?import=forums&lfid='.$lfid.'");
    }
      setTimeout("redirect();", 1000);
    </script>';
    exit();
  }
  
  while ($category = mysql_fetch_array($categories)) {
    $categories_array["$category[id]"] = $category;
  }
  // Done, now go to Import Process
  
  $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
  mysql_select_db($config['database'][database], $mybb_db);
  
  if($start == '0') {
        // Clean Up Forums table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."forums");
  }
  
  print "<h4>Importing " . count($categories_array) . " categories ...";
  
  foreach ($categories_array as $category_id => $category) {
    // If its not the first blank one
    if($category_id != '-1') {
      
      $fid                 = (int) $category['position'];
      $name                = addslashes($category['name']);
      $description         = '';
      $linkto              = '';
      $type                = 'c';
      $pid                 = 0;
      $parentlist          = '0';
      $disporder           = (int) $category['position'];
      $active              = 1;
      $open                = 1;
      $threads             = 1;
      $posts               = 0;   //Stats from here to next
      $lastpost            = 0;   //will be retotaled
      $lastposter          = '0'; //after rebuilding
      $lastposteruid       = 0;   //statistics
      $lastposttid         = 0;
      $lastpostsubject     = '';
      $allowhtml           = 0;
      $allowmycode         = 1;
      $allowsmilies        = 1;
      $allowimgcode        = 1;
      $allowvideocode      = 1;
      $allowpicons         = 1;
      $allowtratings       = 1;
      $status              = 1;
      $usepostcounts       = 1;
      $password            = '';
      $showinjump          = 1;
      $modposts            = 0;
      $modthreads          = 0;
      $mod_edit_posts      = 0;
      $modattachments      = 0;
      $style               = 0;
      $overridestyle       = 0;
      $rulestype           = 0;
      $rulestitle          = '';
      $rules               = '';
      $unapprovedthreads   = 0;
      $unapprovedposts     = 0;
      $defaultdatecut      = 0;
      $defaultsortby       = '';
      $defaultsortorder    = '';
      $lfid = ($lfid < $fid) ? $fid : $lfid;
      mysql_query("INSERT INTO ".$config['database'][table_prefix]."forums (fid, name, description, linkto, type, pid, parentlist, disporder, active, open, threads, posts, lastpost, lastposter, lastposteruid, lastposttid, lastpostsubject, allowhtml, allowmycode, allowsmilies, allowimgcode, allowvideocode, allowpicons, allowtratings, status, usepostcounts, password, showinjump, modposts, modthreads, mod_edit_posts, modattachments, style, overridestyle, rulestype, rulestitle, rules, unapprovedthreads, unapprovedposts, defaultdatecut, defaultsortby, defaultsortorder)
                                VALUES ('".$fid."', '".$name."', '".$description."', '".$linkto."', '".$type."', '".$pid."', '".$parentlist."', '".$disporder."', '".$active."', '".$open."', '".$threads."', '".$posts."', '".$lastpost."', '".$lastposter."', '".$lastposteruid."', '".$lastposttid."', '".$lastpostsubject."', '".$allowhtml."', '".$allowmycode."', '".$allowsmilies."', '".$allowimgcode."', '".$allowvideocode."', '".$allowpicons."', '".$allowtratings."', '".$status."', '".$usepostcounts."', '".$password."', '".$showinjump."', '".$modposts."', '".$modthreads."', '".$mod_edit_posts."', '".$modattachments."', '".$style."', '".$overridestyle."', '".$rulestype."', '".$rulestitle."', '".$rules."', '".$unapprovedthreads."', '".$unapprovedposts."', '".$defaultdatecut."', '".$defaultsortby."', '".$defaultsortorder."')
            ") or die(mysql_error());
    }
  }
  
  // Done?
  // Ok - redirect for the next batch
  $new_start = $start + $end;
  print '    <script>
    function redirect() {
    window.location.replace("jcink_to_mybb.php?import=catgry&start='.$new_start.'&lfid='.$lfid.'");
    }
    setTimeout("redirect();", 1000);
    </script>';
}

function import_forums() {
    global $config, $INFO, $source_table_prefix;
    
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    // Get all Forums and save it in an array
    $forum_array = array();

    $sql = "SELECT * FROM " .$source_table_prefix."forums ORDER BY id LIMIT $start, $end";
    $forums = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($forums))
    {
        // We are done? Redirect to next Step
        print '<h4>Forums conversion complete!</h4>
        <p>rerouting to main list</p>
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=start");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    
    while ($forum = mysql_fetch_array($forums))
    {
        $forum_array["$forum[id]"] = $forum;
    }
    
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    if($start == '0') {
      // Add an Extra field, it´s for the importer
      @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."forums ADD `importforumid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    print "<h4>Importing " . count($forum_array) . " forum(s) ...";
    
    $target_table_prefix = $config['database'][table_prefix];
    $fid=$_GET['lfid'];
    foreach ($forum_array as $forum_id => $forum) {
    
      $parent_id = (int) $forum['category'];
      if ($parent_id == 10) {$pid=1;}
      if ($parent_id == 4) {$pid=2;}
      if ($parent_id == 6) {$pid=3;}
      if ($parent_id == 5) {$pid=4;}
      if ($parent_id == 3) {$pid=5;}
      if ($parent_id == 2) {$pid=6;}
      if ($parent_id == 9) {$pid=7;}
      $fid                 =$fid+1;
      $name                = addslashes($forum['name']);
      $description         = $forum['description'];
      $linkto              = '';
      $type                = 'f';
      $parentlist          = $pid.','.$fid;
      $disporder           = (int) $forum['position'];
      $active              = 1;
      $open                = 1;
      $threads             = (int) $forum['topics'];
      $posts               = (int) $forum['posts'];
      $lastpost            = (int) $forum['last_post'];
      $lastposter          = $forum['last_poster_name'];
      $lastposteruid       = 0;   //Stats from here to next
      $lastposttid         = 0;   //will be retotaled
      $lastpostsubject     = '';  //after rebuilding
      $allowhtml           = 0;   //statistics
      $allowmycode         = 1;
      $allowsmilies        = 1;
      $allowimgcode        = 1;
      $allowvideocode      = 1;
      $allowpicons         = 1;
      $allowtratings       = 1;
      $status              = 1;
      $usepostcounts       = 1;
      $password            = '';
      $showinjump          = 1;
      $modposts            = 0;
      $modthreads          = 0;
      $mod_edit_posts      = 0;
      $modattachments      = 0;
      $style               = 0;
      $overridestyle       = 0;
      $rulestype           = 0;
      $rulestitle          = '';
      $rules               = '';
      $unapprovedthreads   = 0;
      $unapprovedposts     = 0;
      $defaultdatecut      = 0;
      $defaultsortby       = '';
      $defaultsortorder    = '';
      $importforumid       = (int) $forum_id;
      mysql_query("INSERT INTO ".$config['database'][table_prefix]."forums (fid, name, description, linkto, type, pid, parentlist, disporder, active, open, threads, posts, lastpost, lastposter, lastposteruid, lastposttid, lastpostsubject, allowhtml, allowmycode, allowsmilies, allowimgcode, allowvideocode, allowpicons, allowtratings, status, usepostcounts, password, showinjump, modposts, modthreads, mod_edit_posts, modattachments, style, overridestyle, rulestype, rulestitle, rules, unapprovedthreads, unapprovedposts, defaultdatecut, defaultsortby, defaultsortorder, importforumid)
                   VALUES ('".$fid."', '".$name."', '".$description."', '".$linkto."', '".$type."', '".$pid."', '".$parentlist."', '".$disporder."', '".$active."', '".$open."', '".$threads."', '".$posts."', '".$lastpost."', '".$lastposter."', '".$lastposteruid."', '".$lastposttid."', '".$lastpostsubject."', '".$allowhtml."', '".$allowmycode."', '".$allowsmilies."', '".$allowimgcode."', '".$allowvideocode."', '".$allowpicons."', '".$allowtratings."', '".$status."', '".$usepostcounts."', '".$password."', '".$showinjump."', '".$modposts."', '".$modthreads."', '".$mod_edit_posts."', '".$modattachments."', '".$style."', '".$overridestyle."', '".$rulestype."', '".$rulestitle."', '".$rules."', '".$unapprovedthreads."', '".$unapprovedposts."', '".$defaultdatecut."', '".$defaultsortby."', '".$defaultsortorder."', '".$importforumid."')
                  ") or die(mysql_error());
    }
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=start");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}



function ipb_html($post) {
  $post = preg_replace('#<u>([^"]*)</u>#siU', '[u]\\1[/u]', $post);
  $post = preg_replace('#<b>([^"]*)</b>#siU', '[b]\\1[/b]', $post);
  $post = preg_replace('#<i>([^"]*)</i>#siU', '[i]\\1[/i]', $post);
  $post = preg_replace('#<span style=\'font-family:([^"]*)\'>([^"]*)</span>#siU', '[font=\\1]\\2[/font]', $post);
  $post = preg_replace('#<span style=\'color:([^"]*)\'>([^"]*)</span>#siU', '[color=\\1]\\2[/color]', $post);
  $post = preg_replace('#<a href=\'(http://|https://|ftp://|news://)([^"]*)\' target=\'_blank\'>([^"]*)</a>#siU', '[url=\\1\\2]\\3[/url]', $post);
  
  $post = preg_replace('#<a href=\'(ed2k://)([^"]*)\' title=\'ed2klink\'>([^"]*)</a>#siU', '[url=\\1\\2]\\3[/url]', $post);
  $post = preg_replace('#<a href=\'(http://)([^"]*)\'>([^"]*)</a>#siU', '[url=\\1\\2]\\3[/url]', $post);

  $post = preg_replace('#<img src=\'([^"]*)\' border=\'0\' alt=\'user posted image\'(\s/)? >#siU', '[img]\\1[/img]', $post);
  $post = str_replace("<img src='","[img]",$post);
  $post = preg_replace('#<a href=\'mailto:([^"]*)\'>([^"]*)</a>#siU', '[email=\\1]\\2[/email]', $post);

  $post = preg_replace('#<ul>#siU', '[list]', $post);
  $post = preg_replace('#<ol type=\'[1|i]\'>#siU', '[list=1]', $post);
  $post = preg_replace('#<ol type=\'a\'>#siU', '[list=a]', $post);
  $post = preg_replace('#<li>([^"]*)</li>#siU', "[*]\\1\n", $post);
  $post = preg_replace('#</ul>#siU', '[/list]', $post);
  $post = preg_replace('#</ol>#siU', '[/list]', $post);

  $post = preg_replace('#<!--emo&([^"]*)-->([^"]*)<!--endemo-->#siU', '\\1', $post);
  $post = preg_replace('#<!--c1-->([^"]*)<!--ec1-->#siU', '[code]', $post);
  $post = preg_replace('#<!--c2-->([^"]*)<!--ec2-->#siU', '[/co'+'de]', $post);
  $post = preg_replace('#<!--QuoteBegin-->([^"]*)<!--QuoteEBegin-->#siU', '[quote][b]', $post);
  $post = preg_replace('#<!--QuoteBegin-{1,2}([^"]*)\+-->([^"]*)<!--QuoteEBegin-->#si', '[quote][i]Originally posted by \\1[/i]<br />[b]', $post);
  $post = preg_replace('#<!--QuoteBegin-{1,2}([^"]*)\+([^"]*)-->([^"]*)<!--QuoteEBegin-->#si', '[quote][i]Originally posted by \\1[/i]@\\2<br />[b]', $post);
  $post = preg_replace('#<!--QuoteEnd-->([^"]*)<!--QuoteEEnd-->#siU', '[/b][/quote]', $post);
  $post = preg_replace('#<span style=\'font-size:(.+?)pt;line-height:100%\'>(.+?)</span>#e', 'unconvert_size("\\1", "\\2")', $post);
  $post = preg_replace('#<!--EDIT\|([^"]*)\|([^"]*)-->#siU', 'Last edited by \\1 at \\2', $post);

  $post = str_replace("<br />","\n",$post);
  $post = str_replace("<br>","\n",$post);
  $post = str_replace("&amp;","&",$post);
  $post = str_replace("&lt;","<",$post);
  $post = str_replace("&gt;",">",$post);
  $post = str_replace("&quot;","\"",$post);
  $post = str_replace("'","'",$post);
  $post = str_replace("!","!",$post);
  $post = str_replace("|","|",$post);

  $post = preg_replace('#<a href=\'([^"]*)\' target=\'_blank\'><img src=\'([^"]*)\' alt=\'([^"]*)\' width=\'([^"]*)\' height=\'([^"]*)\' class=\'([^"]*)\' /></a>#siU', '[img]\\2[/img]', $post);

  $post = preg_replace('#<!--aimg-->#siU', '', $post);
  $post = preg_replace('#<!--/aimg-->#siU', '', $post);
  $post = preg_replace('#--Resize_Images_Alt_Text--#siU', '', $post);
  $post = preg_replace('#<!--Resize_Images_Hint_Text-->#siU', '', $post);

  $post = preg_replace('#<!--QuoteBegin-{1,2}([^"]*)\+-->([^"]*)<!--QuoteEBegin-->#siU', '[quote]Originally posted by \\1<br />[b]', $post);
  $post = preg_replace('#<!--QuoteBegin-{1,2}([^"]*)\+([^"]*)-->([^"]*)<!--QuoteEBegin-->#siU', '[quote]Originally posted by \\1@\\2<br />[b]', $post);

   return trim(stripslashes($post));;
}

function unconvert_size($size="", $text="")
{
    switch($size)
    {
       case '21':
          $size=4;
          break;
       case '14':
          $size=3;
          break;
       case '8':
          $size=1;
          break;
       default:
          $size=2;
          break;
    }
    return '[SIZE='.$size.']'.$text.'[/SIZE]';
}

function my_ip2long($ip)
{
  $ip = ip2long($ip);
  if($ip >= 2147483648) // Won't occur on 32-bit PHP
  {
    $ip -= 4294967296;
  }
  return $ip;
}

?>

<?php
// After we import the IPB Forums we import all Threads, let´s go!
function import_topics() {
    global $config, $INFO, $source_table_prefix;
    
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all Topics and save it in an array
    $topics_array = array();

    $sql = "SELECT * FROM " .$source_table_prefix."topics ORDER BY tid LIMIT $start, $end";
    $topics = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($topics)) {
        // We are done? Redirect to next Step
        print '<h4>Topics conversion complete! Please wait for next Step (Posts Conversion)</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=posts");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    
    while ($topic = mysql_fetch_array($topics)) {
        $topics_array["$topic[tid]"] = $topic;
    }
    
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    print "<h4>Importing " . count($topics_array) . " Thread(s) ...";
    
    if($start == '0') {
        // Clean Up Threads table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."threads");
    
        // Add some Extra Fields , it´s for the importer
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."threads ADD `importforumid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."threads ADD `importthreadid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    $target_table_prefix = $config['database'][table_prefix];
    
    $forum_ids                 = get_forum_ids($target_table_prefix);
    $users_ids                 = get_user_ids($target_table_prefix);
    $user_names                = get_username($target_table_prefix);
    
    foreach ($topics_array as $topic_id => $topic) {
        $subject             = $topic['title'];
        $fid                 = (int) $forum_ids[$topic['forum_id']]; 
        $importthreadid        = (int) $topic_id;
        $importforumid        = (int) $topic['forum_id'];
        $uid                = (int) $users_ids[$topic['starter_id']];
        $username            = $user_names['starter_name'];
        $dateline            = (int) $topic['start_date'];
        $views                = (int) $topc['views'];
        $replies            = (int) $topic['posts'];
        $notes                = $topic['description'];
        $lastpost            = (int) $topic['last_post'];
        $lastposter            = $topic['last_poster_name'];
        $sticky                = (int) $topic['pinned'];
        $visible            = '1';
        
        if ($topic['state'] == 'open')
        {
            $closed = 'no';
        }
        else if ($topic['state'] == 'closed')
        {
            $closed = 'yes';
        }
        
        mysql_query("INSERT INTO  ".$config['database'][table_prefix]."threads 
                (subject,fid,importthreadid,importforumid,uid,username,dateline,views,replies,notes,lastpost,lastposter,sticky,visible,closed) 
        VALUES ('".$subject."', '".$fid."', '".$importthreadid."', '".$importforumid."', '".$uid."', '".$username."', '".$dateline."', '".$views."', '".$replies."', '".$notes."', '".$lastpost."', '".$lastposter."', '".$sticky."', '".$visible."', '".$closed."')
        ") or die(mysql_error());
    }
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=topics&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}


// After we import the IPB Threads we import all Posts, let´s go!
function import_posts() {
    global $config, $INFO, $source_table_prefix;
    
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all Posts and save it in an array
    $posts_array = array();

    $sql = "SELECT * FROM " .$source_table_prefix."posts ORDER BY pid LIMIT $start, $end";
    $posts = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($posts)) {
        // We are done? Redirect to next Step
        print '<h4>Posts conversion complete! Please wait for next Step (Polls Conversion)</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=polls");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    else {
    
        while ($post = mysql_fetch_array($posts))
        {
            $posts_array["$post[pid]"] = $post;
        }
    }
    
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    print "<h4>Importing " . count($posts_array) . " Posts(s) ...";
    
    if($start == '0') {
        // Clean Up Posts table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."posts");
        // Add some Extra Fields , it´s for the importer
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."posts ADD `importthreadid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."posts ADD `importpostid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    $target_table_prefix = $config['database'][table_prefix];
    
    $thread_ids                = get_threads_ids($target_table_prefix);
    $users_ids                 = get_user_ids($target_table_prefix);
    
    foreach ($posts_array as $post_id => $post) {
        $tid             = (int) $thread_ids[$post['topic_id']];
        $uid             = (int) $users_ids[$post['author_id']];
        $importthreadid = (int) $post['topic_id'];
        $importpostid    = (int) $post_id;
        $dateline        = (int) $post['post_date'];
        $username        = $post['author_name'];
        $ipaddress        = $post['ip_address'];
        
        if ($post['use_sig'] == '1')
        {
            $includesig = 'yes';
        }
        else
        {
            $includesig = 'no';
        }
        
        if ($post['use_emo'] == '1')
        {
            $smilieoff = 'yes';
        }
        else
        {
            $smilieoff = 'no';
        }
        
        $message        = addslashes(ipb_html($post['post']));
        $subject        = $post['post_title'];
        $visible        = '1';
        $edittime        = (int) $post['edit_time'];
        
        mysql_query("INSERT INTO  ".$config['database'][table_prefix]."posts 
                (tid,uid,importthreadid,importpostid,dateline,username,ipaddress,includesig,smilieoff,message,subject,visible,edittime) 
        VALUES ('".$tid."', '".$uid."', '".$importthreadid."', '".$importpostid."', '".$dateline."', '".$username."', '".$ipaddress."', '".$includesig."', '".$smilieoff."', '".$message."', '".$subject."', '".$visible."', '".$edittime."')
        ") or die(mysql_error());
    }
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=posts&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}

// After we import the IPB Posts we import all Polls, let´s go!
function import_polls() {
    global $config, $INFO, $source_table_prefix;
    
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all Polls and save it in an array
    $polls_array = array();

    $sql = "SELECT * FROM " .$source_table_prefix."polls ORDER BY pid LIMIT $start, $end";
    $polls = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($polls)) {
        // We are done? Redirect to next Step
        print '<h4>Polls conversion complete! Please wait for next Step (Attachments Conversion)</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=attachments");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    
    while ($poll = mysql_fetch_array($polls)) {
        $polls_array["$poll[pid]"] = $poll;
    }
    
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    print "<h4>Importing " . count($polls_array) . " Polls(s) ...";
    
    if($start == '0') {
        // Clean Up Polls and Pollvotes table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."polls");
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."pollvotes");
    
        // Add some Extra Fields , it´s for the importer
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."polls ADD `importpollid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    $target_table_prefix = $config['database'][table_prefix];
    
    $thread_ids                = get_threads_ids($target_table_prefix);
    $users_ids                 = get_user_ids($target_table_prefix);
    
    foreach ($polls_array as $poll_id => $poll) {
        $optionsstring     = '';
        $votesstring     = '';
        $numberoptions     = 0;
        $voters         = 0;
        unset($poll_voters_array);

        $poll_answers = unserialize(stripslashes($poll['choices']));

        while ($pollinfo = each($poll_answers))
        {
            $optionsstring .= unhtmlspecialchars($pollinfo['1']['1'])."||~|~||";
            // sanity check for votes count
            $votesbit = intval($pollinfo['1']['2']);
            if ($votesbit < 0)
            {
                $votesbit = 0;
            }
            $voters += $votesbit;
            $votesstring .= $votesbit."||~|~||";
            $numberoptions++;
        }

        unset($poll_answers);
        $poll['options'] = $optionsstring;
        $poll['votes'] = $votesstring;
        
        if(!$poll['poll_question'])
        {
            $question = 'No question to import.';
        }
        else
        {
            $question = $poll['poll_question'];
        }
        
        $importpollid = $poll_id;
        $dateline = $poll['start_date'];
        $options = $poll['options'];
        $votes = $poll['votes'];
        $numoptions = $numberoptions;
        $timeout = '0';
        $multiple = '0';
        $voters = $voters;
        $public = '1';
        $import_thread_id = $poll['tid'];
        
        // If "forum_poll_voters"
        $poll_voters = get_ipb_poll_voters($source_table_prefix, $import_thread_id);
        
        $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
        mysql_select_db($config['database'][database], $mybb_db);
            
        $result = mysql_query("INSERT INTO  ".$config['database'][table_prefix]."polls 
                (importpollid,question,dateline,options,votes,numoptions,timeout,multiple,public) 
        VALUES ('".$importpollid."', '".$question."', '".$dateline."', '".$options."', '".$votes."', '".$numoptions."', '".$timeout."', '".$multiple."', '".$public."')
        ") or die(mysql_error());
        
        $mybb_poll_id = mysql_insert_id();
        
        if(!empty($poll_voters))
        {
            foreach ($poll_voters AS $mybb_user_id => $vote_option)
            {
                if(empty($mybb_user_id))
                {
                    continue;
                }
                if ($vote_option == 0 OR empty($vote_option))
                {
                    $sql = "INSERT INTO " . $config['database'][table_prefix] . "pollvotes (pid, uid) VALUES ('".$mybb_poll_id."', '".$mybb_user_id."')";
                }
                else
                {
                    $sql = "INSERT INTO " . $config['database'][table_prefix] . "pollvotes (pid, uid, voteoption) VALUES ('".$mybb_poll_id."', '".$mybb_user_id."', '".$vote_option."')";
                }

                mysql_query($sql) or die(mysql_error());
            }
        }
        
        mysql_query("UPDATE " . $config['database'][table_prefix] . "threads SET poll = ".$mybb_poll_id." WHERE importthreadid = ".$import_thread_id) or die(mysql_error());
    }
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=polls&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}

// After we import the IPB Polls we import all Attachments, let´s go!
function import_attachments() {
    global $INFO, $config, $source_table_prefix, $attachment_folder, $mybb_uploadspath;
    
    //---------------------------
    // Limit rows
    //---------------------------
        
    $end   = 10;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all Attachments and save it in an array
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);

    $attachment_array = array();
    $sql = "SELECT pid, post_date,attach_id, attach_hits, attach_type, attach_file, author_id FROM " .$source_table_prefix."posts 
            WHERE attach_file != ''
            AND attach_file != '|'
            LIMIT $start, $end";
    $attachments = mysql_query($sql,$ipb_db) or die(mysql_error());
    
    if ( ! mysql_num_rows($attachments)) {
        // We are done?
        print '<h4>Attachment conversion complete! Please wait for next Step (PM´s Conversion!)</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=pms");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        
        exit();
    }
    
    while ($attachment = mysql_fetch_array($attachments)) {
        $attachment_array[] = $attachment;
    }
    // Done, now go to Import Process
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    if($start == '0') {
        // Clean Up Attachments table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."attachments");
        // Add some Extra Fields , it´s for the importer
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."attachments ADD `importattachmentid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    print "<h4>Importing " . count($attachment_array) . " Attachments ...";
    
    $i = 0;
    foreach ($attachment_array as $post_id => $attachment) {
        $filename = $attachment['attach_id'];
        $original= $attachment['attach_file'];
        $counter  = $attachment['attach_hits'];
        

        $the_file = get_ipb_attachment($attachment_folder, $filename);
        $importattachmentid = $i+1;
        $visible = '1';
        $downloads = $attachment['attach_hits'];
        $filesize = $the_file['filesize'];
        $pid = $attachment['pid'];
        $uid = $attachment['author_id'];
                
        // Get the real post id
        $get_post_id = mysql_query("SELECT pid, uid FROM ".$config['database'][table_prefix]."posts WHERE importpostid = '".$pid."'") or die(mysql_error());
        $postid = mysql_fetch_array($get_post_id);
        
        /* 
        * Borrowed from MyBB to Generate Thumbnails
        */
        
        $ext = getextention($attachment['attach_id']);
        
        // Alls well that ends well? Lets generate a thumbnail (if image) and insert it all in to the database
        if($ext == "gif" || $ext == "png" || $ext == "jpg" || $ext == "jpeg" || $ext == "jpe")
        {
            $thumbname = "".strip_file_ext($attachment['attach_id'])."_thumb.".$ext;
            $thumbnail = @generate_thumbnail($mybb_uploadspath."/".$filename, $mybb_uploadspath, $thumbname, '60', '60');
            if($thumbnail['filename'])
            {
                $thumbadd = ",thumbnail";
                $thumbadd2 = ",'".$thumbnail['filename']."'";
            }
            elseif($thumbnail['code'] == 4)
            {
                $thumbadd = ",thumbnail";
                $thumbadd2 = ",'SMALL'";
            }
        }
        else
        {
            $thumbadd = "";
            $thumbadd2 = "";
        }
        

        mysql_query("INSERT INTO " . $config['database'][table_prefix] . "attachments
                        (importattachmentid, filename, visible, downloads, filesize, pid, uid, attachname, filetype$thumbadd)
                        VALUES
                        ('".$importattachmentid."', '".$original."', '".$visible."', '".$downloads."', '".$filesize."', '".$postid['pid']."', '".$postid['uid']."', '".$filename."', '".$attachment['attach_type']."'$thumbadd2)
                    ") or die(mysql_error());
        $i++;
    }
    unset($thumbnail);
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=attachments&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}

// After we import the IPB Attachments we import all Private Messages, let´s go!
function import_pms() {
    global $config, $INFO, $source_table_prefix;
    
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all PMs and save it in an array
    $pms_array = array();
    $sql = "SELECT * FROM " . $source_table_prefix . "messages ORDER BY msg_id LIMIT $start, $end";
    $pms = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($pms)) {
        // We are done? Redirect to next Step
        print '<h4>Private Messages conversion complete! Please wait for next Step (Fix Lastpost Information on Forums)</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=fixes");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    
    while ($pm = mysql_fetch_array($pms)) {
        $pms_array["$pm[msg_id]"] = $pm;
    }
    
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    print "<h4>Importing " . count($pms_array) . " Private Messages ...";
    
    if($start == '0') {
        // Clean Up Posts table_prefix
        mysql_query("TRUNCATE TABLE ".$config['database'][table_prefix]."privatemessages");
    
        // Add some Extra Fields , it´s for the importer
        @mysql_query("ALTER TABLE ".$config['database'][table_prefix]."privatemessages ADD `importpmid` BIGINT( 20 ) DEFAULT '0' NOT NULL ;");
    }
    
    $target_table_prefix = $config['database'][table_prefix];
    
    $users_ids                 = get_user_ids($target_table_prefix);
    $user_names                = get_username($target_table_prefix);
    
    foreach ($pms_array as $pm_id => $pm) {
        $importpmid = (int) $pm_id;
        $fromid = (int) $users_ids[$pm['from_id']];
        $toid = (int) $users_ids[$pm['recipient_id']];
        $uid = (int) $users_ids[$pm['member_id']];
        $message = addslashes(ipb_html($pm['message']));
        $subject = $pm['title'];
        $dateline = (int) $pm['msg_date'];
        $readtime = (int) $pm['read_date'];
        if($pm['vid'] == 'sent')
        {
            $folder = '2';
        }
        else
        {
            $folder = '1';
        }
        $status = '1';
        
        mysql_query("INSERT INTO  ".$config['database'][table_prefix]."privatemessages 
                (importpmid,fromid,toid,uid,message,subject,dateline,readtime,folder,status) 
        VALUES ('".$importpmid."', '".$fromid."', '".$toid."', '".$uid."', '".$message."', '".$subject."', '".$dateline."', '".$readtime."', '".$folder."', '".$status."')
        ") or die(mysql_error());
    }
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
    print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=pms&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
}

// After we import the IPB Private Messages we fix the lastposttid on forums table, let´s go!
function import_fixes() {
    global $config, $INFO, $source_table_prefix;
    
    $mybb_db = mysql_connect($config['database'][hostname], $config['database'][username], $config['database'][password], true);
    mysql_select_db($config['database'][database], $mybb_db);
    
    // Limit rows
    $end   = 500;
    $start = $_GET['start'] ? $_GET['start'] : 0;
    
    // Get all Forums and save it in an array
    $forums_array = array();
    $sql = "SELECT fid FROM " . $config['database'][table_prefix] . "forums WHERE type='f' ORDER BY fid LIMIT $start, $end";
    $forums = mysql_query($sql) or die(mysql_error());
    
    if ( ! mysql_num_rows($forums)) {
        // We are done? Redirect to next Step
        print '<h4>Fixed Lastpost Information complete!</h4>';
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';
        exit();
    }
    
    while ($forum = mysql_fetch_array($forums)) {
        $forums_array["$forum[fid]"] = $forum;
    }
    
    print "<h4>Fixed Lastpost Information for " . count($forums_array) . " Forum(s) ...";
    
    $target_table_prefix = $config['database'][table_prefix];
    
    foreach ($forums_array as $forum_id => $forum) {
        $get = mysql_query("SELECT p.tid, t.subject FROM ".$config['database'][table_prefix]."posts p, ".$config['database'][table_prefix]."threads t
                            WHERE t.fid = '".$forum_id."' AND p.tid = t.tid
                            ORDER BY p.dateline DESC LIMIT 1");
        $result = mysql_fetch_array($get);
        mysql_query("UPDATE ".$config['database'][table_prefix]."forums SET lastposttid='".$result['tid']."' WHERE fid='".$forum_id."'")or die(mysql_error());
    }
    mysql_free_result($get);
    
    // Done?
    // Ok - redirect for the next batch
    $new_start = $start + $end;
        print '
        <script>
        function redirect() {
        window.location.replace("jcink_to_mybb.php?import=fixes&start='.$new_start.'");
        }
        setTimeout("redirect();", 1000);
        </script>
        ';

}

function get_forum_ids(&$tableprefix, $pad=0) {
    
    $forums = mysql_query("SELECT fid, importforumid FROM " . $tableprefix . "forums");
    while ($forum = mysql_fetch_array($forums)) {
        if ($pad)
        {
            $impforumid = intval($forum['importforumid']);
            $forumid["$impforumid"] = $forum['fid'];
        }
        else
        {
            $forumid["$forum[importforumid]"] = $forum['fid'];
        }
    }
    mysql_free_result($forums);
    return $forumid;
}

function get_category_ids(&$tableprefix) {
    
    $forums = mysql_query("SELECT fid, importcategoryid FROM " . $tableprefix . "forums WHERE importcategoryid <> 0");
    while ($forum = mysql_fetch_array($forums)) {
        $categoryid["$forum[importcategoryid]"] = $forum['fid'];
    }
    mysql_free_result($forums);
    return $categoryid;
}

// Returns an array of the user ids key'ed to the import user id's $userid[$importuserid] = $user[userid]
function get_user_ids(&$tableprefix, $do_int_val = false) {
    $users = mysql_query("SELECT uid, username, importuserid FROM " . $tableprefix . "users WHERE importuserid <> 'null'");
    while ($user = mysql_fetch_array($users)) {
        if ($do_int_val)
        {
            $importuserid = intval($user['importuserid']);
        }
        else
        {
            $importuserid = $user['importuserid'];
        }

        $userid["$importuserid"] = $user['uid'];
    }
    mysql_free_result($users);
    return $userid;
}

// Returns an array of the import user ids key'ed to the username
function get_username(&$tableprefix) {
    
    $users = mysql_query("SELECT username, uid, importuserid AS importuserid FROM " . $tableprefix ."users WHERE importuserid <> 0");
    while ($user = mysql_fetch_array($users)) {
        // The normal
        $username["$user[importuserid]"]                     = $user['username'];

        // The reverse
        $username['uid']["$user[uid]"]                         = $user['username'];
    }
    mysql_free_result($users);
    return $username;
}


// Returns a MyBB thread id array
function get_threads_ids(&$tableprefix) {
    
    $threads = mysql_query("SELECT tid, importthreadid FROM " . $tableprefix . "threads WHERE importthreadid <> 0");
    while ($thread = mysql_fetch_array($threads)) {
        $threadid["$thread[importthreadid]"] = $thread['tid'];
    }
    mysql_free_result($threads);
    return $threadid;
}

function get_ipb_poll_voters($table_prefix, $poll_id) {
    global $INFO;
        
    $ipb_db = mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']);
    mysql_select_db($INFO['sql_database'], $ipb_db);
    
    $return_array = array();
    
    // Check that there isn't a empty value
    if(empty($poll_id)) { return $return_array; }
    
    $sql = "SELECT member_id FROM " .$table_prefix."voters WHERE tid = " .$poll_id;

    $poll_voters = mysql_query($sql) or die(mysql_error());
    while ($voter = mysql_fetch_array($poll_voters)) {
        $return_array[] = $voter;
    }        

    return $return_array;
}

function unhtmlspecialchars($text) {
    return str_replace(array('&lt;', '&gt;', '&quot;', '&amp;'), array('<', '>', '"', '&'), $text);
}

function get_ipb_attachment($path, $file_name) {
    $file_address = $path . "/" . $file_name;
    if($file_name == '' OR !is_file($file_address)) {
        return false;
    }
    $the_file = array();
    $file = fopen($file_address,'rb');
    if($file AND filesize($file_address) > 0) {
        $the_file['data']        = fread($file, filesize($file_address));
        $the_file['filesize']    = filesize($file_address);
        $the_file['filehash']    = md5($the_file['data']);
    }
    return $the_file;
}

function getextention($file) {
    return strtolower(substr(strrchr($file, "."), 1));
}

function strip_file_ext($name)  {
    if(($pos = strrpos($name, '.')) === false) return $name;
    return substr($name, 0, $pos);
}


function generate_thumbnail($file, $path, $filename, $maxheight, $maxwidth) {
    if(!function_exists("imagecreate")) {
        $thumb['code'] = 3;
        return $thumb;
    }
    list($imgwidth, $imgheight, $imgtype, $imgattr) = getimagesize($file);
    if(($imgwidth > $maxwidth) || ($imgheight > $maxheight)) {
        if($imgtype == 3)
        {
            if( function_exists("imagecreatefrompng"))
            {
                $im = imagecreatefrompng($file);
            }
        }
        elseif($imgtype == 2)
        {
            if(function_exists("imagecreatefromjpeg"))
            {
                $im = imagecreatefromjpeg($file);
            }
        }
        elseif($imgtype == 1)
        {
            if(function_exists("imagecreatefromgif"))
            {
                $im = imagecreatefromgif($file);
            }
        }
        else
        {
            $thumb['code'] = 3;
            return $thumb;
        }
        if(!$im)
        {
            $thumb['code'] = 3;
            return $thumb;
        }
        $scale = scaleImage($imgwidth, $imgheight, $maxwidth, $maxheight);
        $thumbwidth = $scale['width'];
        $thumbheight = $scale['height'];
        $thumbim = @imagecreatetruecolor($thumbwidth, $thumbheight);
        if($thumbim)
        {
            imagecopyresampled($thumbim, $im, 0, 0, 0, 0, $thumbwidth, $thumbheight, $imgwidth,$imgheight);
        }
        else
        {
            $thumbim = imagecreate($thumbwidth, $thumbheight);
            imagecopyresized($thumbim, $im, 0, 0, 0, 0, $thumbwidth, $thumbheight, $imgwidth, $imgheight);
        }
        @imagedestroy($im);
        if(!function_exists("imagegif") && $imgtype == 1)
        {
            $filename = str_replace(".gif", ".jpg", $filename);
        }
        switch($imgtype)
        {
            case 1:
                if(function_exists("imagegif"))
                {
                    @imagegif($thumbim, $path."/".$filename);
                }
                else
                {
                    @imagejpeg($thumbim, $path."/".$filename);
                }
                break;
            case 2:
                @imagejpeg($thumbim, $path."/".$filename);
                break;
            case 3:
                @imagepng($thumbim, $path."/".$filename);
                break;
        }
        @chmod($path."/".$filename, 0666);
        @imagedestroy($thumbim);
        $thumb['code'] = 1;
        $thumb['filename'] = $filename;
        return $thumb;
    }
    else {
        return array("code" => 4);
    }
}

function scaleImage($width, $height, $maxwidth, $maxheight) {
    $newwidth = $width;
    $newheight = $height;

    if($width > $maxwidth) {
        $newwidth = $maxwidth;
        $newheight = ceil(($height*(($maxwidth*100)/$width))/100);
        $height = $newheight;
        $width = $newwidth;
    }
    if($height > $maxheight) {
        $newheight = $maxheight;
        $newwidth = ceil(($width*(($maxheight*100)/$height))/100);
    }
    $ret['width'] = $newwidth;
    $ret['height'] = $newheight;
    return $ret;
}?>

also needs some method of converting passwords if possible