<?php
/* Nulled by Wizzywig */
	
	include_once ("config.php");
	include_once ("includes/functions_notifications.php");
	include_once ("includes/functions_php.php");
	
	$time 			= time();
	$response 		= array();
	$messages 		= array();
	$notifications 	= array();
	$typing 		= array();
	$markup 		= "";
	$initialize 	= $_REQUEST['ai'];
	$hash_id 		= $_REQUEST['ah'];
	
	if (isset($_REQUEST['hb']) && is_numeric($_REQUEST['hb']) && $_REQUEST['hb'] >= 1)
		$heart_beat = $_REQUEST['hb'];
	else
		$heart_beat = 3;
		
	if (empty($_REQUEST['lp']))
		$long_polling = true;
	else
		$long_polling = false;
	
	$sql = "SELECT userid, last_message FROM arrowchat_status WHERE hash_id='".mysql_real_escape_string($hash_id)."'";
	$result = mysql_query($sql);
	if ($result && mysql_num_rows($result) > 0) {
		$row = mysql_fetch_array($result);
		$last_message 	= $row['last_message'];
		$userid 		= $row['userid'];
	} else {
		$userid = 0;
	}
	
	if ($initialize == 1) {
		session_start();
		if (isset($_SESSION['notifications']))
			unset($_SESSION['notifications']);
		if (isset($_SESSION['tab_alert']))
			unset($_SESSION['tab_alert']);
		if (isset($_SESSION['typing']))
			unset($_SESSION['typing']);
		if (isset($_SESSION['not_typing']))
			unset($_SESSION['not_typing']);
		session_write_close();
	}
	
	function getNotifications() {
		global $response;
		global $userid;
		global $db;
		global $notifications;
		global $markup;
			
		$sql = "SELECT * 
			FROM arrowchat_notifications 
			WHERE to_id='".$userid."' 
				AND (alert_read != '1' OR user_read != '1') 
			ORDER BY alert_time DESC";
		$result = mysql_query($sql);
		
		
		while ($row = mysql_fetch_array($result)) {
			$alert_id		= $row['id'];
			$author_id 		= $row['author_id'];
			$author_name 	= $row['author_name'];
			$type 			= $row['type'];
			$message_time	= $row['alert_time'];
			$test = true;
			
			if (isset($_SESSION['notifications'])) {
				foreach ($_SESSION['notifications'] as $vals) {
					if (in_array($alert_id, $vals)) {
						$test = false;
					}
				}
			}
			
			if ($test || !isset($_SESSION['notifications'])) {
				$markup = getMarkup($author_id, $author_name, $type, $message_time);
				
				$sql = "UPDATE arrowchat_notifications
					SET alert_read='1'
					WHERE id='".$alert_id."'";
				mysql_query($sql);
				
				$notifications[] = array('alert_id' => $alert_id, 'markup' => $markup, 'type' => $type);
			}
			
			$_SESSION['notifications'][] = array($alert_id);

		}
		
			
		if (!empty($notifications)) {
			$response['notifications'] = $notifications;
		}
		
	}
	
	function updateUserSession() {
		global $userid;
		
		$sql = ("UPDATE arrowchat_status SET session_time = '".time()."' WHERE userid = '".mysql_real_escape_string($userid)."'");
		$query = mysql_query($sql);
	}
	
	function getTyping() {
		global $response;
		global $userid;
		global $typing;
		
		$sql = ("SELECT typing FROM arrowchat_status WHERE userid = '".mysql_real_escape_string($userid)."'");
		$result = mysql_query($sql);
		
		if (!isset($_SESSION['typing']))
			$_SESSION['typing'] = array();
		if (!isset($_SESSION['not_typing']))
			$_SESSION['not_typing'] = array();
		
		if ($result && mysql_num_rows($result) > 0) {
			
			$row = mysql_fetch_array($result);
			$old_data = $row['typing'];
			
			if (!empty($old_data)) {
			
				$matches = explode(":", $old_data);
				
				foreach ($matches as $val) {
				
					if (!empty($val)) {
				
						$typing_data = explode("/", $val);
						preg_match("#[0-9]+#", $typing_data[0], $typing_ids);
						$timer = $typing_data[1] + 60;
						if ($typing_data[1] == "0" || time() > $timer) {
							// If the user is not typing
							if (!in_array($typing_ids[0], $_SESSION['not_typing'])) {
								$typing[] = array('typing_id' => $typing_ids[0], 'is_typing' => '-1');
								$_SESSION['not_typing'][] = $typing_ids[0];
							}

							foreach ($_SESSION['typing'] as $index => $val) {
								if ($val == $typing_ids[0])
									unset($_SESSION['typing'][$index]);
							}
						} else {
							// If the user is typing
							if (!in_array($typing_ids[0], $_SESSION['typing'])) {
								$typing[] = array('typing_id' => $typing_ids[0], 'is_typing' => '1');
								$_SESSION['typing'][] = $typing_ids[0];
							}

							foreach ($_SESSION['not_typing'] as $index => $val) {
								if ($val == $typing_ids[0])
									unset($_SESSION['not_typing'][$index]);
							}
						}
						
					}
				
				}
			
			}
			
		}
		
		if (!empty($typing)) {
			$response['typing'] = $typing;
		}

	}
	
	function fetchMessages() {
		global $response;
		global $userid;
		global $messages;
		global $last_message;
		
		$sql = ("select arrowchat.id, arrowchat.from, arrowchat.to, arrowchat.message, arrowchat.sent, arrowchat.read, arrowchat.user_read from arrowchat where arrowchat.to = '".mysql_real_escape_string($userid)."' and (arrowchat.read != 1 || arrowchat.user_read != 1) order by arrowchat.id ASC");
		$query = mysql_query($sql);
		$time_it = time();
		$id_check = 0;
		$messages_test = false;
		
		if (!isset($_SESSION['tab_alert']))
			$_SESSION['tab_alert'] = array();
		
		while ($chat = mysql_fetch_array($query)) {
			$self = 0;
			$old = 0;
			if ($chat['from'] == $userid) {
				$chat['from'] = $chat['to'];
				$self = 1;
				$old = 1;
			}

			if ($chat['read'] == 1 && $chat['user_read'] == 1) {
				$old = 1;
			}
			
			$chatid = $chat['from'];
			if (!empty($last_message)) {
				if (preg_match("#:$chatid/[0-9]+#", $last_message, $matches)) {
					$matches2 = explode("/", $matches[0]);
					$num = (int)$matches2[1];
					$time_check = time();
					if ($num < $time_check) {
						$last_message = str_replace($matches[0], ":".$chatid."/".time()."", $last_message);
					} else {
						$last_message = $last_message;
					}
				} else {
					$last_message .= ":".$chatid."/".time();
				}
			} else {
				$last_message = ":".$chatid."/".time();
			}
			
			$chat_message = $chat['message'];
			$chat_message = str_replace("\\'", "'", $chat_message);
			$chat_message = str_replace('\\"', '"', $chat_message);
			$chat_message = makeClickableLinks($chat_message);

			if (!in_array($chat['id'], $_SESSION['tab_alert'])) {
				$messages[] = array('id' => $chat['id'], 'from' => $chat['from'], 'message' => $chat_message, 'self' => $self, 'old' => $old, 'sent' => $chat['sent']);
				$messages_test = true;
				$_SESSION['tab_alert'][] = $chat['id'];
			}
			
			$id_check = $chat['id'];
		}	
		
		if ($messages_test) {
			$response['messages'] = $messages;
			
			$sql = "UPDATE arrowchat SET arrowchat.read = '1' WHERE arrowchat.to = '".mysql_real_escape_string($userid)."' AND arrowchat.id <= '".mysql_real_escape_string($id_check)."'";
			mysql_query($sql);
				
			$sql = ("update arrowchat_status set last_message = '".$last_message."' where userid = '".mysql_real_escape_string($userid)."'");
			mysql_query($sql);
		}
	}
	
	$max_time = min(30, (int)ini_get("max_execution_time"));
	while ((time() - $time) < ($max_time- $heart_beat)) {
	
		if ($userid != 0) {
	
			updateUserSession();
			
			session_start();
			getTyping();
			getNotifications();
			fetchMessages();
			session_write_close();
			
			if (!empty($response) || !$long_polling) {
				
				header("Content-Type: text/plain");
				echo $_GET['callback'] . '(' . json_encode($response) . ');';
				flush();
				exit;
			}
		
		}
	
		sleep($heart_beat);
	}
	
	function makeClickableLinks($s) {
		return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $s);
	}

	header("Content-Type: text/plain");
	echo $_GET['callback'] . '(' . json_encode($response) . ');';
	flush();
	exit;
	
?>