Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

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