<?
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;
}
}
?>