<?

/**
*
* @package ppkBB3cker
* @version $Id: message_user.php 1.000 2009-04-02 11:38:00 PPK $
* @copyright (c) 2008, 2009 PPK
* http://ppkbb3cker.rx22.ru, http://protoneutron.narod.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

require($phpbb_root_path.'config.'.$phpEx);

if($dbms!='mysql')
{
	err('Only mysql supported');
}

$c=@mysql_connect($dbhost, $dbuser, $dbpasswd);
if(!$c)
{
	err('Error connecting database: '.mysql_error());
}

$s=@mysql_select_db($dbname, $c);
if(!$s)
{
	err('Error selecting database: '.mysql_error());
}

define('CONFIG_TABLE',				$table_prefix . 'config');
define('SMILIES_TABLE',				$table_prefix . 'smilies');
define('CHAT_USERS_TABLE',			$table_prefix . 'chat_users');
define('CHAT_MESSAGES_TABLE',			$table_prefix . 'chat_messages');
my_sql_query("SET NAMES 'utf8'");

$config=array();
$sql="SELECT config_name, config_value FROM ".CONFIG_TABLE." WHERE config_name='smilies_path' OR config_name LIKE 'ppkbb\_chat%'";
$result=my_sql_query($sql);
while($row=mysql_fetch_row($result))
{
	$config[$row[0]]=$row[1];
}
mysql_free_result($result);

$dt = time();
$gmq_gpc = get_magic_quotes_gpc() ? 1 : 0;

$forum_id=intval(@$_GET['f']);
$forum_id < 0 ? $forum_id=0 : '';
$chat_message=$gmq_gpc ? @$_POST['chat_sent'] : mysql_real_escape_string(@$_POST['chat_sent']);
$del_message=intval(@$_GET['del_mess']);
$del_message < 0 ? $del_message=0 : '';
$chat_key=$gmq_gpc ? @$_GET['chatkey'] : mysql_real_escape_string(@$_GET['chatkey']);
$lang='ru';
$css='chat/stylesheet.css';

$sql='SELECT * FROM ' .CHAT_USERS_TABLE. " WHERE room='$forum_id'";
$result=my_sql_query($sql);
$users=array();
while($row=mysql_fetch_array($result))
{
	if($row['chatkey']==$chat_key)
	{
		$chat_user=$row;

	}
	$users[]=$row;
}
mysql_free_result($result);

$message_table='';
$user_table='';

if(@$chat_user)
{
	list($lang, $css, $rights)=explode('//', $chat_user['rights']);
	//0-$is_adm 1-$is_mod 2-$is_canaddchatm 3-$is_canviewchatu
	//4-$is_canviewchatm 5-$is_candelchatm 6-$is_canskipchatktime
	//7-$is_canhiddeninchat 8-$is_canviewhiddinchat 9-$is_cansendchatpm
	//10-$is_canskipdisbutton 11-$is_canusesmilies 12-$is_canusebbcodes
	$rights=explode(' ', $rights);
	$user_class=array();
	$user_rights=array();
	require_once("{$phpbb_root_path}language/$lang/chat.$phpEx");
	intval($config['ppkbb_chat_murefresh']) > 9 ? '' : $config['ppkbb_chat_murefresh']=10;
	$skip_lacheck=0;

	if($rights[4])
	{
		if($rights[5] && $del_message)
		{
			$skip_lacheck=1;
			$sql='DELETE FROM ' .CHAT_MESSAGES_TABLE. " WHERE id='$del_message' LIMIT 1";
			$result=my_sql_query($sql);
		}

		$lastpost=0;
		if($chat_message && $rights[2])
		{
			if(!$rights[10] && ($dt - $chat_user['lastpost']) < $config['ppkbb_chat_waittime'])
			{

			}
			else
			{
				intval($config['ppkbb_chat_messlength']) ? '' : $config['ppkbb_chat_messlength']=255;
				$mbstring=extension_loaded('mbstring') ? 1 : 0;
				$chat_message_len=$mbstring ? mbstring_utf8_strlen($chat_message) : utf8_strlen($chat_message);

				if($chat_message_len > $config['ppkbb_chat_messlength'])
				{
					$chat_message=$mbstring ? mbstring_utf8_substr($chat_message, 0, $config['ppkbb_chat_messlength']) : utf8_substr($chat_message, 0, $config['ppkbb_chat_messlength']);
				}

				$sql='INSERT INTO ' .CHAT_MESSAGES_TABLE. " VALUES ('0', '$chat_message', '{$chat_user['user_id']}', '0', '$dt', '{$chat_user['rights']}', '$forum_id', '{$chat_user['username']}')";
				$result=my_sql_query($sql);

				$lastpost=$dt;
				$skip_lacheck=1;
			}
		}

		$sql='UPDATE ' .CHAT_USERS_TABLE. " SET lastaccess='$dt'".($lastpost ? ", lastpost='$lastpost'" : '')." WHERE chatkey='{$chat_key}' AND room='{$forum_id}'";
		$result=my_sql_query($sql);

		if(!$skip_lacheck && ($dt - $chat_user['lastaccess']) < $config['ppkbb_chat_murefresh'])
		{
			$message_table.=$lang['CHAT_LA_CHECK'];
			exit();
		}
		intval($config['ppkbb_chat_messdisplay']) ? '' : $config['ppkbb_chat_messdisplay']=25;
		$sql='SELECT * FROM ' .CHAT_MESSAGES_TABLE. " WHERE room='$forum_id' ORDER BY id DESC LIMIT {$config['ppkbb_chat_messdisplay']}";
		$result=my_sql_query($sql);
	}
	else
	{
		$config['ppkbb_chat_murefresh']=3600;
	}
	if($rights[3])
	{
		if(!$skip_lacheck && ($dt - $chat_user['lastaccess']) < $config['ppkbb_chat_murefresh'])
		{
			$message_table.=$lang['CHAT_LA_CHECK'];
			exit();
		}
		$user_table.= '<div class="st"><table width="100%" cellpadding="0" cellspacing="1" border="0">';
		foreach($users as $v)
		{
			if(@!$user_rights[$v['user_id']])
			{
				$lcr=explode('//', $v['rights']);
				$user_rights[$v['user_id']]=explode(' ', $lcr[2]);
			}
			if(!$user_rights[$v['user_id']][7] && !$rights[8])
			{
				if(@!$user_class[$v['user_id']])
				{
					if($user_rights[$v['user_id']][0])
					{
						$user_class[$v['user_id']]='adm';
					}
					else if($user_rights[$v['user_id']][1])
					{
						$user_class[$v['user_id']]='mod';
					}
					else
					{
						$user_class[$v['user_id']]='user';
					}
				}
			}
			$v['username']=stripslashes($v['username']);
			$user_table.= '
			<tr valign="top">
				<td>
					<span class="users">&nbsp;<a class="'.$user_class[$v['user_id']].'" href="#" onClick="javascript:inserttext(\''.$v['username'].': \')">'.$v['username'].'</a> [<a target="new" href="'.$phpbb_root_path.'memberlist.'.$phpEx.'?mode=viewprofile&amp;u='.$v['user_id'].'">?</a>]</span>
				</td>
			</tr>';
		}
		$user_table.= '</table></div>';
	}
	else
	{
		$user_table.= '<table width="100%" cellpadding="0" cellspacing="1" border="0">';
		$user_table.= '
			<tr valign="top">
				<td>
					<span class="textuser">'.$lang['CHAT_CANT_VIEWCHATU'].'</span>
				</td>
			</tr>';
		$user_table.= '</table>';
	}
	if($rights[4])
	{
		$smiles=get_chat_smilies();

		$last_mess_id=0;
		$message_table.= '<div class="st"><table width="100%" cellpadding="0" cellspacing="1" border="0">';
		while($row=mysql_fetch_array($result))
		{
			if(@!$user_rights[$row['user_id']])
			{
				$lcr=explode('//', $row['rights']);
				$user_rights[$row['user_id']]=explode(' ', $lcr[2]);
			}
			if(@!$user_rights[$row['user_id']][7] && !$rights[8])
			{
				if(@!$user_class[$row['user_id']])
				{
					if($user_rights[$row['user_id']][0])
					{
						$user_class[$row['user_id']]='adm';
					}
					else if($user_rights[$row['user_id']][1])
					{
						$user_class[$row['user_id']]='mod';
					}
					else
					{
						$user_class[$row['user_id']]='user';
					}
				}
			}
			if($config['ppkbb_chat_timecorrect'])
			{
				if(strpos($config['ppkbb_chat_timecorrect'], '-')===true)
				{
					$row['date']=$row['date'] - intval($config['ppkbb_chat_timecorrect']);
				}
				else
				{
					$row['date']=$row['date'] + intval($config['ppkbb_chat_timecorrect']);
				}
			}
			$row['message']=htmlspecialchars(stripslashes($row['message']));
			$row['message']=wordwrap($row['message'], 60, '&shy;');
			if($user_rights[$row['user_id']][0])
			{
				$row['message']=chat_smilies($row['message'], $smiles['match'], $smiles['replace'], $config['ppkbb_chat_maxsmiles']);
			}
			else
			{
				//$row['message']=htmlspecialchars(stripslashes($row['message']));
			}

			$message_table.= '
			<tr valign="top">
				<td><span class="mess">'.date('H:i:s', $row['date']).' <span class="'.$user_class[$row['user_id']].'">'.$row['username'].'</span> '.(@$rights[5] && $row['user_id']==$chat_user['user_id'] ? '<a href="'.$phpbb_root_path.'chat/message_user.'.$phpEx.'?f='.$forum_id.'&amp;del_mess='.$row['id'].'&amp;chatkey='.$chat_key.'">[x]</a> ' : '').$row['message'].'</span></td>
			</tr>';

			$last_mess_id=$row['id'];
		}
		$message_table.= '</table></div>';
		mysql_free_result($result);

		$config['ppkbb_chat_marchive'] ? $config['ppkbb_chat_messdisplay']+=$config['ppkbb_chat_marchive'] : '';
		if( ($dt - $config['ppkbb_chat_last_cleanup']) > $config['ppkbb_chat_cleanup_interval'] && ($last_mess_id - $config['ppkbb_chat_messdisplay']) > 0)
		{
			$sql='DELETE FROM ' .CHAT_MESSAGES_TABLE. " WHERE room='$forum_id' AND id < '$last_mess_id'";
			$result=my_sql_query($sql);

			$sql='UPDATE ' .CONFIG_TABLE. " SET config_value='$dt' WHERE config_name='ppkbb_chat_last_cleanup'";
			$result=my_sql_query($sql);
		}
	}
	else
	{
		$message_table.= '<table width="100%" cellpadding="0" cellspacing="1" border="0">';
		$message_table.= '
			<tr valign="top">
				<td>
					<span class="textmess">'.$lang['CHAT_CANT_VIEWCHATM'].'</span>
				</td>
			</tr>';
		$message_table.= '</table>';
	}
}
else
{
	require_once("{$phpbb_root_path}language/$lang/chat.$phpEx");
	$config['ppkbb_chat_murefresh']=3600;
	$user_table.= '<table width="100%" cellpadding="0" cellspacing="1" border="0">';
	$user_table.= '
	<tr valign="top">
		<td>
			<span class="textuser">'.$lang['CHAT_LOGIN'].'</span>
		</td>
	</tr>';
	$user_table.= '</table>';

	$message_table.= '<table width="100%" cellpadding="0" cellspacing="1" border="0">';
	$message_table.= '
		<tr valign="top">
			<td>
				<span class="textmess">'.$lang['CHAT_LOGIN'].'</span>
			</td>
		</tr>';
	$message_table.= '</table>';
}

$css_link=stripslashes($css);

intval($config['ppkbb_chat_murefresh']) > 9 ? '' : $config['ppkbb_chat_murefresh']=10;
?>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content="<?=$config['ppkbb_chat_murefresh']?>; URL=./message_user.<?=$phpEx?>?f=<?=$forum_id?>&chatkey=<?=@$chat_user['chatkey']?>">
<link rel="stylesheet" href="<?=$phpbb_root_path.$css_link?>.chat.css" type="text/css">
<script language="JavaScript">
<!--
function inserttext(str)
{
	if(str!='')
	{
		parent.form.document.post_form.chat_message.value += str;
	}
	else
	{
		parent.form.document.post_form.chat_message.value = '';
	}
	parent.form.document.post_form.chat_message.focus();
}
<?
if(@$chat_user && !$rights[6] && $dt - @$chat_user['lastpost'] > $config['ppkbb_chat_killtime'])
{
?>
function killtime()
{
	parent.document.location.href='<?=$phpbb_root_path?>viewchat.<?=$phpEx?>?f=<?=$forum_id?>&chat=exit';
}
killtime();
<?
}
?>
-->
</script>
</head>
<body>
<table width="100%" cellpadding="0" cellspacing="1" border="0" height="400">
	<tr valign="top">
	<td width="76%" class="row1">
		<?=$message_table?>
	</td>
	<td width="24%" class="row2">
		<?=$user_table?>
	</td>
	</tr>
</table>
</body>
</html>
<?
mysql_close();

exit();

//############################################################

function get_chat_smilies()
{
	global $config, $phpbb_root_path, $dbms;
	static $match;
	static $replace;

	// See if the static arrays have already been filled on an earlier invocation
	if (!is_array($match))
	{
		$match = $replace = array();
		$smiles=array();

		$sql = 'SELECT *
			FROM ' . SMILIES_TABLE . '
			ORDER BY LENGTH(code) DESC';

		$result = my_sql_query($sql);

		while($row=mysql_fetch_array($result))
		{
			if (empty($row['code']))
			{
				continue;
			}

			// (assertion)
			$smiles['match'][] = '(?<=^|[\n .])' . preg_quote($row['code'], '#') . '(?![^<>]*>)';
			$smiles['replace'][] = '<img src="'.$phpbb_root_path.$config['smilies_path'].'/' . $row['smiley_url'] . '" alt="' . $row['code'] . '" title="' . $row['emotion'] . '" />';
		}
		mysql_free_result($result);
	}

	return $smiles;
}

function chat_smilies($text, $match, $replace, $max_smilies = 0)
{
	if (sizeof($match))
	{
		if ($max_smilies)
		{
			$num_matches = preg_match_all('#' . implode('|', $match) . '#', $text, $matches);
			unset($matches);

			if ($num_matches !== false && $num_matches > $max_smilies)
			{
				return $text;
			}
		}

		// Make sure the delimiter # is added in front and at the end of every element within $match
		$text = trim(preg_replace(explode(chr(0), '#' . implode('#' . chr(0) . '#', $match) . '#'), $replace, $text));
	}

	return $text;
}

function my_sql_query($query)
{
	global $startsqlcount, $c;
	$startsqlcount+=1;

	return mysql_query($query);
}

//From includes/utf/utf_tools.php
function mbstring_utf8_substr($str, $offset, $length = null)
{
	if (is_null($length))
	{
		return mb_substr($str, $offset);
	}
	else
	{
		return mb_substr($str, $offset, $length);
	}
}

//From includes/utf/utf_tools.php
function mbstring_utf8_strlen($text)
{
	return mb_strlen($text, 'utf-8');
}

//From includes/utf/utf_tools.php
function utf8_substr($str, $offset, $length = NULL)
{
	// generates E_NOTICE
	// for PHP4 objects, but not PHP5 objects
	$str = (string) $str;
	$offset = (int) $offset;
	if (!is_null($length))
	{
		$length = (int) $length;
	}

	// handle trivial cases
	if ($length === 0 || ($offset < 0 && $length < 0 && $length < $offset))
	{
		return '';
	}

	// normalise negative offsets (we could use a tail
	// anchored pattern, but they are horribly slow!)
	if ($offset < 0)
	{
		// see notes
		$strlen = utf8_strlen($str);
		$offset = $strlen + $offset;
		if ($offset < 0)
		{
			$offset = 0;
		}
	}

	$op = '';
	$lp = '';

	// establish a pattern for offset, a
	// non-captured group equal in length to offset
	if ($offset > 0)
	{
		$ox = (int) ($offset / 65535);
		$oy = $offset % 65535;

		if ($ox)
		{
			$op = '(?:.{65535}){' . $ox . '}';
		}

		$op = '^(?:' . $op . '.{' . $oy . '})';
	}
	else
	{
		// offset == 0; just anchor the pattern
		$op = '^';
	}

	// establish a pattern for length
	if (is_null($length))
	{
		// the rest of the string
		$lp = '(.*)$';
	}
	else
	{
		if (!isset($strlen))
		{
			// see notes
			$strlen = utf8_strlen($str);
		}

		// another trivial case
		if ($offset > $strlen)
		{
			return '';
		}

		if ($length > 0)
		{
			// reduce any length that would
			// go passed the end of the string
			$length = min($strlen - $offset, $length);

			$lx = (int) ($length / 65535);
			$ly = $length % 65535;

			// negative length requires a captured group
			// of length characters
			if ($lx)
			{
				$lp = '(?:.{65535}){' . $lx . '}';
			}
			$lp = '(' . $lp . '.{'. $ly . '})';
		}
		else if ($length < 0)
		{
			if ($length < ($offset - $strlen))
			{
				return '';
			}

			$lx = (int)((-$length) / 65535);
			$ly = (-$length) % 65535;

			// negative length requires ... capture everything
			// except a group of  -length characters
			// anchored at the tail-end of the string
			if ($lx)
			{
				$lp = '(?:.{65535}){' . $lx . '}';
			}
			$lp = '(.*)(?:' . $lp . '.{' . $ly . '})$';
		}
	}

	if (!preg_match('#' . $op . $lp . '#us', $str, $match))
	{
		return '';
	}

	return $match[1];
}

//From includes/utf/utf_tools.php
function utf8_strlen($text)
{
	// Since utf8_decode is replacing multibyte characters to ? strlen works fine
	return strlen(utf8_decode($text));
}

function err($str)
{
	echo $str;
	exit();
}
?>
