From c52b4db52d24f50c4e3e9b5e381179f1793eec72 Mon Sep 17 00:00:00 2001 From: Andrew Davis Date: Wed, 23 Jul 2014 09:58:29 +0800 Subject: [PATCH] MDL-46465 mod_chat: assorted coding style fixes --- mod/chat/backup/moodle1/lib.php | 18 +- .../backup_chat_activity_task.class.php | 7 +- .../backup/moodle2/backup_chat_stepslib.php | 21 +- .../restore_chat_activity_task.class.php | 7 +- .../backup/moodle2/restore_chat_stepslib.php | 11 +- mod/chat/chat_ajax.php | 186 ++--- mod/chat/chatd.php | 656 ++++++++---------- mod/chat/db/access.php | 2 +- mod/chat/db/log.php | 13 +- mod/chat/db/upgrade.php | 56 +- mod/chat/gui_ajax/index.php | 70 +- mod/chat/gui_ajax/module.js | 63 +- mod/chat/gui_ajax/theme/bubble/config.php | 15 + mod/chat/gui_ajax/theme/compact/config.php | 15 + .../gui_ajax/theme/course_theme/config.php | 15 + mod/chat/gui_basic/index.php | 57 +- mod/chat/gui_header_js/chatinput.php | 55 +- mod/chat/gui_header_js/index.php | 37 +- mod/chat/gui_header_js/insert.php | 46 +- mod/chat/gui_header_js/jsupdate.php | 168 +++-- mod/chat/gui_header_js/jsupdated.php | 296 ++++---- mod/chat/gui_header_js/module.js | 9 +- mod/chat/gui_header_js/users.php | 69 +- mod/chat/gui_sockets/chat_gui_sockets.js | 4 +- mod/chat/gui_sockets/chatinput.php | 34 +- mod/chat/gui_sockets/index.php | 42 +- mod/chat/index.php | 42 +- mod/chat/lang/en/chat.php | 1 - mod/chat/lib.php | 393 +++++------ mod/chat/locallib.php | 9 +- mod/chat/mod_form.php | 31 +- mod/chat/renderer.php | 1 - mod/chat/report.php | 501 ++++++------- mod/chat/settings.php | 16 +- mod/chat/version.php | 6 +- mod/chat/view.php | 44 +- 36 files changed, 1601 insertions(+), 1415 deletions(-) diff --git a/mod/chat/backup/moodle1/lib.php b/mod/chat/backup/moodle1/lib.php index 86881b1f1f1..1e7d2a7dda8 100644 --- a/mod/chat/backup/moodle1/lib.php +++ b/mod/chat/backup/moodle1/lib.php @@ -1,5 +1,4 @@ get_cminfo($instanceid); $this->moduleid = $cminfo['id']; $contextid = $this->converter->get_contextid(CONTEXT_MODULE, $this->moduleid); - // replay the upgrade step 2010050101 + // Replay the upgrade step 2010050101. if ($CFG->texteditors !== 'textarea') { $data['intro'] = text_to_html($data['intro'], false, false, true); $data['introformat'] = FORMAT_HTML; } - // get a fresh new file manager for this instance + // Get a fresh new file manager for this instance. $this->fileman = $this->converter->get_file_manager($contextid, 'mod_chat'); - // convert course files embedded into the intro + // Convert course files embedded into the intro. $this->fileman->filearea = 'intro'; $this->fileman->itemid = 0; $data['intro'] = moodle1_converter::migrate_referenced_files($data['intro'], $this->fileman); - // start writing chat.xml + // Start writing chat.xml. $this->open_xml_writer("activities/chat_{$this->moduleid}/chat.xml"); $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $this->moduleid, 'modulename' => 'chat', 'contextid' => $contextid)); @@ -112,21 +111,20 @@ class moodle1_mod_chat_handler extends moodle1_mod_handler { * data available */ public function process_chat_message($data) { - //@todo process user data - //$this->write_xml('message', $data, array('/message/id')); + // MDL-46466 - Should this be empty? } /** * This is executed when we reach the closing tag of our 'chat' path */ public function on_chat_end() { - // close chat.xml + // Close chat.xml. $this->xmlwriter->end_tag('messages'); $this->xmlwriter->end_tag('chat'); $this->xmlwriter->end_tag('activity'); $this->close_xml_writer(); - // write inforef.xml + // Write inforef.xml. $this->open_xml_writer("activities/chat_{$this->moduleid}/inforef.xml"); $this->xmlwriter->begin_tag('inforef'); $this->xmlwriter->begin_tag('fileref'); diff --git a/mod/chat/backup/moodle2/backup_chat_activity_task.class.php b/mod/chat/backup/moodle2/backup_chat_activity_task.class.php index ca28c630da9..39ec9c8210f 100644 --- a/mod/chat/backup/moodle2/backup_chat_activity_task.class.php +++ b/mod/chat/backup/moodle2/backup_chat_activity_task.class.php @@ -1,5 +1,4 @@ wwwroot.'/mod/chat','#'); + $base = preg_quote($CFG->wwwroot . '/mod/chat', '#'); - //Link to the list of chats + // Link to the list of chats. $pattern = "#(".$base."\/index.php\?id\=)([0-9]+)#"; $content = preg_replace($pattern, '$@CHATINDEX*$2@$', $content); - //Link to chat view by moduleid + // Link to chat view by moduleid. $pattern = "#(".$base."\/view.php\?id\=)([0-9]+)#"; $content = preg_replace($pattern, '$@CHATVIEWBYID*$2@$', $content); diff --git a/mod/chat/backup/moodle2/backup_chat_stepslib.php b/mod/chat/backup/moodle2/backup_chat_stepslib.php index eb2fdb3bf4f..a6372218d39 100644 --- a/mod/chat/backup/moodle2/backup_chat_stepslib.php +++ b/mod/chat/backup/moodle2/backup_chat_stepslib.php @@ -1,5 +1,4 @@ get_setting_value('userinfo'); - // Define each element separated + // Define each element separated. $chat = new backup_nested_element('chat', array('id'), array( 'name', 'intro', 'introformat', 'keepdays', 'studentlogs', 'chattime', 'schedule', 'timemodified')); @@ -38,29 +37,29 @@ class backup_chat_activity_structure_step extends backup_activity_structure_step $message = new backup_nested_element('message', array('id'), array( 'userid', 'groupid', 'system', 'message_text', 'timestamp')); - // it is not cool to have two tags with same name, so we need to rename message field to message_text + // It is not cool to have two tags with same name, so we need to rename message field to message_text. $message->set_source_alias('message', 'message_text'); - // Build the tree + // Build the tree. $chat->add_child($messages); $messages->add_child($message); - // Define sources + // Define sources. $chat->set_source_table('chat', array('id' => backup::VAR_ACTIVITYID)); - // User related messages only happen if we are including user info + // User related messages only happen if we are including user info. if ($userinfo) { - $message->set_source_table('chat_messages', array('chatid'=>backup::VAR_PARENTID)); + $message->set_source_table('chat_messages', array('chatid' => backup::VAR_PARENTID)); } - // Define id annotations + // Define id annotations. $message->annotate_ids('user', 'userid'); $message->annotate_ids('group', 'groupid'); - // Annotate the file areas in chat module - $chat->annotate_files('mod_chat', 'intro', null); // chat_intro area don't use itemid + // Annotate the file areas in chat module. + $chat->annotate_files('mod_chat', 'intro', null); // The chat_intro area doesn't use itemid. - // Return the root element (chat), wrapped into standard activity structure + // Return the root element (chat), wrapped into standard activity structure. return $this->prepare_activity_structure($chat); } } diff --git a/mod/chat/backup/moodle2/restore_chat_activity_task.class.php b/mod/chat/backup/moodle2/restore_chat_activity_task.class.php index 0e578305fd8..d4f5af78027 100644 --- a/mod/chat/backup/moodle2/restore_chat_activity_task.class.php +++ b/mod/chat/backup/moodle2/restore_chat_activity_task.class.php @@ -1,5 +1,4 @@ dirroot . '/mod/chat/backup/moodle2/restore_chat_stepslib.php'); // Because it exists (must) +require_once($CFG->dirroot . '/mod/chat/backup/moodle2/restore_chat_stepslib.php'); /** * chat restore task that provides all the settings and steps to perform one @@ -36,14 +35,14 @@ class restore_chat_activity_task extends restore_activity_task { * Define (add) particular settings this activity can have */ protected function define_my_settings() { - // No particular settings for this activity + // No particular settings for this activity. } /** * Define (add) particular steps this activity can have */ protected function define_my_steps() { - // chat only has one structure step + // Chat only has one structure step. $this->add_step(new restore_chat_activity_structure_step('chat_structure', 'chat.xml')); } diff --git a/mod/chat/backup/moodle2/restore_chat_stepslib.php b/mod/chat/backup/moodle2/restore_chat_stepslib.php index 4b4e62a4157..582227f02b8 100644 --- a/mod/chat/backup/moodle2/restore_chat_stepslib.php +++ b/mod/chat/backup/moodle2/restore_chat_stepslib.php @@ -1,5 +1,4 @@ prepare_activity_structure($paths); } @@ -55,9 +54,9 @@ class restore_chat_activity_structure_step extends restore_activity_structure_st $data->chattime = $this->apply_date_offset($data->chattime); $data->timemodified = $this->apply_date_offset($data->timemodified); - // insert the chat record + // Insert the chat record. $newitemid = $DB->insert_record('chat', $data); - // immediately after inserting "activity" record, call this + // Immediately after inserting "activity" record, call this. $this->apply_activity_instance($newitemid); } @@ -73,11 +72,11 @@ class restore_chat_activity_structure_step extends restore_activity_structure_st $data->timestamp = $this->apply_date_offset($data->timestamp); $newitemid = $DB->insert_record('chat_messages', $data); - $this->set_mapping('chat_message', $oldid, $newitemid); // because of decode + $this->set_mapping('chat_message', $oldid, $newitemid); // Because of decode. } protected function after_execute() { - // Add chat related files, no need to match by itemname (just internally handled context) + // Add chat related files, no need to match by itemname (just internally handled context). $this->add_related_files('mod_chat', 'intro', null); } } diff --git a/mod/chat/chat_ajax.php b/mod/chat/chat_ajax.php index 378fd0cd83f..076371a7a52 100644 --- a/mod/chat/chat_ajax.php +++ b/mod/chat/chat_ajax.php @@ -20,24 +20,24 @@ 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); +$beepid = optional_param('beep', '', PARAM_RAW); +$chatsid = required_param('chat_sid', PARAM_ALPHANUM); $theme = required_param('theme', PARAM_ALPHANUMEXT); -$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); +$chatmessage = optional_param('chat_message', '', PARAM_RAW); +$chatlasttime = optional_param('chat_lasttime', 0, PARAM_INT); +$chatlastrow = optional_param('chat_lastrow', 1, PARAM_INT); if (!confirm_sesskey()) { throw new moodle_exception('invalidsesskey', 'error'); } -if (!$chatuser = $DB->get_record('chat_users', array('sid'=>$chat_sid))) { +if (!$chatuser = $DB->get_record('chat_users', array('sid' => $chatsid))) { throw new moodle_exception('notlogged', 'chat'); } -if (!$chat = $DB->get_record('chat', array('id'=>$chatuser->chatid))) { +if (!$chat = $DB->get_record('chat', array('id' => $chatuser->chatid))) { throw new moodle_exception('invaliduserid', 'error'); } -if (!$course = $DB->get_record('course', array('id'=>$chat->course))) { +if (!$course = $DB->get_record('course', array('id' => $chat->course))) { throw new moodle_exception('invalidcourseid', 'error'); } if (!$cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) { @@ -48,9 +48,9 @@ if (!isloggedin()) { throw new moodle_exception('notlogged', 'chat'); } -// setup $PAGE so that format_text will work properly +// Set up $PAGE so that format_text will work properly. $PAGE->set_cm($cm, $course, $chat); -$PAGE->set_url('/mod/chat/chat_ajax.php', array('chat_sid'=>$chat_sid)); +$PAGE->set_url('/mod/chat/chat_ajax.php', array('chat_sid' => $chatsid)); require_login($course, false, $cm); @@ -65,104 +65,104 @@ header('Pragma: no-cache'); header('Content-Type: text/html; charset=utf-8'); switch ($action) { -case 'init': - $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 'init': + $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': - \core\session\manager::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)) { - - chat_send_chatmessage($chatuser, $chat_message, 0, $cm); - - $chatuser->lastmessageping = time() - 2; - $DB->update_record('chat_users', $chatuser); - - // Response OK message. - echo json_encode(true); - ob_end_flush(); - } - break; - -case 'update': - if ((time() - $chat_lasttime) > $CFG->chat_old_ping) { + case 'chat': + \core\session\manager::write_close(); chat_delete_old_users(); - } + $chatmessage = clean_text($chatmessage, FORMAT_MOODLE); - if ($latest_message = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) { - $chat_newlasttime = $latest_message->timestamp; - } else { - $chat_newlasttime = 0; - } + if (!empty($beepid)) { + $chatmessage = 'beep '.$beepid; + } - if ($chat_lasttime == 0) { - $chat_lasttime = time() - $CFG->chat_old_ping; - } + if (!empty($chatmessage)) { - $params = array('groupid'=>$chatuser->groupid, 'chatid'=>$chatuser->chatid, 'lasttime'=>$chat_lasttime); + chat_send_chatmessage($chatuser, $chatmessage, 0, $cm); - $groupselect = $chatuser->groupid ? " AND (groupid=".$chatuser->groupid." OR groupid=0) " : ""; + $chatuser->lastmessageping = time() - 2; + $DB->update_record('chat_users', $chatuser); - $messages = $DB->get_records_select('chat_messages_current', - 'chatid = :chatid AND timestamp > :lasttime '.$groupselect, $params, - 'timestamp ASC'); + // Response OK message. + echo json_encode(true); + ob_end_flush(); + } + break; - 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 (!empty($message->system)){ - $send_user_list = true; - } - if ($html = chat_format_message_theme($message, $chatuser, $USER, $cm->groupingid, $theme)) { - $message->mymessage = ($USER->id == $message->userid); - $message->message = $html->html; - if (!empty($html->type)) { - $message->type = $html->type; + case 'update': + if ((time() - $chatlasttime) > $CFG->chat_old_ping) { + chat_delete_old_users(); + } + + if ($latestmessage = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) { + $chatnewlasttime = $latestmessage->timestamp; + } else { + $chatnewlasttime = 0; + } + + if ($chatlasttime == 0) { + $chatlasttime = time() - $CFG->chat_old_ping; + } + + $params = array('groupid' => $chatuser->groupid, 'chatid' => $chatuser->chatid, 'lasttime' => $chatlasttime); + + $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; + } + $chatnewrow = ($chatlastrow + $num) % 2; + $senduserlist = false; + if ($messages && ($chatlasttime != $chatnewlasttime)) { + foreach ($messages as $n => &$message) { + $tmp = new stdClass(); + // When somebody enter room, user list will be updated. + if (!empty($message->system)) { + $senduserlist = true; + } + if ($html = chat_format_message_theme($message, $chatuser, $USER, $cm->groupingid, $theme)) { + $message->mymessage = ($USER->id == $message->userid); + $message->message = $html->html; + if (!empty($html->type)) { + $message->type = $html->type; + } + } else { + unset($messages[$n]); } - } else { - unset($messages[$n]); } } - } - if($send_user_list){ - // return users when system message coming - $users = chat_format_userlist(chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid), $course); - $response['users'] = $users; - } + if ($senduserlist) { + // Return users when system message arrives. + $users = chat_format_userlist(chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid), $course); + $response['users'] = $users; + } - $DB->set_field('chat_users', 'lastping', time(), array('id'=>$chatuser->id)); + $DB->set_field('chat_users', 'lastping', time(), array('id' => $chatuser->id)); - $response['lasttime'] = $chat_newlasttime; - $response['lastrow'] = $chat_newrow; - if($messages){ - $response['msgs'] = $messages; - } + $response['lasttime'] = $chatnewlasttime; + $response['lastrow'] = $chatnewrow; + if ($messages) { + $response['msgs'] = $messages; + } - echo json_encode($response); - header('Content-Length: ' . ob_get_length() ); + echo json_encode($response); + header('Content-Length: ' . ob_get_length()); - ob_end_flush(); - break; + ob_end_flush(); + break; -default: - break; + default: + break; } diff --git a/mod/chat/chatd.php b/mod/chat/chatd.php index f7e0c1ed5fb..69b6a681d85 100644 --- a/mod/chat/chatd.php +++ b/mod/chat/chatd.php @@ -1,5 +1,4 @@ dirroot . '/mod/chat/lib.php'); -// Browser quirks +// Browser quirks. define('QUIRK_CHUNK_UPDATE', 0x0001); -// Connection telltale +// Connection telltale. define('CHAT_CONNECTION', 0x10); -// Connections: Incrementing sequence, 0x10 to 0x1f +// Connections: Incrementing sequence, 0x10 to 0x1f. define('CHAT_CONNECTION_CHANNEL', 0x11); -// Sidekick telltale +// Sidekick telltale. define('CHAT_SIDEKICK', 0x20); -// Sidekicks: Incrementing sequence, 0x21 to 0x2f +// Sidekicks: Incrementing sequence, 0x21 to 0x2f. define('CHAT_SIDEKICK_USERS', 0x21); define('CHAT_SIDEKICK_MESSAGE', 0x22); define('CHAT_SIDEKICK_BEEP', 0x23); @@ -46,9 +45,9 @@ define('CHAT_SIDEKICK_BEEP', 0x23); $phpversion = phpversion(); echo 'Moodle chat daemon v1.0 on PHP '.$phpversion."\n\n"; -/// Set up all the variables we need ///////////////////////////////////// +// Set up all the variables we need. -/// $CFG variables are now defined in database by chat/lib.php +// The $CFG variables are now defined in database by chat/lib.php. $_SERVER['PHP_SELF'] = 'dummy'; $_SERVER['SERVER_NAME'] = 'dummy'; @@ -61,48 +60,47 @@ core_php_time_limit::raise(0); error_reporting(E_ALL); function chat_empty_connection() { - return array('sid' => NULL, 'handle' => NULL, 'ip' => NULL, 'port' => NULL, 'groupid' => NULL); + return array('sid' => null, 'handle' => null, 'ip' => null, 'port' => null, 'groupid' => null); } class ChatConnection { - // Chat-related info - var $sid = NULL; - var $type = NULL; - //var $groupid = NULL; + // Chat-related info. + public $sid = null; + public $type = null; - // PHP-level info - var $handle = NULL; + // PHP-level info. + public $handle = null; - // TCP/IP - var $ip = NULL; - var $port = NULL; + // TCP/IP. + public $ip = null; + public $port = null; - function ChatConnection($resource) { + public function __construct($resource) { $this->handle = $resource; @socket_getpeername($this->handle, $this->ip, $this->port); } } class ChatDaemon { - var $_resetsocket = false; - var $_readytogo = false; - var $_logfile = false; - var $_trace_to_console = true; - var $_trace_to_stdout = true; - var $_logfile_name = 'chatd.log'; - var $_last_idle_poll = 0; + public $_resetsocket = false; + public $_readytogo = false; + public $_logfile = false; + public $_trace_to_console = true; + public $_trace_to_stdout = true; + public $_logfile_name = 'chatd.log'; + public $_last_idle_poll = 0; - var $conn_ufo = array(); // Connections not identified yet - var $conn_side = array(); // Sessions with sidekicks waiting for the main connection to be processed - var $conn_half = array(); // Sessions that have valid connections but not all of them - var $conn_sets = array(); // Sessions with complete connection sets sets - var $sets_info = array(); // Keyed by sessionid exactly like conn_sets, one of these for each of those - var $chatrooms = array(); // Keyed by chatid, holding arrays of data + public $connectionsunidentified = array(); // Connections not identified yet. + public $connectionsside = array(); // Sessions with sidekicks waiting for the main connection to be processed. + public $connectionshalf = array(); // Sessions that have valid connections but not all of them. + public $connectionssets = array(); // Sessions with complete connection sets. + public $setsinfo = array(); // Keyed by sessionid exactly like conn_sets, one of these for each of those. + public $chatrooms = array(); // Keyed by chatid, holding arrays of data. - // IMPORTANT: $conn_sets, $sets_info and $chatrooms must remain synchronized! + // IMPORTANT: $connectionssets, $setsinfo and $chatrooms must remain synchronized! // Pay extra attention when you write code that affects any of them! - function ChatDaemon() { + public function __construct() { $this->_trace_level = E_ALL ^ E_USER_NOTICE; $this->_pcntl_exists = function_exists('pcntl_fork'); $this->_time_rest_socket = 20; @@ -110,33 +108,34 @@ class ChatDaemon { $this->_freq_update_records = 20; $this->_freq_poll_idle_chat = $GLOBALS['CFG']->chat_old_ping; $this->_stdout = fopen('php://stdout', 'w'); - if($this->_stdout) { - // Avoid double traces for everything + if ($this->_stdout) { + // Avoid double traces for everything. $this->_trace_to_console = false; } } - function error_handler ($errno, $errmsg, $filename, $linenum, $vars) { - // Checks if an error needs to be suppressed due to @ - if(error_reporting() != 0) { + public function error_handler ($errno, $errmsg, $filename, $linenum, $vars) { + // Checks if an error needs to be suppressed due to @. + if (error_reporting() != 0) { $this->trace($errmsg.' on line '.$linenum, $errno); } return true; } - function poll_idle_chats($now) { + public function poll_idle_chats($now) { $this->trace('Polling chats to detect disconnected users'); - if(!empty($this->chatrooms)) { - foreach($this->chatrooms as $chatid => $chatroom) { - if(!empty($chatroom['users'])) { - foreach($chatroom['users'] as $sessionid => $userid) { - // We will be polling each user as required + if (!empty($this->chatrooms)) { + foreach ($this->chatrooms as $chatid => $chatroom) { + if (!empty($chatroom['users'])) { + foreach ($chatroom['users'] as $sessionid => $userid) { + // We will be polling each user as required. $this->trace('...shall we poll '.$sessionid.'?'); - if($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) { + if ($this->sets_info[$sessionid]['chatuser']->lastmessageping < $this->_last_idle_poll) { $this->trace('YES!'); - // This user hasn't been polled since his last message - if($this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], '') === false) { - // User appears to have disconnected + // This user hasn't been polled since his last message. + $result = $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], ''); + if ($result === false) { + // User appears to have disconnected. $this->disconnect_session($sessionid); } } @@ -147,76 +146,65 @@ class ChatDaemon { $this->_last_idle_poll = $now; } - function query_start() { + public function query_start() { return $this->_readytogo; } - function trace($message, $level = E_USER_NOTICE) { + public function trace($message, $level = E_USER_NOTICE) { $severity = ''; switch($level) { - case E_USER_WARNING: $severity = '*IMPORTANT* '; break; - case E_USER_ERROR: $severity = ' *CRITICAL* '; break; + case E_USER_WARNING: + $severity = '*IMPORTANT* '; + break; + case E_USER_ERROR: + $severity = ' *CRITICAL* '; + break; case E_NOTICE: - case E_WARNING: $severity = ' *CRITICAL* [php] '; break; + case E_WARNING: + $severity = ' *CRITICAL* [php] '; + break; } $date = date('[Y-m-d H:i:s] '); $message = $date.$severity.$message."\n"; if ($this->_trace_level & $level) { - // It is accepted for output + // It is accepted for output. - // Error-class traces go to STDERR too - if($level & E_USER_ERROR) { + // Error-class traces go to STDERR too. + if ($level & E_USER_ERROR) { fwrite(STDERR, $message); } - // Emit the message to wherever we should - if($this->_trace_to_stdout) { + // Emit the message to wherever we should. + if ($this->_trace_to_stdout) { fwrite($this->_stdout, $message); fflush($this->_stdout); } - if($this->_trace_to_console) { + if ($this->_trace_to_console) { echo $message; flush(); } - if($this->_logfile) { + if ($this->_logfile) { fwrite($this->_logfile, $message); fflush($this->_logfile); } } } - function write_data($connection, $text) { + public function write_data($connection, $text) { $written = @socket_write($connection, $text, strlen($text)); - if($written === false) { - // $this->trace("socket_write() failed: reason: " . socket_strerror(socket_last_error($connection))); + if ($written === false) { return false; } return true; - - // Enclosing the above code inside this blocks makes sure that - // "a socket write operation will not block". I 'm not so sure - // if this is needed, as we have a nonblocking socket anyway. - // If trouble starts to creep up, we 'll restore this. -// $check_socket = array($connection); -// $read = null; -// $except = null; -// $socket_changed = socket_select($read, $check_socket, $except, 0, 0); -// if($socket_changed > 0) { -// -// // ABOVE CODE GOES HERE -// -// } -// return false; } - function user_lazy_update($sessionid) { + public function user_lazy_update($sessionid) { global $DB; - // TODO: this can and should be written as a single UPDATE query - if(empty($this->sets_info[$sessionid])) { + if (empty($this->sets_info[$sessionid])) { $this->trace('user_lazy_update() called for an invalid SID: '.$sessionid, E_USER_WARNING); return false; } @@ -224,16 +212,16 @@ class ChatDaemon { $now = time(); // We 'll be cheating a little, and NOT updating the record data as - // often as we can, so that we save on DB queries (imagine MANY users) - if($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) { - // commit to permanent storage + // often as we can, so that we save on DB queries (imagine MANY users). + if ($now - $this->sets_info[$sessionid]['lastinfocommit'] > $this->_freq_update_records) { + // Commit to permanent storage. $this->sets_info[$sessionid]['lastinfocommit'] = $now; $DB->update_record('chat_users', $this->sets_info[$sessionid]['chatuser']); } return true; } - function get_user_window($sessionid) { + public function get_user_window($sessionid) { global $CFG, $OUTPUT; static $str; @@ -257,10 +245,10 @@ class ChatDaemon { } ob_start(); - $refresh_inval = $CFG->chat_refresh_userlist * 1000; + $refreshinval = $CFG->chat_refresh_userlist * 1000; echo << - + EOD; - // Get the users from that chatroom + // Get the users from that chatroom. $users = $this->chatrooms[$info['chatid']]['users']; foreach ($users as $usersessionid => $userid) { - // Fetch each user's sessionid and then the rest of his data from $this->sets_info + // Fetch each user's sessionid and then the rest of his data from $this->sets_info. $userinfo = $this->sets_info[$usersessionid]; $lastping = $timenow - $userinfo['chatuser']->lastmessageping; @@ -290,7 +278,7 @@ EOD; echo '"; } echo '
'; $link = '/user/view.php?id='.$userinfo['user']->id.'&course='.$userinfo['courseid']; - $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid'=>$userinfo['courseid'])); + $anchortagcontents = $OUTPUT->user_picture($userinfo['user'], array('courseid' => $userinfo['courseid'])); $action = new popup_action('click', $link, 'user'.$userinfo['chatuser']->id); $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action); @@ -300,36 +288,33 @@ EOD; echo "

"; echo fullname($userinfo['user'])."
"; echo "$str->idle: ".format_time($lastping, $str)." "; - echo ''.$str->beep."\n"; echo "

"; echo "
'; - - // About 2K of HTML comments to force browsers to render the HTML - // echo $GLOBALS['CHAT_DUMMY_DATA']; - echo "\n\n"; return ob_get_clean(); } - function new_ufo_id() { + public function new_ufo_id() { static $id = 0; - if($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow + if ($id++ === 0x1000000) { // Cycling very very slowly to prevent overflow. $id = 0; } return $id; } - function process_sidekicks($sessionid) { - if(empty($this->conn_side[$sessionid])) { + public function process_sidekicks($sessionid) { + if (empty($this->conn_side[$sessionid])) { return true; } - foreach($this->conn_side[$sessionid] as $sideid => $sidekick) { + foreach ($this->conn_side[$sessionid] as $sideid => $sidekick) { // TODO: is this late-dispatch working correctly? $this->dispatch_sidekick($sidekick['handle'], $sidekick['type'], $sessionid, $sidekick['customdata']); unset($this->conn_side[$sessionid][$sideid]); @@ -337,14 +322,14 @@ EOD; return true; } - function dispatch_sidekick($handle, $type, $sessionid, $customdata) { + public function dispatch_sidekick($handle, $type, $sessionid, $customdata) { global $CFG, $DB; switch($type) { case CHAT_SIDEKICK_BEEP: - // Incoming beep - $msg = New stdClass; + // Incoming beep. + $msg = new stdClass; $msg->chatid = $this->sets_info[$sessionid]['chatid']; $msg->userid = $this->sets_info[$sessionid]['userid']; $msg->groupid = $this->sets_info[$sessionid]['groupid']; @@ -352,14 +337,14 @@ EOD; $msg->message = 'beep '.$customdata['beep']; $msg->timestamp = time(); - // Commit to DB + // Commit to DB. chat_send_chatmessage($this->sets_info[$sessionid]['chatuser'], $msg->message, false, $this->sets_info[$sessionid]['cm']); - // OK, now push it out to all users + // OK, now push it out to all users. $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']); - // Update that user's lastmessageping + // Update that user's lastmessageping. $this->sets_info[$sessionid]['chatuser']->lastping = $msg->timestamp; $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp; $this->user_lazy_update($sessionid); @@ -378,13 +363,13 @@ EOD; $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n"; $header .= "\n"; - // That's enough headers for one lousy dummy response + // That's enough headers for one lousy dummy response. $this->write_data($handle, $header); - // All done + // All done. break; case CHAT_SIDEKICK_USERS: - // A request to paint a user window + // A request to paint a user window. $content = $this->get_user_window($sessionid); @@ -398,66 +383,66 @@ EOD; $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n"; $header .= "Content-Length: ".strlen($content)."\n"; - // The refresh value is 2 seconds higher than the configuration variable because we are doing JS refreshes all the time. + // The refresh value is 2 seconds higher than the configuration variable. + // This is because we are doing JS refreshes all the time. // However, if the JS doesn't work for some reason, we still want to refresh once in a while. - $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2)."; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&". + $header .= "Refresh: ".(intval($CFG->chat_refresh_userlist) + 2). + "; url=http://$CFG->chat_serverhost:$CFG->chat_serverport/?win=users&". "chat_sid=".$sessionid."\n"; $header .= "\n"; - // That's enough headers for one lousy dummy response + // That's enough headers for one lousy dummy response. $this->trace('writing users http response to handle '.$handle); $this->write_data($handle, $header . $content); - // Update that user's lastping + // Update that user's lastping. $this->sets_info[$sessionid]['chatuser']->lastping = time(); $this->user_lazy_update($sessionid); break; case CHAT_SIDEKICK_MESSAGE: - // Incoming message + // Incoming message. - // Browser stupidity protection from duplicate messages: + // Browser stupidity protection from duplicate messages. $messageindex = intval($customdata['index']); - if($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) { + if ($this->sets_info[$sessionid]['lastmessageindex'] >= $messageindex) { // We have already broadcasted that! - // $this->trace('discarding message with stale index'); break; - } - else { - // Update our info + } else { + // Update our info. $this->sets_info[$sessionid]['lastmessageindex'] = $messageindex; } - $msg = New stdClass; + $msg = new stdClass; $msg->chatid = $this->sets_info[$sessionid]['chatid']; $msg->userid = $this->sets_info[$sessionid]['userid']; $msg->groupid = $this->sets_info[$sessionid]['groupid']; $msg->system = 0; - $msg->message = urldecode($customdata['message']); // have to undo the browser's encoding + $msg->message = urldecode($customdata['message']); // Have to undo the browser's encoding. $msg->timestamp = time(); - if(empty($msg->message)) { - // Someone just hit ENTER, send them on their way + if (empty($msg->message)) { + // Someone just hit ENTER, send them on their way. break; } - // A slight hack to prevent malformed SQL inserts + // A slight hack to prevent malformed SQL inserts. $origmsg = $msg->message; $msg->message = $msg->message; - // Commit to DB + // Commit to DB. chat_send_chatmessage($this->sets_info[$sessionid]['chatuser'], $msg->message, false, $this->sets_info[$sessionid]['cm']); - // Undo the hack + // Undo the hack. $msg->message = $origmsg; - // OK, now push it out to all users + // OK, now push it out to all users. $this->message_broadcast($msg, $this->sets_info[$sessionid]['user']); - // Update that user's lastmessageping + // Update that user's lastmessageping. $this->sets_info[$sessionid]['chatuser']->lastping = $msg->timestamp; $this->sets_info[$sessionid]['chatuser']->lastmessageping = $msg->timestamp; $this->user_lazy_update($sessionid); @@ -476,10 +461,10 @@ EOD; $header .= "Expires: Wed, 4 Oct 1978 09:32:45 GMT\n"; $header .= "\n"; - // That's enough headers for one lousy dummy response + // That's enough headers for one lousy dummy response. $this->write_data($handle, $header); - // All done + // All done. break; } @@ -487,31 +472,31 @@ EOD; socket_close($handle); } - function promote_final($sessionid, $customdata) { + public function promote_final($sessionid, $customdata) { global $DB; - if(isset($this->conn_sets[$sessionid])) { + if (isset($this->conn_sets[$sessionid])) { $this->trace('Set cannot be finalized: Session '.$sessionid.' is already active'); return false; } - $chatuser = $DB->get_record('chat_users', array('sid'=>$sessionid)); - if($chatuser === false) { + $chatuser = $DB->get_record('chat_users', array('sid' => $sessionid)); + if ($chatuser === false) { $this->dismiss_half($sessionid); return false; } - $chat = $DB->get_record('chat', array('id'=>$chatuser->chatid)); - if($chat === false) { + $chat = $DB->get_record('chat', array('id' => $chatuser->chatid)); + if ($chat === false) { $this->dismiss_half($sessionid); return false; } - $user = $DB->get_record('user', array('id'=>$chatuser->userid)); - if($user === false) { + $user = $DB->get_record('user', array('id' => $chatuser->userid)); + if ($user === false) { $this->dismiss_half($sessionid); return false; } - $course = $DB->get_record('course', array('id'=>$chat->course)); - if($course === false) { + $course = $DB->get_record('course', array('id' => $chat->course)); + if ($course === false) { $this->dismiss_half($sessionid); return false; } @@ -520,7 +505,7 @@ EOD; return false; } - global $CHAT_HTMLHEAD_JS, $CFG; + global $CHAT_HTMLHEAD_JS; $this->conn_sets[$sessionid] = $this->conn_half[$sessionid]; @@ -541,17 +526,14 @@ EOD; 'quirks' => $customdata['quirks'] ); - // If we know nothing about this chatroom, initialize it and add the user - if(!isset($this->chatrooms[$chat->id]['users'])) { + // If we know nothing about this chatroom, initialize it and add the user. + if (!isset($this->chatrooms[$chat->id]['users'])) { $this->chatrooms[$chat->id]['users'] = array($sessionid => $user->id); - } - else { - // Otherwise just add the user + } else { + // Otherwise just add the user. $this->chatrooms[$chat->id]['users'][$sessionid] = $user->id; } - // $this->trace('QUIRKS value for this connection is '.$customdata['quirks']); - $header = "HTTP/1.1 200 OK\n"; $header .= "Connection: close\n"; $header .= "Date: ".date('r')."\n"; @@ -564,9 +546,16 @@ EOD; $this->dismiss_half($sessionid, false); $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $header . $CHAT_HTMLHEAD_JS); - $this->trace('Connection accepted: '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL].', SID: '.$sessionid.' UID: '.$chatuser->userid.' GID: '.$chatuser->groupid, E_USER_WARNING); + $this->trace('Connection accepted: ' + .$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL] + .', SID: ' + .$sessionid + .' UID: ' + .$chatuser->userid + .' GID: ' + .$chatuser->groupid, E_USER_WARNING); - // Finally, broadcast the "entered the chat" message + // Finally, broadcast the "entered the chat" message. $msg = new stdClass; $msg->chatid = $chatuser->chatid; @@ -582,54 +571,52 @@ EOD; return true; } - function promote_ufo($handle, $type, $sessionid, $customdata) { - if(empty($this->conn_ufo)) { + public function promote_ufo($handle, $type, $sessionid, $customdata) { + if (empty($this->conn_ufo)) { return false; } - foreach($this->conn_ufo as $id => $ufo) { - if($ufo->handle == $handle) { + foreach ($this->conn_ufo as $id => $ufo) { + if ($ufo->handle == $handle) { // OK, got the id of the UFO, but what is it? - if($type & CHAT_SIDEKICK) { + if ($type & CHAT_SIDEKICK) { // Is the main connection ready? - if(isset($this->conn_sets[$sessionid])) { - // Yes, so dispatch this sidekick now and be done with it - //$this->trace('Dispatching sidekick immediately'); + if (isset($this->conn_sets[$sessionid])) { + // Yes, so dispatch this sidekick now and be done with it. $this->dispatch_sidekick($handle, $type, $sessionid, $customdata); $this->dismiss_ufo($handle, false); - } - else { - // No, so put it in the waiting list + } else { + // No, so put it in the waiting list. $this->trace('sidekick waiting'); $this->conn_side[$sessionid][] = array('type' => $type, 'handle' => $handle, 'customdata' => $customdata); } return true; } - // If it's not a sidekick, at this point it can only be da man + // If it's not a sidekick, at this point it can only be da man. - if($type & CHAT_CONNECTION) { - // This forces a new connection right now... + if ($type & CHAT_CONNECTION) { + // This forces a new connection right now. $this->trace('Incoming connection from '.$ufo->ip.':'.$ufo->port); // Do we have such a connection active? - if(isset($this->conn_sets[$sessionid])) { - // Yes, so regrettably we cannot promote you + if (isset($this->conn_sets[$sessionid])) { + // Yes, so regrettably we cannot promote you. $this->trace('Connection rejected: session '.$sessionid.' is already final'); $this->dismiss_ufo($handle, true, 'Your SID was rejected.'); return false; } - // Join this with what we may have already + // Join this with what we may have already. $this->conn_half[$sessionid][$type] = $handle; - // Do the bookkeeping + // Do the bookkeeping. $this->promote_final($sessionid, $customdata); - // It's not an UFO anymore + // It's not a UFO anymore. $this->dismiss_ufo($handle, false); - // Dispatch waiting sidekicks + // Dispatch waiting sidekicks. $this->process_sidekicks($sessionid); return true; @@ -639,12 +626,12 @@ EOD; return false; } - function dismiss_half($sessionid, $disconnect = true) { - if(!isset($this->conn_half[$sessionid])) { + public function dismiss_half($sessionid, $disconnect = true) { + if (!isset($this->conn_half[$sessionid])) { return false; } - if($disconnect) { - foreach($this->conn_half[$sessionid] as $handle) { + if ($disconnect) { + foreach ($this->conn_half[$sessionid] as $handle) { @socket_shutdown($handle); @socket_close($handle); } @@ -653,10 +640,10 @@ EOD; return true; } - function dismiss_set($sessionid) { - if(!empty($this->conn_sets[$sessionid])) { - foreach($this->conn_sets[$sessionid] as $handle) { - // Since we want to dismiss this, don't generate any errors if it's dead already + public function dismiss_set($sessionid) { + if (!empty($this->conn_sets[$sessionid])) { + foreach ($this->conn_sets[$sessionid] as $handle) { + // Since we want to dismiss this, don't generate any errors if it's dead already. @socket_shutdown($handle); @socket_close($handle); } @@ -670,16 +657,15 @@ EOD; return true; } - - function dismiss_ufo($handle, $disconnect = true, $message = NULL) { - if(empty($this->conn_ufo)) { + public function dismiss_ufo($handle, $disconnect = true, $message = null) { + if (empty($this->conn_ufo)) { return false; } - foreach($this->conn_ufo as $id => $ufo) { - if($ufo->handle == $handle) { + foreach ($this->conn_ufo as $id => $ufo) { + if ($ufo->handle == $handle) { unset($this->conn_ufo[$id]); - if($disconnect) { - if(!empty($message)) { + if ($disconnect) { + if (!empty($message)) { $this->write_data($handle, $message."\n\n"); } socket_shutdown($handle); @@ -691,36 +677,34 @@ EOD; return false; } - function conn_accept() { - $read_socket = array($this->listen_socket); + public function conn_accept() { + $readsocket = array($this->listen_socket); $write = null; $except = null; - $changed = socket_select($read_socket, $write, $except, 0, 0); + $changed = socket_select($readsocket, $write, $except, 0, 0); - if(!$changed) { + if (!$changed) { return false; } $handle = socket_accept($this->listen_socket); - if(!$handle) { + if (!$handle) { return false; } - $newconn = New ChatConnection($handle); + $newconn = new ChatConnection($handle); $id = $this->new_ufo_id(); $this->conn_ufo[$id] = $newconn; - - //$this->trace('UFO #'.$id.': connection from '.$newconn->ip.' on port '.$newconn->port.', '.$newconn->handle); } - function conn_activity_ufo (&$handles) { + public function conn_activity_ufo(&$handles) { $monitor = array(); - if(!empty($this->conn_ufo)) { - foreach($this->conn_ufo as $ufoid => $ufo) { + if (!empty($this->conn_ufo)) { + foreach ($this->conn_ufo as $ufoid => $ufo) { $monitor[$ufoid] = $ufo->handle; } } - if(empty($monitor)) { + if (empty($monitor)) { $handles = array(); return 0; } @@ -733,52 +717,51 @@ EOD; return $retval; } - function message_broadcast($message, $sender) { + public function message_broadcast($message, $sender) { - if(empty($this->conn_sets)) { + if (empty($this->conn_sets)) { return true; } $now = time(); - // First of all, mark this chatroom as having had activity now + // First of all, mark this chatroom as having had activity now. $this->chatrooms[$message->chatid]['lastactivity'] = $now; - foreach($this->sets_info as $sessionid => $info) { - // We need to get handles from users that are in the same chatroom, same group - if($info['chatid'] == $message->chatid && - ($info['groupid'] == $message->groupid || $message->groupid == 0)) - { + foreach ($this->sets_info as $sessionid => $info) { + // We need to get handles from users that are in the same chatroom, same group. + if ($info['chatid'] == $message->chatid && + ($info['groupid'] == $message->groupid || $message->groupid == 0)) { - // Simply give them the message + // Simply give them the message. $output = chat_format_message_manually($message, $info['courseid'], $sender, $info['user']); $this->trace('Delivering message "'.$output->text.'" to '.$this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL]); - if($output->beep) { - $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], ''); + if ($output->beep) { + $this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], + ''); } - if($info['quirks'] & QUIRK_CHUNK_UPDATE) { + if ($info['quirks'] & QUIRK_CHUNK_UPDATE) { $output->html .= $GLOBALS['CHAT_DUMMY_DATA']; $output->html .= $GLOBALS['CHAT_DUMMY_DATA']; $output->html .= $GLOBALS['CHAT_DUMMY_DATA']; } - if(!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) { + if (!$this->write_data($this->conn_sets[$sessionid][CHAT_CONNECTION_CHANNEL], $output->html)) { $this->disconnect_session($sessionid); } - //$this->trace('Sent to UID '.$this->sets_info[$sessionid]['userid'].': '.$message->text_); } } } - function disconnect_session($sessionid) { + public function disconnect_session($sessionid) { global $DB; $info = $this->sets_info[$sessionid]; - $DB->delete_records('chat_users', array('sid'=>$sessionid)); - $msg = New stdClass; + $DB->delete_records('chat_users', array('sid' => $sessionid)); + $msg = new stdClass; $msg->chatid = $info['chatid']; $msg->userid = $info['userid']; $msg->groupid = $info['groupid']; @@ -789,88 +772,80 @@ EOD; $this->trace('User has disconnected, destroying uid '.$info['userid'].' with SID '.$sessionid, E_USER_WARNING); chat_send_chatmessage($info['chatuser'], $msg->message, true); - // *************************** IMPORTANT - // - // Kill him BEFORE broadcasting, otherwise we 'll get infinite recursion! - // - // ********************************************************************** + // IMPORTANT, kill him BEFORE broadcasting, otherwise we 'll get infinite recursion! $latesender = $info['user']; $this->dismiss_set($sessionid); $this->message_broadcast($msg, $latesender); } - function fatal($message) { + public function fatal($message) { $message .= "\n"; - if($this->_logfile) { + if ($this->_logfile) { $this->trace($message, E_USER_ERROR); } echo "FATAL ERROR:: $message\n"; die(); } - function init_sockets() { + public function init_sockets() { global $CFG; $this->trace('Setting up sockets'); - if(false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) { - // Failed to create socket + if (false === ($this->listen_socket = socket_create(AF_INET, SOCK_STREAM, 0))) { + // Failed to create socket. $lasterr = socket_last_error(); $this->fatal('socket_create() failed: '. socket_strerror($lasterr).' ['.$lasterr.']'); } - //socket_close($DAEMON->listen_socket); - //die(); - - if(!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) { - // Failed to bind socket + if (!socket_bind($this->listen_socket, $CFG->chat_serverip, $CFG->chat_serverport)) { + // Failed to bind socket. $lasterr = socket_last_error(); $this->fatal('socket_bind() failed: '. socket_strerror($lasterr).' ['.$lasterr.']'); } - if(!socket_listen($this->listen_socket, $CFG->chat_servermax)) { - // Failed to get socket to listen + if (!socket_listen($this->listen_socket, $CFG->chat_servermax)) { + // Failed to get socket to listen. $lasterr = socket_last_error(); $this->fatal('socket_listen() failed: '. socket_strerror($lasterr).' ['.$lasterr.']'); } - // Socket has been initialized and is ready + // Socket has been initialized and is ready. $this->trace('Socket opened on port '.$CFG->chat_serverport); - // [pj]: I really must have a good read on sockets. What exactly does this do? - // http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me. + // What exactly does this do? http://www.unixguide.net/network/socketfaq/4.5.shtml is still not enlightening enough for me. socket_set_option($this->listen_socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_nonblock($this->listen_socket); } - function cli_switch($switch, $param = NULL) { - switch($switch) { //LOL + public function cli_switch($switch, $param = null) { + switch($switch) { // LOL! case 'reset': - // Reset sockets + // Reset sockets. $this->_resetsocket = true; return false; case 'start': - // Start the daemon + // Start the daemon. $this->_readytogo = true; return false; break; case 'v': - // Verbose mode + // Verbose mode. $this->_trace_level = E_ALL; return false; break; case 'l': - // Use logfile - if(!empty($param)) { + // Use logfile. + if (!empty($param)) { $this->_logfile_name = $param; } $this->_logfile = @fopen($this->_logfile_name, 'a+'); - if($this->_logfile == false) { + if ($this->_logfile == false) { $this->fatal('Failed to open '.$this->_logfile_name.' for writing'); } return false; default: - // Unrecognized + // Unrecognized. $this->fatal('Unrecognized command line switch: '.$switch); break; } @@ -879,54 +854,52 @@ EOD; } -$DAEMON = New ChatDaemon; -set_error_handler(array($DAEMON, 'error_handler')); +$daemon = new ChatDaemon; +set_error_handler(array($daemon, 'error_handler')); -/// Check the parameters ////////////////////////////////////////////////////// +// Check the parameters. unset($argv[0]); $commandline = implode(' ', $argv); -if(strpos($commandline, '-') === false) { - if(!empty($commandline)) { - // We cannot have received any meaningful parameters - $DAEMON->fatal('Garbage in command line'); +if (strpos($commandline, '-') === false) { + if (!empty($commandline)) { + // We cannot have received any meaningful parameters. + $daemon->fatal('Garbage in command line'); } -} -else { - // Parse command line +} else { + // Parse command line. $switches = preg_split('/(-{1,2}[a-zA-Z]+) */', $commandline, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - // Taking advantage of the fact that $switches is indexed with incrementing numeric keys - // We will be using that to pass additional information to those switches who need it + // Taking advantage of the fact that $switches is indexed with incrementing numeric keys. + // We will be using that to pass additional information to those switches who need it. $numswitches = count($switches); - // Fancy way to give a "hyphen" boolean flag to each "switch" + // Fancy way to give a "hyphen" boolean flag to each "switch". $switches = array_map(create_function('$x', 'return array("str" => $x, "hyphen" => (substr($x, 0, 1) == "-"));'), $switches); - for($i = 0; $i < $numswitches; ++$i) { + for ($i = 0; $i < $numswitches; ++$i) { $switch = $switches[$i]['str']; - $params = ($i == $numswitches - 1 ? NULL : - ($switches[$i + 1]['hyphen'] ? NULL : trim($switches[$i + 1]['str'])) + $params = ($i == $numswitches - 1 ? null : + ($switches[$i + 1]['hyphen'] ? null : trim($switches[$i + 1]['str'])) ); - if(substr($switch, 0, 2) == '--') { - // Double-hyphen switch - $DAEMON->cli_switch(strtolower(substr($switch, 2)), $params); - } - else if(substr($switch, 0, 1) == '-') { - // Single-hyphen switch(es), may be more than one run together - $switch = substr($switch, 1); // Get rid of the - + if (substr($switch, 0, 2) == '--') { + // Double-hyphen switch. + $daemon->cli_switch(strtolower(substr($switch, 2)), $params); + } else if (substr($switch, 0, 1) == '-') { + // Single-hyphen switch(es), may be more than one run together. + $switch = substr($switch, 1); // Get rid of the "-". $len = strlen($switch); - for($j = 0; $j < $len; ++$j) { - $DAEMON->cli_switch(strtolower(substr($switch, $j, 1)), $params); + for ($j = 0; $j < $len; ++$j) { + $daemon->cli_switch(strtolower(substr($switch, $j, 1)), $params); } } } } -if(!$DAEMON->query_start()) { - // For some reason we didn't start, so print out some info +if (!$daemon->query_start()) { + // For some reason we didn't start, so print out some info. echo 'Starts the Moodle chat socket server on port '.$CFG->chat_serverport; echo "\n\n"; echo "Usage: chatd.php [parameters]\n\n"; @@ -945,92 +918,42 @@ if (!function_exists('socket_set_option')) { die(); } -$DAEMON->init_sockets(); +$daemon->init_sockets(); -/* -declare(ticks=1); +$daemon->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$daemon->listen_socket, E_USER_WARNING); -$pid = pcntl_fork(); -if ($pid == -1) { - die("could not fork"); -} else if ($pid) { - exit(); // we are the parent -} else { - // we are the child -} +// Clear the decks of old stuff. +$DB->delete_records('chat_users', array('version' => 'sockets')); -// detatch from the controlling terminal -if (!posix_setsid()) { - die("could not detach from terminal"); -} - -// setup signal handlers -pcntl_signal(SIGTERM, "sig_handler"); -pcntl_signal(SIGHUP, "sig_handler"); - -if($DAEMON->_pcntl_exists && false) { - $DAEMON->trace('Unholy spirit possession: daemonizing'); - $DAEMON->pid = pcntl_fork(); - if($pid == -1) { - $DAEMON->trace('Process fork failed, terminating'); - die(); - } - else if($pid) { - // We are the parent - $DAEMON->trace('Successfully forked the daemon with PID '.$pid); - die(); - } - else { - // We are the daemon! :P - } - - // FROM NOW ON, IT'S THE DAEMON THAT'S RUNNING! - - // Detach from controlling terminal - if(!posix_setsid()) { - $DAEMON->trace('Could not detach daemon process from terminal!'); - } -} -else { - // Cannot go demonic - $DAEMON->trace('Unholy spirit possession failed: PHP is not compiled with --enable-pcntl'); -} -*/ - -$DAEMON->trace('Started Moodle chatd on port '.$CFG->chat_serverport.', listening socket '.$DAEMON->listen_socket, E_USER_WARNING); - -/// Clear the decks of old stuff -$DB->delete_records('chat_users', array('version'=>'sockets')); - -while(true) { +while (true) { $active = array(); - // First of all, let's see if any of our UFOs has identified itself - if($DAEMON->conn_activity_ufo($active)) { - foreach($active as $handle) { - $read_socket = array($handle); + // First of all, let's see if any of our UFOs have identified itself. + if ($daemon->conn_activity_ufo($active)) { + foreach ($active as $handle) { + $readsocket = array($handle); $write = null; $except = null; - $changed = socket_select($read_socket, $write, $except, 0, 0); + $changed = socket_select($readsocket, $write, $except, 0, 0); - if($changed > 0) { - // Let's see what it has to say + if ($changed > 0) { + // Let's see what it has to say. - $data = socket_read($handle, 2048); // should be more than 512 to prevent empty pages and repeated messages!! - if(empty($data)) { + $data = socket_read($handle, 2048); // Should be more than 512 to prevent empty pages and repeated messages! + if (empty($data)) { continue; } - if (strlen($data) == 2048) { // socket_read has more data, ignore all data - $DAEMON->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING); - $DAEMON->dismiss_ufo($handle, true, 'Data too long; connection closed'); + if (strlen($data) == 2048) { // If socket_read has more data, ignore all data. + $daemon->trace('UFO with '.$handle.': Data too long; connection closed', E_USER_WARNING); + $daemon->dismiss_ufo($handle, true, 'Data too long; connection closed'); continue; } - if(!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) { - // Malformed data - $DAEMON->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING); - $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); + if (!preg_match('/win=(chat|users|message|beep).*&chat_sid=([a-zA-Z0-9]*) HTTP/', $data, $info)) { + // Malformed data. + $daemon->trace('UFO with '.$handle.': Request with malformed data; connection closed', E_USER_WARNING); + $daemon->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); continue; } @@ -1041,10 +964,10 @@ while(true) { switch($type) { case 'chat': - $type = CHAT_CONNECTION_CHANNEL; + $type = CHAT_CONNECTION_CHANNEL; $customdata['quirks'] = 0; - if(strpos($data, 'Safari')) { - $DAEMON->trace('Safari identified...', E_USER_WARNING); + if (strpos($data, 'Safari')) { + $daemon->trace('Safari identified...', E_USER_WARNING); $customdata['quirks'] += QUIRK_CHUNK_UPDATE; } break; @@ -1053,35 +976,33 @@ while(true) { break; case 'beep': $type = CHAT_SIDEKICK_BEEP; - if(!preg_match('/beep=([^&]*)[& ]/', $data, $info)) { - $DAEMON->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING); - $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); + if (!preg_match('/beep=([^&]*)[& ]/', $data, $info)) { + $daemon->trace('Beep sidekick did not contain a valid userid', E_USER_WARNING); + $daemon->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); continue; - } - else { + } else { $customdata = array('beep' => intval($info[1])); } break; case 'message': $type = CHAT_SIDEKICK_MESSAGE; - if(!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) { - $DAEMON->trace('Message sidekick did not contain a valid message', E_USER_WARNING); - $DAEMON->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); + if (!preg_match('/chat_message=([^&]*)[& ]chat_msgidnr=([^&]*)[& ]/', $data, $info)) { + $daemon->trace('Message sidekick did not contain a valid message', E_USER_WARNING); + $daemon->dismiss_ufo($handle, true, 'Request with malformed data; connection closed'); continue; - } - else { + } else { $customdata = array('message' => $info[1], 'index' => $info[2]); } break; default: - $DAEMON->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING); - $DAEMON->dismiss_ufo($handle, true, 'Request with unknown type; connection closed'); + $daemon->trace('UFO with '.$handle.': Request with unknown type; connection closed', E_USER_WARNING); + $daemon->dismiss_ufo($handle, true, 'Request with unknown type; connection closed'); continue; break; } - // OK, now we know it's something good... promote it and pass it all the data it needs - $DAEMON->promote_ufo($handle, $type, $sessionid, $customdata); + // OK, now we know it's something good. Promote it and pass it all the data it needs. + $daemon->promote_ufo($handle, $type, $sessionid, $customdata); continue; } } @@ -1089,18 +1010,17 @@ while(true) { $now = time(); - // Clean up chatrooms with no activity as required - if($now - $DAEMON->_last_idle_poll >= $DAEMON->_freq_poll_idle_chat) { - $DAEMON->poll_idle_chats($now); + // Clean up chatrooms with no activity as required. + if ($now - $daemon->_last_idle_poll >= $daemon->_freq_poll_idle_chat) { + $daemon->poll_idle_chats($now); } - // Finally, accept new connections - $DAEMON->conn_accept(); + // Finally, accept new connections. + $daemon->conn_accept(); - usleep($DAEMON->_time_rest_socket); + usleep($daemon->_time_rest_socket); } -@socket_shutdown($DAEMON->listen_socket, 0); +@socket_shutdown($daemon->listen_socket, 0); die("\n\n-- terminated --\n"); - diff --git a/mod/chat/db/access.php b/mod/chat/db/access.php index 90e4e016d82..89af1a6554b 100644 --- a/mod/chat/db/access.php +++ b/mod/chat/db/access.php @@ -85,7 +85,7 @@ $capabilities = array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, - // not student - nervous about allowing this by default + // Not student - nervous about allowing this by default. ), ), diff --git a/mod/chat/db/log.php b/mod/chat/db/log.php index 275f5f71fec..5cde13bf2e8 100644 --- a/mod/chat/db/log.php +++ b/mod/chat/db/log.php @@ -1,5 +1,4 @@ 'chat', 'action'=>'view', 'mtable'=>'chat', 'field'=>'name'), - array('module'=>'chat', 'action'=>'add', 'mtable'=>'chat', 'field'=>'name'), - array('module'=>'chat', 'action'=>'update', 'mtable'=>'chat', 'field'=>'name'), - array('module'=>'chat', 'action'=>'report', 'mtable'=>'chat', 'field'=>'name'), - array('module'=>'chat', 'action'=>'talk', 'mtable'=>'chat', 'field'=>'name'), -); \ No newline at end of file + array('module' => 'chat', 'action' => 'view', 'mtable' => 'chat', 'field' => 'name'), + array('module' => 'chat', 'action' => 'add', 'mtable' => 'chat', 'field' => 'name'), + array('module' => 'chat', 'action' => 'update', 'mtable' => 'chat', 'field' => 'name'), + array('module' => 'chat', 'action' => 'report', 'mtable' => 'chat', 'field' => 'name'), + array('module' => 'chat', 'action' => 'talk', 'mtable' => 'chat', 'field' => 'name'), +); diff --git a/mod/chat/db/upgrade.php b/mod/chat/db/upgrade.php index fde34d6d06f..f3367437673 100644 --- a/mod/chat/db/upgrade.php +++ b/mod/chat/db/upgrade.php @@ -1,46 +1,44 @@ . -// This file keeps track of upgrades to -// the chat module -// -// Sometimes, changes between versions involve -// alterations to database structures and other -// major things that may break installations. -// -// The upgrade function in this file will attempt -// to perform all the necessary actions to upgrade -// your older installation to the current version. -// -// If there's something it cannot do itself, it -// will tell you what you need to do. -// -// The commands in here will all be database-neutral, -// using the methods of database_manager class -// -// Please do not forget to use upgrade_set_timeout() -// before any action that may take longer time to finish. +/** + * Upgrade code for the chat activity + * + * @package mod_chat + * @copyright 2006 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ function xmldb_chat_upgrade($oldversion) { global $CFG, $DB; $dbman = $DB->get_manager(); + // Moodle v2.2.0 release upgrade line. + // Put any upgrade step following this. - // Moodle v2.2.0 release upgrade line - // Put any upgrade step following this - - // Moodle v2.3.0 release upgrade line - // Put any upgrade step following this - - - // Moodle v2.4.0 release upgrade line - // Put any upgrade step following this + // Moodle v2.3.0 release upgrade line. + // Put any upgrade step following this. + // Moodle v2.4.0 release upgrade line. + // Put any upgrade step following this. // Moodle v2.5.0 release upgrade line. // Put any upgrade step following this. - // Moodle v2.6.0 release upgrade line. // Put any upgrade step following this. diff --git a/mod/chat/gui_ajax/index.php b/mod/chat/gui_ajax/index.php index ceee1551545..36b9d678806 100644 --- a/mod/chat/gui_ajax/index.php +++ b/mod/chat/gui_ajax/index.php @@ -1,29 +1,44 @@ . + require_once('../../../config.php'); require_once('../lib.php'); $id = required_param('id', PARAM_INT); -$groupid = optional_param('groupid', 0, PARAM_INT); //only for teachers -$theme = optional_param('theme', 'course_theme', PARAM_SAFEDIR); //course_theme to use the current theme. +$groupid = optional_param('groupid', 0, PARAM_INT); // Only for teachers. +$theme = optional_param('theme', 'course_theme', PARAM_SAFEDIR); // The value course_theme == the current theme. -$url = new moodle_url('/mod/chat/gui_ajax/index.php', array('id'=>$id)); +$url = new moodle_url('/mod/chat/gui_ajax/index.php', array('id' => $id)); if ($groupid !== 0) { $url->param('groupid', $groupid); } $PAGE->set_url($url); -$PAGE->set_popup_notification_allowed(false); // No popup notifications in the chat window +$PAGE->set_popup_notification_allowed(false); // No popup notifications in the chat window. $PAGE->requires->strings_for_js(array('coursetheme', 'bubble', 'compact'), 'mod_chat'); -$chat = $DB->get_record('chat', array('id'=>$id), '*', MUST_EXIST); -$course = $DB->get_record('course', array('id'=>$chat->course), '*', MUST_EXIST); +$chat = $DB->get_record('chat', array('id' => $id), '*', MUST_EXIST); +$course = $DB->get_record('course', array('id' => $chat->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('chat', $chat->id, $course->id, false, MUST_EXIST); $context = context_module::instance($cm->id); require_login($course, false, $cm); require_capability('mod/chat:chat', $context); -/// Check to see if groups are being used here - if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used +// Check to see if groups are being used here. +if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used. if ($groupid = groups_get_activity_group($cm)) { if (!$group = groups_get_group($groupid)) { print_error('invalidgroupid'); @@ -37,42 +52,43 @@ require_capability('mod/chat:chat', $context); $groupname = ''; } $showcoursetheme = in_array('bootstrapbase', $PAGE->theme->parents); -if (!$showcoursetheme && $theme === 'course_theme') { //set compact as default for non bootstrapbase based themes +if (!$showcoursetheme && $theme === 'course_theme') { // Set compact as default for non bootstrapbase based themes. $theme = 'compact'; } -// if requested theme doesn't exist, use default 'bubble' theme +// If requested theme doesn't exist, use default 'bubble' theme. if ($theme != 'course_theme' and !file_exists(dirname(__FILE__) . '/theme/'.$theme.'/chat.css')) { $theme = 'compact'; } -// login chat room -if (!$chat_sid = chat_login_user($chat->id, 'ajax', $groupid, $course)) { +// Log into the chat room. +if (!$chatsid = chat_login_user($chat->id, 'ajax', $groupid, $course)) { print_error('cantlogin', 'chat'); } $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id))); $module = array( - 'name' => 'mod_chat_ajax', // chat gui's are not real plugins, we have to break the naming standards for JS modules here :-( + 'name' => 'mod_chat_ajax', // Chat gui's are not real plugins, we have to break the naming standards for JS modules here. 'fullpath' => '/mod/chat/gui_ajax/module.js', - 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'json-parse', 'io', 'overlay', 'yui2-resize', 'yui2-layout', 'yui2-menu'), + 'requires' => array('base', 'dom', 'event', 'event-mouseenter', 'event-key', 'json-parse', 'io', 'overlay', 'yui2-resize', + 'yui2-layout', 'yui2-menu'), 'strings' => array(array('send', 'chat'), array('sending', 'chat'), array('inputarea', 'chat'), array('userlist', 'chat'), array('modulename', 'chat'), array('beep', 'chat'), array('talk', 'chat')) ); $modulecfg = array( - 'home'=>$CFG->httpswwwroot.'/mod/chat/view.php?id='.$cm->id, - 'chaturl'=>$CFG->httpswwwroot.'/mod/chat/gui_ajax/index.php?id='.$id, - 'theme'=>$theme, - 'showcoursetheme'=>$showcoursetheme?1:0, - 'userid'=>$USER->id, - 'sid'=>$chat_sid, - 'timer'=>3000, - 'chat_lasttime'=>0, - 'chat_lastrow'=>null, + 'home' => $CFG->httpswwwroot.'/mod/chat/view.php?id='.$cm->id, + 'chaturl' => $CFG->httpswwwroot.'/mod/chat/gui_ajax/index.php?id='.$id, + 'theme' => $theme, + 'showcoursetheme' => $showcoursetheme ? 1 : 0, + 'userid' => $USER->id, + 'sid' => $chatsid, + 'timer' => 3000, + 'chat_lasttime' => 0, + 'chat_lastrow' => null, 'chatroom_name' => $courseshortname . ": " . format_string($chat->name, true) . $groupname ); $PAGE->requires->js_init_call('M.mod_chat_ajax.init', array($modulecfg), false, $module); -$PAGE->set_title(get_string('modulename', 'chat').": $courseshortname: ".format_string($chat->name,true)."$groupname"); +$PAGE->set_title(get_string('modulename', 'chat').": $courseshortname: ".format_string($chat->name, true)."$groupname"); $PAGE->add_body_class('yui-skin-sam'); $PAGE->set_pagelayout('embedded'); if ( $theme != 'course_theme') { @@ -87,7 +103,11 @@ echo $OUTPUT->box(html_writer::tag('h2', get_string('messages', 'chat'), array( '', '', 'chat-messages'); $table = new html_table(); $table->data = array( - array(' '.get_string('themes').' » ') + array(''. + ' '. + ' '. + get_string('themes'). + ' » ') ); echo $OUTPUT->box(html_writer::tag('h2', get_string('composemessage', 'chat'), array('class' => 'accesshide')) . html_writer::table($table), '', 'chat-input-area'); diff --git a/mod/chat/gui_ajax/module.js b/mod/chat/gui_ajax/module.js index fe872839327..711c1edb500 100644 --- a/mod/chat/gui_ajax/module.js +++ b/mod/chat/gui_ajax/module.js @@ -1,4 +1,3 @@ - /* * NOTE: the /mod/chat/gui_header_js/ is not a real plugin, * ideally this code should be in /mod/chat/module.js @@ -20,14 +19,14 @@ M.mod_chat_ajax.init = function(Y, cfg) { var gui_ajax = { - // Properties - api : M.cfg.wwwroot+'/mod/chat/chat_ajax.php?sesskey='+M.cfg.sesskey, // The path to the ajax callback script - cfg : {}, // A configuration variable - interval : null, // The interval object for refreshes - layout : null, // A reference to the layout used in this module - messages : [], // An array of messages - scrollable : true, // True is scrolling should occur - thememenu : null, // A reference to the menu for changing themes + // Properties. + api : M.cfg.wwwroot + '/mod/chat/chat_ajax.php?sesskey=' + M.cfg.sesskey, // The path to the ajax callback script. + cfg : {}, // A configuration variable. + interval : null, // The interval object for refreshes. + layout : null, // A reference to the layout used in this module. + messages : [], // An array of messages. + scrollable : true, // True is scrolling should occur. + thememenu : null, // A reference to the menu for changing themes. // Elements messageinput : null, @@ -59,19 +58,19 @@ M.mod_chat_ajax.init = function(Y, cfg) { }, this.layout); this.layout.render(); - // Gather the general elements + // Gather the general elements. this.messageinput = Y.one('#input-message'); this.sendbutton = Y.one('#button-send'); this.messagebox = Y.one('#chat-messages'); - // Set aria attributes to messagebox and chat-userlist + // Set aria attributes to messagebox and chat-userlist. this.messagebox.set('role', 'log'); this.messagebox.set('aria-live', 'polite'); var userlist = Y.one('#chat-userlist'); userlist.set('aria-live', 'polite'); userlist.set('aria-relevant', 'all'); - // Attach the default events for this module + // Attach the default events for this module. this.sendbutton.on('click', this.send, this); this.messagebox.on('mouseenter', function() { this.scrollable = false; @@ -80,12 +79,12 @@ M.mod_chat_ajax.init = function(Y, cfg) { this.scrollable = true; }, this); - // Send the message when the enter key is pressed + // Send the message when the enter key is pressed. Y.on('key', this.send, this.messageinput, 'press:13', this); document.title = this.cfg.chatroom_name; - // Prepare and execute the first AJAX request of information + // Prepare and execute the first AJAX request of information. Y.io(this.api,{ method : 'POST', data : build_querystring({ @@ -115,25 +114,25 @@ M.mod_chat_ajax.init = function(Y, cfg) { scope.update_messages(); }, this.cfg.timer, this); - // Create and initalise theme changing menu + // Create and initalise theme changing menu. this.thememenu = new Y.YUI2.widget.Menu('basicmenu', {xy:[0,0]}); this.thememenu.addItems([ - {text: M.util.get_string('bubble', 'mod_chat'), url: this.cfg.chaturl+'&theme=bubble'}, - {text: M.util.get_string('compact', 'mod_chat'), url: this.cfg.chaturl+'&theme=compact'} + {text: M.util.get_string('bubble', 'mod_chat'), url: this.cfg.chaturl + '&theme=bubble'}, + {text: M.util.get_string('compact', 'mod_chat'), url: this.cfg.chaturl + '&theme=compact'} ]); if (this.cfg.showcoursetheme == 1) { - this.thememenu.addItem({text: M.util.get_string('coursetheme', 'mod_chat'), url: this.cfg.chaturl+'&theme=course_theme'}); + this.thememenu.addItem({text: M.util.get_string('coursetheme', 'mod_chat'), url: this.cfg.chaturl + '&theme=course_theme'}); } this.thememenu.render(document.body); - Y.one('#choosetheme').on('click', function(e){ - this.moveTo((e.pageX-20), (e.pageY-20)); + Y.one('#choosetheme').on('click', function(e) { + this.moveTo((e.pageX - 20), (e.pageY - 20)); this.show(); }, this.thememenu); }, append_message : function(key, message, row) { - var item = Y.Node.create('
  • '+message.message+'
  • '); - item.addClass((message.mymessage)?'mdl-chat-my-entry':'mdl-chat-entry'); + var item = Y.Node.create('
  • ' + message.message + '
  • '); + item.addClass((message.mymessage) ? 'mdl-chat-my-entry' : 'mdl-chat-entry'); Y.one('#messages-list').append(item); if (message.type && message.type == 'beep') { Y.one('#chat-notify').setContent(''); @@ -143,7 +142,7 @@ M.mod_chat_ajax.init = function(Y, cfg) { send : function(e, beep) { this.sendbutton.set('value', M.str.chat.sending); var data = { - chat_message : (!beep)?this.messageinput.get('value'):'', + chat_message : (!beep) ? this.messageinput.get('value') : '', chat_sid : this.cfg.sid, theme : this.cfg.theme }; @@ -179,7 +178,7 @@ M.mod_chat_ajax.init = function(Y, cfg) { }, talkto: function (e, name) { - this.messageinput.set('value', "To "+name+": "); + this.messageinput.set('value', "To " + name + ": "); this.messageinput.focus(); }, @@ -214,18 +213,18 @@ M.mod_chat_ajax.init = function(Y, cfg) { } this.cfg.chat_lasttime = data.lasttime; this.cfg.chat_lastrow = data.lastrow; - // Update messages + // Update messages. for (var key in data.msgs){ if (!M.util.in_array(key, this.messages)) { this.messages.push(key); this.append_message(key, data.msgs[key], data.lastrow); } } - // Update users + // Update users. this.update_users(data.users); // Scroll to the bottom of the message list if (this.scrollable) { - Y.Node.getDOMNode(this.messagebox).parentNode.scrollTop+=500; + Y.Node.getDOMNode(this.messagebox).parentNode.scrollTop += 500; } this.messageinput.focus(); }, @@ -237,14 +236,14 @@ M.mod_chat_ajax.init = function(Y, cfg) { var list = Y.one('#users-list'); list.get('children').remove(); for (var i in users) { - var li = Y.Node.create('
  • '+users[i].picture+'
  • '); + var li = Y.Node.create('
  • ' + users[i].picture + '
  • '); if (users[i].id == this.cfg.userid) { - li.all('td').item(1).append(Y.Node.create(''+ users[i].name+'')); + li.all('td').item(1).append(Y.Node.create('' + users[i].name + '')); } else { - li.all('td').item(1).append(Y.Node.create('
    '+users[i].name+'
    ')); - var talk = Y.Node.create(''+M.str.chat.talk+''); + li.all('td').item(1).append(Y.Node.create('
    ' + users[i].name + '
    ')); + var talk = Y.Node.create('' + M.str.chat.talk + ''); talk.on('click', this.talkto, this, users[i].name); - var beep = Y.Node.create(''+M.str.chat.beep+''); + var beep = Y.Node.create('' + M.str.chat.beep + ''); beep.on('click', this.send, this, users[i].id); li.all('td').item(1).append(Y.Node.create('
    ').append(talk).append(' ').append(beep)); } diff --git a/mod/chat/gui_ajax/theme/bubble/config.php b/mod/chat/gui_ajax/theme/bubble/config.php index 5f6649d5cab..b1eb941e1e6 100644 --- a/mod/chat/gui_ajax/theme/bubble/config.php +++ b/mod/chat/gui_ajax/theme/bubble/config.php @@ -1,4 +1,19 @@ . + $chattheme_cfg = new stdClass(); $chattheme_cfg->avatar = true; $chattheme_cfg->align = true; diff --git a/mod/chat/gui_ajax/theme/compact/config.php b/mod/chat/gui_ajax/theme/compact/config.php index 3103704b783..eb13f88ec48 100644 --- a/mod/chat/gui_ajax/theme/compact/config.php +++ b/mod/chat/gui_ajax/theme/compact/config.php @@ -1,4 +1,19 @@ . + $chattheme_cfg = new stdClass(); $chattheme_cfg->avatar = false; $chattheme_cfg->align = false; diff --git a/mod/chat/gui_ajax/theme/course_theme/config.php b/mod/chat/gui_ajax/theme/course_theme/config.php index 19f51688361..130d1b28b87 100644 --- a/mod/chat/gui_ajax/theme/course_theme/config.php +++ b/mod/chat/gui_ajax/theme/course_theme/config.php @@ -1,4 +1,19 @@ . + $chattheme_cfg = new stdClass(); $chattheme_cfg->avatar = false; $chattheme_cfg->align = false; diff --git a/mod/chat/gui_basic/index.php b/mod/chat/gui_basic/index.php index 33d11adc770..588d7c8895f 100644 --- a/mod/chat/gui_basic/index.php +++ b/mod/chat/gui_basic/index.php @@ -1,16 +1,30 @@ . require_once('../../../config.php'); require_once('../lib.php'); $id = required_param('id', PARAM_INT); -$groupid = optional_param('groupid', 0, PARAM_INT); // only for teachers +$groupid = optional_param('groupid', 0, PARAM_INT); // Only for teachers. $message = optional_param('message', '', PARAM_CLEANHTML); -$refresh = optional_param('refresh', '', PARAM_RAW); // force refresh -$last = optional_param('last', 0, PARAM_INT); // last time refresh or sending -$newonly = optional_param('newonly', 0, PARAM_BOOL); // show only new messages +$refresh = optional_param('refresh', '', PARAM_RAW); // Force refresh. +$last = optional_param('last', 0, PARAM_INT); // Last time refresh or sending. +$newonly = optional_param('newonly', 0, PARAM_BOOL); // Show only new messages. -$url = new moodle_url('/mod/chat/gui_basic/index.php', array('id'=>$id)); +$url = new moodle_url('/mod/chat/gui_basic/index.php', array('id' => $id)); if ($groupid !== 0) { $url->param('groupid', $groupid); } @@ -28,11 +42,11 @@ if ($newonly !== 0) { } $PAGE->set_url($url); -if (!$chat = $DB->get_record('chat', array('id'=>$id))) { +if (!$chat = $DB->get_record('chat', array('id' => $id))) { print_error('invalidid', 'chat'); } -if (!$course = $DB->get_record('course', array('id'=>$chat->course))) { +if (!$course = $DB->get_record('course', array('id' => $chat->course))) { print_error('invalidcourseid'); } @@ -47,7 +61,7 @@ $PAGE->set_pagelayout('popup'); $PAGE->set_popup_notification_allowed(false); // Check to see if groups are being used here. - if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used. +if ($groupmode = groups_get_activity_groupmode($cm)) { // Groups are being used. if ($groupid = groups_get_activity_group($cm)) { if (!$group = groups_get_group($groupid)) { print_error('invalidgroupid'); @@ -61,10 +75,10 @@ $PAGE->set_popup_notification_allowed(false); $groupname = ''; } -$strchat = get_string('modulename', 'chat'); // must be before current_language() in chat_login_user() to force course language!!! +$strchat = get_string('modulename', 'chat'); // Must be before current_language() in chat_login_user() to force course language! $strchats = get_string('modulenameplural', 'chat'); -$stridle = get_String('idle', 'chat'); -if (!$chat_sid = chat_login_user($chat->id, 'basic', $groupid, $course)) { +$stridle = get_string('idle', 'chat'); +if (!$chatsid = chat_login_user($chat->id, 'basic', $groupid, $course)) { print_error('cantlogin', 'chat'); } @@ -72,7 +86,7 @@ if (!$chatusers = chat_get_users($chat->id, $groupid, $cm->groupingid)) { print_error('errornousers', 'chat'); } -$DB->set_field('chat_users', 'lastping', time(), array('sid'=>$chat_sid)); +$DB->set_field('chat_users', 'lastping', time(), array('sid' => $chatsid)); if (!isset($SESSION->chatprefs)) { $SESSION->chatprefs = array(); @@ -92,21 +106,21 @@ if (!empty($refresh) and data_submitted()) { } else if (empty($refresh) and data_submitted() and confirm_sesskey()) { - if ($message!='') { + if ($message != '') { - $chatuser = $DB->get_record('chat_users', array('sid' => $chat_sid)); + $chatuser = $DB->get_record('chat_users', array('sid' => $chatsid)); chat_send_chatmessage($chatuser, $message, 0, $cm); - $DB->set_field('chat_users', 'lastmessageping', time(), array('sid'=>$chat_sid)); + $DB->set_field('chat_users', 'lastmessageping', time(), array('sid' => $chatsid)); } chat_delete_old_users(); - $url = new moodle_url('/mod/chat/gui_basic/index.php', array('id'=>$id, 'newonly'=>$newonly, 'last'=>$last)); + $url = new moodle_url('/mod/chat/gui_basic/index.php', array('id' => $id, 'newonly' => $newonly, 'last' => $last)); redirect($url); } -$PAGE->set_title("$strchat: $course->shortname: ".format_string($chat->name,true)."$groupname"); +$PAGE->set_title("$strchat: $course->shortname: ".format_string($chat->name, true)."$groupname"); echo $OUTPUT->header(); echo $OUTPUT->container_start(null, 'page-mod-chat-gui_basic'); @@ -117,9 +131,9 @@ echo $OUTPUT->heading(get_string('participants'), 3); echo $OUTPUT->box_start('generalbox', 'participants'); echo '