Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?
class Chat{
	
	private $prefix;
	private $msg_life;
	private $mem;
	private $poll_duration;

	function __construct($prefix, $msg_life = 604800, $poll_duration = 50, $allow_creation = false){
		$this->prefix = $prefix;
		$this->msg_life = $msg_life;
		$this->poll_duration = $poll_duration;
		$this->mem = new Memcache;
		$this->mem->connect('localhost', 11211);
						
		if($this->mem->get($this->prefix.'chats_num') == false)
			if($allow_creation)
				$this->mem->set($this->prefix.'chats_num',0,0,$this->msg_life);
			else{
				unset($this);
				throw new Exception('Chat Group does not exist');
			}
	}
	
	function alive(){
		return !empty($this->mem);
	}
	
	function poll($last){
		$start = time();
		while($this->mem->get($this->prefix.'chats_num') <= $last && $start+$this->poll_duration > time())
			usleep(500000);
	
		$chats = array();
		$end = $this->mem->get($this->prefix.'chats_num');
		if($end - 10 > $last) $last = $end - 10;
	
		for($i=$last+1;$i<=$end;$i++){
		
			 $msg = $this->mem->get($this->prefix."chatmsg_$i");
			 $msg['index'] = $i;
			 //preg_match_all("//",$msg,$matches);
			 $chats[] = $msg;
		}
	
		return Chat::slashes($chats);
	}
	
	function post($name,$text){
		$this->mem = new Memcache;
		$this->mem->connect('localhost', 11211);
		$i = $this->mem->get($this->prefix.'chats_num') + 1;
		$msg = array(
				'name'=>substr($name,0,30),
				'text'=>substr($text,0,512),
				'time'=>time());
		$this->mem->set($this->prefix."chatmsg_$i",$msg,0,$this->msg_life);
		$this->mem->set($this->prefix.'chats_num',$i,0,$this->msg_life);
		return $i;
	}
	
	static function slashes($n){
		foreach($n as $k=>$v){
			foreach($v as $k1=>$v1){
				$n[$k][$k1] = stripslashes(htmlspecialchars($v1));
			}
		}
		return $n;
	}
}
?>