Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/mod/chat/ -> lib.php (source)

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