Конвертация HTML в BB-коды после конвертации форума

Конвертация HTML в BB-коды после конвертации форума 1.0.0

Нет прав для скачивания
Совместимость с XenForo
  1. 1.0
  2. 1.1
  3. 1.2
  4. 1.3
  5. 1.4
Описание: пример скрипта для конвертации. Зачастую, после конвертации форума некоторые сообщения могут побиться или выглядеть не очень правильно из-за того, что каких-то bb-кодов в XenForo просто нет.

Лично мне доводилось производить конвертацию форума vBulletin в XenForo, с которым стандартный конвертер не очень справился, в результате чего сообщения выглядели в виде просто html-кода, примерно так:

2015-03-25 20-21-14 Скриншот экрана.png

Если форум большой - существующие плагины (https://xenforo.info/resources/post-content-find-replace.2249/) тут особо не помогут, из-за чего может потребоваться запускать скрипт из консоли сервера (там нет лимита времени на выполнение). Собственно пример этого скрипта я и хотел бы привести. Около 10 вариантов для замены мной там уже прописано, поэтому знающим людям разобраться особых проблем не составит. После работы скрипта сообщения будут выглядеть как и положено, примерно так:

2015-03-25 21-49-59 Скриншот экрана.png

Обращаю внимание, что скрипт писался для себя и на коленке без особых планов на его дальнейшую поддержку или работу с ним. Просто в свое время понадобилось, может понадобится кому-то еще. Чтобы не потерялось - выкладываю:
PHP:
<?php

set_time_limit(0);

$startTime = microtime(true);
$fileDir = dirname(__FILE__);

require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');

XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);

for ($i = 0; $i <= 4000; $i++) {

    $input = array(
        'find1'    => 'http://img.forumimg.net/buttons/viewpost.gif',
        'regex1'   => '/<div style="margin:20px; margin-top:5px; "> <div class="smallfont" style="margin-bottom:2px">Цитата:<\/div> <table cellpadding="6" cellspacing="0" border="0" width="100%"> <tr> <td class="alt2" style="border:1px inset">  <div> Сообщение от <strong>(.*?)<\/strong> <a href="(.*?)" rel="nofollow"><img class="inlineimg" src="http:\/\/img\.forumimg\.net\/buttons\/viewpost\.gif" border="0" alt="Посмотреть сообщение" \/><\/a> <\/div> <div style="font-style:italic">(.*?)<\/div>  <\/td> <\/tr> <\/table> <\/div>/isu',
        'replace1' => '[QUOTE="$1"]$3[/QUOTE]',

        'find2'   => '<div style="margin:20px; margin-top:5px; "> <div class="smallfont" style="margin-bottom:2px">Цитата:</div> <table cellpadding="6" cellspacing="0" border="0" width="100%"> <tr> <td class="alt2" style="border:1px inset">  <div> Сообщение от <strong>',
        'regex2'   => '/<div style="margin:20px; margin-top:5px; "> <div class="smallfont" style="margin-bottom:2px">Цитата:<\/div> <table cellpadding="6" cellspacing="0" border="0" width="100%"> <tr> <td class="alt2" style="border:1px inset">  <div> Сообщение от <strong>(.*?)<\/strong>  <\/div> <div style="font-style:italic">(.*?)<\/div>  <\/td> <\/tr> <\/table> <\/div>/isu',
        'replace2' => '[QUOTE="$1"]$2[/QUOTE]',

        'find3'   => '<div style="margin:20px; margin-top:5px; "> <div class="smallfont" style="margin-bottom:2px">Цитата:</div> <table cellpadding="6" cellspacing="0" border="0" width="100%"> <tr> <td class="alt2" style="border:1px inset">',
        'regex3'   => '/<div style="margin:20px; margin-top:5px; "> <div class="smallfont" style="margin-bottom:2px">Цитата:<\/div> <table cellpadding="6" cellspacing="0" border="0" width="100%"> <tr> <td class="alt2" style="border:1px inset">(.*?)<\/td> <\/tr> <\/table> <\/div>/isu',
        'replace3' => '[QUOTE]$1[/QUOTE]',

        'find4'   => 'target="_blank"',
        'regex4'   => '/<a href="(.*?)" target="_blank">(.*?)<\/a>/isu',
        'replace4' => '[URL="$1"]$2[/URL]',

        'find5'   => ']Ответ:',
        'regex5'   => '/\[b\]Ответ:(.*?)\[\/b\]\n\n/isu',
        'replace5' => '',

        'find6'   => ']Re:',
        'regex6'   => '/\[b\]Re:(.*?)\[\/b\]\n\n/isu',
        'replace6' => '',

        'find7'   => '<font size',
        'regex7'   => '/<font size="(.*?)">(.*?)<\/font>/isu',
        'replace7' => '[SIZE=$1]$2[/SIZE]',

        'find8'   => '<font color',
        'regex8'   => '/<font color="(.*?)">(.*?)<\/font>/isu',
        'replace8' => '[COLOR=$1]$2[/COLOR]',

        'find9'   => '<img src=',
        'regex9'   => '/<img src="(.*?)" border="0" alt="" \/>/isu',
        'replace9' => '[IMG]$1[/IMG]',

        'find12'   => '>Код:',
        'regex12'   => '/<div style="margin:20px; margin-top:5px"> <div class="smallfont" style="margin-bottom:2px">Код:<\/div> <pre class="alt2" dir="ltr" style="(.*?)">(.*?)<\/pre> <\/div>/isu',
        'replace12' => '[CODE]$2[/CODE]',

        'find13'   => '>PHP код:',
        'regex13'   => '/<div style="margin:20px; margin-top:5px"> <div class="smallfont" style="margin-bottom:2px">PHP код:<\/div> <div class="alt2" dir="ltr" style="(.*?)"> <code style="white-space:nowrap"> <code>(.*?)<\/code> <\/code> <\/div> <\/div>/isu',
        'replace13' => '[PHP ]$2[/PHP ]',

        'find10'   => 'class="inlineimg"',
        'regex10'   => '/<img src="(.*?)" border="0" alt="" title="(.*?)" class="inlineimg" \/>/isu',
        'replace10' => ':-)',

        'find_'   => 'style="margin: 2px"',
        'regex_'   => '/<img src="(.*?)" style="margin: 2px" \/>/isu',
        'replace_' => '',

        'find'   => '<legend>Изображения',
        'regex'   => '/<\/div>    <div style="padding:6px">   <fieldset class="fieldset"> <legend>Изображения<\/legend> <div style="padding:3px"> <img class="attach" src="(.*?)<\/div> <\/fieldset>/isu',
        'replace' => '',
    );

    $db = XenForo_Application::get('db');
    $sql = "SELECT post.* FROM xf_post AS post WHERE post.message LIKE '%".$input['find']."%' ORDER BY post.post_id LIMIT 5000";
    $posts = $db->fetchAll($sql);
    $gamma = 0;
    foreach ($posts AS $postId => &$post)
    {
        echo $post['post_id'].' + ';
        if (preg_match_all($input['regex'], $post['message'], $matches))
        {
            $gamma++;
            $post['found'] = $matches[0];
            $post['replaced'] = preg_replace($input['regex'], $input['replace'], $post['found']);

            $message = preg_replace($input['regex'], $input['replace'], $post['message']);

            $dw = XenForo_DataWriter::create('XenForo_DataWriter_DiscussionMessage_Post');

            $dw->setOption(XenForo_DataWriter_DiscussionMessage::OPTION_IS_AUTOMATED, true);
            $dw->setExistingData($post, true);

            $dw->set('message', $message);

            $dw->save();
        }
        else
        {
            unset($posts[$postId]);
        }
    }
    echo ' SUMM: '.$i.'->'.$gamma.' | ';
}

echo 'done';
Запуск скрипта через консоль, при помощи /usr/bin/php (путь, естественно, свой), как-то так:
Код:
/usr/bin/php -f /var/www/main/data/***/site.ru/convert.php
Скрипт, разумеется, должен лежать в корне сайта. И после завершения "конвертации" не забывайте его удалить.

PS. Для работы с регулярными выражениями рекомендую
  • Мне нравится
Реакции: butik и SAS
Автор
Exile
Скачивания
7
Просмотры
259
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок

Другие ресурсы пользователя Exile

Поделиться ресурсом

Назад
Сверху Снизу