Replace database functions with Database class methods

This commit is contained in:
Dmitriy Simushev 2012-07-13 12:56:50 +00:00
parent 12883cfbe2
commit 3e4163cbfe
40 changed files with 1003 additions and 909 deletions

View File

@ -22,13 +22,11 @@ require_once('libs/groups.php');
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ""; $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
if($referer && isset($_SESSION['threadid'])) { if($referer && isset($_SESSION['threadid'])) {
$link = connect(); $thread = thread_by_id($_SESSION['threadid']);
$thread = thread_by_id_($_SESSION['threadid'], $link);
if ($thread && $thread['istate'] != $state_closed) { if ($thread && $thread['istate'] != $state_closed) {
$msg = getstring2_("chat.client.visited.page", array($referer), $thread['locale']); $msg = getstring2_("chat.client.visited.page", array($referer), $thread['locale']);
post_message_($thread['threadid'], $kind_for_agent,$msg,$link); post_message_($thread['threadid'], $kind_for_agent,$msg);
} }
close_connection($link);
} }
$image = verifyparam(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "webim"); $image = verifyparam(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "webim");

View File

@ -94,50 +94,46 @@ if( !isset($_GET['token']) || !isset($_GET['thread']) ) {
exit; exit;
} }
$link = connect(); $invitation_state = invitation_state($_SESSION['visitorid']);
$invitation_state = invitation_state($_SESSION['visitorid'], $link);
$visitor_is_invited = $settings['enabletracking'] && $invitation_state['invited'] && !$invitation_state['threadid']; $visitor_is_invited = $settings['enabletracking'] && $invitation_state['invited'] && !$invitation_state['threadid'];
if($settings['enablepresurvey'] == '1' && !(isset($_POST['survey']) && $_POST['survey'] == 'on') && !$visitor_is_invited) { if($settings['enablepresurvey'] == '1' && !(isset($_POST['survey']) && $_POST['survey'] == 'on') && !$visitor_is_invited) {
$page = array(); $page = array();
setup_logo($group); setup_logo($group);
setup_survey($visitor['name'], $email, $groupid, $info, $referrer); setup_survey($visitor['name'], $email, $groupid, $info, $referrer);
expand("styles/dialogs", getchatstyle(), "survey.tpl"); expand("styles/dialogs", getchatstyle(), "survey.tpl");
close_connection($link);
exit; exit;
} }
$remoteHost = get_remote_host(); $remoteHost = get_remote_host();
$userbrowser = $_SERVER['HTTP_USER_AGENT']; $userbrowser = $_SERVER['HTTP_USER_AGENT'];
if(!check_connections_from_remote($remoteHost, $link)) { if(!check_connections_from_remote($remoteHost)) {
close_connection($link);
die("number of connections from your IP is exceeded, try again later"); die("number of connections from your IP is exceeded, try again later");
} }
$thread = create_thread($groupid,$visitor['name'], $remoteHost, $referrer,$current_locale,$visitor['id'], $userbrowser,$state_loading,$link); $thread = create_thread($groupid,$visitor['name'], $remoteHost, $referrer,$current_locale,$visitor['id'], $userbrowser,$state_loading);
$_SESSION['threadid'] = $thread['threadid']; $_SESSION['threadid'] = $thread['threadid'];
$operator = invitation_accept($_SESSION['visitorid'], $thread['threadid'], $link); $operator = invitation_accept($_SESSION['visitorid'], $thread['threadid']);
if ($operator) { if ($operator) {
$operator = operator_by_id_($operator, $link); $operator = operator_by_id($operator);
$operatorName = ($current_locale == $home_locale) ? $operator['vclocalename'] : $operator['vccommonname']; $operatorName = ($current_locale == $home_locale) ? $operator['vclocalename'] : $operator['vccommonname'];
post_message_($thread['threadid'], $kind_for_agent, getstring2('chat.visitor.invitation.accepted', array($operatorName)), $link); post_message_($thread['threadid'], $kind_for_agent, getstring2('chat.visitor.invitation.accepted', array($operatorName)));
} }
if( $referrer ) { if( $referrer ) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.came.from',array($referrer)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.came.from',array($referrer)));
} }
post_message_($thread['threadid'],$kind_info,getstring('chat.wait'),$link); post_message_($thread['threadid'],$kind_info,getstring('chat.wait'));
if($email) { if($email) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.email',array($email)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.email',array($email)));
} }
if($info) { if($info) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.info',array($info)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.info',array($info)));
} }
if($firstmessage) { if($firstmessage) {
$postedid = post_message_($thread['threadid'],$kind_user,$firstmessage,$link,$visitor['name']); $postedid = post_message_($thread['threadid'],$kind_user,$firstmessage,$visitor['name']);
commit_thread( $thread['threadid'], array('shownmessageid' => $postedid), $link); commit_thread( $thread['threadid'], array('shownmessageid' => $postedid));
} }
close_connection($link);
} }
$threadid = $thread['threadid']; $threadid = $thread['threadid'];
$token = $thread['ltoken']; $token = $thread['ltoken'];

View File

@ -231,9 +231,12 @@ function create_table($id, $link)
mysql_query($query, $link) or show_install_err(' Query failed: ' . mysql_error($link)); mysql_query($query, $link) or show_install_err(' Query failed: ' . mysql_error($link));
if ($id == "${mysqlprefix}chatoperator") { if ($id == "${mysqlprefix}chatoperator") {
create_operator_("admin", "", "", "Administrator", "Administrator", "", $link); create_operator("admin", "", "", "Administrator", "Administrator", "");
} else if ($id == "${mysqlprefix}chatrevision") { } else if ($id == "${mysqlprefix}chatrevision") {
perform_query("INSERT INTO ${mysqlprefix}chatrevision VALUES (1)", $link); $result = mysql_query("INSERT INTO ${mysqlprefix}chatrevision VALUES (1)", $link);
if (! $result) {
die(' Query failed: ' . mysql_error($link));
}
} }
} }

View File

@ -30,19 +30,17 @@ function store_message($name, $email, $info, $message,$groupid,$referrer) {
$remoteHost = get_remote_host(); $remoteHost = get_remote_host();
$userbrowser = $_SERVER['HTTP_USER_AGENT']; $userbrowser = $_SERVER['HTTP_USER_AGENT'];
$visitor = visitor_from_request(); $visitor = visitor_from_request();
$link = connect(); $thread = create_thread($groupid,$name,$remoteHost,$referrer,$current_locale,$visitor['id'], $userbrowser,$state_left);
$thread = create_thread($groupid,$name,$remoteHost,$referrer,$current_locale,$visitor['id'], $userbrowser,$state_left,$link);
if( $referrer ) { if( $referrer ) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.came.from',array($referrer)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.came.from',array($referrer)));
} }
if($email) { if($email) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.email',array($email)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.email',array($email)));
} }
if($info) { if($info) {
post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.info',array($info)),$link); post_message_($thread['threadid'],$kind_for_agent,getstring2('chat.visitor.info',array($info)));
} }
post_message_($thread['threadid'],$kind_user,$message,$link,$name); post_message_($thread['threadid'],$kind_user,$message,$name);
close_connection($link);
} }
$groupid = ""; $groupid = "";
@ -121,9 +119,7 @@ if (empty($inbox_mail)) {
} }
if($inbox_mail) { if($inbox_mail) {
$link = connect(); webim_mail($inbox_mail, $email, $subject, $body);
webim_mail($inbox_mail, $email, $subject, $body, $link);
close_connection($link);
} }
setup_logo($group); setup_logo($group);

View File

@ -17,47 +17,54 @@
function load_canned_messages($locale, $groupid) function load_canned_messages($locale, $groupid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $values = array(':locale' => $locale);
$query = "select id, vctitle, vcvalue from ${mysqlprefix}chatresponses " . if ($groupid) {
"where locale = '" . $locale . "' AND (" . $values[':groupid'] = $groupid;
($groupid }
? "groupid = $groupid" return $db->query(
: "groupid is NULL OR groupid = 0") . "select id, vctitle, vcvalue from {chatresponses} " .
") order by vcvalue"; "where locale = :locale AND (" .
$result = select_multi_assoc($query, $link); ($groupid ? "groupid = :groupid" : "groupid is NULL OR groupid = 0") .
close_connection($link); ") order by vcvalue",
return $result; $values,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
} }
function load_canned_message($key) function load_canned_message($key)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $result = $db->query(
$result = select_one_row("select vctitle, vcvalue from ${mysqlprefix}chatresponses where id = $key", $link); "select vctitle, vcvalue from {chatresponses} where id = ?",
close_connection($link); array($key),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return $result ? $result : null; return $result ? $result : null;
} }
function save_canned_message($key, $title, $message) function save_canned_message($key, $title, $message)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
perform_query("update ${mysqlprefix}chatresponses set vcvalue = '" . db_escape_string($message, $link) . "', " . "update {chatresponses} set vcvalue = ?, vctitle = ? where id = ?",
"vctitle = '" . db_escape_string($title, $link) . "' " . array($message, $title, $key)
"where id = $key", $link); );
close_connection($link);
} }
function add_canned_message($locale, $groupid, $title, $message) function add_canned_message($locale, $groupid, $title, $message)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
perform_query("insert into ${mysqlprefix}chatresponses (locale,groupid,vctitle,vcvalue) values ('$locale'," . "insert into {chatresponses} (locale,groupid,vctitle,vcvalue) " .
($groupid ? "$groupid, " : "null, ") . "values (?, ?, ?, ?)",
"'" . db_escape_string($title, $link) . "', " . array(
"'" . db_escape_string($message, $link) . "')", $link); $locale,
close_connection($link); ($groupid ? $groupid : "null"),
$title,
$message
)
);
} }
?> ?>

View File

@ -50,36 +50,40 @@ function next_token()
return rand(99999, 99999999); return rand(99999, 99999999);
} }
function next_revision($link) function next_revision()
{ {
global $mysqlprefix; $db = Database::getInstance();
perform_query("update ${mysqlprefix}chatrevision set id=LAST_INSERT_ID(id+1)", $link); $db->query("update {chatrevision} set id=LAST_INSERT_ID(id+1)");
$val = db_insert_id($link); $val = $db->insertedId();
return $val; return $val;
} }
function post_message_($threadid, $kind, $message, $link, $from = null, $utime = null, $opid = null) /**
* @todo Think about post_message_ and post_message diffrence
*/
function post_message_($threadid, $kind, $message, $from = null, $utime = null, $opid = null)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = sprintf( $query = "insert into {chatmessage} " .
"insert into ${mysqlprefix}chatmessage (threadid,ikind,tmessage,tname,agentId,dtmcreated) values (%s, %s,'%s',%s,%s,%s)", "(threadid,ikind,tmessage,tname,agentId,dtmcreated) " .
"values (?,?,?,?,?,".($utime?"FROM_UNIXTIME(?)":"CURRENT_TIMESTAMP").")";
$values = array(
$threadid, $threadid,
$kind, $kind,
db_escape_string($message, $link), $message,
$from ? "'" . db_escape_string($from, $link) . "'" : "null", ($from ? $from : "null"),
$opid ? $opid : "0", ($opid ? $opid : 0)
$utime ? "FROM_UNIXTIME($utime)" : "CURRENT_TIMESTAMP"); );
if ($utime) {
perform_query($query, $link); $values[] = $utime;
return db_insert_id($link); }
$db->query($query, $values);
return $db->insertedId();
} }
function post_message($threadid, $kind, $message, $from = null, $agentid = null) function post_message($threadid, $kind, $message, $from = null, $agentid = null)
{ {
$link = connect(); return post_message_($threadid, $kind, $message, $from, null, $agentid);
$id = post_message_($threadid, $kind, $message, $link, $from, null, $agentid);
close_connection($link);
return $id;
} }
function prepare_html_message($text, $allow_formating) function prepare_html_message($text, $allow_formating)
@ -127,16 +131,23 @@ function message_to_text($msg)
function get_messages($threadid, $meth, $isuser, &$lastid) function get_messages($threadid, $meth, $isuser, &$lastid)
{ {
global $kind_for_agent, $kind_avatar, $webim_encoding, $mysqlprefix; global $kind_for_agent, $kind_avatar, $webim_encoding;
$link = connect(); $db = Database::getInstance();
$query = sprintf( $msgs = $db->query(
"select messageid,ikind,unix_timestamp(dtmcreated) as created,tname,tmessage from ${mysqlprefix}chatmessage " . "select messageid,ikind,unix_timestamp(dtmcreated) as created,tname,tmessage from {chatmessage} " .
"where threadid = %s and messageid > %s %s order by messageid", "where threadid = :threadid and messageid > :lastid " .
$threadid, $lastid, $isuser ? "and ikind <> $kind_for_agent" : ""); ($isuser ? "and ikind <> {$kind_for_agent} " : "") .
"order by messageid",
array(
':threadid' => $threadid,
':lastid' => $lastid,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$messages = array(); $messages = array();
$msgs = select_multi_assoc($query, $link);
foreach ($msgs as $msg) { foreach ($msgs as $msg) {
$message = ""; $message = "";
if ($meth == 'xml') { if ($meth == 'xml') {
@ -159,7 +170,6 @@ function get_messages($threadid, $meth, $isuser, &$lastid)
} }
} }
close_connection($link);
return $messages; return $messages;
} }
@ -355,15 +365,12 @@ function setup_groups_select($groupid, $markoffline)
{ {
global $settings; global $settings;
$link = connect(); $showgroups = ($groupid == '')?true:group_has_children($groupid);
$showgroups = ($groupid == '')?true:group_has_children($groupid, $link);
if (!$showgroups) { if (!$showgroups) {
close_connection($link);
return false; return false;
} }
$allgroups = get_groups($link, false); $allgroups = get_groups(false);
close_connection($link);
if (empty($allgroups)) { if (empty($allgroups)) {
return false; return false;
@ -404,7 +411,7 @@ function setup_chatview_for_user($thread, $level)
global $page, $webimroot, $settings; global $page, $webimroot, $settings;
loadsettings(); loadsettings();
$page = array(); $page = array();
if (! is_null($thread['groupid'])) { if (! empty($thread['groupid'])) {
$group = group_by_id($thread['groupid']); $group = group_by_id($thread['groupid']);
$group = get_top_level_group($group); $group = get_top_level_group($group);
} else { } else {
@ -483,11 +490,9 @@ function setup_chatview_for_operator($thread, $operator)
$page['historyParams'] = array("userid" => "" . $thread['userid']); $page['historyParams'] = array("userid" => "" . $thread['userid']);
$page['historyParamsLink'] = add_params($webimroot . "/operator/userhistory.php", $page['historyParams']); $page['historyParamsLink'] = add_params($webimroot . "/operator/userhistory.php", $page['historyParams']);
if ($settings['enabletracking']) { if ($settings['enabletracking']) {
$link = connect(); $visitor = track_get_visitor_by_threadid($thread['threadid']);
$visitor = track_get_visitor_by_threadid($thread['threadid'], $link);
$page['trackedParams'] = array("visitor" => "" . $visitor['visitorid']); $page['trackedParams'] = array("visitor" => "" . $visitor['visitorid']);
$page['trackedParamsLink'] = add_params($webimroot . "/operator/tracked.php", $page['trackedParams']); $page['trackedParamsLink'] = add_params($webimroot . "/operator/tracked.php", $page['trackedParams']);
close_connection($link);
} }
$predefinedres = ""; $predefinedres = "";
$canned_messages = load_canned_messages($thread['locale'], 0); $canned_messages = load_canned_messages($thread['locale'], 0);
@ -510,24 +515,29 @@ function setup_chatview_for_operator($thread, $operator)
$page['frequency'] = $settings['updatefrequency_chat']; $page['frequency'] = $settings['updatefrequency_chat'];
} }
function update_thread_access($threadid, $params, $link) function update_thread_access($threadid, $params)
{ {
global $mysqlprefix; $db = Database::getInstance();
$clause = ""; $clause = "";
$values = array();
foreach ($params as $k => $v) { foreach ($params as $k => $v) {
if (strlen($clause) > 0) if (strlen($clause) > 0)
$clause .= ", "; $clause .= ", ";
$clause .= $k . "=" . $v; $clause .= $k . "=?";
$values[] = $v;
} }
perform_query( $values[] = $threadid;
"update ${mysqlprefix}chatthread set $clause " .
"where threadid = $threadid", $link); $db->query(
"update {chatthread} set {$clause} where threadid = ?",
$values
);
} }
function ping_thread($thread, $isuser, $istyping) function ping_thread($thread, $isuser, $istyping)
{ {
global $kind_for_agent, $state_queue, $state_loading, $state_chatting, $state_waiting, $kind_conn, $connection_timeout; global $kind_for_agent, $state_queue, $state_loading, $state_chatting, $state_waiting, $kind_conn, $connection_timeout;
$link = connect();
$params = array(($isuser ? "lastpinguser" : "lastpingagent") => "CURRENT_TIMESTAMP", $params = array(($isuser ? "lastpinguser" : "lastpingagent") => "CURRENT_TIMESTAMP",
($isuser ? "userTyping" : "agentTyping") => ($istyping ? "1" : "0")); ($isuser ? "userTyping" : "agentTyping") => ($istyping ? "1" : "0"));
@ -536,8 +546,7 @@ function ping_thread($thread, $isuser, $istyping)
if ($thread['istate'] == $state_loading && $isuser) { if ($thread['istate'] == $state_loading && $isuser) {
$params['istate'] = $state_queue; $params['istate'] = $state_queue;
commit_thread($thread['threadid'], $params, $link); commit_thread($thread['threadid'], $params);
close_connection($link);
return; return;
} }
@ -545,161 +554,176 @@ function ping_thread($thread, $isuser, $istyping)
$params[$isuser ? "lastpingagent" : "lastpinguser"] = "0"; $params[$isuser ? "lastpingagent" : "lastpinguser"] = "0";
if (!$isuser) { if (!$isuser) {
$message_to_post = getstring_("chat.status.user.dead", $thread['locale']); $message_to_post = getstring_("chat.status.user.dead", $thread['locale']);
post_message_($thread['threadid'], $kind_for_agent, $message_to_post, $link, null, $lastping + $connection_timeout); post_message_($thread['threadid'], $kind_for_agent, $message_to_post, null, $lastping + $connection_timeout);
} else if ($thread['istate'] == $state_chatting) { } else if ($thread['istate'] == $state_chatting) {
$message_to_post = getstring_("chat.status.operator.dead", $thread['locale']); $message_to_post = getstring_("chat.status.operator.dead", $thread['locale']);
post_message_($thread['threadid'], $kind_conn, $message_to_post, $link, null, $lastping + $connection_timeout); post_message_($thread['threadid'], $kind_conn, $message_to_post, null, $lastping + $connection_timeout);
$params['istate'] = $state_waiting; $params['istate'] = $state_waiting;
$params['nextagent'] = 0; $params['nextagent'] = 0;
commit_thread($thread['threadid'], $params, $link); commit_thread($thread['threadid'], $params);
close_connection($link);
return; return;
} }
} }
update_thread_access($thread['threadid'], $params, $link); update_thread_access($thread['threadid'], $params);
close_connection($link);
} }
function commit_thread($threadid, $params, $link) function commit_thread($threadid, $params)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = "update ${mysqlprefix}chatthread t set lrevision = " . next_revision($link) . ", dtmmodified = CURRENT_TIMESTAMP";
foreach ($params as $k => $v) {
$query .= ", " . $k . "=" . $v;
}
$query .= " where threadid = $threadid";
perform_query($query, $link); $query = "update {chatthread} t " .
"set lrevision = ?, dtmmodified = CURRENT_TIMESTAMP";
$values = array(next_revision());
foreach ($params as $k => $v) {
$query .= ", " . $k . "=?";
$values[] = $v;
}
$query .= " where threadid = ?";
$values[] = $threadid;
$db->query($query, $values);
} }
function rename_user($thread, $newname) function rename_user($thread, $newname)
{ {
global $kind_events; global $kind_events;
$link = connect(); commit_thread($thread['threadid'], array('userName' => $newname));
commit_thread($thread['threadid'], array('userName' => "'" . db_escape_string($newname, $link) . "'"), $link);
if ($thread['userName'] != $newname) { if ($thread['userName'] != $newname) {
post_message_($thread['threadid'], $kind_events, post_message_($thread['threadid'], $kind_events,
getstring2_("chat.status.user.changedname", array($thread['userName'], $newname), $thread['locale']), $link); getstring2_("chat.status.user.changedname", array($thread['userName'], $newname), $thread['locale']));
} }
close_connection($link);
} }
function close_thread($thread, $isuser) function close_thread($thread, $isuser)
{ {
global $state_closed, $kind_events, $mysqlprefix; global $state_closed, $kind_events;
$link = connect();
if ($thread['istate'] != $state_closed) { if ($thread['istate'] != $state_closed) {
commit_thread($thread['threadid'], array('istate' => $state_closed, commit_thread(
'messageCount' => "(SELECT COUNT(*) FROM ${mysqlprefix}chatmessage WHERE ${mysqlprefix}chatmessage.threadid = t.threadid AND ikind = 1)"), $link); $thread['threadid'],
array(
'istate' => $state_closed,
'messageCount' => "(SELECT COUNT(*) FROM {chatmessage} WHERE {chatmessage}.threadid = t.threadid AND ikind = 1)"
)
);
} }
$message = $isuser ? getstring2_("chat.status.user.left", array($thread['userName']), $thread['locale']) $message = $isuser ? getstring2_("chat.status.user.left", array($thread['userName']), $thread['locale'])
: getstring2_("chat.status.operator.left", array($thread['agentName']), $thread['locale']); : getstring2_("chat.status.operator.left", array($thread['agentName']), $thread['locale']);
post_message_($thread['threadid'], $kind_events, $message, $link); post_message_($thread['threadid'], $kind_events, $message);
close_connection($link);
} }
function close_old_threads($link) function close_old_threads()
{ {
global $state_closed, $state_left, $state_chatting, $mysqlprefix, $settings; global $state_closed, $state_left, $state_chatting, $settings;
if ($settings['thread_lifetime'] == 0) { if ($settings['thread_lifetime'] == 0) {
return; return;
} }
$next_revision = next_revision($link);
$query = "update ${mysqlprefix}chatthread set lrevision = $next_revision, dtmmodified = CURRENT_TIMESTAMP, istate = $state_closed " .
"where istate <> $state_closed and istate <> $state_left and lastpingagent <> 0 and lastpinguser <> 0 and " .
"(ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpinguser)) > " . $settings['thread_lifetime'] . " and " .
"ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpingagent)) > " . $settings['thread_lifetime'] . ")";
perform_query($query, $link); $db = Database::getInstance();
}
function close_old_threads($link) $query = "update {chatthread} set lrevision = :next_revision, " .
{ "dtmmodified = CURRENT_TIMESTAMP, istate = :state_closed " .
global $state_closed, $state_left, $state_chatting, $mysqlprefix, $settings; "where istate <> :state_closed and istate <> :state_left " .
if ($settings['thread_lifetime'] == 0) { "and lastpingagent <> 0 and lastpinguser <> 0 and " .
return; "(ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpinguser)) > ".
} ":thread_lifetime and " .
$next_revision = next_revision($link); "ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpingagent)) > ".
$query = "update ${mysqlprefix}chatthread set lrevision = $next_revision, dtmmodified = CURRENT_TIMESTAMP, istate = $state_closed " . ":thread_lifetime)";
"where istate <> $state_closed and istate <> $state_left and lastpingagent <> 0 and lastpinguser <> 0 and " .
"(ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpinguser)) > " . $settings['thread_lifetime'] . " and " .
"ABS(UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lastpingagent)) > " . $settings['thread_lifetime'] . ")";
perform_query($query, $link); $db->query(
} $query,
array(
function thread_by_id_($id, $link) ':next_revision' => next_revision(),
{ ':state_closed' => $state_closed,
global $mysqlprefix; ':state_left' => $state_left,
return select_one_row("select threadid,userName,agentName,agentId,lrevision,istate,ltoken,userTyping,agentTyping" . ':thread_lifetime' => $settings['thread_lifetime']
",unix_timestamp(dtmmodified) as modified, unix_timestamp(dtmcreated) as created, unix_timestamp(dtmchatstarted) as chatstarted" . )
",remote,referer,locale,unix_timestamp(lastpinguser) as lpuser,unix_timestamp(lastpingagent) as lpagent, unix_timestamp(CURRENT_TIMESTAMP) as current,nextagent,shownmessageid,userid,userAgent,groupid" . );
" from ${mysqlprefix}chatthread where threadid = " . $id, $link);
}
function ban_for_addr_($addr, $link)
{
global $mysqlprefix;
return select_one_row("select banid,comment from ${mysqlprefix}chatban where unix_timestamp(dtmtill) > unix_timestamp(CURRENT_TIMESTAMP) AND address = '" . db_escape_string($addr, $link) . "'", $link);
} }
function thread_by_id($id) function thread_by_id($id)
{ {
$link = connect(); $db = Database::getInstance();
$thread = thread_by_id_($id, $link); return $db->query(
close_connection($link); "select threadid,userName,agentName,agentId,lrevision,istate,ltoken,userTyping, " .
return $thread; "agentTyping,unix_timestamp(dtmmodified) as modified, " .
"unix_timestamp(dtmcreated) as created, " .
"unix_timestamp(dtmchatstarted) as chatstarted,remote,referer,locale," .
"unix_timestamp(lastpinguser) as lpuser,unix_timestamp(lastpingagent) as lpagent," .
"unix_timestamp(CURRENT_TIMESTAMP) as current,nextagent,shownmessageid,userid, " .
"userAgent,groupid from {chatthread} where threadid = ?",
array($id),
array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
function create_thread($groupid, $username, $remoteHost, $referer, $lang, $userid, $userbrowser, $initialState, $link) function ban_for_addr($addr)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = sprintf( return $db->query(
"insert into ${mysqlprefix}chatthread (userName,userid,ltoken,remote,referer,lrevision,locale,userAgent,dtmcreated,dtmmodified,istate" . ($groupid ? ",groupid" : "") . ") values " . "select banid,comment from {chatban} " .
"('%s','%s',%s,'%s','%s',%s,'%s','%s',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,$initialState" . ($groupid ? ",$groupid" : "") . ")", "where unix_timestamp(dtmtill) > unix_timestamp(CURRENT_TIMESTAMP) AND address = ?",
db_escape_string($username, $link), array($addr),
db_escape_string($userid, $link), array('return_rows' => Database::RETURN_ONE_ROW)
);
}
function create_thread($groupid, $username, $remoteHost, $referer, $lang, $userid, $userbrowser, $initialState)
{
$db = Database::getInstance();
$query = "insert into {chatthread} (userName,userid,ltoken,remote,referer, " .
"lrevision,locale,userAgent,dtmcreated,dtmmodified,istate" .
($groupid ? ",groupid" : "") . ") values " .
"(?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,?" .
($groupid ? ", ?" : "") . ")";
$values = array(
$username,
$userid,
next_token(), next_token(),
db_escape_string($remoteHost, $link), $remoteHost,
db_escape_string($referer, $link), $referer,
next_revision($link), next_revision(),
db_escape_string($lang, $link), $lang,
db_escape_string($userbrowser, $link)); $userbrowser,
$initialState
);
perform_query($query, $link); if ($groupid) {
$id = db_insert_id($link); $values[] = $groupid;
}
$newthread = thread_by_id_($id, $link); $db->query($query, $values);
$id = $db->insertedId();
$newthread = thread_by_id($id);
return $newthread; return $newthread;
} }
function do_take_thread($threadid, $operatorId, $operatorName, $chatstart = false) function do_take_thread($threadid, $operatorId, $operatorName, $chatstart = false)
{ {
global $state_chatting; global $state_chatting;
$link = connect();
$params = array("istate" => $state_chatting, $params = array("istate" => $state_chatting,
"nextagent" => 0, "nextagent" => 0,
"agentId" => $operatorId, "agentId" => $operatorId,
"agentName" => "'" . db_escape_string($operatorName, $link) . "'"); "agentName" => $operatorName);
if ($chatstart){ if ($chatstart){
$params['dtmchatstarted'] = "CURRENT_TIMESTAMP"; $params['dtmchatstarted'] = "CURRENT_TIMESTAMP";
} }
commit_thread($threadid, $params, $link); commit_thread($threadid, $params);
close_connection($link);
} }
function reopen_thread($threadid) function reopen_thread($threadid)
{ {
global $state_queue, $state_loading, $state_waiting, $state_chatting, $state_closed, $state_left, $kind_events, $settings; global $state_queue, $state_loading, $state_waiting, $state_chatting, $state_closed, $state_left, $kind_events, $settings;
$link = connect();
$thread = thread_by_id_($threadid, $link); $thread = thread_by_id($threadid);
if (!$thread) if (!$thread)
return FALSE; return FALSE;
@ -712,12 +736,13 @@ function reopen_thread($threadid)
return FALSE; return FALSE;
if ($thread['istate'] != $state_chatting && $thread['istate'] != $state_queue && $thread['istate'] != $state_loading) { if ($thread['istate'] != $state_chatting && $thread['istate'] != $state_queue && $thread['istate'] != $state_loading) {
commit_thread($threadid, commit_thread(
array("istate" => $state_waiting, "nextagent" => 0), $link); $threadid,
array("istate" => $state_waiting, "nextagent" => 0)
);
} }
post_message_($thread['threadid'], $kind_events, getstring_("chat.status.user.reopenedthread", $thread['locale']), $link); post_message_($thread['threadid'], $kind_events, getstring_("chat.status.user.reopenedthread", $thread['locale']));
close_connection($link);
return $thread; return $thread;
} }
@ -779,15 +804,21 @@ function check_for_reassign($thread, $operator)
} }
} }
function check_connections_from_remote($remote, $link) function check_connections_from_remote($remote)
{ {
global $settings, $state_closed, $state_left, $mysqlprefix; global $settings, $state_closed, $state_left;
if ($settings['max_connections_from_one_host'] == 0) { if ($settings['max_connections_from_one_host'] == 0) {
return true; return true;
} }
$result = select_one_row(
"select count(*) as opened from ${mysqlprefix}chatthread " . $db = Database::getInstance();
"where remote = '" . db_escape_string($remote, $link) . "' AND istate <> $state_closed AND istate <> $state_left", $link); $result = $db->query(
"select count(*) as opened from {chatthread} " .
"where remote = ? AND istate <> ? AND istate <> ?",
array($remote, $state_closed, $state_left),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if ($result && isset($result['opened'])) { if ($result && isset($result['opened'])) {
return $result['opened'] < $settings['max_connections_from_one_host']; return $result['opened'] < $settings['max_connections_from_one_host'];
} }

View File

@ -19,6 +19,7 @@ session_start();
require_once(dirname(__FILE__) . '/converter.php'); require_once(dirname(__FILE__) . '/converter.php');
require_once(dirname(__FILE__) . '/config.php'); require_once(dirname(__FILE__) . '/config.php');
require_once(dirname(__FILE__) . '/database.php');
$version = '1.6.5'; $version = '1.6.5';
$jsver = "165"; $jsver = "165";
@ -350,111 +351,6 @@ function cutstring($string, $length = 75, $ellipsis = '')
return $result; return $result;
} }
function connect()
{
global $mysqlhost, $mysqllogin, $mysqlpass, $mysqldb, $dbencoding, $force_charset_in_connection, $use_persistent_connection;
if (!extension_loaded("mysql")) {
die('Mysql extension is not loaded');
}
if ($use_persistent_connection) {
$link = @mysql_pconnect($mysqlhost, $mysqllogin, $mysqlpass);
}else{
$link = @mysql_connect($mysqlhost, $mysqllogin, $mysqlpass);
}
if (! $link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysqldb, $link) or die('Could not select database');
if ($force_charset_in_connection) {
perform_query("SET NAMES '$dbencoding'", $link);
}
return $link;
}
function close_connection($link)
{
global $use_persistent_connection;
if (! $use_persistent_connection) {
mysql_close($link);
}
}
function db_escape_string($string, $link = NULL)
{
if ( is_null($link) ) {
return mysql_real_escape_string($string);
}
return mysql_real_escape_string($string, $link);
}
function db_error($link)
{
return mysql_error($link);
}
function db_insert_id($link)
{
return mysql_insert_id($link);
}
function db_fetch_row($result)
{
return mysql_fetch_row($result);
}
function db_fetch_assoc($result){
return mysql_fetch_assoc($result);
}
function perform_query($query, $link)
{
$result = mysql_query($query, $link);
if (! $result) {
die(' Query failed: ' . db_error($link));
}
return $result;
}
function db_free_result($result)
{
mysql_free_result($result);
}
function select_one_row($query, $link)
{
$result = perform_query($query, $link);
$line = db_fetch_assoc($result);
db_free_result($result);
return $line;
}
function select_multi_assoc($query, $link)
{
$sqlresult = perform_query($query, $link);
$result = array();
while ($row = db_fetch_assoc($sqlresult)) {
$result[] = $row;
}
db_free_result($sqlresult);
return $result;
}
function db_build_select($fields, $table, $conditions, $orderandgroup)
{
$condition = count($conditions) > 0 ? " where " . implode(" and ", $conditions) : "";
if ($orderandgroup) $orderandgroup = " " . $orderandgroup;
return "select $fields from $table$condition$orderandgroup";
}
function db_rows_count($table, $conditions, $countfields, $link)
{
$result = perform_query(db_build_select("count(" . ($countfields ? $countfields : "*") . ")", $table, $conditions, ""), $link);
$line = db_fetch_row($result);
db_free_result($result);
return $line[0];
}
function start_xml_output() function start_xml_output()
{ {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
@ -716,32 +612,25 @@ $settings = array(
$settingsloaded = false; $settingsloaded = false;
$settings_in_db = array(); $settings_in_db = array();
function loadsettings_($link) function loadsettings()
{ {
global $settingsloaded, $settings_in_db, $settings, $mysqlprefix; global $settingsloaded, $settings_in_db, $settings;
if ($settingsloaded) { if ($settingsloaded) {
return; return;
} }
$settingsloaded = true; $settingsloaded = true;
$sqlresult = perform_query("select vckey,vcvalue from ${mysqlprefix}chatconfig", $link); $db = Database::getInstance();
$rows = $db->query(
while ($row = db_fetch_assoc($sqlresult)) { "select vckey,vcvalue from {chatconfig}",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
foreach ($rows as $row) {
$name = $row['vckey']; $name = $row['vckey'];
$settings[$name] = $row['vcvalue']; $settings[$name] = $row['vcvalue'];
$settings_in_db[$name] = true; $settings_in_db[$name] = true;
} }
db_free_result($sqlresult);
}
function loadsettings()
{
global $settingsloaded;
if (!$settingsloaded) {
$link = connect();
loadsettings_($link);
close_connection($link);
}
} }
function getchatstyle() function getchatstyle()

View File

@ -65,9 +65,7 @@ function verifyparam_groupid($paramid)
function get_groups_list() function get_groups_list()
{ {
$result = array(); $result = array();
$link = connect(); $allgroups = get_all_groups();
$allgroups = get_all_groups($link);
close_connection($link);
$result[] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group"), 'level' => 0); $result[] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group"), 'level' => 0);
foreach ($allgroups as $g) { foreach ($allgroups as $g) {
$result[] = $g; $result[] = $g;

View File

@ -17,11 +17,12 @@
function group_by_id($id) function group_by_id($id)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $group = $db->query(
$group = select_one_row( "select * from {chatgroup} where groupid = ?",
"select * from ${mysqlprefix}chatgroup where groupid = $id", $link); array($id),
close_connection($link); array('return_rows' => Database::RETURN_ONE_ROW)
);
return $group; return $group;
} }
@ -47,12 +48,17 @@ function setup_group_settings_tabs($gid, $active)
} }
} }
function get_operator_groupslist($operatorid, $link) function get_operator_groupslist($operatorid)
{ {
global $settings, $mysqlprefix; global $settings;
$db = Database::getInstance();
if ($settings['enablegroups'] == '1') { if ($settings['enablegroups'] == '1') {
$groupids = array(0); $groupids = array(0);
$allgroups = select_multi_assoc("select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid order by groupid", $link); $allgroups = $db->query(
"select groupid from {chatgroupoperator} where operatorid = ? order by groupid",
array($operatorid),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
foreach ($allgroups as $g) { foreach ($allgroups as $g) {
$groupids[] = $g['groupid']; $groupids[] = $g['groupid'];
} }
@ -64,10 +70,13 @@ function get_operator_groupslist($operatorid, $link)
function get_available_parent_groups($skipgroup) function get_available_parent_groups($skipgroup)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $groupslist = $db->query(
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, parent, vclocalname from ${mysqlprefix}chatgroup order by vclocalname"; "select {chatgroup}.groupid as groupid, parent, vclocalname " .
$groupslist = select_multi_assoc($query, $link); "from {chatgroup} order by vclocalname",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$result = array(array('groupid' => '', 'level' => '', 'vclocalname' => getlocal("form.field.groupparent.root"))); $result = array(array('groupid' => '', 'level' => '', 'vclocalname' => getlocal("form.field.groupparent.root")));
if ($skipgroup) { if ($skipgroup) {
@ -77,15 +86,17 @@ function get_available_parent_groups($skipgroup)
} }
$result = array_merge($result, get_sorted_child_groups_($groupslist, $skipgroup, 0) ); $result = array_merge($result, get_sorted_child_groups_($groupslist, $skipgroup, 0) );
close_connection($link);
return $result; return $result;
} }
function group_has_children($groupid, $link) function group_has_children($groupid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$children = select_one_row(sprintf("select COUNT(*) as count from ${mysqlprefix}chatgroup where parent = %u", $groupid), $children = $db->query(
$link); "select COUNT(*) as count from {chatgroup} where parent = ?",
array($groupid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return ($children['count'] > 0); return ($children['count'] > 0);
} }

View File

@ -15,11 +15,14 @@
* limitations under the License. * limitations under the License.
*/ */
function invitation_state($visitorid, $link) function invitation_state($visitorid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = "select invited, threadid from ${mysqlprefix}chatsitevisitor where visitorid = '" . db_escape_string($visitorid) . "'"; $result = $db->query(
$result = select_one_row($query, $link); "select invited, threadid from {chatsitevisitor} where visitorid = ?",
array($visitorid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if (!$result) { if (!$result) {
$result['invited'] = 0; $result['invited'] = 0;
$result['threadid'] = 0; $result['threadid'] = 0;
@ -27,46 +30,51 @@ function invitation_state($visitorid, $link)
return $result; return $result;
} }
function invitation_invite($visitorid, $operatorid, $link) function invitation_invite($visitorid, $operatorid)
{ {
global $mysqlprefix; if (!invitation_check($visitorid)) {
$db = Database::getInstance();
if (!invitation_check($visitorid, $link)) { $db->query(
$query = "update ${mysqlprefix}chatsitevisitor set invited = 1, invitedby = '" . db_escape_string($operatorid) . "', invitationtime = now(), invitations = invitations + 1 where visitorid = '" . db_escape_string($visitorid) . "'"; "update {chatsitevisitor} set invited = 1, invitedby = ?, " .
perform_query($query, $link); "invitationtime = now(), invitations = invitations + 1 where visitorid = ?",
return invitation_check($visitorid, $link); array($operatorid, $visitorid)
} );
else { return invitation_check($visitorid);
return FALSE; } else {
return FALSE;
} }
} }
function invitation_check($visitorid, $link) function invitation_check($visitorid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$result = $db->query(
$query = "select invitedby from ${mysqlprefix}chatsitevisitor where invited and visitorid = '" . db_escape_string($visitorid) . "'" . "select invitedby from {chatsitevisitor} where invited and visitorid = ? " .
" and lasttime < invitationtime and threadid is null"; " and lasttime < invitationtime and threadid is null",
$result = select_one_row($query, $link); array($visitorid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return ($result && isset($result['invitedby']) && $result['invitedby']) ? $result['invitedby'] : FALSE; return ($result && isset($result['invitedby']) && $result['invitedby']) ? $result['invitedby'] : FALSE;
} }
function invitation_accept($visitorid, $threadid, $link) function invitation_accept($visitorid, $threadid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$db->query(
"update {chatsitevisitor} set threadid = ?, chats = chats + 1 where visitorid = ?",
array($threadid, $visitorid)
);
$query = "update ${mysqlprefix}chatsitevisitor set threadid = " . $threadid . ", chats = chats + 1 where visitorid = " . db_escape_string($visitorid) . ""; $result = $db->query(
perform_query($query, $link); "select invitedby from {chatsitevisitor} where visitorid = ?",
array($visitorid),
$query = "select invitedby from ${mysqlprefix}chatsitevisitor where visitorid = '" . db_escape_string($visitorid) . "'"; array('return_rows' => Database::RETURN_ONE_ROW)
$result = select_one_row($query, $link); );
if ($result && isset($result['invitedby']) && $result['invitedby']) { if ($result && isset($result['invitedby']) && $result['invitedby']) {
return $result['invitedby']; return $result['invitedby'];
} } else {
else { return FALSE;
return FALSE;
} }
} }

View File

@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
function webim_mail($toaddr, $reply_to, $subject, $body, $link) function webim_mail($toaddr, $reply_to, $subject, $body)
{ {
global $webim_encoding, $webim_mailbox, $mail_encoding, $current_locale; global $webim_encoding, $webim_mailbox, $mail_encoding, $current_locale;

400
src/messenger/webim/libs/operator.php Executable file → Normal file
View File

@ -31,37 +31,32 @@ $permission_ids = array(
function operator_by_login($login) function operator_by_login($login)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
$operator = select_one_row( "select * from {chatoperator} where vclogin = ?",
"select * from ${mysqlprefix}chatoperator where vclogin = '" . db_escape_string($login) . "'", $link); array($login),
close_connection($link); array('return_rows' => Database::RETURN_ONE_ROW)
return $operator; );
} }
function operator_by_email($mail) function operator_by_email($mail)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
$operator = select_one_row( "select * from {chatoperator} where vcemail = ?",
"select * from ${mysqlprefix}chatoperator where vcemail = '" . db_escape_string($mail) . "'", $link); array($mail),
close_connection($link); array('return_rows', Database::RETURN_ONE_ROW)
return $operator; );
}
function operator_by_id_($id, $link)
{
global $mysqlprefix;
return select_one_row(
"select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
} }
function operator_by_id($id) function operator_by_id($id)
{ {
$link = connect(); $db = Database::getInstance();
$operator = operator_by_id_($id, $link); return $db->query(
close_connection($link); "select * from {chatoperator} where operatorid = ?",
return $operator; array($id),
array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
/** /**
@ -80,8 +75,7 @@ function operator_by_id($id)
*/ */
function get_operators_list($options) function get_operators_list($options)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect();
if ( !empty($options['sort']) && isset($options['sort']['by']) && isset($options['sort']['desc'])) { if ( !empty($options['sort']) && isset($options['sort']['by']) && isset($options['sort']['desc'])) {
switch ($options['sort']['by']) { switch ($options['sort']['by']) {
@ -103,54 +97,67 @@ function get_operators_list($options)
$orderby = "vclogin"; $orderby = "vclogin";
} }
$query = "select distinct ${mysqlprefix}chatoperator.operatorid, vclogin, vclocalename, vccommonname, istatus, idisabled, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " . $query = "select distinct {chatoperator}.operatorid, vclogin, vclocalename, vccommonname, istatus, idisabled, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator" . "from {chatoperator}" .
( (
empty($options['isolated_operator_id']) ? "" : empty($options['isolated_operator_id']) ? "" :
sprintf(", ${mysqlprefix}chatgroupoperator " . ", {chatgroupoperator} " .
" where ${mysqlprefix}chatoperator.operatorid = ${mysqlprefix}chatgroupoperator.operatorid and ${mysqlprefix}chatgroupoperator.groupid in " . " where {chatoperator}.operatorid = {chatgroupoperator}.operatorid and {chatgroupoperator}.groupid in " .
"(select g.groupid from ${mysqlprefix}chatgroup g, " . "(select g.groupid from {chatgroup} g, " .
"(select distinct parent from ${mysqlprefix}chatgroup, ${mysqlprefix}chatgroupoperator " . "(select distinct parent from {chatgroup}, {chatgroupoperator} " .
"where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid and ${mysqlprefix}chatgroupoperator.operatorid = %u) i " . "where {chatgroup}.groupid = {chatgroupoperator}.groupid and {chatgroupoperator}.operatorid = :operatorid) i " .
"where g.groupid = i.parent or g.parent = i.parent " . "where g.groupid = i.parent or g.parent = i.parent " .
")", $options['isolated_operator_id']) ")"
) . ) .
" order by " . $orderby; " order by " . $orderby;
$operators = select_multi_assoc($query, $link); $operators = $db->query(
close_connection($link); $query,
(
empty($options['isolated_operator_id'])
? array()
: array(':operatorid' => $options['isolated_operator_id'])
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
return $operators; return $operators;
} }
function operator_get_all() function operator_get_all()
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $operators = $db->query(
"select operatorid, vclogin, vclocalename, vccommonname, istatus, idisabled, " .
$query = "select operatorid, vclogin, vclocalename, vccommonname, istatus, idisabled, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " . "(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator order by vclogin"; "from {chatoperator} order by vclogin",
$operators = select_multi_assoc($query, $link); NULL,
close_connection($link); array('return_rows' => Database::RETURN_ALL_ROWS)
return $operators; );
} }
function get_operators_from_adjacent_groups($operator) function get_operators_from_adjacent_groups($operator)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $query = "select distinct {chatoperator}.operatorid, vclogin, vclocalename,vccommonname, " .
"istatus, idisabled, " .
$query = "select distinct ${mysqlprefix}chatoperator.operatorid, vclogin, vclocalename, vccommonname, istatus, idisabled, (unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " . "(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator, ${mysqlprefix}chatgroupoperator " . "from {chatoperator}, {chatgroupoperator} " .
" where ${mysqlprefix}chatoperator.operatorid = ${mysqlprefix}chatgroupoperator.operatorid and ${mysqlprefix}chatgroupoperator.groupid in " . "where {chatoperator}.operatorid = {chatgroupoperator}.operatorid " .
"(select g.groupid from ${mysqlprefix}chatgroup g, " . "and {chatgroupoperator}.groupid in " .
"(select distinct parent from ${mysqlprefix}chatgroup, ${mysqlprefix}chatgroupoperator " . "(select g.groupid from {chatgroup} g, " .
"where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid and ${mysqlprefix}chatgroupoperator.operatorid = ".$operator['operatorid'].") i " . "(select distinct parent from {chatgroup}, {chatgroupoperator} " .
"where g.groupid = i.parent or g.parent = i.parent " . "where {chatgroup}.groupid = {chatgroupoperator}.groupid " .
") order by vclogin"; "and {chatgroupoperator}.operatorid = ?) i " .
"where g.groupid = i.parent or g.parent = i.parent " .
$operators = select_multi_assoc($query, $link); ") order by vclogin";
close_connection($link);
return $operators;
return $db->query(
$query,
array($operator['operatorid']),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
} }
function operator_is_online($operator) function operator_is_online($operator)
@ -178,100 +185,116 @@ function operator_is_disabled($operator)
function update_operator($operatorid, $login, $email, $password, $localename, $commonname) function update_operator($operatorid, $login, $email, $password, $localename, $commonname)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
$query = sprintf( "update {chatoperator} set vclogin = :login, " .
"update ${mysqlprefix}chatoperator set vclogin = '%s',%s vclocalename = '%s', vccommonname = '%s'" . ($password ? " vcpassword=:password, " : "") .
", vcemail = '%s', vcjabbername= '%s'" . "vclocalename = :localname, vccommonname = :commonname, " .
" where operatorid = %s", "vcemail = :email, vcjabbername= :jabbername " .
db_escape_string($login), "where operatorid = :operatorid",
($password ? " vcpassword='" . md5($password) . "'," : ""), array(
db_escape_string($localename), ':login' => $login,
db_escape_string($commonname), ':password' => $password,
db_escape_string($email), ':localname' => $localename,
'', ':commonname' => $commonname,
$operatorid); ':email' => $email,
':jabbername' => '',
perform_query($query, $link); ':operatorid' => $operatorid
close_connection($link); )
);
} }
function update_operator_avatar($operatorid, $avatar) function update_operator_avatar($operatorid, $avatar)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
$query = sprintf( "update {chatoperator} set vcavatar = ? where operatorid = ?",
"update ${mysqlprefix}chatoperator set vcavatar = '%s' where operatorid = %s", array($avatar, $operatorid)
db_escape_string($avatar), $operatorid); );
perform_query($query, $link);
close_connection($link);
}
function create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link)
{
global $mysqlprefix;
$query = sprintf(
"insert into ${mysqlprefix}chatoperator (vclogin,vcpassword,vclocalename,vccommonname,vcavatar,vcemail,vcjabbername) values ('%s','%s','%s','%s','%s','%s','%s')",
db_escape_string($login),
md5($password),
db_escape_string($localename),
db_escape_string($commonname),
db_escape_string($avatar),
db_escape_string($email), '');
perform_query($query, $link);
$id = db_insert_id($link);
return select_one_row("select * from ${mysqlprefix}chatoperator where operatorid = $id", $link);
} }
/**
* @todo Rename create_operator_ function to create_operator and remove any usage of create_operator_
*/
function create_operator($login, $email, $password, $localename, $commonname, $avatar) function create_operator($login, $email, $password, $localename, $commonname, $avatar)
{ {
$link = connect(); $db = Database::getInstance();
$newop = create_operator_($login, $email, $password, $localename, $commonname, $avatar, $link); $db->query(
close_connection($link); "insert into {chatoperator} " .
return $newop; "(vclogin,vcpassword,vclocalename,vccommonname,vcavatar,vcemail,vcjabbername) " .
"values (?, ?, ?, ?, ?, ?, ?)",
array(
$login,
md5($password),
$localename,
$commonname,
$avatar,
$email,
''
)
);
$id = $db->insertedId();
return $db->query(
"select * from {chatoperator} where operatorid = ?",
array($id),
array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
function notify_operator_alive($operatorid, $istatus) function notify_operator_alive($operatorid, $istatus)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
perform_query("update ${mysqlprefix}chatoperator set istatus = $istatus, dtmlastvisited = CURRENT_TIMESTAMP where operatorid = $operatorid", $link); "update {chatoperator} set istatus = ?, dtmlastvisited = CURRENT_TIMESTAMP " .
close_connection($link); "where operatorid = ?",
array($istatus, $operatorid)
);
} }
function has_online_operators($groupid = "") function has_online_operators($groupid = "")
{ {
global $settings, $mysqlprefix; global $settings;
loadsettings(); loadsettings();
$link = connect(); $db = Database::getInstance();
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time from ${mysqlprefix}chatoperator";
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time from {chatoperator}";
if ($groupid) { if ($groupid) {
$query .= ", ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatgroup where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid and " . $query .= ", {chatgroupoperator}, {chatgroup} where {chatgroup}.groupid = {chatgroupoperator}.groupid and " .
"(${mysqlprefix}chatgroup.groupid = $groupid or ${mysqlprefix}chatgroup.parent = $groupid) and ${mysqlprefix}chatoperator.operatorid = " . "({chatgroup}.groupid = :groupid or {chatgroup}.parent = :groupid) and {chatoperator}.operatorid = " .
"${mysqlprefix}chatgroupoperator.operatorid and istatus = 0"; "{chatgroupoperator}.operatorid and istatus = 0";
} else { } else {
if ($settings['enablegroups'] == 1) { if ($settings['enablegroups'] == 1) {
$query .= ", ${mysqlprefix}chatgroupoperator where ${mysqlprefix}chatoperator.operatorid = " . $query .= ", {chatgroupoperator} where {chatoperator}.operatorid = " .
"${mysqlprefix}chatgroupoperator.operatorid and istatus = 0"; "{chatgroupoperator}.operatorid and istatus = 0";
} else { } else {
$query .= " where istatus = 0"; $query .= " where istatus = 0";
} }
} }
$row = select_one_row($query, $link);
close_connection($link); $row = $db->query(
$query,
array(':groupid'=>$groupid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return $row['time'] < $settings['online_timeout'] && $row['total'] > 0; return $row['time'] < $settings['online_timeout'] && $row['total'] > 0;
} }
function is_operator_online($operatorid, $link) function is_operator_online($operatorid)
{ {
global $settings, $mysqlprefix; global $settings;
loadsettings_($link); loadsettings();
$query = "select count(*) as total, min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatoperator where operatorid = $operatorid"; $db = Database::getInstance();
$row = select_one_row($query, $link); $row = $db->query(
"select count(*) as total, " .
"min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from {chatoperator} where operatorid = ?",
array($operatorid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return $row['time'] < $settings['online_timeout'] && $row['total'] == 1; return $row['time'] < $settings['online_timeout'] && $row['total'] == 1;
} }
@ -361,7 +384,7 @@ function logout_operator()
function setup_redirect_links($threadid, $operator, $token) function setup_redirect_links($threadid, $operator, $token)
{ {
global $page, $webimroot, $settings, $mysqlprefix; global $page, $webimroot, $settings;
loadsettings(); loadsettings();
$operator_in_isolation = in_isolation($operator); $operator_in_isolation = in_isolation($operator);
@ -370,12 +393,10 @@ function setup_redirect_links($threadid, $operator, $token)
$operators = get_operators_list($list_options); $operators = get_operators_list($list_options);
$operatorscount = count($operators); $operatorscount = count($operators);
$link = connect();
$groupscount = 0; $groupscount = 0;
$groups = array(); $groups = array();
if ($settings['enablegroups'] == "1") { if ($settings['enablegroups'] == "1") {
$groupslist = $operator_in_isolation?get_groups_for_operator($link, $operator, true):get_groups($link, true); $groupslist = $operator_in_isolation?get_groups_for_operator($operator, true):get_groups(true);
foreach ($groupslist as $group) { foreach ($groupslist as $group) {
if ($group['inumofagents'] == 0) { if ($group['inumofagents'] == 0) {
continue; continue;
@ -384,7 +405,6 @@ function setup_redirect_links($threadid, $operator, $token)
} }
$groupscount = count($groups); $groupscount = count($groups);
} }
close_connection($link);
prepare_pagination(max($operatorscount, $groupscount), 8); prepare_pagination(max($operatorscount, $groupscount), 8);
$p = $page['pagination']; $p = $page['pagination'];
@ -471,23 +491,35 @@ function prepare_menu($operator, $hasright = true)
} }
} }
function get_all_groups($link) function get_all_groups()
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, parent, vclocalname, vclocaldescription from ${mysqlprefix}chatgroup order by vclocalname"; $groups = $db->query(
return get_sorted_child_groups_(select_multi_assoc($query, $link)); "select {chatgroup}.groupid as groupid, parent, vclocalname, vclocaldescription " .
"from {chatgroup} order by vclocalname",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
return get_sorted_child_groups_($groups);
} }
function get_all_groups_for_operator($operator, $link) function get_all_groups_for_operator($operator)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query = "select g.groupid as groupid, g.parent, g.vclocalname, g.vclocaldescription " . $query = "select g.groupid as groupid, g.parent, g.vclocalname, g.vclocaldescription " .
"from ${mysqlprefix}chatgroup g, " . "from {chatgroup} g, " .
"(select distinct parent from ${mysqlprefix}chatgroup, ${mysqlprefix}chatgroupoperator " . "(select distinct parent from {chatgroup}, {chatgroupoperator} " .
"where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid and ${mysqlprefix}chatgroupoperator.operatorid = ".$operator['operatorid'].") i " . "where {chatgroup}.groupid = {chatgroupoperator}.groupid " .
"where g.groupid = i.parent or g.parent = i.parent " . "and {chatgroupoperator}.operatorid = ?) i " .
"order by vclocalname"; "where g.groupid = i.parent or g.parent = i.parent " .
return get_sorted_child_groups_(select_multi_assoc($query, $link)); "order by vclocalname";
$groups = $db->query(
$query,
array($operator['operatorid']),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
return get_sorted_child_groups_($groups);
} }
function get_sorted_child_groups_($groupslist, $skipgroups = array(), $maxlevel = -1, $groupid = NULL, $level = 0) function get_sorted_child_groups_($groupslist, $skipgroups = array(), $maxlevel = -1, $groupid = NULL, $level = 0)
@ -505,10 +537,9 @@ function get_sorted_child_groups_($groupslist, $skipgroups = array(), $maxlevel
return $child_groups; return $child_groups;
} }
function get_groups_($link, $checkaway, $operator, $order = NULL) function get_groups_($checkaway, $operator, $order = NULL)
{ {
global $mysqlprefix; $db = Database::getInstance();
if($order){ if($order){
switch($order['by']){ switch($order['by']){
case 'weight': case 'weight':
@ -518,63 +549,68 @@ function get_groups_($link, $checkaway, $operator, $order = NULL)
$orderby = "ilastseen"; $orderby = "ilastseen";
break; break;
default: default:
$orderby = "${mysqlprefix}chatgroup.vclocalname"; $orderby = "{chatgroup}.vclocalname";
} }
$orderby = sprintf(" IF(ISNULL(${mysqlprefix}chatgroup.parent),CONCAT('_',%s),'') %s, ${mysqlprefix}chatgroup.iweight ", $orderby = sprintf(" IF(ISNULL({chatgroup}.parent),CONCAT('_',%s),'') %s, {chatgroup}.iweight ",
$orderby, $orderby,
($order['desc']?'DESC':'ASC')); ($order['desc']?'DESC':'ASC'));
}else{ }else{
$orderby = "iweight, vclocalname"; $orderby = "iweight, vclocalname";
} }
$query = "select ${mysqlprefix}chatgroup.groupid as groupid, ${mysqlprefix}chatgroup.parent as parent, vclocalname, vclocaldescription, iweight" . $query = "select {chatgroup}.groupid as groupid, {chatgroup}.parent as parent, vclocalname, vclocaldescription, iweight" .
", (SELECT count(*) from ${mysqlprefix}chatgroupoperator where ${mysqlprefix}chatgroup.groupid = " . ", (SELECT count(*) from {chatgroupoperator} where {chatgroup}.groupid = " .
"${mysqlprefix}chatgroupoperator.groupid) as inumofagents" . "{chatgroupoperator}.groupid) as inumofagents" .
", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " . ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus = 0 and " . "from {chatgroupoperator}, {chatoperator} where istatus = 0 and " .
"${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " . "{chatgroup}.groupid = {chatgroupoperator}.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseen" . "and {chatgroupoperator}.operatorid = {chatoperator}.operatorid) as ilastseen" .
($checkaway ($checkaway
? ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " . ? ", (SELECT min(unix_timestamp(CURRENT_TIMESTAMP)-unix_timestamp(dtmlastvisited)) as time " .
"from ${mysqlprefix}chatgroupoperator, ${mysqlprefix}chatoperator where istatus <> 0 and " . "from {chatgroupoperator}, {chatoperator} where istatus <> 0 and " .
"${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid " . "{chatgroup}.groupid = {chatgroupoperator}.groupid " .
"and ${mysqlprefix}chatgroupoperator.operatorid = ${mysqlprefix}chatoperator.operatorid) as ilastseenaway" "and {chatgroupoperator}.operatorid = {chatoperator}.operatorid) as ilastseenaway"
: "" : ""
) . ) .
" from ${mysqlprefix}chatgroup" . " from {chatgroup} " .
($operator ($operator
? ", (select distinct parent from ${mysqlprefix}chatgroup, ${mysqlprefix}chatgroupoperator " . ? ", (select distinct parent from {chatgroup}, {chatgroupoperator} " .
"where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatgroupoperator.groupid and ${mysqlprefix}chatgroupoperator.operatorid = ".$operator['operatorid'].") i " . "where {chatgroup}.groupid = {chatgroupoperator}.groupid and {chatgroupoperator}.operatorid = ?) i " .
"where ${mysqlprefix}chatgroup.groupid = i.parent or ${mysqlprefix}chatgroup.parent = i.parent " "where {chatgroup}.groupid = i.parent or {chatgroup}.parent = i.parent "
: "" : ""
) . ) .
" order by " . $orderby; " order by " . $orderby;
return get_sorted_child_groups_(select_multi_assoc($query, $link)); $groups = $db->query(
$query,
array($operator['operatorid']),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
return get_sorted_child_groups_($groups);
} }
function get_groups($link, $checkaway) function get_groups($checkaway)
{ {
return get_groups_($link, $checkaway, NULL); return get_groups_($checkaway, NULL);
} }
function get_groups_for_operator($link, $operator, $checkaway) function get_groups_for_operator($operator, $checkaway)
{ {
return get_groups_($link, $checkaway, $operator); return get_groups_($checkaway, $operator);
} }
function get_sorted_groups($link, $order) function get_sorted_groups($order)
{ {
return get_groups_($link, true, NULL, $order); return get_groups_(true, NULL, $order);
} }
function get_operator_groupids($operatorid) function get_operator_groupids($operatorid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
$query = "select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid"; "select groupid from {chatgroupoperator} where operatorid = ?",
$result = select_multi_assoc($query, $link); array($operatorid),
close_connection($link); array('return_rows' => Database::RETURN_ALL_ROWS)
return $result; );
} }
?> ?>

View File

@ -72,15 +72,47 @@ function setup_pagination($items, $default_items_per_page = 15)
} }
} }
function select_with_pagintation($fields, $table, $conditions, $order, $countfields, $link) /**
* Selects rows from database taking pagination into account.
*
* @global array $page
* @param string $fields Selected fields
* @param string $table Table name in database
* @param string $conditions Where close
* @param string $order Order clause
* @param string $countfields Field, substituted in SQL COUNT function
* @param array $values Associative array of substituted values. Keys are named placeholders in the
* query(see Database::query() and its $values parameter description)
*
* @see Database::query()
*/
function select_with_pagintation($fields, $table, $conditions, $order, $countfields, $values)
{ {
global $page; global $page;
$count = db_rows_count($table, $conditions, $countfields, $link); $db = Database::getInstance();
list($count) = $db->query(
"select count(". ($countfields ? $countfieds : "*") .") from {$table} " .
"where " . (count($conditions) ? implode(" and ", $conditions) : "") .
($order ? " " . $order : ""),
$values,
array(
'return_rows' => Database::RETURN_ONE_ROW,
'fetch_type' => Database::FETCH_NUM
)
);
prepare_pagination($count); prepare_pagination($count);
if ($count) { if ($count) {
$p = $page['pagination']; $p = $page['pagination'];
$limit = $p['limit']; $limit = $p['limit'];
$page['pagination.items'] = select_multi_assoc(db_build_select($fields, $table, $conditions, $order) . " " . $limit, $link); $page['pagination.items'] = $db->query(
"select {$fields} from {$table} " .
"where " . (count($conditions) ? implode(" and ", $conditions) : "") .
($order ? " " . $order : "") . " " . $limit,
$values,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
} else { } else {
$page['pagination.items'] = false; $page['pagination.items'] = false;
} }

View File

@ -17,17 +17,14 @@
function update_settings() function update_settings()
{ {
global $settings, $settings_in_db, $mysqlprefix; global $settings, $settings_in_db;
$link = connect(); $db = Database::getInstance();
foreach ($settings as $key => $value) { foreach ($settings as $key => $value) {
if (!isset($settings_in_db[$key])) { if (!isset($settings_in_db[$key])) {
perform_query("insert into ${mysqlprefix}chatconfig (vckey) values ('$key')", $link); $db->query("insert into {chatconfig} (vckey) values (?)", array($key));
} }
$query = sprintf("update ${mysqlprefix}chatconfig set vcvalue='%s' where vckey='$key'", db_escape_string($value)); $db->query("update {chatconfig} set vcvalue=? where vckey=?", array($value, $key));
perform_query($query, $link);
} }
close_connection($link);
} }
function setup_settings_tabs($active) function setup_settings_tabs($active)

View File

@ -17,88 +17,108 @@
require_once(dirname(__FILE__).'/chat.php'); require_once(dirname(__FILE__).'/chat.php');
function track_visitor($visitorid, $entry, $referer, $link) function track_visitor($visitorid, $entry, $referer)
{ {
global $mysqlprefix; $visitor = track_get_visitor_by_id($visitorid);
$visitor = track_get_visitor_by_id($visitorid, $link);
if (FALSE === $visitor) { if (FALSE === $visitor) {
$visitor = track_visitor_start($entry, $referer, $link); $visitor = track_visitor_start($entry, $referer);
return $visitor; return $visitor;
} } else {
else { $db = Database::getInstance();
perform_query("update ${mysqlprefix}chatsitevisitor set lasttime = CURRENT_TIMESTAMP where visitorid=" . $visitor['visitorid'], $link); $db->query(
track_visit_page($visitor['visitorid'], $referer, $link); "update {chatsitevisitor} set lasttime = CURRENT_TIMESTAMP " .
return $visitor['visitorid']; "where visitorid=?",
array($visitor['visitorid'])
);
track_visit_page($visitor['visitorid'], $referer);
return $visitor['visitorid'];
} }
} }
function track_visitor_start($entry, $referer, $link) function track_visitor_start($entry, $referer)
{ {
global $mysqlprefix;
$visitor = visitor_from_request(); $visitor = visitor_from_request();
perform_query(sprintf("insert into ${mysqlprefix}chatsitevisitor (userid, username, firsttime, lasttime, entry, details) values ('%s', '%s', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '%s', '%s')", $db = Database::getInstance();
db_escape_string($visitor['id']), $db->query(
db_escape_string($visitor['name']), "insert into {chatsitevisitor} (userid,username,firsttime,lasttime,entry,details) ".
db_escape_string($entry), "values (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?)",
db_escape_string(track_build_details())), $link); array(
$id = db_insert_id($link); $visitor['id'],
$visitor['name'],
$entry,
track_build_details()
)
);
$id = $db->insertedId();
if ($id) { if ($id) {
track_visit_page($id, $referer, $link); track_visit_page($id, $referer);
} }
return $id ? $id : 0; return $id ? $id : 0;
} }
function track_get_visitor_by_id($visitorid, $link) function track_get_visitor_by_id($visitorid)
{ {
global $mysqlprefix; $db = Database::getInstance();
return $db->query(
$visitor = select_one_row( "select * from {chatsitevisitor} where visitorid = ?",
"select * from ${mysqlprefix}chatsitevisitor where visitorid = $visitorid", $link); array($visitorid),
array('return_rows' => Database::RETURN_ONE_ROW)
return $visitor; );
} }
function track_get_visitor_by_threadid($threadid, $link) function track_get_visitor_by_threadid($threadid)
{ {
global $mysqlprefix; $db = Database::getInstance();
return $db->query(
$visitor = select_one_row( "select * from {chatsitevisitor} where threadid = ?",
"select * from ${mysqlprefix}chatsitevisitor where threadid = $threadid", $link); array($threadid),
array('return_rows' => Database::RETURN_ONE_ROW)
return $visitor; );
} }
function track_visit_page($visitorid, $page, $link) function track_visit_page($visitorid, $page)
{ {
global $mysqlprefix; $db = Database::getInstance();
if (empty($page)) { if (empty($page)) {
return; return;
} }
$lastpage = select_one_row(sprintf("select address from ${mysqlprefix}visitedpage where visitorid = '%s' order by visittime desc limit 1", $lastpage = $db->query(
db_escape_string($visitorid)), $link); "select address from {visitedpage} where visitorid = ? " .
"order by visittime desc limit 1",
array($visitorid),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if ( $lastpage['address'] != $page ) { if ( $lastpage['address'] != $page ) {
perform_query(sprintf("insert into ${mysqlprefix}visitedpage (visitorid, address, visittime) values ('%s', '%s', CURRENT_TIMESTAMP)", $db->query(
db_escape_string($visitorid), "insert into {visitedpage} (visitorid, address, visittime) " .
db_escape_string($page)), $link); "values (?, ?, CURRENT_TIMESTAMP)",
perform_query(sprintf("insert into ${mysqlprefix}visitedpagestatistics (address, visittime) values ('%s', CURRENT_TIMESTAMP)", array($visitorid, $page)
db_escape_string($page)), $link); );
$db->query(
"insert into {visitedpagestatistics} (address, visittime) " .
"values (?, CURRENT_TIMESTAMP)",
array($page)
);
} }
} }
function track_get_path($visitor, $link) function track_get_path($visitor)
{ {
global $mysqlprefix; $db = Database::getInstance();
$query_result = perform_query(sprintf("select address, UNIX_TIMESTAMP(visittime) as visittime from ${mysqlprefix}visitedpage where visitorid = '%s'", $query_result = $db->query(
db_escape_string($visitor['visitorid'])), $link); "select address, UNIX_TIMESTAMP(visittime) as visittime from {visitedpage} " .
"where visitorid = ?",
array($visitor['visitorid']),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$result = array(); $result = array();
while( $page = db_fetch_assoc($query_result) ){ foreach ($query_result as $page) {
$result[$page['visittime']] = $page['address']; $result[$page['visittime']] = $page['address'];
} }
return $result; return $result;

View File

@ -63,9 +63,7 @@ loadsettings();
$subject = getstring("mail.user.history.subject"); $subject = getstring("mail.user.history.subject");
$body = getstring2("mail.user.history.body", array($thread['userName'],$history,$settings['title'],$settings['hosturl']) ); $body = getstring2("mail.user.history.body", array($thread['userName'],$history,$settings['title'],$settings['hosturl']) );
$link = connect(); webim_mail($email, $webim_mailbox, $subject, $body);
webim_mail($email, $webim_mailbox, $subject, $body, $link);
close_connection($link);
setup_logo($group); setup_logo($group);
expand("styles/dialogs", getchatstyle(), "mailsent.tpl"); expand("styles/dialogs", getchatstyle(), "mailsent.tpl");

View File

@ -46,9 +46,7 @@ if (isset($_POST['address'])) {
$errors[] = no_field("form.field.ban_comment"); $errors[] = no_field("form.field.ban_comment");
} }
$link = connect(); $existing_ban = ban_for_addr($address);
$existing_ban = ban_for_addr_($address, $link);
close_connection($link);
if ((!$banId && $existing_ban) || if ((!$banId && $existing_ban) ||
($banId && $existing_ban && $banId != $existing_ban['banid'])) { ($banId && $existing_ban && $banId != $existing_ban['banid'])) {
@ -56,24 +54,30 @@ if (isset($_POST['address'])) {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
$link = connect(); $db = Database::getInstance();
$utime = time() + $days * 24 * 60 * 60; $utime = time() + $days * 24 * 60 * 60;
if (!$banId) { if (!$banId) {
$query = sprintf( $db->query(
"insert into ${mysqlprefix}chatban (dtmcreated,dtmtill,address,comment) values (CURRENT_TIMESTAMP,%s,'%s','%s')", "insert into {chatban} (dtmcreated,dtmtill,address,comment) " .
"FROM_UNIXTIME($utime)", "values (CURRENT_TIMESTAMP,FROM_UNIXTIME(?),?,?)",
db_escape_string($address, $link), array(
db_escape_string($comment, $link)); $utime,
perform_query($query, $link); $address,
$comment
)
);
} else { } else {
$query = sprintf( $db->query(
"update ${mysqlprefix}chatban set dtmtill = %s,address = '%s',comment = '%s' where banid = $banId", "update {chatban} set dtmtill = FROM_UNIXTIME(?),address = ?, " .
"FROM_UNIXTIME($utime)", "comment = ? where banid = ?",
db_escape_string($address, $link), array(
db_escape_string($comment, $link)); $utime,
perform_query($query, $link); $address,
$comment,
$banId
)
);
} }
close_connection($link);
if (!$threadid) { if (!$threadid) {
header("Location: $webimroot/operator/blocked.php"); header("Location: $webimroot/operator/blocked.php");
@ -91,9 +95,13 @@ if (isset($_POST['address'])) {
} }
} else if (isset($_GET['id'])) { } else if (isset($_GET['id'])) {
$banId = verifyparam('id', "/^\d{1,9}$/"); $banId = verifyparam('id', "/^\d{1,9}$/");
$link = connect(); $db = Database::getInstance();
$ban = select_one_row("select banid,(unix_timestamp(dtmtill)-unix_timestamp(CURRENT_TIMESTAMP)) as days,address,comment from ${mysqlprefix}chatban where banid = $banId", $link); $ban = $db->query(
close_connection($link); "select banid,(unix_timestamp(dtmtill)-unix_timestamp(CURRENT_TIMESTAMP))" .
" as days,address,comment from {chatban} where banid = ?",
array($banId),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if ($ban) { if ($ban) {
$page['banId'] = topage($ban['banid']); $page['banId'] = topage($ban['banid']);

View File

@ -26,7 +26,7 @@ $errors = array();
setlocale(LC_TIME, getstring("time.locale")); setlocale(LC_TIME, getstring("time.locale"));
$link = connect(); $db = Database::getInstance();
if (isset($_GET['act']) && $_GET['act'] == 'del') { if (isset($_GET['act']) && $_GET['act'] == 'del') {
$banId = isset($_GET['id']) ? $_GET['id'] : ""; $banId = isset($_GET['id']) ? $_GET['id'] : "";
@ -36,15 +36,17 @@ if (isset($_GET['act']) && $_GET['act'] == 'del') {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
perform_query("delete from ${mysqlprefix}chatban where banid = $banId", $link); $db->query("delete from {chatban} where banid = ?", array($banId));
header("Location: $webimroot/operator/blocked.php"); header("Location: $webimroot/operator/blocked.php");
exit; exit;
} }
} }
$blockedList = select_multi_assoc("select banid,unix_timestamp(dtmtill) as till,address,comment from ${mysqlprefix}chatban", $link); $blockedList = $db->query(
"select banid,unix_timestamp(dtmtill) as till,address,comment from {chatban}",
close_connection($link); NULL,
array('return_rows' => Database::RETURN_ONE_ROW)
);
setup_pagination($blockedList); setup_pagination($blockedList);

View File

@ -57,9 +57,7 @@ if ($groupid) {
} }
} }
$link = connect(); $allgroups = in_isolation($operator)?get_all_groups_for_operator($operator):get_all_groups();
$allgroups = in_isolation($operator)?get_all_groups_for_operator($operator, $link):get_all_groups($link);
close_connection($link);
$page['groups'] = array(); $page['groups'] = array();
$page['groups'][] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group")); $page['groups'][] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group"));
foreach ($allgroups as $g) { foreach ($allgroups as $g) {
@ -76,9 +74,8 @@ if (isset($_GET['act']) && $_GET['act'] == 'delete') {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
$link = connect(); $db = Database::getInstance();
perform_query("delete from ${mysqlprefix}chatresponses where id = $key", $link); $db->query("delete from {chatresponses} where id = ?", array($key));
close_connection($link);
header("Location: $webimroot/operator/canned.php?lang=$lang&group=$groupid"); header("Location: $webimroot/operator/canned.php?lang=$lang&group=$groupid");
exit; exit;
} }

View File

@ -27,11 +27,12 @@ $groupid = '';
function group_by_name($name) function group_by_name($name)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $group = $db->query(
$group = select_one_row( "select * from {chatgroup} where vclocalname = ?",
"select * from ${mysqlprefix}chatgroup where vclocalname = '" . db_escape_string($name) . "'", $link); array($name),
close_connection($link); array('return_rows' => Database::RETURN_ONE_ROW)
);
return $group; return $group;
} }
@ -55,39 +56,49 @@ function check_group_params($group, $extra_params = NULL)
} }
/** /**
* Creates group
*
* @param array $group Operators' group. * @param array $group Operators' group.
* The $group array must contains following keys: * The $group array must contains following keys:
* name, description, commonname, commondescription, * name, description, commonname, commondescription,
* email, weight, parent, title, chattitle, hosturl, logo * email, weight, parent, title, chattitle, hosturl, logo
* @return array Created group
*/ */
function create_group($group) function create_group($group)
{ {
global $mysqlprefix; $db = Database::getInstance();
check_group_params($group); check_group_params($group);
$link = connect(); $db->query(
$query = sprintf( "insert into {chatgroup} (parent, vclocalname,vclocaldescription,vccommonname, " .
"insert into ${mysqlprefix}chatgroup (parent, vclocalname,vclocaldescription,vccommonname,vccommondescription,vcemail,vctitle,vcchattitle,vchosturl,vclogo,iweight) values (%s, '%s','%s','%s','%s','%s','%s','%s','%s','%s',%u)", "vccommondescription,vcemail,vctitle,vcchattitle,vchosturl,vclogo,iweight) " .
($group['parent']?(int)$group['parent']:'NULL'), "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
db_escape_string($group['name']), array(
db_escape_string($group['description']), ($group['parent'] ? (int)$group['parent'] : 'NULL'),
db_escape_string($group['commonname']), $group['name'],
db_escape_string($group['commondescription']), $group['description'],
db_escape_string($group['email']), $group['commonname'],
db_escape_string($group['title']), $group['commondescription'],
db_escape_string($group['chattitle']), $group['email'],
db_escape_string($group['hosturl']), $group['title'],
db_escape_string($group['logo']), $group['chattitle'],
$group['weight']); $group['hosturl'],
$group['logo'],
$group['weight']
)
);
$id = $db->insertedId();
perform_query($query, $link); $newdep = $db->query(
$id = db_insert_id($link); "select * from {chatgroup} where groupid = ?",
array($id),
$newdep = select_one_row("select * from ${mysqlprefix}chatgroup where groupid = $id", $link); array('return_rows' => Database::RETURN_ONE_ROW)
close_connection($link); );
return $newdep; return $newdep;
} }
/** /**
* Updates group info
*
* @param array $group Operators' group. * @param array $group Operators' group.
* The $group array must contains following keys: * The $group array must contains following keys:
* id, name, description, commonname, commondescription, * id, name, description, commonname, commondescription,
@ -95,30 +106,34 @@ function create_group($group)
*/ */
function update_group($group) function update_group($group)
{ {
global $mysqlprefix; $db = Database::getInstance();
check_group_params($group, array('id')); check_group_params($group, array('id'));
$link = connect(); $db->query(
$query = sprintf( "update {chatgroup} set parent = ?, vclocalname = ?, vclocaldescription = ?, " .
"update ${mysqlprefix}chatgroup set parent = %s, vclocalname = '%s', vclocaldescription = '%s', vccommonname = '%s', vccommondescription = '%s', vcemail = '%s', vctitle = '%s', vcchattitle = '%s', vchosturl = '%s', vclogo = '%s', iweight = %u where groupid = %s", "vccommonname = ?, vccommondescription = ?, vcemail = ?, vctitle = ?, " .
($group['parent']?(int)$group['parent']:'NULL'), "vcchattitle = ?, vchosturl = ?, vclogo = ?, iweight = ? where groupid = ?",
db_escape_string($group['name']), array(
db_escape_string($group['description']), ($group['parent'] ? (int)$group['parent'] : 'NULL'),
db_escape_string($group['commonname']), $group['name'],
db_escape_string($group['commondescription']), $group['description'],
db_escape_string($group['email']), $group['commonname'],
db_escape_string($group['title']), $group['commondescription'],
db_escape_string($group['chattitle']), $group['email'],
db_escape_string($group['hosturl']), $group['title'],
db_escape_string($group['logo']), $group['chattitle'],
$group['weight'], $group['hosturl'],
$group['id']); $group['logo'],
perform_query($query, $link); $group['weight'],
$group['id']
)
);
if ($group['parent']) { if ($group['parent']) {
$query = sprintf("update ${mysqlprefix}chatgroup set parent = NULL where parent = %u", $group['id']); $db->query(
perform_query($query, $link); "update {chatgroup} set parent = NULL where parent = ?",
array($group['id'])
);
} }
close_connection($link);
} }
if (isset($_POST['name'])) { if (isset($_POST['name'])) {

View File

@ -23,34 +23,35 @@ $operator = check_login();
function get_group_members($groupid) function get_group_members($groupid)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
$query = "select operatorid from ${mysqlprefix}chatgroupoperator where groupid = $groupid"; "select operatorid from {chatgroupoperator} where groupid = ?",
$result = select_multi_assoc($query, $link); array($groupid),
close_connection($link); array('return_rows' => Database::RETURN_ALL_ROWS)
return $result; );
} }
function update_group_members($groupid, $newvalue) function update_group_members($groupid, $newvalue)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query("delete from {chatgroupoperator} where groupid = ?", array($groupid));
perform_query("delete from ${mysqlprefix}chatgroupoperator where groupid = $groupid", $link);
foreach ($newvalue as $opid) { foreach ($newvalue as $opid) {
perform_query("insert into ${mysqlprefix}chatgroupoperator (groupid, operatorid) values ($groupid,$opid)", $link); $db->query(
"insert into {chatgroupoperator} (groupid, operatorid) values (?, ?)",
array($groupid,$opid)
);
} }
close_connection($link);
} }
function get_operators() function get_operators()
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
"select * from {chatoperator} order by vclogin",
$query = "select * from ${mysqlprefix}chatoperator order by vclogin"; NULL,
$result = select_multi_assoc($query, $link); array('return_rows' => Database::RETURN_ALL_ROWS)
close_connection($link); );
return $result;
} }
$groupid = verifyparam("gid", "/^\d{1,9}$/"); $groupid = verifyparam("gid", "/^\d{1,9}$/");

View File

@ -33,11 +33,10 @@ if (isset($_GET['act']) && $_GET['act'] == 'del') {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
$link = connect(); $db = Database::getInstance();
perform_query("delete from ${mysqlprefix}chatgroup where groupid = $groupid", $link); $db->query("delete from {chatgroup} where groupid = ?", array($groupid));
perform_query("delete from ${mysqlprefix}chatgroupoperator where groupid = $groupid", $link); $db->query("delete from {chatgroupoperator} where groupid = ?", array($groupid));
perform_query("update ${mysqlprefix}chatthread set groupid = 0 where groupid = $groupid", $link); $db->query("update {chatthread} set groupid = 0 where groupid = ?",array($groupid));
close_connection($link);
header("Location: $webimroot/operator/groups.php"); header("Location: $webimroot/operator/groups.php");
exit; exit;
} }
@ -59,9 +58,7 @@ function is_away($group)
$page = array(); $page = array();
$sort['by'] = verifyparam("sortby", "/^(name|lastseen|weight)$/", "name"); $sort['by'] = verifyparam("sortby", "/^(name|lastseen|weight)$/", "name");
$sort['desc'] = (verifyparam("sortdirection", "/^(desc|asc)$/", "desc") == "desc"); $sort['desc'] = (verifyparam("sortdirection", "/^(desc|asc)$/", "desc") == "desc");
$link = connect(); $page['groups'] = get_sorted_groups($sort);
$page['groups'] = get_sorted_groups($link, $sort);
close_connection($link);
$page['formsortby'] = $sort['by']; $page['formsortby'] = $sort['by'];
$page['formsortdirection'] = $sort['desc']?'desc':'asc'; $page['formsortdirection'] = $sort['desc']?'desc':'asc';
$page['canmodify'] = is_capable($can_administrate, $operator); $page['canmodify'] = is_capable($can_administrate, $operator);

View File

@ -35,44 +35,50 @@ $searchType = verifyparam('type', '/^(all|message|operator|visitor)$/', 'all');
$searchInSystemMessages = (verifyparam('insystemmessages', '/^on$/', 'off') == 'on') || !$query; $searchInSystemMessages = (verifyparam('insystemmessages', '/^on$/', 'off') == 'on') || !$query;
if ($query !== false) { if ($query !== false) {
$link = connect(); $db = Database::getInstance();
$groups = $db->query(
"select {chatgroup}.groupid as groupid, vclocalname " .
"from {chatgroup} order by vclocalname",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$result = perform_query("select ${mysqlprefix}chatgroup.groupid as groupid, vclocalname " .
"from ${mysqlprefix}chatgroup order by vclocalname", $link);
$groupName = array(); $groupName = array();
while ($group = db_fetch_assoc($result)) { foreach ($groups as $group) {
$groupName[$group['groupid']] = $group['vclocalname']; $groupName[$group['groupid']] = $group['vclocalname'];
} }
db_free_result($result);
$page['groupName'] = $groupName; $page['groupName'] = $groupName;
$escapedQuery = db_escape_string($query, $link); $values = array(
':query' => "%{$escapedQuery}%",
':kind_user' => $kind_user,
':kind_agent' => $kind_agent
);
$searchConditions = array(); $searchConditions = array();
if ($searchType == 'message' || $searchType == 'all') { if ($searchType == 'message' || $searchType == 'all') {
$searchConditions[] = "(${mysqlprefix}chatmessage.tmessage LIKE '%%$escapedQuery%%'" . $searchConditions[] = "({chatmessage}.tmessage LIKE :query" .
($searchInSystemMessages?'':" AND (${mysqlprefix}chatmessage.ikind = $kind_user OR ${mysqlprefix}chatmessage.ikind = $kind_agent)") . ($searchInSystemMessages?'':" AND ({chatmessage}.ikind = :kind_user OR {chatmessage}.ikind = :kind_agent)") .
")"; ")";
} }
if ($searchType == 'operator' || $searchType == 'all') { if ($searchType == 'operator' || $searchType == 'all') {
$searchConditions[] = "(${mysqlprefix}chatthread.agentName LIKE '%%$escapedQuery%%')"; $searchConditions[] = "({chatthread}.agentName LIKE :query)";
} }
if ($searchType == 'visitor' || $searchType == 'all') { if ($searchType == 'visitor' || $searchType == 'all') {
$searchConditions[] = "(${mysqlprefix}chatthread.userName LIKE '%%$escapedQuery%%')"; $searchConditions[] = "({chatthread}.userName LIKE :query)";
$searchConditions[] = "(${mysqlprefix}chatthread.remote LIKE '%%$escapedQuery%%')"; $searchConditions[] = "({chatthread}.remote LIKE :query)";
} }
select_with_pagintation("DISTINCT unix_timestamp(${mysqlprefix}chatthread.dtmcreated) as created, " . select_with_pagintation("DISTINCT unix_timestamp({chatthread}.dtmcreated) as created, " .
"unix_timestamp(${mysqlprefix}chatthread.dtmmodified) as modified, ${mysqlprefix}chatthread.threadid, " . "unix_timestamp({chatthread}.dtmmodified) as modified, {chatthread}.threadid, " .
"${mysqlprefix}chatthread.remote, ${mysqlprefix}chatthread.agentName, ${mysqlprefix}chatthread.userName, groupid, " . "{chatthread}.remote, {chatthread}.agentName, {chatthread}.userName, groupid, " .
"messageCount as size", "messageCount as size",
"${mysqlprefix}chatthread, ${mysqlprefix}chatmessage", "{chatthread}, {chatmessage}",
array( array(
"${mysqlprefix}chatmessage.threadid = ${mysqlprefix}chatthread.threadid", "{chatmessage}.threadid = {chatthread}.threadid",
"(" . implode(' or ', $searchConditions) . ")" "(" . implode(' or ', $searchConditions) . ")"
), ),
"order by created DESC", "order by created DESC",
"DISTINCT ${mysqlprefix}chatthread.dtmcreated", $link); "DISTINCT {chatthread}.dtmcreated", $values);
close_connection($link);
$page['formq'] = topage($query); $page['formq'] = topage($query);
} else { } else {

View File

@ -21,10 +21,8 @@ require_once('../libs/operator.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
$link = connect(); loadsettings();
loadsettings_($link); $isonline = is_operator_online($operator['operatorid']);
$isonline = is_operator_online($operator['operatorid'], $link);
close_connection($link);
$page = array( $page = array(
'version' => $version, 'version' => $version,

View File

@ -27,9 +27,7 @@ $visitorid = verifyparam("visitor", "/^\d{1,8}$/");
$errors = array(); $errors = array();
$link = connect(); $invitation = invitation_state($visitorid);
$invitation = invitation_state($visitorid, $link);
close_connection($link);
start_xml_output(); start_xml_output();
echo '<invitation>'; echo '<invitation>';

View File

@ -25,11 +25,9 @@ loadsettings();
$visitorid = verifyparam("visitor", "/^\d{1,8}$/"); $visitorid = verifyparam("visitor", "/^\d{1,8}$/");
$link = connect(); if (!invitation_invite($visitorid, $operator['operatorid'])) {
if (!invitation_invite($visitorid, $operator['operatorid'], $link)) {
die("Invitation failed!"); die("Invitation failed!");
} }
close_connection($link);
$page = array(); $page = array();
$page['visitor'] = $visitorid; $page['visitor'] = $visitorid;

View File

@ -48,11 +48,15 @@ if (isset($_GET['act'])) {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
$link = connect(); $db = Database::getInstance();
perform_query("delete from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid", $link); $db->query(
perform_query("delete from ${mysqlprefix}chatoperator where operatorid = $operatorid", $link); "delete from {chatgroupoperator} where operatorid = ?",
close_connection($link); array($operatorid)
);
$db->query(
"delete from {chatoperator} where operatorid = ?",
array($operatorid)
);
header("Location: $webimroot/operator/operators.php"); header("Location: $webimroot/operator/operators.php");
exit; exit;
} }
@ -77,9 +81,11 @@ if (isset($_GET['act'])) {
} }
if (count($errors) == 0) { if (count($errors) == 0) {
$link = connect(); $db = Database::getInstance();
perform_query("update ${mysqlprefix}chatoperator set idisabled = ".($act_disable?'1':'0')." where operatorid = $operatorid", $link); $db->query(
close_connection($link); "update {chatoperator} set idisabled = ? where operatorid = ?",
array(($act_disable ? '1' : '0'), $operatorid)
);
header("Location: $webimroot/operator/operators.php"); header("Location: $webimroot/operator/operators.php");
exit; exit;

View File

@ -23,22 +23,25 @@ $operator = check_login();
function update_operator_groups($operatorid, $newvalue) function update_operator_groups($operatorid, $newvalue)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
perform_query("delete from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid", $link); "delete from {chatgroupoperator} where operatorid = ?",
array($operatorid)
);
foreach ($newvalue as $groupid) { foreach ($newvalue as $groupid) {
perform_query("insert into ${mysqlprefix}chatgroupoperator (groupid, operatorid) values ($groupid,$operatorid)", $link); $db->query(
"insert into {chatgroupoperator} (groupid, operatorid) values (?,?)",
array($groupid, $operatorid)
);
} }
close_connection($link);
} }
$operator_in_isolation = in_isolation($operator); $operator_in_isolation = in_isolation($operator);
$opId = verifyparam("op", "/^\d{1,9}$/"); $opId = verifyparam("op", "/^\d{1,9}$/");
$page = array('opid' => $opId); $page = array('opid' => $opId);
$link = connect(); $page['groups'] = $operator_in_isolation?get_all_groups_for_operator($operator):get_all_groups();
$page['groups'] = $operator_in_isolation?get_all_groups_for_operator($operator, $link):get_all_groups($link);
close_connection($link);
$errors = array(); $errors = array();
$canmodify = is_capable($can_administrate, $operator); $canmodify = is_capable($can_administrate, $operator);

View File

@ -24,12 +24,11 @@ csrfchecktoken();
function update_operator_permissions($operatorid, $newvalue) function update_operator_permissions($operatorid, $newvalue)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); $db->query(
$query = "update ${mysqlprefix}chatoperator set iperm = $newvalue where operatorid = $operatorid"; "update {chatoperator} set iperm = ? where operatorid = ?",
array($newvalue, $operatorid)
perform_query($query, $link); );
close_connection($link);
} }
$opId = verifyparam("op", "/^\d{1,9}$/"); $opId = verifyparam("op", "/^\d{1,9}$/");

View File

@ -41,13 +41,11 @@ if (isset($_GET['nextGroup'])) {
if ($nextGroup) { if ($nextGroup) {
$page['message'] = getlocal2("chat.redirected.group.content", array(topage(get_group_name($nextGroup)))); $page['message'] = getlocal2("chat.redirected.group.content", array(topage(get_group_name($nextGroup))));
if ($thread['istate'] == $state_chatting) { if ($thread['istate'] == $state_chatting) {
$link = connect();
commit_thread($threadid, commit_thread($threadid,
array("istate" => $state_waiting, "nextagent" => 0, "groupid" => $nextid, "agentId" => 0, "agentName" => "''"), $link); array("istate" => $state_waiting, "nextagent" => 0, "groupid" => $nextid, "agentId" => 0, "agentName" => "''"));
post_message_($thread['threadid'], $kind_events, post_message_($thread['threadid'], $kind_events,
getstring2_("chat.status.operator.redirect", getstring2_("chat.status.operator.redirect",
array(get_operator_name($operator)), $thread['locale']), $link); array(get_operator_name($operator)), $thread['locale']));
close_connection($link);
} else { } else {
$errors[] = getlocal("chat.redirect.cannot"); $errors[] = getlocal("chat.redirect.cannot");
} }
@ -62,18 +60,26 @@ if (isset($_GET['nextGroup'])) {
if ($nextOperator) { if ($nextOperator) {
$page['message'] = getlocal2("chat.redirected.content", array(topage(get_operator_name($nextOperator)))); $page['message'] = getlocal2("chat.redirected.content", array(topage(get_operator_name($nextOperator))));
if ($thread['istate'] == $state_chatting) { if ($thread['istate'] == $state_chatting) {
$link = connect();
$threadupdate = array("istate" => $state_waiting, "nextagent" => $nextid, "agentId" => 0); $threadupdate = array("istate" => $state_waiting, "nextagent" => $nextid, "agentId" => 0);
if ($thread['groupid'] != 0) { if ($thread['groupid'] != 0) {
if (FALSE === select_one_row("select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $nextid and groupid = " . $thread['groupid'], $link)) { $db = Database::getInstance();
list($groups_count) = $db->query(
"select count(*) AS count from {chatgroupoperator} " .
"where operatorid = ? and groupid = ?",
array($nextid, $thread['groupid']),
array(
'return_rows' => Database::RETURN_ONE_ROW,
'fetch_type' => Database::FETCH_NUM
)
);
if ($groups_count === 0) {
$threadupdate['groupid'] = 0; $threadupdate['groupid'] = 0;
} }
} }
commit_thread($threadid, $threadupdate, $link); commit_thread($threadid, $threadupdate);
post_message_($thread['threadid'], $kind_events, post_message_($thread['threadid'], $kind_events,
getstring2_("chat.status.operator.redirect", getstring2_("chat.status.operator.redirect",
array(get_operator_name($operator)), $thread['locale']), $link); array(get_operator_name($operator)), $thread['locale']));
close_connection($link);
} else { } else {
$errors[] = getlocal("chat.redirect.cannot"); $errors[] = getlocal("chat.redirect.cannot");
} }

View File

@ -48,10 +48,12 @@ if (count($errors) == 0 && isset($_POST['password'])) {
if (count($errors) == 0) { if (count($errors) == 0) {
$page['isdone'] = true; $page['isdone'] = true;
$link = connect(); $db = Database::getInstance();
$query = "update ${mysqlprefix}chatoperator set vcpassword = '" . md5($password) . "', vcrestoretoken = '' where operatorid = " . $opId; $db->query(
perform_query($query, $link); "update {chatoperator} set vcpassword = ?, vcrestoretoken = '' " .
close_connection($link); "where operatorid = ?",
array(md5($password), $opId)
);
$page['loginname'] = $operator['vclogin']; $page['loginname'] = $operator['vclogin'];
start_html_output(); start_html_output();

View File

@ -40,13 +40,15 @@ if (isset($_POST['loginoremail'])) {
if (count($errors) == 0) { if (count($errors) == 0) {
$token = md5((time() + microtime()) . rand(0, 99999999)); $token = md5((time() + microtime()) . rand(0, 99999999));
$link = connect(); $db = Database::getInstance();
$query = "update ${mysqlprefix}chatoperator set dtmrestore = CURRENT_TIMESTAMP, vcrestoretoken = '$token' where operatorid = " . $torestore['operatorid']; $db->query(
perform_query($query, $link); "update {chatoperator} set dtmrestore = CURRENT_TIMESTAMP, " .
"vcrestoretoken = ? where operatorid = ?",
array($token, $torestore['operatorid'])
);
$href = get_app_location(true, false) . "/operator/resetpwd.php?id=" . $torestore['operatorid'] . "&token=$token"; $href = get_app_location(true, false) . "/operator/resetpwd.php?id=" . $torestore['operatorid'] . "&token=$token";
webim_mail($email, $email, getstring("restore.mailsubj"), getstring2("restore.mailtext", array(get_operator_name($torestore), $href)), $link); webim_mail($email, $email, getstring("restore.mailsubj"), getstring2("restore.mailtext", array(get_operator_name($torestore), $href)));
close_connection($link);
$page['isdone'] = true; $page['isdone'] = true;
require('../view/restore.php'); require('../view/restore.php');

View File

@ -71,31 +71,61 @@ if ($start > $end) {
} }
$activetab = 0; $activetab = 0;
$link = connect(); $db = Database::getInstance();
if ($statisticstype == 'bydate') { if ($statisticstype == 'bydate') {
$page['reportByDate'] = select_multi_assoc("select DATE(t.dtmcreated) as date, COUNT(distinct t.threadid) as threads, SUM(m.ikind = $kind_agent) as agents, SUM(m.ikind = $kind_user) as users, ROUND(AVG(unix_timestamp(t.dtmchatstarted)-unix_timestamp(t.dtmcreated)),1) as avgwaitingtime, ROUND(AVG(tmp.lastmsgtime - unix_timestamp(t.dtmchatstarted)),1) as avgchattime " . $page['reportByDate'] = $db->query(
"from ${mysqlprefix}chatmessage m, ${mysqlprefix}chatthread t, (SELECT i.threadid, unix_timestamp(MAX(i.dtmcreated)) AS lastmsgtime FROM ${mysqlprefix}chatmessage i WHERE (ikind = $kind_user OR ikind = $kind_agent) GROUP BY i.threadid) tmp " . "select DATE(t.dtmcreated) as date, COUNT(distinct t.threadid) as threads, SUM(m.ikind = :kind_agent) as agents, SUM(m.ikind = :kind_user) as users, ROUND(AVG(unix_timestamp(t.dtmchatstarted)-unix_timestamp(t.dtmcreated)),1) as avgwaitingtime, ROUND(AVG(tmp.lastmsgtime - unix_timestamp(t.dtmchatstarted)),1) as avgchattime " .
"where m.threadid = t.threadid AND tmp.threadid = t.threadid AND unix_timestamp(t.dtmchatstarted) <> 0 AND unix_timestamp(m.dtmcreated) >= $start AND unix_timestamp(m.dtmcreated) < $end group by DATE(m.dtmcreated) order by m.dtmcreated desc", $link); "from {chatmessage} m, {chatthread} t, (SELECT i.threadid, unix_timestamp(MAX(i.dtmcreated)) AS lastmsgtime FROM {chatmessage} i WHERE (ikind = :kind_user OR ikind = :kind_agent) GROUP BY i.threadid) tmp " .
"where m.threadid = t.threadid AND tmp.threadid = t.threadid AND unix_timestamp(t.dtmchatstarted) <> 0 AND unix_timestamp(m.dtmcreated) >= :start AND unix_timestamp(m.dtmcreated) < :end group by DATE(m.dtmcreated) order by m.dtmcreated desc",
$page['reportByDateTotal'] = select_one_row("select DATE(t.dtmcreated) as date, COUNT(distinct t.threadid) as threads, SUM(m.ikind = $kind_agent) as agents, SUM(m.ikind = $kind_user) as users, ROUND(AVG(unix_timestamp(t.dtmchatstarted)-unix_timestamp(t.dtmcreated)),1) as avgwaitingtime, ROUND(AVG(tmp.lastmsgtime - unix_timestamp(t.dtmchatstarted)),1) as avgchattime " . array(
"from ${mysqlprefix}chatmessage m, ${mysqlprefix}chatthread t, (SELECT i.threadid, unix_timestamp(MAX(i.dtmcreated)) AS lastmsgtime FROM ${mysqlprefix}chatmessage i WHERE (ikind = $kind_user OR ikind = $kind_agent) GROUP BY i.threadid) tmp " . ':kind_agent' => $kind_agent,
"where m.threadid = t.threadid AND tmp.threadid = t.threadid AND unix_timestamp(t.dtmchatstarted) <> 0 AND unix_timestamp(m.dtmcreated) >= $start AND unix_timestamp(m.dtmcreated) < $end", $link); ':kind_user' => $kind_user,
':start' => $start,
':end' => $end
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$page['reportByDateTotal'] = $db->query(
"select DATE(t.dtmcreated) as date, COUNT(distinct t.threadid) as threads, SUM(m.ikind = :kind_agent) as agents, SUM(m.ikind = :kind_user) as users, ROUND(AVG(unix_timestamp(t.dtmchatstarted)-unix_timestamp(t.dtmcreated)),1) as avgwaitingtime, ROUND(AVG(tmp.lastmsgtime - unix_timestamp(t.dtmchatstarted)),1) as avgchattime " .
"from {chatmessage} m, {chatthread} t, (SELECT i.threadid, unix_timestamp(MAX(i.dtmcreated)) AS lastmsgtime FROM {chatmessage} i WHERE (ikind = :kind_user OR ikind = :kind_agent) GROUP BY i.threadid) tmp " .
"where m.threadid = t.threadid AND tmp.threadid = t.threadid AND unix_timestamp(t.dtmchatstarted) <> 0 AND unix_timestamp(m.dtmcreated) >= :start AND unix_timestamp(m.dtmcreated) < :end",
array(
':kind_agent' => $kind_agent,
':kind_user' => $kind_user,
':start' => $start,
':end' => $end
),
array('return_rows' => Database::RETURN_ONE_ROW)
);
$activetab = 0; $activetab = 0;
} elseif($statisticstype == 'byagent') { } elseif($statisticstype == 'byagent') {
$page['reportByAgent'] = select_multi_assoc("select vclocalename as name, COUNT(distinct threadid) as threads, SUM(ikind = $kind_agent) as msgs, AVG(CHAR_LENGTH(tmessage)) as avglen " . $page['reportByAgent'] = $db->query(
"from ${mysqlprefix}chatmessage, ${mysqlprefix}chatoperator " . "select vclocalename as name, COUNT(distinct threadid) as threads, " .
"where agentId = operatorid AND unix_timestamp(dtmcreated) >= $start AND unix_timestamp(dtmcreated) < $end group by operatorid", $link); "SUM(ikind = :kind_agent) as msgs, AVG(CHAR_LENGTH(tmessage)) as avglen " .
"from {chatmessage}, {chatoperator} " .
"where agentId = operatorid AND unix_timestamp(dtmcreated) >= :start " .
"AND unix_timestamp(dtmcreated) < :end group by operatorid",
array(
':kind_agent' => $kind_agent,
':start' => $start,
':end' => $end
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$activetab = 1; $activetab = 1;
} elseif($statisticstype == 'bypage') { } elseif($statisticstype == 'bypage') {
$page['reportByPage'] = select_multi_assoc("SELECT COUNT(DISTINCT p.pageid) as visittimes, p.address, COUNT(DISTINCT t.threadid) as chattimes " . $page['reportByPage'] = $db->query(
"FROM ${mysqlprefix}visitedpagestatistics p LEFT OUTER JOIN ${mysqlprefix}chatthread t ON (p.address = t.referer AND DATE(p.visittime) = DATE(t.dtmcreated)) " . "SELECT COUNT(DISTINCT p.pageid) as visittimes, p.address, COUNT(DISTINCT t.threadid) as chattimes " .
"WHERE unix_timestamp(p.visittime) >= $start AND unix_timestamp(p.visittime) < $end GROUP BY p.address", $link); "FROM {visitedpagestatistics} p LEFT OUTER JOIN {chatthread} t ON (p.address = t.referer AND DATE(p.visittime) = DATE(t.dtmcreated)) " .
"WHERE unix_timestamp(p.visittime) >= :start AND unix_timestamp(p.visittime) < :end GROUP BY p.address",
array(':start' => $start, ':end' => $end),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$activetab = 2; $activetab = 2;
} }
$page['showresults'] = count($errors) == 0; $page['showresults'] = count($errors) == 0;
close_connection($link);
prepare_menu($operator); prepare_menu($operator);
setup_statistics_tabs($activetab); setup_statistics_tabs($activetab);
start_html_output(); start_html_output();

View File

@ -29,15 +29,16 @@ setlocale(LC_TIME, getstring("time.locale"));
function thread_info($id) function thread_info($id)
{ {
global $mysqlprefix; $db = Database::getInstance();
$link = connect(); return $db->query(
$thread = select_one_row("select userName,agentName,remote,userAgent," . "select userName,agentName,remote,userAgent," .
"unix_timestamp(dtmmodified) as modified, unix_timestamp(dtmcreated) as created," . "unix_timestamp(dtmmodified) as modified, unix_timestamp(dtmcreated) as created," .
"vclocalname as groupName " . "vclocalname as groupName " .
"from ${mysqlprefix}chatthread left join ${mysqlprefix}chatgroup on ${mysqlprefix}chatthread.groupid = ${mysqlprefix}chatgroup.groupid " . "from {chatthread} left join {chatgroup} on {chatthread}.groupid = {chatgroup}.groupid " .
"where threadid = " . $id, $link); "where threadid = ?",
close_connection($link); array($id),
return $thread; array('return_rows' => Database::RETURN_ONE_ROW)
);
} }

View File

@ -36,21 +36,19 @@ else {
$visitorid = verifyparam("visitor", "/^\d{1,8}$/"); $visitorid = verifyparam("visitor", "/^\d{1,8}$/");
} }
$link = connect();
if (isset($threadid)) { if (isset($threadid)) {
$visitor = track_get_visitor_by_threadid($threadid, $link); $visitor = track_get_visitor_by_threadid($threadid);
if (!$visitor) { if (!$visitor) {
die("Wrong thread!"); die("Wrong thread!");
} }
} }
else { else {
$visitor = track_get_visitor_by_id($visitorid, $link); $visitor = track_get_visitor_by_id($visitorid);
if (!$visitor) { if (!$visitor) {
die("Wrong visitor!"); die("Wrong visitor!");
} }
} }
$path = track_get_path($visitor, $link); $path = track_get_path($visitor);
close_connection($link);
$page['entry'] = htmlspecialchars($visitor['entry']); $page['entry'] = htmlspecialchars($visitor['entry']);
$page['history'] = array(); $page['history'] = array();

View File

@ -46,18 +46,18 @@ $threadstate_key = array(
$state_loading => "chat.thread.state_loading" $state_loading => "chat.thread.state_loading"
); );
function thread_to_xml($thread, $link) function thread_to_xml($thread)
{ {
global $state_chatting, $threadstate_to_string, $threadstate_key, global $state_chatting, $threadstate_to_string, $threadstate_key,
$webim_encoding, $operator, $settings, $webim_encoding, $operator, $settings,
$can_viewthreads, $can_takeover, $mysqlprefix; $can_viewthreads, $can_takeover;
$state = $threadstate_to_string[$thread['istate']]; $state = $threadstate_to_string[$thread['istate']];
$result = "<thread id=\"" . $thread['threadid'] . "\" stateid=\"$state\""; $result = "<thread id=\"" . $thread['threadid'] . "\" stateid=\"$state\"";
if ($state == "closed") if ($state == "closed")
return $result . "/>"; return $result . "/>";
$state = getstring($threadstate_key[$thread['istate']]); $state = getstring($threadstate_key[$thread['istate']]);
$nextagent = $thread['nextagent'] != 0 ? operator_by_id_($thread['nextagent'], $link) : null; $nextagent = $thread['nextagent'] != 0 ? operator_by_id($thread['nextagent']) : null;
$threadoperator = $nextagent ? get_operator_name($nextagent) $threadoperator = $nextagent ? get_operator_name($nextagent)
: ($thread['agentName'] ? $thread['agentName'] : "-"); : ($thread['agentName'] ? $thread['agentName'] : "-");
@ -76,7 +76,7 @@ $can_viewthreads, $can_takeover, $mysqlprefix;
$result .= " canban=\"true\""; $result .= " canban=\"true\"";
} }
$banForThread = $settings['enableban'] == "1" ? ban_for_addr_($thread['remote'], $link) : false; $banForThread = $settings['enableban'] == "1" ? ban_for_addr($thread['remote']) : false;
if ($banForThread) { if ($banForThread) {
$result .= " ban=\"blocked\" banid=\"" . $banForThread['banid'] . "\""; $result .= " ban=\"blocked\" banid=\"" . $banForThread['banid'] . "\"";
} }
@ -99,8 +99,12 @@ $can_viewthreads, $can_takeover, $mysqlprefix;
$userAgent = get_useragent_version($thread['userAgent']); $userAgent = get_useragent_version($thread['userAgent']);
$result .= "<useragent>" . $userAgent . "</useragent>"; $result .= "<useragent>" . $userAgent . "</useragent>";
if ($thread["shownmessageid"] != 0) { if ($thread["shownmessageid"] != 0) {
$query = "select tmessage from ${mysqlprefix}chatmessage where messageid = " . $thread["shownmessageid"]; $db = Database::getInstance();
$line = select_one_row($query, $link); $line = $db->query(
"select tmessage from {chatmessage} where messageid = ?",
array($thread["shownmessageid"]),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if ($line) { if ($line) {
$message = preg_replace("/[\r\n\t]+/", " ", $line["tmessage"]); $message = preg_replace("/[\r\n\t]+/", " ", $line["tmessage"]);
$result .= "<message>" . htmlspecialchars(htmlspecialchars($message)) . "</message>"; $result .= "<message>" . htmlspecialchars(htmlspecialchars($message)) . "</message>";
@ -112,34 +116,42 @@ $can_viewthreads, $can_takeover, $mysqlprefix;
function print_pending_threads($groupids, $since) function print_pending_threads($groupids, $since)
{ {
global $webim_encoding, $settings, $state_closed, $state_left, $mysqlprefix; global $webim_encoding, $settings, $state_closed, $state_left;
$link = connect(); $db = Database::getInstance();
$revision = $since; $revision = $since;
$output = array();
$query = "select threadid, userName, agentName, unix_timestamp(dtmcreated), userTyping, " . $query = "select threadid, userName, agentName, unix_timestamp(dtmcreated), userTyping, " .
"unix_timestamp(dtmmodified), lrevision, istate, remote, nextagent, agentId, userid, shownmessageid, userAgent, (select vclocalname from ${mysqlprefix}chatgroup where ${mysqlprefix}chatgroup.groupid = ${mysqlprefix}chatthread.groupid) as groupname " . "unix_timestamp(dtmmodified), lrevision, istate, remote, nextagent, agentId, " .
"from ${mysqlprefix}chatthread where lrevision > $since " . "userid, shownmessageid, userAgent, (select vclocalname from {chatgroup} where {chatgroup}.groupid = {chatthread}.groupid) as groupname " .
($since <= 0 "from {chatthread} where lrevision > :since " .
? "AND istate <> $state_closed AND istate <> $state_left " ($since <= 0
: "") . ? "AND istate <> :state_closed AND istate <> :state_left "
($settings['enablegroups'] == '1' : "") .
? "AND (groupid is NULL" . ($groupids ($settings['enablegroups'] == '1'
? " OR groupid IN ($groupids) OR groupid IN (SELECT parent FROM ${mysqlprefix}chatgroup WHERE groupid IN ($groupids)) " ? "AND (groupid is NULL" . ($groupids
: "") . ? " OR groupid IN ($groupids) OR groupid IN (SELECT parent FROM {chatgroup} WHERE groupid IN ($groupids)) "
") " : "") .
: "") . ") "
"ORDER BY threadid"; : "") .
$rows = select_multi_assoc($query, $link); "ORDER BY threadid";
$rows = $db->query(
$query,
array(
':since' => $since,
':state_closed' => $state_closed,
':state_left' => $state_left
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$output = array();
foreach ($rows as $row) { foreach ($rows as $row) {
$thread = thread_to_xml($row, $link); $thread = thread_to_xml($row);
$output[] = $thread; $output[] = $thread;
if ($row['lrevision'] > $revision) if ($row['lrevision'] > $revision)
$revision = $row['lrevision']; $revision = $row['lrevision'];
} }
close_connection($link);
echo "<threads revision=\"$revision\" time=\"" . time() . "000\">"; echo "<threads revision=\"$revision\" time=\"" . time() . "000\">";
foreach ($output as $thr) { foreach ($output as $thr) {
print myiconv($webim_encoding, "utf-8", $thr); print myiconv($webim_encoding, "utf-8", $thr);
@ -167,7 +179,7 @@ function print_operators($operator)
echo "</operators>"; echo "</operators>";
} }
function visitor_to_xml($visitor, $link) function visitor_to_xml($visitor)
{ {
$result = "<visitor id=\"" . $visitor['visitorid'] . "\">"; $result = "<visitor id=\"" . $visitor['visitorid'] . "\">";
@ -197,7 +209,7 @@ function visitor_to_xml($visitor, $link)
$result .= "<invitation>"; $result .= "<invitation>";
if ($visitor['invited']) { if ($visitor['invited']) {
$result .= "<invitationtime>" . $visitor['unix_timestamp(invitationtime)'] . "000</invitationtime>"; $result .= "<invitationtime>" . $visitor['unix_timestamp(invitationtime)'] . "000</invitationtime>";
$operator = get_operator_name(operator_by_id_($visitor['invitedby'], $link)); $operator = get_operator_name(operator_by_id($visitor['invitedby']));
$result .= "<operator>" . htmlspecialchars(htmlspecialchars($operator)) . "</operator>"; $result .= "<operator>" . htmlspecialchars(htmlspecialchars($operator)) . "</operator>";
} }
$result .= "</invitation>"; $result .= "</invitation>";
@ -208,50 +220,56 @@ function visitor_to_xml($visitor, $link)
function print_visitors() function print_visitors()
{ {
global $webim_encoding, $settings, $state_closed, $state_left, $mysqlprefix; global $webim_encoding, $settings, $state_closed, $state_left;
$link = connect(); $db = Database::getInstance();
// Remove old visitors // Remove old visitors
$query = "DELETE FROM ${mysqlprefix}chatsitevisitor WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lasttime)) > " . $settings['tracking_lifetime'] . $db->query(
" AND (threadid IS NULL OR (SELECT count(*) FROM ${mysqlprefix}chatthread WHERE threadid = ${mysqlprefix}chatsitevisitor.threadid" . "DELETE FROM {chatsitevisitor} " .
" AND istate <> $state_closed AND istate <> $state_left) = 0)"; "WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(lasttime)) > ? ".
perform_query($query, $link); "AND (threadid IS NULL OR " .
"(SELECT count(*) FROM {chatthread} WHERE threadid = {chatsitevisitor}.threadid " .
"AND istate <> {$state_closed} AND istate <> {$state_left}) = 0)",
array($settings['tracking_lifetime'])
);
// Remove old invitations // Remove old invitations
$query = "UPDATE ${mysqlprefix}chatsitevisitor SET invited = 0, invitationtime = NULL, invitedby = NULL" . $db->query(
" WHERE threadid IS NULL AND (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(invitationtime)) > " . "UPDATE {chatsitevisitor} SET invited = 0, invitationtime = NULL, invitedby = NULL".
$settings['invitation_lifetime']; " WHERE threadid IS NULL AND (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(invitationtime)) > ?",
perform_query($query, $link); array($settings['invitation_lifetime'])
);
// Remove associations of visitors with closed threads // Remove associations of visitors with closed threads
$query = "UPDATE ${mysqlprefix}chatsitevisitor SET threadid = NULL WHERE threadid IS NOT NULL AND" . $db->query(
" (SELECT count(*) FROM ${mysqlprefix}chatthread WHERE threadid = ${mysqlprefix}chatsitevisitor.threadid" . "UPDATE {chatsitevisitor} SET threadid = NULL WHERE threadid IS NOT NULL AND" .
" AND istate <> $state_closed AND istate <> $state_left) = 0"; " (SELECT count(*) FROM {chatthread} WHERE threadid = {chatsitevisitor}.threadid" .
perform_query($query, $link); " AND istate <> {$state_closed} AND istate <> {$state_left}) = 0"
);
// Remove old visitors' tracks // Remove old visitors' tracks
$query = "DELETE FROM ${mysqlprefix}visitedpage WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(visittime)) > " . $settings['tracking_lifetime'] . $db->query(
" AND visitorid NOT IN (SELECT visitorid FROM ${mysqlprefix}chatsitevisitor)"; "DELETE FROM {visitedpage} WHERE (UNIX_TIMESTAMP(CURRENT_TIMESTAMP) - UNIX_TIMESTAMP(visittime)) > ? " .
perform_query($query, $link); " AND visitorid NOT IN (SELECT visitorid FROM {chatsitevisitor})",
array($settings['tracking_lifetime'])
$output = array(); );
$query = "SELECT visitorid, userid, username, unix_timestamp(firsttime), unix_timestamp(lasttime), " . $query = "SELECT visitorid, userid, username, unix_timestamp(firsttime), unix_timestamp(lasttime), " .
"entry, details, invited, unix_timestamp(invitationtime), invitedby, invitations, chats " . "entry, details, invited, unix_timestamp(invitationtime), invitedby, invitations, chats " .
"FROM ${mysqlprefix}chatsitevisitor " . "FROM {chatsitevisitor} " .
"WHERE threadid IS NULL " . "WHERE threadid IS NULL " .
"ORDER BY invited, lasttime DESC, invitations"; "ORDER BY invited, lasttime DESC, invitations";
$query .= ($settings['visitors_limit'] == '0') ? "" : " LIMIT " . $settings['visitors_limit']; $query .= ($settings['visitors_limit'] == '0') ? "" : " LIMIT " . $settings['visitors_limit'];
$rows = select_multi_assoc($query, $link); $rows = $db->query($query, NULL, array('return_rows' => Database::RETURN_ALL_ROWS));
$output = array();
foreach ($rows as $row) { foreach ($rows as $row) {
$visitor = visitor_to_xml($row, $link); $visitor = visitor_to_xml($row);
$output[] = $visitor; $output[] = $visitor;
} }
close_connection($link);
echo "<visitors>"; echo "<visitors>";
foreach ($output as $thr) { foreach ($output as $thr) {
print myiconv($webim_encoding, "utf-8", $thr); print myiconv($webim_encoding, "utf-8", $thr);
@ -264,13 +282,11 @@ $status = verifyparam("status", "/^\d{1,2}$/", 0);
$showonline = verifyparam("showonline", "/^1$/", 0); $showonline = verifyparam("showonline", "/^1$/", 0);
$showvisitors = verifyparam("showvisitors", "/^1$/", 0); $showvisitors = verifyparam("showvisitors", "/^1$/", 0);
$link = connect(); loadsettings();
loadsettings_($link);
if (!isset($_SESSION["${mysqlprefix}operatorgroups"])) { if (!isset($_SESSION["${mysqlprefix}operatorgroups"])) {
$_SESSION["${mysqlprefix}operatorgroups"] = get_operator_groupslist($operator['operatorid'], $link); $_SESSION["${mysqlprefix}operatorgroups"] = get_operator_groupslist($operator['operatorid']);
} }
close_old_threads($link); close_old_threads();
close_connection($link);
$groupids = $_SESSION["${mysqlprefix}operatorgroups"]; $groupids = $_SESSION["${mysqlprefix}operatorgroups"];
start_xml_output(); start_xml_output();

View File

@ -35,21 +35,19 @@ if (isset($_GET['userid'])) {
function threads_by_userid($userid) function threads_by_userid($userid)
{ {
global $mysqlprefix; $db = Database::getInstance();
if ($userid == "") { if ($userid == "") {
return null; return null;
} }
$link = connect();
return $db->query(
$query = sprintf("select unix_timestamp(dtmcreated) as created, unix_timestamp(dtmmodified) as modified, " . "select unix_timestamp(dtmcreated) as created, " .
" threadid, remote, agentName, userName " . "unix_timestamp(dtmmodified) as modified, threadid, remote, agentName, userName " .
"from ${mysqlprefix}chatthread " . "from {chatthread} " .
"where userid=\"$userid\" order by created DESC", $userid); "where userid=? order by created DESC",
array($userid),
$foundThreads = select_multi_assoc($query, $link); array('return_rows' => Database::RETURN_ALL_ROWS)
);
close_connection($link);
return $foundThreads;
} }
$found = threads_by_userid($userid); $found = threads_by_userid($userid);

View File

@ -26,10 +26,8 @@ $status = isset($_GET['away']) ? 1 : 0;
notify_operator_alive($operator['operatorid'], $status); notify_operator_alive($operator['operatorid'], $status);
$link = connect(); loadsettings();
loadsettings_($link); $_SESSION["${mysqlprefix}operatorgroups"] = get_operator_groupslist($operator['operatorid']);
$_SESSION["${mysqlprefix}operatorgroups"] = get_operator_groupslist($operator['operatorid'], $link);
close_connection($link);
$page = array(); $page = array();
$page['havemenu'] = isset($_GET['nomenu']) ? "0" : "1"; $page['havemenu'] = isset($_GET['nomenu']) ? "0" : "1";

View File

@ -30,14 +30,12 @@ if ($settings['enabletracking'] == '1') {
$entry = isset($_GET['entry']) ? $_GET['entry'] : ""; $entry = isset($_GET['entry']) ? $_GET['entry'] : "";
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ""; $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
$link = connect();
if (isset($_SESSION['visitorid']) && preg_match('/^[0-9]+$/', $_SESSION['visitorid'])) { if (isset($_SESSION['visitorid']) && preg_match('/^[0-9]+$/', $_SESSION['visitorid'])) {
$invited = invitation_check($_SESSION['visitorid'], $link); $invited = invitation_check($_SESSION['visitorid']);
$visitorid = track_visitor($_SESSION['visitorid'], $entry, $referer, $link); $visitorid = track_visitor($_SESSION['visitorid'], $entry, $referer);
} }
else { else {
$visitorid = track_visitor_start($entry, $referer, $link); $visitorid = track_visitor_start($entry, $referer);
} }
if ($visitorid) { if ($visitorid) {
@ -45,10 +43,9 @@ if ($settings['enabletracking'] == '1') {
} }
if ($invited !== FALSE) { if ($invited !== FALSE) {
$operator = operator_by_id_($invited, $link); $operator = operator_by_id($invited);
} }
close_connection($link);
} }
$response = array(); $response = array();

View File

@ -73,12 +73,10 @@ if( $act == "refresh" ) {
show_error("cannot send"); show_error("cannot send");
} }
$link = connect(); $postedid = post_message_($threadid,$kind,$message,$from,null,$isuser ? null : $operator['operatorid'] );
$postedid = post_message_($threadid,$kind,$message,$link,$from,null,$isuser ? null : $operator['operatorid'] );
if($isuser && $thread["shownmessageid"] == 0) { if($isuser && $thread["shownmessageid"] == 0) {
commit_thread( $thread['threadid'], array('shownmessageid' => $postedid), $link); commit_thread( $thread['threadid'], array('shownmessageid' => $postedid));
} }
close_connection($link);
print_thread_messages($thread, $token, $lastid, $isuser, $outformat, $isuser ? null : $operator['operatorid']); print_thread_messages($thread, $token, $lastid, $isuser, $outformat, $isuser ? null : $operator['operatorid']);
exit; exit;