VBsupport перешел с домена .ORG на родной .RU
Ура!
Пожалуйста, обновите свои закладки - VBsupport.ru
Блок РКН снят, форум доступен на всей территории России, включая новые терртории, без VPN
На форуме введена премодерация ВСЕХ новых пользователей
Почта с временных сервисов, типа mailinator.com, gawab.com и/или прочих, которые предоставляют временный почтовый ящик без регистрации и/или почтовый ящик для рассылки спама, отслеживается и блокируется, а так же заносится в спам-блок форума, аккаунты удаляются
Если вы хотите приобрести какой то скрипт/продукт/хак из каталогов перечисленных ниже: Каталог модулей/хаков
Ещё раз обращаем Ваше внимание: всё, что Вы скачиваете и устанавливаете на свой форум, Вы устанавливаете исключительно на свой страх и риск.
Сообщество vBSupport'а физически не в состоянии проверять все стили, хаки и нули, выкладываемые пользователями.
Помните: безопасность Вашего проекта - Ваша забота. Убедительная просьба: при обнаружении уязвимостей или сомнительных кодов обязательно отписывайтесь в теме хака/стиля
Спасибо за понимание
В общем, что-то мне совсем не нравицца, как выглядит лента активности на форуме. Ну, то, что там многое выкусывается, оно понятно, типа превьюха. Но ведь читаемость пропадает напрочь. Про прикручивание смайлов в ленту активности я видел, но мне захотелось большего. Ну, вот, хотя бы форматирования текста нормального, возможность ссылки отображать...
Написать все это с нуля самому опыта не хватает, поэтому пошел рыть.
Ну, допустим вариант функции strip_bbcode я наваял. Добавил туда возможность не выкусывать ссылки и задавать список bb-кодов, которые нужно оставить в тексте.
Потом вот здесь нашел функцю, которая, вроде как, делает обрезку 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');
аналогичные изменения и в 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 с закрытием тегов. Там, вроде, даже все проще получилось по причине более простой структуры тегов.
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) {
Ниче не понял что ты понаписал тут, но лента активности у тебя и вправду получше стала, можешь по пунктам написать что надо сделать чтобы было как у тебя, а н етак что вот это надо сделать, а нет вот это, а лучше вот так, потом ещё вставьте это
поставил ленту от GiveMeABreak
выглядит так
+ звук новых сообщений в ленте
+ обновление на ajax
+ подсветка новых сообщений
+ фильтр
@WatcherOfTheSun
Продвинутый
Join Date: Mar 2013
Posts: 63
Версия vB: 4.2.х
Reputation:
Опытный 27
Репутация в разделе: 23
3
Quote:
Originally Posted by dhonchik
Ниче не понял что ты понаписал тут, но лента активности у тебя и вправду получше стала, можешь по пунктам написать что надо сделать чтобы было как у тебя, а н етак что вот это надо сделать, а нет вот это, а лучше вот так, потом ещё вставьте это
Ну, я не то, чтобы готовое решение выкладывал. Так, просто мысли бродлили. Сейчас добродились до чего-то конкретного. Но, в принципе, могу и по шагам рассказать.
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();
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) {
В функции MakePostActivityStreamPreview в массиве $keeptags определяется, какие теги нужно оставить в тексте. Я оставил базовое форматирование, таблицы, цитаты.
2. Идем в forum\vb\activitystream\view\perm\forum\post.php
2.1 добавляем в начало файла что-то типа (путь подправить, чтобы показывал на файл из пункта 1)
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 и меняем там
Вот это:
@WatcherOfTheSun, отлично, отлично... "Приведение 4ки в божеский вид - дело рук самих четвёрошников. Нет смысла ждать милостей от разрабов, напильник в руки, и - вперёд..."
Бонус (в честь пятницы): "продвинутый" статус до конца года
@dhonchik
Продвинутый
Join Date: Feb 2012
Location: Архангельск
Posts: 909
Версия vB: 4.2.х
Пол:
Reputation:
Опытный 46
Репутация в разделе: 84
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
Продвинутый
Join Date: Mar 2013
Posts: 63
Версия vB: 4.2.х
Reputation:
Опытный 27
Репутация в разделе: 23
1
Quote:
Originally Posted by Luvilla
Нет смысла ждать милостей от разрабов, напильник в руки, и - вперёд..."
Ну, так это... "Не ждать милостей" - это нормальное состояние. Мне, как программеру, не привыкать во всяких потрохах ковыряться. Другое дело, что я вообще ни разу не вебпрограммер и не php-шник, а всем этим занимаюсь в режиме "больше некому". Но это - тоже нормально.
Quote:
Бонус (в честь пятницы): "продвинутый" статус до конца года
Окак... И шо мне с этим теперь делать?
Luvilla
Гость
Posts: n/a
Quote:
Originally Posted by WatcherOfTheSun
И шо мне с этим теперь делать?
можно качать вложения
можно править свои посты
а можно просто выпить в честь пятницы
@WatcherOfTheSun
Продвинутый
Join Date: Mar 2013
Posts: 63
Версия vB: 4.2.х
Reputation:
Опытный 27
Репутация в разделе: 23
0
Quote:
Originally Posted by dhonchik
У меня ошибку выдаёт, белый лист, 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
Продвинутый
Join Date: Feb 2012
Location: Архангельск
Posts: 909
Версия vB: 4.2.х
Пол:
Reputation:
Опытный 46
Репутация в разделе: 84
0
Жаль что не пашет что этот метод у меня, может потому что 4.2.3 beta 3 но я сомневаюсь
dhonchik добавил 21.11.2014 в 15:54
Quote:
Originally Posted by WatcherOfTheSun
Я вот фиг знает. А файлик-то на месте лежит?
Да, создал файл в Includes с тем содержимым что ты скинул, потом подредактировал post.php и thead.php как у тебя указано и чет не работает
Last edited by dhonchik : 11-21-2014 at 04:54 PM.
Reason: Добавлено сообщение