From 83064f9c2407aa37982e8f991bc637e58d3d25a6 Mon Sep 17 00:00:00 2001 From: dongsheng Date: Sat, 5 Sep 2009 18:41:25 +0000 Subject: [PATCH] "MDL-14651, improve ajax chat module" --- mod/chat/chat.css | 44 +++++++ mod/chat/chat_ajax.php | 175 ++++++++++++++++++++++++++ mod/chat/gui_ajax/common.php | 68 ----------- mod/chat/gui_ajax/index.php | 71 ++++++----- mod/chat/gui_ajax/post.php | 59 --------- mod/chat/gui_ajax/script.js | 230 ++++++++++++++++++++--------------- mod/chat/gui_ajax/update.php | 157 ------------------------ mod/chat/lib.php | 119 ++++++++++++------ 8 files changed, 472 insertions(+), 451 deletions(-) create mode 100644 mod/chat/chat.css create mode 100644 mod/chat/chat_ajax.php delete mode 100755 mod/chat/gui_ajax/common.php delete mode 100755 mod/chat/gui_ajax/post.php delete mode 100755 mod/chat/gui_ajax/update.php diff --git a/mod/chat/chat.css b/mod/chat/chat.css new file mode 100644 index 0000000000..1ac39cbe7a --- /dev/null +++ b/mod/chat/chat.css @@ -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; +} diff --git a/mod/chat/chat_ajax.php b/mod/chat/chat_ajax.php new file mode 100644 index 0000000000..0112f634fd --- /dev/null +++ b/mod/chat/chat_ajax.php @@ -0,0 +1,175 @@ +. + +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; +} diff --git a/mod/chat/gui_ajax/common.php b/mod/chat/gui_ajax/common.php deleted file mode 100755 index f9ac61428c..0000000000 --- a/mod/chat/gui_ajax/common.php +++ /dev/null @@ -1,68 +0,0 @@ -wwwroot.'/user/view.php?id='.$v->id.'&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)); - } -} diff --git a/mod/chat/gui_ajax/index.php b/mod/chat/gui_ajax/index.php index 2c35bfc6cb..9deed34827 100644 --- a/mod/chat/gui_ajax/index.php +++ b/mod/chat/gui_ajax/index.php @@ -1,7 +1,6 @@ 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 << -#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} - -STY; +echo $OUTPUT->heading($str_title, 1); +$intro = format_text($chat->intro, $chat->introformat); -echo $OUTPUT->heading($str_title,1); echo << +
+{$chat->name} {$intro}
-
- - -
-
-
    +
    +
      +
    -
    -
      -
        +
        +
        +
          +
        • +
            +
        +
        +
        + +
        diff --git a/mod/chat/gui_ajax/post.php b/mod/chat/gui_ajax/post.php deleted file mode 100755 index 1989783179..0000000000 --- a/mod/chat/gui_ajax/post.php +++ /dev/null @@ -1,59 +0,0 @@ -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(); -} diff --git a/mod/chat/gui_ajax/script.js b/mod/chat/gui_ajax/script.js index 9639581a68..64fe33faba 100644 --- a/mod/chat/gui_ajax/script.js +++ b/mod/chat/gui_ajax/script.js @@ -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 += '
        ' + users[i].picture + '' - html += ''+ users[i].name+'
        '; - html += '
        Talk '; - html += 'Beep'; - html += '
        '; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += '
        ' + users[i].picture + ''; + html += ' '+ users[i].name+'
        '; + html += '
        '+mstr.chat.talk+' '; + html += ' '+mstr.chat.beep+''; + html += '
        '; 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 = ''; } list.appendChild(item); + if (!row) { + var anim = new YAHOO.util.ColorAnim(item.id, YAHOO.moodle.chat.oddmsg_cfg); + anim.animate(); + } + if (msg.mymessage) { + //var anim = new YAHOO.util.ColorAnim(item.id, YAHOO.moodle.chat.mymsg_cfg); + //anim.animate(); + } } -var update_cb = { -success: function(o){ - try { - if(o.responseText){ - var data = YAHOO.lang.JSON.parse(o.responseText); - } else { + +YAHOO.moodle.chat.update_cb = { + success: function(o){ + var data = json_decode(o.responseText); + if (!data) { return; } - } catch(e) { - alert('json invalid'); - alert(o.responseText); - return; - } - if(data.error) { - if(data.error.level == 'ERROR'){ - clearInterval(interval); - window.location = chat_cfg.home; + if(data.error) { + if(data.error.level == 'ERROR'){ + clearInterval(YAHOO.moodle.chat.interval); + window.location = chat_cfg.home; + } } - } - 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]); + 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 - 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(){ + // 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(); } } diff --git a/mod/chat/gui_ajax/update.php b/mod/chat/gui_ajax/update.php deleted file mode 100755 index 51bbe0c4b7..0000000000 --- a/mod/chat/gui_ajax/update.php +++ /dev/null @@ -1,157 +0,0 @@ -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; diff --git a/mod/chat/lib.php b/mod/chat/lib.php index d528e8039c..325656233e 100644 --- a/mod/chat/lib.php +++ b/mod/chat/lib.php @@ -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 ( is used to get some browsers starting with output global $CHAT_HTMLHEAD; $CHAT_HTMLHEAD = "\n\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 = "wwwroot/user/view.php?id=$sender->id&course=$courseid')\" href=\"$CFG->wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture"; + if (empty($courseid)) { + $courseid = $COURSE->id; } + $message->picture = "wwwroot/user/view.php?id=$sender->id&course=$courseid\">$message->picture"; //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 = '
        '.$message->picture.''; - $output->html .= ''.$output->text.'
        '; - $output->basic = '
        '.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'
        '; + $result->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)); + + $result->html = '
        '; + $result->html .= ''.$message->strtime.' '; + $userlink = "wwwroot/user/view.php?id=$sender->id&course=$courseid\">".fullname($sender).""; + $result->html .= ''.get_string('message'.$message->message, 'chat', $userlink).' '; + $result->html .= '
        '; + + $result->basic = '
        '.$message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender)).'
        '; 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 = '*** '.$sender->firstname.' '.substr($text, 4).''; 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').' '.$matches[1].': '.$matches[2]; + $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' '.$matches[1].': '.$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 = "
        $message->picture"; - $output->html = "
        $message->picture"; - $output->html .= "$outinfo"; - if ($outmain) { - $output->html .= ": $outmain"; - $output->basic = '
        '.$outinfo.':
        '.$outmain.'
        '; + $result->html .= "[{$outtime}] "; + if(!$special) { + $result->html .= "{$sender->firstname}"; + $result->html .= ": $outmain"; } else { - $output->basic = '
        '.$outinfo.'
        '; + $result->html .= "$outmain"; } - $output->html .= "
        "; - return $output; + $result->html .= "
        "; + + $result->basic = '
        '; + $result->basic .= '['.$outtime.'] '; + $result->basic .= ''.$sender->firstname.''; + $result->basic .= ': '; + $result->basic .= '
        '; + $result->basic .= '
        '.$outmain.'
        '; + $result->basic .= '
        '; + + 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.'&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 */ -- 2.39.5