java/src/messenger/webim/libs/chat.php

505 lines
16 KiB
PHP
Raw Normal View History

<?php
/*
2013-03-07 01:22:53 +04:00
* Copyright 2005-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2011-04-07 12:34:04 +04:00
require_once(dirname(__FILE__).'/track.php');
require_once(dirname(__FILE__).'/classes/thread.php');
$namecookie = "WEBIM_Data";
$usercookie = "WEBIM_UserID";
2011-02-26 17:04:12 +03:00
function get_user_id()
{
return (time() + microtime()) . rand(0, 99999999);
}
function prepare_html_message($text, $allow_formating)
2011-02-26 17:04:12 +03:00
{
$escaped_text = htmlspecialchars($text);
2011-04-07 12:34:04 +04:00
$text_w_links = preg_replace('/(https?|ftp):\/\/\S*/', '<a href="$0" target="_blank">$0</a>', $escaped_text);
2011-02-26 17:04:12 +03:00
$multiline = str_replace("\n", "<br/>", $text_w_links);
if (! $allow_formating) {
return $multiline;
}
$formated = preg_replace('/&lt;(span|strong)&gt;(.*)&lt;\/\1&gt;/U', '<$1>$2</$1>', $multiline);
$formated = preg_replace('/&lt;span class=&quot;(.*)&quot;&gt;(.*)&lt;\/span&gt;/U', '<span class="$1">$2</span>', $formated);
return $formated;
}
2011-02-26 17:04:12 +03:00
function message_to_html($msg)
{
if ($msg['ikind'] == Thread::KIND_AVATAR) {
return "";
}
2011-02-26 17:04:12 +03:00
$message = "<span>" . date("H:i:s", $msg['created']) . "</span> ";
$kind = Thread::kindToString($msg['ikind']);
2011-02-26 17:04:12 +03:00
if ($msg['tname'])
$message .= "<span class='n$kind'>" . htmlspecialchars($msg['tname']) . "</span>: ";
$allow_formating = ($msg['ikind'] != Thread::KIND_USER && $msg['ikind'] != Thread::KIND_AGENT);
$message .= "<span class='m$kind'>" . prepare_html_message($msg['tmessage'], $allow_formating) . "</span><br/>";
return $message;
}
2011-02-26 17:04:12 +03:00
function message_to_text($msg)
{
if ($msg['ikind'] == Thread::KIND_AVATAR) {
return "";
}
2011-02-26 17:04:12 +03:00
$message_time = date("H:i:s ", $msg['created']);
if ($msg['ikind'] == Thread::KIND_USER || $msg['ikind'] == Thread::KIND_AGENT) {
2011-02-26 17:04:12 +03:00
if ($msg['tname'])
return $message_time . $msg['tname'] . ": " . $msg['tmessage'] . "\n";
else
2011-02-26 17:04:12 +03:00
return $message_time . $msg['tmessage'] . "\n";
} else if ($msg['ikind'] == Thread::KIND_INFO) {
2011-02-26 17:04:12 +03:00
return $message_time . $msg['tmessage'] . "\n";
} else {
2011-02-26 17:04:12 +03:00
return $message_time . "[" . $msg['tmessage'] . "]\n";
}
}
2011-02-26 17:04:12 +03:00
function get_messages($threadid, $meth, $isuser, &$lastid)
{
global $webim_encoding;
$db = Database::getInstance();
$msgs = $db->query(
"select messageid,ikind,dtmcreated as created,tname,tmessage from {chatmessage} " .
"where threadid = :threadid and messageid > :lastid " .
($isuser ? "and ikind <> ". Thread::KIND_FOR_AGENT : "") .
" order by messageid",
array(
':threadid' => $threadid,
':lastid' => $lastid,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$messages = array();
foreach ($msgs as $msg) {
$message = "";
if ($meth == 'xml') {
switch ($msg['ikind']) {
case Thread::KIND_AVATAR:
2011-02-26 17:04:12 +03:00
$message = "<avatar>" . myiconv($webim_encoding, "utf-8", escape_with_cdata($msg['tmessage'])) . "</avatar>";
break;
default:
2011-02-26 17:04:12 +03:00
$message = "<message>" . myiconv($webim_encoding, "utf-8", escape_with_cdata(message_to_html($msg))) . "</message>\n";
}
} else {
if ($msg['ikind'] != Thread::KIND_AVATAR) {
$message = (($meth == 'text') ? message_to_text($msg) : topage(message_to_html($msg)));
}
}
$messages[] = $message;
2011-02-26 17:04:12 +03:00
if ($msg['messageid'] > $lastid) {
$lastid = $msg['messageid'];
}
}
return $messages;
}
2011-02-26 17:04:12 +03:00
function print_thread_messages($thread, $token, $lastid, $isuser, $format, $agentid = null)
{
global $webim_encoding, $webimroot;
$threadid = $thread->id;
$istyping = abs(time() - $isuser ? $thread->lastPingAgent : $thread->lastPingUser) < Thread::CONNECTION_TIMEOUT
&& (($isuser ? $thread->agentTyping : $thread->userTyping) == "1") ? "1" : "0";
2011-02-26 17:04:12 +03:00
if ($format == "xml") {
$output = get_messages($threadid, "xml", $isuser, $lastid);
start_xml_output();
print("<thread lastid=\"$lastid\" typing=\"" . $istyping . "\" canpost=\"" . (($isuser || $agentid != null && $agentid == $thread->agentId) ? 1 : 0) . "\">");
2011-02-26 17:04:12 +03:00
foreach ($output as $msg) {
print $msg;
}
print("</thread>");
2011-02-26 17:04:12 +03:00
} else if ($format == "html") {
$output = get_messages($threadid, "html", $isuser, $lastid);
start_html_output();
2011-02-26 17:04:12 +03:00
$url = "$webimroot/thread.php?act=refresh&amp;thread=$threadid&amp;token=$token&amp;html=on&amp;user=" . ($isuser ? "true" : "false");
print(
2011-02-26 17:04:12 +03:00
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" .
"<html>\n<head>\n" .
"<link href=\"$webimroot/styles/default/chat.css\" rel=\"stylesheet\" type=\"text/css\">\n" .
"<meta http-equiv=\"Refresh\" content=\"" . Settings::get('updatefrequency_oldchat') . "; URL=$url&amp;sn=11\">\n" .
2011-02-26 17:04:12 +03:00
"<meta http-equiv=\"Pragma\" content=\"no-cache\">\n" .
"<title>chat</title>\n" .
"</head>\n" .
"<body bgcolor='#FFFFFF' text='#000000' link='#C28400' vlink='#C28400' alink='#C28400' onload=\"if( location.hash != '#aend' ){location.hash='#aend';}\">" .
"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr><td valign='top' class='message'>");
foreach ($output as $msg) {
print $msg;
}
print(
2011-02-26 17:04:12 +03:00
"</td></tr></table><a name='aend'></a>" .
"</body></html>");
}
}
2011-02-26 17:04:12 +03:00
function get_user_name($username, $addr, $id)
{
return str_replace(
"{addr}", $addr,
str_replace(
"{id}", $id,
str_replace("{name}", $username, Settings::get('usernamepattern'))
)
);
}
2011-02-26 17:04:12 +03:00
function is_ajax_browser($browserid, $ver, $useragent)
{
if ($browserid == "opera")
return $ver >= 8.02;
2011-02-26 17:04:12 +03:00
if ($browserid == "safari")
return $ver >= 125;
2011-02-26 17:04:12 +03:00
if ($browserid == "msie")
return $ver >= 5.5 && !strstr($useragent, "powerpc");
2011-02-26 17:04:12 +03:00
if ($browserid == "netscape")
return $ver >= 7.1;
2011-02-26 17:04:12 +03:00
if ($browserid == "mozilla")
return $ver >= 1.4;
2011-02-26 17:04:12 +03:00
if ($browserid == "firefox")
return $ver >= 1.0;
2011-02-26 17:04:12 +03:00
if ($browserid == "chrome")
return true;
return false;
}
2011-02-26 17:04:12 +03:00
function is_old_browser($browserid, $ver)
{
if ($browserid == "opera")
return $ver < 7.0;
2011-02-26 17:04:12 +03:00
if ($browserid == "msie")
return $ver < 5.0;
return false;
}
2011-02-26 17:04:12 +03:00
$knownAgents = array("opera", "msie", "chrome", "safari", "firefox", "netscape", "mozilla");
2011-02-26 17:04:12 +03:00
function get_remote_level($useragent)
{
global $knownAgents;
$useragent = strtolower($useragent);
2011-02-26 17:04:12 +03:00
foreach ($knownAgents as $agent) {
if (strstr($useragent, $agent)) {
if (preg_match("/" . $agent . "[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches)) {
$ver = $matches[1];
2011-02-26 17:04:12 +03:00
if (is_ajax_browser($agent, $ver, $useragent))
return "ajaxed";
2011-02-26 17:04:12 +03:00
else if (is_old_browser($agent, $ver))
return "old";
return "simple";
}
}
}
return "simple";
}
2011-02-26 17:04:12 +03:00
function is_agent_opera95()
{
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
2011-02-26 17:04:12 +03:00
if (strstr($useragent, "opera")) {
if (preg_match("/opera[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches)) {
$ver = $matches[1];
if ($ver >= "9.5")
return true;
}
}
return false;
}
2011-02-26 17:04:12 +03:00
function is_mac_opera()
{
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
2011-02-26 17:04:12 +03:00
return strstr($useragent, "opera") && strstr($useragent, "mac");
}
2011-02-26 17:04:12 +03:00
function needsFramesrc()
{
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
2011-02-26 17:04:12 +03:00
return strstr($useragent, "safari/");
}
2012-03-13 21:26:18 +04:00
function setup_logo($group = NULL)
2011-02-26 17:04:12 +03:00
{
global $page;
2012-03-13 21:26:18 +04:00
$toplevelgroup = (!$group)?array():get_top_level_group($group);
$page['ct.company.name'] = topage(empty($toplevelgroup['vctitle'])?Settings::get('title'):$toplevelgroup['vctitle']);
$page['ct.company.chatLogoURL'] = topage(empty($toplevelgroup['vclogo'])?Settings::get('logo'):$toplevelgroup['vclogo']);
$page['webimHost'] = topage(empty($toplevelgroup['vchosturl'])?Settings::get('hosturl'):$toplevelgroup['vchosturl']);
}
2011-02-26 17:04:12 +03:00
function setup_leavemessage($name, $email, $message, $groupid, $groupname, $info, $referrer, $canshowcaptcha)
{
global $page;
$page['formname'] = topage($name);
$page['formemail'] = topage($email);
$page['formmessage'] = $message ? topage($message) : "";
$page['showcaptcha'] = Settings::get("enablecaptcha") == "1" && $canshowcaptcha ? "1" : "";
$page['formgroupid'] = $groupid;
$page['formgroupname'] = $groupname;
2011-02-16 04:17:30 +03:00
$page['forminfo'] = topage($info);
$page['referrer'] = urlencode(topage($referrer));
if (Settings::get('enablegroups') == '1') {
$groups = setup_groups_select($groupid, false);
if ($groups) {
$page['groups'] = $groups['select'];
$page['group.descriptions'] = json_encode($groups['descriptions']);
$page['default.department.description'] = $groups['defaultdescription'];
}
}
}
2011-02-26 17:04:12 +03:00
function setup_survey($name, $email, $groupid, $info, $referrer)
{
global $page;
2011-02-26 17:04:12 +03:00
$page['formname'] = topage($name);
$page['formemail'] = topage($email);
$page['formgroupid'] = $groupid;
$page['forminfo'] = topage($info);
$page['referrer'] = urlencode(topage($referrer));
if (Settings::get('enablegroups') == '1' && Settings::get('surveyaskgroup') == '1') {
$groups = setup_groups_select($groupid, true);
if ($groups) {
$page['groups'] = $groups['select'];
$page['group.descriptions'] = json_encode($groups['descriptions']);
$page['default.department.description'] = $groups['defaultdescription'];
}
}
2011-02-26 17:04:12 +03:00
$page['showemail'] = Settings::get("surveyaskmail") == "1" ? "1" : "";
$page['showmessage'] = Settings::get("surveyaskmessage") == "1" ? "1" : "";
$page['showname'] = Settings::get('usercanchangename') == "1" ? "1" : "";
}
function setup_groups_select($groupid, $markoffline)
{
$showgroups = ($groupid == '')?true:group_has_children($groupid);
if (!$showgroups) {
return false;
}
$allgroups = get_groups(false);
if (empty($allgroups)) {
return false;
}
$val = "";
$selectedgroupid = $groupid;
$groupdescriptions = array();
foreach ($allgroups as $k) {
$groupname = $k['vclocalname'];
if ($k['inumofagents'] == 0 || ($groupid && $k['parent'] != $groupid && $k['groupid'] != $groupid )) {
continue;
}
if ($k['ilastseen'] !== NULL && $k['ilastseen'] < Settings::get('online_timeout')) {
if (!$selectedgroupid) {
$selectedgroupid = $k['groupid']; // select first online group
}
} else {
$groupname .= $markoffline?" (offline)":"";
}
$isselected = $k['groupid'] == $selectedgroupid;
if ($isselected) {
$defaultdescription = $k['vclocaldescription'];
}
$val .= "<option value=\"" . $k['groupid'] . "\"" . ($isselected ? " selected=\"selected\"" : "") . ">$groupname</option>";
$groupdescriptions[] = $k['vclocaldescription'];
}
return array(
'select' => $val,
'descriptions' => $groupdescriptions,
'defaultdescription' => $defaultdescription
);
}
2011-02-26 17:04:12 +03:00
function setup_chatview_for_user($thread, $level)
{
global $page, $webimroot;
$page = array();
if (! empty($thread->groupId)) {
$group = group_by_id($thread->groupId);
2012-03-13 21:26:18 +04:00
$group = get_top_level_group($group);
} else {
$group = array();
}
$page['agent'] = false;
$page['user'] = true;
$page['canpost'] = true;
$nameisset = getstring("chat.default.username") != $thread->userName;
$page['displ1'] = $nameisset ? "none" : "inline";
$page['displ2'] = $nameisset ? "inline" : "none";
$page['level'] = $level;
$page['ct.chatThreadId'] = $thread->id;
$page['ct.token'] = $thread->lastToken;
$page['ct.user.name'] = htmlspecialchars(topage($thread->userName));
$page['canChangeName'] = Settings::get('usercanchangename') == "1";
$page['chat.title'] = topage(empty($group['vcchattitle'])?Settings::get('chattitle'):$group['vcchattitle']);
2011-12-26 22:39:27 +04:00
$page['chat.close.confirmation'] = getlocal('chat.close.confirmation');
2012-03-13 21:26:18 +04:00
setup_logo($group);
if (Settings::get('sendmessagekey') == 'enter') {
$page['send_shortcut'] = "Enter";
2011-02-26 17:04:12 +03:00
$page['ignorectrl'] = 1;
} else {
$page['send_shortcut'] = is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
2011-02-26 17:04:12 +03:00
$page['ignorectrl'] = 0;
}
$params = "thread=" . $thread->id . "&amp;token=" . $thread->lastToken;
2011-02-26 17:04:12 +03:00
$page['mailLink'] = "$webimroot/client.php?" . $params . "&amp;level=$level&amp;act=mailthread";
if (Settings::get('enablessl') == "1" && !is_secure_request()) {
2011-02-26 17:04:12 +03:00
$page['sslLink'] = get_app_location(true, true) . "/client.php?" . $params . "&amp;level=$level";
}
$page['isOpera95'] = is_agent_opera95();
$page['neediframesrc'] = needsFramesrc();
$page['frequency'] = Settings::get('updatefrequency_chat');
}
2011-02-26 17:04:12 +03:00
function setup_chatview_for_operator($thread, $operator)
{
global $page, $webimroot, $company_logo_link, $webim_encoding, $company_name;
$page = array();
if (! is_null($thread->groupId)) {
$group = group_by_id($thread->groupId);
2012-03-13 21:26:18 +04:00
$group = get_top_level_group($group);
} else {
$group = array();
}
$page['agent'] = true;
$page['user'] = false;
$page['canpost'] = $thread->agentId == $operator['operatorid'];
$page['ct.chatThreadId'] = $thread->id;
$page['ct.token'] = $thread->lastToken;
$page['ct.user.name'] = htmlspecialchars(topage(get_user_name($thread->userName, $thread->remote, $thread->userId)));
$page['chat.title'] = topage(empty($group['vcchattitle'])?Settings::get('chattitle'):$group['vcchattitle']);
$page['chat.close.confirmation'] = getlocal('chat.close.confirmation');
2012-03-13 21:26:18 +04:00
setup_logo($group);
if (Settings::get('sendmessagekey') == 'enter') {
$page['send_shortcut'] = "Enter";
2011-02-26 17:04:12 +03:00
$page['ignorectrl'] = 1;
} else {
$page['send_shortcut'] = is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
2011-02-26 17:04:12 +03:00
$page['ignorectrl'] = 0;
}
if (Settings::get('enablessl') == "1" && !is_secure_request()) {
$page['sslLink'] = get_app_location(true, true) . "/operator/agent.php?thread=" . $thread->id . "&amp;token=" . $thread->lastToken;
}
$page['isOpera95'] = is_agent_opera95();
$page['neediframesrc'] = needsFramesrc();
$page['historyParams'] = array("userid" => "" . $thread->userId);
2011-02-26 17:04:12 +03:00
$page['historyParamsLink'] = add_params($webimroot . "/operator/userhistory.php", $page['historyParams']);
if (Settings::get('enabletracking')) {
$visitor = track_get_visitor_by_threadid($thread->id);
2011-04-07 12:34:04 +04:00
$page['trackedParams'] = array("visitor" => "" . $visitor['visitorid']);
$page['trackedParamsLink'] = add_params($webimroot . "/operator/tracked.php", $page['trackedParams']);
}
$predefinedres = "";
$canned_messages = load_canned_messages($thread->locale, 0);
if ($thread->groupId) {
$canned_messages = array_merge(
load_canned_messages($thread->locale, $thread->groupId),
$canned_messages
);
};
2011-02-26 17:04:12 +03:00
foreach ($canned_messages as $answer) {
2012-01-29 01:52:44 +04:00
$predefinedres .= "<option>" . htmlspecialchars(topage($answer['vctitle']?$answer['vctitle']:cutstring($answer['vcvalue'], 97, '...'))) . "</option>";
$fullAnswers[] = myiconv($webim_encoding, getoutputenc(), $answer['vcvalue']);
}
$page['predefinedAnswers'] = $predefinedres;
2012-01-29 01:52:44 +04:00
$page['fullPredefinedAnswers'] = json_encode($fullAnswers);
$params = "thread=" . $thread->id . "&amp;token=" . $thread->lastToken;
2011-02-26 17:04:12 +03:00
$page['redirectLink'] = "$webimroot/operator/agent.php?" . $params . "&amp;act=redirect";
$page['namePostfix'] = "";
$page['frequency'] = Settings::get('updatefrequency_chat');
}
function ban_for_addr($addr)
2011-02-26 17:04:12 +03:00
{
$db = Database::getInstance();
return $db->query(
"select banid,comment from {chatban} " .
"where dtmtill > :now AND address = :addr",
array(
':addr' => $addr,
':now' => time()
),
array('return_rows' => Database::RETURN_ONE_ROW)
);
}
2011-02-26 17:04:12 +03:00
function visitor_from_request()
{
global $namecookie, $webim_encoding, $usercookie;
$defaultName = getstring("chat.default.username");
$userName = $defaultName;
2011-02-26 17:04:12 +03:00
if (isset($_COOKIE[$namecookie])) {
$data = base64_decode(strtr($_COOKIE[$namecookie], '-_,', '+/='));
if (strlen($data) > 0) {
$userName = myiconv("utf-8", $webim_encoding, $data);
}
}
2011-02-26 17:04:12 +03:00
if ($userName == $defaultName) {
$userName = getgetparam('name', $userName);
}
if (isset($_COOKIE[$usercookie])) {
$userId = $_COOKIE[$usercookie];
} else {
$userId = get_user_id();
2011-02-26 17:04:12 +03:00
setcookie($usercookie, $userId, time() + 60 * 60 * 24 * 365);
}
2011-02-26 17:04:12 +03:00
return array('id' => $userId, 'name' => $userName);
}
2011-02-26 17:04:12 +03:00
function get_remote_host()
{
$extAddr = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &&
2011-02-26 17:04:12 +03:00
$_SERVER['HTTP_X_FORWARDED_FOR'] != $_SERVER['REMOTE_ADDR']) {
$extAddr = $_SERVER['REMOTE_ADDR'] . ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')';
}
return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : $extAddr;
}
2013-03-13 01:03:50 +04:00
?>