Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Chat external API
  19   *
  20   * @package    mod_chat
  21   * @category   external
  22   * @copyright  2015 Juan Leyva <juan@moodle.com>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   * @since      Moodle 3.0
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die;
  28  
  29  require_once($CFG->libdir . '/externallib.php');
  30  require_once($CFG->dirroot . '/mod/chat/lib.php');
  31  
  32  use core_course\external\helper_for_get_mods_by_courses;
  33  use mod_chat\external\chat_message_exporter;
  34  
  35  /**
  36   * Chat external functions
  37   *
  38   * @package    mod_chat
  39   * @category   external
  40   * @copyright  2015 Juan Leyva <juan@moodle.com>
  41   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42   * @since      Moodle 3.0
  43   */
  44  class mod_chat_external extends external_api {
  45  
  46      /**
  47       * Returns description of method parameters
  48       *
  49       * @return external_function_parameters
  50       * @since Moodle 3.0
  51       */
  52      public static function login_user_parameters() {
  53          return new external_function_parameters(
  54              array(
  55                  'chatid' => new external_value(PARAM_INT, 'chat instance id'),
  56                  'groupid' => new external_value(PARAM_INT, 'group id, 0 means that the function will determine the user group',
  57                                                  VALUE_DEFAULT, 0),
  58              )
  59          );
  60      }
  61  
  62      /**
  63       * Log the current user into a chat room in the given chat.
  64       *
  65       * @param int $chatid the chat instance id
  66       * @param int $groupid the user group id
  67       * @return array of warnings and the chat unique session id
  68       * @since Moodle 3.0
  69       * @throws moodle_exception
  70       */
  71      public static function login_user($chatid, $groupid = 0) {
  72          global $DB;
  73  
  74          $params = self::validate_parameters(self::login_user_parameters(),
  75                                              array(
  76                                                  'chatid' => $chatid,
  77                                                  'groupid' => $groupid
  78                                              ));
  79          $warnings = array();
  80  
  81          // Request and permission validation.
  82          $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
  83          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
  84  
  85          $context = context_module::instance($cm->id);
  86          self::validate_context($context);
  87  
  88          require_capability('mod/chat:chat', $context);
  89  
  90          if (!empty($params['groupid'])) {
  91              $groupid = $params['groupid'];
  92              // Determine is the group is visible to user.
  93              if (!groups_group_visible($groupid, $course, $cm)) {
  94                  throw new moodle_exception('notingroup');
  95              }
  96          } else {
  97              // Check to see if groups are being used here.
  98              if ($groupmode = groups_get_activity_groupmode($cm)) {
  99                  $groupid = groups_get_activity_group($cm);
 100                  // Determine is the group is visible to user (this is particullary for the group 0).
 101                  if (!groups_group_visible($groupid, $course, $cm)) {
 102                      throw new moodle_exception('notingroup');
 103                  }
 104              } else {
 105                  $groupid = 0;
 106              }
 107          }
 108  
 109          // Get the unique chat session id.
 110          // Since we are going to use the chat via Web Service requests we set the ajax version (since it's the most similar).
 111          if (!$chatsid = chat_login_user($chat->id, 'ajax', $groupid, $course)) {
 112              throw new moodle_exception('cantlogin', 'chat');
 113          }
 114  
 115          $result = array();
 116          $result['chatsid'] = $chatsid;
 117          $result['warnings'] = $warnings;
 118          return $result;
 119      }
 120  
 121      /**
 122       * Returns description of method result value
 123       *
 124       * @return external_description
 125       * @since Moodle 3.0
 126       */
 127      public static function login_user_returns() {
 128          return new external_single_structure(
 129              array(
 130                  'chatsid' => new external_value(PARAM_ALPHANUM, 'unique chat session id'),
 131                  'warnings' => new external_warnings()
 132              )
 133          );
 134      }
 135  
 136      /**
 137       * Returns description of method parameters
 138       *
 139       * @return external_function_parameters
 140       * @since Moodle 3.0
 141       */
 142      public static function get_chat_users_parameters() {
 143          return new external_function_parameters(
 144              array(
 145                  'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)')
 146              )
 147          );
 148      }
 149  
 150      /**
 151       * Get the list of users in the given chat session.
 152       *
 153       * @param int $chatsid the chat session id
 154       * @return array of warnings and the user lists
 155       * @since Moodle 3.0
 156       * @throws moodle_exception
 157       */
 158      public static function get_chat_users($chatsid) {
 159          global $DB, $PAGE;
 160  
 161          $params = self::validate_parameters(self::get_chat_users_parameters(),
 162                                              array(
 163                                                  'chatsid' => $chatsid
 164                                              ));
 165          $warnings = array();
 166  
 167          // Request and permission validation.
 168          if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
 169              throw new moodle_exception('notlogged', 'chat');
 170          }
 171          $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
 172          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 173  
 174          $context = context_module::instance($cm->id);
 175          self::validate_context($context);
 176  
 177          require_capability('mod/chat:chat', $context);
 178  
 179          // First, delete old users from the chats.
 180          chat_delete_old_users();
 181  
 182          $users = chat_get_users($chatuser->chatid, $chatuser->groupid, $cm->groupingid);
 183          $returnedusers = array();
 184  
 185          foreach ($users as $user) {
 186  
 187              $userpicture = new user_picture($user);
 188              $userpicture->size = 1; // Size f1.
 189              $profileimageurl = $userpicture->get_url($PAGE)->out(false);
 190  
 191              $returnedusers[] = array(
 192                  'id' => $user->id,
 193                  'fullname' => fullname($user),
 194                  'profileimageurl' => $profileimageurl
 195              );
 196          }
 197  
 198          $result = array();
 199          $result['users'] = $returnedusers;
 200          $result['warnings'] = $warnings;
 201          return $result;
 202      }
 203  
 204      /**
 205       * Returns description of method result value
 206       *
 207       * @return external_description
 208       * @since Moodle 3.0
 209       */
 210      public static function get_chat_users_returns() {
 211          return new external_single_structure(
 212              array(
 213                  'users' => new external_multiple_structure(
 214                      new external_single_structure(
 215                          array(
 216                              'id' => new external_value(PARAM_INT, 'user id'),
 217                              'fullname' => new external_value(PARAM_NOTAGS, 'user full name'),
 218                              'profileimageurl' => new external_value(PARAM_URL, 'user picture URL'),
 219                          )
 220                      ),
 221                      'list of users'
 222                  ),
 223                  'warnings' => new external_warnings()
 224              )
 225          );
 226      }
 227  
 228      /**
 229       * Returns description of method parameters
 230       *
 231       * @return external_function_parameters
 232       * @since Moodle 3.0
 233       */
 234      public static function send_chat_message_parameters() {
 235          return new external_function_parameters(
 236              array(
 237                  'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)'),
 238                  'messagetext' => new external_value(PARAM_RAW, 'the message text'),
 239                  'beepid' => new external_value(PARAM_RAW, 'the beep id', VALUE_DEFAULT, ''),
 240  
 241              )
 242          );
 243      }
 244  
 245      /**
 246       * Send a message on the given chat session.
 247       *
 248       * @param int $chatsid the chat session id
 249       * @param string $messagetext the message text
 250       * @param string $beepid the beep message id
 251       * @return array of warnings and the new message id (0 if the message was empty)
 252       * @since Moodle 3.0
 253       * @throws moodle_exception
 254       */
 255      public static function send_chat_message($chatsid, $messagetext, $beepid = '') {
 256          global $DB;
 257  
 258          $params = self::validate_parameters(self::send_chat_message_parameters(),
 259                                              array(
 260                                                  'chatsid' => $chatsid,
 261                                                  'messagetext' => $messagetext,
 262                                                  'beepid' => $beepid
 263                                              ));
 264          $warnings = array();
 265  
 266          // Request and permission validation.
 267          if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
 268              throw new moodle_exception('notlogged', 'chat');
 269          }
 270          $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
 271          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 272  
 273          $context = context_module::instance($cm->id);
 274          self::validate_context($context);
 275  
 276          require_capability('mod/chat:chat', $context);
 277  
 278          $chatmessage = clean_text($params['messagetext'], FORMAT_MOODLE);
 279  
 280          if (!empty($params['beepid'])) {
 281              $chatmessage = 'beep ' . $params['beepid'];
 282          }
 283  
 284          if (!empty($chatmessage)) {
 285              // Send the message.
 286              $messageid = chat_send_chatmessage($chatuser, $chatmessage, 0, $cm);
 287              // Update ping time.
 288              $chatuser->lastmessageping = time() - 2;
 289              $DB->update_record('chat_users', $chatuser);
 290          } else {
 291              $messageid = 0;
 292          }
 293  
 294          $result = array();
 295          $result['messageid'] = $messageid;
 296          $result['warnings'] = $warnings;
 297          return $result;
 298      }
 299  
 300      /**
 301       * Returns description of method result value
 302       *
 303       * @return external_description
 304       * @since Moodle 3.0
 305       */
 306      public static function send_chat_message_returns() {
 307          return new external_single_structure(
 308              array(
 309                  'messageid' => new external_value(PARAM_INT, 'message sent id'),
 310                  'warnings' => new external_warnings()
 311              )
 312          );
 313      }
 314  
 315      /**
 316       * Returns description of method parameters
 317       *
 318       * @return external_function_parameters
 319       * @since Moodle 3.0
 320       */
 321      public static function get_chat_latest_messages_parameters() {
 322          return new external_function_parameters(
 323              array(
 324                  'chatsid' => new external_value(PARAM_ALPHANUM, 'chat session id (obtained via mod_chat_login_user)'),
 325                  'chatlasttime' => new external_value(PARAM_INT, 'last time messages were retrieved (epoch time)', VALUE_DEFAULT, 0)
 326              )
 327          );
 328      }
 329  
 330      /**
 331       * Get the latest messages from the given chat session.
 332       *
 333       * @param int $chatsid the chat session id
 334       * @param int $chatlasttime last time messages were retrieved (epoch time)
 335       * @return array of warnings and the new message id (0 if the message was empty)
 336       * @since Moodle 3.0
 337       * @throws moodle_exception
 338       */
 339      public static function get_chat_latest_messages($chatsid, $chatlasttime = 0) {
 340          global $DB, $CFG;
 341  
 342          $params = self::validate_parameters(self::get_chat_latest_messages_parameters(),
 343                                              array(
 344                                                  'chatsid' => $chatsid,
 345                                                  'chatlasttime' => $chatlasttime
 346                                              ));
 347          $warnings = array();
 348  
 349          // Request and permission validation.
 350          if (!$chatuser = $DB->get_record('chat_users', array('sid' => $params['chatsid']))) {
 351              throw new moodle_exception('notlogged', 'chat');
 352          }
 353          $chat = $DB->get_record('chat', array('id' => $chatuser->chatid), '*', MUST_EXIST);
 354          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 355  
 356          $context = context_module::instance($cm->id);
 357          self::validate_context($context);
 358  
 359          require_capability('mod/chat:chat', $context);
 360  
 361          $chatlasttime = $params['chatlasttime'];
 362          if ((time() - $chatlasttime) > $CFG->chat_old_ping) {
 363              chat_delete_old_users();
 364          }
 365  
 366          // Set default chat last time (to not retrieve all the conversations).
 367          if ($chatlasttime == 0) {
 368              $chatlasttime = time() - $CFG->chat_old_ping;
 369          }
 370  
 371          if ($latestmessage = chat_get_latest_message($chatuser->chatid, $chatuser->groupid)) {
 372              $chatnewlasttime = $latestmessage->timestamp;
 373          } else {
 374              $chatnewlasttime = 0;
 375          }
 376  
 377          $messages = chat_get_latest_messages($chatuser, $chatlasttime);
 378          $returnedmessages = array();
 379  
 380          foreach ($messages as $message) {
 381  
 382              // FORMAT_MOODLE is mandatory in the chat plugin.
 383              list($messageformatted, $format) = external_format_text($message->message, FORMAT_MOODLE, $context->id, 'mod_chat',
 384                                                                      '', 0);
 385  
 386              $returnedmessages[] = array(
 387                  'id' => $message->id,
 388                  'userid' => $message->userid,
 389                  'system' => (bool) $message->issystem,
 390                  'message' => $messageformatted,
 391                  'timestamp' => $message->timestamp,
 392              );
 393          }
 394  
 395          // Update our status since we are active in the chat.
 396          $DB->set_field('chat_users', 'lastping', time(), array('id' => $chatuser->id));
 397  
 398          $result = array();
 399          $result['messages'] = $returnedmessages;
 400          $result['chatnewlasttime'] = $chatnewlasttime;
 401          $result['warnings'] = $warnings;
 402          return $result;
 403      }
 404  
 405      /**
 406       * Returns description of method result value
 407       *
 408       * @return external_description
 409       * @since Moodle 3.0
 410       */
 411      public static function get_chat_latest_messages_returns() {
 412          return new external_single_structure(
 413              array(
 414                  'messages' => new external_multiple_structure(
 415                      new external_single_structure(
 416                          array(
 417                              'id' => new external_value(PARAM_INT, 'message id'),
 418                              'userid' => new external_value(PARAM_INT, 'user id'),
 419                              'system' => new external_value(PARAM_BOOL, 'true if is a system message (like user joined)'),
 420                              'message' => new external_value(PARAM_RAW, 'message text'),
 421                              'timestamp' => new external_value(PARAM_INT, 'timestamp for the message'),
 422                          )
 423                      ),
 424                      'list of users'
 425                  ),
 426                  'chatnewlasttime' => new external_value(PARAM_INT, 'new last time'),
 427                  'warnings' => new external_warnings()
 428              )
 429          );
 430      }
 431  
 432      /**
 433       * Returns description of method parameters
 434       *
 435       * @return external_function_parameters
 436       * @since Moodle 3.0
 437       */
 438      public static function view_chat_parameters() {
 439          return new external_function_parameters(
 440              array(
 441                  'chatid' => new external_value(PARAM_INT, 'chat instance id')
 442              )
 443          );
 444      }
 445  
 446      /**
 447       * Trigger the course module viewed event and update the module completion status.
 448       *
 449       * @param int $chatid the chat instance id
 450       * @return array of warnings and status result
 451       * @since Moodle 3.0
 452       * @throws moodle_exception
 453       */
 454      public static function view_chat($chatid) {
 455          global $DB, $CFG;
 456  
 457          $params = self::validate_parameters(self::view_chat_parameters(),
 458                                              array(
 459                                                  'chatid' => $chatid
 460                                              ));
 461          $warnings = array();
 462  
 463          // Request and permission validation.
 464          $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
 465          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 466  
 467          $context = context_module::instance($cm->id);
 468          self::validate_context($context);
 469  
 470          require_capability('mod/chat:chat', $context);
 471  
 472          // Call the url/lib API.
 473          chat_view($chat, $course, $cm, $context);
 474  
 475          $result = array();
 476          $result['status'] = true;
 477          $result['warnings'] = $warnings;
 478          return $result;
 479      }
 480  
 481      /**
 482       * Returns description of method result value
 483       *
 484       * @return external_description
 485       * @since Moodle 3.0
 486       */
 487      public static function view_chat_returns() {
 488          return new external_single_structure(
 489              array(
 490                  'status' => new external_value(PARAM_BOOL, 'status: true if success'),
 491                  'warnings' => new external_warnings()
 492              )
 493          );
 494      }
 495  
 496  
 497      /**
 498       * Describes the parameters for get_chats_by_courses.
 499       *
 500       * @return external_function_parameters
 501       * @since Moodle 3.0
 502       */
 503      public static function get_chats_by_courses_parameters() {
 504          return new external_function_parameters (
 505              array(
 506                  'courseids' => new external_multiple_structure(
 507                      new external_value(PARAM_INT, 'course id'), 'Array of course ids', VALUE_DEFAULT, array()
 508                  ),
 509              )
 510          );
 511      }
 512  
 513      /**
 514       * Returns a list of chats in a provided list of courses,
 515       * if no list is provided all chats that the user can view will be returned.
 516       *
 517       * @param array $courseids the course ids
 518       * @return array of chats details
 519       * @since Moodle 3.0
 520       */
 521      public static function get_chats_by_courses($courseids = array()) {
 522          global $CFG;
 523  
 524          $returnedchats = array();
 525          $warnings = array();
 526  
 527          $params = self::validate_parameters(self::get_chats_by_courses_parameters(), array('courseids' => $courseids));
 528  
 529          $courses = array();
 530          if (empty($params['courseids'])) {
 531              $courses = enrol_get_my_courses();
 532              $params['courseids'] = array_keys($courses);
 533          }
 534  
 535          // Ensure there are courseids to loop through.
 536          if (!empty($params['courseids'])) {
 537  
 538              list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses);
 539  
 540              // Get the chats in this course, this function checks users visibility permissions.
 541              // We can avoid then additional validate_context calls.
 542              $chats = get_all_instances_in_courses("chat", $courses);
 543              foreach ($chats as $chat) {
 544                  $chatcontext = context_module::instance($chat->coursemodule);
 545  
 546                  $chatdetails = helper_for_get_mods_by_courses::standard_coursemodule_element_values($chat, 'mod_chat');
 547  
 548                  if (has_capability('mod/chat:chat', $chatcontext)) {
 549                      $chatdetails['chatmethod']    = $CFG->chat_method;
 550                      $chatdetails['keepdays']      = $chat->keepdays;
 551                      $chatdetails['studentlogs']   = $chat->studentlogs;
 552                      $chatdetails['chattime']      = $chat->chattime;
 553                      $chatdetails['schedule']      = $chat->schedule;
 554                  }
 555  
 556                  if (has_capability('moodle/course:manageactivities', $chatcontext)) {
 557                      $chatdetails['timemodified']  = $chat->timemodified;
 558                  }
 559                  $returnedchats[] = $chatdetails;
 560              }
 561          }
 562          $result = array();
 563          $result['chats'] = $returnedchats;
 564          $result['warnings'] = $warnings;
 565          return $result;
 566      }
 567  
 568      /**
 569       * Describes the get_chats_by_courses return value.
 570       *
 571       * @return external_single_structure
 572       * @since Moodle 3.0
 573       */
 574      public static function get_chats_by_courses_returns() {
 575          return new external_single_structure(
 576              array(
 577                  'chats' => new external_multiple_structure(
 578                      new external_single_structure(array_merge(
 579                          helper_for_get_mods_by_courses::standard_coursemodule_elements_returns(),
 580                          [
 581                              'chatmethod' => new external_value(PARAM_PLUGIN, 'chat method (sockets, ajax, header_js)',
 582                                  VALUE_OPTIONAL),
 583                              'keepdays' => new external_value(PARAM_INT, 'keep days', VALUE_OPTIONAL),
 584                              'studentlogs' => new external_value(PARAM_INT, 'student logs visible to everyone', VALUE_OPTIONAL),
 585                              'chattime' => new external_value(PARAM_INT, 'chat time', VALUE_OPTIONAL),
 586                              'schedule' => new external_value(PARAM_INT, 'schedule type', VALUE_OPTIONAL),
 587                              'timemodified' => new external_value(PARAM_INT, 'time of last modification', VALUE_OPTIONAL),
 588                          ]
 589                      ), 'Chats')
 590                  ),
 591                  'warnings' => new external_warnings(),
 592              )
 593          );
 594      }
 595  
 596      /**
 597       * Returns description of method parameters
 598       *
 599       * @return external_function_parameters
 600       * @since Moodle 3.4
 601       */
 602      public static function get_sessions_parameters() {
 603          return new external_function_parameters(
 604              array(
 605                  'chatid' => new external_value(PARAM_INT, 'Chat instance id.'),
 606                  'groupid' => new external_value(PARAM_INT, 'Get messages from users in this group.
 607                                                  0 means that the function will determine the user group', VALUE_DEFAULT, 0),
 608                  'showall' => new external_value(PARAM_BOOL, 'Whether to show completed sessions or not.', VALUE_DEFAULT, false),
 609              )
 610          );
 611      }
 612  
 613      /**
 614       * Retrieves chat sessions for a given chat.
 615       *
 616       * @param int $chatid the chat instance id
 617       * @param int $groupid filter messages by this group. 0 to determine the group.
 618       * @param bool $showall whether to include incomplete sessions or not
 619       * @return array of warnings and the sessions
 620       * @since Moodle 3.4
 621       * @throws moodle_exception
 622       */
 623      public static function get_sessions($chatid, $groupid = 0, $showall = false) {
 624          global $DB;
 625  
 626          $params = self::validate_parameters(self::get_sessions_parameters(),
 627                                              array(
 628                                                  'chatid' => $chatid,
 629                                                  'groupid' => $groupid,
 630                                                  'showall' => $showall,
 631                                              ));
 632          $sessions = $warnings = array();
 633  
 634          // Request and permission validation.
 635          $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
 636          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 637  
 638          $context = context_module::instance($cm->id);
 639          self::validate_context($context);
 640  
 641          if (empty($chat->studentlogs) && !has_capability('mod/chat:readlog', $context)) {
 642              throw new moodle_exception('nopermissiontoseethechatlog', 'chat');
 643          }
 644  
 645          if (!empty($params['groupid'])) {
 646              $groupid = $params['groupid'];
 647              // Determine is the group is visible to user.
 648              if (!groups_group_visible($groupid, $course, $cm)) {
 649                  throw new moodle_exception('notingroup');
 650              }
 651          } else {
 652              // Check to see if groups are being used here.
 653              if ($groupmode = groups_get_activity_groupmode($cm)) {
 654                  $groupid = groups_get_activity_group($cm);
 655                  // Determine is the group is visible to user (this is particullary for the group 0).
 656                  if (!groups_group_visible($groupid, $course, $cm)) {
 657                      throw new moodle_exception('notingroup');
 658                  }
 659              } else {
 660                  $groupid = 0;
 661              }
 662          }
 663  
 664          $messages = chat_get_session_messages($chat->id, $groupid, 0, 0, 'timestamp DESC');
 665          if ($messages) {
 666              $chatsessions = chat_get_sessions($messages, $params['showall']);
 667              // Format sessions for external.
 668              foreach ($chatsessions as $session) {
 669                  $sessionusers = array();
 670                  foreach ($session->sessionusers as $sessionuser => $usermessagecount) {
 671                      $sessionusers[] = array(
 672                          'userid' => $sessionuser,
 673                          'messagecount' => $usermessagecount
 674                      );
 675                  }
 676                  $session->sessionusers = $sessionusers;
 677                  $sessions[] = $session;
 678              }
 679          }
 680  
 681          $result = array();
 682          $result['sessions'] = $sessions;
 683          $result['warnings'] = $warnings;
 684          return $result;
 685      }
 686  
 687      /**
 688       * Returns description of method result value
 689       *
 690       * @return external_description
 691       * @since Moodle 3.4
 692       */
 693      public static function get_sessions_returns() {
 694          return new external_single_structure(
 695              array(
 696                  'sessions' => new external_multiple_structure(
 697                      new external_single_structure(
 698                          array(
 699                              'sessionstart' => new external_value(PARAM_INT, 'Session start time.'),
 700                              'sessionend' => new external_value(PARAM_INT, 'Session end time.'),
 701                              'sessionusers' => new external_multiple_structure(
 702                                  new external_single_structure(
 703                                      array(
 704                                          'userid' => new external_value(PARAM_INT, 'User id.'),
 705                                          'messagecount' => new external_value(PARAM_INT, 'Number of messages in the session.'),
 706                                      )
 707                                  ), 'Session users.'
 708                              ),
 709                              'iscomplete' => new external_value(PARAM_BOOL, 'Whether the session is completed or not.'),
 710                          )
 711                      ),
 712                      'list of users'
 713                  ),
 714                  'warnings' => new external_warnings()
 715              )
 716          );
 717      }
 718  
 719      /**
 720       * Returns description of method parameters
 721       *
 722       * @return external_function_parameters
 723       * @since Moodle 3.4
 724       */
 725      public static function get_session_messages_parameters() {
 726          return new external_function_parameters(
 727              array(
 728                  'chatid' => new external_value(PARAM_INT, 'Chat instance id.'),
 729                  'sessionstart' => new external_value(PARAM_INT, 'The session start time (timestamp).'),
 730                  'sessionend' => new external_value(PARAM_INT, 'The session end time (timestamp).'),
 731                  'groupid' => new external_value(PARAM_INT, 'Get messages from users in this group.
 732                                                  0 means that the function will determine the user group', VALUE_DEFAULT, 0),
 733              )
 734          );
 735      }
 736  
 737      /**
 738       * Retrieves messages of the given chat session.
 739       *
 740       * @param int $chatid the chat instance id
 741       * @param int $sessionstart the session start time (timestamp)
 742       * @param int $sessionend the session end time (timestamp)
 743       * @param int $groupid filter messages by this group. 0 to determine the group.
 744       * @return array of warnings and the messages
 745       * @since Moodle 3.4
 746       * @throws moodle_exception
 747       */
 748      public static function get_session_messages($chatid, $sessionstart, $sessionend, $groupid = 0) {
 749          global $DB, $PAGE;
 750  
 751          $params = self::validate_parameters(self::get_session_messages_parameters(),
 752                                              array(
 753                                                  'chatid' => $chatid,
 754                                                  'sessionstart' => $sessionstart,
 755                                                  'sessionend' => $sessionend,
 756                                                  'groupid' => $groupid,
 757                                              ));
 758          $messages = $warnings = array();
 759  
 760          // Request and permission validation.
 761          $chat = $DB->get_record('chat', array('id' => $params['chatid']), '*', MUST_EXIST);
 762          list($course, $cm) = get_course_and_cm_from_instance($chat, 'chat');
 763  
 764          $context = context_module::instance($cm->id);
 765          self::validate_context($context);
 766  
 767          if (empty($chat->studentlogs) && !has_capability('mod/chat:readlog', $context)) {
 768              throw new moodle_exception('nopermissiontoseethechatlog', 'chat');
 769          }
 770  
 771          if (!empty($params['groupid'])) {
 772              $groupid = $params['groupid'];
 773              // Determine is the group is visible to user.
 774              if (!groups_group_visible($groupid, $course, $cm)) {
 775                  throw new moodle_exception('notingroup');
 776              }
 777          } else {
 778              // Check to see if groups are being used here.
 779              if ($groupmode = groups_get_activity_groupmode($cm)) {
 780                  $groupid = groups_get_activity_group($cm);
 781                  // Determine is the group is visible to user (this is particullary for the group 0).
 782                  if (!groups_group_visible($groupid, $course, $cm)) {
 783                      throw new moodle_exception('notingroup');
 784                  }
 785              } else {
 786                  $groupid = 0;
 787              }
 788          }
 789  
 790          $messages = chat_get_session_messages($chat->id, $groupid, $params['sessionstart'], $params['sessionend'],
 791              'timestamp ASC');
 792          if ($messages) {
 793              foreach ($messages as $message) {
 794                  $exporter = new chat_message_exporter($message, array('context' => $context));
 795                  $returneditems[] = $exporter->export($PAGE->get_renderer('core'));
 796              }
 797          }
 798  
 799          $result = array(
 800              'messages' => $messages,
 801              'warnings' => $warnings,
 802          );
 803          return $result;
 804      }
 805  
 806      /**
 807       * Returns description of method result value
 808       *
 809       * @return external_description
 810       * @since Moodle 3.4
 811       */
 812      public static function get_session_messages_returns() {
 813          return new external_single_structure(
 814              array(
 815                  'messages' => new external_multiple_structure(
 816                      chat_message_exporter::get_read_structure()
 817                  ),
 818                  'warnings' => new external_warnings()
 819              )
 820          );
 821      }
 822  }