Merge branch 'MDL-50853-master' of git://github.com/jleyva/moodle
authorDan Poltawski <dan@moodle.com>
Tue, 8 Sep 2015 12:37:35 +0000 (13:37 +0100)
committerDan Poltawski <dan@moodle.com>
Tue, 8 Sep 2015 12:37:35 +0000 (13:37 +0100)
lib/db/services.php
mod/chat/chat_ajax.php
mod/chat/classes/external.php [new file with mode: 0644]
mod/chat/db/services.php [new file with mode: 0644]
mod/chat/lib.php
mod/chat/tests/externallib_test.php [new file with mode: 0644]
mod/chat/version.php
mod/chat/view.php
version.php

index 70187da..8e4fc13 100644 (file)
@@ -1160,6 +1160,11 @@ $services = array(
             'mod_page_view_page',
             'mod_resource_view_resource',
             'mod_folder_view_folder',
+            'mod_chat_login_user',
+            'mod_chat_get_chat_users',
+            'mod_chat_send_chat_message',
+            'mod_chat_get_chat_latest_messages',
+            'mod_chat_view_chat',
             ),
         'enabled' => 0,
         'restrictedusers' => 0,
index 076371a..02bd5d4 100644 (file)
@@ -109,13 +109,7 @@ switch ($action) {
             $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');
+        $messages = chat_get_latest_messages($chatuser, $chatlasttime);
 
         if (!empty($messages)) {
             $num = count($messages);
diff --git a/mod/chat/classes/external.php b/mod/chat/classes/external.php
new file mode 100644 (file)
index 0000000..26204d6
--- /dev/null
@@ -0,0 +1,496 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Chat external API
+ *
+ * @package    mod_chat
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      Moodle 3.0
+ */
+
+defined('MOODLE_INTERNAL') || die;
+
+require_once($CFG->libdir . '/externallib.php');
+require_once($CFG->dirroot . '/mod/chat/lib.php');
+
+/**
+ * Chat external functions
+ *
+ * @package    mod_chat
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      Moodle 3.0
+ */
+class mod_chat_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.0
+     */
+    public static function login_user_parameters() {
+        return new external_function_parameters(
+            array(
+                'chatid' => new external_value(PARAM_INT, 'chat instance id'),
+                'groupid' => new external_value(PARAM_INT, 'group id, 0 means that the function will determine the user group',
+                                                VALUE_DEFAULT, 0),
+            )
+        );
+    }
+
+    /**
+     * Log the current user into a chat room in the given chat.
+     *
+     * @param int $chatid the chat instance id
+     * @param int $groupid the user group id
+     * @return array of warnings and the chat unique session id
+     * @since Moodle 3.0
+     * @throws moodle_exception
+     */
+    public static function login_user($chatid, $groupid = 0) {
+        global $DB;
+
+        $params = self::validate_parameters(self::login_user_parameters(),
+                                            array(
+                                                'chatid' => $chatid,
+                                                'groupid' => $groupid
+                                            ));
+        $warnings = array();
+
+        // Request and permission validation.
+        $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
+        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
+
+        $context = context_module::instance($cm->id);
+        self::validate_context($context);
+
+        require_capability('mod/chat:chat', $context);
+
+        if (!empty($params['groupid'])) {
+            $groupid = $params['groupid'];
+            // Determine is the group is visible to user.
+            if (!groups_group_visible($groupid, $course, $cm)) {
+                throw new moodle_exception('notingroup');
+            }
+        } else {
+            // Check to see if groups are being used here.
+            if ($groupmode = groups_get_activity_groupmode($cm)) {
+                $groupid = groups_get_activity_group($cm);
+                // Determine is the group is visible to user (this is particullary for the group 0).
+                if (!groups_group_visible($groupid, $course, $cm)) {
+                    throw new moodle_exception('notingroup');
+                }
+            } else {
+                $groupid = 0;
+            }
+        }
+
+        // Get the unique chat session id.
+        // Since we are going to use the chat via Web Service requests we set the ajax version (since it's the most similar).
+        if (!$chatsid = chat_login_user($chat->id, 'ajax', $groupid, $course)) {
+            throw moodle_exception('cantlogin', 'chat');
+        }
+
+        $result = array();
+        $result['chatsid'] = $chatsid;
+        $result['warnings'] = $warnings;
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.0
+     */
+    public static function login_user_returns() {
+        return new external_single_structure(
+            array(
+                'chatsid' => new external_value(PARAM_ALPHANUM, 'unique chat session id'),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.0
+     */
+    public static function get_chat_users_parameters() {
+        return new external_function_parameters(
+            array(
+                'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)')
+            )
+        );
+    }
+
+    /**
+     * Get the list of users in the given chat session.
+     *
+     * @param int $chatsid the chat session id
+     * @return array of warnings and the user lists
+     * @since Moodle 3.0
+     * @throws moodle_exception
+     */
+    public static function get_chat_users($chatsid) {
+        global $DB;
+
+        $params = self::validate_parameters(self::get_chat_users_parameters(),
+                                            array(
+                                                'chatsid' => $chatsid
+                                            ));
+        $warnings = array();
+
+        // Request and permission validation.
+        if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
+            throw new moodle_exception('notlogged', 'chat');
+        }
+        $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
+        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
+
+        $context = context_module::instance($cm->id);
+        self::validate_context($context);
+
+        require_capability('mod/chat:chat', $context);
+
+        // First, delete old users from the chats.
+        chat_delete_old_users();
+
+        $users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
+        $returnedusers = array();
+
+        foreach ($users as $user) {
+            $usercontext = context_user::instance($user->id, IGNORE_MISSING);
+            $profileimageurl = '';
+
+            if ($usercontext) {
+                $profileimageurl = moodle_url::make_webservice_pluginfile_url(
+                                    $usercontext->id, 'user', 'icon', null, '/', 'f1')->out(false);
+            }
+
+            $returnedusers[] = array(
+                'id' => $user->id,
+                'fullname' => fullname($user),
+                'profileimageurl' => $profileimageurl
+            );
+        }
+
+        $result = array();
+        $result['users'] = $returnedusers;
+        $result['warnings'] = $warnings;
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.0
+     */
+    public static function get_chat_users_returns() {
+        return new external_single_structure(
+            array(
+                'users' => new external_multiple_structure(
+                    new external_single_structure(
+                        array(
+                            'id' => new external_value(PARAM_INT, 'user id'),
+                            'fullname' => new external_value(PARAM_NOTAGS, 'user full name'),
+                            'profileimageurl' => new external_value(PARAM_URL, 'user picture URL'),
+                        )
+                    ),
+                    'list of users'
+                ),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.0
+     */
+    public static function send_chat_message_parameters() {
+        return new external_function_parameters(
+            array(
+                'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)'),
+                'messagetext' => new external_value(PARAM_RAW, 'the message text'),
+                'beepid' => new external_value(PARAM_RAW, 'the beep id', VALUE_DEFAULT, ''),
+
+            )
+        );
+    }
+
+    /**
+     * Send a message on the given chat session.
+     *
+     * @param int $chatsid the chat session id
+     * @param string $messagetext the message text
+     * @param string $beepid the beep message id
+     * @return array of warnings and the new message id (0 if the message was empty)
+     * @since Moodle 3.0
+     * @throws moodle_exception
+     */
+    public static function send_chat_message($chatsid, $messagetext, $beepid = '') {
+        global $DB;
+
+        $params = self::validate_parameters(self::send_chat_message_parameters(),
+                                            array(
+                                                'chatsid' => $chatsid,
+                                                'messagetext' => $messagetext,
+                                                'beepid' => $beepid
+                                            ));
+        $warnings = array();
+
+        // Request and permission validation.
+        if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
+            throw new moodle_exception('notlogged', 'chat');
+        }
+        $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
+        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
+
+        $context = context_module::instance($cm->id);
+        self::validate_context($context);
+
+        require_capability('mod/chat:chat', $context);
+
+        $chatmessage = clean_text($params['messagetext'], FORMAT_MOODLE);
+
+        if (!empty($params['beepid'])) {
+            $chatmessage = 'beep ' . $params['beepid'];
+        }
+
+        if (!empty($chatmessage)) {
+            // Send the message.
+            $messageid = chat_send_chatmessage($chatuser, $chatmessage, 0, $cm);
+            // Update ping time.
+            $chatuser->lastmessageping = time() - 2;
+            $DB->update_record('chat_users', $chatuser);
+        } else {
+            $messageid = 0;
+        }
+
+        $result = array();
+        $result['messageid'] = $messageid;
+        $result['warnings'] = $warnings;
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.0
+     */
+    public static function send_chat_message_returns() {
+        return new external_single_structure(
+            array(
+                'messageid' => new external_value(PARAM_INT, 'message sent id'),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.0
+     */
+    public static function get_chat_latest_messages_parameters() {
+        return new external_function_parameters(
+            array(
+                'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)'),
+                'chatlasttime' => new external_value(PARAM_INT, 'last time messages were retrieved (epoch time)', VALUE_DEFAULT, 0)
+            )
+        );
+    }
+
+    /**
+     * Get the latest messages from the given chat session.
+     *
+     * @param int $chatsid the chat session id
+     * @param int $chatlasttime last time messages were retrieved (epoch time)
+     * @return array of warnings and the new message id (0 if the message was empty)
+     * @since Moodle 3.0
+     * @throws moodle_exception
+     */
+    public static function get_chat_latest_messages($chatsid, $chatlasttime = 0) {
+        global $DB, $CFG;
+
+        $params = self::validate_parameters(self::get_chat_latest_messages_parameters(),
+                                            array(
+                                                'chatsid' => $chatsid,
+                                                'chatlasttime' => $chatlasttime
+                                            ));
+        $warnings = array();
+
+        // Request and permission validation.
+        if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
+            throw new moodle_exception('notlogged', 'chat');
+        }
+        $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
+        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
+
+        $context = context_module::instance($cm->id);
+        self::validate_context($context);
+
+        require_capability('mod/chat:chat', $context);
+
+        $chatlasttime = $params['chatlasttime'];
+        if ((time() - $chatlasttime) > $CFG->chat_old_ping) {
+            chat_delete_old_users();
+        }
+
+        // Set default chat last time (to not retrieve all the conversations).
+        if ($chatlasttime == 0) {
+            $chatlasttime = time() - $CFG->chat_old_ping;
+        }
+
+        if ($latestmessage = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
+            $chatnewlasttime = $latestmessage->timestamp;
+        } else {
+            $chatnewlasttime = 0;
+        }
+
+        $messages = chat_get_latest_messages($chatuser, $chatlasttime);
+        $returnedmessages = array();
+
+        foreach ($messages as $message) {
+
+            // FORMAT_MOODLE is mandatory in the chat plugin.
+            list($messageformatted, $format) = external_format_text($message->message, FORMAT_MOODLE, $context->id, 'mod_chat',
+                                                                    '', 0);
+
+            $returnedmessages[] = array(
+                'id' => $message->id,
+                'userid' => $message->userid,
+                'system' => (bool) $message->system,
+                'message' => $messageformatted,
+                'timestamp' => $message->timestamp,
+            );
+        }
+
+        // Update our status since we are active in the chat.
+        $DB->set_field('chat_users', 'lastping', time(), array('id' => $chatuser->id));
+
+        $result = array();
+        $result['messages'] = $returnedmessages;
+        $result['chatnewlasttime'] = $chatnewlasttime;
+        $result['warnings'] = $warnings;
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.0
+     */
+    public static function get_chat_latest_messages_returns() {
+        return new external_single_structure(
+            array(
+                'messages' => new external_multiple_structure(
+                    new external_single_structure(
+                        array(
+                            'id' => new external_value(PARAM_INT, 'message id'),
+                            'userid' => new external_value(PARAM_INT, 'user id'),
+                            'system' => new external_value(PARAM_BOOL, 'true if is a system message (like user joined)'),
+                            'message' => new external_value(PARAM_RAW, 'message text'),
+                            'timestamp' => new external_value(PARAM_INT, 'timestamp for the message'),
+                        )
+                    ),
+                    'list of users'
+                ),
+                'chatnewlasttime' => new external_value(PARAM_INT, 'new last time'),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
+
+    /**
+     * Returns description of method parameters
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.0
+     */
+    public static function view_chat_parameters() {
+        return new external_function_parameters(
+            array(
+                'chatid' => new external_value(PARAM_INT, 'chat instance id')
+            )
+        );
+    }
+
+    /**
+     * Trigger the course module viewed event and update the module completion status.
+     *
+     * @param int $chatid the chat instance id
+     * @return array of warnings and status result
+     * @since Moodle 3.0
+     * @throws moodle_exception
+     */
+    public static function view_chat($chatid) {
+        global $DB, $CFG;
+
+        $params = self::validate_parameters(self::view_chat_parameters(),
+                                            array(
+                                                'chatid' => $chatid
+                                            ));
+        $warnings = array();
+
+        // Request and permission validation.
+        $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
+        list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
+
+        $context = context_module::instance($cm->id);
+        self::validate_context($context);
+
+        require_capability('mod/chat:chat', $context);
+
+        // Call the url/lib API.
+        chat_view($chat, $course, $cm, $context);
+
+        $result = array();
+        $result['status'] = true;
+        $result['warnings'] = $warnings;
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     *
+     * @return external_description
+     * @since Moodle 3.0
+     */
+    public static function view_chat_returns() {
+        return new external_single_structure(
+            array(
+                'status' => new external_value(PARAM_BOOL, 'status: true if success'),
+                'warnings' => new external_warnings()
+            )
+        );
+    }
+
+}
diff --git a/mod/chat/db/services.php b/mod/chat/db/services.php
new file mode 100644 (file)
index 0000000..750943f
--- /dev/null
@@ -0,0 +1,71 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Chat external functions and service definitions.
+ *
+ * @package    mod_chat
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      Moodle 3.0
+ */
+
+defined('MOODLE_INTERNAL') || die;
+
+$functions = array(
+
+    'mod_chat_login_user' => array(
+        'classname'     => 'mod_chat_external',
+        'methodname'    => 'login_user',
+        'description'   => 'Log a user into a chat room in the given chat.',
+        'type'          => 'write',
+        'capabilities'  => 'mod/chat:chat'
+    ),
+
+    'mod_chat_get_chat_users' => array(
+        'classname'     => 'mod_chat_external',
+        'methodname'    => 'get_chat_users',
+        'description'   => 'Get the list of users in the given chat session.',
+        'type'          => 'read',
+        'capabilities'  => 'mod/chat:chat'
+    ),
+
+    'mod_chat_send_chat_message' => array(
+        'classname'     => 'mod_chat_external',
+        'methodname'    => 'send_chat_message',
+        'description'   => 'Send a message on the given chat session.',
+        'type'          => 'write',
+        'capabilities'  => 'mod/chat:chat'
+    ),
+
+    'mod_chat_get_chat_latest_messages' => array(
+        'classname'     => 'mod_chat_external',
+        'methodname'    => 'get_chat_latest_messages',
+        'description'   => 'Get the latest messages from the given chat session.',
+        'type'          => 'read',
+        'capabilities'  => 'mod/chat:chat'
+    ),
+
+    'mod_chat_view_chat' => array(
+        'classname'     => 'mod_chat_external',
+        'methodname'    => 'view_chat',
+        'description'   => 'Trigger the course module viewed event and update the module completion status.',
+        'type'          => 'write',
+        'capabilities'  => 'mod/chat:chat'
+    ),
+
+);
index c575fa8..848fd47 100644 (file)
@@ -1304,3 +1304,50 @@ function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
     $modulepagetype = array('mod-chat-*' => get_string('page-mod-chat-x', 'chat'));
     return $modulepagetype;
 }
+
+/**
+ * Return a list of the latest messages in the given chat session.
+ *
+ * @param  stdClass $chatuser     chat user session data
+ * @param  int      $chatlasttime last time messages were retrieved
+ * @return array    list of messages
+ * @since  Moodle 3.0
+ */
+function chat_get_latest_messages($chatuser, $chatlasttime) {
+    global $DB;
+
+    $params = array('groupid' => $chatuser->groupid, 'chatid' => $chatuser->chatid, 'lasttime' => $chatlasttime);
+
+    $groupselect = $chatuser->groupid ? " AND (groupid=" . $chatuser->groupid . " OR groupid=0) " : "";
+
+    return $DB->get_records_select('chat_messages_current', 'chatid = :chatid AND timestamp > :lasttime ' . $groupselect,
+                                    $params, 'timestamp ASC');
+}
+
+/**
+ * Mark the activity completed (if required) and trigger the course_module_viewed event.
+ *
+ * @param  stdClass $chat       chat object
+ * @param  stdClass $course     course object
+ * @param  stdClass $cm         course module object
+ * @param  stdClass $context    context object
+ * @since Moodle 3.0
+ */
+function chat_view($chat, $course, $cm, $context) {
+
+    // Trigger course_module_viewed event.
+    $params = array(
+        'context' => $context,
+        'objectid' => $chat->id
+    );
+
+    $event = \mod_chat\event\course_module_viewed::create($params);
+    $event->add_record_snapshot('course_modules', $cm);
+    $event->add_record_snapshot('course', $course);
+    $event->add_record_snapshot('chat', $chat);
+    $event->trigger();
+
+    // Completion.
+    $completion = new completion_info($course);
+    $completion->set_module_viewed($cm);
+}
diff --git a/mod/chat/tests/externallib_test.php b/mod/chat/tests/externallib_test.php
new file mode 100644 (file)
index 0000000..5497b24
--- /dev/null
@@ -0,0 +1,222 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * External mod_chat functions unit tests
+ *
+ * @package    mod_chat
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      Moodle 3.0
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+global $CFG;
+
+require_once($CFG->dirroot . '/webservice/tests/helpers.php');
+
+/**
+ * External mod_chat functions unit tests
+ *
+ * @package    mod_chat
+ * @category   external
+ * @copyright  2015 Juan Leyva <juan@moodle.com>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @since      Moodle 3.0
+ */
+class mod_chat_external_testcase extends externallib_advanced_testcase {
+
+    /**
+     * Test login user
+     */
+    public function test_login_user() {
+        global $DB;
+
+        $this->resetAfterTest(true);
+
+        // Setup test data.
+        $this->setAdminUser();
+        $course = $this->getDataGenerator()->create_course();
+        $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
+
+        $user = self::getDataGenerator()->create_user();
+        $this->setUser($user);
+        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
+        $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
+
+        $result = mod_chat_external::login_user($chat->id);
+        $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
+
+        // Test session started.
+        $sid = $DB->get_field('chat_users', 'sid', array('userid' => $user->id, 'chatid' => $chat->id));
+        $this->assertEquals($result['chatsid'], $sid);
+
+    }
+
+    /**
+     * Test get chat users
+     */
+    public function test_get_chat_users() {
+        global $DB;
+
+        $this->resetAfterTest(true);
+
+        // Setup test data.
+        $this->setAdminUser();
+        $course = $this->getDataGenerator()->create_course();
+        $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
+
+        $user1 = self::getDataGenerator()->create_user();
+        $user2 = self::getDataGenerator()->create_user();
+
+        $this->setUser($user1);
+        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
+        $this->getDataGenerator()->enrol_user($user1->id, $course->id, $studentrole->id);
+        $this->getDataGenerator()->enrol_user($user2->id, $course->id, $studentrole->id);
+
+        $result = mod_chat_external::login_user($chat->id);
+        $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
+
+        $this->setUser($user2);
+        $result = mod_chat_external::login_user($chat->id);
+        $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
+
+        // Get users.
+        $result = mod_chat_external::get_chat_users($result['chatsid']);
+        $result = external_api::clean_returnvalue(mod_chat_external::get_chat_users_returns(), $result);
+
+        // Check correct users.
+        $this->assertCount(2, $result['users']);
+        $found = 0;
+        foreach ($result['users'] as $user) {
+            if ($user['id'] == $user1->id or $user['id'] == $user2->id) {
+                $found++;
+            }
+        }
+        $this->assertEquals(2, $found);
+
+    }
+
+    /**
+     * Test send and get chat messages
+     */
+    public function test_send_get_chat_message() {
+        global $DB;
+
+        $this->resetAfterTest(true);
+
+        // Setup test data.
+        $this->setAdminUser();
+        $course = $this->getDataGenerator()->create_course();
+        $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
+
+        $user = self::getDataGenerator()->create_user();
+        $this->setUser($user);
+        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
+        $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
+
+        $result = mod_chat_external::login_user($chat->id);
+        $result = external_api::clean_returnvalue(mod_chat_external::login_user_returns(), $result);
+        $chatsid = $result['chatsid'];
+
+        $result = mod_chat_external::send_chat_message($chatsid, 'hello!');
+        $result = external_api::clean_returnvalue(mod_chat_external::send_chat_message_returns(), $result);
+
+        // Test messages received.
+
+        $result = mod_chat_external::get_chat_latest_messages($chatsid, 0);
+        $result = external_api::clean_returnvalue(mod_chat_external::get_chat_latest_messages_returns(), $result);
+
+        foreach ($result['messages'] as $message) {
+            // Ommit system messages, like user just joined in.
+            if ($message['system']) {
+                continue;
+            }
+            $this->assertEquals('hello!', $message['message']);
+        }
+    }
+
+    /**
+     * Test view_chat
+     */
+    public function test_view_chat() {
+        global $DB;
+
+        $this->resetAfterTest(true);
+
+        // Setup test data.
+        $this->setAdminUser();
+        $course = $this->getDataGenerator()->create_course();
+        $chat = $this->getDataGenerator()->create_module('chat', array('course' => $course->id));
+        $context = context_module::instance($chat->cmid);
+        $cm = get_coursemodule_from_instance('chat', $chat->id);
+
+        // Test invalid instance id.
+        try {
+            mod_chat_external::view_chat(0);
+            $this->fail('Exception expected due to invalid mod_chat instance id.');
+        } catch (moodle_exception $e) {
+            $this->assertEquals('invalidrecord', $e->errorcode);
+        }
+
+        // Test not-enrolled user.
+        $user = self::getDataGenerator()->create_user();
+        $this->setUser($user);
+        try {
+            mod_chat_external::view_chat($chat->id);
+            $this->fail('Exception expected due to not enrolled user.');
+        } catch (moodle_exception $e) {
+            $this->assertEquals('requireloginerror', $e->errorcode);
+        }
+
+        // Test user with full capabilities.
+        $studentrole = $DB->get_record('role', array('shortname' => 'student'));
+        $this->getDataGenerator()->enrol_user($user->id, $course->id, $studentrole->id);
+
+        // Trigger and capture the event.
+        $sink = $this->redirectEvents();
+
+        $result = mod_chat_external::view_chat($chat->id);
+        $result = external_api::clean_returnvalue(mod_chat_external::view_chat_returns(), $result);
+
+        $events = $sink->get_events();
+        $this->assertCount(1, $events);
+        $event = array_shift($events);
+
+        // Checking that the event contains the expected values.
+        $this->assertInstanceOf('\mod_chat\event\course_module_viewed', $event);
+        $this->assertEquals($context, $event->get_context());
+        $moodlechat = new \moodle_url('/mod/chat/view.php', array('id' => $cm->id));
+        $this->assertEquals($moodlechat, $event->get_url());
+        $this->assertEventContextNotUsed($event);
+        $this->assertNotEmpty($event->get_name());
+
+        // Test user with no capabilities.
+        // We need a explicit prohibit since this capability is only defined in authenticated user and guest roles.
+        assign_capability('mod/chat:chat', CAP_PROHIBIT, $studentrole->id, $context->id);
+        accesslib_clear_all_caches_for_unit_testing();
+
+        try {
+            mod_chat_external::view_chat($chat->id);
+            $this->fail('Exception expected due to missing capability.');
+        } catch (moodle_exception $e) {
+            $this->assertEquals('nopermissions', $e->errorcode);
+        }
+
+    }
+}
index 0d659b3..13c3965 100644 (file)
@@ -24,7 +24,7 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version   = 2015051100; // The current module version (Date: YYYYMMDDXX).
+$plugin->version   = 2015051101; // The current module version (Date: YYYYMMDDXX).
 $plugin->requires  = 2015050500; // Requires this Moodle version.
 $plugin->component = 'mod_chat'; // Full name of the plugin (used for diagnostics).
 $plugin->cron      = 300;
index 8740654..55478d7 100644 (file)
@@ -69,15 +69,8 @@ if (isguestuser()) {
     exit;
 }
 
-// Log this request - the problem here is that the view page
-// does not display the chat content which is actually in a new window.
-$params = array(
-    'objectid' => $chat->id,
-    'context' => $context
-);
-$event = \mod_chat\event\course_module_viewed::create($params);
-$event->add_record_snapshot('chat', $chat);
-$event->trigger();
+// Completion and trigger events.
+chat_view($chat, $course, $cm, $context);
 
 $strenterchat    = get_string('enterchat', 'chat');
 $stridle         = get_string('idle', 'chat');
@@ -87,10 +80,6 @@ $strnextsession  = get_string('nextsession', 'chat');
 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
 $title = $courseshortname . ': ' . format_string($chat->name);
 
-// Mark viewed by user (if required).
-$completion = new completion_info($course);
-$completion->set_module_viewed($cm);
-
 // Initialize $PAGE.
 $PAGE->set_url('/mod/chat/view.php', array('id' => $cm->id));
 $PAGE->set_title($title);
index cbbb354..9441797 100644 (file)
@@ -29,7 +29,7 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$version  = 2015090801.00;              // YYYYMMDD      = weekly release date of this DEV branch.
+$version  = 2015090802.00;              // YYYYMMDD      = weekly release date of this DEV branch.
                                         //         RR    = release increments - 00 in DEV branches.
                                         //           .XX = incremental changes.