форум vBSupport.ru > vBulletin > vBulletin 4.2.x > Вопросы по vBulletin 4.2.x
Register Меню vBsupport Изображения Files Manager О рекламе Today's Posts Search
  • Родная гавань
  • Блок РКН снят
  • Premoderation
  • For English speaking users
  • Каталог Фрилансеров
  • If you want to buy some product or script
  • Администраторам
VBsupport перешел с домена .ORG на родной .RU Ура! Пожалуйста, обновите свои закладки - VBsupport.ru
Блок РКН снят, форум доступен на всей территории России, включая новые терртории, без VPN
На форуме введена премодерация ВСЕХ новых пользователей

Почта с временных сервисов, типа mailinator.com, gawab.com и/или прочих, которые предоставляют временный почтовый ящик без регистрации и/или почтовый ящик для рассылки спама, отслеживается и блокируется, а так же заносится в спам-блок форума, аккаунты удаляются
for English speaking users:
You may be surprised with restriction of access to the attachments of the forum. The reason is the recent change in vbsupport.org strategy:

- users with reputation < 10 belong to "simple_users" users' group
- if your reputation > 10 then administrator (kerk, Luvilla) can decide to move you into an "improved" group, but only manually

Main idea is to increase motivation of community members to share their ideas and willingness to support to each other. You may write an article for the subject where you are good enough, you may answer questions, you may share vbulletin.com/org content with vbsupport.org users, receiving "thanks" equal your reputation points. We should not only consume, we should produce something.

- you may:
* increase your reputation (doing something useful for another members of community) and being improved
* purchase temporary access to the improved category:
10 $ for 3 months. - this group can download attachments, reputation/posts do not matter.
20 $ for 3 months. - this group can download attachments, reputation/posts do not matter + adds eliminated + Inbox capacity increased + files manager increased permissions.

Please contact kerk or Luvilla regarding payments.

Important!:
- if your reputation will become less then 0, you will be moved into "simple_users" users' group automatically.*
*for temporary groups (pre-paid for 3 months) reputation/posts do not matter.
Уважаемые пользователи!

На форуме открыт новый раздел "Каталог фрилансеров"

и отдельный раздел для платных заказов "Куплю/Закажу"

Если вы хотите приобрести какой то скрипт/продукт/хак из каталогов перечисленных ниже:
Каталог модулей/хаков
Ещё раз обращаем Ваше внимание: всё, что Вы скачиваете и устанавливаете на свой форум, Вы устанавливаете исключительно на свой страх и риск.
Сообщество vBSupport'а физически не в состоянии проверять все стили, хаки и нули, выкладываемые пользователями.
Помните: безопасность Вашего проекта - Ваша забота.
Убедительная просьба: при обнаружении уязвимостей или сомнительных кодов обязательно отписывайтесь в теме хака/стиля
Спасибо за понимание
 
 
 
 
WatcherOfTheSun
Продвинутый
Default Лента активности. Попытка привести в божеский вид
7

В общем, что-то мне совсем не нравицца, как выглядит лента активности на форуме. Ну, то, что там многое выкусывается, оно понятно, типа превьюха. Но ведь читаемость пропадает напрочь. Про прикручивание смайлов в ленту активности я видел, но мне захотелось большего. Ну, вот, хотя бы форматирования текста нормального, возможность ссылки отображать...

Написать все это с нуля самому опыта не хватает, поэтому пошел рыть.
Ну, допустим вариант функции strip_bbcode я наваял. Добавил туда возможность не выкусывать ссылки и задавать список bb-кодов, которые нужно оставить в тексте.

PHP Code:
function strip_bbcode_ex($message, $stripquotes = false, $striplinks = true, $showlinks = true, $stripimg = false, $keeptags=null)
{
    
$find = array();
    
$replace = array();
        
$keeptags_str = "";
    
$block_elements = array(
        
'code',
        
'php',
        
'html',
        
'quote',
        
'indent',
        
'center',
        
'left',
        
'right',
        
'video',
    );

        (
$hook = vBulletinHook::fetch_hook('strip_bbcode')) ? eval($hook) : false;
        
    if (
$stripquotes)
    {
        
// [quote=username] and [quote]
        
$message = strip_quotes($message);
               
    }

    if (
$stripimg)
    {
        
$find[] = '#\[(attach|img|video).*\].+\[\/\\1\]#siU';
        
$replace[] = '';
    }

        if (
$striplinks)
        {
            
// simple links
            
$find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU';
            
$replace[] = '\3';

            
// named links
            
$find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU';
            
$replace[] = ($showlinks ? '\4 (\3)' : '\4');
        }
        
        
// replace links (and quotes if specified) from message
        
$message = preg_replace($find, $replace, $message);
        
        
        if (
is_array($keeptags))
            foreach(
$keeptags as $value)
              
$keeptags_str .= ((strlen($keeptags_str)!= 0) ? "|" : "") . $value;
         
        if (
strlen($keeptags_str) != 0)
        {
                
$regex = '#\[(?!' .$keeptags_str. ')(\w+?)(?>[^\]]*?)\](.*)(\[/\1\])#siU';
        } 
        else
        {
                
$regex = '#\[(\w+?)(?>[^\]]*?)\](.*)(\[/\1\])#siU';
        }

        
// strip out all other instances of [x]...[/x]
        
while(preg_match_all($regex, $message, $regs))
        { 
            
                foreach(
$regs[0] AS $key => $val)
                {
                        
$message  = str_replace($val, (in_array(strtolower($regs[1]["$key"]), $block_elements) ? "\n" : '') . $regs[2]["$key"], $message);
                }
        }
        
$message = str_replace('[*]', ' ', $message);
    return 
trim($message);
} 
Потом вот здесь нашел функцю, которая, вроде как, делает обрезку html с сохранением тегов. По мере способностей, допилил её для работы с UTF-8. mb_preg_match_all взял отсюда.
PHP Code:
function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
    if (
$considerHtml) {
        
// if the plain text is shorter than the maximum length, return the whole text
        
if (mb_strlen(preg_replace('/<.*?>/', '', $text),'utf-8') <= $length) {
            return 
$text;
        }
        
// splits all html-tags to scanable lines
        
mb_preg_match_all('/(<.+?>)?([^<>]*)/su', $text, $lines, PREG_SET_ORDER, 'utf-8');
        
$total_length = mb_strlen($ending, 'utf-8');
        
$open_tags = array();
        
$truncate = '';
        foreach (
$lines as $line_matchings) {
            
// if there is any html-tag in this line, handle it and add it (uncounted) to the output
            
if (!empty($line_matchings[1])) {
                
// if it's an "empty element" with or without xhtml-conform closing slash
                
if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/isu', $line_matchings[1])) {
                    
// do nothing
                // if tag is a closing tag
                
} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/su', $line_matchings[1], $tag_matchings)) {
                    
// delete tag from $open_tags list
                    
$pos = array_search($tag_matchings[1], $open_tags);
                    if (
$pos !== false) {
                    unset(
$open_tags[$pos]);
                    }
                
// if tag is an opening tag
                
} else if (preg_match('/^<\s*([^\s>!]+).*?>$/su', $line_matchings[1], $tag_matchings)) {
                    
// add tag to the beginning of $open_tags list
                    
array_unshift($open_tags, mb_strtolower($tag_matchings[1]), 'utf-8');
                }
                
// add html-tag to $truncate'd text
                
$truncate .= $line_matchings[1];
            }
            
// calculate the length of the plain text part of the line; handle entities as one character
            
$content_length = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/iu', ' ', $line_matchings[2]), 'utf-8');
            if (
$total_length+$content_length> $length) {
                
// the number of characters which are left
                
$left = $length - $total_length;
                
$entities_length = 0;
                
// search for html entities
                
if (mb_preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/iu', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE, 'utf-8')) {
                    
// calculate the real length of all entities in the legal range
                    
foreach ($entities[0] as $entity) {
                        if (
$entity[1]+1-$entities_length <= $left) {
                            
$left--;
                            
$entities_length += mb_strlen($entity[0], 'utf-8');
                        } else {
                            
// no more characters left
                            
break;
                        }
                    }
                }
                
$truncate .= mb_substr($line_matchings[2], 0, $left+$entities_length, 'utf-8');
                
// maximum lenght is reached, so get off the loop
                
break;
            } else {
                
$truncate .= $line_matchings[2];
                
$total_length += $content_length;
            }
            
// if the maximum length is reached, get off the loop
            
if($total_length>= $length) {
                break;
            }
        }
    } else {
        if (
mb_strlen($text, 'utf-8') <= $length) {
            return 
$text;
        } else {
            
$truncate = mb_substr($text, 0, $length - strlen($ending), 'utf-8');
        }
    }
    
// if the words shouldn't be cut in the middle...
    
if (!$exact) {
        
// ...search the last occurance of a space...
        
$spacepos = mb_strrpos($truncate, ' ', 'utf-8');
        if (isset(
$spacepos)) {
            
// ...and cut the text in this position
            
$truncate = mb_substr($truncate, 0, $spacepos, 'utf-8');
        }
    }
    
// add the defined ending to the text
    
$truncate .= $ending;
    if(
$considerHtml) {
        
// close all unclosed html-tags
        
foreach ($open_tags as $tag) {
            
$truncate .= '</' . $tag . '>';
        }
    }
    return 
$truncate;
} 
Потом на основании всего вышеуказанного запилил это:
PHP Code:
function MakePostActivityStreamPreview($source, $length, $forumid, $allowsmilie)
{
    
$keeptags = array('b','i','u','left','right','center','list','font','size','color',
        
'table','tr','td','quote');
    
    
$source = fetch_censored_text( strip_bbcode_ex($source, false, false, false, true, $keeptags) );

    global 
$vbulletin;
    require_once(
DIR . "/includes/class_bbcode.php");
    
$parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
    
$source = $parser->parse($source, $forumid, $allowsmilie, false, '', 3, false, 'on_nl2br');

    if (
$length > 0){
       
$source = TruncateHTML($source, $length);
    }    
    return 
$source;
} 


далее в vb/activitystream/view/perm/forum/thread.php в методе fetchTemplate заменил
PHP Code:
$threadinfo['preview'] = strip_quotes($threadinfo['pagetext']);
$threadinfo['preview'] = htmlspecialchars_uni(fetch_censored_text(
        
fetch_trimmed_title(strip_bbcode($threadinfo['preview'], false, true, true, true),
                
vb::$vbulletin->options['as_snippet'])
)); 
на
PHP Code:
$threadinfo['preview'] = MakePostActivityStreamPreview($threadinfo['pagetext'], 
        
vb::$vbulletin->options['as_snippet'], $threadinfo['forumid'], $threadinfo['allowsmilie']); 
и в методе process добавил в выборку поле allowsmilie:
Code:
SELECT
        t.threadid, t.title, t.forumid, t.pollid, t.open, t.views, t.visible, t.postuserid, t.postuserid AS userid, t.replycount,
        t.postusername, t.prefixid, fp.pagetext, fp.allowsmilie
аналогичные изменения и в vb/activitystream/view/perm/forum/post.php.

В результате лента активности приняла примерно такой вид:


Ну и раз тут таки "Вопросы", то сопцтвенно, вопрос. Может я чего где не учел/сделал не так/изобрел велосипед?

WatcherOfTheSun добавил 20.11.2014 в 19:19
Упс... Небольшой косячок. Подправил truncateHtml

PHP Code:
function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
    if (
$considerHtml) {
        
// if the plain text is shorter than the maximum length, return the whole text
        
if (mb_strlen(preg_replace('/<.*?>/', '', $text),'utf-8') <= $length) {
            return 
$text;
        }
        
// splits all html-tags to scanable lines
        
mb_preg_match_all('/(<.+?>)?([^<>]*)/su', $text, $lines, PREG_SET_ORDER, 'utf-8');
        
$total_length = mb_strlen($ending, 'utf-8');
        
$open_tags = array();
        
$truncate = '';
        foreach (
$lines as $line_matchings) {
            
// if there is any html-tag in this line, handle it and add it (uncounted) to the output
            
if (!empty($line_matchings[1])) {
                
// if it's an "empty element" with or without xhtml-conform closing slash
                
if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/isu', $line_matchings[1])) {
                    
// do nothing
                // if tag is a closing tag
                
} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/su', $line_matchings[1], $tag_matchings)) {
                    
// delete tag from $open_tags list
                    
$pos = array_search($tag_matchings[1], $open_tags);
                    if (
$pos !== false) {
                    unset(
$open_tags[$pos]);
                    }
                
// if tag is an opening tag
                
} else if (preg_match('/^<\s*([^\s>!]+).*?>$/su', $line_matchings[1], $tag_matchings)) {
                    
// add tag to the beginning of $open_tags list
                    
array_unshift($open_tags, mb_strtolower($tag_matchings[1], 'utf-8'));
                }
                
// add html-tag to $truncate'd text
                
$truncate .= $line_matchings[1];
            }
            
// calculate the length of the plain text part of the line; handle entities as one character
            
$content_length = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/iu', ' ', $line_matchings[2]), 'utf-8');
            if (
$total_length+$content_length> $length) {
                
// the number of characters which are left
                
$left = $length - $total_length;
                
$entities_length = 0;
                
// search for html entities
                
if (mb_preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/iu', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE, 'utf-8')) {
                    
// calculate the real length of all entities in the legal range
                    
foreach ($entities[0] as $entity) {
                        if (
$entity[1]+1-$entities_length <= $left) {
                            
$left--;
                            
$entities_length += mb_strlen($entity[0], 'utf-8');
                        } else {
                            
// no more characters left
                            
break;
                        }
                    }
                }
                
$truncate .= mb_substr($line_matchings[2], 0, $left+$entities_length, 'utf-8');
                
// maximum lenght is reached, so get off the loop
                
break;
            } else {
                
$truncate .= $line_matchings[2];
                
$total_length += $content_length;
            }
            
// if the maximum length is reached, get off the loop
            
if($total_length>= $length) {
                break;
            }
        }
    } else {
        if (
mb_strlen($text, 'utf-8') <= $length) {
            return 
$text;
        } else {
            
$truncate = mb_substr($text, 0, $length - strlen($ending), 'utf-8');
        }
    }
    
// if the words shouldn't be cut in the middle...
    
if (!$exact) {
        
// ...search the last occurance of a space...
        
$spacepos = mb_strrpos($truncate, ' ', 'utf-8');
        if (isset(
$spacepos)) {
            
// ...and cut the text in this position
            
$truncate = mb_substr($truncate, 0, $spacepos, 'utf-8');
        }
    }
    
// add the defined ending to the text
    
$truncate .= $ending;
    if(
$considerHtml) {
        
// close all unclosed html-tags
        
foreach ($open_tags as $tag) {
            
$truncate .= '</' . $tag . '>';
        }
    }
    return 
$truncate;
} 
WatcherOfTheSun добавил 21.11.2014 в 10:39
UPD.
Ну, вобчем, поковырявшись понял, что truncateHTML работает кривовато и написал по её мотивам обрезку текста с bbcode с закрытием тегов. Там, вроде, даже все проще получилось по причине более простой структуры тегов.
PHP Code:
function truncate_bbcoded_text($text, $length = 100, $ending = '...') 
{
        if (
mb_strlen(preg_replace('/<.*?>/', '', $text),'utf-8') <= $length) {
            return 
$text;
        }
        
mb_preg_match_all('/(\[.+?\])?([^\[\]]*)/su', $text, $lines, PREG_SET_ORDER, 'utf-8');
        
$total_length = mb_strlen($ending, 'utf-8');
        
$open_tags = array();
        
$truncate = '';
        foreach (
$lines as $line_matchings) {
            
            if (!empty(
$line_matchings[1])) {
                
                            
                if (
preg_match('/^\[\s*\/([^\s]+?)\s*\]$/su', $line_matchings[1], $tag_matchings)) {
                    
//close tag
                    
$pos = array_search(mb_strtolower($tag_matchings[1], 'utf-8'), $open_tags);
                                    
                    if (
$pos !== false) {
                    unset(
$open_tags[$pos]);
                    }
                                
                } else if (
preg_match('/^\[\s*([\w]+).*?\]$/su', $line_matchings[1], $tag_matchings)) {
                    
//open tag
                    
array_unshift($open_tags, mb_strtolower($tag_matchings[1], 'utf-8'));
                }
                
// add tag to truncated text
                
$truncate .= $line_matchings[1];
            }

            
$content_length = mb_strlen($line_matchings[2], 'utf-8');
            if (
$total_length+$content_length> $length) {
                
                
$pos = mb_strpos($line_matchings[2], ' ', $length - $total_length, 'utf-8');
                
$truncate .= ($pos) ? mb_substr($line_matchings[2], 0, $pos, 'utf-8'): $line_matchings[2];
                
                break;
            } else {
                
$truncate .= $line_matchings[2];
                
$total_length += $content_length;
            }            
            if (
$total_length >$length)
            {  
               break; 
            }
        }
    
    
// close all unclosed tags
    
foreach ($open_tags as $tag) {
        
$truncate .= '[/' . $tag . ']';
    }
    
    
$truncate .= $ending;
    return 
$truncate;
} 

Ну и, соответственно, обрезка текста перенесена на фазу до парсинга bb-кодов.
PHP Code:
function MakePostActivityStreamPreview($source, $length, $forumid, $allowsmilie)
{
    
$keeptags = array('b','i','u','left','right','center','list','font','size','color',
        
'table','tr','td','quote');
    
    
$source = fetch_censored_text( strip_bbcode_ex($source, false, false, false, true, $keeptags) );
    if (
$length > 0){
       
$source = truncate_bbcoded_text($source, $length,'...');
    }
    global 
$vbulletin;
    require_once(
DIR . "/includes/class_bbcode.php");
    
$parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
    
$source = $parser->parse($source, $forumid, $allowsmilie, false, '', 3, false, 'on_nl2br');

    return 
$source;
} 

Last edited by WatcherOfTheSun : 11-21-2014 at 11:39 AM. Reason: Добавлено сообщение
Bot
Yandex Bot Yandex Bot is online now
 
Join Date: 05.05.2005
Реклама на форуме А что у нас тут интересного? =)
 
 
dhonchik
Продвинутый
Экстремал
 
dhonchik's Avatar
Default
0

Ниче не понял что ты понаписал тут, но лента активности у тебя и вправду получше стала, можешь по пунктам написать что надо сделать чтобы было как у тебя, а н етак что вот это надо сделать, а нет вот это, а лучше вот так, потом ещё вставьте это
 
 
liner
Эксперт
 
liner's Avatar
Default
0

Оффтоп
 
 
WatcherOfTheSun
Продвинутый
Default
3

Quote:
Originally Posted by dhonchik View Post
Ниче не понял что ты понаписал тут, но лента активности у тебя и вправду получше стала, можешь по пунктам написать что надо сделать чтобы было как у тебя, а н етак что вот это надо сделать, а нет вот это, а лучше вот так, потом ещё вставьте это
Ну, я не то, чтобы готовое решение выкладывал. Так, просто мысли бродлили. Сейчас добродились до чего-то конкретного. Но, в принципе, могу и по шагам рассказать.
1. Делаем файл с таким содержимым (как его назвать и куда положить - личное дело каждого, у меня он называется preview_utils.php):
PHP Code:
<?php

require_once(DIR . "/includes/functions.php");

if (!
function_exists("mb_preg_match_all")) 
{
    function 
mb_preg_match_all($ps_pattern, $ps_subject, &$pa_matches, $pn_flags = PREG_PATTERN_ORDER, $pn_offset = 0, $ps_encoding = NULL) {
      
// WARNING! - All this function does is to correct offsets, nothing else:
      //
      
if (is_null($ps_encoding))
        
$ps_encoding = mb_internal_encoding();

      
$pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
      
$ret = preg_match_all($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);

      if (
$ret && ($pn_flags & PREG_OFFSET_CAPTURE))
        foreach(
$pa_matches as &$ha_match)
          foreach(
$ha_match as &$ha_match)
            
$ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
        
//
        // (code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)

      
return $ret;
    }

}







function 
truncate_bbcoded_text($text, $length = 100, $ending = '...') 
{
        if (
mb_strlen(preg_replace('/<.*?>/', '', $text),'utf-8') <= $length) {
            return 
$text;
        }
        
mb_preg_match_all('/(\[.+?\])?([^\[\]]*)/su', $text, $lines, PREG_SET_ORDER, 'utf-8');
        
$total_length = mb_strlen($ending, 'utf-8');
        
$open_tags = array();
        
$truncate = '';
        foreach (
$lines as $line_matchings) {
            
            if (!empty(
$line_matchings[1])) {
                
                            
                if (
preg_match('/^\[\s*\/([^\s]+?)\s*\]$/su', $line_matchings[1], $tag_matchings)) {
                    
//close tag
                    
$pos = array_search(mb_strtolower($tag_matchings[1], 'utf-8'), $open_tags);
                                    
                    if (
$pos !== false) {
                    unset(
$open_tags[$pos]);
                    }
                                
                } else if (
preg_match('/^\[\s*([\w]+).*?\]$/su', $line_matchings[1], $tag_matchings)) {
                    
//open tag
                    
array_unshift($open_tags, mb_strtolower($tag_matchings[1], 'utf-8'));
                }
                
// add tag to $truncate'd text
                
$truncate .= $line_matchings[1];
            }

            
$content_length = mb_strlen($line_matchings[2], 'utf-8');
            if (
$total_length+$content_length> $length) {
                
                
$pos = mb_strpos($line_matchings[2], ' ', $length - $total_length, 'utf-8');
                
$truncate .= ($pos) ? mb_substr($line_matchings[2], 0, $pos, 'utf-8'): $line_matchings[2];
                
                break;
            } else {
                
$truncate .= $line_matchings[2];
                
$total_length += $content_length;
            }            
            if (
$total_length >$length)
            {  
               break; 
            }
        }
    
    
// close all unclosed tags
    
foreach ($open_tags as $tag) {
        
$truncate .= '[/' . $tag . ']';
    }
    
    
$truncate .= $ending;
    return 
$truncate;
}


function 
strip_bbcode_ex($message, $stripquotes = false, $striplinks = true, $showlinks = true, $stripimg = false, $keeptags=null)
{
    
$find = array();
    
$replace = array();
        
$keeptags_str = "";
    
$block_elements = array(
        
'code',
        
'php',
        
'html',
        
'quote',
        
'indent',
        
'center',
        
'left',
        
'right',
        
'video',
    );

        (
$hook = vBulletinHook::fetch_hook('strip_bbcode')) ? eval($hook) : false;
        
    if (
$stripquotes)
    {
        
// [quote=username] and [quote]
        
$message = strip_quotes($message);
               
    }

    if (
$stripimg)
    {
        
$find[] = '#\[(attach|img|video).*\].+\[\/\\1\]#siU';
        
$replace[] = '';
    }

        if (
$striplinks)
        {
            
// simple links
            
$find[] = '#\[(email|url)=("??)(.+)\\2\]\\3\[/\\1\]#siU';
            
$replace[] = '\3';

            
// named links
            
$find[] = '#\[(email|url)=("??)(.+)\\2\](.+)\[/\\1\]#siU';
            
$replace[] = ($showlinks ? '\4 (\3)' : '\4');
        }
        
        
// replace links (and quotes if specified) from message
        
$message = preg_replace($find, $replace, $message);
        
        
        if (
is_array($keeptags))
            foreach(
$keeptags as $value)
              
$keeptags_str .= ((strlen($keeptags_str)!= 0) ? "|" : "") . $value;
         
        if (
strlen($keeptags_str) != 0)
        {
                
$regex = '#\[(?!' .$keeptags_str. ')(\w+?)(?>[^\]]*?)\](.*)(\[/\1\])#siU';
        } 
        else
        {
                
$regex = '#\[(\w+?)(?>[^\]]*?)\](.*)(\[/\1\])#siU';
        }

        
// strip out all other instances of [x]...[/x]
        
while(preg_match_all($regex, $message, $regs))
        { 
            
                foreach(
$regs[0] AS $key => $val)
                {
                        
$message  = str_replace($val, (in_array(strtolower($regs[1]["$key"]), $block_elements) ? "\n" : '') . $regs[2]["$key"], $message);
                }
        }
        
$message = str_replace('[*]', ' ', $message);
    return 
trim($message);
}



function 
MakePostActivityStreamPreview($source, $length, $forumid, $allowsmilie)
{
    
$keeptags = array('b','i','u','left','right','center','list','font','size','color',
        
'table','tr','td','quote');
    
    
$source = fetch_censored_text( strip_bbcode_ex($source, false, false, false, true, $keeptags) );
    if (
$length > 0){
       
$source = truncate_bbcoded_text($source, $length,'...');
    }
    global 
$vbulletin;
    require_once(
DIR . "/includes/class_bbcode.php");
    
$parser = new vB_BbCodeParser($vbulletin, fetch_tag_list());
    
$source = $parser->parse($source, $forumid, $allowsmilie, false, '', 3, false, 'on_nl2br');

    return 
$source;
}

?>
В функции MakePostActivityStreamPreview в массиве $keeptags определяется, какие теги нужно оставить в тексте. Я оставил базовое форматирование, таблицы, цитаты.




2. Идем в forum\vb\activitystream\view\perm\forum\post.php

2.1 добавляем в начало файла что-то типа (путь подправить, чтобы показывал на файл из пункта 1)
PHP Code:
 require_once(DIR . "/includes/preview_utils.php"); 

2.2 находим там метод process и в выборку добавляем поле allowsmilie


Code:
SELECT
    p.postid AS p_postid, p.threadid AS p_threadid, p.title AS p_title, p.visible AS p_visible, p.userid AS p_userid, p.pagetext AS p_pagetext, p.username AS p_username,
    t.threadid AS t_threadid, t.title AS t_title, t.forumid AS t_forumid, t.pollid AS t_pollid, t.open AS t_open, t.postusername AS t_postusername,
    t.views AS t_views, t.visible AS t_visible, t.postuserid AS t_postuserid, t.postuserid AS t_userid, t.replycount AS t_replycount,
    fp.pagetext AS t_pagetext, p.allowsmilie as p_allowsmilie
2.3 Находим метод fetchTemplate и меняем там
Вот это:
PHP Code:
        $preview = strip_quotes($postinfo['pagetext']);
        
$postinfo['preview'] = htmlspecialchars_uni(fetch_censored_text(
            
fetch_trimmed_title(strip_bbcode($preview, false, true, true, true),
                
vb::$vbulletin->options['as_snippet'])
        )); 
на вот это:
PHP Code:
        $postinfo['preview'] = MakePostActivityStreamPreview($postinfo['pagetext'], 
                
vb::$vbulletin->options['as_snippet'], $threadinfo['forumid'], $postinfo['allowsmilie']); 

3. идем в forum\vb\activitystream\view\perm\forum\thread.php

3.1 добавляем в начало подключение preview_utils.php аналогично пункту 2.1

3.2 находим там метод process и в выборку добавляем поле allowsmilie

Code:
SELECT
    t.threadid, t.title, t.forumid, t.pollid, t.open, t.views, t.visible, t.postuserid, t.postuserid AS userid, t.replycount,
    t.postusername, fp.pagetext, fp.allowsmilie
3.3 Находим метод fetchTemplate и меняем там
Вот это:
PHP Code:
$threadinfo['preview'] = strip_quotes($threadinfo['pagetext']);
        
$threadinfo['preview'] = htmlspecialchars_uni(fetch_censored_text(
            
fetch_trimmed_title(strip_bbcode($threadinfo['preview'], false, true, true, true),
                
vb::$vbulletin->options['as_snippet'])
        )); 
на вот это:
PHP Code:
        $threadinfo['preview'] = MakePostActivityStreamPreview($threadinfo['pagetext'], 
                
vb::$vbulletin->options['as_snippet'], $threadinfo['forumid'], $threadinfo['allowsmilie']); 
Вроде все.
Проверялось на 4.2.0 и 4.2.2
 
 
Luvilla
Гость
Default

@WatcherOfTheSun, отлично, отлично... "Приведение 4ки в божеский вид - дело рук самих четвёрошников. Нет смысла ждать милостей от разрабов, напильник в руки, и - вперёд..."

Бонус (в честь пятницы): "продвинутый" статус до конца года
 
 
dhonchik
Продвинутый
Экстремал
 
dhonchik's Avatar
Default
0

У меня ошибку выдаёт, белый лист, require_once(DIR . "/forum/includes/preview_utils.php"); require_once(DIR . "/forum/includes/preview_utils.php");

pescups.ru/forum/activity.php

Last edited by dhonchik : 11-21-2014 at 04:42 PM.
 
 
WatcherOfTheSun
Продвинутый
Default
1

Quote:
Originally Posted by Luvilla View Post
Нет смысла ждать милостей от разрабов, напильник в руки, и - вперёд..."
Ну, так это... "Не ждать милостей" - это нормальное состояние. Мне, как программеру, не привыкать во всяких потрохах ковыряться. Другое дело, что я вообще ни разу не вебпрограммер и не php-шник, а всем этим занимаюсь в режиме "больше некому". Но это - тоже нормально.

Quote:
Бонус (в честь пятницы): "продвинутый" статус до конца года
Окак... И шо мне с этим теперь делать?
 
 
Luvilla
Гость
Default

Quote:
Originally Posted by WatcherOfTheSun View Post
И шо мне с этим теперь делать?
можно качать вложения
можно править свои посты
а можно просто выпить в честь пятницы
 
 
WatcherOfTheSun
Продвинутый
Default
0

Quote:
Originally Posted by dhonchik View Post
У меня ошибку выдаёт, белый лист, require_once(DIR . "/forum/includes/preview_utils.php"); require_once(DIR . "/forum/includes/preview_utils.php");

pescups.ru/forum/activity.php
Я вот фиг знает. А файлик-то на месте лежит? У меня работает в трех местах: на живом форуме (IIS, винда, 4.2.0), на его же виртуальной копии (но под 4.2.2) и на домашнем тестовом NAS-е под линуксом (4.2.0).
 
 
dhonchik
Продвинутый
Экстремал
 
dhonchik's Avatar
Default
0

Жаль что не пашет что этот метод у меня, может потому что 4.2.3 beta 3 но я сомневаюсь

dhonchik добавил 21.11.2014 в 15:54
Quote:
Originally Posted by WatcherOfTheSun View Post
Я вот фиг знает. А файлик-то на месте лежит?
Да, создал файл в Includes с тем содержимым что ты скинул, потом подредактировал post.php и thead.php как у тебя указано и чет не работает

Last edited by dhonchik : 11-21-2014 at 04:54 PM. Reason: Добавлено сообщение
 


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off




All times are GMT +4. The time now is 03:30 PM.


Powered by vBulletin® Version Ъ Edition
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.