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.
/mod/chat/ -> lib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 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   * Library of functions and constants for module chat
  19   *
  20   * @package   mod_chat
  21   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  require_once($CFG->dirroot.'/calendar/lib.php');
  28  
  29  // Event types.
  30  define('CHAT_EVENT_TYPE_CHATTIME', 'chattime');
  31  
  32  // Gap between sessions. 5 minutes or more of idleness between messages in a chat means the messages belong in different sessions.
  33  define('CHAT_SESSION_GAP', 300);
  34  // Don't publish next chat time
  35  define('CHAT_SCHEDULE_NONE', 0);
  36  // Publish the specified time only.
  37  define('CHAT_SCHEDULE_SINGLE', 1);
  38  // Repeat chat session at the same time daily.
  39  define('CHAT_SCHEDULE_DAILY', 2);
  40  // Repeat chat session at the same time weekly.
  41  define('CHAT_SCHEDULE_WEEKLY', 3);
  42  
  43  // The HTML head for the message window to start with (<!-- nix --> is used to get some browsers starting with output.
  44  global $CHAT_HTMLHEAD;
  45  $CHAT_HTMLHEAD = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head></head>\n<body>\n\n".padding(200);
  46  
  47  // The HTML head for the message window to start with (with js scrolling).
  48  global $CHAT_HTMLHEAD_JS;
  49  $CHAT_HTMLHEAD_JS = <<<EOD
  50  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
  51  <html><head><script type="text/javascript">
  52  //<![CDATA[
  53  function move() {
  54      if (scroll_active)
  55          window.scroll(1,400000);
  56      window.setTimeout("move()",100);
  57  }
  58  var scroll_active = true;
  59  move();
  60  //]]>
  61  </script>
  62  </head>
  63  <body onBlur="scroll_active = true" onFocus="scroll_active = false">
  64  EOD;
  65  global $CHAT_HTMLHEAD_JS;
  66  $CHAT_HTMLHEAD_JS .= padding(200);
  67  
  68  // The HTML code for standard empty pages (e.g. if a user was kicked out).
  69  global $CHAT_HTMLHEAD_OUT;
  70  $CHAT_HTMLHEAD_OUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>You are out!</title></head><body></body></html>";
  71  
  72  // The HTML head for the message input page.
  73  global $CHAT_HTMLHEAD_MSGINPUT;
  74  $CHAT_HTMLHEAD_MSGINPUT = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\"><html><head><title>Message Input</title></head><body>";
  75  
  76  // The HTML code for the message input page, with JavaScript.
  77  global $CHAT_HTMLHEAD_MSGINPUT_JS;
  78  $CHAT_HTMLHEAD_MSGINPUT_JS = <<<EOD
  79  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
  80  <html>
  81      <head><title>Message Input</title>
  82      <script type="text/javascript">
  83      //<![CDATA[
  84      scroll_active = true;
  85      function empty_field_and_submit() {
  86          document.fdummy.arsc_message.value=document.f.arsc_message.value;
  87          document.fdummy.submit();
  88          document.f.arsc_message.focus();
  89          document.f.arsc_message.select();
  90          return false;
  91      }
  92      //]]>
  93      </script>
  94      </head><body OnLoad="document.f.arsc_message.focus();document.f.arsc_message.select();">;
  95  EOD;
  96  
  97  // Dummy data that gets output to the browser as needed, in order to make it show output.
  98  global $CHAT_DUMMY_DATA;
  99  $CHAT_DUMMY_DATA = padding(200);
 100  
 101  /**
 102   * @param int $n
 103   * @return string
 104   */
 105  function padding($n) {
 106      $str = '';
 107      for ($i = 0; $i < $n; $i++) {
 108          $str .= "<!-- nix -->\n";
 109      }
 110      return $str;
 111  }
 112  
 113  /**
 114   * Given an object containing all the necessary data,
 115   * (defined by the form in mod_form.php) this function
 116   * will create a new instance and return the id number
 117   * of the new instance.
 118   *
 119   * @global object
 120   * @param object $chat
 121   * @return int
 122   */
 123  function chat_add_instance($chat) {
 124      global $DB, $CFG;
 125      require_once($CFG->dirroot . '/course/lib.php');
 126  
 127      $chat->timemodified = time();
 128      $chat->chattime = chat_calculate_next_chat_time($chat->schedule, $chat->chattime);
 129  
 130      $returnid = $DB->insert_record("chat", $chat);
 131  
 132      if ($chat->schedule > 0) {
 133          $event = new stdClass();
 134          $event->type        = CALENDAR_EVENT_TYPE_ACTION;
 135          $event->name        = $chat->name;
 136          $event->description = format_module_intro('chat', $chat, $chat->coursemodule, false);
 137          $event->format      = FORMAT_HTML;
 138          $event->courseid    = $chat->course;
 139          $event->groupid     = 0;
 140          $event->userid      = 0;
 141          $event->modulename  = 'chat';
 142          $event->instance    = $returnid;
 143          $event->eventtype   = CHAT_EVENT_TYPE_CHATTIME;
 144          $event->timestart   = $chat->chattime;
 145          $event->timesort    = $chat->chattime;
 146          $event->timeduration = 0;
 147  
 148          calendar_event::create($event, false);
 149      }
 150  
 151      if (!empty($chat->completionexpected)) {
 152          \core_completion\api::update_completion_date_event($chat->coursemodule, 'chat', $returnid, $chat->completionexpected);
 153      }
 154  
 155      return $returnid;
 156  }
 157  
 158  /**
 159   * Given an object containing all the necessary data,
 160   * (defined by the form in mod_form.php) this function
 161   * will update an existing instance with new data.
 162   *
 163   * @global object
 164   * @param object $chat
 165   * @return bool
 166   */
 167  function chat_update_instance($chat) {
 168      global $DB;
 169  
 170      $chat->timemodified = time();
 171      $chat->id = $chat->instance;
 172      $chat->chattime = chat_calculate_next_chat_time($chat->schedule, $chat->chattime);
 173  
 174      $DB->update_record("chat", $chat);
 175  
 176      $event = new stdClass();
 177  
 178      if ($event->id = $DB->get_field('event', 'id', array('modulename' => 'chat',
 179          'instance' => $chat->id, 'eventtype' => CHAT_EVENT_TYPE_CHATTIME))) {
 180  
 181          if ($chat->schedule > 0) {
 182              $event->type        = CALENDAR_EVENT_TYPE_ACTION;
 183              $event->name        = $chat->name;
 184              $event->description = format_module_intro('chat', $chat, $chat->coursemodule, false);
 185              $event->format      = FORMAT_HTML;
 186              $event->timestart   = $chat->chattime;
 187              $event->timesort    = $chat->chattime;
 188  
 189              $calendarevent = calendar_event::load($event->id);
 190              $calendarevent->update($event, false);
 191          } else {
 192              // Do not publish this event, so delete it.
 193              $calendarevent = calendar_event::load($event->id);
 194              $calendarevent->delete();
 195          }
 196      } else {
 197          // No event, do we need to create one?
 198          if ($chat->schedule > 0) {
 199              $event = new stdClass();
 200              $event->type        = CALENDAR_EVENT_TYPE_ACTION;
 201              $event->name        = $chat->name;
 202              $event->description = format_module_intro('chat', $chat, $chat->coursemodule, false);
 203              $event->format      = FORMAT_HTML;
 204              $event->courseid    = $chat->course;
 205              $event->groupid     = 0;
 206              $event->userid      = 0;
 207              $event->modulename  = 'chat';
 208              $event->instance    = $chat->id;
 209              $event->eventtype   = CHAT_EVENT_TYPE_CHATTIME;
 210              $event->timestart   = $chat->chattime;
 211              $event->timesort    = $chat->chattime;
 212              $event->timeduration = 0;
 213  
 214              calendar_event::create($event, false);
 215          }
 216      }
 217  
 218      $completionexpected = (!empty($chat->completionexpected)) ? $chat->completionexpected : null;
 219      \core_completion\api::update_completion_date_event($chat->coursemodule, 'chat', $chat->id, $completionexpected);
 220  
 221      return true;
 222  }
 223  
 224  /**
 225   * Given an ID of an instance of this module,
 226   * this function will permanently delete the instance
 227   * and any data that depends on it.
 228   *
 229   * @global object
 230   * @param int $id
 231   * @return bool
 232   */
 233  function chat_delete_instance($id) {
 234      global $DB;
 235  
 236      if (! $chat = $DB->get_record('chat', array('id' => $id))) {
 237          return false;
 238      }
 239  
 240      $result = true;
 241  
 242      // Delete any dependent records here.
 243  
 244      if (! $DB->delete_records('chat', array('id' => $chat->id))) {
 245          $result = false;
 246      }
 247      if (! $DB->delete_records('chat_messages', array('chatid' => $chat->id))) {
 248          $result = false;
 249      }
 250      if (! $DB->delete_records('chat_messages_current', array('chatid' => $chat->id))) {
 251          $result = false;
 252      }
 253      if (! $DB->delete_records('chat_users', array('chatid' => $chat->id))) {
 254          $result = false;
 255      }
 256  
 257      if (! $DB->delete_records('event', array('modulename' => 'chat', 'instance' => $chat->id))) {
 258          $result = false;
 259      }
 260  
 261      return $result;
 262  }
 263  
 264  /**
 265   * Given a course and a date, prints a summary of all chat rooms past and present
 266   * This function is called from block_recent_activity
 267   *
 268   * @global object
 269   * @global object
 270   * @global object
 271   * @param object $course
 272   * @param bool $viewfullnames
 273   * @param int|string $timestart Timestamp
 274   * @return bool
 275   */
 276  function chat_print_recent_activity($course, $viewfullnames, $timestart) {
 277      global $CFG, $USER, $DB, $OUTPUT;
 278  
 279      // This is approximate only, but it is really fast.
 280      $timeout = $CFG->chat_old_ping * 10;
 281  
 282      if (!$mcms = $DB->get_records_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
 283                                           FROM {course_modules} cm
 284                                           JOIN {modules} md        ON md.id = cm.module
 285                                           JOIN {chat} ch           ON ch.id = cm.instance
 286                                           JOIN {chat_messages} chm ON chm.chatid = ch.id
 287                                          WHERE chm.timestamp > ? AND ch.course = ? AND md.name = 'chat'
 288                                       GROUP BY cm.id
 289                                       ORDER BY lasttime ASC", array($timestart, $course->id))) {
 290           return false;
 291      }
 292  
 293      $past     = array();
 294      $current  = array();
 295      $modinfo = get_fast_modinfo($course); // Reference needed because we might load the groups.
 296  
 297      foreach ($mcms as $cmid => $mcm) {
 298          if (!array_key_exists($cmid, $modinfo->cms)) {
 299              continue;
 300          }
 301          $cm = $modinfo->cms[$cmid];
 302          if (!$modinfo->cms[$cm->id]->uservisible) {
 303              continue;
 304          }
 305  
 306          if (groups_get_activity_groupmode($cm) != SEPARATEGROUPS
 307           or has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
 308              if ($timeout > time() - $mcm->lasttime) {
 309                  $current[] = $cm;
 310              } else {
 311                  $past[] = $cm;
 312              }
 313  
 314              continue;
 315          }
 316  
 317          // Verify groups in separate mode.
 318          if (!$mygroupids = $modinfo->get_groups($cm->groupingid)) {
 319              continue;
 320          }
 321  
 322          // Ok, last post was not for my group - we have to query db to get last message from one of my groups.
 323          // The only minor problem is that the order will not be correct.
 324          $mygroupids = implode(',', $mygroupids);
 325  
 326          if (!$mcm = $DB->get_record_sql("SELECT cm.id, MAX(chm.timestamp) AS lasttime
 327                                             FROM {course_modules} cm
 328                                             JOIN {chat} ch           ON ch.id = cm.instance
 329                                             JOIN {chat_messages_current} chm ON chm.chatid = ch.id
 330                                            WHERE chm.timestamp > ? AND cm.id = ? AND
 331                                                  (chm.groupid IN ($mygroupids) OR chm.groupid = 0)
 332                                         GROUP BY cm.id", array($timestart, $cm->id))) {
 333               continue;
 334          }
 335  
 336          $mcms[$cmid]->lasttime = $mcm->lasttime;
 337          if ($timeout > time() - $mcm->lasttime) {
 338              $current[] = $cm;
 339          } else {
 340              $past[] = $cm;
 341          }
 342      }
 343  
 344      if (!$past and !$current) {
 345          return false;
 346      }
 347  
 348      $strftimerecent = get_string('strftimerecent');
 349  
 350      if ($past) {
 351          echo $OUTPUT->heading(get_string("pastchats", 'chat') . ':', 6);
 352  
 353          foreach ($past as $cm) {
 354              $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
 355              $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
 356              echo '<div class="head"><div class="date">'.$date.'</div></div>';
 357              echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name, true).'</a></div>';
 358          }
 359      }
 360  
 361      if ($current) {
 362          echo $OUTPUT->heading(get_string("currentchats", 'chat') . ':', 6);
 363  
 364          $oldest = floor((time() - $CFG->chat_old_ping) / 10) * 10;  // Better db caching.
 365  
 366          $timeold    = time() - $CFG->chat_old_ping;
 367          $timeold    = floor($timeold / 10) * 10;  // Better db caching.
 368          $timeoldext = time() - ($CFG->chat_old_ping * 10); // JSless gui_basic needs much longer timeouts.
 369          $timeoldext = floor($timeoldext / 10) * 10;  // Better db caching.
 370  
 371          $params = array('timeold' => $timeold, 'timeoldext' => $timeoldext, 'cmid' => $cm->id);
 372  
 373          $timeout = "AND ((chu.version<>'basic' AND chu.lastping>:timeold) OR (chu.version='basic' AND chu.lastping>:timeoldext))";
 374  
 375          foreach ($current as $cm) {
 376              // Count users first.
 377              $mygroupids = $modinfo->groups[$cm->groupingid];
 378              if (!empty($mygroupids)) {
 379                  list($subquery, $subparams) = $DB->get_in_or_equal($mygroupids, SQL_PARAMS_NAMED, 'gid');
 380                  $params += $subparams;
 381                  $groupselect = "AND (chu.groupid $subquery OR chu.groupid = 0)";
 382              } else {
 383                  $groupselect = "";
 384              }
 385  
 386              $userfieldsapi = \core_user\fields::for_userpic();
 387              $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 388              if (!$users = $DB->get_records_sql("SELECT $userfields
 389                                                    FROM {course_modules} cm
 390                                                    JOIN {chat} ch        ON ch.id = cm.instance
 391                                                    JOIN {chat_users} chu ON chu.chatid = ch.id
 392                                                    JOIN {user} u         ON u.id = chu.userid
 393                                                   WHERE cm.id = :cmid $timeout $groupselect
 394                                                GROUP BY $userfields", $params)) {
 395              }
 396  
 397              $link = $CFG->wwwroot.'/mod/chat/view.php?id='.$cm->id;
 398              $date = userdate($mcms[$cm->id]->lasttime, $strftimerecent);
 399  
 400              echo '<div class="head"><div class="date">'.$date.'</div></div>';
 401              echo '<div class="info"><a href="'.$link.'">'.format_string($cm->name, true).'</a></div>';
 402              echo '<div class="userlist">';
 403              if ($users) {
 404                  echo '<ul>';
 405                  foreach ($users as $user) {
 406                      echo '<li>'.fullname($user, $viewfullnames).'</li>';
 407                  }
 408                  echo '</ul>';
 409              }
 410              echo '</div>';
 411          }
 412      }
 413  
 414      return true;
 415  }
 416  
 417  /**
 418   * This standard function will check all instances of this module
 419   * and make sure there are up-to-date events created for each of them.
 420   * If courseid = 0, then every chat event in the site is checked, else
 421   * only chat events belonging to the course specified are checked.
 422   * This function is used, in its new format, by restore_refresh_events()
 423   *
 424   * @global object
 425   * @param int $courseid
 426   * @param int|stdClass $instance Chat module instance or ID.
 427   * @param int|stdClass $cm Course module object or ID.
 428   * @return bool
 429   */
 430  function chat_refresh_events($courseid = 0, $instance = null, $cm = null) {
 431      global $DB;
 432  
 433      // If we have instance information then we can just update the one event instead of updating all events.
 434      if (isset($instance)) {
 435          if (!is_object($instance)) {
 436              $instance = $DB->get_record('chat', array('id' => $instance), '*', MUST_EXIST);
 437          }
 438          if (isset($cm)) {
 439              if (!is_object($cm)) {
 440                  chat_prepare_update_events($instance);
 441                  return true;
 442              } else {
 443                  chat_prepare_update_events($instance, $cm);
 444                  return true;
 445              }
 446          }
 447      }
 448  
 449      if ($courseid) {
 450          if (! $chats = $DB->get_records("chat", array("course" => $courseid))) {
 451              return true;
 452          }
 453      } else {
 454          if (! $chats = $DB->get_records("chat")) {
 455              return true;
 456          }
 457      }
 458      foreach ($chats as $chat) {
 459          chat_prepare_update_events($chat);
 460      }
 461      return true;
 462  }
 463  
 464  /**
 465   * Updates both the normal and completion calendar events for chat.
 466   *
 467   * @param  stdClass $chat The chat object (from the DB)
 468   * @param  stdClass $cm The course module object.
 469   */
 470  function chat_prepare_update_events($chat, $cm = null) {
 471      global $DB;
 472      if (!isset($cm)) {
 473          $cm = get_coursemodule_from_instance('chat', $chat->id, $chat->course);
 474      }
 475      $event = new stdClass();
 476      $event->name        = $chat->name;
 477      $event->type        = CALENDAR_EVENT_TYPE_ACTION;
 478      $event->description = format_module_intro('chat', $chat, $cm->id, false);
 479      $event->format      = FORMAT_HTML;
 480      $event->timestart   = $chat->chattime;
 481      $event->timesort    = $chat->chattime;
 482      if ($event->id = $DB->get_field('event', 'id', array('modulename' => 'chat', 'instance' => $chat->id,
 483              'eventtype' => CHAT_EVENT_TYPE_CHATTIME))) {
 484          $calendarevent = calendar_event::load($event->id);
 485          $calendarevent->update($event, false);
 486      } else if ($chat->schedule > 0) {
 487          // The chat is scheduled and the event should be published.
 488          $event->courseid    = $chat->course;
 489          $event->groupid     = 0;
 490          $event->userid      = 0;
 491          $event->modulename  = 'chat';
 492          $event->instance    = $chat->id;
 493          $event->eventtype   = CHAT_EVENT_TYPE_CHATTIME;
 494          $event->timeduration = 0;
 495          $event->visible = $cm->visible;
 496          calendar_event::create($event, false);
 497      }
 498  }
 499  
 500  // Functions that require some SQL.
 501  
 502  /**
 503   * @global object
 504   * @param int $chatid
 505   * @param int $groupid
 506   * @param int $groupingid
 507   * @return array
 508   */
 509  function chat_get_users($chatid, $groupid=0, $groupingid=0) {
 510      global $DB;
 511  
 512      $params = array('chatid' => $chatid, 'groupid' => $groupid, 'groupingid' => $groupingid);
 513  
 514      if ($groupid) {
 515          $groupselect = " AND (c.groupid=:groupid OR c.groupid='0')";
 516      } else {
 517          $groupselect = "";
 518      }
 519  
 520      if (!empty($groupingid)) {
 521          $groupingjoin = "JOIN {groups_members} gm ON u.id = gm.userid
 522                           JOIN {groupings_groups} gg ON gm.groupid = gg.groupid AND gg.groupingid = :groupingid ";
 523  
 524      } else {
 525          $groupingjoin = '';
 526      }
 527  
 528      $userfieldsapi = \core_user\fields::for_userpic();
 529      $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 530      return $DB->get_records_sql("SELECT DISTINCT $ufields, c.lastmessageping, c.firstping
 531                                     FROM {chat_users} c
 532                                     JOIN {user} u ON u.id = c.userid $groupingjoin
 533                                    WHERE c.chatid = :chatid $groupselect
 534                                 ORDER BY c.firstping ASC", $params);
 535  }
 536  
 537  /**
 538   * @global object
 539   * @param int $chatid
 540   * @param int $groupid
 541   * @return array
 542   */
 543  function chat_get_latest_message($chatid, $groupid=0) {
 544      global $DB;
 545  
 546      $params = array('chatid' => $chatid, 'groupid' => $groupid);
 547  
 548      if ($groupid) {
 549          $groupselect = "AND (groupid=:groupid OR groupid=0)";
 550      } else {
 551          $groupselect = "";
 552      }
 553  
 554      $sql = "SELECT *
 555          FROM {chat_messages_current} WHERE chatid = :chatid $groupselect
 556          ORDER BY timestamp DESC, id DESC";
 557  
 558      // Return the lastest one message.
 559      return $DB->get_record_sql($sql, $params, true);
 560  }
 561  
 562  /**
 563   * login if not already logged in
 564   *
 565   * @global object
 566   * @global object
 567   * @param int $chatid
 568   * @param string $version
 569   * @param int $groupid
 570   * @param object $course
 571   * @return bool|int Returns the chat users sid or false
 572   */
 573  function chat_login_user($chatid, $version, $groupid, $course) {
 574      global $USER, $DB;
 575  
 576      if (($version != 'sockets') and $chatuser = $DB->get_record('chat_users', array('chatid' => $chatid,
 577                                                                                      'userid' => $USER->id,
 578                                                                                      'groupid' => $groupid))) {
 579          // This will update logged user information.
 580          $chatuser->version  = $version;
 581          $chatuser->ip       = $USER->lastip;
 582          $chatuser->lastping = time();
 583          $chatuser->lang     = current_language();
 584  
 585          // Sometimes $USER->lastip is not setup properly during login.
 586          // Update with current value if possible or provide a dummy value for the db.
 587          if (empty($chatuser->ip)) {
 588              $chatuser->ip = getremoteaddr();
 589          }
 590  
 591          if (($chatuser->course != $course->id) or ($chatuser->userid != $USER->id)) {
 592              return false;
 593          }
 594          $DB->update_record('chat_users', $chatuser);
 595  
 596      } else {
 597          $chatuser = new stdClass();
 598          $chatuser->chatid   = $chatid;
 599          $chatuser->userid   = $USER->id;
 600          $chatuser->groupid  = $groupid;
 601          $chatuser->version  = $version;
 602          $chatuser->ip       = $USER->lastip;
 603          $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time();
 604          $chatuser->sid      = random_string(32);
 605          $chatuser->course   = $course->id; // Caching - needed for current_language too.
 606          $chatuser->lang     = current_language(); // Caching - to resource intensive to find out later.
 607  
 608          // Sometimes $USER->lastip is not setup properly during login.
 609          // Update with current value if possible or provide a dummy value for the db.
 610          if (empty($chatuser->ip)) {
 611              $chatuser->ip = getremoteaddr();
 612          }
 613  
 614          $DB->insert_record('chat_users', $chatuser);
 615  
 616          if ($version == 'sockets') {
 617              // Do not send 'enter' message, chatd will do it.
 618          } else {
 619              chat_send_chatmessage($chatuser, 'enter', true);
 620          }
 621      }
 622  
 623      return $chatuser->sid;
 624  }
 625  
 626  /**
 627   * Delete the old and in the way
 628   *
 629   * @global object
 630   * @global object
 631   */
 632  function chat_delete_old_users() {
 633      // Delete the old and in the way.
 634      global $CFG, $DB;
 635  
 636      $timeold = time() - $CFG->chat_old_ping;
 637      $timeoldext = time() - ($CFG->chat_old_ping * 10); // JSless gui_basic needs much longer timeouts.
 638  
 639      $query = "(version<>'basic' AND lastping<?) OR (version='basic' AND lastping<?)";
 640      $params = array($timeold, $timeoldext);
 641  
 642      if ($oldusers = $DB->get_records_select('chat_users', $query, $params) ) {
 643          $DB->delete_records_select('chat_users', $query, $params);
 644          foreach ($oldusers as $olduser) {
 645              chat_send_chatmessage($olduser, 'exit', true);
 646          }
 647      }
 648  }
 649  
 650  /**
 651   * Calculate next chat session time based on schedule.
 652   *
 653   * @param int $schedule
 654   * @param int $chattime
 655   *
 656   * @return int timestamp
 657   */
 658  function chat_calculate_next_chat_time(int $schedule, int $chattime): int {
 659      $timenow = time();
 660  
 661      switch ($schedule) {
 662          case CHAT_SCHEDULE_DAILY: { // Repeat daily.
 663              while ($chattime <= $timenow) {
 664                  $chattime += DAYSECS;
 665              }
 666              break;
 667          }
 668          case CHAT_SCHEDULE_WEEKLY: { // Repeat weekly.
 669              while ($chattime <= $timenow) {
 670                  $chattime += WEEKSECS;
 671              }
 672              break;
 673          }
 674      }
 675  
 676      return $chattime;
 677  }
 678  
 679  /**
 680   * Updates chat records so that the next chat time is correct
 681   *
 682   * @global object
 683   * @param int $chatid
 684   * @return void
 685   */
 686  function chat_update_chat_times($chatid=0) {
 687      // Updates chat records so that the next chat time is correct.
 688      global $DB;
 689  
 690      $timenow = time();
 691  
 692      $params = array('timenow' => $timenow, 'chatid' => $chatid);
 693  
 694      if ($chatid) {
 695          if (!$chats[] = $DB->get_record_select("chat", "id = :chatid AND chattime <= :timenow AND schedule > 0", $params)) {
 696              return;
 697          }
 698      } else {
 699          if (!$chats = $DB->get_records_select("chat", "chattime <= :timenow AND schedule > 0", $params)) {
 700              return;
 701          }
 702      }
 703  
 704      $courseids = [];
 705      foreach ($chats as $chat) {
 706          $originalchattime = $chat->chattime;
 707          $chat->chattime = chat_calculate_next_chat_time($chat->schedule, $chat->chattime);
 708          if ($originalchattime != $chat->chattime) {
 709              $courseids[] = $chat->course;
 710              $DB->update_record("chat", $chat);
 711  
 712              $cm = get_coursemodule_from_instance('chat', $chat->id, $chat->course);
 713              \course_modinfo::purge_course_module_cache($cm->course, $cm->id);
 714          }
 715  
 716          $event = new stdClass(); // Update calendar too.
 717          $cond = "modulename='chat' AND eventtype = :eventtype AND instance = :chatid AND timestart <> :chattime";
 718          $params = ['chattime' => $chat->chattime, 'eventtype' => CHAT_EVENT_TYPE_CHATTIME, 'chatid' => $chat->id];
 719  
 720          if ($event->id = $DB->get_field_select('event', 'id', $cond, $params)) {
 721              $event->timestart = $chat->chattime;
 722              $event->timesort = $chat->chattime;
 723              $calendarevent = calendar_event::load($event->id);
 724              $calendarevent->update($event, false);
 725          }
 726      }
 727  
 728      $courseids = array_unique($courseids);
 729      foreach ($courseids as $courseid) {
 730          rebuild_course_cache($courseid, true, true);
 731      }
 732  }
 733  
 734  /**
 735   * Send a message on the chat.
 736   *
 737   * @param object $chatuser The chat user record.
 738   * @param string $messagetext The message to be sent.
 739   * @param bool $issystem False for non-system messages, true for system messages.
 740   * @param object $cm The course module object, pass it to save a database query when we trigger the event.
 741   * @return int The message ID.
 742   * @since Moodle 2.6
 743   */
 744  function chat_send_chatmessage($chatuser, $messagetext, $issystem = false, $cm = null) {
 745      global $DB;
 746  
 747      $message = new stdClass();
 748      $message->chatid    = $chatuser->chatid;
 749      $message->userid    = $chatuser->userid;
 750      $message->groupid   = $chatuser->groupid;
 751      $message->message   = $messagetext;
 752      $message->issystem  = $issystem ? 1 : 0;
 753      $message->timestamp = time();
 754  
 755      $messageid = $DB->insert_record('chat_messages', $message);
 756      $DB->insert_record('chat_messages_current', $message);
 757      $message->id = $messageid;
 758  
 759      if (!$issystem) {
 760  
 761          if (empty($cm)) {
 762              $cm = get_coursemodule_from_instance('chat', $chatuser->chatid, $chatuser->course);
 763          }
 764  
 765          $params = array(
 766              'context' => context_module::instance($cm->id),
 767              'objectid' => $message->id,
 768              // We set relateduserid, because when triggered from the chat daemon, the event userid is null.
 769              'relateduserid' => $chatuser->userid
 770          );
 771          $event = \mod_chat\event\message_sent::create($params);
 772          $event->add_record_snapshot('chat_messages', $message);
 773          $event->trigger();
 774      }
 775  
 776      return $message->id;
 777  }
 778  
 779  /**
 780   * @global object
 781   * @global object
 782   * @param object $message
 783   * @param int $courseid
 784   * @param object $sender
 785   * @param object $currentuser
 786   * @param string $chatlastrow
 787   * @return bool|string Returns HTML or false
 788   */
 789  function chat_format_message_manually($message, $courseid, $sender, $currentuser, $chatlastrow = null) {
 790      global $CFG, $USER, $OUTPUT;
 791  
 792      $output = new stdClass();
 793      $output->beep = false;       // By default.
 794      $output->refreshusers = false; // By default.
 795  
 796      // Find the correct timezone for displaying this message.
 797      $tz = core_date::get_user_timezone($currentuser);
 798  
 799      $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
 800  
 801      $message->picture = $OUTPUT->user_picture($sender, array('size' => false, 'courseid' => $courseid, 'link' => false));
 802  
 803      if ($courseid) {
 804          $message->picture = "<a onclick=\"window.open('$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid')\"".
 805                              " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
 806      }
 807  
 808      // Calculate the row class.
 809      if ($chatlastrow !== null) {
 810          $rowclass = ' class="r'.$chatlastrow.'" ';
 811      } else {
 812          $rowclass = '';
 813      }
 814  
 815      // Start processing the message.
 816  
 817      if (!empty($message->issystem)) {
 818          // System event.
 819          $output->text = $message->strtime.': '.get_string('message'.$message->message, 'chat', fullname($sender));
 820          $output->html  = '<table class="chat-event"><tr'.$rowclass.'><td class="picture">'.$message->picture.'</td>';
 821          $output->html .= '<td class="text"><span class="event">'.$output->text.'</span></td></tr></table>';
 822          $output->basic = '<tr class="r1">
 823                              <th scope="row" class="cell c1 title"></th>
 824                              <td class="cell c2 text">' . get_string('message'.$message->message, 'chat', fullname($sender)) . '</td>
 825                              <td class="cell c3">' . $message->strtime . '</td>
 826                            </tr>';
 827          if ($message->message == 'exit' or $message->message == 'enter') {
 828              $output->refreshusers = true; // Force user panel refresh ASAP.
 829          }
 830          return $output;
 831      }
 832  
 833      // It's not a system event.
 834      $rawtext = trim($message->message);
 835  
 836      // Options for format_text, when we get to it...
 837      // format_text call will parse the text to clean and filter it.
 838      // It cannot be called here as HTML-isation interferes with special case
 839      // recognition, but *must* be called on any user-sourced text to be inserted
 840      // into $outmain.
 841      $options = new stdClass();
 842      $options->para = false;
 843      $options->blanktarget = true;
 844  
 845      // And now check for special cases.
 846      $patternto = '#^\s*To\s([^:]+):(.*)#';
 847      $special = false;
 848  
 849      if (substr($rawtext, 0, 5) == 'beep ') {
 850          // It's a beep!
 851          $special = true;
 852          $beepwho = trim(substr($rawtext, 5));
 853  
 854          if ($beepwho == 'all') {   // Everyone.
 855              $outinfobasic = get_string('messagebeepseveryone', 'chat', fullname($sender));
 856              $outinfo = $message->strtime . ': ' . $outinfobasic;
 857              $outmain = '';
 858  
 859              $output->beep = true;  // Eventually this should be set to a filename uploaded by the user.
 860  
 861          } else if ($beepwho == $currentuser->id) {  // Current user.
 862              $outinfobasic = get_string('messagebeepsyou', 'chat', fullname($sender));
 863              $outinfo = $message->strtime . ': ' . $outinfobasic;
 864              $outmain = '';
 865              $output->beep = true;
 866  
 867          } else {  // Something is not caught?
 868              return false;
 869          }
 870      } else if (substr($rawtext, 0, 1) == '/') {     // It's a user command.
 871          $special = true;
 872          $pattern = '#(^\/)(\w+).*#';
 873          preg_match($pattern, $rawtext, $matches);
 874          $command = isset($matches[2]) ? $matches[2] : false;
 875          // Support some IRC commands.
 876          switch ($command) {
 877              case 'me':
 878                  $outinfo = $message->strtime;
 879                  $text = '*** <b>'.$sender->firstname.' '.substr($rawtext, 4).'</b>';
 880                  $outmain = format_text($text, FORMAT_MOODLE, $options, $courseid);
 881                  break;
 882              default:
 883                  // Error, we set special back to false to use the classic message output.
 884                  $special = false;
 885                  break;
 886          }
 887      } else if (preg_match($patternto, $rawtext)) {
 888          $special = true;
 889          $matches = array();
 890          preg_match($patternto, $rawtext, $matches);
 891          if (isset($matches[1]) && isset($matches[2])) {
 892              $text = format_text($matches[2], FORMAT_MOODLE, $options, $courseid);
 893              $outinfo = $message->strtime;
 894              $outmain = $sender->firstname.' '.get_string('saidto', 'chat').' <i>'.$matches[1].'</i>: '.$text;
 895          } else {
 896              // Error, we set special back to false to use the classic message output.
 897              $special = false;
 898          }
 899      }
 900  
 901      if (!$special) {
 902          $text = format_text($rawtext, FORMAT_MOODLE, $options, $courseid);
 903          $outinfo = $message->strtime.' '.$sender->firstname;
 904          $outmain = $text;
 905      }
 906  
 907      // Format the message as a small table.
 908  
 909      $output->text  = strip_tags($outinfo.': '.$outmain);
 910  
 911      $output->html  = "<table class=\"chat-message\"><tr$rowclass><td class=\"picture\" valign=\"top\">$message->picture</td>";
 912      $output->html .= "<td class=\"text\"><span class=\"title\">$outinfo</span>";
 913      if ($outmain) {
 914          $output->html .= ": $outmain";
 915          $output->basic = '<tr class="r0">
 916                              <th scope="row" class="cell c1 title">' . $sender->firstname . '</th>
 917                              <td class="cell c2 text">' . $outmain . '</td>
 918                              <td class="cell c3">' . $message->strtime . '</td>
 919                            </tr>';
 920      } else {
 921          $output->basic = '<tr class="r1">
 922                              <th scope="row" class="cell c1 title"></th>
 923                              <td class="cell c2 text">' . $outinfobasic . '</td>
 924                              <td class="cell c3">' . $message->strtime . '</td>
 925                            </tr>';
 926      }
 927      $output->html .= "</td></tr></table>";
 928      return $output;
 929  }
 930  
 931  /**
 932   * Given a message object this function formats it appropriately into text and html then returns the formatted data
 933   * @global object
 934   * @param object $message
 935   * @param int $courseid
 936   * @param object $currentuser
 937   * @param string $chatlastrow
 938   * @return bool|string Returns HTML or false
 939   */
 940  function chat_format_message($message, $courseid, $currentuser, $chatlastrow=null) {
 941      global $DB;
 942  
 943      static $users;     // Cache user lookups.
 944  
 945      if (isset($users[$message->userid])) {
 946          $user = $users[$message->userid];
 947      } else if ($user = $DB->get_record('user', ['id' => $message->userid], implode(',', \core_user\fields::get_picture_fields()))) {
 948          $users[$message->userid] = $user;
 949      } else {
 950          return null;
 951      }
 952      return chat_format_message_manually($message, $courseid, $user, $currentuser, $chatlastrow);
 953  }
 954  
 955  /**
 956   * @global object
 957   * @param object $message message to be displayed.
 958   * @param mixed $chatuser user chat data
 959   * @param object $currentuser current user for whom the message should be displayed.
 960   * @param int $groupingid course module grouping id
 961   * @param string $theme name of the chat theme.
 962   * @return bool|string Returns HTML or false
 963   */
 964  function chat_format_message_theme ($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble') {
 965      global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
 966      require_once($CFG->dirroot.'/mod/chat/locallib.php');
 967  
 968      static $users;     // Cache user lookups.
 969  
 970      $result = new stdClass();
 971  
 972      if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php')) {
 973          include($CFG->dirroot . '/mod/chat/gui_ajax/theme/'.$theme.'/config.php');
 974      }
 975  
 976      if (isset($users[$message->userid])) {
 977          $sender = $users[$message->userid];
 978      } else if ($sender = $DB->get_record('user', array('id' => $message->userid),
 979              implode(',', \core_user\fields::get_picture_fields()))) {
 980          $users[$message->userid] = $sender;
 981      } else {
 982          return null;
 983      }
 984  
 985      // Find the correct timezone for displaying this message.
 986      $tz = core_date::get_user_timezone($currentuser);
 987  
 988      if (empty($chatuser->course)) {
 989          $courseid = $COURSE->id;
 990      } else {
 991          $courseid = $chatuser->course;
 992      }
 993  
 994      $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
 995      $message->picture = $OUTPUT->user_picture($sender, array('courseid' => $courseid));
 996  
 997      $message->picture = "<a target='_blank'".
 998                          " href=\"$CFG->wwwroot/user/view.php?id=$sender->id&amp;course=$courseid\">$message->picture</a>";
 999  
1000      // Start processing the message.
1001      if (!empty($message->issystem)) {
1002          $result->type = 'system';
1003  
1004          $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
1005          $event = get_string('message'.$message->message, 'chat', fullname($sender));
1006          $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
1007  
1008          $output = $PAGE->get_renderer('mod_chat');
1009          $result->html = $output->render($eventmessage);
1010  
1011          return $result;
1012      }
1013  
1014      // It's not a system event.
1015      $rawtext = trim($message->message);
1016  
1017      // Options for format_text, when we get to it...
1018      // format_text call will parse the text to clean and filter it.
1019      // It cannot be called here as HTML-isation interferes with special case
1020      // recognition, but *must* be called on any user-sourced text to be inserted
1021      // into $outmain.
1022      $options = new stdClass();
1023      $options->para = false;
1024      $options->blanktarget = true;
1025  
1026      // And now check for special cases.
1027      $special = false;
1028      $outtime = $message->strtime;
1029  
1030      // Initialise variables.
1031      $outmain = '';
1032      $patternto = '#^\s*To\s([^:]+):(.*)#';
1033  
1034      if (substr($rawtext, 0, 5) == 'beep ') {
1035          $special = true;
1036          // It's a beep!
1037          $result->type = 'beep';
1038          $beepwho = trim(substr($rawtext, 5));
1039  
1040          if ($beepwho == 'all') {   // Everyone.
1041              $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
1042          } else if ($beepwho == $currentuser->id) {  // Current user.
1043              $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
1044          } else if ($sender->id == $currentuser->id) {  // Something is not caught?
1045              // Allow beep for a active chat user only, else user can beep anyone and get fullname.
1046              if (!empty($chatuser) && is_numeric($beepwho)) {
1047                  $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
1048                  if (array_key_exists($beepwho, $chatusers)) {
1049                      $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
1050                  } else {
1051                      $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1052                  }
1053              } else {
1054                  $outmain = get_string('messageyoubeep', 'chat', $beepwho);
1055              }
1056          }
1057      } else if (substr($rawtext, 0, 1) == '/') {     // It's a user command.
1058          $special = true;
1059          $result->type = 'command';
1060          $pattern = '#(^\/)(\w+).*#';
1061          preg_match($pattern, $rawtext, $matches);
1062          $command = isset($matches[2]) ? $matches[2] : false;
1063          // Support some IRC commands.
1064          switch ($command) {
1065              case 'me':
1066                  $text = '*** <b>'.$sender->firstname.' '.substr($rawtext, 4).'</b>';
1067                  $outmain = format_text($text, FORMAT_MOODLE, $options, $courseid);
1068                  break;
1069              default:
1070                  // Error, we set special back to false to use the classic message output.
1071                  $special = false;
1072                  break;
1073          }
1074      } else if (preg_match($patternto, $rawtext)) {
1075          $special = true;
1076          $result->type = 'dialogue';
1077          $matches = array();
1078          preg_match($patternto, $rawtext, $matches);
1079          if (isset($matches[1]) && isset($matches[2])) {
1080              $text = format_text($matches[2], FORMAT_MOODLE, $options, $courseid);
1081              $outmain = $sender->firstname.' <b>'.get_string('saidto', 'chat').'</b> <i>'.$matches[1].'</i>: '.$text;
1082          } else {
1083              // Error, we set special back to false to use the classic message output.
1084              $special = false;
1085          }
1086      }
1087  
1088      if (!$special) {
1089          $text = format_text($rawtext, FORMAT_MOODLE, $options, $courseid);
1090          $outmain = $text;
1091      }
1092  
1093      $result->text = strip_tags($outtime.': '.$outmain);
1094  
1095      $mymessageclass = '';
1096      if ($sender->id == $USER->id) {
1097          $mymessageclass = 'chat-message-mymessage';
1098      }
1099  
1100      $senderprofile = $CFG->wwwroot.'/user/view.php?id='.$sender->id.'&amp;course='.$courseid;
1101      $usermessage = new user_message($senderprofile, fullname($sender), $message->picture,
1102                                      $mymessageclass, $outtime, $outmain, $theme);
1103  
1104      $output = $PAGE->get_renderer('mod_chat');
1105      $result->html = $output->render($usermessage);
1106  
1107      // When user beeps other user, then don't show any timestamp to other users in chat.
1108      if (('' === $outmain) && $special) {
1109          return false;
1110      } else {
1111          return $result;
1112      }
1113  }
1114  
1115  /**
1116   * @global object $DB
1117   * @global object $CFG
1118   * @global object $COURSE
1119   * @global object $OUTPUT
1120   * @param object $users
1121   * @param object $course
1122   * @return array return formatted user list
1123   */
1124  function chat_format_userlist($users, $course) {
1125      global $CFG, $DB, $COURSE, $OUTPUT;
1126      $result = array();
1127      foreach ($users as $user) {
1128          $item = array();
1129          $item['name'] = fullname($user);
1130          $item['url'] = $CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id;
1131          $item['picture'] = $OUTPUT->user_picture($user);
1132          $item['id'] = $user->id;
1133          $result[] = $item;
1134      }
1135      return $result;
1136  }
1137  
1138  /**
1139   * Print json format error
1140   * @param string $level
1141   * @param string $msg
1142   */
1143  function chat_print_error($level, $msg) {
1144      header('Content-Length: ' . ob_get_length() );
1145      $error = new stdClass();
1146      $error->level = $level;
1147      $error->msg   = $msg;
1148      $response['error'] = $error;
1149      echo json_encode($response);
1150      ob_end_flush();
1151      exit;
1152  }
1153  
1154  /**
1155   * List the actions that correspond to a view of this module.
1156   * This is used by the participation report.
1157   *
1158   * Note: This is not used by new logging system. Event with
1159   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1160   *       be considered as view action.
1161   *
1162   * @return array
1163   */
1164  function chat_get_view_actions() {
1165      return array('view', 'view all', 'report');
1166  }
1167  
1168  /**
1169   * List the actions that correspond to a post of this module.
1170   * This is used by the participation report.
1171   *
1172   * Note: This is not used by new logging system. Event with
1173   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1174   *       will be considered as post action.
1175   *
1176   * @return array
1177   */
1178  function chat_get_post_actions() {
1179      return array('talk');
1180  }
1181  
1182  /**
1183   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
1184   */
1185  function chat_print_overview() {
1186      throw new coding_exception('chat_print_overview() can not be used any more and is obsolete.');
1187  }
1188  
1189  
1190  /**
1191   * Implementation of the function for printing the form elements that control
1192   * whether the course reset functionality affects the chat.
1193   *
1194   * @param object $mform form passed by reference
1195   */
1196  function chat_reset_course_form_definition(&$mform) {
1197      $mform->addElement('header', 'chatheader', get_string('modulenameplural', 'chat'));
1198      $mform->addElement('advcheckbox', 'reset_chat', get_string('removemessages', 'chat'));
1199  }
1200  
1201  /**
1202   * Course reset form defaults.
1203   *
1204   * @param object $course
1205   * @return array
1206   */
1207  function chat_reset_course_form_defaults($course) {
1208      return array('reset_chat' => 1);
1209  }
1210  
1211  /**
1212   * Actual implementation of the reset course functionality, delete all the
1213   * chat messages for course $data->courseid.
1214   *
1215   * @global object
1216   * @global object
1217   * @param object $data the data submitted from the reset course.
1218   * @return array status array
1219   */
1220  function chat_reset_userdata($data) {
1221      global $CFG, $DB;
1222  
1223      $componentstr = get_string('modulenameplural', 'chat');
1224      $status = array();
1225  
1226      if (!empty($data->reset_chat)) {
1227          $chatessql = "SELECT ch.id
1228                          FROM {chat} ch
1229                         WHERE ch.course=?";
1230          $params = array($data->courseid);
1231  
1232          $DB->delete_records_select('chat_messages', "chatid IN ($chatessql)", $params);
1233          $DB->delete_records_select('chat_messages_current', "chatid IN ($chatessql)", $params);
1234          $DB->delete_records_select('chat_users', "chatid IN ($chatessql)", $params);
1235          $status[] = array('component' => $componentstr, 'item' => get_string('removemessages', 'chat'), 'error' => false);
1236      }
1237  
1238      // Updating dates - shift may be negative too.
1239      if ($data->timeshift) {
1240          // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1241          // See MDL-9367.
1242          shift_course_mod_dates('chat', array('chattime'), $data->timeshift, $data->courseid);
1243          $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
1244      }
1245  
1246      return $status;
1247  }
1248  
1249  /**
1250   * @param string $feature FEATURE_xx constant for requested feature
1251   * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
1252   */
1253  function chat_supports($feature) {
1254      switch($feature) {
1255          case FEATURE_GROUPS:
1256              return true;
1257          case FEATURE_GROUPINGS:
1258              return true;
1259          case FEATURE_MOD_INTRO:
1260              return true;
1261          case FEATURE_BACKUP_MOODLE2:
1262              return true;
1263          case FEATURE_COMPLETION_TRACKS_VIEWS:
1264              return true;
1265          case FEATURE_GRADE_HAS_GRADE:
1266              return false;
1267          case FEATURE_GRADE_OUTCOMES:
1268              return true;
1269          case FEATURE_SHOW_DESCRIPTION:
1270              return true;
1271          case FEATURE_MOD_PURPOSE:
1272              return MOD_PURPOSE_COMMUNICATION;
1273          default:
1274              return null;
1275      }
1276  }
1277  
1278  function chat_extend_navigation($navigation, $course, $module, $cm) {
1279      global $CFG;
1280  
1281      $currentgroup = groups_get_activity_group($cm, true);
1282  
1283      if (has_capability('mod/chat:chat', context_module::instance($cm->id))) {
1284          $strenterchat    = get_string('enterchat', 'chat');
1285  
1286          $target = $CFG->wwwroot.'/mod/chat/';
1287          $params = array('id' => $cm->instance);
1288  
1289          if ($currentgroup) {
1290              $params['groupid'] = $currentgroup;
1291          }
1292  
1293          $links = array();
1294  
1295          $url = new moodle_url($target.'gui_'.$CFG->chat_method.'/index.php', $params);
1296          $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup,
1297                                     array('height' => 500, 'width' => 700));
1298          $links[] = new action_link($url, $strenterchat, $action);
1299  
1300          $url = new moodle_url($target.'gui_basic/index.php', $params);
1301          $action = new popup_action('click', $url, 'chat'.$course->id.$cm->instance.$currentgroup,
1302                                     array('height' => 500, 'width' => 700));
1303          $links[] = new action_link($url, get_string('noframesjs', 'message'), $action);
1304  
1305          foreach ($links as $link) {
1306              $navigation->add($link->text, $link, navigation_node::TYPE_SETTING, null , null, new pix_icon('i/group' , ''));
1307          }
1308      }
1309  
1310      $chatusers = chat_get_users($cm->instance, $currentgroup, $cm->groupingid);
1311      if (is_array($chatusers) && count($chatusers) > 0) {
1312          $users = $navigation->add(get_string('currentusers', 'chat'));
1313          foreach ($chatusers as $chatuser) {
1314              $userlink = new moodle_url('/user/view.php', array('id' => $chatuser->id, 'course' => $course->id));
1315              $users->add(fullname($chatuser).' '.format_time(time() - $chatuser->lastmessageping),
1316                          $userlink, navigation_node::TYPE_USER, null, null, new pix_icon('i/user', ''));
1317          }
1318      }
1319  }
1320  
1321  /**
1322   * Adds module specific settings to the settings block
1323   *
1324   * @param settings_navigation $settings The settings navigation object
1325   * @param navigation_node $chatnode The node to add module settings to
1326   */
1327  function chat_extend_settings_navigation(settings_navigation $settings, navigation_node $chatnode) {
1328      global $DB;
1329      $chat = $DB->get_record("chat", array("id" => $settings->get_page()->cm->instance));
1330  
1331      $currentgroup = groups_get_activity_group($settings->get_page()->cm, true);
1332      if ($currentgroup) {
1333          $groupselect = " AND groupid = '$currentgroup'";
1334      } else {
1335          $groupselect = '';
1336      }
1337  
1338      if ($chat->studentlogs || has_capability('mod/chat:readlog', $settings->get_page()->cm->context)) {
1339          if ($DB->get_records_select('chat_messages', "chatid = ? $groupselect", array($chat->id))) {
1340              $chatnode->add(get_string('pastsessions', 'chat'),
1341                  new moodle_url('/mod/chat/report.php', array('id' => $settings->get_page()->cm->id)),
1342                  navigation_node::TYPE_SETTING, null, 'pastsessions');
1343          }
1344      }
1345  }
1346  
1347  /**
1348   * user logout event handler
1349   *
1350   * @param \core\event\user_loggedout $event The event.
1351   * @return void
1352   */
1353  function chat_user_logout(\core\event\user_loggedout $event) {
1354      global $DB;
1355      $DB->delete_records('chat_users', array('userid' => $event->objectid));
1356  }
1357  
1358  /**
1359   * Return a list of page types
1360   * @param string $pagetype current page type
1361   * @param stdClass $parentcontext Block's parent context
1362   * @param stdClass $currentcontext Current context of block
1363   */
1364  function chat_page_type_list($pagetype, $parentcontext, $currentcontext) {
1365      $modulepagetype = array('mod-chat-*' => get_string('page-mod-chat-x', 'chat'));
1366      return $modulepagetype;
1367  }
1368  
1369  /**
1370   * Return a list of the latest messages in the given chat session.
1371   *
1372   * @param  stdClass $chatuser     chat user session data
1373   * @param  int      $chatlasttime last time messages were retrieved
1374   * @return array    list of messages
1375   * @since  Moodle 3.0
1376   */
1377  function chat_get_latest_messages($chatuser, $chatlasttime) {
1378      global $DB;
1379  
1380      $params = array('groupid' => $chatuser->groupid, 'chatid' => $chatuser->chatid, 'lasttime' => $chatlasttime);
1381  
1382      $groupselect = $chatuser->groupid ? " AND (groupid=" . $chatuser->groupid . " OR groupid=0) " : "";
1383  
1384      return $DB->get_records_select('chat_messages_current', 'chatid = :chatid AND timestamp > :lasttime ' . $groupselect,
1385                                      $params, 'timestamp ASC');
1386  }
1387  
1388  /**
1389   * Mark the activity completed (if required) and trigger the course_module_viewed event.
1390   *
1391   * @param  stdClass $chat       chat object
1392   * @param  stdClass $course     course object
1393   * @param  stdClass $cm         course module object
1394   * @param  stdClass $context    context object
1395   * @since Moodle 3.0
1396   */
1397  function chat_view($chat, $course, $cm, $context) {
1398  
1399      // Trigger course_module_viewed event.
1400      $params = array(
1401          'context' => $context,
1402          'objectid' => $chat->id
1403      );
1404  
1405      $event = \mod_chat\event\course_module_viewed::create($params);
1406      $event->add_record_snapshot('course_modules', $cm);
1407      $event->add_record_snapshot('course', $course);
1408      $event->add_record_snapshot('chat', $chat);
1409      $event->trigger();
1410  
1411      // Completion.
1412      $completion = new completion_info($course);
1413      $completion->set_module_viewed($cm);
1414  }
1415  
1416  /**
1417   * This function receives a calendar event and returns the action associated with it, or null if there is none.
1418   *
1419   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1420   * is not displayed on the block.
1421   *
1422   * @param calendar_event $event
1423   * @param \core_calendar\action_factory $factory
1424   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1425   * @return \core_calendar\local\event\entities\action_interface|null
1426   */
1427  function mod_chat_core_calendar_provide_event_action(calendar_event $event,
1428                                                       \core_calendar\action_factory $factory,
1429                                                       int $userid = 0) {
1430      global $USER, $DB;
1431  
1432      if ($userid) {
1433          $user = core_user::get_user($userid, 'id, timezone');
1434      } else {
1435          $user = $USER;
1436      }
1437  
1438      $cm = get_fast_modinfo($event->courseid, $user->id)->instances['chat'][$event->instance];
1439  
1440      if (!$cm->uservisible) {
1441          // The module is not visible to the user for any reason.
1442          return null;
1443      }
1444  
1445      $completion = new \completion_info($cm->get_course());
1446  
1447      $completiondata = $completion->get_data($cm, false, $userid);
1448  
1449      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1450          return null;
1451      }
1452  
1453      $chattime = $DB->get_field('chat', 'chattime', array('id' => $event->instance));
1454      $usertimezone = core_date::get_user_timezone($user);
1455      $chattimemidnight = usergetmidnight($chattime, $usertimezone);
1456      $todaymidnight = usergetmidnight(time(), $usertimezone);
1457  
1458      if ($chattime < $todaymidnight) {
1459          // The chat is before today. Do not show at all.
1460          return null;
1461      } else {
1462          // The chat is actionable if it is at some point today.
1463          $actionable = $chattimemidnight == $todaymidnight;
1464  
1465          return $factory->create_instance(
1466              get_string('enterchat', 'chat'),
1467              new \moodle_url('/mod/chat/view.php', array('id' => $cm->id)),
1468              1,
1469              $actionable
1470          );
1471      }
1472  }
1473  
1474  /**
1475   * Given a set of messages for a chat, return the completed chat sessions (including optionally not completed ones).
1476   *
1477   * @param  array $messages list of messages from a chat. It is assumed that these are sorted by timestamp in DESCENDING order.
1478   * @param  bool $showall   whether to include incomplete sessions or not
1479   * @return array           the list of sessions
1480   * @since  Moodle 3.5
1481   */
1482  function chat_get_sessions($messages, $showall = false) {
1483      $sessions     = [];
1484      $start        = 0;
1485      $end          = 0;
1486      $sessiontimes = [];
1487  
1488      // Group messages by session times.
1489      foreach ($messages as $message) {
1490          // Initialise values start-end times if necessary.
1491          if (empty($start)) {
1492              $start = $message->timestamp;
1493          }
1494          if (empty($end)) {
1495              $end = $message->timestamp;
1496          }
1497  
1498          // If this message's timestamp has been more than the gap, it means it's been idle.
1499          if ($start - $message->timestamp > CHAT_SESSION_GAP) {
1500              // Mark this as the session end of the next session.
1501              $end = $message->timestamp;
1502          }
1503          // Use this time as the session's start (until it gets overwritten on the next iteration, if needed).
1504          $start = $message->timestamp;
1505  
1506          // Set this start-end pair in our list of session times.
1507          $sessiontimes[$end]['sessionstart'] = $start;
1508          if (!isset($sessiontimes[$end]['sessionend'])) {
1509              $sessiontimes[$end]['sessionend'] = $end;
1510          }
1511          if ($message->userid && !$message->issystem) {
1512              if (!isset($sessiontimes[$end]['sessionusers'][$message->userid])) {
1513                  $sessiontimes[$end]['sessionusers'][$message->userid] = 1;
1514              } else {
1515                  $sessiontimes[$end]['sessionusers'][$message->userid]++;
1516              }
1517          }
1518      }
1519  
1520      // Go through each session time and prepare the session data to be returned.
1521      foreach ($sessiontimes as $sessionend => $sessiondata) {
1522          if (!isset($sessiondata['sessionusers'])) {
1523              $sessiondata['sessionusers'] = [];
1524          }
1525          $sessionusers = $sessiondata['sessionusers'];
1526          $sessionstart = $sessiondata['sessionstart'];
1527  
1528          $iscomplete = $sessionend - $sessionstart > 60 && count($sessionusers) > 1;
1529          if ($showall || $iscomplete) {
1530              $sessions[] = (object) ($sessiondata + ['iscomplete' => $iscomplete]);
1531          }
1532      }
1533  
1534      return $sessions;
1535  }
1536  
1537  /**
1538   * Return the messages of the given chat session.
1539   *
1540   * @param  int $chatid      the chat id
1541   * @param  mixed $group     false if groups not used, int if groups used, 0 means all groups
1542   * @param  int $start       the session start timestamp (0 to not filter by time)
1543   * @param  int $end         the session end timestamp (0 to not filter by time)
1544   * @param  string $sort     an order to sort the results in (optional, a valid SQL ORDER BY parameter)
1545   * @return array session messages
1546   * @since  Moodle 3.5
1547   */
1548  function chat_get_session_messages($chatid, $group = false, $start = 0, $end = 0, $sort = '') {
1549      global $DB;
1550  
1551      $params = array('chatid' => $chatid);
1552  
1553      // If the user is allocated to a group, only show messages from people in the same group, or no group.
1554      if ($group) {
1555          $groupselect = " AND (groupid = :currentgroup OR groupid = 0)";
1556          $params['currentgroup'] = $group;
1557      } else {
1558          $groupselect = "";
1559      }
1560  
1561      $select = "chatid = :chatid $groupselect";
1562      if (!empty($start)) {
1563          $select .= ' AND timestamp >= :start';
1564          $params['start'] = $start;
1565      }
1566      if (!empty($end)) {
1567          $select .= ' AND timestamp <= :end';
1568          $params['end'] = $end;
1569      }
1570  
1571      return $DB->get_records_select('chat_messages', $select, $params, $sort);
1572  }
1573  
1574  /**
1575   * Add a get_coursemodule_info function in case chat instance wants to add 'extra' information
1576   * for the course (see resource).
1577   *
1578   * Given a course_module object, this function returns any "extra" information that may be needed
1579   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
1580   *
1581   * @param stdClass $coursemodule The coursemodule object (record).
1582   * @return cached_cm_info An object on information that the courses
1583   *                        will know about (most noticeably, an icon).
1584   */
1585  function chat_get_coursemodule_info($coursemodule) {
1586      global $DB;
1587  
1588      $dbparams = ['id' => $coursemodule->instance];
1589      $fields = 'id, name, intro, introformat, chattime, schedule';
1590      if (!$chat = $DB->get_record('chat', $dbparams, $fields)) {
1591          return false;
1592      }
1593  
1594      $result = new cached_cm_info();
1595      $result->name = $chat->name;
1596      if ($coursemodule->showdescription) {
1597          // Convert intro to html. Do not filter cached version, filters run at display time.
1598          $result->content = format_module_intro('chat', $chat, $coursemodule->id, false);
1599      }
1600  
1601      // Populate some other values that can be used in calendar or on dashboard.
1602      if ($chat->chattime) {
1603          $result->customdata['chattime'] = $chat->chattime;
1604          $result->customdata['schedule'] = $chat->schedule;
1605      }
1606  
1607      return $result;
1608  }