Помощ, редакция на код

DownFall

Registered
Имам следния код

PHP:
<?php

define ('DBPATH','127.0.0.1');
define ('DBUSER','');
define ('DBPASS','');
define ('DBNAME','');

session_start();

global $dbh;
$dbh = mysql_connect(DBPATH,DBUSER,DBPASS) or die (mysql_error());
mysql_selectdb(DBNAME,$dbh);

if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); } 
if ($_GET['action'] == "sendchat") { sendChat(); } 
if ($_GET['action'] == "closechat") { closeChat(); } 
if ($_GET['action'] == "startchatsession") { startChatSession(); } 

if (!isset($_SESSION['chatHistory'])) {
	$_SESSION['chatHistory'] = array();	
}

if (!isset($_SESSION['openChatBoxes'])) {
	$_SESSION['openChatBoxes'] = array();	
}

function chatHeartbeat() {
	
	$sql = "select * from chat where (chat.to = '".mysql_real_escape_string($_SESSION['username'])."' AND recd = 0) order by id ASC";
	$query = mysql_query($sql);
	$items = '';

	$chatBoxes = array();

	while ($chat = mysql_fetch_array($query)) {

		if (!isset($_SESSION['openChatBoxes'][$chat['from']]) && isset($_SESSION['chatHistory'][$chat['from']])) {
			$items = $_SESSION['chatHistory'][$chat['from']];
		}

		$chat['message'] = sanitize($chat['message']);

		$items .= <<<EOD
					   {
			"s": "0",
			"f": "{$chat['from']}",
			"m": "{$chat['message']}"
	   },
EOD;

	if (!isset($_SESSION['chatHistory'][$chat['from']])) {
		$_SESSION['chatHistory'][$chat['from']] = '';
	}

	$_SESSION['chatHistory'][$chat['from']] .= <<<EOD
						   {
			"s": "0",
			"f": "{$chat['from']}",
			"m": "{$chat['message']}"
	   },
EOD;
		
		unset($_SESSION['tsChatBoxes'][$chat['from']]);
		$_SESSION['openChatBoxes'][$chat['from']] = $chat['sent'];
	}

	if (!empty($_SESSION['openChatBoxes'])) {
	foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
		if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
			$now = time()-strtotime($time);
			$time = date('g:iA M dS', strtotime($time));

			$message = "Sent at $time";
			if ($now > 180) {
				$items .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;

	if (!isset($_SESSION['chatHistory'][$chatbox])) {
		$_SESSION['chatHistory'][$chatbox] = '';
	}

	$_SESSION['chatHistory'][$chatbox] .= <<<EOD
		{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;
			$_SESSION['tsChatBoxes'][$chatbox] = 1;
		}
		}
	}
}

	$sql = "update chat set recd = 1 where chat.to = '".mysql_real_escape_string($_SESSION['username'])."' and recd = 0";
	$query = mysql_query($sql);

	if ($items != '') {
		$items = substr($items, 0, -1);
	}
header('Content-type: application/json');
?>
{
		"items": [
			<?php echo $items;?>
        ]
}

<?php
			exit(0);
}

function chatBoxSession($chatbox) {
	
	$items = '';
	
	if (isset($_SESSION['chatHistory'][$chatbox])) {
		$items = $_SESSION['chatHistory'][$chatbox];
	}

	return $items;
}

function startChatSession() {
	$items = '';
	if (!empty($_SESSION['openChatBoxes'])) {
		foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
			$items .= chatBoxSession($chatbox);
		}
	}


	if ($items != '') {
		$items = substr($items, 0, -1);
	}

header('Content-type: application/json');
?>
{
		"username": "<?php echo $_SESSION['username'];?>",
		"items": [
			<?php echo $items;?>
        ]
}

<?php


	exit(0);
}

function sendChat() {
	$from = $_SESSION['username'];
	$to = $_POST['to'];
	$message = $_POST['message'];

	$_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());
	
	$messagesan = sanitize($message);

	if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
		$_SESSION['chatHistory'][$_POST['to']] = '';
	}

	$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
					   {
			"s": "1",
			"f": "{$to}",
			"m": "{$messagesan}"
	   },
EOD;


	unset($_SESSION['tsChatBoxes'][$_POST['to']]);

	$sql = "insert into chat (chat.from,chat.to,message,sent) values ('".mysql_real_escape_string($from)."', '".mysql_real_escape_string($to)."','".mysql_real_escape_string($message)."',NOW())";
	$query = mysql_query($sql);
	echo "1";
	exit(0);
}

function closeChat() {

	unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);
	
	echo "1";
	exit(0);
}

function sanitize($text) {
	$text = htmlspecialchars($text, ENT_QUOTES);
	$text = str_replace("\n\r","\n",$text);
	$text = str_replace("\r\n","\n",$text);
	$text = str_replace("\n","<br>",$text);
	return $text;
}

Опитвам се да го преработя, така че да мога да го интегрирам в сайта си, но не искам да използвам сесии - изцяло да се прехвърли към база данните.

Ето какво сглобих до момента:

PHP:
$action = $_GET['action'];
switch($action)
{
	case 'chatheartbeat';
	exit;
		echo Chat_Heartbeat();
		exit;
	
	case 'sendchat';
		Chat_SendMessage();
		exit;
	
	case 'startchatsession';
		echo Chat_SessionStart();
		exit;
}

function Chat_SendMessage()
{
	global $context;
	
	$from = $context['member']['u_id'];
	
	$Param['pm_subject'] = 'test';
	$Param['pm_id_member_from'] = $context['member']['u_id'];
	list($Param['pm_id_member_to']) = db_query(__FILE__, __LINE__, 'SELECT `u_id` FROM `[sql_database]`.`[sql_prefix]users` WHERE `u_display_name` = "[to]" LIMIT 1', array('to' => $context['POST']['to']), 'FETCH_ROW');
	$Param['pm_topic_id'] = create_pm_topic_id($Param['pm_id_member_from'], $Param['pm_id_member_to']);
	$Param['pm_sender_ip'] = $_SERVER['REMOTE_ADDR'];
	$Param['pm_ctime'] = $context['thetime'];
	$Param['pm_content'] = sanitize($context['POST']['message']);
	db_query(__FILE__, __LINE__, 'INSERT INTO `[sql_database]`.`[sql_prefix]personal_messages` (`pm_topic_id`, `pm_subject`, `pm_id_member_from`, `pm_id_member_to`, `pm_sender_ip`, `pm_ctime`, `pm_content`) VALUES ("[pm_topic_id]", "[pm_subject]", [pm_id_member_from], [pm_id_member_to], "[pm_sender_ip]", [pm_ctime], "[pm_content]")', $Param);
}

function Chat_Heartbeat()
{
	global $context;
	
	$Results = db_query(__FILE__, __LINE__, 'SELECT * FROM `[sql_database]`.`[sql_prefix]personal_messages` WHERE `pm_id_member_from` = 1 AND `pm_is_read` = 0', array('me' => $context['member']['u_id']), 'FETCH_ALL');
	$items = NULL;
	foreach($Results['results'] as $R)
	{
		
	}
}

function Chat_SessionStart()
{
	global $context;
	
	$Results = db_query(__FILE__, __LINE__, 'SELECT * FROM `[sql_database]`.`[sql_prefix]personal_messages`', array(), 'FETCH_ALL');
	foreach($Results['results'] as $R)
	{
		$items[] = json_encode(array('s' => '2', 'f' => 'Wicked', 'm' => $R['pm_content']));
	}
	
	header('Content-type: application/json');
	$array['userid'] = $context['member']['u_id'];
	$array['username'] = $context['member']['u_display_name'];
	$array['items'] = $items;
	return json_encode($array);
}

function create_pm_topic_id($user1, $user2)
{
	if($user1 > $user2)
	{
		$a = $user2;
		$b = $user1;
	}
	else
	{
		$a = $user1;
		$b = $user2;
	}
	
	return sprintf('%d-%d', $a, $b);
}

function sanitize($text) {
	$text = htmlspecialchars($text, ENT_QUOTES);
	$text = str_replace("\n\r","\n",$text);
	$text = str_replace("\r\n","\n",$text);
	$text = str_replace("\n","<br />",$text);
	return $text;
}

Но нещо не работи.. Часове наред вече си блъскам главата и не става и не става.. Дано успеете да помогнете, мерси.
 

Горе