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.

Differences Between: [Versions 39 and 310] [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   * Contains helper class for the message area.
  19   *
  20   * @package    core_message
  21   * @copyright  2016 Mark Nelson <markn@moodle.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace core_message;
  26  use DOMDocument;
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  require_once($CFG->dirroot . '/message/lib.php');
  31  
  32  /**
  33   * Helper class for the message area.
  34   *
  35   * @copyright  2016 Mark Nelson <markn@moodle.com>
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class helper {
  39  
  40      /**
  41       * Helper function to retrieve the messages between two users
  42       *
  43       * TODO: This function should be removed once the related web services go through final deprecation.
  44       * The related web services are data_for_messagearea_messages AND data_for_messagearea_get_most_recent_message.
  45       * Followup: MDL-63261
  46       *
  47       * @param int $userid the current user
  48       * @param int $otheruserid the other user
  49       * @param int $timedeleted the time the message was deleted
  50       * @param int $limitfrom
  51       * @param int $limitnum
  52       * @param string $sort
  53       * @param int $timefrom the time from the message being sent
  54       * @param int $timeto the time up until the message being sent
  55       * @return array of messages
  56       */
  57      public static function get_messages($userid, $otheruserid, $timedeleted = 0, $limitfrom = 0, $limitnum = 0,
  58                                          $sort = 'timecreated ASC', $timefrom = 0, $timeto = 0) {
  59          global $DB;
  60  
  61          $hash = self::get_conversation_hash([$userid, $otheruserid]);
  62  
  63          $sql = "SELECT m.id, m.useridfrom, m.subject, m.fullmessage, m.fullmessagehtml,
  64                         m.fullmessageformat, m.fullmessagetrust, m.smallmessage, m.timecreated,
  65                         mc.contextid, muaread.timecreated AS timeread
  66                    FROM {message_conversations} mc
  67              INNER JOIN {messages} m
  68                      ON m.conversationid = mc.id
  69               LEFT JOIN {message_user_actions} muaread
  70                      ON (muaread.messageid = m.id
  71                     AND muaread.userid = :userid1
  72                     AND muaread.action = :readaction)";
  73          $params = ['userid1' => $userid, 'readaction' => api::MESSAGE_ACTION_READ, 'convhash' => $hash];
  74  
  75          if (empty($timedeleted)) {
  76              $sql .= " LEFT JOIN {message_user_actions} mua
  77                               ON (mua.messageid = m.id
  78                              AND mua.userid = :userid2
  79                              AND mua.action = :deleteaction
  80                              AND mua.timecreated is NOT NULL)";
  81          } else {
  82              $sql .= " INNER JOIN {message_user_actions} mua
  83                                ON (mua.messageid = m.id
  84                               AND mua.userid = :userid2
  85                               AND mua.action = :deleteaction
  86                               AND mua.timecreated = :timedeleted)";
  87              $params['timedeleted'] = $timedeleted;
  88          }
  89  
  90          $params['userid2'] = $userid;
  91          $params['deleteaction'] = api::MESSAGE_ACTION_DELETED;
  92  
  93          $sql .= " WHERE mc.convhash = :convhash";
  94  
  95          if (!empty($timefrom)) {
  96              $sql .= " AND m.timecreated >= :timefrom";
  97              $params['timefrom'] = $timefrom;
  98          }
  99  
 100          if (!empty($timeto)) {
 101              $sql .= " AND m.timecreated <= :timeto";
 102              $params['timeto'] = $timeto;
 103          }
 104  
 105          if (empty($timedeleted)) {
 106              $sql .= " AND mua.id is NULL";
 107          }
 108  
 109          $sql .= " ORDER BY m.$sort";
 110  
 111          $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
 112          foreach ($messages as &$message) {
 113              $message->useridto = ($message->useridfrom == $userid) ? $otheruserid : $userid;
 114          }
 115  
 116          return $messages;
 117      }
 118  
 119      /**
 120       * Helper function to retrieve conversation messages.
 121       *
 122       * @param  int $userid The current user.
 123       * @param  int $convid The conversation identifier.
 124       * @param  int $timedeleted The time the message was deleted
 125       * @param  int $limitfrom Return a subset of records, starting at this point (optional).
 126       * @param  int $limitnum Return a subset comprising this many records in total (optional, required if $limitfrom is set).
 127       * @param  string $sort The column name to order by including optionally direction.
 128       * @param  int $timefrom The time from the message being sent.
 129       * @param  int $timeto The time up until the message being sent.
 130       * @return array of messages
 131       */
 132      public static function get_conversation_messages(int $userid, int $convid, int $timedeleted = 0, int $limitfrom = 0,
 133                                                       int $limitnum = 0, string $sort = 'timecreated ASC', int $timefrom = 0,
 134                                                       int $timeto = 0) : array {
 135          global $DB;
 136  
 137          $sql = "SELECT m.id, m.useridfrom, m.subject, m.fullmessage, m.fullmessagehtml,
 138                         m.fullmessageformat, m.fullmessagetrust, m.smallmessage, m.timecreated,
 139                         mc.contextid, muaread.timecreated AS timeread
 140                    FROM {message_conversations} mc
 141              INNER JOIN {messages} m
 142                      ON m.conversationid = mc.id
 143               LEFT JOIN {message_user_actions} muaread
 144                      ON (muaread.messageid = m.id
 145                     AND muaread.userid = :userid1
 146                     AND muaread.action = :readaction)";
 147          $params = ['userid1' => $userid, 'readaction' => api::MESSAGE_ACTION_READ, 'convid' => $convid];
 148  
 149          if (empty($timedeleted)) {
 150              $sql .= " LEFT JOIN {message_user_actions} mua
 151                               ON (mua.messageid = m.id
 152                              AND mua.userid = :userid2
 153                              AND mua.action = :deleteaction
 154                              AND mua.timecreated is NOT NULL)";
 155          } else {
 156              $sql .= " INNER JOIN {message_user_actions} mua
 157                                ON (mua.messageid = m.id
 158                               AND mua.userid = :userid2
 159                               AND mua.action = :deleteaction
 160                               AND mua.timecreated = :timedeleted)";
 161              $params['timedeleted'] = $timedeleted;
 162          }
 163  
 164          $params['userid2'] = $userid;
 165          $params['deleteaction'] = api::MESSAGE_ACTION_DELETED;
 166  
 167          $sql .= " WHERE mc.id = :convid";
 168  
 169          if (!empty($timefrom)) {
 170              $sql .= " AND m.timecreated >= :timefrom";
 171              $params['timefrom'] = $timefrom;
 172          }
 173  
 174          if (!empty($timeto)) {
 175              $sql .= " AND m.timecreated <= :timeto";
 176              $params['timeto'] = $timeto;
 177          }
 178  
 179          if (empty($timedeleted)) {
 180              $sql .= " AND mua.id is NULL";
 181          }
 182  
 183          $sql .= " ORDER BY m.$sort";
 184  
 185          $messages = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
 186  
 187          return $messages;
 188      }
 189  
 190      /**
 191       * Helper function to return a conversation messages with the involved members (only the ones
 192       * who have sent any of these messages).
 193       *
 194       * @param int $userid The current userid.
 195       * @param int $convid The conversation id.
 196       * @param array $messages The formated array messages.
 197       * @return array A conversation array with the messages and the involved members.
 198       */
 199      public static function format_conversation_messages(int $userid, int $convid, array $messages) : array {
 200          global $USER;
 201  
 202          // Create the conversation array.
 203          $conversation = array(
 204              'id' => $convid,
 205          );
 206  
 207          // Store the messages.
 208          $arrmessages = array();
 209  
 210          foreach ($messages as $message) {
 211              // Store the message information.
 212              $msg = new \stdClass();
 213              $msg->id = $message->id;
 214              $msg->useridfrom = $message->useridfrom;
 215              $msg->text = message_format_message_text($message);
 216              $msg->timecreated = $message->timecreated;
 217              $arrmessages[] = $msg;
 218          }
 219          // Add the messages to the conversation.
 220          $conversation['messages'] = $arrmessages;
 221  
 222          // Get the users who have sent any of the $messages.
 223          $memberids = array_unique(array_map(function($message) {
 224              return $message->useridfrom;
 225          }, $messages));
 226  
 227          if (!empty($memberids)) {
 228              // Get members information.
 229              $conversation['members'] = self::get_member_info($userid, $memberids);
 230          } else {
 231              $conversation['members'] = array();
 232          }
 233  
 234          return $conversation;
 235      }
 236  
 237      /**
 238       * Helper function to return an array of messages.
 239       *
 240       * TODO: This function should be removed once the related web services go through final deprecation.
 241       * The related web services are data_for_messagearea_messages AND data_for_messagearea_get_most_recent_message.
 242       * Followup: MDL-63261
 243       *
 244       * @param int $userid
 245       * @param array $messages
 246       * @return array
 247       */
 248      public static function create_messages($userid, $messages) {
 249          // Store the messages.
 250          $arrmessages = array();
 251  
 252          // We always view messages from oldest to newest, ensure we have it in that order.
 253          $lastmessage = end($messages);
 254          $firstmessage = reset($messages);
 255          if ($lastmessage->timecreated < $firstmessage->timecreated) {
 256              $messages = array_reverse($messages);
 257          }
 258  
 259          // Keeps track of the last day, month and year combo we were viewing.
 260          $day = '';
 261          $month = '';
 262          $year = '';
 263          foreach ($messages as $message) {
 264              // Check if we are now viewing a different block period.
 265              $displayblocktime = false;
 266              $date = usergetdate($message->timecreated);
 267              if ($day != $date['mday'] || $month != $date['month'] || $year != $date['year']) {
 268                  $day = $date['mday'];
 269                  $month = $date['month'];
 270                  $year = $date['year'];
 271                  $displayblocktime = true;
 272              }
 273              // Store the message to pass to the renderable.
 274              $msg = new \stdClass();
 275              $msg->id = $message->id;
 276              $msg->text = message_format_message_text($message);
 277              $msg->currentuserid = $userid;
 278              $msg->useridfrom = $message->useridfrom;
 279              $msg->useridto = $message->useridto;
 280              $msg->displayblocktime = $displayblocktime;
 281              $msg->timecreated = $message->timecreated;
 282              $msg->timeread = $message->timeread;
 283              $arrmessages[] = $msg;
 284          }
 285  
 286          return $arrmessages;
 287      }
 288  
 289      /**
 290       * Helper function for creating a contact object.
 291       *
 292       * @param \stdClass $contact
 293       * @param string $prefix
 294       * @return \stdClass
 295       */
 296      public static function create_contact($contact, $prefix = '') {
 297          global $PAGE;
 298  
 299          // Create the data we are going to pass to the renderable.
 300          $userfields = \user_picture::unalias($contact, array('lastaccess'), $prefix . 'id', $prefix);
 301          $data = new \stdClass();
 302          $data->userid = $userfields->id;
 303          $data->useridfrom = null;
 304          $data->fullname = fullname($userfields);
 305          // Get the user picture data.
 306          $userpicture = new \user_picture($userfields);
 307          $userpicture->size = 1; // Size f1.
 308          $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
 309          $userpicture->size = 0; // Size f2.
 310          $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
 311          // Store the message if we have it.
 312          $data->ismessaging = false;
 313          $data->lastmessage = null;
 314          $data->lastmessagedate = null;
 315          $data->messageid = null;
 316          if (isset($contact->smallmessage)) {
 317              $data->ismessaging = true;
 318              // Strip the HTML tags from the message for displaying in the contact area.
 319              $data->lastmessage = clean_param($contact->smallmessage, PARAM_NOTAGS);
 320              $data->lastmessagedate = $contact->timecreated;
 321              $data->useridfrom = $contact->useridfrom;
 322              if (isset($contact->messageid)) {
 323                  $data->messageid = $contact->messageid;
 324              }
 325          }
 326          $data->isonline = null;
 327          $user = \core_user::get_user($data->userid);
 328          if (self::show_online_status($user)) {
 329              $data->isonline = self::is_online($userfields->lastaccess);
 330          }
 331          $data->isblocked = isset($contact->blocked) ? (bool) $contact->blocked : false;
 332          $data->isread = isset($contact->isread) ? (bool) $contact->isread : false;
 333          $data->unreadcount = isset($contact->unreadcount) ? $contact->unreadcount : null;
 334          $data->conversationid = $contact->conversationid ?? null;
 335  
 336          return $data;
 337      }
 338  
 339      /**
 340       * Helper function for checking if we should show the user's online status.
 341       *
 342       * @param \stdClass $user
 343       * @return boolean
 344       */
 345      public static function show_online_status($user) {
 346          global $CFG;
 347  
 348          require_once($CFG->dirroot . '/user/lib.php');
 349  
 350          if ($lastaccess = user_get_user_details($user, null, array('lastaccess'))) {
 351              if (isset($lastaccess['lastaccess'])) {
 352                  return true;
 353              }
 354          }
 355  
 356          return false;
 357      }
 358  
 359      /**
 360       * Helper function for checking the time meets the 'online' condition.
 361       *
 362       * @param int $lastaccess
 363       * @return boolean
 364       */
 365      public static function is_online($lastaccess) {
 366          global $CFG;
 367  
 368          // Variable to check if we consider this user online or not.
 369          $timetoshowusers = 300; // Seconds default.
 370          if (isset($CFG->block_online_users_timetosee)) {
 371              $timetoshowusers = $CFG->block_online_users_timetosee * 60;
 372          }
 373          $time = time() - $timetoshowusers;
 374  
 375          return $lastaccess >= $time;
 376      }
 377  
 378      /**
 379       * Get providers preferences.
 380       *
 381       * @param array $providers
 382       * @param int $userid
 383       * @return \stdClass
 384       */
 385      public static function get_providers_preferences($providers, $userid) {
 386          $preferences = new \stdClass();
 387  
 388          // Get providers preferences.
 389          foreach ($providers as $provider) {
 390              foreach (array('loggedin', 'loggedoff') as $state) {
 391                  $linepref = get_user_preferences('message_provider_' . $provider->component . '_' . $provider->name
 392                      . '_' . $state, '', $userid);
 393                  if ($linepref == '') {
 394                      continue;
 395                  }
 396                  $lineprefarray = explode(',', $linepref);
 397                  $preferences->{$provider->component.'_'.$provider->name.'_'.$state} = array();
 398                  foreach ($lineprefarray as $pref) {
 399                      $preferences->{$provider->component.'_'.$provider->name.'_'.$state}[$pref] = 1;
 400                  }
 401              }
 402          }
 403  
 404          return $preferences;
 405      }
 406  
 407      /**
 408       * Requires the JS libraries for the toggle contact button.
 409       *
 410       * @return void
 411       */
 412      public static function togglecontact_requirejs() {
 413          global $PAGE;
 414  
 415          static $done = false;
 416          if ($done) {
 417              return;
 418          }
 419  
 420          $PAGE->requires->js_call_amd('core_message/toggle_contact_button', 'enhance', array('#toggle-contact-button'));
 421          $done = true;
 422      }
 423  
 424      /**
 425       * Returns the attributes to place on a contact button.
 426       *
 427       * @param object $user User object.
 428       * @param bool $iscontact
 429       * @return array
 430       */
 431      public static function togglecontact_link_params($user, $iscontact = false) {
 432          $params = array(
 433              'data-userid' => $user->id,
 434              'data-is-contact' => $iscontact,
 435              'id' => 'toggle-contact-button',
 436              'role' => 'button',
 437              'class' => 'ajax-contact-button',
 438          );
 439  
 440          return $params;
 441      }
 442  
 443      /**
 444       * Requires the JS libraries for the message user button.
 445       *
 446       * @return void
 447       */
 448      public static function messageuser_requirejs() {
 449          global $PAGE;
 450  
 451          static $done = false;
 452          if ($done) {
 453              return;
 454          }
 455  
 456          $PAGE->requires->js_call_amd('core_message/message_user_button', 'send', array('#message-user-button'));
 457          $done = true;
 458      }
 459  
 460      /**
 461       * Returns the attributes to place on the message user button.
 462       *
 463       * @param int $useridto
 464       * @return array
 465       */
 466      public static function messageuser_link_params(int $useridto) : array {
 467          global $USER;
 468  
 469          return [
 470              'id' => 'message-user-button',
 471              'role' => 'button',
 472              'data-conversationid' => api::get_conversation_between_users([$USER->id, $useridto]),
 473              'data-userid' => $useridto,
 474          ];
 475      }
 476  
 477      /**
 478       * Returns the conversation hash between users for easy look-ups in the DB.
 479       *
 480       * @param array $userids
 481       * @return string
 482       */
 483      public static function get_conversation_hash(array $userids) {
 484          sort($userids);
 485  
 486          return sha1(implode('-', $userids));
 487      }
 488  
 489      /**
 490       * Returns the cache key for the time created value of the last message of this conversation.
 491       *
 492       * @param int $convid The conversation identifier.
 493       * @return string The key.
 494       */
 495      public static function get_last_message_time_created_cache_key(int $convid) {
 496          return $convid;
 497      }
 498  
 499      /**
 500       * Checks if legacy messages exist for a given user.
 501       *
 502       * @param int $userid
 503       * @return bool
 504       */
 505      public static function legacy_messages_exist($userid) {
 506          global $DB;
 507  
 508          $sql = "SELECT id
 509                    FROM {message} m
 510                   WHERE useridfrom = ?
 511                      OR useridto = ?";
 512          $messageexists = $DB->record_exists_sql($sql, [$userid, $userid]);
 513  
 514          $sql = "SELECT id
 515                    FROM {message_read} m
 516                   WHERE useridfrom = ?
 517                      OR useridto = ?";
 518          $messagereadexists = $DB->record_exists_sql($sql, [$userid, $userid]);
 519  
 520          return $messageexists || $messagereadexists;
 521      }
 522  
 523      /**
 524       * Returns conversation member info for the supplied users, relative to the supplied referenceuserid.
 525       *
 526       * This is the basic structure used when returning members, and includes information about the relationship between each member
 527       * and the referenceuser, such as a whether the referenceuser has marked the member as a contact, or has blocked them.
 528       *
 529       * @param int $referenceuserid the id of the user which check contact and blocked status.
 530       * @param array $userids
 531       * @param bool $includecontactrequests Do we want to include contact requests with this data?
 532       * @param bool $includeprivacyinfo Do we want to include whether the user can message another, and if the user
 533       *             requires a contact.
 534       * @return array the array of objects containing member info, indexed by userid.
 535       * @throws \coding_exception
 536       * @throws \dml_exception
 537       */
 538      public static function get_member_info(int $referenceuserid, array $userids, bool $includecontactrequests = false,
 539                                             bool $includeprivacyinfo = false) : array {
 540          global $DB, $PAGE;
 541  
 542          // Prevent exception being thrown when array is empty.
 543          if (empty($userids)) {
 544              return [];
 545          }
 546  
 547          list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
 548          $userfields = \user_picture::fields('u', array('lastaccess'));
 549          $userssql = "SELECT $userfields, u.deleted, mc.id AS contactid, mub.id AS blockedid
 550                         FROM {user} u
 551                    LEFT JOIN {message_contacts} mc
 552                           ON ((mc.userid = ? AND mc.contactid = u.id) OR (mc.userid = u.id AND mc.contactid = ?))
 553                    LEFT JOIN {message_users_blocked} mub
 554                           ON (mub.userid = ? AND mub.blockeduserid = u.id)
 555                        WHERE u.id $useridsql";
 556          $usersparams = array_merge([$referenceuserid, $referenceuserid, $referenceuserid], $usersparams);
 557          $otherusers = $DB->get_records_sql($userssql, $usersparams);
 558  
 559          $members = [];
 560          foreach ($otherusers as $member) {
 561              // Set basic data.
 562              $data = new \stdClass();
 563              $data->id = $member->id;
 564              $data->fullname = fullname($member);
 565  
 566              // Create the URL for their profile.
 567              $profileurl = new \moodle_url('/user/profile.php', ['id' => $member->id]);
 568              $data->profileurl = $profileurl->out(false);
 569  
 570              // Set the user picture data.
 571              $userpicture = new \user_picture($member);
 572              $userpicture->size = 1; // Size f1.
 573              $data->profileimageurl = $userpicture->get_url($PAGE)->out(false);
 574              $userpicture->size = 0; // Size f2.
 575              $data->profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
 576  
 577              // Set online status indicators.
 578              $data->isonline = false;
 579              $data->showonlinestatus = false;
 580              if (!$member->deleted) {
 581                  $data->isonline = self::show_online_status($member) ? self::is_online($member->lastaccess) : null;
 582                  $data->showonlinestatus = is_null($data->isonline) ? false : true;
 583              }
 584  
 585              // Set contact and blocked status indicators.
 586              $data->iscontact = ($member->contactid) ? true : false;
 587  
 588              // We don't want that a user has been blocked if they can message the user anyways.
 589              $canmessageifblocked = api::can_send_message($referenceuserid, $member->id, true);
 590              $data->isblocked = ($member->blockedid && !$canmessageifblocked) ? true : false;
 591  
 592              $data->isdeleted = ($member->deleted) ? true : false;
 593  
 594              $data->requirescontact = null;
 595              $data->canmessage = null;
 596              $data->canmessageevenifblocked = null;
 597              if ($includeprivacyinfo) {
 598                  $privacysetting = api::get_user_privacy_messaging_preference($member->id);
 599                  $data->requirescontact = $privacysetting == api::MESSAGE_PRIVACY_ONLYCONTACTS;
 600  
 601                  // Here we check that if the sender wanted to block the recipient, the
 602                  // recipient would still be able to message them regardless.
 603                  $data->canmessageevenifblocked = !$data->isdeleted && $canmessageifblocked;
 604                  $data->canmessage = !$data->isdeleted && api::can_send_message($member->id, $referenceuserid);
 605              }
 606  
 607              // Populate the contact requests, even if we don't need them.
 608              $data->contactrequests = [];
 609  
 610              $members[$data->id] = $data;
 611          }
 612  
 613          // Check if we want to include contact requests as well.
 614          if (!empty($members) && $includecontactrequests) {
 615              list($useridsql, $usersparams) = $DB->get_in_or_equal($userids);
 616  
 617              $wheresql = "(userid $useridsql AND requesteduserid = ?) OR (userid = ? AND requesteduserid $useridsql)";
 618              $params = array_merge($usersparams, [$referenceuserid, $referenceuserid], $usersparams);
 619              if ($contactrequests = $DB->get_records_select('message_contact_requests', $wheresql, $params,
 620                      'timecreated ASC, id ASC')) {
 621                  foreach ($contactrequests as $contactrequest) {
 622                      if (isset($members[$contactrequest->userid])) {
 623                          $members[$contactrequest->userid]->contactrequests[] = $contactrequest;
 624                      }
 625                      if (isset($members[$contactrequest->requesteduserid])) {
 626                          $members[$contactrequest->requesteduserid]->contactrequests[] = $contactrequest;
 627                      }
 628                  }
 629              }
 630          }
 631  
 632          // Remove any userids not in $members. This can happen in the case of a user who has been deleted
 633          // from the Moodle database table (which can happen in earlier versions of Moodle).
 634          $userids = array_filter($userids, function($userid) use ($members) {
 635              return isset($members[$userid]);
 636          });
 637  
 638          // Return member information in the same order as the userids originally provided.
 639          $members = array_replace(array_flip($userids), $members);
 640  
 641          return $members;
 642      }
 643  
 644      /**
 645       * Backwards compatibility formatter, transforming the new output of get_conversations() into the old format.
 646       *
 647       * TODO: This function should be removed once the related web services go through final deprecation.
 648       * The related web services are data_for_messagearea_conversations.
 649       * Followup: MDL-63261
 650       *
 651       * @param array $conversations the array of conversations, which must come from get_conversations().
 652       * @return array the array of conversations, formatted in the legacy style.
 653       */
 654      public static function get_conversations_legacy_formatter(array $conversations) : array {
 655          // Transform new data format back into the old format, just for BC during the deprecation life cycle.
 656          $tmp = [];
 657          foreach ($conversations as $id => $conv) {
 658              // Only individual conversations were supported in legacy messaging.
 659              if ($conv->type != \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
 660                  continue;
 661              }
 662              $data = new \stdClass();
 663              // The logic for the 'other user' is as follows:
 664              // If a conversation is of type 'individual', the other user is always the member who is not the current user.
 665              // If the conversation is of type 'group', the other user is always the sender of the most recent message.
 666              // The get_conversations method already follows this logic, so we just need the first member.
 667              $otheruser = reset($conv->members);
 668              $data->userid = $otheruser->id;
 669              $data->useridfrom = $conv->messages[0]->useridfrom ?? null;
 670              $data->fullname = $conv->members[$otheruser->id]->fullname;
 671              $data->profileimageurl = $conv->members[$otheruser->id]->profileimageurl;
 672              $data->profileimageurlsmall = $conv->members[$otheruser->id]->profileimageurlsmall;
 673              $data->ismessaging = isset($conv->messages[0]->text) ? true : false;
 674              $data->lastmessage = $conv->messages[0]->text ? clean_param($conv->messages[0]->text, PARAM_NOTAGS) : null;
 675              $data->lastmessagedate = $conv->messages[0]->timecreated ?? null;
 676              $data->messageid = $conv->messages[0]->id ?? null;
 677              $data->isonline = $conv->members[$otheruser->id]->isonline ?? null;
 678              $data->isblocked = $conv->members[$otheruser->id]->isblocked ?? null;
 679              $data->isread = $conv->isread;
 680              $data->unreadcount = $conv->unreadcount;
 681              $tmp[$data->userid] = $data;
 682          }
 683          return $tmp;
 684      }
 685  
 686      /**
 687       * Renders the messaging widget.
 688       *
 689       * @param bool $isdrawer Are we are rendering the drawer or is this on a full page?
 690       * @param int|null $sendtouser The ID of the user we want to send a message to
 691       * @param int|null $conversationid The ID of the conversation we want to load
 692       * @param string|null $view The first view to load in the message widget
 693       * @return string The HTML.
 694       */
 695      public static function render_messaging_widget(
 696          bool $isdrawer,
 697          int $sendtouser = null,
 698          int $conversationid = null,
 699          string $view = null
 700      ) {
 701          global $USER, $CFG, $PAGE;
 702  
 703          // Early bail out conditions.
 704          if (empty($CFG->messaging) || !isloggedin() || isguestuser() || user_not_fully_set_up($USER) ||
 705              get_user_preferences('auth_forcepasswordchange') ||
 706              (!$USER->policyagreed && !is_siteadmin() &&
 707                  ($manager = new \core_privacy\local\sitepolicy\manager()) && $manager->is_defined())) {
 708              return '';
 709          }
 710  
 711          $renderer = $PAGE->get_renderer('core');
 712          $requestcount = \core_message\api::get_received_contact_requests_count($USER->id);
 713          $contactscount = \core_message\api::count_contacts($USER->id);
 714  
 715          $choices = [];
 716          $choices[] = [
 717              'value' => \core_message\api::MESSAGE_PRIVACY_ONLYCONTACTS,
 718              'text' => get_string('contactableprivacy_onlycontacts', 'message')
 719          ];
 720          $choices[] = [
 721              'value' => \core_message\api::MESSAGE_PRIVACY_COURSEMEMBER,
 722              'text' => get_string('contactableprivacy_coursemember', 'message')
 723          ];
 724          if (!empty($CFG->messagingallusers)) {
 725              // Add the MESSAGE_PRIVACY_SITE option when site-wide messaging between users is enabled.
 726              $choices[] = [
 727                  'value' => \core_message\api::MESSAGE_PRIVACY_SITE,
 728                  'text' => get_string('contactableprivacy_site', 'message')
 729              ];
 730          }
 731  
 732          // Enter to send.
 733          $entertosend = get_user_preferences('message_entertosend', $CFG->messagingdefaultpressenter, $USER);
 734  
 735          $notification = '';
 736          if (!get_user_preferences('core_message_migrate_data', false)) {
 737              $notification = get_string('messagingdatahasnotbeenmigrated', 'message');
 738          }
 739  
 740          if ($isdrawer) {
 741              $template = 'core_message/message_drawer';
 742              $messageurl = new \moodle_url('/message/index.php');
 743          } else {
 744              $template = 'core_message/message_index';
 745              $messageurl = null;
 746          }
 747  
 748          $templatecontext = [
 749              'contactrequestcount' => $requestcount,
 750              'loggedinuser' => [
 751                  'id' => $USER->id,
 752                  'midnight' => usergetmidnight(time())
 753              ],
 754              // The starting timeout value for message polling.
 755              'messagepollmin' => $CFG->messagingminpoll ?? MESSAGE_DEFAULT_MIN_POLL_IN_SECONDS,
 756              // The maximum value that message polling timeout can reach.
 757              'messagepollmax' => $CFG->messagingmaxpoll ?? MESSAGE_DEFAULT_MAX_POLL_IN_SECONDS,
 758              // The timeout to reset back to after the max polling time has been reached.
 759              'messagepollaftermax' => $CFG->messagingtimeoutpoll ?? MESSAGE_DEFAULT_TIMEOUT_POLL_IN_SECONDS,
 760              'contacts' => [
 761                  'sectioncontacts' => [
 762                      'placeholders' => array_fill(0, $contactscount > 50 ? 50 : $contactscount, true)
 763                  ],
 764                  'sectionrequests' => [
 765                      'placeholders' => array_fill(0, $requestcount > 50 ? 50 : $requestcount, true)
 766                  ],
 767              ],
 768              'settings' => [
 769                  'privacy' => $choices,
 770                  'entertosend' => $entertosend
 771              ],
 772              'overview' => [
 773                  'messageurl' => $messageurl,
 774                  'notification' => $notification
 775              ],
 776              'isdrawer' => $isdrawer,
 777              'showemojipicker' => !empty($CFG->allowemojipicker),
 778              'messagemaxlength' => api::MESSAGE_MAX_LENGTH,
 779          ];
 780  
 781          if ($sendtouser || $conversationid) {
 782              $route = [
 783                  'path' => 'view-conversation',
 784                  'params' => $conversationid ? [$conversationid] : [null, 'create', $sendtouser]
 785              ];
 786          } else if ($view === 'contactrequests') {
 787              $route = [
 788                  'path' => 'view-contacts',
 789                  'params' => ['requests']
 790              ];
 791          } else {
 792              $route = null;
 793          }
 794  
 795          $templatecontext['route'] = json_encode($route);
 796  
 797          return $renderer->render_from_template($template, $templatecontext);
 798      }
 799  
 800      /**
 801       * Returns user details for a user, if they are visible to the current user in the message search.
 802       *
 803       * This method checks the visibility of a user specifically for the purpose of inclusion in the message search results.
 804       * Visibility depends on the site-wide messaging setting 'messagingallusers':
 805       * If enabled, visibility depends only on the core notion of visibility; a visible site or course profile.
 806       * If disabled, visibility requires that the user be sharing a course with the searching user, and have a visible profile there.
 807       * The current user is always returned.
 808       *
 809       * @param \stdClass $user
 810       * @return array the array of userdetails, if visible, or an empty array otherwise.
 811       */
 812      public static function search_get_user_details(\stdClass $user) : array {
 813          global $CFG, $USER;
 814          require_once($CFG->dirroot . '/user/lib.php');
 815  
 816          if ($CFG->messagingallusers || $user->id == $USER->id) {
 817              return \user_get_user_details_courses($user) ?? []; // This checks visibility of site and course profiles.
 818          } else {
 819              // Messaging specific: user must share a course with the searching user AND have a visible profile there.
 820              $sharedcourses = enrol_get_shared_courses($USER, $user);
 821              foreach ($sharedcourses as $course) {
 822                  if (user_can_view_profile($user, $course)) {
 823                      $userdetails = user_get_user_details($user, $course);
 824                      if (!is_null($userdetails)) {
 825                          return $userdetails;
 826                      }
 827                  }
 828              }
 829          }
 830          return [];
 831      }
 832  
 833      /**
 834       * Prevent unclosed HTML elements in a message.
 835       *
 836       * @param string $message The html message.
 837       * @param bool $removebody True if we want to remove tag body.
 838       * @return string The html properly structured.
 839       */
 840      public static function prevent_unclosed_html_tags(
 841          string $message,
 842          bool $removebody = false
 843      ) : string {
 844          $html = '';
 845          if (!empty($message)) {
 846              $doc = new DOMDocument();
 847              $olderror = libxml_use_internal_errors(true);
 848              $doc->loadHTML('<?xml version="1.0" encoding="UTF-8" ?>' . $message);
 849              libxml_clear_errors();
 850              libxml_use_internal_errors($olderror);
 851              $html = $doc->getElementsByTagName('body')->item(0)->C14N(false, true);
 852              if ($removebody) {
 853                  // Remove <body> element added in C14N function.
 854                  $html = preg_replace('~<(/?(?:body))[^>]*>\s*~i', '', $html);
 855              }
 856          }
 857  
 858          return $html;
 859      }
 860  }