<?php

#############################################################################
#                              Site@School Chat module
# Site@School is a website management system designed for schools.
# This is a chat module which can be used in Site@School.
#
# coded by Fred Stuurman (fc.stuurman@hccnet.nl)
#############################################################################
#		based on 	CHATNESS v2		 see http://www.chatness.us/
#		BY: Stephen Craton
#   Altered for Site@School with consent of the author
#############################################################################
# chat.php: last changed 03/06/2005  , version: 1.0
#              by Fred Stuurman (fc.stuurman@hccnet.nl)
#$Id: chat.php,v 1.2 2006/10/15 19:08:53 fstuurman Exp $
############################################################################
#                        LICENSE INFORMATION
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
##############################################################################
if (!defined('IN_SAS'))
{
	die("Hacking attempt");
}
if (IsSet ($_POST['password']))
{
	$password = $_POST['password'];
}
if (IsSet ($_POST['username']))
{
	$username = $_POST['username'];
}
if (IsSet ($_POST['login']))
{
	$login = $_POST['login'];
}
if (IsSet ($_GET['chat_logout']))
{
	$chat_logout = $_GET['chat_logout'];
}

load_language($cmsdir . '/', 'sn_chat'); //load language file

$pagetitle = htmlspecialchars(strip_tags($pagetitle)); //sanitize

$chats_usertable = $dbprefix . "m_chat_users";
$chats_table = $dbprefix . "m_chat";
$chats_messagetable = $dbprefix . "m_chat_log";
$ip = getenv('REMOTE_ADDR');

$query = "SELECT id, title, welcome, width, height, public, password, refresh, options 
          FROM $chats_table 
          WHERE name='" . $pagetitle . "'"; // get chat id which corresponds with this pagename

$result = mysql_query($query) or die_script($query, mysql_error());
$recordcount = mysql_num_rows($result);

if ($recordcount > 0)
{
	$chat_id = mysql_result($result, 0, 0);
	$chat_title = mysql_result($result, 0, 1);
	$chat_welcome = mysql_result($result, 0, 2);
	$chat_width = mysql_result($result, 0, 3);
	$chat_height = mysql_result($result, 0, 4);
	$chat_public = mysql_result($result, 0, 5);
	$chat_public_password = mysql_result($result, 0, 6);
	$chat_refresh = mysql_result($result, 0, 7);
	$show_time = mysql_result($result, 0, 8);

	$expiretime = date("YmdHis", time() - 28800); //longer than 8 hours no update, delete these active users
	mysql_query("DELETE FROM $chats_usertable WHERE joined < '$expiretime'"); //delete users from users table not longer active

	if (IsSet ($chat_logout))
	{
		mysql_query("UPDATE $chats_usertable SET status = 'out' WHERE user = '$_SESSION[Chat_Username]'"); //set status user to out
		mysql_query("INSERT INTO $chats_messagetable SET user='" . $_SESSION['Chat_Username'] . "',
		     text='<i>" . $sas_lang['chat_module_left_room'] . "</i>', system=1, posted=NOW(), room='$chat_id', ip='$ip'");
		session_unset();
		session_destroy();
	}

	if (IsSet ($login))
	{

		$expiretime = date("YmdHis", time() - 5);
		$time = date("YmdHis", time());
		$_SESSION['chat_language'] = $language;

		if (($chat_public == "1") AND ($chat_public_password == $password)) //public user is allowed and password matches
		{
			$result = mysql_query("SELECT user FROM $chats_usertable WHERE user = '$username'");
			$record_count = mysql_num_rows($result);
			if ($record_count == '1')
			{
				$result = mysql_query("SELECT user FROM $chats_usertable WHERE user LIKE '$username(%' ORDER BY user DESC");
				$record_count = mysql_num_rows($result);
				if ($record_count > 0)
				{
					$username = mysql_result($result, 0); //get the highest user with same name.
					$pos1 = strpos($username, "("); //first bracket position
					$pos2 = strpos($username, ")"); //second bracket position
					$len = $pos2 - $pos1;
					$teller = substr($username, $pos1 +1, $len -1) + 1;
					$username = $_POST['username'] . "($teller)";
				}
				else
				{
					$username = $username . "(2)";
				}
			}
			$query = "SELECT id FROM $chats_usertable WHERE id > 9000 ORDER BY id DESC limit 1"; //get the highest id for the public user
			$result = mysql_query($query) or die_script($query, mysql_error());
			$record_count = mysql_num_rows($result);
			if ($record_count == '1')
			{
				$id = mysql_result($result, 0) + 1;
			}
			else
			{
				$id = 9001;
			}

			mysql_query("INSERT INTO $chats_usertable (id,user,joined,room,ip) VALUES ('$id','$username','$time','$chat_id','$ip')");
			$_SESSION['Chat_UserID'] = $id;
			$_SESSION['Chat_ID'] = $chat_id;
			$_SESSION['Chat_Username'] = $username;
		}
		else
		{
			if ($sas_config['use_encryption'] == 1) //passwords are encrypted
			{
				$password = md5($password);
			}
			$query = "SELECT id FROM $table_users WHERE username = '$username' AND password = '$password'";
			$result = mysql_query($query) or die_script($query, mysql_error());
			$record_count = mysql_num_rows($result);

			if ($record_count == '1') // username and password match
			{
				$id = mysql_result($result, 0);
				$result = mysql_query("SELECT id FROM $chats_usertable WHERE user = '$username' AND id < 9000");
				$record_count = mysql_num_rows($result);
				if ($record_count == '1') //user is still in the userstable
				{
					mysql_query("UPDATE $chats_usertable SET joined = '$time', status = '' WHERE user = '$username'");
				}
				else
				{
					$result = mysql_query("SELECT user FROM $chats_usertable WHERE user = '$username' AND id > 9000");
					$record_count = mysql_num_rows($result);
					if ($record_count == '1')
					{
						$result = mysql_query("SELECT user FROM $chats_usertable WHERE user LIKE '$username(%' ORDER BY user DESC");
						$record_count = mysql_num_rows($result);
						if ($record_count == '0')
						{
							$username = $username . "(2)";
						}
						else
						{
							$username = mysql_result($result, 0); //get the highest user with same name.
							$pos1 = strpos($username, "("); //first bracket position
							$pos2 = strpos($username, ")"); //second bracket position
							$len = $pos2 - $pos1;
							$teller = substr($username, $pos1 +1, $len -1) + 1;
							$username = $_POST['username'] . "($teller)";
						}
					}

					mysql_query("INSERT INTO $chats_usertable (id,user,joined,room,ip) VALUES ('$id','$username','$time','$chat_id','$ip')");
				}
				//mysql_query("INSERT INTO $chats_usertable (UserID,UserName,LastUpdate,room) VALUES ('$id','$_POST[username]','$time','$chat_id')");
				$_SESSION['Chat_UserID'] = $id;
				$_SESSION['Chat_ID'] = $chat_id;
				$_SESSION['Chat_Username'] = $username;
			}
		}
		if (!$_SESSION['Chat_UserID'])
		{
			print $sas_lang['login_error'] . "<a href=index.php?section=$section&page=$page><br>" . $sas_lang['login'] . "</a>";
		}
	}
	else
	{
		if (!$_SESSION['Chat_UserID'])
		{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  <head>
    <title>Chat</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
    <?php echo $chat_title ?>
    <form method="post" action="index.php?section=<?php echo $section ?>&page=<?php echo $page ?>">
      <table border="0" cellspacing="0" cellpadding="3"><tr><td colspan="2">
      <?php echo $sas_lang['login_text'] ?></td></tr>
      <tr><td><label for="username"><?php echo $sas_lang['username'] ?>: </label></td>
      <td><input type="text" id="username" name="username" value="<?php echo str_replace('"','&quot;',stripslashes($_POST['username'])) ?>" /></td></tr>
      <tr><td><label for="username"><?php echo $sas_lang['password'] ?>: </label></td>
      <INPUT TYPE=hidden NAME="login" value=\"yes\">
      <td><INPUT TYPE=password NAME="password" SIZE=20></td></tr>
      <td colspan="2" align="right"><input type="submit" value="<?php echo $sas_lang['login'] ?>" class="submit" /></td>
      </table>
      
    </form>
    <p class="error">
      <?php echo $error; ?>
    </p>
  </body>
</html>
<?php

			//exit;
		}
	}
	if (($_SESSION['Chat_UserID']) AND ($_SESSION['Chat_ID'] != $chat_id))
	{
		print $sas_lang['chat_module_already_loggedin'];
	}
	elseif ($_SESSION['Chat_UserID'])
	{
		if (IsSet ($_SESSION['Chat_Username'])) //we have a session
		{
			$username = $_SESSION['Chat_Username'];
		}
		else
		{
			$username = $_POST['username']; //we assign the just entered usernam.
		}
		//$_SESSION['Chat_Username'] = $_POST[username];
		mysql_query("INSERT INTO $chats_messagetable SET user='$username', 
		                   text='<i>" . $sas_lang['chat_module_enters_room'] . "</i>', posted=NOW(), system=1, room='$chat_id', ip='$ip'");
		echo $chat_welcome;
		echo "<table bgcolor=\"#FFFFFF\" border=\"1\" style=\"border-collapse: collapse\" bordercolor=\"#111111\" 
		            cellpadding=\"0\" cellspacing=\"0\" width=\"$chat_width\">
		            <tr>
		          	<td width=\"75%\" height=\"$chat_height\" valign=\"top\">" . '<iframe type="content-primary" name="chatlogs" 
		            id="external" style="width:100%;height:100%" src="starnet/modules/sn_chat/log.php" scrolling="YES" 
		            frameborder="NO" leftmargin="0" topmargin="0" rightmargin="0"></iframe>' . "</td>
		          	<td width=\"25%\" height=\"$chat_height\" valign=\"top\">
		            <table cellspacing=\"0\" cellspacing=\"0\" height=\"$chat_height\"><tr><td>
		            <iframe type=\"content\" id=\"external\" src=\"starnet/modules/sn_chat/users.php\" scrolling=\"AUTO\" 
		            frameborder=\"NO\" name=\"users\" width=\"100%\" height=\"100%\"></iframe></td>
		            </td></tr>
		            <tr><td align=\"center\" height=\"25\">
		            <a href=\"index.php?section=$section&page=$page&chat_logout=yes\">
		            <img title=\"" . $sas_lang['logout'] . "\" alt=\"" . $sas_lang['logout'] . "\" src=\"starnet/modules/sn_chat/logout.gif\" border=\"0\"></a>
		            </td></tr></table>
		            </tr>
		            <tr>
		          	<td colspan=\"2\" height=\"40\" nowrap valign=\"top\"><table width=\"100%\"><tr><td>
		          	<iframe name=\"message\" id=\"external\" style=\"width:100%;height:40\" 
		            src=\"starnet/modules/sn_chat/message.php?user=" . $username . "&show_time=" . $show_time . "\" scrolling=\"NO\" 
		            frameborder=\"NO\" leftmargin=\"0\" topmargin=\"0\" rightmargin=\"0\"></iframe>
		          	</td></tr></table></td>
		            </tr>
		            </table>";
		echo '<iframe name="checker" src="starnet/modules/sn_chat/check.php?user=' . $username . '&refresh=' . $chat_refresh . '&show_time=' . $show_time . '" width="0" height="0" scrolling="no" frameborder="no"></iframe>';

	}
}
else
{
	print $sas_lang['chat_module_no_linkpage'];
}
?>
