<?php
$chat = new chats;
class chats{
private $timestamp = 0;
private $action;
function chats(){
require 'databaseConfig.txt';
$this->timestamp = time();
mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die (mysql_error());
mysql_select_db(DATABASENAME);
$result = mysql_query("SHOW TABLES LIKE 'chat'");
if (mysql_num_rows($result) === 0){
$this->createDatabaseSchema();
}
$this->action = isset($_POST['action']) ? $_POST['action'] : 'getChatData';
$this->switchBoard();
}
function switchBoard(){
switch ($this->action){
case 'writeChatData':
if ($this->writeChatData()){
echo '1';
} else {
echo '0';
; }
break;
default:
echo $this->getChatData();
}
}
function buffer(& $result){
$temp = array();
while ($row = myqsl_fetch_assoc($result)){
$temp[] = $row;
}
return $temp;
}
function getChatData(){
$return ='';
$timestamp = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
if ($timestamp == 'null') $timestamp = 0;
$query = "Select chatID, chatPerson, chatTimestamp, chatText from chat where chatTimestamp > ? order by chatTimestamp DESC limit 50 ";
$result = mysql_query($query) or die(mysql_error());
$chats = buffer($result);
foreach ($chats as $chat){
$date = date('Y-m-d H:i:s', $chat['chatTimestamp']);
$chatText = nl2br($chat['chatText']);
$return .= <<<HTML
<tr>
<td id="{$chat['chatID']}">{$chat['chatPerson']}<br/>$date</td>
<td>{$chatText}</td>
</tr>
HTML;
}
if (empty($return)){
return 'none';
} else {
return json_encode(array('timestamp'=>$this->timestamp,'chatText'=>$return));
}
}
function writeChatData(){
$chatPerson = empty($_POST['chatPerson']) ? NULL : trim($_POST['chatPerson']);
$chatText = empty($_POST['chatText']) ? NULL : trim($_POST['chatText']);
if (empty($chatText) || empty($chatPerson)){
return false;
} else {
$query = "Insert into chat (chatTimestamp, chatPerson, chatText) values ('%s','%s','%s')";
$params = array(time(), $chatPerson, $chatText);
array_walk($params, 'mysql_real_escape_string');
$query = vsprintf($query, $params);
$result = mysql_query($query);
if (!$result){
echo mysql_error();
return false;
}
return true;
}
}
function createDatabaseSchema(){
$query = " CREATE TABLE chat (
chatID INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
chatTimestamp INT( 11 ) NOT NULL ,
chatPerson VARCHAR( 255 ) NOT NULL ,
chatText LONGTEXT NOT NULL
) ;
)";
mysql_query($query);
}
}
?>