"MDL-14651, improve ajax chat module"

This commit is contained in:
dongsheng 2009-09-05 18:41:25 +00:00
parent 1a3f83348d
commit 83064f9c24
8 changed files with 473 additions and 452 deletions

44
mod/chat/chat.css Normal file
View File

@ -0,0 +1,44 @@
#messages-list, #users-list{list-style-type:none;padding:0;margin:0}
#chat-header {
background: transparent;
font-size: 200%;
overflow: hidden;
}
#chat-header p {
display:inline;
font-size: 50%;
color: grey;
}
.time{
font-weight: bold;
}
.user{
color:blue;
}
.chat-event{
text-align:center;
color:grey;
}
.yui-skin-sam .yui-layout .yui-layout-unit div.yui-layout-bd {
background: transparent;
}
.yui-layout-unit-top {
background: #FFE39D;
}
.yui-layout-unit-right {
border-top: 5px solid white;
background: #FFD46B;
}
.yui-layout-unit-bottom {
border-top: 5px solid white;
background: #FFCB44;
}
.yui-skin-sam .yui-layout .yui-layout-unit div.yui-layout-unit-right {
background: white;
}
.yui-skin-sam .yui-layout .yui-layout-unit div.yui-layout-bd {
border:0;
}
.yui-skin-sam .yui-layout .yui-layout-hd {
border:0;
}

175
mod/chat/chat_ajax.php Normal file
View File

@ -0,0 +1,175 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
require_once(dirname(__FILE__) . '/lib.php');
$action = optional_param('action', '', PARAM_ALPHANUM);
$beep_id = optional_param('beep', '', PARAM_RAW);
$chat_sid = required_param('chat_sid', PARAM_ALPHANUM);
$chat_message = optional_param('chat_message', '', PARAM_RAW);
$chat_lasttime = optional_param('chat_lasttime', 0, PARAM_INT);
$chat_lastrow = optional_param('chat_lastrow', 1, PARAM_INT);
if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
if (!$chat = $DB->get_record('chat', array('id'=>$chatuser->chatid))) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
if (!$course = $DB->get_record('course', array('id'=>$chat->course))) {
chat_print_error('ERROR', get_string('invaliduserid', 'error'));
}
if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
if (isguest()) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
// setup $PAGE so that format_text will work properly
$PAGE->set_cm($cm, $course, $chat);
ob_start();
header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html; charset=utf-8');
header('X-Powered-By: MOODLE-Chat-V2');
switch ($action) {
case 'init':
if($CFG->chat_use_cache){
$cache = new file_cache();
$users = $cache->get('user');
if(empty($users)) {
$users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
$cache->set('user', $users);
}
} else {
$users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
}
$users = chat_format_userlist($users, $course);
$response['users'] = $users;
echo json_encode($response);
break;
case 'chat':
session_get_instance()->write_close();
chat_delete_old_users();
$chat_message = clean_text($chat_message, FORMAT_MOODLE);
if (!empty($beep_id)) {
$chat_message = 'beep '.$beep_id;
}
if (!empty($chat_message)) {
$message = new object();
$message->chatid = $chatuser->chatid;
$message->userid = $chatuser->userid;
$message->groupid = $chatuser->groupid;
$message->message = $chat_message;
$message->timestamp = time();
$chatuser->lastmessageping = time() - 2;
$DB->update_record('chat_users', $chatuser);
if (!($DB->insert_record('chat_messages', $message) && $DB->insert_record('chat_messages_current', $message))) {
chat_print_error('ERROR', get_string('cantlogin','chat'));
} else {
echo 200;
}
add_to_log($course->id, 'chat', 'talk', "view.php?id=$cm->id", $chat->id, $cm->id);
ob_end_flush();
}
break;
case 'update':
if ((time() - $chat_lasttime) > $CFG->chat_old_ping) {
chat_delete_old_users();
}
if ($latest_message = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
$chat_newlasttime = $latest_message->timestamp;
} else {
$chat_newlasttime = 0;
}
if ($chat_lasttime == 0) {
$chat_lasttime = time() - $CFG->chat_old_ping;
}
$params = array('groupid'=>$chatuser->groupid, 'chatid'=>$chatuser->chatid, 'lasttime'=>$chat_lasttime);
$groupselect = $chatuser->groupid ? " AND (groupid=".$chatuser->groupid." OR groupid=0) " : "";
$messages = $DB->get_records_select('chat_messages_current',
'chatid = :chatid AND timestamp > :lasttime '.$groupselect, $params,
'timestamp ASC');
if (!empty($messages)) {
$num = count($messages);
} else {
$num = 0;
}
$chat_newrow = ($chat_lastrow + $num) % 2;
$send_user_list = false;
if ($messages && ($chat_lasttime != $chat_newlasttime)) {
foreach ($messages as $n => &$message) {
$tmp = new stdclass;
// when somebody enter room, user list will be updated
if($message->system == 1){
$send_user_list = true;
$tmp->type = 'system';
$users = chat_format_userlist(chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid), $course);
}
if ($html = chat_format_message($message, $chatuser->course, $USER, $chat_lastrow)) {
if ($html->beep) {
$tmp->type = 'beep';
} elseif (empty($tmp->type)) {
$tmp->type = 'user';
}
$tmp->mymessage = ($USER->id == $message->userid);
$tmp->msg = $html->html;
$message = $tmp;
} else {
unset($message);
}
}
}
if(!empty($users) && $send_user_list){
// return users when system message coming
$response['users'] = $users;
}
$DB->set_field('chat_users', 'lastping', time(), array('id'=>$chatuser->id));
$response['lasttime'] = $chat_newlasttime;
$response['lastrow'] = $chat_newrow;
if($messages){
$response['msgs'] = $messages;
}
echo json_encode($response);
header('Content-Length: ' . ob_get_length() );
ob_end_flush();
break;
default:
break;
}

View File

@ -1,68 +0,0 @@
<?php
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec+(float)$sec);
}
function format_user_list($data, $course) {
global $CFG, $DB, $COURSE, $OUTPUT;
$users = array();
foreach($data as $v){
$user['name'] = fullname($v);
$user['url'] = $CFG->wwwroot.'/user/view.php?id='.$v->id.'&amp;course='.$course->id;
$user['picture'] = $OUTPUT->user_picture(moodle_user_picture::make($v, $COURSE->id));
$user['id'] = $v->id;
$users[] = $user;
}
return $users;
}
function chat_print_error($level, $msg) {
header('Content-Length: ' . ob_get_length() );
$error = new stdclass;
$error->level = $level;
$error->msg = $msg;
$response['error'] = $error;
echo json_encode($response);
ob_end_flush();
exit;
}
class file_cache{
private $dir = '';
public function __construct($dir='/dev/shm'){
$this->dir = $dir.'/chat_cache';
if(!is_dir($this->dir)) {
// create cache folder
if(mkdir($this->dir, 777)) {
$this->write('test', 'Deny from all');
}
}
}
private function write($name, $content){
$name = $this->dir.'/'.$name.'.data';
if (file_exists($name)) {
unlink($name);
}
$fp = fopen($name, 'w');
if($fp) {
fputs($fp, $content);
fclose($fp);
}
}
public function get($name){
$content = '';
$fp = fopen($this->dir.'/'.$name.'.data', 'r');
if ($fp){
while(!feof($fp))
$content .= fread($fp, 4096);
fclose($fp);
return unserialize($content);
} else {
return false;
}
}
public function set($name, $content){
$this->write($name, serialize($content));
}
}

View File

@ -1,7 +1,6 @@
<?php
require_once('../../../config.php');
require_once('../lib.php');
require_once('common.php');
$id = required_param('id', PARAM_INT);
$groupid = optional_param('groupid', 0, PARAM_INT); //only for teachers
if (!$chat = $DB->get_record('chat', array('id'=>$id))) {
@ -46,17 +45,11 @@ if (!$chat_sid = chat_login_user($chat->id, 'ajax', $groupid, $course)) {
print_error('cantlogin', 'chat');
}
// language string
$str_chat = get_string('modulename', 'chat'); // must be before current_language() in chat_login_user() to force course language!!!
$str_send = get_string('send', 'chat');
$str_sending = get_string('sending', 'chat');
$str_title = format_string($course->shortname) . ": ".format_string($chat->name,true).$groupname;
$str_inputarea = get_string('inputarea', 'chat');
$str_userlist = get_string('userlist', 'chat');
$str_title = format_string($course->shortname) . ": ".format_string($chat->name,true).$groupname;
$str_send = get_string('send', 'chat');
$PAGE->set_generaltype('popup');
$PAGE->set_title('Chat');
$PAGE->requires->yui_lib('dragdrop');
$PAGE->requires->yui_lib('resize');
$PAGE->requires->yui_lib('layout');
@ -65,39 +58,55 @@ $PAGE->requires->yui_lib('connection');
$PAGE->requires->yui_lib('json');
$PAGE->requires->yui_lib('button');
$PAGE->requires->yui_lib('selector');
$PAGE->requires->data_for_js('chat_cfg', array('home'=>$CFG->httpswwwroot.'/mod/chat/view.php?id='.$cm->id, 'userid'=>$USER->id, 'sid'=>$chat_sid,'timer'=>5000, 'chat_lasttime'=>0,'chat_lastrow'=>null,'header_title'=>$str_chat,'chatroom_name'=>$str_title));
$PAGE->requires->data_for_js('chat_lang', array('send'=>$str_send, 'sending'=>$str_sending, 'inputarea'=>$str_inputarea, 'userlist'=>$str_userlist));
$PAGE->requires->data_for_js('chat_cfg', array(
'home'=>$CFG->httpswwwroot.'/mod/chat/view.php?id='.$cm->id,
'userid'=>$USER->id,
'sid'=>$chat_sid,
'timer'=>5000,
'chat_lasttime'=>0,
'chat_lastrow'=>null,
'chatroom_name'=>$str_title
));
$PAGE->requires->string_for_js('send', 'chat');
$PAGE->requires->string_for_js('sending', 'chat');
$PAGE->requires->string_for_js('inputarea', 'chat');
$PAGE->requires->string_for_js('userlist', 'chat');
$PAGE->requires->string_for_js('modulename', 'chat');
$PAGE->requires->string_for_js('beep', 'chat');
$PAGE->requires->string_for_js('talk', 'chat');
$PAGE->requires->js('mod/chat/gui_ajax/script.js');
$PAGE->requires->yui_lib('animation')->in_head();
$PAGE->requires->css('mod/chat/chat.css');
$PAGE->add_body_class('yui-skin-sam');
echo $OUTPUT->header();
echo <<<STY
<style type='text/css'>
#messageslist{list-style-type:none;padding:0;margin:0}
#listing a{text-decoration:none;color:gray}
#listing a:hover {text-decoration:underline;color:white;background:blue}
#listing{padding: .5em}
h2{margin:0}
</style>
STY;
echo $OUTPUT->heading($str_title, 1);
$intro = format_text($chat->intro, $chat->introformat);
echo $OUTPUT->heading($str_title,1);
echo <<<DIVS
<div id="chat_header">
<div id="chat-header">
{$chat->name} {$intro}
</div>
<div id="chat_input">
<input type="text" id="input_msgbox" value="" size="48" />
<input type="button" id="btn_send" value="$str_send" />
</div>
<div id="chat_user_list">
<ul id="listing">
<div id="chat-userlist">
<ul id="users-list">
<li></li>
</ul>
</div>
<div id="chat_options">
</div>
<div id="chat_panel">
<ul id="messageslist">
<ul>
<div id="chat-messages">
<div>
<ul id="messages-list">
<li></li>
<ul>
</div>
</div>
<div id="chat-input">
<input type="text" id="input_msgbox" value="" size="70" />
<input type="button" id="btn_send" value="$str_send" />
</div>
<div id="notify">
</div>

View File

@ -1,59 +0,0 @@
<?php // $Id$
include('../../../config.php');
include('../lib.php');
ob_start();
header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html; charset=utf-8');
header('X-Powered-By: MOODLE-Chat-V2');
$chat_sid = required_param('chat_sid', PARAM_ALPHANUM);
$chat_message = optional_param('chat_message', '', PARAM_RAW);
$beep_id = optional_param('beep', '', PARAM_RAW);
if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
if (!$chat = $DB->get_record('chat', array('id'=>$chatuser->chatid))) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
if (!$course = $DB->get_record('course', array('id'=>$chat->course))) {
chat_print_error('ERROR', get_string('invaliduserid', 'error'));
}
if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
if (isguest()) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
session_get_instance()->write_close();
chat_delete_old_users();
$chat_message = clean_text($chat_message, FORMAT_MOODLE);
if (!empty($beep_id)) {
$chat_message = 'beep '.$beep_id;
}
if (!empty($chat_message)) {
$message = new object();
$message->chatid = $chatuser->chatid;
$message->userid = $chatuser->userid;
$message->groupid = $chatuser->groupid;
$message->message = $chat_message;
$message->timestamp = time();
$chatuser->lastmessageping = time() - 2;
$DB->update_record('chat_users', $chatuser);
if (!($DB->insert_record('chat_messages', $message) && $DB->insert_record('chat_messages_current', $message))) {
chat_print_error('ERROR', get_string('cantlogin','chat'));
} else {
echo 200;
}
add_to_log($course->id, 'chat', 'talk', "view.php?id=$cm->id", $chat->id, $cm->id);
ob_end_flush();
}

View File

@ -1,7 +1,11 @@
// record msg IDs
var msgs = [];
var interval = null;
var scrollable = true;
YAHOO.namespace('moodle.chat');
YAHOO.moodle.chat.api = moodle_cfg.wwwroot+'/mod/chat/chat_ajax.php';
YAHOO.moodle.chat.interval = null;
YAHOO.moodle.chat.chat_input_element = null;
YAHOO.moodle.chat.msgs = [];
YAHOO.moodle.chat.scrollable = true;
(function() {
var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event;
@ -10,11 +14,11 @@ Event.onDOMReady(function() {
// build layout
var layout = new YAHOO.widget.Layout({
units: [
{ position: 'top', height: 60, body: 'chat_header', header: chat_cfg.header_title, gutter: '5px', collapse: true, resize: false },
{ position: 'right', header: chat_lang.userlist, width: 180, resize: true, gutter: '5px', footer: null, collapse: true, scroll: true, body: 'chat_user_list', animate: false },
{ position: 'bottom', header: chat_lang.inputarea, height: 60, resize: true, body: 'chat_input', gutter: '5px', collapse: false, resize: false },
{ position: 'top', height: 50, body: 'chat-header', gutter: '5px', resize: false },
{ position: 'right', width: 180, resize: true, gutter: '5px', scroll: true, body: 'chat-userlist', animate: false },
{ position: 'bottom', height: 42, resize: false, body: 'chat-input', gutter: '5px', collapse: false, resize: false },
//{ position: 'left', header: 'Options', width: 200, resize: true, body: 'chat_options', gutter: '5px', collapse: true, close: true, collapseSize: 50, scroll: true, animate: false },
{ position: 'center', body: 'chat_panel', gutter: '5px', scroll: true }
{ position: 'center', body: 'chat-messages', gutter: '5px', scroll: true }
]
});
layout.on('render', function() {
@ -25,37 +29,45 @@ Event.onDOMReady(function() {
layout.render();
Event.on('btn_send', 'click', function(ev) {
Event.stopEvent(ev);
send_message();
YAHOO.moodle.chat.send_message();
});
Event.on('chat_panel', 'mouseover', function(ev) {
Event.on('chat-messages', 'mouseover', function(ev) {
Event.stopEvent(ev);
scrollable = false;
YAHOO.moodle.chat.scrollable = false;
});
Event.on('chat_panel', 'mouseout', function(ev) {
Event.on('chat-messages', 'mouseout', function(ev) {
Event.stopEvent(ev);
scrollable = true;
YAHOO.moodle.chat.scrollable = true;
});
var key_send = new YAHOO.util.KeyListener(document, { keys:13 }, {fn:send_message, correctScope:true });
key_send.enable();
document.getElementById('input_msgbox').focus();
YAHOO.moodle.chat.chat_input_element = document.getElementById('input_msgbox');
YAHOO.moodle.chat.chat_input_element.onkeypress = function(ev) {
var e = (ev)?ev:event;
if (e.keyCode == 13) {
YAHOO.moodle.chat.send_message();
}
}
document.title = chat_cfg.chatroom_name;
this.cb = {
success: function(o){
YAHOO.moodle.chat.chat_input_element.focus();
if(o.responseText){
var data = YAHOO.lang.JSON.parse(o.responseText);
} else {
return;
}
if (data.users) {
update_users(data.users);
YAHOO.moodle.chat.update_users(data.users);
}
}
}
var transaction = YAHOO.util.Connect.asyncRequest('POST', "update.php?chat_sid="+chat_cfg.sid+"&chat_init=1", this.cb, null);
interval = setInterval(function(){
update_messages();
var params = {};
params.action = 'init';
params.chat_init = 1;
params.chat_sid = chat_cfg.sid;
var trans = YAHOO.util.Connect.asyncRequest('POST', YAHOO.moodle.chat.api, this.cb, build_querystring(params));
YAHOO.moodle.chat.interval = setInterval(function(){
YAHOO.moodle.chat.update_messages();
}, chat_cfg.timer);
});
})();
@ -71,129 +83,151 @@ function in_array(f, t){
return a;
}
function talkto(name) {
YAHOO.moodle.chat.talkto = function(name) {
var msg = document.getElementById('input_msgbox');
msg.value = "To "+name+": ";
msg.focus();
}
function send_message() {
YAHOO.moodle.chat.send_callback = {
success: function(o) {
if(o.responseText == 200){
document.getElementById('btn_send').value = mstr.chat.send;
document.getElementById('input_msgbox').value = '';
}
clearInterval(YAHOO.moodle.chat.interval)
YAHOO.moodle.chat.update_messages();
YAHOO.moodle.chat.interval = setInterval(function(){
YAHOO.moodle.chat.update_messages();
}, chat_cfg.timer);
//document.getElementById('input_msgbox').focus();
}
}
YAHOO.moodle.chat.send_message = function(ev) {
var msg = document.getElementById('input_msgbox').value;
var el_send = document.getElementById('btn_send');
if (!msg) {
alert('Empty message not allowed');
return;
}
var url = 'post.php?chat_sid='+chat_cfg.sid;
el_send.value = chat_lang.sending;
var trans = YAHOO.util.Connect.asyncRequest('POST', url, send_cb, "chat_message="+msg);
}
function send_beep(id){
var url = 'post.php?chat_sid='+chat_cfg.sid;
var trans = YAHOO.util.Connect.asyncRequest('POST', url, send_cb, "beep="+id);
el_send.value = mstr.chat.sending;
var params = {};
params.chat_message=msg;
params.chat_sid=chat_cfg.sid;
var trans = YAHOO.util.Connect.asyncRequest('POST', YAHOO.moodle.chat.api+"?action=chat", YAHOO.moodle.chat.send_callback, build_querystring(params));
}
var send_cb = {
success: function(o) {
if(o.responseText == 200){
document.getElementById('btn_send').value = chat_lang.send;
document.getElementById('input_msgbox').value = '';
}
clearInterval(interval)
update_messages();
interval = setInterval(function(){
update_messages();
}, chat_cfg.timer);
document.getElementById('input_msgbox').focus();
}
YAHOO.moodle.chat.send_beep = function(user_id) {
var url = 'post.php?chat_sid='+chat_cfg.sid;
var params = {};
params.chat_sid = chat_cfg.sid;
params.beep=user_id;
var trans = YAHOO.util.Connect.asyncRequest('POST', YAHOO.moodle.chat.api+"?action=chat", YAHOO.moodle.chat.send_callback, build_querystring(params));
}
function update_users(users) {
YAHOO.moodle.chat.update_users = function(users) {
if(!users){
return;
}
var list = document.getElementById('listing');
var list = document.getElementById('users-list');
list.innerHTML = '';
var html = '';
for(var i in users){
var el = document.createElement('li');
html += '<table><tr><td>' + users[i].picture + '</td><td>'
html += '<a target="_blank" href="'+users[i].url+'">'+ users[i].name+'<br/>';
html += '<a href="###" onclick="talkto(\''+users[i].name+'\')">Talk</a> ';
html += '<a href="###" onclick="send_beep('+users[i].id+')">Beep</a>';
html += '</td></tr></table>';
html += '<table>';
html += '<tr>';
html += '<td>' + users[i].picture + '</td>';
html += '<td>';
html += ' <a target="_blank" href="'+users[i].url+'">'+ users[i].name+'<br/>';
html += ' <a href="###" onclick="YAHOO.moodle.chat.talkto(\''+users[i].name+'\')">'+mstr.chat.talk+'</a> ';
html += ' <a href="###" onclick="YAHOO.moodle.chat.send_beep('+users[i].id+')">'+mstr.chat.beep+'</a>';
html += '</td>';
html += '</tr>';
html += '</table>';
el.innerHTML = html;
list.appendChild(el);
}
}
function update_messages() {
YAHOO.moodle.chat.update_messages = function() {
if(!chat_cfg.req_count){
chat_cfg.req_count = 1;
} else {
chat_cfg.req_count++;
}
console.info('Update count: '+chat_cfg.req_count);
var url = "update.php?chat_sid="+chat_cfg.sid+"&chat_lasttime="+chat_cfg.chat_lasttime;
var params = {};
if(chat_cfg.chat_lastrow != null){
url += "&chat_lastrow="+chat_cfg.chat_lastrow;
params.chat_lastrow = chat_cfg.chat_lastrow;
}
var trans = YAHOO.util.Connect.asyncRequest('POST', url, update_cb, null);
params.chat_lasttime = chat_cfg.chat_lasttime;
params.chat_sid = chat_cfg.sid;
var trans = YAHOO.util.Connect.asyncRequest('POST', YAHOO.moodle.chat.api+"?action=update", YAHOO.moodle.chat.update_cb, build_querystring(params));
}
function append_msg(msg) {
var list = document.getElementById('messageslist');
YAHOO.moodle.chat.mymsg_cfg = {
color: { to: '#06e' },
backgroundColor: { to: '#e06' }
};
YAHOO.moodle.chat.oddmsg_cfg = {
color: { to: 'red' },
backgroundColor: { to: '#FFFFCC' }
};
YAHOO.moodle.chat.evenmsg_cfg = {
color: { to: 'blue' }
};
YAHOO.moodle.chat.append_msg = function(key, msg, row) {
var list = document.getElementById('messages-list');
var item = document.createElement('li');
console.info('New message:'+msg.msg);
item.id="mdl-chat-entry-"+key;
if (msg.mymessage) {
item.className = 'mdl-chat-my-entry';
} else {
item.className = 'mdl-chat-entry';
}
item.innerHTML = msg.msg;
if(msg.type && msg.type == 'beep'){
document.getElementById('notify').innerHTML = '<embed src="../beep.wav" autostart="true" hidden="true" name="beep" />';
}
list.appendChild(item);
}
var update_cb = {
success: function(o){
try {
if(o.responseText){
var data = YAHOO.lang.JSON.parse(o.responseText);
} else {
return;
}
} catch(e) {
alert('json invalid');
alert(o.responseText);
return;
if (!row) {
var anim = new YAHOO.util.ColorAnim(item.id, YAHOO.moodle.chat.oddmsg_cfg);
anim.animate();
}
if(data.error) {
if(data.error.level == 'ERROR'){
clearInterval(interval);
window.location = chat_cfg.home;
}
if (msg.mymessage) {
//var anim = new YAHOO.util.ColorAnim(item.id, YAHOO.moodle.chat.mymsg_cfg);
//anim.animate();
}
if(!data)
return false;
chat_cfg.chat_lasttime = data['lasttime'];
chat_cfg.chat_lastrow = data['lastrow'];
// update messages
for (key in data['msgs']){
if(!in_array(key, msgs)){
msgs.push(key);
append_msg(data['msgs'][key]);
}
}
// update users
update_users(data['users']);
// scroll to the bottom of the message list
if(scrollable){
document.getElementById('chat_panel').parentNode.scrollTop+=500;
}
}
}
// debug code
if(!console){
var console = {
info: function(){
},
log: function(){
YAHOO.moodle.chat.update_cb = {
success: function(o){
var data = json_decode(o.responseText);
if (!data) {
return;
}
if(data.error) {
if(data.error.level == 'ERROR'){
clearInterval(YAHOO.moodle.chat.interval);
window.location = chat_cfg.home;
}
}
chat_cfg.chat_lasttime = data['lasttime'];
chat_cfg.chat_lastrow = data['lastrow'];
// update messages
for (key in data['msgs']){
if(!in_array(key, YAHOO.moodle.chat.msgs)){
YAHOO.moodle.chat.msgs.push(key);
YAHOO.moodle.chat.append_msg(key, data['msgs'][key], data.lastrow);
}
}
// update users
YAHOO.moodle.chat.update_users(data['users']);
// scroll to the bottom of the message list
if(YAHOO.moodle.chat.scrollable){
document.getElementById('chat-messages').parentNode.scrollTop+=500;
}
YAHOO.moodle.chat.chat_input_element.focus();
}
}

View File

@ -1,157 +0,0 @@
<?php
/**
* Produce update data (json format)
* @version $Id$
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
define('NO_MOODLE_COOKIES', true); // session not used here
require_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/config.php');
require_once(dirname(dirname(__FILE__)) . '/lib.php');
require_once(dirname(__FILE__) . '/common.php');
ob_start();
header('Expires: Sun, 28 Dec 1997 09:32:45 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: text/html; charset=utf-8');
header('X-Powered-By: MOODLE-Chat-V2');
$time_start = microtime_float();
$chat_sid = required_param('chat_sid', PARAM_ALPHANUM);
$chat_init = optional_param('chat_init', 0, PARAM_INT);
$chat_lasttime = optional_param('chat_lasttime', 0, PARAM_INT);
$chat_lastrow = optional_param('chat_lastrow', 1, PARAM_INT);
$response = array();
if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) {
chat_print_error('ERROR', get_string('notlogged','chat'));
}
//Get the minimal course
if (!$course = $DB->get_record('course', array('id'=>$chatuser->course), 'id,theme,lang')) {
chat_print_error('ERROR', get_string('invalidcourseid', 'error'));
}
//Get the user theme and enough info to be used in chat_format_message() which passes it along to
if (!$USER = $DB->get_record('user', array('id'=>$chatuser->userid))) {
// no optimisation here, it would break again in future!
chat_print_error('ERROR', get_string('invaliduserid', 'error'));
}
if (!$chat = $DB->get_record('chat', array('id'=>$chatuser->chatid))) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
if (!$cm = get_coursemodule_from_instance('chat', $chatuser->chatid, $course->id)) {
chat_print_error('ERROR', get_string('invalidcoursemodule', 'error'));
}
// setup $PAGE so that format_text will work properly
$PAGE->set_cm($cm, $course, $chat);
if($CFG->chat_use_cache){
$cache = new file_cache();
$users = $cache->get('user');
if(empty($users)) {
$users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
$cache->set('user', $users);
}
} else {
$users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
}
$users = format_user_list($users, $course);
if(!empty($chat_init)) {
$response['users'] = $users;
echo json_encode($response);
exit;
}
// force deleting of timed out users if there is a silence in room or just entering
if ((time() - $chat_lasttime) > $CFG->chat_old_ping) {
// must be done before chat_get_latest_message!!!
chat_delete_old_users();
}
if ($latest_message = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
$chat_newlasttime = $latest_message->timestamp;
} else {
$chat_newlasttime = 0;
}
if ($chat_lasttime == 0) {
$chat_lasttime = time() - $CFG->chat_old_ping;
}
$params = array('groupid'=>$chatuser->groupid, 'chatid'=>$chatuser->chatid, 'lasttime'=>$chat_lasttime);
$groupselect = $chatuser->groupid ? " AND (groupid=".$chatuser->groupid." OR groupid=0) " : "";
$messages = $DB->get_records_select('chat_messages_current',
'chatid = :chatid AND timestamp > :lasttime '.$groupselect, $params,
'timestamp ASC');
if (!empty($messages)) {
$num = count($messages);
} else {
$num = 0;
}
$chat_newrow = ($chat_lastrow + $num) % 2;
$send_user_list = false;
if ($messages && ($chat_lasttime != $chat_newlasttime)) {
foreach ($messages as $n => &$message) {
$tmp = new stdclass;
// when somebody enter room, user list will be updated
if($message->system == 1){
$send_user_list = true;
$tmp->type = 'system';
$users = format_user_list(
chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid), $course);
}
if ($html = chat_format_message($message, $chatuser->course, $USER, $chat_lastrow)) {
if ($html->beep) {
$tmp->type = 'beep';
} elseif (empty($tmp->type)) {
$tmp->type = 'user';
}
$tmp->msg = $html->html;
$message = $tmp;
} else {
unset($message);
}
}
}
if(!empty($users) && $send_user_list){
// return users when system message coming
$response['users'] = $users;
}
$DB->set_field('chat_users', 'lastping', time(), array('id'=>$chatuser->id));
$response['lasttime'] = $chat_newlasttime;
$response['lastrow'] = $chat_newrow;
if($messages){
$response['msgs'] = $messages;
}
$time_end = microtime_float();
$time = $time_end - $time_start;
if(!empty($CFG->chat_ajax_debug)) {
$response['time'] = $time;
}
echo json_encode($response);
header('Content-Length: ' . ob_get_length() );
ob_end_flush();
exit;

View File

@ -26,9 +26,6 @@
/** Include portfoliolib.php */
require_once($CFG->libdir.'/portfoliolib.php');
$CFG->chat_ajax_debug = false;
$CFG->chat_use_cache = false;
// The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output
global $CHAT_HTMLHEAD;
$CHAT_HTMLHEAD = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head></head>\n<body>\n\n".padding(200);
@ -758,11 +755,11 @@ function chat_update_chat_times($chatid=0) {
* @return bool|string Returns HTML or false
*/
function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chat_lastrow=NULL) {
global $CFG, $USER, $OUTPUT;
global $CFG, $USER, $OUTPUT, $COURSE;
$output = new object();
$output->beep = false; // by default
$output->refreshusers = false; // by default
$result = new object();
$result->beep = false; // by default
$result->refreshusers = false; // by default
// Use get_user_timezone() to find the correct timezone for displaying this message:
// It's either the current user's timezone or else decided by some Moodle config setting
@ -778,9 +775,10 @@ function chat_format_message_manually($message, $courseid, $sender, $currentuser
$message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
$message->picture = $OUTPUT->user_picture(moodle_user_picture::make($sender, $courseid));
if ($courseid) {
$message->picture = "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid')\" href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
if (empty($courseid)) {
$courseid = $COURSE->id;
}
$message->picture = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
//Calculate the row class
if ($chat_lastrow !== NULL) {
@ -790,32 +788,35 @@ function chat_format_message_manually($message, $courseid, $sender, $currentuser
}
// Start processing the message
if(!empty($message->system)) {
// System event
$output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
$output->html = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td><td class="text">';
$output->html .= '<span class="event">'.$output->text.'</span></td></tr></table>';
$output->basic = '<dl><dt class="event">'.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'</dt></dl>';
$result->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
$result->html = '<div class="chat-event">';
$result->html .= '<span class="time">'.$message->strtime.'</span> ';
$userlink = "<a target='_blank' href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">".fullname($sender)."</a>";
$result->html .= '<span class="event">'.get_string('message'.$message->message, 'chat', $userlink).'</span> ';
$result->html .= '</div>';
$result->basic = '<dl><dt class="event">'.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'</dt></dl>';
if($message->message == 'exit' or $message->message == 'enter') {
$output->refreshusers = true; //force user panel refresh ASAP
$result->refreshusers = true; //force user panel refresh ASAP
}
return $output;
return $result;
}
// It's not a system event
$text = $message->message;
/// Parse the text to clean and filter it
$options = new object();
$options->para = false;
$text = format_text($text, FORMAT_MOODLE, $options, $courseid);
// And now check for special cases
$special = false;
$outtime = $message->strtime;
if (substr($text, 0, 5) == 'beep ') {
/// It's a beep!
@ -823,15 +824,13 @@ function chat_format_message_manually($message, $courseid, $sender, $currentuser
$beepwho = trim(substr($text, 5));
if ($beepwho == 'all') { // everyone
$outinfo = $message->strtime.': '.get_string('messagebeepseveryone', 'chat', fullname($sender));
$outmain = '';
$output->beep = true; // (eventually this should be set to
$outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
$result->beep = true; // (eventually this should be set to
// to a filename uploaded by the user)
} else if ($beepwho == $currentuser->id) { // current user
$outinfo = $message->strtime.': '.get_string('messagebeepsyou', 'chat', fullname($sender));
$outmain = '';
$output->beep = true;
$outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
$result->beep = true;
} else { //something is not caught?
return false;
@ -844,7 +843,6 @@ function chat_format_message_manually($message, $courseid, $sender, $currentuser
switch ($command){
case 'me':
$special = true;
$outinfo = $message->strtime;
$outmain = '*** <b>'.$sender->firstname.' '.substr($text, 4).'</b>';
break;
}
@ -852,29 +850,35 @@ function chat_format_message_manually($message, $courseid, $sender, $currentuser
$pattern = '#To[[:space:]](.*):(.*)#';
preg_match($pattern, trim($text), $matches);
$special = true;
$outinfo = $message->strtime;
$outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$matches[2];
$outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$matches[2];
}
if(!$special) {
$outinfo = $message->strtime.' '.$sender->firstname;
$outmain = $text;
}
/// Format the message as a small table
$result->text = strip_tags($outtime.': '.$outmain);
$output->text = strip_tags($outinfo.': '.$outmain);
$result->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
$output->html = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td><td class=\"text\">";
$output->html .= "<span class=\"title\">$outinfo</span>";
if ($outmain) {
$output->html .= ": $outmain";
$output->basic = '<dl><dt class="title">'.$outinfo.':</dt><dd class="text">'.$outmain.'</dd></dl>';
$result->html .= "<span class=\"time\">[{$outtime}]</span> ";
if(!$special) {
$result->html .= "<span class=\"user\">{$sender->firstname}</span>";
$result->html .= ": $outmain";
} else {
$output->basic = '<dl><dt class="title">'.$outinfo.'</dt></dl>';
$result->html .= "$outmain";
}
$output->html .= "</td></tr></table>";
return $output;
$result->html .= "</td></tr></table>";
$result->basic = '<dl><dt>';
$result->basic .= '<span cass="time">['.$outtime.']</span> ';
$result->basic .= '<span class="user">'.$sender->firstname.'</span>';
$result->basic .= ': ';
$result->basic .= '</dt>';
$result->basic .= '<dd class="text">'.$outmain.'</dd>';
$result->basic .= '</dl>';
return $result;
}
/**
@ -903,6 +907,45 @@ function chat_format_message($message, $courseid, $currentuser, $chat_lastrow=NU
return chat_format_message_manually($message, $courseid, $user, $currentuser, $chat_lastrow);
}
/**
* @global object $DB
* @global object $CFG
* @global object $COURSE
* @global object $OUTPUT
* @param object $users
* @param object $course
* @return array return formatted user list
*/
function chat_format_userlist($users, $course) {
global $CFG, $DB, $COURSE, $OUTPUT;
$result = array();
foreach($users as $user){
$item = array();
$item['name'] = fullname($user);
$item['url'] = $CFG->wwwroot.'/user/view.php?id='.$v->id.'&amp;course='.$course->id;
$item['picture'] = $OUTPUT->user_picture(moodle_user_picture::make($user, $COURSE->id));
$item['id'] = $user->id;
$result[] = $item;
}
return $result;
}
/**
* Print json format error
* @param string $level
* @param string $msg
*/
function chat_print_error($level, $msg) {
header('Content-Length: ' . ob_get_length() );
$error = new stdclass;
$error->level = $level;
$error->msg = $msg;
$response['error'] = $error;
echo json_encode($response);
ob_end_flush();
exit;
}
/**
* @return array
*/