From a90594235a92ecb7ccac9b84d53104ae8e1a8048 Mon Sep 17 00:00:00 2001
From: Evgeny Gryaznov <egryaznov@gmail.com>
Date: Sat, 26 Feb 2011 15:04:12 +0100
Subject: [PATCH] format code in libs/

---
 src/messenger/webim/libs/captcha.php          |  81 +--
 src/messenger/webim/libs/chat.php             | 525 ++++++++++--------
 src/messenger/webim/libs/common.php           | 479 +++++++++-------
 src/messenger/webim/libs/config.php           |   4 +-
 src/messenger/webim/libs/converter.php        |  60 +-
 src/messenger/webim/libs/demothread.php       |  80 +--
 src/messenger/webim/libs/expand.php           |  70 +--
 src/messenger/webim/libs/groups.php           |  42 +-
 src/messenger/webim/libs/notify.php           |  17 +-
 .../webim/libs/operator_settings.php          |   9 +-
 src/messenger/webim/libs/pagination.php       |  83 +--
 src/messenger/webim/libs/settings.php         |  14 +-
 src/messenger/webim/libs/userinfo.php         |  50 +-
 13 files changed, 819 insertions(+), 695 deletions(-)

diff --git a/src/messenger/webim/libs/captcha.php b/src/messenger/webim/libs/captcha.php
index 3515aa4e..cd4628d0 100644
--- a/src/messenger/webim/libs/captcha.php
+++ b/src/messenger/webim/libs/captcha.php
@@ -15,54 +15,57 @@
 	Copyright 2006 WebCheatSheet.com
 */
 
-function can_show_captcha() {
+function can_show_captcha()
+{
 	return extension_loaded("gd");
 }
 
-function gen_captcha() {
-	$md5_hash = md5(rand(0,9999)); 
-	return substr($md5_hash, 15, 5); 
+function gen_captcha()
+{
+	$md5_hash = md5(rand(0, 9999));
+	return substr($md5_hash, 15, 5);
 }
 
-function draw_captcha($security_code) { 
+function draw_captcha($security_code)
+{
 
-    //Set the image width and height 
-    $width = 100; 
-    $height = 25;  
+	//Set the image width and height
+	$width = 100;
+	$height = 25;
 
-    //Create the image resource 
-    $image = ImageCreate($width, $height);  
-    if(function_exists('imageantialias')) {
+	//Create the image resource
+	$image = ImageCreate($width, $height);
+	if (function_exists('imageantialias')) {
 		imageantialias($image, true);
-    }
-    
-    //We are making three colors, white, black and gray 
-    $white = ImageColorAllocate($image, 255, 255, 255); 
-    $black = ImageColorAllocate($image, 15, 50, 15); 
-    $grey = ImageColorAllocate($image, 204, 204, 204); 
-    $ellipsec = ImageColorAllocate($image, 0, 100, 60); 
-    
-    //Make the background black 
-    ImageFill($image, 0, 0, $black); 
-    imagefilledellipse($image, 56,15,30,17, $ellipsec);
-    
-    //Add randomly generated string in white to the image
-    ImageString($image, 5, 30, 4, $security_code, $white); 
-    
-    //Throw in some lines to make it a little bit harder for any bots to break 
-    ImageRectangle($image,0,0,$width-1,$height-1,$grey); 
-    imageline($image, 0, $height/2+3, $width, $height/2+5, $grey); 
-    imageline($image, $width/2-14, 0, $width/2+7, $height, $grey);
+	}
 
- 
-    //Tell the browser what kind of file is come in 
-    header("Content-Type: image/jpeg"); 
+	//We are making three colors, white, black and gray
+	$white = ImageColorAllocate($image, 255, 255, 255);
+	$black = ImageColorAllocate($image, 15, 50, 15);
+	$grey = ImageColorAllocate($image, 204, 204, 204);
+	$ellipsec = ImageColorAllocate($image, 0, 100, 60);
 
-    //Output the newly created image in jpeg format 
-    ImageJpeg($image); 
-    
-    //Free up resources
-    ImageDestroy($image); 
+	//Make the background black
+	ImageFill($image, 0, 0, $black);
+	imagefilledellipse($image, 56, 15, 30, 17, $ellipsec);
+
+	//Add randomly generated string in white to the image
+	ImageString($image, 5, 30, 4, $security_code, $white);
+
+	//Throw in some lines to make it a little bit harder for any bots to break
+	ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);
+	imageline($image, 0, $height / 2 + 3, $width, $height / 2 + 5, $grey);
+	imageline($image, $width / 2 - 14, 0, $width / 2 + 7, $height, $grey);
+
+
+	//Tell the browser what kind of file is come in
+	header("Content-Type: image/jpeg");
+
+	//Output the newly created image in jpeg format
+	ImageJpeg($image);
+
+	//Free up resources
+	ImageDestroy($image);
 }
- 
+
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/chat.php b/src/messenger/webim/libs/chat.php
index 9a00cb67..7deb64f7 100644
--- a/src/messenger/webim/libs/chat.php
+++ b/src/messenger/webim/libs/chat.php
@@ -40,88 +40,97 @@ $kind_conn = 5;
 $kind_events = 6;
 $kind_avatar = 7;
 
-$kind_to_string = array( $kind_user => "user", $kind_agent => "agent", $kind_for_agent => "hidden",
-	$kind_info => "inf", $kind_conn => "conn", $kind_events => "event", $kind_avatar => "avatar" );
+$kind_to_string = array($kind_user => "user", $kind_agent => "agent", $kind_for_agent => "hidden",
+						$kind_info => "inf", $kind_conn => "conn", $kind_events => "event", $kind_avatar => "avatar");
 
-function get_user_id() {
-	return (time() + microtime()).rand(0,99999999);
+function get_user_id()
+{
+	return (time() + microtime()) . rand(0, 99999999);
 }
 
-function next_token() {
-	return rand(99999,99999999);
+function next_token()
+{
+	return rand(99999, 99999999);
 }
 
-function next_revision($link) {
-    global $mysqlprefix;
-	perform_query("update ${mysqlprefix}chatrevision set id=LAST_INSERT_ID(id+1)",$link);
+function next_revision($link)
+{
+	global $mysqlprefix;
+	perform_query("update ${mysqlprefix}chatrevision set id=LAST_INSERT_ID(id+1)", $link);
 	$val = mysql_insert_id($link);
 	return $val;
 }
 
-function post_message_($threadid,$kind,$message,$link,$from=null,$utime=null,$opid=null) {
-    global $mysqlprefix;
+function post_message_($threadid, $kind, $message, $link, $from = null, $utime = null, $opid = null)
+{
+	global $mysqlprefix;
 	$query = sprintf(
 		"insert into ${mysqlprefix}chatmessage (threadid,ikind,tmessage,tname,agentId,dtmcreated) values (%s, %s,'%s',%s,%s,%s)",
-			$threadid,
-			$kind,
-			mysql_real_escape_string($message,$link),
-			$from ? "'".mysql_real_escape_string($from,$link)."'" : "null",
-			$opid ? $opid : "0",
-			$utime ? "FROM_UNIXTIME($utime)" : "CURRENT_TIMESTAMP" );
+		$threadid,
+		$kind,
+		mysql_real_escape_string($message, $link),
+		$from ? "'" . mysql_real_escape_string($from, $link) . "'" : "null",
+		$opid ? $opid : "0",
+		$utime ? "FROM_UNIXTIME($utime)" : "CURRENT_TIMESTAMP");
 
-	perform_query($query,$link);
+	perform_query($query, $link);
 	return mysql_insert_id($link);
 }
 
-function post_message($threadid,$kind,$message,$from=null,$agentid=null) {
+function post_message($threadid, $kind, $message, $from = null, $agentid = null)
+{
 	$link = connect();
-	$id = post_message_($threadid,$kind,$message,$link,$from,null,$agentid);
+	$id = post_message_($threadid, $kind, $message, $link, $from, null, $agentid);
 	mysql_close($link);
 	return $id;
 }
 
-function prepare_html_message($text) {
+function prepare_html_message($text)
+{
 	$escaped_text = htmlspecialchars($text);
-	$text_w_links = preg_replace('/(http|ftp):\/\/\S*/','<a href="$0" target="_blank">$0</a>',$escaped_text);
-	$multiline = str_replace("\n","<br/>",$text_w_links);
+	$text_w_links = preg_replace('/(http|ftp):\/\/\S*/', '<a href="$0" target="_blank">$0</a>', $escaped_text);
+	$multiline = str_replace("\n", "<br/>", $text_w_links);
 	return $multiline;
 }
 
-function message_to_html($msg) {
+function message_to_html($msg)
+{
 	global $kind_to_string, $kind_avatar;
-	if( $msg['ikind'] == $kind_avatar ) return "";
-	$message = "<span>".date("H:i:s",$msg['created'])."</span> ";
+	if ($msg['ikind'] == $kind_avatar) return "";
+	$message = "<span>" . date("H:i:s", $msg['created']) . "</span> ";
 	$kind = $kind_to_string{$msg['ikind']};
-	if( $msg['tname'] )
-		$message.= "<span class='n$kind'>".htmlspecialchars($msg['tname'])."</span>: ";
-	$message.= "<span class='m$kind'>".prepare_html_message($msg['tmessage'])."</span><br/>";
+	if ($msg['tname'])
+		$message .= "<span class='n$kind'>" . htmlspecialchars($msg['tname']) . "</span>: ";
+	$message .= "<span class='m$kind'>" . prepare_html_message($msg['tmessage']) . "</span><br/>";
 	return $message;
 }
 
-function message_to_text($msg) {
+function message_to_text($msg)
+{
 	global $kind_user, $kind_agent, $kind_info, $kind_avatar;
-	if( $msg['ikind'] == $kind_avatar ) return "";
-	$message_time = date("H:i:s ",$msg['created']);
-	if($msg['ikind'] == $kind_user || $msg['ikind'] == $kind_agent) {
-		if( $msg['tname'] )
-			return $message_time.$msg['tname'].": ".$msg['tmessage']."\n";
+	if ($msg['ikind'] == $kind_avatar) return "";
+	$message_time = date("H:i:s ", $msg['created']);
+	if ($msg['ikind'] == $kind_user || $msg['ikind'] == $kind_agent) {
+		if ($msg['tname'])
+			return $message_time . $msg['tname'] . ": " . $msg['tmessage'] . "\n";
 		else
-			return $message_time.$msg['tmessage']."\n";
-	} else if($msg['ikind'] == $kind_info ) {
-		return $message_time.$msg['tmessage']."\n";
+			return $message_time . $msg['tmessage'] . "\n";
+	} else if ($msg['ikind'] == $kind_info) {
+		return $message_time . $msg['tmessage'] . "\n";
 	} else {
-		return $message_time."[".$msg['tmessage']."]\n";
+		return $message_time . "[" . $msg['tmessage'] . "]\n";
 	}
 }
 
-function get_messages($threadid,$meth,$isuser,&$lastid) {
+function get_messages($threadid, $meth, $isuser, &$lastid)
+{
 	global $kind_for_agent, $kind_avatar, $webim_encoding, $mysqlprefix;
 	$link = connect();
 
 	$query = sprintf(
-		"select messageid,ikind,unix_timestamp(dtmcreated) as created,tname,tmessage from ${mysqlprefix}chatmessage ".
+		"select messageid,ikind,unix_timestamp(dtmcreated) as created,tname,tmessage from ${mysqlprefix}chatmessage " .
 		"where threadid = %s and messageid > %s %s order by messageid",
-		$threadid, $lastid, $isuser ? "and ikind <> $kind_for_agent" : "" );
+		$threadid, $lastid, $isuser ? "and ikind <> $kind_for_agent" : "");
 
 	$messages = array();
 	$msgs = select_multi_assoc($query, $link);
@@ -130,10 +139,10 @@ function get_messages($threadid,$meth,$isuser,&$lastid) {
 		if ($meth == 'xml') {
 			switch ($msg['ikind']) {
 				case $kind_avatar:
-					$message = "<avatar>".myiconv($webim_encoding,"utf-8",escape_with_cdata($msg['tmessage']))."</avatar>";
+					$message = "<avatar>" . myiconv($webim_encoding, "utf-8", escape_with_cdata($msg['tmessage'])) . "</avatar>";
 					break;
 				default:
-					$message = "<message>".myiconv($webim_encoding,"utf-8",escape_with_cdata(message_to_html($msg)))."</message>\n";
+					$message = "<message>" . myiconv($webim_encoding, "utf-8", escape_with_cdata(message_to_html($msg))) . "</message>\n";
 			}
 		} else {
 			if ($msg['ikind'] != $kind_avatar) {
@@ -142,7 +151,7 @@ function get_messages($threadid,$meth,$isuser,&$lastid) {
 		}
 
 		$messages[] = $message;
-		if( $msg['messageid'] > $lastid ) {
+		if ($msg['messageid'] > $lastid) {
 			$lastid = $msg['messageid'];
 		}
 	}
@@ -151,97 +160,102 @@ function get_messages($threadid,$meth,$isuser,&$lastid) {
 	return $messages;
 }
 
-function print_thread_messages($thread, $token, $lastid, $isuser, $format, $agentid=null) {
+function print_thread_messages($thread, $token, $lastid, $isuser, $format, $agentid = null)
+{
 	global $webim_encoding, $webimroot, $connection_timeout, $settings;
 	$threadid = $thread['threadid'];
-	$istyping = abs($thread['current']-$thread[$isuser ? "lpagent" : "lpuser"]) < $connection_timeout
-				&& $thread[$isuser?"agentTyping":"userTyping"] == "1" ? "1" : "0";
+	$istyping = abs($thread['current'] - $thread[$isuser ? "lpagent" : "lpuser"]) < $connection_timeout
+				&& $thread[$isuser ? "agentTyping" : "userTyping"] == "1" ? "1" : "0";
 
-	if( $format == "xml" ) {
-		$output = get_messages($threadid,"xml",$isuser,$lastid);
+	if ($format == "xml") {
+		$output = get_messages($threadid, "xml", $isuser, $lastid);
 
 		start_xml_output();
-		print("<thread lastid=\"$lastid\" typing=\"".$istyping."\" canpost=\"".(($isuser || $agentid != null && $agentid == $thread['agentId']) ? 1 : 0)."\">");
-		foreach( $output as $msg ) {
+		print("<thread lastid=\"$lastid\" typing=\"" . $istyping . "\" canpost=\"" . (($isuser || $agentid != null && $agentid == $thread['agentId']) ? 1 : 0) . "\">");
+		foreach ($output as $msg) {
 			print $msg;
 		}
 		print("</thread>");
-	} else if( $format == "html" ) {
+	} else if ($format == "html") {
 		loadsettings();
-		$output = get_messages($threadid,"html",$isuser,$lastid);
+		$output = get_messages($threadid, "html", $isuser, $lastid);
 
 		start_html_output();
-		$url = "$webimroot/thread.php?act=refresh&amp;thread=$threadid&amp;token=$token&amp;html=on&amp;user=".($isuser?"true":"false");
+		$url = "$webimroot/thread.php?act=refresh&amp;thread=$threadid&amp;token=$token&amp;html=on&amp;user=" . ($isuser ? "true" : "false");
 
 		print(
-			"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">".
-			"<html>\n<head>\n".
-			"<link href=\"$webimroot/styles/default/chat.css\" rel=\"stylesheet\" type=\"text/css\">\n".
-			"<meta http-equiv=\"Refresh\" content=\"".$settings['updatefrequency_oldchat']."; URL=$url&amp;sn=11\">\n".
-			"<meta http-equiv=\"Pragma\" content=\"no-cache\">\n".
-			"<title>chat</title>\n".
-			"</head>\n".
-			"<body bgcolor='#FFFFFF' text='#000000' link='#C28400' vlink='#C28400' alink='#C28400' onload=\"if( location.hash != '#aend' ){location.hash='#aend';}\">".
-			"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr><td valign='top' class='message'>" );
-		
-		foreach( $output as $msg ) {
+				"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" .
+				"<html>\n<head>\n" .
+				"<link href=\"$webimroot/styles/default/chat.css\" rel=\"stylesheet\" type=\"text/css\">\n" .
+				"<meta http-equiv=\"Refresh\" content=\"" . $settings['updatefrequency_oldchat'] . "; URL=$url&amp;sn=11\">\n" .
+				"<meta http-equiv=\"Pragma\" content=\"no-cache\">\n" .
+				"<title>chat</title>\n" .
+				"</head>\n" .
+				"<body bgcolor='#FFFFFF' text='#000000' link='#C28400' vlink='#C28400' alink='#C28400' onload=\"if( location.hash != '#aend' ){location.hash='#aend';}\">" .
+				"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr><td valign='top' class='message'>");
+
+		foreach ($output as $msg) {
 			print $msg;
 		}
 
 		print(
-			"</td></tr></table><a name='aend'></a>".
-			"</body></html>" );
+				"</td></tr></table><a name='aend'></a>" .
+				"</body></html>");
 	}
 }
 
-function get_user_name($username, $addr, $id) {
+function get_user_name($username, $addr, $id)
+{
 	global $settings;
 	loadsettings();
 	return str_replace("{addr}", $addr,
-			str_replace("{id}", $id,
-			str_replace("{name}", $username, $settings['usernamepattern'])));
+					   str_replace("{id}", $id,
+								   str_replace("{name}", $username, $settings['usernamepattern'])));
 }
 
-function is_ajax_browser($browserid,$ver,$useragent) {
-	if( $browserid == "opera" )
+function is_ajax_browser($browserid, $ver, $useragent)
+{
+	if ($browserid == "opera")
 		return $ver >= 8.02;
-	if( $browserid == "safari" )
+	if ($browserid == "safari")
 		return $ver >= 125;
-	if( $browserid == "msie" )
+	if ($browserid == "msie")
 		return $ver >= 5.5 && !strstr($useragent, "powerpc");
-	if( $browserid == "netscape" )
+	if ($browserid == "netscape")
 		return $ver >= 7.1;
-	if( $browserid == "mozilla")
+	if ($browserid == "mozilla")
 		return $ver >= 1.4;
-	if( $browserid == "firefox")
+	if ($browserid == "firefox")
 		return $ver >= 1.0;
-	if( $browserid == "chrome")
+	if ($browserid == "chrome")
 		return true;
 
 	return false;
 }
 
-function is_old_browser($browserid,$ver) {
-	if( $browserid == "opera" )
+function is_old_browser($browserid, $ver)
+{
+	if ($browserid == "opera")
 		return $ver < 7.0;
-	if( $browserid == "msie" )
+	if ($browserid == "msie")
 		return $ver < 5.0;
 	return false;
 }
 
-$knownAgents = array("opera","msie","chrome","safari","firefox","netscape","mozilla");
+$knownAgents = array("opera", "msie", "chrome", "safari", "firefox", "netscape", "mozilla");
 
-function get_remote_level($useragent) {
+function get_remote_level($useragent)
+{
 	global $knownAgents;
 	$useragent = strtolower($useragent);
-	foreach( $knownAgents as $agent ) {
-		if( strstr($useragent,$agent) ) {
-			if( preg_match( "/".$agent."[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches ) ) {
+	foreach ($knownAgents as $agent) {
+		if (strstr($useragent, $agent)) {
+			if (preg_match("/" . $agent . "[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches)) {
 				$ver = $matches[1];
 
-				if( is_ajax_browser($agent,$ver,$useragent) )
+				if (is_ajax_browser($agent, $ver, $useragent))
 					return "ajaxed";
-				else if( is_old_browser($agent,$ver) )
+				else if (is_old_browser($agent, $ver))
 					return "old";
 
 				return "simple";
@@ -251,10 +265,11 @@ function get_remote_level($useragent) {
 	return "simple";
 }
 
-function is_agent_opera95() {
+function is_agent_opera95()
+{
 	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
-	if( strstr($useragent,"opera") ) {
-		if( preg_match( "/opera[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches ) ) {
+	if (strstr($useragent, "opera")) {
+		if (preg_match("/opera[\\s\/]?(\\d+(\\.\\d+)?)/", $useragent, $matches)) {
 			$ver = $matches[1];
 
 			if ($ver >= "9.5")
@@ -264,17 +279,20 @@ function is_agent_opera95() {
 	return false;
 }
 
-function is_mac_opera() {
+function is_mac_opera()
+{
 	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
-	return strstr($useragent,"opera") && strstr($useragent, "mac");
+	return strstr($useragent, "opera") && strstr($useragent, "mac");
 }
 
-function needsFramesrc() {
+function needsFramesrc()
+{
 	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
-	return strstr($useragent,"safari/");
+	return strstr($useragent, "safari/");
 }
 
-function setup_logo() {
+function setup_logo()
+{
 	global $page, $settings;
 	loadsettings();
 	$page['ct.company.name'] = topage($settings['title']);
@@ -282,7 +300,8 @@ function setup_logo() {
 	$page['webimHost'] = topage($settings['hosturl']);
 }
 
-function setup_leavemessage($name, $email, $message, $groupid, $groupname, $info, $referrer,$canshowcaptcha) {
+function setup_leavemessage($name, $email, $message, $groupid, $groupname, $info, $referrer, $canshowcaptcha)
+{
 	global $settings, $page;
 	$page['formname'] = topage($name);
 	$page['formemail'] = topage($email);
@@ -294,44 +313,46 @@ function setup_leavemessage($name, $email, $message, $groupid, $groupname, $info
 	$page['referrer'] = urlencode(topage($referrer));
 }
 
-function setup_survey($name, $email, $groupid, $info, $referrer) {
+function setup_survey($name, $email, $groupid, $info, $referrer)
+{
 	global $settings, $page;
-	
+
 	$page['formname'] = topage($name);
 	$page['formemail'] = topage($email);
 	$page['formgroupid'] = $groupid;
 	$page['forminfo'] = topage($info);
 	$page['referrer'] = urlencode(topage($referrer));
 
-	if($settings['enablegroups'] == '1' && $settings["surveyaskgroup"] == "1") {
+	if ($settings['enablegroups'] == '1' && $settings["surveyaskgroup"] == "1") {
 		$link = connect();
-		$allgroups = get_groups($link,false);
+		$allgroups = get_groups($link, false);
 		mysql_close($link);
 		$val = "";
-		foreach($allgroups as $k) {
+		foreach ($allgroups as $k) {
 			$groupname = $k['vclocalname'];
-			if($k['inumofagents'] == 0) {
+			if ($k['inumofagents'] == 0) {
 				continue;
 			}
-			if($k['ilastseen'] !== NULL && $k['ilastseen'] < $settings['online_timeout']) {
-				if(!$groupid) {
-					$groupid = $k['groupid'];  // select first online group
+			if ($k['ilastseen'] !== NULL && $k['ilastseen'] < $settings['online_timeout']) {
+				if (!$groupid) {
+					$groupid = $k['groupid']; // select first online group
 				}
 			} else {
 				$groupname .= " (offline)";
 			}
 			$isselected = $k['groupid'] == $groupid;
-			$val .= "<option value=\"".$k['groupid']."\"".($isselected ? " selected=\"selected\"" : "").">$groupname</option>";
+			$val .= "<option value=\"" . $k['groupid'] . "\"" . ($isselected ? " selected=\"selected\"" : "") . ">$groupname</option>";
 		}
 		$page['groups'] = $val;
 	}
-	
+
 	$page['showemail'] = $settings["surveyaskmail"] == "1" ? "1" : "";
 	$page['showmessage'] = $settings["surveyaskmessage"] == "1" ? "1" : "";
 	$page['showname'] = $settings['usercanchangename'] == "1" ? "1" : "";
 }
 
-function setup_chatview_for_user($thread,$level) {
+function setup_chatview_for_user($thread, $level)
+{
 	global $page, $webimroot, $settings;
 	loadsettings();
 	$page = array();
@@ -349,19 +370,19 @@ function setup_chatview_for_user($thread,$level) {
 	$page['chat.title'] = topage($settings['chattitle']);
 
 	setup_logo();
-	if($settings['sendmessagekey'] == 'enter') {
+	if ($settings['sendmessagekey'] == 'enter') {
 		$page['send_shortcut'] = "Enter";
-		$page['ignorectrl'] =  1;
+		$page['ignorectrl'] = 1;
 	} else {
 		$page['send_shortcut'] = is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
-		$page['ignorectrl'] =  0;
+		$page['ignorectrl'] = 0;
 	}
 
-	$params = "thread=".$thread['threadid']."&amp;token=".$thread['ltoken'];
-	$page['mailLink'] = "$webimroot/client.php?".$params."&amp;level=$level&amp;act=mailthread";
+	$params = "thread=" . $thread['threadid'] . "&amp;token=" . $thread['ltoken'];
+	$page['mailLink'] = "$webimroot/client.php?" . $params . "&amp;level=$level&amp;act=mailthread";
 
-	if($settings['enablessl'] == "1" && !is_secure_request()) {
-		$page['sslLink'] = get_app_location(true, true)."/client.php?".$params."&amp;level=$level";
+	if ($settings['enablessl'] == "1" && !is_secure_request()) {
+		$page['sslLink'] = get_app_location(true, true) . "/client.php?" . $params . "&amp;level=$level";
 	}
 
 	$page['isOpera95'] = is_agent_opera95();
@@ -370,22 +391,23 @@ function setup_chatview_for_user($thread,$level) {
 	$page['frequency'] = $settings['updatefrequency_chat'];
 }
 
-function load_canned_messages($locale, $groupid) {
-    global $mysqlprefix;
+function load_canned_messages($locale, $groupid)
+{
+	global $mysqlprefix;
 	$link = connect();
 	$result = select_multi_assoc(
-			"select vcvalue from ${mysqlprefix}chatresponses where locale = '".$locale."' ".
-			"AND (groupid is NULL OR groupid = 0) order by vcvalue", $link);
-	if(count($result) == 0) {
-		foreach(explode("\n", getstring_('chat.predefined_answers', $locale)) as $answer) {
+		"select vcvalue from ${mysqlprefix}chatresponses where locale = '$locale' " .
+		"AND (groupid is NULL OR groupid = 0) order by vcvalue", $link);
+	if (count($result) == 0) {
+		foreach (explode("\n", getstring_('chat.predefined_answers', $locale)) as $answer) {
 			$result[] = array('vcvalue' => $answer);
 		}
 	}
-	if($groupid) {
+	if ($groupid) {
 		$result2 = select_multi_assoc(
-				"select vcvalue from ${mysqlprefix}chatresponses where locale = '".$locale."' ".
-				"AND groupid = $groupid order by vcvalue", $link);
-		foreach($result as $r) {
+			"select vcvalue from ${mysqlprefix}chatresponses where locale = '$locale' " .
+			"AND groupid = $groupid order by vcvalue", $link);
+		foreach ($result as $r) {
 			$result2[] = $r;
 		}
 		$result = $result2;
@@ -394,7 +416,8 @@ function load_canned_messages($locale, $groupid) {
 	return $result;
 }
 
-function setup_chatview_for_operator($thread,$operator) {
+function setup_chatview_for_operator($thread, $operator)
+{
 	global $page, $webimroot, $company_logo_link, $company_name, $settings;
 	loadsettings();
 	$page = array();
@@ -403,76 +426,78 @@ function setup_chatview_for_operator($thread,$operator) {
 	$page['canpost'] = $thread['agentId'] == $operator['operatorid'];
 	$page['ct.chatThreadId'] = $thread['threadid'];
 	$page['ct.token'] = $thread['ltoken'];
-	$page['ct.user.name'] = htmlspecialchars(topage(get_user_name($thread['userName'],$thread['remote'],$thread['userid'])));
+	$page['ct.user.name'] = htmlspecialchars(topage(get_user_name($thread['userName'], $thread['remote'], $thread['userid'])));
 	$page['chat.title'] = topage($settings['chattitle']);
 
 	setup_logo();
-	if($settings['sendmessagekey'] == 'enter') {
+	if ($settings['sendmessagekey'] == 'enter') {
 		$page['send_shortcut'] = "Enter";
-		$page['ignorectrl'] =  1;
+		$page['ignorectrl'] = 1;
 	} else {
 		$page['send_shortcut'] = is_mac_opera() ? "&#8984;-Enter" : "Ctrl-Enter";
-		$page['ignorectrl'] =  0;
+		$page['ignorectrl'] = 0;
 	}
 
-	if($settings['enablessl'] == "1" && !is_secure_request()) {
-		$page['sslLink'] = get_app_location(true, true)."/operator/agent.php?thread=".$thread['threadid']."&amp;token=".$thread['ltoken'];
+	if ($settings['enablessl'] == "1" && !is_secure_request()) {
+		$page['sslLink'] = get_app_location(true, true) . "/operator/agent.php?thread=" . $thread['threadid'] . "&amp;token=" . $thread['ltoken'];
 	}
 	$page['isOpera95'] = is_agent_opera95();
 	$page['neediframesrc'] = needsFramesrc();
-	$page['historyParams'] = array("userid" => "".$thread['userid']);
-	$page['historyParamsLink'] = add_params($webimroot."/operator/userhistory.php",$page['historyParams']);
+	$page['historyParams'] = array("userid" => "" . $thread['userid']);
+	$page['historyParamsLink'] = add_params($webimroot . "/operator/userhistory.php", $page['historyParams']);
 	$predefinedres = "";
 	$canned_messages = load_canned_messages($thread['locale'], $thread['groupid']);
-	foreach($canned_messages as $answer) {
-		$predefinedres .= "<option>".htmlspecialchars(topage($answer['vcvalue']))."</option>";
+	foreach ($canned_messages as $answer) {
+		$predefinedres .= "<option>" . htmlspecialchars(topage($answer['vcvalue'])) . "</option>";
 	}
 	$page['predefinedAnswers'] = $predefinedres;
-	$params = "thread=".$thread['threadid']."&amp;token=".$thread['ltoken'];
-	$page['redirectLink'] = "$webimroot/operator/agent.php?".$params."&amp;act=redirect";
+	$params = "thread=" . $thread['threadid'] . "&amp;token=" . $thread['ltoken'];
+	$page['redirectLink'] = "$webimroot/operator/agent.php?" . $params . "&amp;act=redirect";
 
 	$page['namePostfix'] = "";
 	$page['frequency'] = $settings['updatefrequency_chat'];
 }
 
-function update_thread_access($threadid, $params, $link) {
-    global $mysqlprefix;
+function update_thread_access($threadid, $params, $link)
+{
+	global $mysqlprefix;
 	$clause = "";
-	foreach( $params as $k => $v ) {
-		if( strlen($clause) > 0 )
+	foreach ($params as $k => $v) {
+		if (strlen($clause) > 0)
 			$clause .= ", ";
-		$clause .= $k."=".$v;
+		$clause .= $k . "=" . $v;
 	}
 	perform_query(
-		 "update ${mysqlprefix}chatthread set $clause ".
-		 "where threadid = ".$threadid,$link);
+		"update ${mysqlprefix}chatthread set $clause " .
+		"where threadid = $threadid", $link);
 }
 
-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;
 	$link = connect();
 	$params = array(($isuser ? "lastpinguser" : "lastpingagent") => "CURRENT_TIMESTAMP",
-					($isuser ? "userTyping" : "agentTyping") => ($istyping? "1" : "0") );
+					($isuser ? "userTyping" : "agentTyping") => ($istyping ? "1" : "0"));
 
 	$lastping = $thread[$isuser ? "lpagent" : "lpuser"];
 	$current = $thread['current'];
 
-	if( $thread['istate'] == $state_loading && $isuser) {
+	if ($thread['istate'] == $state_loading && $isuser) {
 		$params['istate'] = $state_queue;
 		commit_thread($thread['threadid'], $params, $link);
 		mysql_close($link);
 		return;
 	}
 
- 	if( $lastping > 0 && abs($current-$lastping) > $connection_timeout ) {
+	if ($lastping > 0 && abs($current - $lastping) > $connection_timeout) {
 		$params[$isuser ? "lastpingagent" : "lastpinguser"] = "0";
-		if( !$isuser ) {
+		if (!$isuser) {
 			$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);
-		} else if( $thread['istate'] == $state_chatting ) {
+			post_message_($thread['threadid'], $kind_for_agent, $message_to_post, $link, null, $lastping + $connection_timeout);
+		} else if ($thread['istate'] == $state_chatting) {
 
 			$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, $link, null, $lastping + $connection_timeout);
 			$params['istate'] = $state_waiting;
 			$params['nextagent'] = 0;
 			commit_thread($thread['threadid'], $params, $link);
@@ -485,111 +510,120 @@ function ping_thread($thread, $isuser,$istyping) {
 	mysql_close($link);
 }
 
-function commit_thread($threadid,$params,$link) {
-    global $mysqlprefix;
-	$query = "update ${mysqlprefix}chatthread t set lrevision = ".next_revision($link).", dtmmodified = CURRENT_TIMESTAMP";
-	foreach( $params as $k => $v ) {
-		$query .= ", ".$k."=".$v;
+function commit_thread($threadid, $params, $link)
+{
+	global $mysqlprefix;
+	$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;
+	$query .= " where threadid = $threadid";
 
-	perform_query($query,$link);
+	perform_query($query, $link);
 }
 
-function rename_user($thread, $newname) {
+function rename_user($thread, $newname)
+{
 	global $kind_events;
 
 	$link = connect();
-	commit_thread( $thread['threadid'], array('userName' => "'".mysql_real_escape_string($newname,$link)."'"), $link);
+	commit_thread($thread['threadid'], array('userName' => "'" . mysql_real_escape_string($newname, $link) . "'"), $link);
 
-	if( $thread['userName'] != $newname ) {
-		post_message_($thread['threadid'],$kind_events,
-			getstring2_("chat.status.user.changedname",array($thread['userName'], $newname), $thread['locale']), $link);
+	if ($thread['userName'] != $newname) {
+		post_message_($thread['threadid'], $kind_events,
+					  getstring2_("chat.status.user.changedname", array($thread['userName'], $newname), $thread['locale']), $link);
 	}
 	mysql_close($link);
 }
 
-function close_thread($thread,$isuser) {
+function close_thread($thread, $isuser)
+{
 	global $state_closed, $kind_events, $mysqlprefix;
 
 	$link = connect();
-	if( $thread['istate'] != $state_closed ) {
-		commit_thread( $thread['threadid'], array('istate' => $state_closed,
-			'messageCount' => "(SELECT COUNT(*) FROM ${mysqlprefix}chatmessage WHERE ${mysqlprefix}chatmessage.threadid = t.threadid AND ikind = 1)"), $link);
+	if ($thread['istate'] != $state_closed) {
+		commit_thread($thread['threadid'], array('istate' => $state_closed,
+												'messageCount' => "(SELECT COUNT(*) FROM ${mysqlprefix}chatmessage WHERE ${mysqlprefix}chatmessage.threadid = t.threadid AND ikind = 1)"), $link);
 	}
 
-	$message =  $isuser ? getstring2_("chat.status.user.left", array($thread['userName']), $thread['locale'])
-					: getstring2_("chat.status.operator.left", array($thread['agentName']), $thread['locale']);
+	$message = $isuser ? getstring2_("chat.status.user.left", array($thread['userName']), $thread['locale'])
+			: getstring2_("chat.status.operator.left", array($thread['agentName']), $thread['locale']);
 	post_message_($thread['threadid'], $kind_events, $message, $link);
 	mysql_close($link);
 }
 
-function thread_by_id_($id,$link) {
-    global $mysqlprefix;
-	return select_one_row("select threadid,userName,agentName,agentId,lrevision,istate,ltoken,userTyping,agentTyping".
-			",unix_timestamp(dtmmodified) as modified, unix_timestamp(dtmcreated) as created".
-			",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 thread_by_id_($id, $link)
+{
+	global $mysqlprefix;
+	return select_one_row("select threadid,userName,agentName,agentId,lrevision,istate,ltoken,userTyping,agentTyping" .
+						  ",unix_timestamp(dtmmodified) as modified, unix_timestamp(dtmcreated) as created" .
+						  ",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 = '".mysql_real_escape_string($addr,$link)."'", $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 = '" . mysql_real_escape_string($addr, $link) . "'", $link);
 }
 
-function thread_by_id($id) {
+function thread_by_id($id)
+{
 	$link = connect();
-	$thread = thread_by_id_($id,$link);
+	$thread = thread_by_id_($id, $link);
 	mysql_close($link);
 	return $thread;
 }
 
-function create_thread($groupid,$username,$remoteHost,$referer,$lang,$userid,$userbrowser,$initialState,$link) {
-    global $mysqlprefix;
+function create_thread($groupid, $username, $remoteHost, $referer, $lang, $userid, $userbrowser, $initialState, $link)
+{
+	global $mysqlprefix;
 	$query = sprintf(
-		 "insert into ${mysqlprefix}chatthread (userName,userid,ltoken,remote,referer,lrevision,locale,userAgent,dtmcreated,dtmmodified,istate".($groupid?",groupid":"").") values ".
-								 "('%s','%s',%s,'%s','%s',%s,'%s','%s',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,$initialState".($groupid?",$groupid":"").")",
-			mysql_real_escape_string($username, $link),
-			mysql_real_escape_string($userid, $link),
-			next_token(),
-			mysql_real_escape_string($remoteHost, $link),
-			mysql_real_escape_string($referer, $link),
-			next_revision($link),
-			mysql_real_escape_string($lang, $link),
-			mysql_real_escape_string($userbrowser, $link));
+		"insert into ${mysqlprefix}chatthread (userName,userid,ltoken,remote,referer,lrevision,locale,userAgent,dtmcreated,dtmmodified,istate" . ($groupid ? ",groupid" : "") . ") values " .
+		"('%s','%s',%s,'%s','%s',%s,'%s','%s',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,$initialState" . ($groupid ? ",$groupid" : "") . ")",
+		mysql_real_escape_string($username, $link),
+		mysql_real_escape_string($userid, $link),
+		next_token(),
+		mysql_real_escape_string($remoteHost, $link),
+		mysql_real_escape_string($referer, $link),
+		next_revision($link),
+		mysql_real_escape_string($lang, $link),
+		mysql_real_escape_string($userbrowser, $link));
 
-	perform_query($query,$link);
+	perform_query($query, $link);
 	$id = mysql_insert_id($link);
 
-	$newthread = thread_by_id_($id,$link);
+	$newthread = thread_by_id_($id, $link);
 	return $newthread;
 }
 
-function do_take_thread($threadid,$operatorId,$operatorName) {
+function do_take_thread($threadid, $operatorId, $operatorName)
+{
 	global $state_chatting;
 	$link = connect();
-	commit_thread( $threadid,
-		array("istate" => $state_chatting,
-			  "nextagent" => 0,
-			  "agentId" => $operatorId,
-			  "agentName" => "'".mysql_real_escape_string($operatorName, $link)."'"), $link);
+	commit_thread($threadid,
+				  array("istate" => $state_chatting,
+					   "nextagent" => 0,
+					   "agentId" => $operatorId,
+					   "agentName" => "'" . mysql_real_escape_string($operatorName, $link) . "'"), $link);
 	mysql_close($link);
 }
 
-function reopen_thread($threadid) {
-	global $state_queue,$state_loading,$state_waiting,$state_chatting,$state_closed,$state_left,$kind_events;
+function reopen_thread($threadid)
+{
+	global $state_queue, $state_loading, $state_waiting, $state_chatting, $state_closed, $state_left, $kind_events;
 	$link = connect();
 	$thread = thread_by_id_($threadid, $link);
 
-	if( !$thread )
+	if (!$thread)
 		return FALSE;
 
-	if( $thread['istate'] == $state_closed || $thread['istate'] == $state_left )
+	if ($thread['istate'] == $state_closed || $thread['istate'] == $state_left)
 		return FALSE;
 
-	if( $thread['istate'] != $state_chatting && $thread['istate'] != $state_queue && $thread['istate'] != $state_loading ) {
-		commit_thread( $threadid,
-			array("istate" => $state_waiting, "nextagent" => 0), $link);
+	if ($thread['istate'] != $state_chatting && $thread['istate'] != $state_queue && $thread['istate'] != $state_loading) {
+		commit_thread($threadid,
+					  array("istate" => $state_waiting, "nextagent" => 0), $link);
 	}
 
 	post_message_($thread['threadid'], $kind_events, getstring_("chat.status.user.reopenedthread", $thread['locale']), $link);
@@ -597,7 +631,8 @@ function reopen_thread($threadid) {
 	return $thread;
 }
 
-function take_thread($thread,$operator) {
+function take_thread($thread, $operator)
+{
 	global $state_queue, $state_loading, $state_waiting, $state_chatting, $kind_events, $kind_avatar, $home_locale;
 
 	$state = $thread['istate'];
@@ -606,11 +641,11 @@ function take_thread($thread,$operator) {
 
 	$operatorName = ($thread['locale'] == $home_locale) ? $operator['vclocalename'] : $operator['vccommonname'];
 
-	if( $state == $state_queue || $state == $state_waiting || $state == $state_loading) {
+	if ($state == $state_queue || $state == $state_waiting || $state == $state_loading) {
 		do_take_thread($threadid, $operator['operatorid'], $operatorName);
 
-		if( $state == $state_waiting ) {
-			if( $operatorName != $thread['agentName'] ) {
+		if ($state == $state_waiting) {
+			if ($operatorName != $thread['agentName']) {
 				$message_to_post = getstring2_("chat.status.operator.changed", array($operatorName, $thread['agentName']), $thread['locale']);
 			} else {
 				$message_to_post = getstring2_("chat.status.operator.returned", array($operatorName), $thread['locale']);
@@ -618,8 +653,8 @@ function take_thread($thread,$operator) {
 		} else {
 			$message_to_post = getstring2_("chat.status.operator.joined", array($operatorName), $thread['locale']);
 		}
-	} else if( $state == $state_chatting ) {
-		if( $operator['operatorid'] != $thread['agentId'] ) {
+	} else if ($state == $state_chatting) {
+		if ($operator['operatorid'] != $thread['agentId']) {
 			do_take_thread($threadid, $operator['operatorid'], $operatorName);
 			$message_to_post = getstring2_("chat.status.operator.changed", array($operatorName, $thread['agentName']), $thread['locale']);
 		}
@@ -627,56 +662,59 @@ function take_thread($thread,$operator) {
 		die("cannot take thread");
 	}
 
-	if( $message_to_post ) {
-		post_message($threadid,$kind_events,$message_to_post);
-		post_message($threadid,$kind_avatar,$operator['vcavatar'] ? $operator['vcavatar'] : "");
+	if ($message_to_post) {
+		post_message($threadid, $kind_events, $message_to_post);
+		post_message($threadid, $kind_avatar, $operator['vcavatar'] ? $operator['vcavatar'] : "");
 	}
 }
 
-function check_for_reassign($thread,$operator) {
+function check_for_reassign($thread, $operator)
+{
 	global $state_waiting, $home_locale, $kind_events, $kind_avatar;
 	$operatorName = ($thread['locale'] == $home_locale) ? $operator['vclocalename'] : $operator['vccommonname'];
-	if( $thread['istate'] == $state_waiting &&
-			(  $thread['nextagent'] == $operator['operatorid']
-			|| $thread['agentId'] == $operator['operatorid'] )) {
+	if ($thread['istate'] == $state_waiting &&
+		($thread['nextagent'] == $operator['operatorid']
+		 || $thread['agentId'] == $operator['operatorid'])) {
 		do_take_thread($thread['threadid'], $operator['operatorid'], $operatorName);
-		if( $operatorName != $thread['agentName'] ) {
+		if ($operatorName != $thread['agentName']) {
 			$message_to_post = getstring2_("chat.status.operator.changed", array($operatorName, $thread['agentName']), $thread['locale']);
 		} else {
 			$message_to_post = getstring2_("chat.status.operator.returned", array($operatorName), $thread['locale']);
 		}
 
-		post_message($thread['threadid'],$kind_events,$message_to_post);
-		post_message($thread['threadid'],$kind_avatar,$operator['vcavatar'] ? $operator['vcavatar'] : "");
+		post_message($thread['threadid'], $kind_events, $message_to_post);
+		post_message($thread['threadid'], $kind_avatar, $operator['vcavatar'] ? $operator['vcavatar'] : "");
 	}
 }
 
-function check_connections_from_remote($remote,$link) {
+function check_connections_from_remote($remote, $link)
+{
 	global $settings, $state_closed, $state_left, $mysqlprefix;
-	if($settings['max_connections_from_one_host'] == 0) {
+	if ($settings['max_connections_from_one_host'] == 0) {
 		return true;
 	}
 	$result = select_one_row(
-			"select count(*) as opened from ${mysqlprefix}chatthread ".
-			"where remote = '". mysql_real_escape_string($remote, $link)."' AND istate <> $state_closed AND istate <> $state_left", $link );
-	if($result && isset($result['opened'])) {
+		"select count(*) as opened from ${mysqlprefix}chatthread " .
+		"where remote = '" . mysql_real_escape_string($remote, $link) . "' AND istate <> $state_closed AND istate <> $state_left", $link);
+	if ($result && isset($result['opened'])) {
 		return $result['opened'] < $settings['max_connections_from_one_host'];
 	}
 	return true;
 }
 
-function visitor_from_request() {
+function visitor_from_request()
+{
 	global $namecookie, $webim_encoding, $usercookie;
 	$defaultName = getstring("chat.default.username");
 	$userName = $defaultName;
-	if( isset($_COOKIE[$namecookie]) ) {
-		$data = base64_decode(strtr($_COOKIE[$namecookie],'-_,', '+/='));
-		if( strlen($data) > 0 ) {
-			$userName = myiconv("utf-8",$webim_encoding,$data);
+	if (isset($_COOKIE[$namecookie])) {
+		$data = base64_decode(strtr($_COOKIE[$namecookie], '-_,', '+/='));
+		if (strlen($data) > 0) {
+			$userName = myiconv("utf-8", $webim_encoding, $data);
 		}
 	}
 
-	if($userName == $defaultName) {
+	if ($userName == $defaultName) {
 		$userName = getgetparam('name', $userName);
 	}
 
@@ -684,16 +722,17 @@ function visitor_from_request() {
 		$userId = $_COOKIE[$usercookie];
 	} else {
 		$userId = get_user_id();
-		setcookie($usercookie, $userId, time()+60*60*24*365);
+		setcookie($usercookie, $userId, time() + 60 * 60 * 24 * 365);
 	}
-	return array( 'id' => $userId, 'name' => $userName );
+	return array('id' => $userId, 'name' => $userName);
 }
 
-function get_remote_host() {
+function get_remote_host()
+{
 	$extAddr = $_SERVER['REMOTE_ADDR'];
 	if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &&
-	          $_SERVER['HTTP_X_FORWARDED_FOR'] != $_SERVER['REMOTE_ADDR']) {
-		$extAddr = $_SERVER['REMOTE_ADDR'].' ('.$_SERVER['HTTP_X_FORWARDED_FOR'].')';
+		$_SERVER['HTTP_X_FORWARDED_FOR'] != $_SERVER['REMOTE_ADDR']) {
+		$extAddr = $_SERVER['REMOTE_ADDR'] . ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')';
 	}
 	return isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : $extAddr;
 }
diff --git a/src/messenger/webim/libs/common.php b/src/messenger/webim/libs/common.php
index d9ab098c..a2dde416 100644
--- a/src/messenger/webim/libs/common.php
+++ b/src/messenger/webim/libs/common.php
@@ -21,68 +21,73 @@
 
 session_start();
 
-require_once(dirname(__FILE__).'/converter.php');
-require_once(dirname(__FILE__).'/config.php');
+require_once(dirname(__FILE__) . '/converter.php');
+require_once(dirname(__FILE__) . '/config.php');
 
 $version = '1.6.4';
 $jsver = "164";
 
-function myiconv($in_enc, $out_enc, $string) {
+function myiconv($in_enc, $out_enc, $string)
+{
 	global $_utf8win1251, $_win1251utf8;
-	if($in_enc == $out_enc ) {
+	if ($in_enc == $out_enc) {
 		return $string;
 	}
-	if( function_exists('iconv') ) {
+	if (function_exists('iconv')) {
 		$converted = @iconv($in_enc, $out_enc, $string);
-		if( $converted !== FALSE ) {
+		if ($converted !== FALSE) {
 			return $converted;
 		}
 	}
-	if( $in_enc == "cp1251" && $out_enc == "utf-8" )
+	if ($in_enc == "cp1251" && $out_enc == "utf-8")
 		return strtr($string, $_win1251utf8);
-	if( $in_enc == "utf-8" && $out_enc == "cp1251" )
+	if ($in_enc == "utf-8" && $out_enc == "cp1251")
 		return strtr($string, $_utf8win1251);
 
 	return $string; // do not know how to convert
 }
 
-function verifyparam( $name, $regexp, $default = null ) {
-	if( isset( $_GET[$name] ) ) {
+function verifyparam($name, $regexp, $default = null)
+{
+	if (isset($_GET[$name])) {
 		$val = $_GET[$name];
-		if( preg_match( $regexp, $val ) )
+		if (preg_match($regexp, $val))
 			return $val;
 
-	} else if( isset( $_POST[$name] ) ) {
+	} else if (isset($_POST[$name])) {
 		$val = $_POST[$name];
-		if( preg_match( $regexp, $val ) )
+		if (preg_match($regexp, $val))
 			return $val;
 
 	} else {
-		if( isset( $default ) )
+		if (isset($default))
 			return $default;
 	}
-	echo "<html><head></head><body>Wrong parameter used or absent: ".$name."</body></html>";
+	echo "<html><head></head><body>Wrong parameter used or absent: " . $name . "</body></html>";
 	exit;
 }
 
-function debugexit_print( $var ) {
+function debugexit_print($var)
+{
 	echo "<html><body><pre>";
-	print_r( $var );
+	print_r($var);
 	echo "</pre></body></html>";
 	exit;
 }
 
 $locale_pattern = "/^[\w-]{2,5}$/";
 
-function locale_exists($locale) {
-	return file_exists(dirname(__FILE__)."/../locales/$locale/properties");
+function locale_exists($locale)
+{
+	return file_exists(dirname(__FILE__) . "/../locales/$locale/properties");
 }
 
-function get_available_locales() {
+function get_available_locales()
+{
 	global $locale_pattern;
 	$list = array();
-	$folder = dirname(__FILE__)."/../locales";
-	if($handle = opendir($folder)) {
+	$folder = dirname(__FILE__) . "/../locales";
+	if ($handle = opendir($folder)) {
 		while (false !== ($file = readdir($handle))) {
 			if (preg_match($locale_pattern, $file) && $file != 'names' && is_dir("$folder/$file")) {
 				$list[] = $file;
@@ -94,45 +99,47 @@ function get_available_locales() {
 	return $list;
 }
 
-function get_user_locale() {
+function get_user_locale()
+{
 	global $default_locale;
 
-	if( isset($_COOKIE['webim_locale']) ) {
+	if (isset($_COOKIE['webim_locale'])) {
 		$requested_lang = $_COOKIE['webim_locale'];
-		if( locale_exists($requested_lang) )
+		if (locale_exists($requested_lang))
 			return $requested_lang;
 	}
 
-	if( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) {
-		$requested_langs = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
-		foreach( $requested_langs as $requested_lang) {
-			if( strlen($requested_lang) > 2 )
-				$requested_lang = substr($requested_lang,0,2);
+	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
+		$requested_langs = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
+		foreach ($requested_langs as $requested_lang) {
+			if (strlen($requested_lang) > 2)
+				$requested_lang = substr($requested_lang, 0, 2);
 
-			if( locale_exists($requested_lang) )
+			if (locale_exists($requested_lang))
 				return $requested_lang;
 		}
 	}
 
-	if( locale_exists($default_locale) )
+	if (locale_exists($default_locale))
 		return $default_locale;
 
 	return 'en';
 }
 
-function get_locale() {
+function get_locale()
+{
 	global $webimroot, $locale_pattern;
 
 	$locale = verifyparam("locale", $locale_pattern, "");
 
-	if( $locale && locale_exists($locale) ) {
+	if ($locale && locale_exists($locale)) {
 		$_SESSION['locale'] = $locale;
-		setcookie('webim_locale', $locale, time()+60*60*24*1000, "$webimroot/");
-	} else if( isset($_SESSION['locale']) ){
+		setcookie('webim_locale', $locale, time() + 60 * 60 * 24 * 1000, "$webimroot/");
+	} else if (isset($_SESSION['locale'])) {
 		$locale = $_SESSION['locale'];
 	}
 
-	if( !$locale || !locale_exists($locale) )
+	if (!$locale || !locale_exists($locale))
 		$locale = get_user_locale();
 	return $locale;
 }
@@ -141,42 +148,44 @@ $current_locale = get_locale();
 $messages = array();
 $output_encoding = array();
 
-if(function_exists("date_default_timezone_set")) {
+if (function_exists("date_default_timezone_set")) {
 	// TODO try to get timezone from config.php/session etc.
 	// autodetect timezone
 	@date_default_timezone_set(function_exists("date_default_timezone_get") ? @date_default_timezone_get() : "GMT");
 }
 
-function get_locale_links($href) {
+function get_locale_links($href)
+{
 	global $current_locale;
 	$localeLinks = array();
 	$allLocales = get_available_locales();
-	if(count($allLocales) < 2) {
+	if (count($allLocales) < 2) {
 		return null;
 	}
-	foreach($allLocales as $k) {
+	foreach ($allLocales as $k) {
 		$localeLinks[$k] = getlocal_($k, "names");
 	}
 	return $localeLinks;
 }
 
-function load_messages($locale) {
+function load_messages($locale)
+{
 	global $messages, $webim_encoding, $output_encoding;
 	$hash = array();
 	$current_encoding = $webim_encoding;
-	$fp = fopen(dirname(__FILE__)."/../locales/$locale/properties", "r");
+	$fp = fopen(dirname(__FILE__) . "/../locales/$locale/properties", "r");
 	while (!feof($fp)) {
 		$line = fgets($fp, 4096);
-		$keyval = preg_split("/=/", $line, 2 );
-		if( isset($keyval[1]) ) {
-			if($keyval[0] == 'encoding') {
+		$keyval = preg_split("/=/", $line, 2);
+		if (isset($keyval[1])) {
+			if ($keyval[0] == 'encoding') {
 				$current_encoding = trim($keyval[1]);
-			} else if($keyval[0] == 'output_encoding') {
+			} else if ($keyval[0] == 'output_encoding') {
 				$output_encoding[$locale] = trim($keyval[1]);
-			} else if( $current_encoding == $webim_encoding ) {
-				$hash[$keyval[0]] = str_replace("\\n", "\n",trim($keyval[1]));
+			} else if ($current_encoding == $webim_encoding) {
+				$hash[$keyval[0]] = str_replace("\\n", "\n", trim($keyval[1]));
 			} else {
-				$hash[$keyval[0]] = myiconv($current_encoding, $webim_encoding, str_replace("\\n", "\n",trim($keyval[1])));
+				$hash[$keyval[0]] = myiconv($current_encoding, $webim_encoding, str_replace("\\n", "\n", trim($keyval[1])));
 			}
 		}
 	}
@@ -184,132 +193,146 @@ function load_messages($locale) {
 	$messages[$locale] = $hash;
 }
 
-function getoutputenc() {
+function getoutputenc()
+{
 	global $current_locale, $output_encoding, $webim_encoding, $messages;
-	if(!isset($messages[$current_locale]))
+	if (!isset($messages[$current_locale]))
 		load_messages($current_locale);
 	return isset($output_encoding[$current_locale]) ? $output_encoding[$current_locale] : $webim_encoding;
 }
 
-function getstring_($text,$locale) {
+function getstring_($text, $locale)
+{
 	global $messages;
-	if(!isset($messages[$locale]))
+	if (!isset($messages[$locale]))
 		load_messages($locale);
 
 	$localized = $messages[$locale];
-	if( isset($localized[$text]) )
+	if (isset($localized[$text]))
 		return $localized[$text];
-	if( $locale != 'en' ) {
-		return getstring_($text,'en');
+	if ($locale != 'en') {
+		return getstring_($text, 'en');
 	}
 
-	return "!".$text;
+	return "!" . $text;
 }
 
-function getstring($text) {
+function getstring($text)
+{
 	global $current_locale;
-	return getstring_($text,$current_locale);
+	return getstring_($text, $current_locale);
 }
 
-function getlocal($text) {
+function getlocal($text)
+{
 	global $current_locale, $webim_encoding;
-	return myiconv($webim_encoding,getoutputenc(), getstring_($text,$current_locale));
+	return myiconv($webim_encoding, getoutputenc(), getstring_($text, $current_locale));
 }
 
-function getlocal_($text,$locale) {
+function getlocal_($text, $locale)
+{
 	global $webim_encoding;
-	return myiconv($webim_encoding,getoutputenc(), getstring_($text,$locale));
+	return myiconv($webim_encoding, getoutputenc(), getstring_($text, $locale));
 }
 
-function topage($text) {
+function topage($text)
+{
 	global $webim_encoding;
-	return myiconv($webim_encoding,getoutputenc(), $text);
+	return myiconv($webim_encoding, getoutputenc(), $text);
 }
 
-function getstring2_($text,$params,$locale) {
-	$string = getstring_($text,$locale);
-	for( $i = 0; $i < count($params); $i++ ) {
-		$string = str_replace("{".$i."}", $params[$i], $string);
+function getstring2_($text, $params, $locale)
+{
+	$string = getstring_($text, $locale);
+	for ($i = 0; $i < count($params); $i++) {
+		$string = str_replace("{" . $i . "}", $params[$i], $string);
 	}
 	return $string;
 }
 
-function getstring2($text,$params) {
+function getstring2($text, $params)
+{
 	global $current_locale;
-	return getstring2_($text,$params,$current_locale);
+	return getstring2_($text, $params, $current_locale);
 }
 
-function getlocal2($text,$params) {
+function getlocal2($text, $params)
+{
 	global $current_locale, $webim_encoding;
-	$string = myiconv($webim_encoding,getoutputenc(), getstring_($text,$current_locale));
-	for( $i = 0; $i < count($params); $i++ ) {
-		$string = str_replace("{".$i."}", $params[$i], $string);
+	$string = myiconv($webim_encoding, getoutputenc(), getstring_($text, $current_locale));
+	for ($i = 0; $i < count($params); $i++) {
+		$string = str_replace("{" . $i . "}", $params[$i], $string);
 	}
 	return $string;
 }
 
 /* prepares for Javascript string */
-function getlocalforJS($text,$params) {
+function getlocalforJS($text, $params)
+{
 	global $current_locale, $webim_encoding;
-	$string = myiconv($webim_encoding,getoutputenc(), getstring_($text,$current_locale));
-	$string = str_replace("\"", "\\\"", str_replace("\n", "\\n", $string)); 
-	for( $i = 0; $i < count($params); $i++ ) {
-		$string = str_replace("{".$i."}", $params[$i], $string);
+	$string = myiconv($webim_encoding, getoutputenc(), getstring_($text, $current_locale));
+	$string = str_replace("\"", "\\\"", str_replace("\n", "\\n", $string));
+	for ($i = 0; $i < count($params); $i++) {
+		$string = str_replace("{" . $i . "}", $params[$i], $string);
 	}
 	return $string;
 }
 
 /* ajax server actions use utf-8 */
-function getrawparam( $name ) {
+function getrawparam($name)
+{
 	global $webim_encoding;
-	if( isset($_POST[$name]) ) {
-		$value = myiconv("utf-8",$webim_encoding,$_POST[$name]);
+	if (isset($_POST[$name])) {
+		$value = myiconv("utf-8", $webim_encoding, $_POST[$name]);
 		if (get_magic_quotes_gpc()) {
 			$value = stripslashes($value);
 		}
 		return $value;
 	}
-	die("no ".$name." parameter");
+	die("no " . $name . " parameter");
 }
 
 /* form processors use current Output encoding */
-function getparam( $name ) {
+function getparam($name)
+{
 	global $webim_encoding;
-	if( isset($_POST[$name]) ) {
+	if (isset($_POST[$name])) {
 		$value = myiconv(getoutputenc(), $webim_encoding, $_POST[$name]);
 		if (get_magic_quotes_gpc()) {
 			$value = stripslashes($value);
 		}
 		return $value;
 	}
-	die("no ".$name." parameter");
+	die("no " . $name . " parameter");
 }
 
-function unicode_urldecode($url) {
-    preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);
+function unicode_urldecode($url)
+{
+	preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);
 
-    foreach ($a[1] as $uniord) {
-        $dec = hexdec($uniord);
-        $utf = '';
+	foreach ($a[1] as $uniord) {
+		$dec = hexdec($uniord);
+		$utf = '';
 
-        if ($dec < 128) {
-            $utf = chr($dec);
-        } else if ($dec < 2048) {
-            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
-            $utf .= chr(128 + ($dec % 64));
-        } else {
-            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
-            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
-            $utf .= chr(128 + ($dec % 64));
-        }
-        $url = str_replace('%u'.$uniord, $utf, $url);
-    }
-    return urldecode($url);
+		if ($dec < 128) {
+			$utf = chr($dec);
+		} else if ($dec < 2048) {
+			$utf = chr(192 + (($dec - ($dec % 64)) / 64));
+			$utf .= chr(128 + ($dec % 64));
+		} else {
+			$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
+			$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
+			$utf .= chr(128 + ($dec % 64));
+		}
+		$url = str_replace('%u' . $uniord, $utf, $url);
+	}
+	return urldecode($url);
 }
 
-function getgetparam($name,$default='') {
+function getgetparam($name, $default = '')
+{
 	global $webim_encoding;
-	if( !isset($_GET[$name]) || !$_GET[$name] ) {
+	if (!isset($_GET[$name]) || !$_GET[$name]) {
 		return $default;
 	}
 	$value = myiconv("utf-8", $webim_encoding, unicode_urldecode($_GET[$name]));
@@ -319,36 +342,40 @@ function getgetparam($name,$default='') {
 	return $value;
 }
 
-function connect() {
+function connect()
+{
 	global $mysqlhost, $mysqllogin, $mysqlpass, $mysqldb, $dbencoding, $force_charset_in_connection;
-	if(!extension_loaded("mysql")) {
+	if (!extension_loaded("mysql")) {
 		die('Mysql extension is not loaded');
 	}
-	$link = @mysql_connect($mysqlhost,$mysqllogin ,$mysqlpass )
-		or die('Could not connect: ' . mysql_error());
-	mysql_select_db($mysqldb,$link) or die('Could not select database');
-	if( $force_charset_in_connection ) {
+	$link = @mysql_connect($mysqlhost, $mysqllogin, $mysqlpass)
+			 or die('Could not connect: ' . mysql_error());
+	mysql_select_db($mysqldb, $link) or die('Could not select database');
+	if ($force_charset_in_connection) {
 		mysql_query("SET NAMES '$dbencoding'", $link);
 	}
 	return $link;
 }
 
-function perform_query($query,$link) {
-	mysql_query($query,$link)
-		or die(' Query failed: '.mysql_error($link)/*.": ".$query*/);
+function perform_query($query, $link)
+{
+	mysql_query($query, $link)
+	or die(' Query failed: ' . mysql_error($link) /*.": ".$query*/);
 }
 
-function select_one_row($query,$link) {
-	$result = mysql_query($query,$link) or die(' Query failed: ' .
-		mysql_error($link) /*.": ".$query*/);
+function select_one_row($query, $link)
+{
+	$result = mysql_query($query, $link) or die(' Query failed: ' .
+												mysql_error($link) /*.": ".$query*/);
 	$line = mysql_fetch_array($result, MYSQL_ASSOC);
 	mysql_free_result($result);
 	return $line;
 }
 
-function select_multi_assoc($query, $link) {
-	$sqlresult = mysql_query($query,$link) or die(' Query failed: ' .
-		mysql_error($link) /*.": ".$query*/);
+function select_multi_assoc($query, $link)
+{
+	$sqlresult = mysql_query($query, $link) or die(' Query failed: ' .
+												   mysql_error($link) /*.": ".$query*/);
 
 	$result = array();
 	while ($row = mysql_fetch_array($sqlresult, MYSQL_ASSOC)) {
@@ -358,21 +385,24 @@ function select_multi_assoc($query, $link) {
 	return $result;
 }
 
-function db_build_select($fields, $table, $conditions, $orderandgroup) {
-	$condition = count($conditions) > 0 ? " where ".implode(" and ", $conditions) : "";
-	if($orderandgroup) $orderandgroup = " ".$orderandgroup;
+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 = mysql_query(db_build_select("count(".($countfields ? $countfields : "*").")", $table, $conditions, ""),$link)
-			or die(' Count query failed: '.mysql_error($link));
+function db_rows_count($table, $conditions, $countfields, $link)
+{
+	$result = mysql_query(db_build_select("count(" . ($countfields ? $countfields : "*") . ")", $table, $conditions, ""), $link)
+	or die(' Count query failed: ' . mysql_error($link));
 	$line = mysql_fetch_array($result, MYSQL_NUM);
 	mysql_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("Cache-Control: no-store, no-cache, must-revalidate");
 	header("Pragma: no-cache");
@@ -380,173 +410,196 @@ function start_xml_output() {
 	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
 }
 
-function start_html_output() {
+function start_html_output()
+{
 	$charset = getstring("output_charset");
 	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 	header("Cache-Control: no-store, no-cache, must-revalidate");
 	header("Pragma: no-cache");
-	header("Content-type: text/html".(isset($charset)?"; charset=".$charset:""));
+	header("Content-type: text/html" . (isset($charset) ? "; charset=" . $charset : ""));
 }
 
-function escape_with_cdata($text) {
-	return "<![CDATA[" . str_replace("]]>", "]]>]]&gt;<![CDATA[",$text) . "]]>";
+function escape_with_cdata($text)
+{
+	return "<![CDATA[" . str_replace("]]>", "]]>]]&gt;<![CDATA[", $text) . "]]>";
 }
 
-function form_value($key) {
+function form_value($key)
+{
 	global $page;
-	if( isset($page) && isset($page["form$key"]) )
+	if (isset($page) && isset($page["form$key"]))
 		return htmlspecialchars($page["form$key"]);
 	return "";
 }
 
-function form_value_cb($key) {
+function form_value_cb($key)
+{
 	global $page;
-	if( isset($page) && isset($page["form$key"]) )
+	if (isset($page) && isset($page["form$key"]))
 		return $page["form$key"] === true;
 	return false;
 }
 
-function form_value_mb($key,$id) {
+function form_value_mb($key, $id)
+{
 	global $page;
-	if( isset($page) && isset($page["form$key"]) && is_array($page["form$key"]) ) {
+	if (isset($page) && isset($page["form$key"]) && is_array($page["form$key"])) {
 		return in_array($id, $page["form$key"]);
 	}
 	return false;
 }
 
-function no_field($key) {
-	return getlocal2("errors.required",array(getlocal($key)));
+function no_field($key)
+{
+	return getlocal2("errors.required", array(getlocal($key)));
 }
 
-function failed_uploading_file($filename, $key) {
+function failed_uploading_file($filename, $key)
+{
 	return getlocal2("errors.failed.uploading.file",
-					  array($filename, getlocal($key)));
+					 array($filename, getlocal($key)));
 }
 
-function wrong_field($key) {
-	return getlocal2("errors.wrong_field",array(getlocal($key)));
+function wrong_field($key)
+{
+	return getlocal2("errors.wrong_field", array(getlocal($key)));
 }
 
-function get_popup($href,$jshref,$message,$title,$wndName,$options) {
-	if(!$jshref) { $jshref = "'$href'"; }
-	return "<a href=\"$href\" target=\"_blank\" ".($title?"title=\"$title\" ":"")."onclick=\"if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open($jshref, '$wndName', '$options');this.newWindow.focus();this.newWindow.opener=window;return false;\">$message</a>";
+function get_popup($href, $jshref, $message, $title, $wndName, $options)
+{
+	if (!$jshref) {
+		$jshref = "'$href'";
+	}
+	return "<a href=\"$href\" target=\"_blank\" " . ($title ? "title=\"$title\" " : "") . "onclick=\"if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open($jshref, '$wndName', '$options');this.newWindow.focus();this.newWindow.opener=window;return false;\">$message</a>";
 }
 
-function get_image($href,$width,$height) {
-	if( $width != 0 && $height != 0 )
+function get_image($href, $width, $height)
+{
+	if ($width != 0 && $height != 0)
 		return "<img src=\"$href\" border=\"0\" width=\"$width\" height=\"$height\" alt=\"\"/>";
 	return "<img src=\"$href\" border=\"0\" alt=\"\"/>";
 }
 
-function get_gifimage_size($filename) {
-	if( function_exists('gd_info')) {
+function get_gifimage_size($filename)
+{
+	if (function_exists('gd_info')) {
 		$info = gd_info();
-		if( isset($info['GIF Read Support']) && $info['GIF Read Support'] ) {
+		if (isset($info['GIF Read Support']) && $info['GIF Read Support']) {
 			$img = @imagecreatefromgif($filename);
-			if($img) {
+			if ($img) {
 				$height = imagesy($img);
 				$width = imagesx($img);
 				imagedestroy($img);
-				return array($width,$height);
+				return array($width, $height);
 			}
 		}
 	}
-	return array(0,0);
+	return array(0, 0);
 }
 
-function add_params($servlet, $params) {
+function add_params($servlet, $params)
+{
 	$infix = '?';
-	if( strstr($servlet,$infix) !== FALSE )
+	if (strstr($servlet, $infix) !== FALSE)
 		$infix = '&amp;';
-	foreach($params as $k => $v) {
-		$servlet .= $infix.$k."=".$v;
+	foreach ($params as $k => $v) {
+		$servlet .= $infix . $k . "=" . $v;
 		$infix = '&amp;';
 	}
 	return $servlet;
 }
 
-function div($a,$b) {
-	return ($a-($a % $b)) / $b;
+function div($a, $b)
+{
+	return ($a - ($a % $b)) / $b;
 }
 
-function date_diff_to_text($seconds) {
-	$minutes = div($seconds,60);
+function date_diff_to_text($seconds)
+{
+	$minutes = div($seconds, 60);
 	$seconds = $seconds % 60;
-	if( $minutes < 60 ) {
-		return sprintf("%02d:%02d",$minutes, $seconds);
+	if ($minutes < 60) {
+		return sprintf("%02d:%02d", $minutes, $seconds);
 	} else {
-		$hours = div($minutes,60);
+		$hours = div($minutes, 60);
 		$minutes = $minutes % 60;
-		return sprintf("%02d:%02d:%02d",$hours, $minutes, $seconds);
+		return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
 	}
 }
 
-function is_valid_email($email) {
+function is_valid_email($email)
+{
 	return preg_match("/^[^@]+@[^\.]+(\.[^\.]+)*$/", $email);
 }
 
-function get_app_location($showhost,$issecure) {
+function get_app_location($showhost, $issecure)
+{
 	global $webimroot;
-	if( $showhost ) {
-		return ($issecure?"https://":"http://").$_SERVER['HTTP_HOST'].$webimroot;
+	if ($showhost) {
+		return ($issecure ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . $webimroot;
 	} else {
 		return $webimroot;
 	}
 }
 
-function is_secure_request() {
+function is_secure_request()
+{
 	return
-		   isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443'
-		|| isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on"
-		|| isset($_SERVER["HTTP_HTTPS"]) && $_SERVER["HTTP_HTTPS"] == "on";
+			isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443'
+			|| isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on"
+			|| isset($_SERVER["HTTP_HTTPS"]) && $_SERVER["HTTP_HTTPS"] == "on";
 }
 
-function get_month_selection($fromtime,$totime) {
+function get_month_selection($fromtime, $totime)
+{
 	$start = getdate($fromtime);
 	$month = $start['mon'];
 	$year = $start['year'];
 	$result = array();
 	do {
-		$current = mktime(0,0,0,$month,1,$year);
-		$result[date("m.y",$current)] = strftime("%B, %Y",$current);
+		$current = mktime(0, 0, 0, $month, 1, $year);
+		$result[date("m.y", $current)] = strftime("%B, %Y", $current);
 		$month++;
-		if( $month > 12 ) {
+		if ($month > 12) {
 			$month = 1;
 			$year++;
 		}
-	} while( $current < $totime );
+	} while ($current < $totime);
 	return $result;
 }
 
-function get_form_date($day,$month) {
-	if( preg_match('/^(\d{2}).(\d{2})$/', $month, $matches)) {
-		return mktime(0,0,0,$matches[1],$day,$matches[2]);
+function get_form_date($day, $month)
+{
+	if (preg_match('/^(\d{2}).(\d{2})$/', $month, $matches)) {
+		return mktime(0, 0, 0, $matches[1], $day, $matches[2]);
 	}
 	return 0;
 }
 
-function set_form_date($utime,$prefix) {
+function set_form_date($utime, $prefix)
+{
 	global $page;
 	$page["form${prefix}day"] = date("d", $utime);
 	$page["form${prefix}month"] = date("m.y", $utime);
 }
 
-function date_to_text($unixtime) {
-	if ($unixtime < 60*60*24*30)
+function date_to_text($unixtime)
+{
+	if ($unixtime < 60 * 60 * 24 * 30)
 		return getlocal("time.never");
-		
+
 	$then = getdate($unixtime);
 	$now = getdate();
 
 	if ($then['yday'] == $now['yday'] && $then['year'] == $now['year']) {
 		$date_format = getlocal("time.today.at");
-	} else if (($then['yday']+1) == $now['yday'] && $then['year'] == $now['year']) {
+	} else if (($then['yday'] + 1) == $now['yday'] && $then['year'] == $now['year']) {
 		$date_format = getlocal("time.yesterday.at");
 	} else {
 		$date_format = getlocal("time.dateformat");
 	}
-	
-	return strftime($date_format." ".getlocal("time.timeformat"), $unixtime);
+
+	return strftime($date_format . " " . getlocal("time.timeformat"), $unixtime);
 }
 
 $dbversion = '1.6.3';
@@ -566,25 +619,25 @@ $settings = array(
 	'max_uploaded_file_size' => 100000,
 	'max_connections_from_one_host' => 10,
 
-	'email' => '',				/* inbox for left messages */
+	'email' => '', /* inbox for left messages */
 	'left_messages_locale' => $home_locale,
 	'sendmessagekey' => 'center',
 
 	'enableban' => '0',
 	'enablessl' => '0',
-		'forcessl' => '0',
+	'forcessl' => '0',
 	'usercanchangename' => '1',
 	'enablegroups' => '0',
 	'enablestatistics' => '1',
 	'enablepresurvey' => '1',
-		'surveyaskmail' => '0',
-		'surveyaskgroup' => '1',
-		'surveyaskmessage' => '0',
+	'surveyaskmail' => '0',
+	'surveyaskgroup' => '1',
+	'surveyaskmessage' => '0',
 	'enablepopupnotification' => '0',
 	'showonlineoperators' => '0',
 	'enablecaptcha' => '0',
 
-	'online_timeout' => 30,		/* Timeout (in seconds) when online operator becomes offline */
+	'online_timeout' => 30, /* Timeout (in seconds) when online operator becomes offline */
 	'updatefrequency_operator' => 2,
 	'updatefrequency_chat' => 2,
 	'updatefrequency_oldchat' => 7,
@@ -592,14 +645,15 @@ $settings = array(
 $settingsloaded = false;
 $settings_in_db = array();
 
-function loadsettings_($link) {
+function loadsettings_($link)
+{
 	global $settingsloaded, $settings_in_db, $settings, $mysqlprefix;
-	if($settingsloaded) {
+	if ($settingsloaded) {
 		return;
 	}
 	$settingsloaded = true;
 
-	$sqlresult = mysql_query("select vckey,vcvalue from ${mysqlprefix}chatconfig", $link) or die(' Query failed: '.mysql_error($link));
+	$sqlresult = mysql_query("select vckey,vcvalue from ${mysqlprefix}chatconfig", $link) or die(' Query failed: ' . mysql_error($link));
 
 	while ($row = mysql_fetch_array($sqlresult, MYSQL_ASSOC)) {
 		$name = $row['vckey'];
@@ -609,28 +663,31 @@ function loadsettings_($link) {
 	mysql_free_result($sqlresult);
 }
 
-function loadsettings() {
+function loadsettings()
+{
 	global $settingsloaded;
-	if(!$settingsloaded) {
+	if (!$settingsloaded) {
 		$link = connect();
 		loadsettings_($link);
-	    mysql_close($link);
-    }
+		mysql_close($link);
+	}
 }
 
-function getchatstyle() {
+function getchatstyle()
+{
 	global $settings;
-	$chatstyle = verifyparam( "style", "/^\w+$/", "");
-	if($chatstyle) {
+	$chatstyle = verifyparam("style", "/^\w+$/", "");
+	if ($chatstyle) {
 		return $chatstyle;
 	}
 	loadsettings();
 	return $settings['chatstyle'];
 }
 
-function jspath() {
+function jspath()
+{
 	global $jsver;
-	return "js/$jsver";	
+	return "js/$jsver";
 }
 
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/config.php b/src/messenger/webim/libs/config.php
index fbeca687..6d541b4e 100644
--- a/src/messenger/webim/libs/config.php
+++ b/src/messenger/webim/libs/config.php
@@ -50,7 +50,7 @@ $mail_encoding = "utf-8";
 /*
  *  Locales
  */
-$home_locale = "en";						/* native name will be used in this locale */
-$default_locale = "en";						/* if user does not provide known lang */
+$home_locale = "en"; /* native name will be used in this locale */
+$default_locale = "en"; /* if user does not provide known lang */
 
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/converter.php b/src/messenger/webim/libs/converter.php
index a7ea04d5..02e5a2e2 100644
--- a/src/messenger/webim/libs/converter.php
+++ b/src/messenger/webim/libs/converter.php
@@ -20,36 +20,36 @@
  */
 
 $_utf8win1251 = array(
-"\xD0\x90"=>"\xC0","\xD0\x91"=>"\xC1","\xD0\x92"=>"\xC2","\xD0\x93"=>"\xC3","\xD0\x94"=>"\xC4",
-"\xD0\x95"=>"\xC5","\xD0\x81"=>"\xA8","\xD0\x96"=>"\xC6","\xD0\x97"=>"\xC7","\xD0\x98"=>"\xC8",
-"\xD0\x99"=>"\xC9","\xD0\x9A"=>"\xCA","\xD0\x9B"=>"\xCB","\xD0\x9C"=>"\xCC","\xD0\x9D"=>"\xCD",
-"\xD0\x9E"=>"\xCE","\xD0\x9F"=>"\xCF","\xD0\xA0"=>"\xD0","\xD0\xA1"=>"\xD1","\xD0\xA2"=>"\xD2",
-"\xD0\xA3"=>"\xD3","\xD0\xA4"=>"\xD4","\xD0\xA5"=>"\xD5","\xD0\xA6"=>"\xD6","\xD0\xA7"=>"\xD7",
-"\xD0\xA8"=>"\xD8","\xD0\xA9"=>"\xD9","\xD0\xAA"=>"\xDA","\xD0\xAB"=>"\xDB","\xD0\xAC"=>"\xDC",
-"\xD0\xAD"=>"\xDD","\xD0\xAE"=>"\xDE","\xD0\xAF"=>"\xDF","\xD0\x87"=>"\xAF","\xD0\x86"=>"\xB2",
-"\xD0\x84"=>"\xAA","\xD0\x8E"=>"\xA1","\xD0\xB0"=>"\xE0","\xD0\xB1"=>"\xE1","\xD0\xB2"=>"\xE2",
-"\xD0\xB3"=>"\xE3","\xD0\xB4"=>"\xE4","\xD0\xB5"=>"\xE5","\xD1\x91"=>"\xB8","\xD0\xB6"=>"\xE6",
-"\xD0\xB7"=>"\xE7","\xD0\xB8"=>"\xE8","\xD0\xB9"=>"\xE9","\xD0\xBA"=>"\xEA","\xD0\xBB"=>"\xEB",
-"\xD0\xBC"=>"\xEC","\xD0\xBD"=>"\xED","\xD0\xBE"=>"\xEE","\xD0\xBF"=>"\xEF","\xD1\x80"=>"\xF0",
-"\xD1\x81"=>"\xF1","\xD1\x82"=>"\xF2","\xD1\x83"=>"\xF3","\xD1\x84"=>"\xF4","\xD1\x85"=>"\xF5",
-"\xD1\x86"=>"\xF6","\xD1\x87"=>"\xF7","\xD1\x88"=>"\xF8","\xD1\x89"=>"\xF9","\xD1\x8A"=>"\xFA",
-"\xD1\x8B"=>"\xFB","\xD1\x8C"=>"\xFC","\xD1\x8D"=>"\xFD","\xD1\x8E"=>"\xFE","\xD1\x8F"=>"\xFF",
-"\xD1\x96"=>"\xB3","\xD1\x97"=>"\xBF","\xD1\x94"=>"\xBA","\xD1\x9E"=>"\xA2");
+	"\xD0\x90" => "\xC0", "\xD0\x91" => "\xC1", "\xD0\x92" => "\xC2", "\xD0\x93" => "\xC3", "\xD0\x94" => "\xC4",
+	"\xD0\x95" => "\xC5", "\xD0\x81" => "\xA8", "\xD0\x96" => "\xC6", "\xD0\x97" => "\xC7", "\xD0\x98" => "\xC8",
+	"\xD0\x99" => "\xC9", "\xD0\x9A" => "\xCA", "\xD0\x9B" => "\xCB", "\xD0\x9C" => "\xCC", "\xD0\x9D" => "\xCD",
+	"\xD0\x9E" => "\xCE", "\xD0\x9F" => "\xCF", "\xD0\xA0" => "\xD0", "\xD0\xA1" => "\xD1", "\xD0\xA2" => "\xD2",
+	"\xD0\xA3" => "\xD3", "\xD0\xA4" => "\xD4", "\xD0\xA5" => "\xD5", "\xD0\xA6" => "\xD6", "\xD0\xA7" => "\xD7",
+	"\xD0\xA8" => "\xD8", "\xD0\xA9" => "\xD9", "\xD0\xAA" => "\xDA", "\xD0\xAB" => "\xDB", "\xD0\xAC" => "\xDC",
+	"\xD0\xAD" => "\xDD", "\xD0\xAE" => "\xDE", "\xD0\xAF" => "\xDF", "\xD0\x87" => "\xAF", "\xD0\x86" => "\xB2",
+	"\xD0\x84" => "\xAA", "\xD0\x8E" => "\xA1", "\xD0\xB0" => "\xE0", "\xD0\xB1" => "\xE1", "\xD0\xB2" => "\xE2",
+	"\xD0\xB3" => "\xE3", "\xD0\xB4" => "\xE4", "\xD0\xB5" => "\xE5", "\xD1\x91" => "\xB8", "\xD0\xB6" => "\xE6",
+	"\xD0\xB7" => "\xE7", "\xD0\xB8" => "\xE8", "\xD0\xB9" => "\xE9", "\xD0\xBA" => "\xEA", "\xD0\xBB" => "\xEB",
+	"\xD0\xBC" => "\xEC", "\xD0\xBD" => "\xED", "\xD0\xBE" => "\xEE", "\xD0\xBF" => "\xEF", "\xD1\x80" => "\xF0",
+	"\xD1\x81" => "\xF1", "\xD1\x82" => "\xF2", "\xD1\x83" => "\xF3", "\xD1\x84" => "\xF4", "\xD1\x85" => "\xF5",
+	"\xD1\x86" => "\xF6", "\xD1\x87" => "\xF7", "\xD1\x88" => "\xF8", "\xD1\x89" => "\xF9", "\xD1\x8A" => "\xFA",
+	"\xD1\x8B" => "\xFB", "\xD1\x8C" => "\xFC", "\xD1\x8D" => "\xFD", "\xD1\x8E" => "\xFE", "\xD1\x8F" => "\xFF",
+	"\xD1\x96" => "\xB3", "\xD1\x97" => "\xBF", "\xD1\x94" => "\xBA", "\xD1\x9E" => "\xA2");
 $_win1251utf8 = array(
-"\xC0"=>"\xD0\x90","\xC1"=>"\xD0\x91","\xC2"=>"\xD0\x92","\xC3"=>"\xD0\x93","\xC4"=>"\xD0\x94",
-"\xC5"=>"\xD0\x95","\xA8"=>"\xD0\x81","\xC6"=>"\xD0\x96","\xC7"=>"\xD0\x97","\xC8"=>"\xD0\x98",
-"\xC9"=>"\xD0\x99","\xCA"=>"\xD0\x9A","\xCB"=>"\xD0\x9B","\xCC"=>"\xD0\x9C","\xCD"=>"\xD0\x9D",
-"\xCE"=>"\xD0\x9E","\xCF"=>"\xD0\x9F","\xD0"=>"\xD0\xA0","\xD1"=>"\xD0\xA1","\xD2"=>"\xD0\xA2",
-"\xD3"=>"\xD0\xA3","\xD4"=>"\xD0\xA4","\xD5"=>"\xD0\xA5","\xD6"=>"\xD0\xA6","\xD7"=>"\xD0\xA7",
-"\xD8"=>"\xD0\xA8","\xD9"=>"\xD0\xA9","\xDA"=>"\xD0\xAA","\xDB"=>"\xD0\xAB","\xDC"=>"\xD0\xAC",
-"\xDD"=>"\xD0\xAD","\xDE"=>"\xD0\xAE","\xDF"=>"\xD0\xAF","\xAF"=>"\xD0\x87","\xB2"=>"\xD0\x86",
-"\xAA"=>"\xD0\x84","\xA1"=>"\xD0\x8E","\xE0"=>"\xD0\xB0","\xE1"=>"\xD0\xB1","\xE2"=>"\xD0\xB2",
-"\xE3"=>"\xD0\xB3","\xE4"=>"\xD0\xB4","\xE5"=>"\xD0\xB5","\xB8"=>"\xD1\x91","\xE6"=>"\xD0\xB6",
-"\xE7"=>"\xD0\xB7","\xE8"=>"\xD0\xB8","\xE9"=>"\xD0\xB9","\xEA"=>"\xD0\xBA","\xEB"=>"\xD0\xBB",
-"\xEC"=>"\xD0\xBC","\xED"=>"\xD0\xBD","\xEE"=>"\xD0\xBE","\xEF"=>"\xD0\xBF","\xF0"=>"\xD1\x80",
-"\xF1"=>"\xD1\x81","\xF2"=>"\xD1\x82","\xF3"=>"\xD1\x83","\xF4"=>"\xD1\x84","\xF5"=>"\xD1\x85",
-"\xF6"=>"\xD1\x86","\xF7"=>"\xD1\x87","\xF8"=>"\xD1\x88","\xF9"=>"\xD1\x89","\xFA"=>"\xD1\x8A",
-"\xFB"=>"\xD1\x8B","\xFC"=>"\xD1\x8C","\xFD"=>"\xD1\x8D","\xFE"=>"\xD1\x8E","\xFF"=>"\xD1\x8F",
-"\xB3"=>"\xD1\x96","\xBF"=>"\xD1\x97","\xBA"=>"\xD1\x94","\xA2"=>"\xD1\x9E");
+	"\xC0" => "\xD0\x90", "\xC1" => "\xD0\x91", "\xC2" => "\xD0\x92", "\xC3" => "\xD0\x93", "\xC4" => "\xD0\x94",
+	"\xC5" => "\xD0\x95", "\xA8" => "\xD0\x81", "\xC6" => "\xD0\x96", "\xC7" => "\xD0\x97", "\xC8" => "\xD0\x98",
+	"\xC9" => "\xD0\x99", "\xCA" => "\xD0\x9A", "\xCB" => "\xD0\x9B", "\xCC" => "\xD0\x9C", "\xCD" => "\xD0\x9D",
+	"\xCE" => "\xD0\x9E", "\xCF" => "\xD0\x9F", "\xD0" => "\xD0\xA0", "\xD1" => "\xD0\xA1", "\xD2" => "\xD0\xA2",
+	"\xD3" => "\xD0\xA3", "\xD4" => "\xD0\xA4", "\xD5" => "\xD0\xA5", "\xD6" => "\xD0\xA6", "\xD7" => "\xD0\xA7",
+	"\xD8" => "\xD0\xA8", "\xD9" => "\xD0\xA9", "\xDA" => "\xD0\xAA", "\xDB" => "\xD0\xAB", "\xDC" => "\xD0\xAC",
+	"\xDD" => "\xD0\xAD", "\xDE" => "\xD0\xAE", "\xDF" => "\xD0\xAF", "\xAF" => "\xD0\x87", "\xB2" => "\xD0\x86",
+	"\xAA" => "\xD0\x84", "\xA1" => "\xD0\x8E", "\xE0" => "\xD0\xB0", "\xE1" => "\xD0\xB1", "\xE2" => "\xD0\xB2",
+	"\xE3" => "\xD0\xB3", "\xE4" => "\xD0\xB4", "\xE5" => "\xD0\xB5", "\xB8" => "\xD1\x91", "\xE6" => "\xD0\xB6",
+	"\xE7" => "\xD0\xB7", "\xE8" => "\xD0\xB8", "\xE9" => "\xD0\xB9", "\xEA" => "\xD0\xBA", "\xEB" => "\xD0\xBB",
+	"\xEC" => "\xD0\xBC", "\xED" => "\xD0\xBD", "\xEE" => "\xD0\xBE", "\xEF" => "\xD0\xBF", "\xF0" => "\xD1\x80",
+	"\xF1" => "\xD1\x81", "\xF2" => "\xD1\x82", "\xF3" => "\xD1\x83", "\xF4" => "\xD1\x84", "\xF5" => "\xD1\x85",
+	"\xF6" => "\xD1\x86", "\xF7" => "\xD1\x87", "\xF8" => "\xD1\x88", "\xF9" => "\xD1\x89", "\xFA" => "\xD1\x8A",
+	"\xFB" => "\xD1\x8B", "\xFC" => "\xD1\x8C", "\xFD" => "\xD1\x8D", "\xFE" => "\xD1\x8E", "\xFF" => "\xD1\x8F",
+	"\xB3" => "\xD1\x96", "\xBF" => "\xD1\x97", "\xBA" => "\xD1\x94", "\xA2" => "\xD1\x9E");
 
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/demothread.php b/src/messenger/webim/libs/demothread.php
index aca5a73a..b795a787 100644
--- a/src/messenger/webim/libs/demothread.php
+++ b/src/messenger/webim/libs/demothread.php
@@ -19,72 +19,74 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function demo_print_message($msg,$format) {
+function demo_print_message($msg, $format)
+{
 	global $webim_encoding;
-	if($format == "xml") {
-		print "<message>".myiconv($webim_encoding,"utf-8",escape_with_cdata(message_to_html($msg)))."</message>\n";
+	if ($format == "xml") {
+		print "<message>" . myiconv($webim_encoding, "utf-8", escape_with_cdata(message_to_html($msg))) . "</message>\n";
 	} else {
 		print topage(message_to_html($msg));
 	}
 }
 
-function demo_process_thread($act,$outformat,$lastid,$isuser,$canpost,$istyping,$postmessage) {
+function demo_process_thread($act, $outformat, $lastid, $isuser, $canpost, $istyping, $postmessage)
+{
 	global $kind_for_agent, $kind_info, $kind_events, $kind_user, $kind_agent, $webimroot, $settings;
 	loadsettings();
-	if( $act == "refresh" || $act == "post" ) {
+	if ($act == "refresh" || $act == "post") {
 		$lastid++;
-		if($outformat == "xml") {
+		if ($outformat == "xml") {
 			start_xml_output();
-			print("<thread lastid=\"$lastid\" typing=\"".($istyping ? 1 : 0)."\" canpost=\"".($canpost ? 1 : 0)."\">");
+			print("<thread lastid=\"$lastid\" typing=\"" . ($istyping ? 1 : 0) . "\" canpost=\"" . ($canpost ? 1 : 0) . "\">");
 		} else {
 			start_html_output();
-			$url = "$webimroot/thread.php?act=refresh&amp;thread=0&amp;token=123&amp;html=on&amp;user=".($isuser?"true":"false");
-			
+			$url = "$webimroot/thread.php?act=refresh&amp;thread=0&amp;token=123&amp;html=on&amp;user=" . ($isuser ? "true" : "false");
+
 			print(
-				"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">".
-				"<html>\n<head>\n".
-				"<link href=\"$webimroot/styles/default/chat.css\" rel=\"stylesheet\" type=\"text/css\">\n".
-				"<meta http-equiv=\"Refresh\" content=\"".$settings['updatefrequency_oldchat']."; URL=$url&amp;sn=11\">\n".
-				"<meta http-equiv=\"Pragma\" content=\"no-cache\">\n".
-				"<title>chat</title>\n".
-				"</head>\n".
-				"<body bgcolor='#FFFFFF' text='#000000' link='#C28400' vlink='#C28400' alink='#C28400'>".
-				"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr><td valign='top' class='message'>" );
-			
+					"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" .
+					"<html>\n<head>\n" .
+					"<link href=\"$webimroot/styles/default/chat.css\" rel=\"stylesheet\" type=\"text/css\">\n" .
+					"<meta http-equiv=\"Refresh\" content=\"" . $settings['updatefrequency_oldchat'] . "; URL=$url&amp;sn=11\">\n" .
+					"<meta http-equiv=\"Pragma\" content=\"no-cache\">\n" .
+					"<title>chat</title>\n" .
+					"</head>\n" .
+					"<body bgcolor='#FFFFFF' text='#000000' link='#C28400' vlink='#C28400' alink='#C28400'>" .
+					"<table width='100%' cellspacing='0' cellpadding='0' border='0'><tr><td valign='top' class='message'>");
+
 		}
-		if($lastid == 1) {
+		if ($lastid == 1) {
 			demo_print_message(
-				array('ikind'=>$kind_for_agent,'created'=>time()-15,'tname'=>'',
-					  'tmessage'=>getstring2('chat.came.from',array("http://google.com"))), $outformat);
+				array('ikind' => $kind_for_agent, 'created' => time() - 15, 'tname' => '',
+					 'tmessage' => getstring2('chat.came.from', array("http://google.com"))), $outformat);
 			demo_print_message(
-				array('ikind'=>$kind_info,'created'=>time()-15,'tname'=>'',
-					  'tmessage'=>getstring('chat.wait')), $outformat);
+				array('ikind' => $kind_info, 'created' => time() - 15, 'tname' => '',
+					 'tmessage' => getstring('chat.wait')), $outformat);
 			demo_print_message(
-				array('ikind'=>$kind_events,'created'=>time()-10,'tname'=>'',
-					  'tmessage'=>getstring2("chat.status.operator.joined", array("Administrator"))), $outformat);
+				array('ikind' => $kind_events, 'created' => time() - 10, 'tname' => '',
+					 'tmessage' => getstring2("chat.status.operator.joined", array("Administrator"))), $outformat);
 			demo_print_message(
-				array('ikind'=>$kind_agent,'created'=>time()-9,'tname'=>'Administrator',
-					  'tmessage'=>getstring("demo.chat.welcome")), $outformat);
+				array('ikind' => $kind_agent, 'created' => time() - 9, 'tname' => 'Administrator',
+					 'tmessage' => getstring("demo.chat.welcome")), $outformat);
 			demo_print_message(
-				array('ikind'=>$kind_user,'created'=>time()-5,'tname'=>getstring("chat.default.username"),
-					  'tmessage'=>getstring("demo.chat.question")), $outformat);
-			if($canpost && $outformat == 'xml') {
+				array('ikind' => $kind_user, 'created' => time() - 5, 'tname' => getstring("chat.default.username"),
+					 'tmessage' => getstring("demo.chat.question")), $outformat);
+			if ($canpost && $outformat == 'xml') {
 				demo_print_message(
-					array('ikind'=>$kind_info,'created'=>time()-5,'tname'=>'',
-						  'tmessage'=>'Hint: type something in message field to see typing notification'), $outformat);
+					array('ikind' => $kind_info, 'created' => time() - 5, 'tname' => '',
+						 'tmessage' => 'Hint: type something in message field to see typing notification'), $outformat);
 			}
 		}
-		if($act == 'post') {
+		if ($act == 'post') {
 			demo_print_message(
-				array('ikind'=>$isuser?$kind_user:$kind_agent,'created'=>time(),'tmessage'=>$postmessage,
-					  'tname'=>$isuser?getstring("chat.default.username"):"Administrator"), $outformat);
+				array('ikind' => $isuser ? $kind_user : $kind_agent, 'created' => time(), 'tmessage' => $postmessage,
+					 'tname' => $isuser ? getstring("chat.default.username") : "Administrator"), $outformat);
 		}
-		if($outformat == "xml") {
+		if ($outformat == "xml") {
 			print("</thread>");
 		} else {
 			print(
-				"</td></tr></table><a name='aend'></a>".
-				"</body></html>" );
+					"</td></tr></table><a name='aend'></a>" .
+					"</body></html>");
 		}
 	}
 }
diff --git a/src/messenger/webim/libs/expand.php b/src/messenger/webim/libs/expand.php
index dbd918ef..c82c407d 100644
--- a/src/messenger/webim/libs/expand.php
+++ b/src/messenger/webim/libs/expand.php
@@ -23,97 +23,103 @@ $ifregexp = "/\\\${(if|ifnot):([\w\.]+)}(.*?)(\\\${else:\\2}.*?)?\\\${endif:\\2}
 $expand_include_path = "";
 $current_style = "";
 
-function check_condition($condition) {
+function check_condition($condition)
+{
 	global $errors, $page;
-	if($condition == 'errors') {
+	if ($condition == 'errors') {
 		return isset($errors) && count($errors) > 0;
 	}
 	return isset($page[$condition]) && $page[$condition];
 }
 
-function expand_condition($matches) {
+function expand_condition($matches)
+{
 	global $page, $ifregexp;
 	$value = check_condition($matches[2]) ^ ($matches[1] != 'if');
-	if($value) {
+	if ($value) {
 		return preg_replace_callback($ifregexp, "expand_condition", $matches[3]);
-	} else if(isset($matches[4])) {
-		return preg_replace_callback($ifregexp, "expand_condition", substr($matches[4],strpos($matches[4],"}")+1));
+	} else if (isset($matches[4])) {
+		return preg_replace_callback($ifregexp, "expand_condition", substr($matches[4], strpos($matches[4], "}") + 1));
 	}
 	return "";
 }
 
-function expand_var($matches) {
+function expand_var($matches)
+{
 	global $page, $webimroot, $jsver, $errors, $current_style;
 	$prefix = $matches[1];
 	$var = $matches[2];
-	if(!$prefix) {
-		if($var == 'webimroot') {
+	if (!$prefix) {
+		if ($var == 'webimroot') {
 			return $webimroot;
-		} else if($var == 'jsver') {
+		} else if ($var == 'jsver') {
 			return $jsver;
-		} else if($var == 'tplroot') {
+		} else if ($var == 'tplroot') {
 			return "$webimroot/styles/$current_style";
-		} else if($var == 'styleid') {
+		} else if ($var == 'styleid') {
 			return $current_style;
-		} else if($var == 'pagination') {
+		} else if ($var == 'pagination') {
 			return generate_pagination($page['pagination']);
-		} else if($var == 'errors' || $var == 'harderrors') {
-			if( isset($errors) && count($errors) > 0 ) {
+		} else if ($var == 'errors' || $var == 'harderrors') {
+			if (isset($errors) && count($errors) > 0) {
 				$result = getlocal("$var.header");
-				foreach( $errors as $e ) {
-					$result .= getlocal("errors.prefix").$e.getlocal("errors.suffix");
+				foreach ($errors as $e) {
+					$result .= getlocal("errors.prefix") . $e . getlocal("errors.suffix");
 				}
 				$result .= getlocal("errors.footer");
 				return $result;
 			}
 		}
 
-	} else if($prefix == 'msg:' || $prefix == 'url:') {
-		if(strpos($var,",")!==false) {
-			$pos = strpos($var,",");
-			$param = substr($var, $pos+1);
+	} else if ($prefix == 'msg:' || $prefix == 'url:') {
+		if (strpos($var, ",") !== false) {
+			$pos = strpos($var, ",");
+			$param = substr($var, $pos + 1);
 			$var = substr($var, 0, $pos);
 			return getlocal2($var, array($page[$param]));
 		}
 		return getlocal($var);
-	} else if($prefix == 'form:') {
+	} else if ($prefix == 'form:') {
 		return form_value($var);
-	} else if($prefix == 'page:') {
+	} else if ($prefix == 'page:') {
 		return isset($page[$var]) ? $page[$var] : "";
-	} else if($prefix == 'if:' || $prefix == 'else:' || $prefix == 'endif:' || $prefix == 'ifnot:') {
+	} else if ($prefix == 'if:' || $prefix == 'else:' || $prefix == 'endif:' || $prefix == 'ifnot:') {
 		return "<!-- wrong $prefix:$var -->";
 	}
 
 	return "";
 }
 
-function expand_include($matches) {
+function expand_include($matches)
+{
 	global $expand_include_path;
 	$name = $matches[1];
-	$contents = @file_get_contents($expand_include_path.$name) or die("cannot load template");
+	$contents = @file_get_contents($expand_include_path . $name) or die("cannot load template");
 	return $contents;
 }
 
-function expandtext($text) {
+function expandtext($text)
+{
 	global $ifregexp;
 	$text = preg_replace_callback("/\\\${include:([\w\.]+)}/", "expand_include", $text);
 	$text = preg_replace_callback($ifregexp, "expand_condition", $text);
 	return preg_replace_callback("/\\\${(\w+:)?([\w\.,]+)}/", "expand_var", $text);
 }
 
-function expand($basedir,$style,$filename) {
+function expand($basedir, $style, $filename)
+{
 	global $expand_include_path, $current_style;
 	start_html_output();
-	if(!is_dir("$basedir/$style")) {
+	if (!is_dir("$basedir/$style")) {
 		$style = "default";
 	}
 	$expand_include_path = "$basedir/$style/templates/";
 	$current_style = $style;
-	$contents = @file_get_contents($expand_include_path.$filename);
-	if($contents === false) {
+	$contents = @file_get_contents($expand_include_path . $filename);
+	if ($contents === false) {
 		$expand_include_path = "$basedir/default/templates/";
 		$current_style = "default";
-		$contents = @file_get_contents($expand_include_path.$filename) or die("cannot load template");
+		$contents = @file_get_contents($expand_include_path . $filename) or die("cannot load template");
 	}
 	echo expandtext($contents);
 }
diff --git a/src/messenger/webim/libs/groups.php b/src/messenger/webim/libs/groups.php
index 6f2edf3a..27beb5fe 100644
--- a/src/messenger/webim/libs/groups.php
+++ b/src/messenger/webim/libs/groups.php
@@ -19,26 +19,29 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function group_by_id($id) {
-    global $mysqlprefix;
+function group_by_id($id)
+{
+	global $mysqlprefix;
 	$link = connect();
 	$group = select_one_row(
-		 "select * from ${mysqlprefix}chatgroup where groupid = $id", $link );
+		"select * from ${mysqlprefix}chatgroup where groupid = $id", $link);
 	mysql_close($link);
 	return $group;
 }
 
-function get_group_name($group) {
+function get_group_name($group)
+{
 	global $home_locale, $current_locale;
-	if( $home_locale == $current_locale || !isset($group['vccommonname']) || !$group['vccommonname'])
+	if ($home_locale == $current_locale || !isset($group['vccommonname']) || !$group['vccommonname'])
 		return $group['vclocalname'];
 	else
 		return $group['vccommonname'];
 }
 
-function setup_group_settings_tabs($gid, $active) {
+function setup_group_settings_tabs($gid, $active)
+{
 	global $page, $webimroot, $settings;
-	if($gid) {
+	if ($gid) {
 		$page['tabs'] = array(
 			getlocal("page_group.tab.main") => $active != 0 ? "$webimroot/operator/group.php?gid=$gid" : "",
 			getlocal("page_group.tab.members") => $active != 1 ? "$webimroot/operator/groupmembers.php?gid=$gid" : "",
@@ -48,18 +51,19 @@ function setup_group_settings_tabs($gid, $active) {
 	}
 }
 
-function get_operator_groupslist($operatorid, $link) {
-    global $settings, $mysqlprefix;
-    if($settings['enablegroups'] == '1') {
-        $groupids = array(0);
-        $allgroups = select_multi_assoc("select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid order by groupid",$link);
-        foreach($allgroups as $g) {
-            $groupids[] = $g['groupid'];
-        }
-        return implode(",", $groupids);
-    } else {
-        return "";
-    }
+function get_operator_groupslist($operatorid, $link)
+{
+	global $settings, $mysqlprefix;
+	if ($settings['enablegroups'] == '1') {
+		$groupids = array(0);
+		$allgroups = select_multi_assoc("select groupid from ${mysqlprefix}chatgroupoperator where operatorid = $operatorid order by groupid", $link);
+		foreach ($allgroups as $g) {
+			$groupids[] = $g['groupid'];
+		}
+		return implode(",", $groupids);
+	} else {
+		return "";
+	}
 }
 
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/notify.php b/src/messenger/webim/libs/notify.php
index 672ba88c..99de38b6 100644
--- a/src/messenger/webim/libs/notify.php
+++ b/src/messenger/webim/libs/notify.php
@@ -19,19 +19,20 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function webim_mail($toaddr, $reply_to, $subject, $body, $link) {
+function webim_mail($toaddr, $reply_to, $subject, $body, $link)
+{
 	global $webim_encoding, $webim_mailbox, $mail_encoding, $current_locale;
 
 	$headers = "From: $webim_mailbox\r\n"
-	   ."Reply-To: ".myiconv($webim_encoding, $mail_encoding, $reply_to)."\r\n"
-	   ."Content-Type: text/plain; charset=$mail_encoding\r\n"
-	   .'X-Mailer: PHP/'.phpversion();
+			   . "Reply-To: " . myiconv($webim_encoding, $mail_encoding, $reply_to) . "\r\n"
+			   . "Content-Type: text/plain; charset=$mail_encoding\r\n"
+			   . 'X-Mailer: PHP/' . phpversion();
 
-	$real_subject = "=?".$mail_encoding."?B?".base64_encode(myiconv($webim_encoding,$mail_encoding,$subject))."?=";
+	$real_subject = "=?" . $mail_encoding . "?B?" . base64_encode(myiconv($webim_encoding, $mail_encoding, $subject)) . "?=";
 
-	$body = preg_replace("/\n/","\r\n", $body);
-	
-	@mail($toaddr, $real_subject, wordwrap(myiconv($webim_encoding, $mail_encoding, $body),70), $headers);
+	$body = preg_replace("/\n/", "\r\n", $body);
+
+	@mail($toaddr, $real_subject, wordwrap(myiconv($webim_encoding, $mail_encoding, $body), 70), $headers);
 }
 
 ?>
\ No newline at end of file
diff --git a/src/messenger/webim/libs/operator_settings.php b/src/messenger/webim/libs/operator_settings.php
index efad27ec..edf112d7 100644
--- a/src/messenger/webim/libs/operator_settings.php
+++ b/src/messenger/webim/libs/operator_settings.php
@@ -19,12 +19,13 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function setup_operator_settings_tabs($opId, $active) {
+function setup_operator_settings_tabs($opId, $active)
+{
 	global $page, $webimroot, $settings;
 	loadsettings();
-	
-	if($opId) {
-		if($settings['enablegroups'] == '1') {
+
+	if ($opId) {
+		if ($settings['enablegroups'] == '1') {
 			$page['tabs'] = array(
 				getlocal("page_agent.tab.main") => $active != 0 ? "$webimroot/operator/operator.php?op=$opId" : "",
 				getlocal("page_agent.tab.avatar") => $active != 1 ? "$webimroot/operator/avatar.php?op=$opId" : "",
diff --git a/src/messenger/webim/libs/pagination.php b/src/messenger/webim/libs/pagination.php
index 19d5a80a..01e9e54b 100644
--- a/src/messenger/webim/libs/pagination.php
+++ b/src/messenger/webim/libs/pagination.php
@@ -22,110 +22,117 @@
 $pagination_spacing = "&nbsp;&nbsp;&nbsp;";
 $links_on_page = 5;
 
-function generate_pagination_link($page,$title) {
+function generate_pagination_link($page, $title)
+{
 	$lnk = $_SERVER['REQUEST_URI'];
 	$href = preg_replace("/\?page=\d+\&/", "?", preg_replace("/\&page=\d+/", "", $lnk));
-	$href .= strstr($href,"?") ? "&page=$page" : "?page=$page";
-	return "<a href=\"".htmlspecialchars($href)."\" class=\"pagelink\">$title</a>";
+	$href .= strstr($href, "?") ? "&page=$page" : "?page=$page";
+	return "<a href=\"" . htmlspecialchars($href) . "\" class=\"pagelink\">$title</a>";
 }
 
-function generate_pagination_image($id,$alt) {
+function generate_pagination_image($id, $alt)
+{
 	global $webimroot;
-	return "<img src=\"$webimroot/images/$id.gif\" border=\"0\" alt=\"".htmlspecialchars($alt)."\"/>";
+	return "<img src=\"$webimroot/images/$id.gif\" border=\"0\" alt=\"" . htmlspecialchars($alt) . "\"/>";
 }
 
-function prepare_pagination($items_count,$default_items_per_page=15) {
+function prepare_pagination($items_count, $default_items_per_page = 15)
+{
 	global $page;
 
-	if( $items_count ) {
+	if ($items_count) {
 		$items_per_page = verifyparam("items", "/^\d{1,3}$/", $default_items_per_page);
-		if( $items_per_page < 2 )
+		if ($items_per_page < 2)
 			$items_per_page = 2;
 
 		$total_pages = div($items_count + $items_per_page - 1, $items_per_page);
 		$curr_page = verifyparam("page", "/^\d{1,6}$/", 1);
 
-		if( $curr_page < 1 )
+		if ($curr_page < 1)
 			$curr_page = 1;
-		if( $curr_page > $total_pages )
+		if ($curr_page > $total_pages)
 			$curr_page = $total_pages;
 
-		$start_index = ($curr_page-1)*$items_per_page;
-		$end_index = min($start_index+$items_per_page, $items_count);
+		$start_index = ($curr_page - 1) * $items_per_page;
+		$end_index = min($start_index + $items_per_page, $items_count);
 		$page['pagination'] =
-			array(  "page" => $curr_page, "items" => $items_per_page, "total" => $total_pages,
-					"count" => $items_count, "start" => $start_index, "end" => $end_index,
-					"limit" => "LIMIT $start_index,".($end_index - $start_index) );
+				array("page" => $curr_page, "items" => $items_per_page, "total" => $total_pages,
+					  "count" => $items_count, "start" => $start_index, "end" => $end_index,
+					  "limit" => "LIMIT $start_index," . ($end_index - $start_index));
 	} else {
 		$page['pagination'] = true;
 	}
 }
 
-function setup_pagination($items,$default_items_per_page=15) {
+function setup_pagination($items, $default_items_per_page = 15)
+{
 	global $page;
 	prepare_pagination($items ? count($items) : 0, $default_items_per_page);
-	if($items && count($items) > 0) {
+	if ($items && count($items) > 0) {
 		$p = $page['pagination'];
-		$page['pagination.items'] = array_slice($items, $p['start'], $p['end']-$p['start']);
+		$page['pagination.items'] = array_slice($items, $p['start'], $p['end'] - $p['start']);
 	} else {
 		$page['pagination.items'] = false;
 	}
 }
 
-function select_with_pagintation($fields, $table, $conditions, $order, $countfields, $link) {
+function select_with_pagintation($fields, $table, $conditions, $order, $countfields, $link)
+{
 	global $page;
 	$count = db_rows_count($table, $conditions, $countfields, $link);
 	prepare_pagination($count);
-	if($count) {
+	if ($count) {
 		$p = $page['pagination'];
 		$limit = $p['limit'];
-		$page['pagination.items'] = select_multi_assoc(db_build_select($fields, $table, $conditions, $order)." ".$limit, $link);
+		$page['pagination.items'] = select_multi_assoc(db_build_select($fields, $table, $conditions, $order) . " " . $limit, $link);
 	} else {
 		$page['pagination.items'] = false;
 	}
 }
 
-function setup_empty_pagination() {
+function setup_empty_pagination()
+{
 	global $page;
 	$page['pagination.items'] = false;
 	$page['pagination'] = false;
 }
 
-function generate_pagination($pagination,$bottom=true) {
+function generate_pagination($pagination, $bottom = true)
+{
 	global $pagination_spacing, $links_on_page;
 	$result = getlocal2("tag.pagination.info",
-		array($pagination['page'],$pagination['total'],$pagination['start']+1,$pagination['end'],$pagination['count']))."<br/>";
+						array($pagination['page'], $pagination['total'], $pagination['start'] + 1, $pagination['end'], $pagination['count'])) . "<br/>";
 
-	if( $pagination['total'] > 1 ) {
-		if(!$bottom) {
+	if ($pagination['total'] > 1) {
+		if (!$bottom) {
 			$result = "";
 		} else {
 			$result .= "<br/>";
 		}
-		$result.="<div class='pagination'>";
+		$result .= "<div class='pagination'>";
 		$curr_page = $pagination['page'];
 
-		$minPage = max( $curr_page - $links_on_page, 1 );
-		$maxPage = min( $curr_page + $links_on_page, $pagination['total'] );
+		$minPage = max($curr_page - $links_on_page, 1);
+		$maxPage = min($curr_page + $links_on_page, $pagination['total']);
 
-		if( $curr_page > 1 ) {
-			$result .= generate_pagination_link($curr_page-1, generate_pagination_image("prevpage", getlocal("tag.pagination.previous"))).$pagination_spacing;
+		if ($curr_page > 1) {
+			$result .= generate_pagination_link($curr_page - 1, generate_pagination_image("prevpage", getlocal("tag.pagination.previous"))) . $pagination_spacing;
 		}
 
-		for($i = $minPage; $i <= $maxPage; $i++ ) {
-			$title = abs($curr_page-$i) >= $links_on_page && $i != 1 ? "..." : $i;
-			if( $i != $curr_page)
+		for ($i = $minPage; $i <= $maxPage; $i++) {
+			$title = abs($curr_page - $i) >= $links_on_page && $i != 1 ? "..." : $i;
+			if ($i != $curr_page)
 				$result .= generate_pagination_link($i, $title);
 			else
 				$result .= "<span class=\"pagecurrent\">$title</span>";
-			if( $i < $maxPage )
+			if ($i < $maxPage)
 				$result .= $pagination_spacing;
 		}
 
-		if( $curr_page < $pagination['total'] ) {
-			$result .= $pagination_spacing.generate_pagination_link($curr_page+1, generate_pagination_image("nextpage", getlocal("tag.pagination.next")));
+		if ($curr_page < $pagination['total']) {
+			$result .= $pagination_spacing . generate_pagination_link($curr_page + 1, generate_pagination_image("nextpage", getlocal("tag.pagination.next")));
 		}
-		$result.="</div>";
+		$result .= "</div>";
 	}
 	return $result;
 }
diff --git a/src/messenger/webim/libs/settings.php b/src/messenger/webim/libs/settings.php
index cdd24415..24fbbf6e 100644
--- a/src/messenger/webim/libs/settings.php
+++ b/src/messenger/webim/libs/settings.php
@@ -19,21 +19,23 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function update_settings() {
+function update_settings()
+{
 	global $settings, $settings_in_db, $mysqlprefix;
 	$link = connect();
 	foreach ($settings as $key => $value) {
-		if(!isset($settings_in_db[$key])) {
-			perform_query("insert into ${mysqlprefix}chatconfig (vckey) values ('$key')",$link);
+		if (!isset($settings_in_db[$key])) {
+			perform_query("insert into ${mysqlprefix}chatconfig (vckey) values ('$key')", $link);
 		}
-        $query = sprintf("update ${mysqlprefix}chatconfig set vcvalue='%s' where vckey='$key'", mysql_real_escape_string($value));
-		perform_query($query,$link);
+		$query = sprintf("update ${mysqlprefix}chatconfig set vcvalue='%s' where vckey='$key'", mysql_real_escape_string($value));
+		perform_query($query, $link);
 	}
 
 	mysql_close($link);
 }
 
-function setup_settings_tabs($active) {
+function setup_settings_tabs($active)
+{
 	global $page, $webimroot;
 	$page['tabs'] = array(
 		getlocal("page_settings.tab.main") => $active != 0 ? "$webimroot/operator/settings.php" : "",
diff --git a/src/messenger/webim/libs/userinfo.php b/src/messenger/webim/libs/userinfo.php
index 8f8915c9..710c31e6 100644
--- a/src/messenger/webim/libs/userinfo.php
+++ b/src/messenger/webim/libs/userinfo.php
@@ -19,38 +19,40 @@
  *    Evgeny Gryaznov - initial API and implementation
  */
 
-function get_useragent_version($userAgent) {
-    global $knownAgents;
-    if (is_array($knownAgents)) {
-	$userAgent = strtolower($userAgent);
-	foreach( $knownAgents as $agent ) {
-		if( strstr($userAgent,$agent) ) {
-			if( preg_match( "/".$agent."[\\s\/]?(\\d+(\\.\\d+(\\.\\d+(\\.\\d+)?)?)?)/", $userAgent, $matches ) ) {
-				$ver = $matches[1];
-				if($agent=='safari') {
-					if(preg_match( "/version\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) {
-						$ver = $matches[1];
-					} else {
-						$ver = "1 or 2 (build ".$ver.")";
+function get_useragent_version($userAgent)
+{
+	global $knownAgents;
+	if (is_array($knownAgents)) {
+		$userAgent = strtolower($userAgent);
+		foreach ($knownAgents as $agent) {
+			if (strstr($userAgent, $agent)) {
+				if (preg_match("/" . $agent . "[\\s\/]?(\\d+(\\.\\d+(\\.\\d+(\\.\\d+)?)?)?)/", $userAgent, $matches)) {
+					$ver = $matches[1];
+					if ($agent == 'safari') {
+						if (preg_match("/version\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) {
+							$ver = $matches[1];
+						} else {
+							$ver = "1 or 2 (build " . $ver . ")";
+						}
+						if (preg_match("/mobile\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) {
+							$userAgent = "iPhone " . $matches[1] . " ($agent $ver)";
+							break;
+						}
 					}
-					if(preg_match( "/mobile\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) {
-						$userAgent = "iPhone ".$matches[1]." ($agent $ver)";
-						break;
-					}
-				}
 
-				$userAgent = ucfirst($agent)." ".$ver;
-				break;
+					$userAgent = ucfirst($agent) . " " . $ver;
+					break;
+				}
 			}
 		}
 	}
-    }
-    return $userAgent;
+	return $userAgent;
 }
 
-function get_user_addr($addr) {
+function get_user_addr($addr)
+{
 	global $settings;
-	if($settings['geolink'] && preg_match( "/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $addr, $matches )) {
+	if ($settings['geolink'] && preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $addr, $matches)) {
 		$userip = $matches[1];
 		return get_popup(str_replace("{ip}", $userip, $settings['geolink']), '', htmlspecialchars($addr), "GeoLocation", "ip$userip", $settings['geolinkparams']);
 	}