<?php
/* Nulled by Wizzywig */
/***********تعريب***********/
/**          saher        **/
/**  منتديات شباب وصبايا  **/
/**   www.shababtop.com   **/
/**  saher1986@live.com   **/
/***************************/

// ########################## INCLUDE BACK-END ###########################
include_once ("data_core.php");

// ########################### INITILIZATION #############################
$response = array();
$messages = array();
$timestamp = time();

// ######################## START HISTROY RECEIVE ########################
if ($userid != 0) {
	if (!empty($_POST['chatbox'])) {
		$chatbox = $_POST['chatbox'];
		
		$sql = "UPDATE arrowchat 
			SET arrowchat.user_read='1' 
			WHERE arrowchat.from='".mysql_real_escape_string($chatbox)."' 
				AND arrowchat.to='".mysql_real_escape_string($userid)."' 
				AND arrowchat.user_read='0'";
		mysql_query($sql);
		
		$sql = "SELECT last_message FROM arrowchat_status WHERE userid='".mysql_real_escape_string($userid)."'";
		$result = mysql_query($sql);
		$row = mysql_fetch_array($result);
		$last_message = $row['last_message'];
		
		if (!empty($last_message)) {
			if (preg_match("#:$chatbox/[0-9]+#", $last_message, $matches)) {
				$matches2 = explode("/", $matches[0]);
				$time_check = (int)$matches2[1] - 3600;
			} else {
				$time_check = time() - 3600;
			}
		} else {
			$time_check = time() - 3600;
		}
		
		$sql = ("select arrowchat.id, arrowchat.from, arrowchat.to, arrowchat.message, arrowchat.sent, arrowchat.read from arrowchat where ((arrowchat.to = '".mysql_real_escape_string($userid)."' and arrowchat.from = '".mysql_real_escape_string($chatbox)."') or (arrowchat.from = '".mysql_real_escape_string($userid)."' and arrowchat.to = '".mysql_real_escape_string($chatbox)."')) and arrowchat.sent > ".$time_check." order by arrowchat.id");
		$query = mysql_query($sql);
	 
		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) {
				$old = 1;
			}
			
			$chat_message = $chat['message'];
			$chat_message = str_replace("\\'", "'", $chat_message);
			$chat_message = str_replace('\\"', '"', $chat_message);
			$chat_message = makeClickableLinks($chat_message);

			$messages[] = array('id' => $chat['id'], 'from' => $chat['from'], 'message' => $chat_message, 'self' => $self, 'old' => $old, 'sent' => $chat['sent']);

			$timestamp = $chat['id'];
		}	
		
	}
	if (!empty($messages)) {
		$response['messages'] = $messages;
	}
}

function makeClickableLinks($s) {
    return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $s);
}

header('Content-type: application/json; charset=utf-8');
echo json_encode($response);
exit;

?>