<?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
#############################################################################
# post.php: last changed 05/10/2006  , version: 2.4.10
#              by Fred Stuurman (fc.stuurman@hccnet.nl)
#$Id: check.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.
##############################################################################
define('IN_SAS', true);

include ("../../configuration/database.inc.php");
mysql_connect("$db_server", "$db_username", "$db_password");
mysql_select_db("$db_name");

require ("../../core/session.php"); //build a session

if (!IsSet ($_SESSION['Chat_Username']))
{
	exit;
}

$chats_usertable = $dbprefix . "m_chat_users";
$chats_messagetable = $dbprefix . "m_chat_log";

if (IsSet ($_GET['user']))
{

	if (!get_magic_quotes_gpc())
	{
		$user = strip_tags(addslashes($_GET['user']));
	}
	else
	{
		$user = strip_tags($_GET['user']);
	}
}

$beep = '<EMBED SRC=\'ding.wav\' HIDDEN=\'true\' AUTOSTART=\'true\' LOOP=\'false\'><NOEMBED><BGSOUND SRC=\'ding.wav\' LOOP=1></NOEMBED></embed>';
if ($_GET['refresh'] != 0) //check if the refresh is not 0 otherwise use 2
{
	$refresh = $_GET['refresh'];
}
else
{
	$refresh = '2';
}

$kick = -1;
$idle = 600;

// Check to make sure the user is still in the room
$query = "SELECT status FROM $chats_usertable WHERE user=\'" . $user . "\'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$status = mysql_result($result, 0);
//if($num < 1) {
// 	$query = "INSERT INTO $chats_usertable SET user='".$user."', joined=NOW()";
//	mysql_query($query);
//}
//echo 'Value of last check variable: '.$_SESSION['lastcheck1']."<br>\n";
if (!isset ($_SESSION['lastcheck1']))
{
	echo 'User may not have cookies enable >_<';
	$_SESSION['lastcheck1'] = date('YmdHis');
	$_SESSION['lastcheck2'] = date('YmdHis');
}

if ($status != 'booted')
{
	echo '<meta http-equiv="refresh" content="' . $refresh . '">';
	echo '<script language="JavaScript1.1"><!--
				function goto_bottom() 
				{
				    window.parent.chatlogs.scroll(0,1000000000);
				}
				//--></script>
				<script language="JavaScript1.2"><!--
				function goto_bottom() {
				    window.parent.chatlogs.scrollTo(0,1000000000);
				}
				//-->
		      </script>';
	echo '<script language="javascript">';

	// Check for new messages

	$lastcheck = $_SESSION['lastcheck1'];
	$now = date('YmdHis');
	$query = "SELECT * FROM $chats_messagetable 
					WHERE posted BETWEEN '" . $lastcheck . "' AND '" . $now . "' AND room = '" . $_SESSION['Chat_ID'] . "' 
					ORDER BY posted ASC";
	$result = mysql_query($query);
	if (mysql_num_rows($result) > 0)
	{
		while ($message_list = mysql_fetch_array($result))
		{
			if ($message_list[1] != $user)
			{

				if ($message_list[7] == '0')
				{
					if ($_GET['show_time'] == 1)
					{
						$message = '<font size=2>' . substr($message_list[6], 11) . ':</font><b> [' . $message_list[1] . ']</b>&nbsp;';
					}
					else
					{
						$message = '<b> [' . $message_list[1] . ']</b>&nbsp;';
					}

					if ($message_list[8] != 1)
					{
						$message2 = htmlentities($message_list[5]);
					}
					else
					{
						$message2 = $message_list[5];
					}
					$message2 = $message . '<font color=\\"' . @ ($_SESSION['color']) . '\\">' . $message2;
					$message2 .= '</font>' . $beep;
					echo 'window.parent.chatlogs.thelement.innerHTML += "' . $message2 . '<br>";' . "\n";
					echo 'goto_bottom();' . "\n";
				}
				else
				{
					// Private message, so let's show it to the right user
					if ($message_list[7] == $user)
					{
						if ($_GET['show_time'] == 1)
						{
							$message = '<font size=2>' . substr($message_list[6], 11) . ':</font><font color=\\"red\\"><b> [' . $message_list[1] . ']</b>&nbsp;<i>(to ' . $user . ')</i></font>:&nbsp;';
						}
						else
						{
							$message = '<font color=\\"red\\"><b> [' . $message_list[1] . ']</b>&nbsp;<i>(to ' . $user . ')</i></font>:&nbsp;';
						}

						if ($message_list[8] != 1)
						{
							$message2 = htmlentities($message_list[5]);
						}
						else
						{
							$message2 = $message_list[5];
						}
						$message2 = $message . '<font color=\\"' . @ ($_SESSION['color']) . '\\">' . $message2;
						$message2 .= '</font>' . $beep;
						echo 'window.parent.chatlogs.thelement.innerHTML += "' . $message2 . '<br>";' . "\n";
						echo 'goto_bottom();' . "\n";
					}
				}
			}
		}
		sleep(1); //delay one second.
		$_SESSION['lastcheck1'] = date('YmdHis');
	}
	//check for logged off users
	$query = "SELECT status FROM $chats_usertable WHERE status = 'out'";
	$result = mysql_query($query);
	if (mysql_num_rows($result) > 0)
	{
		echo 'window.parent.users.location.reload();';
		mysql_query("DELETE FROM $chats_usertable WHERE status = 'out'");
	}

	// Check for new users
	$query = "SELECT joined FROM $chats_usertable ORDER BY joined DESC LIMIT 1";
	$result = mysql_query($query);
	$num = str_replace('-', '', mysql_result($result, 0, 0));
	$num = str_replace(' ', '', $num);
	$num = str_replace(':', '', $num);
	if ($_SESSION['lastcheck2'] <= $num)
	{
		// Refresh users page
		echo 'window.parent.users.location.reload();';
		$_SESSION['lastcheck2'] = date('YmdHis');
	}
	// Check for idleness
	$query = "SELECT status FROM $chats_usertable WHERE user='" . $user . "'";
	$result = mysql_query($query);
	$status = mysql_result($result, 0);

	if ($status != 'booted')
	{
		$query = "SELECT posted FROM $chats_messagetable WHERE user='$user' ORDER BY posted DESC LIMIT 1";
		$result = mysql_query($query);
		if (mysql_num_rows($result) > 0)
		{
			$num = str_replace('-', '', mysql_result($result, 0, 0));
			$num = str_replace(' ', '', $num);
			$num = str_replace(':', '', $num);
			$now = date('YmdHis');
			$temp = $now - $num;
			//echo 'document.write("Idle time: '.$temp.'<br>");';
			if (($idle > 0) AND ($temp > $idle) AND ($status != 'idle'))
			{
				mysql_query("UPDATE $chats_usertable SET status='idle' WHERE user = '" . $user . "'");
				echo 'window.parent.users.location.reload();';
			}
			if (($kick > 0) AND ($temp > $kick))
			{
				mysql_query("UPDATE $chats_usertable SET status='out' WHERE user = '" . $user . "'");
				//echo 'window.parent.location = "index.php?section=$section&page=$page&chat_logout=yes";';
			}
		}
	}
	echo '</script>';
}
else
{
	echo '<script>
	  			window.parent.users.location.reload();
	  			window.parent.message.location.reload();
				window.parent.chatlogs.thelement.innerHTML = "<b>You have been removed from the chat room. Please <a href=\\"logoff.php?user=' . $user . '\\" target=\\"_parent\\">logout</a>.</b><br>";
	  	      </script>';
}
//echo 'Last successful check: '.$_SESSION['lastcheck1']."<br>\nLast message sent: ".$num;
?>
