- Автор темы
- Администратор
- Модер.
- Команда форума
- #1
Добрый день всем. Всё тестилось и работает на ксени 1.2.5
Собственно решение для создания ЛС и простого обращения по никам.
Т.е. Будут использоваться
/to - обращение по нику с подсветкой строки желтоватого цвета
/pm - личное сообщение с подсветкой строки красноватого цвета
Работает по клику ника. Первый клик - преобразуется маска ява скрипта в /to, второй клик преобразует в /pm, третий снова в /to и т.д.
Так выглядят сообщения м/у участниками, без ЛС - простые посты и обращения по нику:
Делается всё очень просто!!!
1. Устанавливаем версию 1.2.0 ТАЙГАЧАТ (может работать по сути и на 0.5.5!!!)
2. Заходим в /js/dark/taigachat.js и весь код меняем на этот:
3. Идем в бибку создания модели: \library\Dark\TaigaChat\Model\TaigaChat.php
Будет производиться выборка из БД для /pm
Заменяем все на это
4. Идем в глобал! \library\Dark\TaigaChat\Helper\Global.php
И заменяем весь код на этот:
5. Шаблоны! Открываем - dark_taigachat.css и добавляем (учтите, что картинки сами найдете, сами знаете где... я про иконки, красную, зеленую, синюю)
6. Открываете шаблон dark_taigachat_list
И заменяете на:
7.8.9. И еще
Шаблон dark_taigachat_single (для того, чтоб пр редактировании сообщения - не слетал CSS)
Заменить все на это:
Собственно всё на этом.
С чего все начиналось!!!
Изначально послужила статья "ЛОГИКА СКРИПТА ЛИЧНЫХ СООБЩЕНИЙ"
Не реклама: _http://phpclub.ru/talk/threads/Логика-скрипта-личных-сообщений.70204/
Собственно решение для создания ЛС и простого обращения по никам.
Т.е. Будут использоваться
/to - обращение по нику с подсветкой строки желтоватого цвета
/pm - личное сообщение с подсветкой строки красноватого цвета
Работает по клику ника. Первый клик - преобразуется маска ява скрипта в /to, второй клик преобразует в /pm, третий снова в /to и т.д.
Так выглядят сообщения м/у участниками, без ЛС - простые посты и обращения по нику:
Делается всё очень просто!!!
1. Устанавливаем версию 1.2.0 ТАЙГАЧАТ (может работать по сути и на 0.5.5!!!)
2. Заходим в /js/dark/taigachat.js и весь код меняем на этот:
PHP:
/* Darkimmortal's TaigaChat */
var taigachat_decay = 1.25;
var taigachat_refreshtime = 5;
var taigachat_initialFired = false;
var taigachat_reverse = false;
var taigachat_initialTime = 0;
var taigachat_lastRefresh = 0;
var taigachat_lastRefreshServer = 0;
var taigachat_lastMessage = 0;
//var taigachat_refreshTimer = false;
var taigachat_nextRefresh = 0;
var taigachat_isRefreshing = false;
var taigachat_lastPostTime = 0;
var taigachat_lastPostMessage = "";
var taigachat_scrolled = false;
var taigachat_PopupMenu = XenForo.PopupMenu;
taigachat_PopupMenu.setMenuPosition = function(caller){
//console.info('setMenuPosition(%s)', caller);
var controlLayout, // control coordinates
menuLayout, // menu coordinates
contentLayout, // #content coordinates
$content,
$window,
proposedLeft,
proposedTop;
controlLayout = this.$control.coords('outer');
this.$control.removeClass('BottomControl');
// set the menu to sit flush with the left of the control, immediately below it
this.$menu.removeClass('BottomControl').css(
{
left: controlLayout.left,
top: controlLayout.top + controlLayout.height
});
menuLayout = this.$menu.coords('outer');
$content = $('#content .pageContent');
if ($content.length)
{
contentLayout = $content.coords('outer');
}
else
{
contentLayout = $('body').coords('outer');
}
$window = $(window);
$window.sT = $window.scrollTop();
$window.sL = $window.scrollLeft();
/*
* if the menu's right edge is off the screen, check to see if
* it would be better to position it flush with the right edge of the control
*/
if (menuLayout.left + menuLayout.width > contentLayout.left + contentLayout.width)
{
proposedLeft = controlLayout.left + controlLayout.width - menuLayout.width;
// must always position to left with mobile webkit as the menu seems to close if it goes off the screen
if (proposedLeft > $window.sL || XenForo._isWebkitMobile)
{
this.$menu.css('left', proposedLeft);
}
}
/*
* if the menu's bottom edge is off the screen, check to see if
* it would be better to position it above the control
*/
//if (menuLayout.top + menuLayout.height > $window.height() + $window.sT)
{
proposedTop = controlLayout.top - menuLayout.height-500;
//if (proposedTop > $window.sT)
{
this.$control.addClass('BottomControl');
this.$menu.addClass('BottomControl');
this.$menu.css('top', proposedTop);
}
}
};
$(document).ready(function(){
$(window).focus(taigachat_focus);
$("#taigachat_message").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
sendShout();
return false;
}
if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)) {
setTimeout("$('#taigachat_message').val('');", 200);
setTimeout("$('#taigachat_message').focus();", 300);
}
return true;
});
$('a.dark_tc_username').live('click', function () {
try {
var username = $(this).attr('title').toString();
if (!username) {
return;
}
if (!$('#taigachat_message')) {
return;
}
var msg = $('#taigachat_message').val().toString();
var replacement = '/to ' + username + ': ' + msg;
if (msg.length >= 6 + username.length) {
var mask = msg.substring(0, 6 + username.length);
var _ra = '/to ' + username + ': ';
var _rb = '/pm ' + username + ': ';
if (mask == _ra) {
replacement = msg.replace(/^\/to/, '/pm');
}
if (mask == _rb) {
replacement = msg.replace(/^\/pm/, '/to');
}
}
$('#taigachat_message').val(replacement);
$('#taigachat_message').focus();
} catch (e) { }
return false;
});
$("#taigachat_smilies").hover(function(){
if($(".taigachat_smilie > img").length > 0)
return;
$(".taigachat_smilie").each(function(){
if($(this).hasClass('mceSmilieSprite')){
var img = $("<img />");
img.attr("src", "styles/default/xenforo/clear.png");
img.attr("alt", $(this).attr("data-alt"));
img.attr("title", $(this).attr("data-title"));
img.attr("class", $(this).attr("class").replace("taigachat_smilie", ""));
$(this).append(img);
} else {
var img = $("<img />");
img.attr("src", $(this).attr("data-src"));
img.attr("alt", $(this).attr("data-alt"));
img.attr("title", $(this).attr("data-title"));
$(this).append(img);
}
});
$(this).unbind('hover');
});
$("#taigachat_send").click(sendShout);
refreshShoutbox(true, true, false);
$("#taigachat_send, #taigachat_message").removeAttr('disabled').removeClass('disabled');
//$("#taigachat_message").val("");
$("#taigachat_message").focus(function(e){
if($("#taigachat_toolbar:visible").length == 0){
$("#taigachat_toolbar").slideDown(500);
}
});
$(".taigachat_smilie").live('click', function(e){
e.stopPropagation();
if($("#taigachat_message").val() == $("#taigachat_message").attr("placeholder")){
$("#taigachat_message").removeClass("prompt").val("");
}
$("#taigachat_message").insertAroundCaret(" " + $(this).children("img").attr("alt") + " ", "");
return true;
});
$(".taigachat_bbcode").live('click', function(e){
e.stopPropagation();
if($("#taigachat_message").val() == $("#taigachat_message").attr("placeholder")){
$("#taigachat_message").removeClass("prompt").val("");
}
var bbcode = $(this).attr("data-code");
var position = bbcode.length;
var ins = getCaretLength($("#taigachat_message").get(0)) > 0;
$("#taigachat_message").insertAroundCaret(bbcode.substring(0, bbcode.indexOf('][')+1), bbcode.substring(bbcode.indexOf('][')+1, bbcode.length));
if(bbcode.indexOf('=][') != -1){
position = bbcode.indexOf('=][')+1;
} else {
position = bbcode.indexOf('][')+1;
}
if(!ins)
setCaretPosition($("#taigachat_message").get(0), getCaretPosition($("#taigachat_message").get(0)) - (bbcode.length - position));
else
setCaretPosition($("#taigachat_message").get(0), getCaretPosition($("#taigachat_message").get(0)) + bbcode.length - position);
return true;
});
try {
XenForo.register('.taigachat_Popup', 'taigachat_PopupMenu');
setTimeout(function(){
// Add the icon/styling without XenForo registering its own events etc.
$(".taigachat_Popup").addClass("Popup");
}, 50);
} catch (e) { }
});
function sendShout(){
var txt_msg = $("#taigachat_message").val();
if (txt_msg.match(/^(\s+|)\/clear(\s+|)/)) {
$('#taigachat_box ol').html('');
$("#taigachat_message").val('')
return;
}
// silently prevent same message within 5 seconds
if(taigachat_lastPostTime + 5000 > new Date().getTime() && taigachat_lastPostMessage == $("#taigachat_message").val())
return;
if($("#taigachat_message").val().length == 0 || $("#taigachat_message").val() == $("#taigachat_message").attr("placeholder")) return;
$("#taigachat_send, #taigachat_message").attr('disabled', true).addClass('disabled');
taigachat_lastPostMessage = $("#taigachat_message").val();
taigachat_lastPostTime = new Date().getTime();
XenForo.ajax(
"index.php?taigachat/post.json",
{
message: $("#taigachat_message").val(),
sidebar: taigachat_sidebar ? "1" : "0",
lastrefresh: taigachat_lastRefreshServer
},
function(json){
if(XenForo.hasResponseError(json) !== false){
return true;
}
$("#taigachat_message").val("");
handleListResponse(json, false, true);
$("#taigachat_send, #taigachat_message").removeAttr('disabled').removeClass('disabled');
$("#taigachat_message").blur();
$("#taigachat_message").focus();
//taigachat_nextRefresh = 0;
//if(taigachat_refreshTimer)
// clearTimeout(taigachat_refreshTimer);
//refreshShoutbox(false, true, false);
},
{cache: false}
);
}
function taigachat_focus(e){
// workaround the .blur/.focus on #taigachat_message being passed down
//if(typeof e.target == "undefined" || e.target == window)
//refreshShoutbox(false, true, true);
taigachat_nextRefresh = 0;
}
// force = ignore focus event delay and ignore document focus
// unsync = out-of-sync request, do not restart timer
function refreshShoutbox(initial, force, unsync){
// Assert initial refresh will only happen once
if(initial){
if(taigachat_initialFired)
return;
taigachat_initialFired = true;
taigachat_initialTime = new Date().getTime();
} else {
// Assert we aren't refreshing within 4 seconds of the first refresh - i.e. document focus event
if(taigachat_initialTime + 4000 > new Date().getTime() && !force)
return;
}
// Stop refresh spam
if(taigachat_lastRefresh + 2000 > new Date().getTime())
return;
// Stop focus refresh spam
if(force && unsync && taigachat_lastRefresh + 6000 > new Date().getTime())
return;
if(taigachat_initialTime + 50 * 60 * 1000 < new Date().getTime() && !initial){
// time for a CSRF token refresh...
XenForo._CsrfRefresh.refresh();
taigachat_refreshtime = 10;
restartTimer();
taigachat_initialTime = new Date().getTime();
return;
}
taigachat_lastRefresh = new Date().getTime();
if((XenForo._hasFocus && taigachat_autorefresh) || force){
taigachat_isRefreshing = true;
XenForo.ajax(
"index.php?taigachat/list.json",
{
sidebar: taigachat_sidebar ? "1" : "0",
lastrefresh: taigachat_lastRefreshServer
},
function(json, textStatus){
taigachat_isRefreshing = false;
if (XenForo.hasResponseError(json))
{
return false;
}
handleListResponse(json, initial, unsync);
if(initial){
//taigachat_refreshTime = 5;
//restartTimer();
setInterval(checkRefresh, 250);
}
},
{
global: false,
cache: false,
error: function(xhr, textStatus, errorThrown){
try
{
success.call(null, $.parseJSON(xhr.responseText), textStatus);
}
catch (e)
{
// workarounds :3
if(xhr.responseText.substr(0, 1) == '{')
XenForo.handleServerError(xhr, textStatus, errorThrown);
}
}
}
); // ajax
} // if focused etc
else {
if(!unsync){
decayRefreshTime();
restartTimer();
}
}
}
function handleListResponse(json, initial, unsync){
taigachat_lastRefreshServer = parseInt(json.lastrefresh, 10) || 0;
// error'd
if(!XenForo.hasTemplateHtml(json) && taigachat_lastRefreshServer == 0){
XenForo.hasResponseError(json);
//taigachat_autorefresh = false;
return false;
}
var gotNew = 0;
var reverse = parseInt(json.reverse, 10) == 1 ? true : false;
taigachat_reverse = reverse;
// Grab the chat elements, reverse if not in top to bottom order
try {
var lis = $(json.templateHtml).filter("li").get();
} catch (e) { }
if(!reverse)
lis = lis.reverse();
$(lis).each(function(){
if($("#"+$(this).attr("id")).length == 0){
gotNew++;
if(!reverse)
$(this).attr("style", "visibility:hidden").addClass("taigachat_new").prependTo("#taigachat_box > ol");
else
$(this).attr("style", "visibility:hidden").addClass("taigachat_new").appendTo("#taigachat_box > ol");
}
});
if(initial || gotNew > 2 || taigachat_lastMessage + 15000 > new Date().getTime()){
$("#taigachat_box > ol > li.taigachat_new").removeClass("taigachat_new").css({visibility:"visible"}).show();
// wee bit of a workaround here
setTimeout(function(){
if(taigachat_reverse)
scrollChatBottom();
}, 200);
} else {
$("#taigachat_box > ol > li.taigachat_new").removeClass("taigachat_new").css({visibility:"visible",display:"none"}).fadeIn(600);
}
if(taigachat_reverse){
var total = $("#taigachat_box > ol > li").length;
total -= taigachat_limit;
if(total > 0)
$("#taigachat_box > ol > li").slice(0, total).remove();
} else {
$("#taigachat_box > ol > li").slice(taigachat_limit).remove();
}
if(initial || gotNew>0){
XenForo.register('.Popup', 'XenForo.PopupMenu', 'XenForoActivatePopups');
XenForo.register(
'a.OverlayTrigger, input.OverlayTrigger, button.OverlayTrigger, label.OverlayTrigger, a.username, a.avatar',
'XenForo.OverlayTrigger'
);
XenForo.activate(document);
//XenForo._TimestampRefresh.refresh();
if(reverse)
scrollChatBottom();
taigachat_refreshtime = 5;
restartTimer();
} else {
if(!unsync){
decayRefreshTime();
restartTimer();
}
}
// don't count initial load against anti fade
if(gotNew > 0 && !initial){
taigachat_lastMessage = new Date().getTime();
}
}
function scrollChatBottom(){
//if($("#taigachat_box").get(0).scrollTop >= $("#taigachat_box").scrollHeight - $("#taigachat_box").height() - 10 || !taigachat_scrolled)
$("#taigachat_box").get(0).scrollTop = 99999;
taigachat_scrolled = true;
}
function restartTimer(){
/*if(taigachat_refreshTimer)
clearTimeout(taigachat_refreshTimer);
taigachat_refreshTimer = setTimeout(function(){ refreshShoutbox(false, false, false); }, taigachat_refreshtime*1000); */
taigachat_nextRefresh = new Date().getTime() + taigachat_refreshtime * 1000;
}
function checkRefresh(){
if(taigachat_nextRefresh < new Date().getTime()){
if(taigachat_isRefreshing){
taigachat_nextRefresh = new Date().getTime();
return;
}
refreshShoutbox(false, false, false);
if(taigachat_nextRefresh < new Date().getTime())
taigachat_nextRefresh = new Date().getTime() + 5000;
}
}
function decayRefreshTime(){
taigachat_refreshtime = taigachat_refreshtime * taigachat_decay;
if(taigachat_refreshtime > taigachat_maxrefreshtime)
taigachat_refreshtime = taigachat_maxrefreshtime;
}
// http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery, modified slightly
jQuery.fn.extend({
insertAroundCaret: function(myValue, myValue2){
return this.each(function(i) {
if(document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue + sel.text + myValue2;
this.focus();
} else if(this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(startPos, endPos)+myValue2+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length + myValue2.length + (endPos-startPos);
this.selectionEnd = startPos + myValue.length + myValue2.length + (endPos-startPos);
this.scrollTop = scrollTop;
} else {
this.value += myValue + myValue2;
this.focus();
}
})
}
});
// http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if(document.selection){
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if(ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function getCaretLength (ctrl) {
var CaretPos = 0;
if(document.selection){
ctrl.focus ();
var Sel = document.selection.createRange ();
//Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
else if(ctrl.selectionEnd || ctrl.selectionEnd == '0')
CaretPos = ctrl.selectionEnd-ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange){
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if(ctrl.createTextRange){
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
3. Идем в бибку создания модели: \library\Dark\TaigaChat\Model\TaigaChat.php
Будет производиться выборка из БД для /pm
Заменяем все на это
PHP:
<?php
class Dark_TaigaChat_Model_TaigaChat extends XenForo_Model
{
// maybe one day this will be completed
public function getRooms($regen = false){
/** @var XenForo_Model_DataRegistry */
$registryModel = $this->getModelFromCache('XenForo_Model_DataRegistry');
$rooms = array();
if($regen)
$rooms = $registryModel->get('dark_taigachat_rooms');
if(empty($rooms) || $regen){
$rooms = $this->fetchAllKeyed(
"
SELECT *
FROM dark_taigachat_rooms
ORDER BY display_order asc
"
, 'id');
foreach($rooms as &$room){
if(!empty($room['group_whitelist']))
$room['group_whitelist'] = unserialize($room['group_whitelist']);
else
$room['group_whitelist'] = array();
$room['title'] = new XenForo_Phrase($this->getRoomTitlePhraseName($room['id']));
}
$registryModel->set('dark_taigachat_rooms', $rooms);
}
return $rooms;
}
public function deletePublicHtml(){
@unlink(XenForo_Helper_File::getExternalDataPath().'/taigachat/messages.html');
@unlink(XenForo_Helper_File::getExternalDataPath().'/taigachat/messagesmini.html');
}
/**
* @param mixed $overrideMotd set motd pre-cache-update
* @param mixed $unsync if not due to new message set true
*/
public function regeneratePublicHtml($overrideMotd = false, $unsync = false){
$viewParams = array();
$options = XenForo_Application::get('options');
$visitor = XenForo_Visitor::getInstance();
if($options->dark_taigachat_speedmode == 'Disabled')
return;
if($unsync){
/** @var XenForo_Model_DataRegistry */
$registryModel = $this->getModelFromCache('XenForo_Model_DataRegistry');
$lastUnsync = $registryModel->get('dark_taigachat_unsync');
if(!empty($lastUnsync) && $lastUnsync > time() - 30){
return;
}
$registryModel->set('dark_taigachat_unsync', time());
}
// swap timezone to default temporarily
$oldTimeZone = XenForo_Locale::getDefaultTimeZone()->getName();
XenForo_Locale::setDefaultTimeZone($options->guestTimeZone);
$messages = $this->getMessages(array(
"page" => 1,
"perPage" => $options->dark_taigachat_fullperpage,
"lastRefresh" => 0,
));
$messagesMini = $this->getMessages(array(
"page" => 1,
"perPage" => $options->dark_taigachat_sidebarperpage,
"lastRefresh" => 0,
));
$bbCodeParser = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('Base'));
$motd = new XenForo_BbCode_TextWrapper($overrideMotd !== false ? $overrideMotd : $options->dark_taigachat_motd, $bbCodeParser);
$onlineUsersTaiga = null;
if($options->dark_taigachat_sidebar){
$onlineUsersTaiga = $this->getActivityUserList($visitor->toArray());
}
$viewParams = array(
'taigachat' => array(
"messages" => $messages,
"sidebar" => false,
"editside" => $options->dark_taigachat_editside,
"timedisplay" => $options->dark_taigachat_timedisplay,
"miniavatar" => $options->dark_taigachat_miniavatar,
"lastrefresh" => 0,
"numInChat" => $this->getActivityUserCount(),
"motd" => $motd,
"online" => $onlineUsersTaiga,
"route" => $options->dark_taigachat_route,
"publichtml" => true,
'canView' => true,
'enabled' => true,
),
);
$dep = new Dark_TaigaChat_Dependencies();
$dep->preLoadData();
$dep->preloadTemplate('dark_taigachat_list');
$viewRenderer = new Dark_TaigaChat_ViewRenderer_JsonInternal($dep, new Zend_Controller_Response_Http(), new Zend_Controller_Request_Http());
if(!file_exists(XenForo_Helper_File::getExternalDataPath().'/taigachat'))
XenForo_Helper_File::createDirectory(XenForo_Helper_File::getExternalDataPath().'/taigachat', true);
$innerContent = $viewRenderer->renderView('Dark_TaigaChat_ViewPublic_TaigaChat_List', $viewParams, 'dark_taigachat_list');
$filename = XenForo_Helper_File::getExternalDataPath().'/taigachat/messages.html';
$yayForNoLocking = mt_rand(0, 10000000);
if(file_put_contents($filename.".{$yayForNoLocking}.tmp", $innerContent, LOCK_EX) === false)
throw new XenForo_Exception("Failed writing TaigaChat messages to {$filename}.{$yayForNoLocking}.tmp");
if(!@rename($filename.".{$yayForNoLocking}.tmp", $filename))
@unlink($filename.".{$yayForNoLocking}.tmp");
XenForo_Helper_File::makeWritableByFtpUser($filename);
$viewParams['taigachat']['messages'] = $messagesMini;
$viewParams['taigachat']['sidebar'] = true;
//$viewParams['taigachat']['online'] = null;
$innerContent = $viewRenderer->renderView('Dark_TaigaChat_ViewPublic_TaigaChat_List', $viewParams, 'dark_taigachat_list');
$filename = XenForo_Helper_File::getExternalDataPath().'/taigachat/messagesmini.html';
if(file_put_contents($filename.".{$yayForNoLocking}.tmp", $innerContent, LOCK_EX) === false)
throw new XenForo_Exception("Failed writing TaigaChat messages to {$filename}.{$yayForNoLocking}.tmp");
// The only reason this could fail is if the file is being hammered, hence no worries ignoring failure
if(!@rename($filename.".{$yayForNoLocking}.tmp", $filename))
@unlink($filename.".{$yayForNoLocking}.tmp");
XenForo_Helper_File::makeWritableByFtpUser($filename);
// put timezone back to how it was
XenForo_Locale::setDefaultTimeZone($oldTimeZone);
}
public function getMessages(array $fetchOptions = array())
{
$pmresult = XenForo_Visitor::getInstance();
$limitOptions = $this->prepareLimitFetchOptions($fetchOptions);
return $this->_getDb()->fetchAll($this->limitQueryResults(
"
SELECT *, IF(user.username IS NULL, taigachat.username, user.username) AS username, IF(DATEDIFF(NOW(), FROM_UNIXTIME(date)) = 0, 1, 0) AS today
FROM dark_taigachat AS taigachat
LEFT JOIN xf_user AS user ON
(user.user_id = taigachat.user_id)
WHERE (taigachat.message NOT LIKE '%/pm%' OR taigachat.message LIKE '%/pm ".$pmresult['username'].": %' OR (taigachat.message LIKE '%/pm%' AND taigachat.username = '".$pmresult['username']."')) AND taigachat.id > ?
ORDER BY taigachat.id DESC
", $limitOptions['limit'], $limitOptions['offset']
), array($fetchOptions['lastRefresh']));
}
public function getMessagesToday()
{
return $this->_getDb()->fetchAll(
"
SELECT *, IF(user.username IS NULL, taigachat.username, user.username) AS username
FROM dark_taigachat AS taigachat
LEFT JOIN xf_user AS user ON
(user.user_id = taigachat.user_id)
WHERE date > UNIX_TIMESTAMP()-60*60*24 and taigachat.activity=0
ORDER BY date DESC
"
);
}
public function getRoomDefinitionById($id){
return $this->_getDb()->fetchRow('
SELECT *
FROM dark_taigachat_rooms
WHERE id = ?
', $id);
}
public function getRoomTitlePhraseName($id)
{
return 'dark_taigachat_room_' . $id . '_title';
}
public function getMessageById($id, array $fetchOptions = array())
{
return $this->_getDb()->fetchRow('
SELECT *, IF(user.username IS NULL, taigachat.username, user.username) AS username, IF(DATEDIFF(NOW(), FROM_UNIXTIME(date)) = 0, 1, 0) AS today
FROM dark_taigachat AS taigachat
LEFT JOIN xf_user AS user ON
(user.user_id = taigachat.user_id)
WHERE taigachat.id = ?
', $id);
}
public function deleteMessage($id){
return $this->_getDb()->query('
DELETE FROM dark_taigachat
WHERE id = ?
', $id);
}
public function deleteOldMessages(){
$this->_getDb()->query("
select @goat := date from dark_taigachat order by date desc limit 1000;
");
return $this->_getDb()->query("
delete from dark_taigachat where date < @goat
");
}
public function deleteOldActivity(){
return $this->_getDb()->query("
delete from dark_taigachat_activity where date < UNIX_TIMESTAMP()-30*60
");
}
public function getActivityUserList(array $viewingUser=array())
{
$records = $this->_getDb()->fetchAll(
"
SELECT *
FROM dark_taigachat_activity AS activity
LEFT JOIN xf_user AS user ON
(user.user_id = activity.user_id)
WHERE activity.date > UNIX_TIMESTAMP()-150
ORDER BY activity.date DESC
"
);
$output = array(
'guests' => 0,
'members' => 0,
);
foreach ($records AS $key => &$record)
{
if(!$record['visible']){
unset($records[$key]);
continue;
}
$output['members']++;
}
$output['limit'] = 99999999;
$output['total'] = $output['members'];
$output['records'] = $records;
return $output;
}
public function getActivityUserCount(){
return $this->_getDb()->fetchOne(
"
SELECT count(*)
FROM dark_taigachat_activity AS activity
LEFT JOIN xf_user AS user ON
(user.user_id = activity.user_id)
WHERE activity.date > UNIX_TIMESTAMP()-150
AND user.visible=1
"
);
}
public function floodCheck($user = null){
$visitor = XenForo_Visitor::getInstance();
$options = XenForo_Application::get('options');
if($options->dark_taigachat_flood_time == 0)
return 0;
$this->standardizeViewingUserReference($user);
if(XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'flood'))
return 0;
$date = $this->_getDb()->fetchOne(
"
SELECT date
FROM dark_taigachat
WHERE user_id = ?
order by id desc
limit 1
", array($visitor->getUserId())
);
if(empty($date))
return 0;
if(time() - $date < $options->dark_taigachat_flood_time){
return $options->dark_taigachat_flood_time - (time() - $date);
}
return 0;
}
public function updateActivity($user_id, $updateHtml = true, $unsync = false){
// triple check this only runs once per request, spaghetti everywhere thanks to xenporta etc.
if(empty($GLOBALS['taigachat_updated_activity'])){
$GLOBALS['taigachat_updated_activity'] = true;
if($user_id > 0){
$this->_getDb()->query("
replace into dark_taigachat_activity
set user_id = ?, date = UNIX_TIMESTAMP()
", array($user_id));
}
if($updateHtml)
$this->regeneratePublicHtml(false, $unsync);
}
}
public function pruneShoutbox(){
Dark_TaigaChat_CronEntry_CleanUp::runDailyCleanUp();
$this->_getDb()->query("
delete from dark_taigachat
");
$visitor = XenForo_Visitor::getInstance();
$dw = XenForo_DataWriter::create('Dark_TaigaChat_DataWriter_Message');
$dw->setOption(Dark_TaigaChat_DataWriter_Message::OPTION_IS_AUTOMATED, true);
$dw->set('user_id', $visitor['user_id']);
$dw->set('username', $visitor['user_id'] > 0 ? $visitor['username'] : new XenForo_Phrase('guest'));
$dw->set('message', new XenForo_Phrase('dark_taigachat_pruned'));
$dw->save();
}
public function canModifyMessage(array $message, array $user = null)
{
$this->standardizeViewingUserReference($user);
if ($user['user_id'] == $message['user_id'])
{
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'modify');
}
else
{
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'modifyAll');
}
}
public function canViewMessages(array $user = null)
{
$this->standardizeViewingUserReference($user);
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'view');
}
public function canPostMessages(array $user = null)
{
$this->standardizeViewingUserReference($user);
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'post');
}
public function canPruneShoutbox(array $user = null)
{
$this->standardizeViewingUserReference($user);
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'prune');
}
public function canBanFromShoutbox(array $user = null)
{
$this->standardizeViewingUserReference($user);
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'ban');
}
public function canUseColor(array $user = null)
{
$this->standardizeViewingUserReference($user);
return $user['user_id'] > 0 && XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'color');
}
public function canEditMotd(array $user = null)
{
$this->standardizeViewingUserReference($user);
return XenForo_Permission::hasPermission($user['permissions'], 'dark_taigachat', 'motd');
}
}
4. Идем в глобал! \library\Dark\TaigaChat\Helper\Global.php
И заменяем весь код на этот:
PHP:
<?php
class Dark_TaigaChat_Helper_Global
{
public static function getTaigaChatStuff(&$response, $action, $dis=false){
$options = XenForo_Application::get('options');
$visitor = XenForo_Visitor::getInstance();
/** @var Dark_TaigaChat_Model_TaigaChat */
$taigamodel = XenForo_Model::create("Dark_TaigaChat_Model_TaigaChat");
$visitor = XenForo_Visitor::getInstance();
/** @var Dark_TaigaChat_Model_TaigaChat */
$taigamodel->updateActivity($visitor['user_id'], false);
$smilies = array();
$toolbar_bbcode = array();
if($options->dark_taigachat_toolbar){
$toolbar_bbcode_temp2 = preg_replace('#(^//.+$)#mi', '', trim($options->dark_taigachat_toolbar_bbcode));
$toolbar_bbcode_temp2 = str_replace("\r", "", $toolbar_bbcode_temp2);
if(!empty($toolbar_bbcode_temp2)){
$toolbar_bbcode_temp = explode("\n", $toolbar_bbcode_temp2);
foreach($toolbar_bbcode_temp as $bbcode){
$bbcode = trim($bbcode);
if(!empty($bbcode)){
$bbcode = explode(":", trim($bbcode));
if(!empty($bbcode))
$toolbar_bbcode[$bbcode[0]] = $bbcode[1];
}
}
}
if (XenForo_Application::isRegistered('smilies'))
{
$smilies = XenForo_Application::get('smilies');
}
else
{
$smilies = XenForo_Model::create('XenForo_Model_Smilie')->getAllSmiliesForCache();
XenForo_Application::set('smilies', $smilies);
}
foreach($smilies as &$smilie){
$smilie['text'] = $smilie['smilieText'][0];
$smilie['sprite_mode'] = array_key_exists('sprite_params', $smilie);
}
}
if(empty($response->params['taigachat']))
$response->params['taigachat'] = array();
if (!XenForo_Application::isRegistered('config'))
{
$path = 'data';
}
else
{
$path = XenForo_Application::get('config')->externalDataPath;
}
if($path == 'data' && $options->dark_taigachat_speedmode == 'Https')
$path = $options->boardUrl . '/' . $path;
$isSidebar = $response->viewName != "Dark_TaigaChat_ViewPublic_TaigaChat_Index" && $action != 'popup' && $action != 'xenporta_alt';
//$bbCodeParser = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('Base'));
//$motd = new XenForo_BbCode_TextWrapper($options->dark_taigachat_motd, $bbCodeParser);
$motd = false;
if(!empty($options->dark_taigachat_motd)){
$motd = " ";
}
// Don't forget to add to dark_taigachat template too
$response->params['taigachat'] += array(
"focusedrefreshtime" => $options->dark_taigachat_focusedrefreshtime,
"unfocusedrefreshtime" => $options->dark_taigachat_unfocusedrefreshtime,
"tabunfocusedrefreshtime" => $options->dark_taigachat_tabunfocusedrefreshtime,
"enabled" => true,///$options->dark_taigachat_enabled,
"maxlength" => $options->dark_taigachat_maxlength,
"reverse" => $options->dark_taigachat_direction,
"height" => $options->dark_taigachat_height,
"route" => $options->dark_taigachat_route,
"timedisplay" => $options->dark_taigachat_timedisplay,
"toolbar" => $options->dark_taigachat_toolbar,
"ignorehide" => $options->dark_taigachat_ignorehide,
"showAlert" => $options->dark_taigachat_showalert,
"toolbar_bbcode" => $toolbar_bbcode,
"toolbar_smilies" => $smilies,
"activity_newtab" => $options->dark_taigachat_activity_newtab,
"newtab" => $options->dark_taigachat_newtab,
"thumbzoom" => $options->dark_taigachat_imagemode == 'ThumbZoom',
"js_modification" => filemtime("js/dark/taigachat.js"),
"canView" => $visitor->hasPermission('dark_taigachat', 'view'),
"canPost" => $visitor->hasPermission('dark_taigachat', 'post'),
"canBan" => $visitor->hasPermission('dark_taigachat', 'ban'),
"canColor" => $taigamodel->canUseColor(),
"color" => $visitor->taigachat_color,
"canModify" => $visitor->hasPermission('dark_taigachat', 'modify'),
"canModifyAll" => $visitor->hasPermission('dark_taigachat', 'modifyAll'),
"canMotd" => $visitor->hasPermission('dark_taigachat', 'motd'),
"motd" => $motd,
//"numInChat" => $taigamodel->getActivityUserCount(),
"sidebar" => $isSidebar,
"popup" => $action == 'popup',
"limit" => $isSidebar ? $options->dark_taigachat_sidebarperpage : $options->dark_taigachat_fullperpage,
"speed" => $options->dark_taigachat_speedmode != 'Disabled',
"speedurl" => $isSidebar ? ($path.'/taigachat/messagesmini.html') : ($path.'/taigachat/messages.html'),
);
}
public static function processMessagesForView(&$params, &$view){
$options = XenForo_Application::get('options');
$formatter = XenForo_BbCode_Formatter_Base::create('Dark_TaigaChat_BbCode_Formatter_Tenori', array('view' => $view));
switch($options->dark_taigachat_bbcode){
case 'Full':
$formatter->displayableTags = true;
break;
case 'Basic':
default:
$formatter->displayableTags = array('img', 'url', 'email', 'b', 'u', 'i', 's', 'color');
break;
case 'None':
$formatter->displayableTags = array('url', 'email');
break;
}
$formatter->getTagsAgain();
$parser = new XenForo_BbCode_Parser($formatter);
if($options->dark_taigachat_imagemode == 'Link')
foreach($params['taigachat']['messages'] as &$message){
$message['message'] = str_ireplace(array("[img]", "[/img]"), array("[url]", "[/url]"), $message['message']);
}
$maxid = $params['taigachat']['lastrefresh'];
foreach($params['taigachat']['messages'] as &$message){
if($options->dark_taigachat_bbcode == 'Full')
$message['message'] = XenForo_Helper_String::autoLinkBbCode($message['message']);
else
{
// We don't want to parse youtube etc. urls if [media] is disabled
$autoLinkParser = new XenForo_BbCode_Parser(XenForo_BbCode_Formatter_Base::create('Dark_TaigaChat_BbCode_Formatter_BbCode_AutoLink', false));
$message['message'] = $autoLinkParser->render($message['message']);
}
if($message['id'] > $maxid)
$maxid = $message['id'];
if(substr($message['message'], 0, 3) == '/me'){
$message['message'] = substr($message['message'], 4);
$message['me'] = true;
}
if(substr($message['message'], 0, 3) == '/to'){
$message['message'] = str_ireplace(array("/to"), array(">>"), $message['message']);
$message['to'] = true;
}
if(substr($message['message'], 0, 3) == '/pm'){
$message['message'] = str_ireplace(array("/pm"), array(">>"), $message['message']);
$message['pm'] = true;
}
}
if($options->dark_taigachat_smilies)
XenForo_ViewPublic_Helper_Message::bbCodeWrapMessages($params['taigachat']['messages'], $parser);
else
XenForo_ViewPublic_Helper_Message::bbCodeWrapMessages($params['taigachat']['messages'], $parser, array("states" => array("stopSmilies" => true)));
if($options->dark_taigachat_direction)
$params['taigachat']['messages'] = array_reverse($params['taigachat']['messages']);
return $maxid;
}
}
5. Шаблоны! Открываем - dark_taigachat.css и добавляем (учтите, что картинки сами найдете, сами знаете где... я про иконки, красную, зеленую, синюю)
PHP:
.taigachat_msg_moderadmin{padding-left:18px;line-height:16px;height:16px;display:inline-block !important;background:transparent url('styles/dark/user_red.png') 0 0 no-repeat;color:red !important}
.taigachat_msg_moder{padding-left:18px;line-height:16px;height:16px;display:inline-block !important;background:transparent url('styles/dark/user_green.png') 0 0 no-repeat;color:#189d11 !important}
.taigachat_msg_{padding-left:18px;line-height:16px;height:16px;display:inline-block !important;background:transparent url('styles/dark/user_blue.png') 0 0 no-repeat;color:#2fa0ed !important}
.taigachat_thread_alert{padding:3px 3px 3px 20px;position:relative;margin:5px 2px;background:transparent url('styles/dark/newthread.png') 2px 0 no-repeat}
.taigachat_msg_pm{background-color:#ffe0e0 !important}
.taigachat_msg_to{background-color:#FFFFD2 !important}
.taigachat_msg_me{border:#f0f7fc 1px solid !important;font-style:italic;padding:2px 6px 4px 6px}
6. Открываете шаблон dark_taigachat_list
И заменяете на:
PHP:
<xen:if is="{$taigachat.publichtml}">
<meta name='robots' content='noindex,nofollow,noimageindex,noarchive'>
</xen:if>
<xen:foreach loop="$taigachat.messages" value="$message">
<li id="taigachat_message_{$message.id}" data-userid="{$message.user_id}" data-messageid="{$message.id}" class="{xen:if {$message.to}, 'taigachat_msg_to'}{xen:if {$message.pm}, 'taigachat_msg_pm'}">
<xen:if is="{$taigachat.editside} OR !{$taigachat.sidebar}">
<xen:if is="{$message.canModify} OR {$taigachat.canBan} OR {$taigachat.publichtml}">
<div class="Popup" {xen:if $taigachat.publichtml, 'style="display:none"'}>
<a rel="Menu"></a>
<div class="Menu">
<div class="primaryContent menuHeader"><h3>{xen:phrase dark_message_tools}</h3></div>
<ul class="secondaryContent blockLinksList">
<li><a href="{xen:link 'taigachat/edit', $message}" class="OverlayTrigger" data-cacheOverlay="false" id="taigachat_edit_{$message.id}">{xen:phrase edit}</a></li>
<li><a href="{xen:link 'taigachat/delete', $message}" class="taigachat_delete" data-messageid="{$message.id}">{xen:phrase delete}</a></li>
<xen:if is="{$message.user_id} > 0">
<li id="taigachat_canban_{$message.id}" class="taigachat_canban"><a data-link="{xen:link 'taigachat/ban', $message}" href="#" class="taigachat_ban">{xen:phrase dark_ban_from_shoutbox}</a></li>
</xen:if>
</ul>
</div>
</div>
</xen:if>
</xen:if>
<xen:if is="{$taigachat.miniavatar}">
<xen:avatar user="$message" size="s" img="true" class="_plainImage taigachat_avatar" />
</xen:if>
<xen:if is="{$taigachat.timedisplay} == 'Absolute' || ({$taigachat.timedisplay} == 'AbsoluteTime' && !{$message.today})">
<span class='DateTime muted taigachat_absolute_timestamp' data-timestamp="{$message.date}" data-today="0">{xen:datetime $message.date, 'absolute'} - </span>
<xen:elseif is="{$taigachat.timedisplay} == 'Time' || ({$taigachat.timedisplay} == 'AbsoluteTime' && {$message.today})" />
<span class='DateTime muted taigachat_absolute_timestamp' data-timestamp="{$message.date}" data-today="1">{xen:time $message.date, 'absolute'} - </span>
<xen:elseif is="{$taigachat.timedisplay} == 'Relative'" />
<span class='DateTime muted'><xen:datetime time="$message.date" /> - </span>
<xen:else />
</xen:if>
<span class="{xen:if {$message.me}, 'taigachat_me'} {xen:if {$message.activity}, 'taigachat_activity'}">
<a {xen:if $message.user_id, 'title="{$message.username}" href="{xen:link members, $message}" '}class="dark_tc_username taigachat_msg_{xen:if {$message.is_moderator}, 'moder'}{xen:if {$message.is_admin}, 'admin'}" itemprop="name">
<xen:if is="{$message.usernameHtml}">{xen:raw $message.usernameHtml}<xen:else /><span class="dark_tc_username">{xen:helper richUserName, $message}</span></xen:if></a>:
<div class='taigachat_messagetext ugc'>{xen:raw $message.messageHtml}</div>
</span>
</li>
</xen:foreach>
<div class='taigachat_list_online_users' style='display:none'>
<xen:if is="{$taigachat.online}">
<xen:include template="dark_taigachat_online_users">
<xen:map from="$taigachat" to="$taigachat" />
</xen:include>
</xen:if>
</div>
7.8.9. И еще
Шаблон dark_taigachat_single (для того, чтоб пр редактировании сообщения - не слетал CSS)
Заменить все на это:
PHP:
<span class="{xen:if {$message.me}, 'taigachat_me'} {xen:if {$message.activity}, 'taigachat_activity'}">
<a {xen:if $message.user_id, 'href="{xen:link members, $message}" '}class="dark_tc_username taigachat_msg_{xen:if {$message.is_moderator}, 'moder'}{xen:if {$message.is_admin}, 'admin'}" itemprop="name"><xen:if is="{$message.usernameHtml}">{xen:raw $message.usernameHtml}<xen:else />{xen:helper richUserName, $message}</xen:if></a><xen:if is="!{$message.me} && !{$message.activity}">:</xen:if>
<div class='taigachat_messagetext ugc'>{xen:raw $message.messageHtml}</div>
</span>
Собственно всё на этом.
С чего все начиналось!!!
Изначально послужила статья "ЛОГИКА СКРИПТА ЛИЧНЫХ СООБЩЕНИЙ"
Не реклама: _http://phpclub.ru/talk/threads/Логика-скрипта-личных-сообщений.70204/