Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

   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   * Forum subscription manager.
  19   *
  20   * @package    mod_forum
  21   * @copyright  2014 Andrew Nicols <andrew@nicols.co.uk>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace mod_forum;
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  /**
  30   * Forum subscription manager.
  31   *
  32   * @copyright  2014 Andrew Nicols <andrew@nicols.co.uk>
  33   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  34   */
  35  class subscriptions {
  36  
  37      /**
  38       * The status value for an unsubscribed discussion.
  39       *
  40       * @var int
  41       */
  42      const FORUM_DISCUSSION_UNSUBSCRIBED = -1;
  43  
  44      /**
  45       * The subscription cache for forums.
  46       *
  47       * The first level key is the user ID
  48       * The second level is the forum ID
  49       * The Value then is bool for subscribed of not.
  50       *
  51       * @var array[] An array of arrays.
  52       */
  53      protected static $forumcache = array();
  54  
  55      /**
  56       * The list of forums which have been wholly retrieved for the forum subscription cache.
  57       *
  58       * This allows for prior caching of an entire forum to reduce the
  59       * number of DB queries in a subscription check loop.
  60       *
  61       * @var bool[]
  62       */
  63      protected static $fetchedforums = array();
  64  
  65      /**
  66       * The subscription cache for forum discussions.
  67       *
  68       * The first level key is the user ID
  69       * The second level is the forum ID
  70       * The third level key is the discussion ID
  71       * The value is then the users preference (int)
  72       *
  73       * @var array[]
  74       */
  75      protected static $forumdiscussioncache = array();
  76  
  77      /**
  78       * The list of forums which have been wholly retrieved for the forum discussion subscription cache.
  79       *
  80       * This allows for prior caching of an entire forum to reduce the
  81       * number of DB queries in a subscription check loop.
  82       *
  83       * @var bool[]
  84       */
  85      protected static $discussionfetchedforums = array();
  86  
  87      /**
  88       * Whether a user is subscribed to this forum, or a discussion within
  89       * the forum.
  90       *
  91       * If a discussion is specified, then report whether the user is
  92       * subscribed to posts to this particular discussion, taking into
  93       * account the forum preference.
  94       *
  95       * If it is not specified then only the forum preference is considered.
  96       *
  97       * @param int $userid The user ID
  98       * @param \stdClass $forum The record of the forum to test
  99       * @param int $discussionid The ID of the discussion to check
 100       * @param $cm The coursemodule record. If not supplied, this will be calculated using get_fast_modinfo instead.
 101       * @return boolean
 102       */
 103      public static function is_subscribed($userid, $forum, $discussionid = null, $cm = null) {
 104          // If forum is force subscribed and has allowforcesubscribe, then user is subscribed.
 105          if (self::is_forcesubscribed($forum)) {
 106              if (!$cm) {
 107                  $cm = get_fast_modinfo($forum->course)->instances['forum'][$forum->id];
 108              }
 109              if (has_capability('mod/forum:allowforcesubscribe', \context_module::instance($cm->id), $userid)) {
 110                  return true;
 111              }
 112          }
 113  
 114          if ($discussionid === null) {
 115              return self::is_subscribed_to_forum($userid, $forum);
 116          }
 117  
 118          $subscriptions = self::fetch_discussion_subscription($forum->id, $userid);
 119  
 120          // Check whether there is a record for this discussion subscription.
 121          if (isset($subscriptions[$discussionid])) {
 122              return ($subscriptions[$discussionid] != self::FORUM_DISCUSSION_UNSUBSCRIBED);
 123          }
 124  
 125          return self::is_subscribed_to_forum($userid, $forum);
 126      }
 127  
 128      /**
 129       * Whether a user is subscribed to this forum.
 130       *
 131       * @param int $userid The user ID
 132       * @param \stdClass $forum The record of the forum to test
 133       * @return boolean
 134       */
 135      protected static function is_subscribed_to_forum($userid, $forum) {
 136          return self::fetch_subscription_cache($forum->id, $userid);
 137      }
 138  
 139      /**
 140       * Helper to determine whether a forum has it's subscription mode set
 141       * to forced subscription.
 142       *
 143       * @param \stdClass $forum The record of the forum to test
 144       * @return bool
 145       */
 146      public static function is_forcesubscribed($forum) {
 147          return ($forum->forcesubscribe == FORUM_FORCESUBSCRIBE);
 148      }
 149  
 150      /**
 151       * Helper to determine whether a forum has it's subscription mode set to disabled.
 152       *
 153       * @param \stdClass $forum The record of the forum to test
 154       * @return bool
 155       */
 156      public static function subscription_disabled($forum) {
 157          return ($forum->forcesubscribe == FORUM_DISALLOWSUBSCRIBE);
 158      }
 159  
 160      /**
 161       * Helper to determine whether the specified forum can be subscribed to.
 162       *
 163       * @param \stdClass $forum The record of the forum to test
 164       * @return bool
 165       */
 166      public static function is_subscribable($forum) {
 167          return (isloggedin() && !isguestuser() &&
 168                  !\mod_forum\subscriptions::is_forcesubscribed($forum) &&
 169                  !\mod_forum\subscriptions::subscription_disabled($forum));
 170      }
 171  
 172      /**
 173       * Set the forum subscription mode.
 174       *
 175       * By default when called without options, this is set to FORUM_FORCESUBSCRIBE.
 176       *
 177       * @param \stdClass $forum The record of the forum to set
 178       * @param int $status The new subscription state
 179       * @return bool
 180       */
 181      public static function set_subscription_mode($forumid, $status = 1) {
 182          global $DB;
 183          return $DB->set_field("forum", "forcesubscribe", $status, array("id" => $forumid));
 184      }
 185  
 186      /**
 187       * Returns the current subscription mode for the forum.
 188       *
 189       * @param \stdClass $forum The record of the forum to set
 190       * @return int The forum subscription mode
 191       */
 192      public static function get_subscription_mode($forum) {
 193          return $forum->forcesubscribe;
 194      }
 195  
 196      /**
 197       * Returns an array of forums that the current user is subscribed to and is allowed to unsubscribe from
 198       *
 199       * @return array An array of unsubscribable forums
 200       */
 201      public static function get_unsubscribable_forums() {
 202          global $USER, $DB;
 203  
 204          // Get courses that $USER is enrolled in and can see.
 205          $courses = enrol_get_my_courses();
 206          if (empty($courses)) {
 207              return array();
 208          }
 209  
 210          $courseids = array();
 211          foreach($courses as $course) {
 212              $courseids[] = $course->id;
 213          }
 214          list($coursesql, $courseparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'c');
 215  
 216          // Get all forums from the user's courses that they are subscribed to and which are not set to forced.
 217          // It is possible for users to be subscribed to a forum in subscription disallowed mode so they must be listed
 218          // here so that that can be unsubscribed from.
 219          $sql = "SELECT f.id, cm.id as cm, cm.visible, f.course
 220                  FROM {forum} f
 221                  JOIN {course_modules} cm ON cm.instance = f.id
 222                  JOIN {modules} m ON m.name = :modulename AND m.id = cm.module
 223                  LEFT JOIN {forum_subscriptions} fs ON (fs.forum = f.id AND fs.userid = :userid)
 224                  WHERE f.forcesubscribe <> :forcesubscribe
 225                  AND fs.id IS NOT NULL
 226                  AND cm.course
 227                  $coursesql";
 228          $params = array_merge($courseparams, array(
 229              'modulename'=>'forum',
 230              'userid' => $USER->id,
 231              'forcesubscribe' => FORUM_FORCESUBSCRIBE,
 232          ));
 233          $forums = $DB->get_recordset_sql($sql, $params);
 234  
 235          $unsubscribableforums = array();
 236          foreach($forums as $forum) {
 237              if (empty($forum->visible)) {
 238                  // The forum is hidden - check if the user can view the forum.
 239                  $context = \context_module::instance($forum->cm);
 240                  if (!has_capability('moodle/course:viewhiddenactivities', $context)) {
 241                      // The user can't see the hidden forum to cannot unsubscribe.
 242                      continue;
 243                  }
 244              }
 245  
 246              $unsubscribableforums[] = $forum;
 247          }
 248          $forums->close();
 249  
 250          return $unsubscribableforums;
 251      }
 252  
 253      /**
 254       * Get the list of potential subscribers to a forum.
 255       *
 256       * @param context_module $context the forum context.
 257       * @param integer $groupid the id of a group, or 0 for all groups.
 258       * @param string $fields the list of fields to return for each user. As for get_users_by_capability.
 259       * @param string $sort sort order. As for get_users_by_capability.
 260       * @return array list of users.
 261       */
 262      public static function get_potential_subscribers($context, $groupid, $fields, $sort = '') {
 263          global $DB;
 264  
 265          // Only active enrolled users or everybody on the frontpage.
 266          list($esql, $params) = get_enrolled_sql($context, 'mod/forum:allowforcesubscribe', $groupid, true);
 267          if (!$sort) {
 268              list($sort, $sortparams) = users_order_by_sql('u');
 269              $params = array_merge($params, $sortparams);
 270          }
 271  
 272          $sql = "SELECT $fields
 273                  FROM {user} u
 274                  JOIN ($esql) je ON je.id = u.id
 275                 WHERE u.auth <> 'nologin' AND u.suspended = 0 AND u.confirmed = 1
 276              ORDER BY $sort";
 277  
 278          return $DB->get_records_sql($sql, $params);
 279      }
 280  
 281      /**
 282       * Fetch the forum subscription data for the specified userid and forum.
 283       *
 284       * @param int $forumid The forum to retrieve a cache for
 285       * @param int $userid The user ID
 286       * @return boolean
 287       */
 288      public static function fetch_subscription_cache($forumid, $userid) {
 289          if (isset(self::$forumcache[$userid]) && isset(self::$forumcache[$userid][$forumid])) {
 290              return self::$forumcache[$userid][$forumid];
 291          }
 292          self::fill_subscription_cache($forumid, $userid);
 293  
 294          if (!isset(self::$forumcache[$userid]) || !isset(self::$forumcache[$userid][$forumid])) {
 295              return false;
 296          }
 297  
 298          return self::$forumcache[$userid][$forumid];
 299      }
 300  
 301      /**
 302       * Fill the forum subscription data for the specified userid and forum.
 303       *
 304       * If the userid is not specified, then all subscription data for that forum is fetched in a single query and used
 305       * for subsequent lookups without requiring further database queries.
 306       *
 307       * @param int $forumid The forum to retrieve a cache for
 308       * @param int $userid The user ID
 309       * @return void
 310       */
 311      public static function fill_subscription_cache($forumid, $userid = null) {
 312          global $DB;
 313  
 314          if (!isset(self::$fetchedforums[$forumid])) {
 315              // This forum has not been fetched as a whole.
 316              if (isset($userid)) {
 317                  if (!isset(self::$forumcache[$userid])) {
 318                      self::$forumcache[$userid] = array();
 319                  }
 320  
 321                  if (!isset(self::$forumcache[$userid][$forumid])) {
 322                      if ($DB->record_exists('forum_subscriptions', array(
 323                          'userid' => $userid,
 324                          'forum' => $forumid,
 325                      ))) {
 326                          self::$forumcache[$userid][$forumid] = true;
 327                      } else {
 328                          self::$forumcache[$userid][$forumid] = false;
 329                      }
 330                  }
 331              } else {
 332                  $subscriptions = $DB->get_recordset('forum_subscriptions', array(
 333                      'forum' => $forumid,
 334                  ), '', 'id, userid');
 335                  foreach ($subscriptions as $id => $data) {
 336                      if (!isset(self::$forumcache[$data->userid])) {
 337                          self::$forumcache[$data->userid] = array();
 338                      }
 339                      self::$forumcache[$data->userid][$forumid] = true;
 340                  }
 341                  self::$fetchedforums[$forumid] = true;
 342                  $subscriptions->close();
 343              }
 344          }
 345      }
 346  
 347      /**
 348       * Fill the forum subscription data for all forums that the specified userid can subscribe to in the specified course.
 349       *
 350       * @param int $courseid The course to retrieve a cache for
 351       * @param int $userid The user ID
 352       * @return void
 353       */
 354      public static function fill_subscription_cache_for_course($courseid, $userid) {
 355          global $DB;
 356  
 357          if (!isset(self::$forumcache[$userid])) {
 358              self::$forumcache[$userid] = array();
 359          }
 360  
 361          $sql = "SELECT
 362                      f.id AS forumid,
 363                      s.id AS subscriptionid
 364                  FROM {forum} f
 365                  LEFT JOIN {forum_subscriptions} s ON (s.forum = f.id AND s.userid = :userid)
 366                  WHERE f.course = :course
 367                  AND f.forcesubscribe <> :subscriptionforced";
 368  
 369          $subscriptions = $DB->get_recordset_sql($sql, array(
 370              'course' => $courseid,
 371              'userid' => $userid,
 372              'subscriptionforced' => FORUM_FORCESUBSCRIBE,
 373          ));
 374  
 375          foreach ($subscriptions as $id => $data) {
 376              self::$forumcache[$userid][$id] = !empty($data->subscriptionid);
 377          }
 378          $subscriptions->close();
 379      }
 380  
 381      /**
 382       * Returns a list of user objects who are subscribed to this forum.
 383       *
 384       * @param stdClass $forum The forum record.
 385       * @param int $groupid The group id if restricting subscriptions to a group of users, or 0 for all.
 386       * @param context_module $context the forum context, to save re-fetching it where possible.
 387       * @param string $fields requested user fields (with "u." table prefix).
 388       * @param boolean $includediscussionsubscriptions Whether to take discussion subscriptions and unsubscriptions into consideration.
 389       * @return array list of users.
 390       */
 391      public static function fetch_subscribed_users($forum, $groupid = 0, $context = null, $fields = null,
 392              $includediscussionsubscriptions = false) {
 393          global $CFG, $DB;
 394  
 395          if (empty($fields)) {
 396              $userfieldsapi = \core_user\fields::for_name();
 397              $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 398              $fields ="u.id,
 399                        u.username,
 400                        $allnames,
 401                        u.maildisplay,
 402                        u.mailformat,
 403                        u.maildigest,
 404                        u.imagealt,
 405                        u.email,
 406                        u.emailstop,
 407                        u.city,
 408                        u.country,
 409                        u.lastaccess,
 410                        u.lastlogin,
 411                        u.picture,
 412                        u.timezone,
 413                        u.theme,
 414                        u.lang,
 415                        u.trackforums,
 416                        u.mnethostid";
 417          }
 418  
 419          // Retrieve the forum context if it wasn't specified.
 420          $context = forum_get_context($forum->id, $context);
 421  
 422          if (self::is_forcesubscribed($forum)) {
 423              $results = \mod_forum\subscriptions::get_potential_subscribers($context, $groupid, $fields, "u.email ASC");
 424  
 425          } else {
 426              // Only active enrolled users or everybody on the frontpage.
 427              list($esql, $params) = get_enrolled_sql($context, '', $groupid, true);
 428              $params['forumid'] = $forum->id;
 429  
 430              if ($includediscussionsubscriptions) {
 431                  $params['sforumid'] = $forum->id;
 432                  $params['dsforumid'] = $forum->id;
 433                  $params['unsubscribed'] = self::FORUM_DISCUSSION_UNSUBSCRIBED;
 434  
 435                  $sql = "SELECT $fields
 436                          FROM (
 437                              SELECT userid FROM {forum_subscriptions} s
 438                              WHERE
 439                                  s.forum = :sforumid
 440                                  UNION
 441                              SELECT userid FROM {forum_discussion_subs} ds
 442                              WHERE
 443                                  ds.forum = :dsforumid AND ds.preference <> :unsubscribed
 444                          ) subscriptions
 445                          JOIN {user} u ON u.id = subscriptions.userid
 446                          JOIN ($esql) je ON je.id = u.id
 447                          WHERE u.auth <> 'nologin' AND u.suspended = 0 AND u.confirmed = 1
 448                          ORDER BY u.email ASC";
 449  
 450              } else {
 451                  $sql = "SELECT $fields
 452                          FROM {user} u
 453                          JOIN ($esql) je ON je.id = u.id
 454                          JOIN {forum_subscriptions} s ON s.userid = u.id
 455                          WHERE
 456                            s.forum = :forumid AND u.auth <> 'nologin' AND u.suspended = 0 AND u.confirmed = 1
 457                          ORDER BY u.email ASC";
 458              }
 459              $results = $DB->get_records_sql($sql, $params);
 460          }
 461  
 462          // Guest user should never be subscribed to a forum.
 463          unset($results[$CFG->siteguest]);
 464  
 465          // Apply the activity module availability resetrictions.
 466          $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course);
 467          $modinfo = get_fast_modinfo($forum->course);
 468          $info = new \core_availability\info_module($modinfo->get_cm($cm->id));
 469          $results = $info->filter_user_list($results);
 470  
 471          return $results;
 472      }
 473  
 474      /**
 475       * Retrieve the discussion subscription data for the specified userid and forum.
 476       *
 477       * This is returned as an array of discussions for that forum which contain the preference in a stdClass.
 478       *
 479       * @param int $forumid The forum to retrieve a cache for
 480       * @param int $userid The user ID
 481       * @return array of stdClass objects with one per discussion in the forum.
 482       */
 483      public static function fetch_discussion_subscription($forumid, $userid = null) {
 484          self::fill_discussion_subscription_cache($forumid, $userid);
 485  
 486          if (!isset(self::$forumdiscussioncache[$userid]) || !isset(self::$forumdiscussioncache[$userid][$forumid])) {
 487              return array();
 488          }
 489  
 490          return self::$forumdiscussioncache[$userid][$forumid];
 491      }
 492  
 493      /**
 494       * Fill the discussion subscription data for the specified userid and forum.
 495       *
 496       * If the userid is not specified, then all discussion subscription data for that forum is fetched in a single query
 497       * and used for subsequent lookups without requiring further database queries.
 498       *
 499       * @param int $forumid The forum to retrieve a cache for
 500       * @param int $userid The user ID
 501       * @return void
 502       */
 503      public static function fill_discussion_subscription_cache($forumid, $userid = null) {
 504          global $DB;
 505  
 506          if (!isset(self::$discussionfetchedforums[$forumid])) {
 507              // This forum hasn't been fetched as a whole yet.
 508              if (isset($userid)) {
 509                  if (!isset(self::$forumdiscussioncache[$userid])) {
 510                      self::$forumdiscussioncache[$userid] = array();
 511                  }
 512  
 513                  if (!isset(self::$forumdiscussioncache[$userid][$forumid])) {
 514                      $subscriptions = $DB->get_recordset('forum_discussion_subs', array(
 515                          'userid' => $userid,
 516                          'forum' => $forumid,
 517                      ), null, 'id, discussion, preference');
 518  
 519                      self::$forumdiscussioncache[$userid][$forumid] = array();
 520                      foreach ($subscriptions as $id => $data) {
 521                          self::add_to_discussion_cache($forumid, $userid, $data->discussion, $data->preference);
 522                      }
 523  
 524                      $subscriptions->close();
 525                  }
 526              } else {
 527                  $subscriptions = $DB->get_recordset('forum_discussion_subs', array(
 528                      'forum' => $forumid,
 529                  ), null, 'id, userid, discussion, preference');
 530                  foreach ($subscriptions as $id => $data) {
 531                      self::add_to_discussion_cache($forumid, $data->userid, $data->discussion, $data->preference);
 532                  }
 533                  self::$discussionfetchedforums[$forumid] = true;
 534                  $subscriptions->close();
 535              }
 536          }
 537      }
 538  
 539      /**
 540       * Add the specified discussion and user preference to the discussion
 541       * subscription cache.
 542       *
 543       * @param int $forumid The ID of the forum that this preference belongs to
 544       * @param int $userid The ID of the user that this preference belongs to
 545       * @param int $discussion The ID of the discussion that this preference relates to
 546       * @param int $preference The preference to store
 547       */
 548      protected static function add_to_discussion_cache($forumid, $userid, $discussion, $preference) {
 549          if (!isset(self::$forumdiscussioncache[$userid])) {
 550              self::$forumdiscussioncache[$userid] = array();
 551          }
 552  
 553          if (!isset(self::$forumdiscussioncache[$userid][$forumid])) {
 554              self::$forumdiscussioncache[$userid][$forumid] = array();
 555          }
 556  
 557          self::$forumdiscussioncache[$userid][$forumid][$discussion] = $preference;
 558      }
 559  
 560      /**
 561       * Reset the discussion cache.
 562       *
 563       * This cache is used to reduce the number of database queries when
 564       * checking forum discussion subscription states.
 565       */
 566      public static function reset_discussion_cache() {
 567          self::$forumdiscussioncache = array();
 568          self::$discussionfetchedforums = array();
 569      }
 570  
 571      /**
 572       * Reset the forum cache.
 573       *
 574       * This cache is used to reduce the number of database queries when
 575       * checking forum subscription states.
 576       */
 577      public static function reset_forum_cache() {
 578          self::$forumcache = array();
 579          self::$fetchedforums = array();
 580      }
 581  
 582      /**
 583       * Adds user to the subscriber list.
 584       *
 585       * @param int $userid The ID of the user to subscribe
 586       * @param \stdClass $forum The forum record for this forum.
 587       * @param \context_module|null $context Module context, may be omitted if not known or if called for the current
 588       *      module set in page.
 589       * @param boolean $userrequest Whether the user requested this change themselves. This has an effect on whether
 590       *     discussion subscriptions are removed too.
 591       * @return bool|int Returns true if the user is already subscribed, or the forum_subscriptions ID if the user was
 592       *     successfully subscribed.
 593       */
 594      public static function subscribe_user($userid, $forum, $context = null, $userrequest = false) {
 595          global $DB;
 596  
 597          if (self::is_subscribed($userid, $forum)) {
 598              return true;
 599          }
 600  
 601          $sub = new \stdClass();
 602          $sub->userid  = $userid;
 603          $sub->forum = $forum->id;
 604  
 605          $result = $DB->insert_record("forum_subscriptions", $sub);
 606  
 607          if ($userrequest) {
 608              $discussionsubscriptions = $DB->get_recordset('forum_discussion_subs', array('userid' => $userid, 'forum' => $forum->id));
 609              $DB->delete_records_select('forum_discussion_subs',
 610                      'userid = :userid AND forum = :forumid AND preference <> :preference', array(
 611                          'userid' => $userid,
 612                          'forumid' => $forum->id,
 613                          'preference' => self::FORUM_DISCUSSION_UNSUBSCRIBED,
 614                      ));
 615  
 616              // Reset the subscription caches for this forum.
 617              // We know that the there were previously entries and there aren't any more.
 618              if (isset(self::$forumdiscussioncache[$userid]) && isset(self::$forumdiscussioncache[$userid][$forum->id])) {
 619                  foreach (self::$forumdiscussioncache[$userid][$forum->id] as $discussionid => $preference) {
 620                      if ($preference != self::FORUM_DISCUSSION_UNSUBSCRIBED) {
 621                          unset(self::$forumdiscussioncache[$userid][$forum->id][$discussionid]);
 622                      }
 623                  }
 624              }
 625          }
 626  
 627          // Reset the cache for this forum.
 628          self::$forumcache[$userid][$forum->id] = true;
 629  
 630          $context = forum_get_context($forum->id, $context);
 631          $params = array(
 632              'context' => $context,
 633              'objectid' => $result,
 634              'relateduserid' => $userid,
 635              'other' => array('forumid' => $forum->id),
 636  
 637          );
 638          $event  = event\subscription_created::create($params);
 639          if ($userrequest && $discussionsubscriptions) {
 640              foreach ($discussionsubscriptions as $subscription) {
 641                  $event->add_record_snapshot('forum_discussion_subs', $subscription);
 642              }
 643              $discussionsubscriptions->close();
 644          }
 645          $event->trigger();
 646  
 647          return $result;
 648      }
 649  
 650      /**
 651       * Removes user from the subscriber list
 652       *
 653       * @param int $userid The ID of the user to unsubscribe
 654       * @param \stdClass $forum The forum record for this forum.
 655       * @param \context_module|null $context Module context, may be omitted if not known or if called for the current
 656       *     module set in page.
 657       * @param boolean $userrequest Whether the user requested this change themselves. This has an effect on whether
 658       *     discussion subscriptions are removed too.
 659       * @return boolean Always returns true.
 660       */
 661      public static function unsubscribe_user($userid, $forum, $context = null, $userrequest = false) {
 662          global $DB;
 663  
 664          $sqlparams = array(
 665              'userid' => $userid,
 666              'forum' => $forum->id,
 667          );
 668          $DB->delete_records('forum_digests', $sqlparams);
 669  
 670          if ($forumsubscription = $DB->get_record('forum_subscriptions', $sqlparams)) {
 671              $DB->delete_records('forum_subscriptions', array('id' => $forumsubscription->id));
 672  
 673              if ($userrequest) {
 674                  $discussionsubscriptions = $DB->get_recordset('forum_discussion_subs', $sqlparams);
 675                  $DB->delete_records('forum_discussion_subs',
 676                          array('userid' => $userid, 'forum' => $forum->id, 'preference' => self::FORUM_DISCUSSION_UNSUBSCRIBED));
 677  
 678                  // We know that the there were previously entries and there aren't any more.
 679                  if (isset(self::$forumdiscussioncache[$userid]) && isset(self::$forumdiscussioncache[$userid][$forum->id])) {
 680                      self::$forumdiscussioncache[$userid][$forum->id] = array();
 681                  }
 682              }
 683  
 684              // Reset the cache for this forum.
 685              self::$forumcache[$userid][$forum->id] = false;
 686  
 687              $context = forum_get_context($forum->id, $context);
 688              $params = array(
 689                  'context' => $context,
 690                  'objectid' => $forumsubscription->id,
 691                  'relateduserid' => $userid,
 692                  'other' => array('forumid' => $forum->id),
 693  
 694              );
 695              $event = event\subscription_deleted::create($params);
 696              $event->add_record_snapshot('forum_subscriptions', $forumsubscription);
 697              if ($userrequest && $discussionsubscriptions) {
 698                  foreach ($discussionsubscriptions as $subscription) {
 699                      $event->add_record_snapshot('forum_discussion_subs', $subscription);
 700                  }
 701                  $discussionsubscriptions->close();
 702              }
 703              $event->trigger();
 704          }
 705  
 706          return true;
 707      }
 708  
 709      /**
 710       * Subscribes the user to the specified discussion.
 711       *
 712       * @param int $userid The userid of the user being subscribed
 713       * @param \stdClass $discussion The discussion to subscribe to
 714       * @param \context_module|null $context Module context, may be omitted if not known or if called for the current
 715       *     module set in page.
 716       * @return boolean Whether a change was made
 717       */
 718      public static function subscribe_user_to_discussion($userid, $discussion, $context = null) {
 719          global $DB;
 720  
 721          // First check whether the user is subscribed to the discussion already.
 722          $subscription = $DB->get_record('forum_discussion_subs', array('userid' => $userid, 'discussion' => $discussion->id));
 723          if ($subscription) {
 724              if ($subscription->preference != self::FORUM_DISCUSSION_UNSUBSCRIBED) {
 725                  // The user is already subscribed to the discussion. Ignore.
 726                  return false;
 727              }
 728          }
 729          // No discussion-level subscription. Check for a forum level subscription.
 730          if ($DB->record_exists('forum_subscriptions', array('userid' => $userid, 'forum' => $discussion->forum))) {
 731              if ($subscription && $subscription->preference == self::FORUM_DISCUSSION_UNSUBSCRIBED) {
 732                  // The user is subscribed to the forum, but unsubscribed from the discussion, delete the discussion preference.
 733                  $DB->delete_records('forum_discussion_subs', array('id' => $subscription->id));
 734                  unset(self::$forumdiscussioncache[$userid][$discussion->forum][$discussion->id]);
 735              } else {
 736                  // The user is already subscribed to the forum. Ignore.
 737                  return false;
 738              }
 739          } else {
 740              if ($subscription) {
 741                  $subscription->preference = time();
 742                  $DB->update_record('forum_discussion_subs', $subscription);
 743              } else {
 744                  $subscription = new \stdClass();
 745                  $subscription->userid  = $userid;
 746                  $subscription->forum = $discussion->forum;
 747                  $subscription->discussion = $discussion->id;
 748                  $subscription->preference = time();
 749  
 750                  $subscription->id = $DB->insert_record('forum_discussion_subs', $subscription);
 751                  self::$forumdiscussioncache[$userid][$discussion->forum][$discussion->id] = $subscription->preference;
 752              }
 753          }
 754  
 755          $context = forum_get_context($discussion->forum, $context);
 756          $params = array(
 757              'context' => $context,
 758              'objectid' => $subscription->id,
 759              'relateduserid' => $userid,
 760              'other' => array(
 761                  'forumid' => $discussion->forum,
 762                  'discussion' => $discussion->id,
 763              ),
 764  
 765          );
 766          $event  = event\discussion_subscription_created::create($params);
 767          $event->trigger();
 768  
 769          return true;
 770      }
 771      /**
 772       * Unsubscribes the user from the specified discussion.
 773       *
 774       * @param int $userid The userid of the user being unsubscribed
 775       * @param \stdClass $discussion The discussion to unsubscribe from
 776       * @param \context_module|null $context Module context, may be omitted if not known or if called for the current
 777       *     module set in page.
 778       * @return boolean Whether a change was made
 779       */
 780      public static function unsubscribe_user_from_discussion($userid, $discussion, $context = null) {
 781          global $DB;
 782  
 783          // First check whether the user's subscription preference for this discussion.
 784          $subscription = $DB->get_record('forum_discussion_subs', array('userid' => $userid, 'discussion' => $discussion->id));
 785          if ($subscription) {
 786              if ($subscription->preference == self::FORUM_DISCUSSION_UNSUBSCRIBED) {
 787                  // The user is already unsubscribed from the discussion. Ignore.
 788                  return false;
 789              }
 790          }
 791          // No discussion-level preference. Check for a forum level subscription.
 792          if (!$DB->record_exists('forum_subscriptions', array('userid' => $userid, 'forum' => $discussion->forum))) {
 793              if ($subscription && $subscription->preference != self::FORUM_DISCUSSION_UNSUBSCRIBED) {
 794                  // The user is not subscribed to the forum, but subscribed from the discussion, delete the discussion subscription.
 795                  $DB->delete_records('forum_discussion_subs', array('id' => $subscription->id));
 796                  unset(self::$forumdiscussioncache[$userid][$discussion->forum][$discussion->id]);
 797              } else {
 798                  // The user is not subscribed from the forum. Ignore.
 799                  return false;
 800              }
 801          } else {
 802              if ($subscription) {
 803                  $subscription->preference = self::FORUM_DISCUSSION_UNSUBSCRIBED;
 804                  $DB->update_record('forum_discussion_subs', $subscription);
 805              } else {
 806                  $subscription = new \stdClass();
 807                  $subscription->userid  = $userid;
 808                  $subscription->forum = $discussion->forum;
 809                  $subscription->discussion = $discussion->id;
 810                  $subscription->preference = self::FORUM_DISCUSSION_UNSUBSCRIBED;
 811  
 812                  $subscription->id = $DB->insert_record('forum_discussion_subs', $subscription);
 813              }
 814              self::$forumdiscussioncache[$userid][$discussion->forum][$discussion->id] = $subscription->preference;
 815          }
 816  
 817          $context = forum_get_context($discussion->forum, $context);
 818          $params = array(
 819              'context' => $context,
 820              'objectid' => $subscription->id,
 821              'relateduserid' => $userid,
 822              'other' => array(
 823                  'forumid' => $discussion->forum,
 824                  'discussion' => $discussion->id,
 825              ),
 826  
 827          );
 828          $event  = event\discussion_subscription_deleted::create($params);
 829          $event->trigger();
 830  
 831          return true;
 832      }
 833  
 834      /**
 835       * Gets the default subscription value for the logged in user.
 836       *
 837       * @param \stdClass $forum The forum record
 838       * @param \context $context The course context
 839       * @param \cm_info $cm cm_info
 840       * @param int|null $discussionid The discussion we are checking against
 841       * @return bool Default subscription
 842       * @throws coding_exception
 843       */
 844      public static function get_user_default_subscription($forum, $context, $cm, ?int $discussionid) {
 845          global $USER;
 846          $manageactivities = has_capability('moodle/course:manageactivities', $context);
 847          if (\mod_forum\subscriptions::subscription_disabled($forum) && !$manageactivities) {
 848              // User does not have permission to subscribe to this discussion at all.
 849              $discussionsubscribe = false;
 850          } else if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
 851              // User does not have permission to unsubscribe from this discussion at all.
 852              $discussionsubscribe = true;
 853          } else {
 854              if (isset($discussionid) && self::is_subscribed($USER->id, $forum, $discussionid, $cm)) {
 855                  // User is subscribed to the discussion - continue the subscription.
 856                  $discussionsubscribe = true;
 857              } else if (!isset($discussionid) && \mod_forum\subscriptions::is_subscribed($USER->id, $forum, null, $cm)) {
 858                  // Starting a new discussion, and the user is subscribed to the forum - subscribe to the discussion.
 859                  $discussionsubscribe = true;
 860              } else {
 861                  // User is not subscribed to either forum or discussion. Follow user preference.
 862                  $discussionsubscribe = $USER->autosubscribe ?? false;
 863              }
 864          }
 865  
 866          return $discussionsubscribe;
 867      }
 868  }