<?
set_time_limit
(0);
if (!
file_exists('./vars.php'))
    die(
'File vars.php does\'t exist');
else
    include(
'./vars.php');

$lastID 23624;

/*~~~~~~~~~~ define's section ~~~~~~~~~*/
define('DB_HOST''localhost');// DB host
define('DB_LOGIN''');// login to DB
define('DB_PASS''');// pass to DB
define('DB_NAME''');// DB name
define('PHPBB_PREFIX''phpbb_');// prefix to phpBB's tables
define('TBL_WITH_FORUM_IDS''b_gp_old_bb');// table with old and new IDs
define('TBL_WITH_TOPIC_IDS''b_gp_old_bb_topics');// table with old and new topic's IDs
define('TBL_WITH_POSTS_IDS''b_gp_old_bb_posts');// table with old and new topic's IDs
define('POST_STICKY'1);// from constants of phpBB
define('GUEST_NAME''Guest');// name for not authorized users
define('QUOTE_WRITE''пишет');// string for quotes
define('UPDATE_TOPIC_COUNT''Y');// can Bitrix update count of topics with CForumTopic::Add? Y/N
define('LIMIT_FOR_ONE_STEP''300');// max limit for one select
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~ variable's section ~~~~~~~~~*/
$arAllTopics = array();
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~~~~~ connect to DB ~~~~~~~~~~*/
$link mysql_connect(DB_HOSTDB_LOGINDB_PASS);
if (!
$link)
{
    die(
"Error connect to DB!");
}
/*~~~~~~~~ afterconnect section ~~~~~~~~*/
mysql_query("SET NAMES 'UTF8'");
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mysql_select_db(DB_NAME);
if (
$e mysql_error($link))
{
    die(
$e);
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~~~~~~~~ checking ~~~~~~~~~~~~*/
$strSql "SELECT OLD_ID, NEW_ID FROM ".TBL_WITH_FORUM_IDS;
$rs mysql_query($strSql);
if (
$e mysql_error($link))
{
    die(
$e);
}
$strSql "SELECT OLD_ID, NEW_ID FROM ".TBL_WITH_POSTS_IDS;
$rs mysql_query($strSql);
if (
$e mysql_error($link))
{
    die(
$e);
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~ function's section ~~~~~~~~~*/
function __ConvertPosts($txt)
{
    global 
$arTruncateBB;

    
// truncate BB
    
foreach ($arTruncateBB as $bb)
    {
        
$txt preg_replace('/(\['.$bb.'.*?\])/'""$txt);
        
$txt preg_replace('/(\[\/'.$bb.'\])/'""$txt);
    }

    
// special chars
    
$txt preg_replace('/(&#([\d]+);)/e'"chr('\\2')"$txt);
    
// smiles by CAHbI4
    
$txt preg_replace('/(<!--[ ]+s.*?[ ]+-->.*?<img.*?alt="(.*?)".*?\/>.*?<!--[ ]+s.*?[ ]+-->)/''${2}'$txt);
    
// links
    
$txt preg_replace('/(<a.*?href="(.*?)".*?>(.*?)<\/a>)/''[url=${2}]${3}[/url]'$txt);
    
// quotes by CAHbI4
    
$txt preg_replace('/(.*?\[quote)=&quot;(.*?)&quot;\](.*?)/''${1}]${2} '.QUOTE_WRITE.':'."\n".' ${3}'$txt, -1$rpl_cnt);
    
// tech.comments
    
$txt preg_replace('/(<!--.*?-->)/'""$txt);

    return 
$txt;
}

$arExistUser = array();
function 
__GetUserInfo($userID)
{
    global 
$arExistSess;

    if (!isset(
$arExistSess[$userID]))
    {
        
$rsUser CUser::GetList($by="ID"$order="DESC", array("UF_PHPBB_ID" => $userID));
        if (
$arUser $rsUser->GetNext())
        {
            
$arExistSess[$userID] = array("ID" => $arUser["ID"], "NAME" => $arUser["LOGIN"]);
        }
        else
        {
            
$arExistSess[$userID] = array("ID" => """NAME" => GUEST_NAME);
        }
    }

    return 
$arExistSess[$userID];
}

function 
__GetAttachmentsArray($postID)
{
    
/*
    must be return array (see CFile::MakeFileArray()):
    array =>
            0 => array("name", "size", "tmp_name", "type"),
            1 => array("name", "size", "tmp_name", "type"),
            ...
    or "" if post have not attachments
    */
    
$arFiles = array();

    
/*~~~~ for example ~~~~*/
    /*
    $arFiles = array(
                    CFile::MakeFileArray($_SERVER['DOCUMENT_ROOT']."/00.jpg"),
                    CFile::MakeFileArray($_SERVER['DOCUMENT_ROOT']."/00s.jpg"),
                    );
    */
    /*~~~~~~~~~~~~~~~~~~~~~*/

    
if (empty($arFiles))
        return 
"";
    else
        return 
$arFiles;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~~~~~~ main select ~~~~~~~~~~~*/
$strSql " SELECT
                bb_topics.*, bb_old.NEW_ID AS new_forum_id
            FROM
                "
.PHPBB_PREFIX."topics AS bb_topics
            RIGHT JOIN
                "
.TBL_WITH_FORUM_IDS." AS bb_old
            ON
                bb_old.OLD_ID = bb_topics.forum_id
            WHERE bb_topics.topic_id > 
$lastID
            ORDER BY
                topic_id ASC
            LIMIT "
.LIMIT_FOR_ONE_STEP.";";
$rsTopics mysql_query($strSql);
if (
$e mysql_error($link))
{
    die(
$e);
}
while (
$arTopics mysql_fetch_assoc($rsTopics))
{
    
$strSql "SELECT * FROM ".PHPBB_PREFIX."posts WHERE topic_id=".$arTopics["topic_id"]." ORDER BY post_id ASC";
    
$rsPosts mysql_query($strSql);
    if (!
$e mysql_error($link))
    {
        
$arTopics["topic_posts"] = array();
        while (
$arPosts mysql_fetch_assoc($rsPosts))
        {
            
$arPosts["post_text"] = str_replace(":".$arPosts["bbcode_uid"], ""$arPosts["post_text"]);
            
$arPosts["post_text"] = __ConvertPosts($arPosts["post_text"]);
            
$arTopics["topic_posts"][] = $arPosts;
        }
    }
    else
    {
        
$arTopics["topic_posts"] = "null";
    }

    
$arAllTopics[] = $arTopics;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mysql_close($link);
?>
<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/header.php");
$APPLICATION->SetTitle("Update forum");
?>
<?
if (CModule::IncludeModule("forum")):

    foreach (
$arAllTopics as $arItem)
    {
        echo 
"Moving id ".$arItem["topic_id"].": ";

        
$arUser __GetUserInfo($arItem["topic_poster"]);
        
$arUserLast __GetUserInfo($arItem["topic_last_poster_id"]);

        
$arFields = array(
                        
"TITLE" => $arItem["topic_title"],
                        
"STATE" => $arItem["topic_status"]=="N" "Y",
                        
"USER_START_ID" => $arUser["ID"],
                        
"USER_START_NAME" => trim($arItem["topic_first_poster_name"])=="" $arUser["NAME"] : $arItem["topic_first_poster_name"],
                        
"START_DATE" => date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")), $arItem["topic_time"]),
                        
"ICON_ID" => $arLinkIcons[$arItem["icon_id"]],
                        
"VIEWS" => $arItem["topic_views"],
                        
"FORUM_ID" => $arItem["new_forum_id"],
                        
"APPROVED" => $arItem["topic_approved"]=="Y" "N",
                        
"SORT" => $arItem["topic_type"]==POST_STICKY "250" "150",
                        
"LAST_POSTER_ID" => $arUserLast["ID"],
                        
"LAST_POSTER_NAME" => trim($arItem["topic_last_poster_name"])=="" $arUserLast["NAME"] : $arItem["topic_last_poster_name"],
                        
"LAST_POST_DATE" => date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")), $arItem["last_post_time"]),
                        );
        
$newTID CForumTopic::Add($arFields);
        if (
$newTID 0)
        {
            echo 
"<font color=\"green\">success add topic, new ID = $newTID</font>, ";
            echo 
"adding posts: ";
            if (
$arItem["topic_posts"] == "null")
            {
                echo 
"<font color=\"red\">post array is empty, TID $newTID was deleted.</font>";
                
CForumTopic::Delete($newTID);
            }
            else
            {
                if (
UPDATE_TOPIC_COUNT == "Y")
                {
                    
$DB->Query("UPDATE b_forum SET TOPICS=TOPICS+1 WHERE ID=".$arItem["new_forum_id"]);
                }

                
$DB->Query("INSERT INTO ".TBL_WITH_TOPIC_IDS." (OLD_ID, NEW_ID) VALUES(".$arItem["topic_id"].", $newTID);");

                
$succ 0;
                
$fail 0;
                foreach (
$arItem["topic_posts"] as $arPost)
                {
                    
$arUser __GetUserInfo($arPost["poster_id"]);

                    
$arFields = array(
                                    
"AUTHOR_ID" => $arUser["ID"],
                                    
"AUTHOR_NAME" => trim($arPost["post_username"])=="" $arUser["NAME"] : $arPost["post_username"],
                                    
"AUTHOR_IP" => $arPost["poster_ip"],
                                    
"USE_SMILES" => $arPost["enable_smilies"]=="Y" "N",
                                    
"POST_DATE" => date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")), $arPost["post_time"]),
                                    
"POST_MESSAGE" => $arPost["post_text"],
                                    
"FORUM_ID" => $arItem["new_forum_id"],
                                    
"TOPIC_ID" => $newTID,
                                    
"APPROVED" => $arPost["post_approved"]=="Y" "N",
                                    
"FILES" => __GetAttachmentsArray($arPost["post_id"]),
                                    );
                    if (
$arPost["post_edit_time"] > 0)
                    {
                        
$arUserEdit __GetUserInfo($arPost["post_edit_user"]);
                        
$arFields["EDIT_DATE"] = date($DB->DateFormatToPHP(CLang::GetDateFormat("FULL")), $arPost["post_edit_time"]);
                        
$arFields["EDIT_REASON"] = $arPost["post_edit_reason"];
                        
$arFields["EDITOR_NAME"] = $arUserEdit["NAME"];
                        
$arFields["EDITOR_ID"] = $arUserEdit["ID"];
                    }
                    
$MID CForumMessage::Add($arFields);
                    if (
$MID 0)
                    {
                        
$DB->Query("INSERT INTO ".TBL_WITH_POSTS_IDS." (OLD_ID, NEW_ID) VALUES(".$arPost["post_id"].", $MID);");
                        
$succ++;
                    }
                    else
                    {
                        
$fail++;
                    }
                }
                echo 
"<font color=\"green\">success added $succ posts</font>";
                if (
$fail 0)
                    echo 
", <font color=\"red\">$fail posts was not added</font>";

                echo 
". Complete.";
            }
        }
        else
        {
            echo 
"<font color=\"red\">error add topic</font>";
        }

        echo 
"<br />";
    }

endif;
?>
<?
require($_SERVER['DOCUMENT_ROOT']."/bitrix/footer.php");?>