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

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [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   * @package   mod_forum
  19   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  20   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21   */
  22  
  23  defined('MOODLE_INTERNAL') || die();
  24  
  25  /** Include required files */
  26  require_once (__DIR__ . '/deprecatedlib.php');
  27  require_once($CFG->libdir.'/filelib.php');
  28  
  29  /// CONSTANTS ///////////////////////////////////////////////////////////
  30  
  31  define('FORUM_MODE_FLATOLDEST', 1);
  32  define('FORUM_MODE_FLATNEWEST', -1);
  33  define('FORUM_MODE_THREADED', 2);
  34  define('FORUM_MODE_NESTED', 3);
  35  define('FORUM_MODE_NESTED_V2', 4);
  36  
  37  define('FORUM_CHOOSESUBSCRIBE', 0);
  38  define('FORUM_FORCESUBSCRIBE', 1);
  39  define('FORUM_INITIALSUBSCRIBE', 2);
  40  define('FORUM_DISALLOWSUBSCRIBE',3);
  41  
  42  /**
  43   * FORUM_TRACKING_OFF - Tracking is not available for this forum.
  44   */
  45  define('FORUM_TRACKING_OFF', 0);
  46  
  47  /**
  48   * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
  49   */
  50  define('FORUM_TRACKING_OPTIONAL', 1);
  51  
  52  /**
  53   * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
  54   * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
  55   */
  56  define('FORUM_TRACKING_FORCED', 2);
  57  
  58  define('FORUM_MAILED_PENDING', 0);
  59  define('FORUM_MAILED_SUCCESS', 1);
  60  define('FORUM_MAILED_ERROR', 2);
  61  
  62  if (!defined('FORUM_CRON_USER_CACHE')) {
  63      /** Defines how many full user records are cached in forum cron. */
  64      define('FORUM_CRON_USER_CACHE', 5000);
  65  }
  66  
  67  /**
  68   * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
  69   */
  70  define('FORUM_POSTS_ALL_USER_GROUPS', -2);
  71  
  72  define('FORUM_DISCUSSION_PINNED', 1);
  73  define('FORUM_DISCUSSION_UNPINNED', 0);
  74  
  75  /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
  76  
  77  /**
  78   * Given an object containing all the necessary data,
  79   * (defined by the form in mod_form.php) this function
  80   * will create a new instance and return the id number
  81   * of the new instance.
  82   *
  83   * @param stdClass $forum add forum instance
  84   * @param mod_forum_mod_form $mform
  85   * @return int intance id
  86   */
  87  function forum_add_instance($forum, $mform = null) {
  88      global $CFG, $DB;
  89  
  90      require_once($CFG->dirroot.'/mod/forum/locallib.php');
  91  
  92      $forum->timemodified = time();
  93  
  94      if (empty($forum->assessed)) {
  95          $forum->assessed = 0;
  96      }
  97  
  98      if (empty($forum->ratingtime) or empty($forum->assessed)) {
  99          $forum->assesstimestart  = 0;
 100          $forum->assesstimefinish = 0;
 101      }
 102  
 103      $forum->id = $DB->insert_record('forum', $forum);
 104      $modcontext = context_module::instance($forum->coursemodule);
 105  
 106      if ($forum->type == 'single') {  // Create related discussion.
 107          $discussion = new stdClass();
 108          $discussion->course        = $forum->course;
 109          $discussion->forum         = $forum->id;
 110          $discussion->name          = $forum->name;
 111          $discussion->assessed      = $forum->assessed;
 112          $discussion->message       = $forum->intro;
 113          $discussion->messageformat = $forum->introformat;
 114          $discussion->messagetrust  = trusttext_trusted(context_course::instance($forum->course));
 115          $discussion->mailnow       = false;
 116          $discussion->groupid       = -1;
 117  
 118          $message = '';
 119  
 120          $discussion->id = forum_add_discussion($discussion, null, $message);
 121  
 122          if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
 123              // Ugly hack - we need to copy the files somehow.
 124              $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
 125              $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
 126  
 127              $options = array('subdirs'=>true); // Use the same options as intro field!
 128              $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
 129              $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
 130          }
 131      }
 132  
 133      forum_update_calendar($forum, $forum->coursemodule);
 134      forum_grade_item_update($forum);
 135  
 136      $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
 137      \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
 138  
 139      return $forum->id;
 140  }
 141  
 142  /**
 143   * Handle changes following the creation of a forum instance.
 144   * This function is typically called by the course_module_created observer.
 145   *
 146   * @param object $context the forum context
 147   * @param stdClass $forum The forum object
 148   * @return void
 149   */
 150  function forum_instance_created($context, $forum) {
 151      if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
 152          $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
 153          foreach ($users as $user) {
 154              \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
 155          }
 156      }
 157  }
 158  
 159  /**
 160   * Given an object containing all the necessary data,
 161   * (defined by the form in mod_form.php) this function
 162   * will update an existing instance with new data.
 163   *
 164   * @global object
 165   * @param object $forum forum instance (with magic quotes)
 166   * @return bool success
 167   */
 168  function forum_update_instance($forum, $mform) {
 169      global $CFG, $DB, $OUTPUT, $USER;
 170  
 171      require_once($CFG->dirroot.'/mod/forum/locallib.php');
 172  
 173      $forum->timemodified = time();
 174      $forum->id           = $forum->instance;
 175  
 176      if (empty($forum->assessed)) {
 177          $forum->assessed = 0;
 178      }
 179  
 180      if (empty($forum->ratingtime) or empty($forum->assessed)) {
 181          $forum->assesstimestart  = 0;
 182          $forum->assesstimefinish = 0;
 183      }
 184  
 185      $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
 186  
 187      // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
 188      // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
 189      // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
 190      $updategrades = false;
 191  
 192      if ($oldforum->assessed <> $forum->assessed) {
 193          // Whether this forum is rated.
 194          $updategrades = true;
 195      }
 196  
 197      if ($oldforum->scale <> $forum->scale) {
 198          // The scale currently in use.
 199          $updategrades = true;
 200      }
 201  
 202      if (empty($oldforum->grade_forum) || $oldforum->grade_forum <> $forum->grade_forum) {
 203          // The whole forum grading.
 204          $updategrades = true;
 205      }
 206  
 207      if ($updategrades) {
 208          forum_update_grades($forum); // Recalculate grades for the forum.
 209      }
 210  
 211      if ($forum->type == 'single') {  // Update related discussion and post.
 212          $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
 213          if (!empty($discussions)) {
 214              if (count($discussions) > 1) {
 215                  echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
 216              }
 217              $discussion = array_pop($discussions);
 218          } else {
 219              // try to recover by creating initial discussion - MDL-16262
 220              $discussion = new stdClass();
 221              $discussion->course          = $forum->course;
 222              $discussion->forum           = $forum->id;
 223              $discussion->name            = $forum->name;
 224              $discussion->assessed        = $forum->assessed;
 225              $discussion->message         = $forum->intro;
 226              $discussion->messageformat   = $forum->introformat;
 227              $discussion->messagetrust    = true;
 228              $discussion->mailnow         = false;
 229              $discussion->groupid         = -1;
 230  
 231              $message = '';
 232  
 233              forum_add_discussion($discussion, null, $message);
 234  
 235              if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
 236                  print_error('cannotadd', 'forum');
 237              }
 238          }
 239          if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
 240              print_error('cannotfindfirstpost', 'forum');
 241          }
 242  
 243          $cm         = get_coursemodule_from_instance('forum', $forum->id);
 244          $modcontext = context_module::instance($cm->id, MUST_EXIST);
 245  
 246          $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
 247          $post->subject       = $forum->name;
 248          $post->message       = $forum->intro;
 249          $post->messageformat = $forum->introformat;
 250          $post->messagetrust  = trusttext_trusted($modcontext);
 251          $post->modified      = $forum->timemodified;
 252          $post->userid        = $USER->id;    // MDL-18599, so that current teacher can take ownership of activities.
 253  
 254          if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
 255              // Ugly hack - we need to copy the files somehow.
 256              $options = array('subdirs'=>true); // Use the same options as intro field!
 257              $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
 258          }
 259  
 260          \mod_forum\local\entities\post::add_message_counts($post);
 261          $DB->update_record('forum_posts', $post);
 262          $discussion->name = $forum->name;
 263          $DB->update_record('forum_discussions', $discussion);
 264      }
 265  
 266      $DB->update_record('forum', $forum);
 267  
 268      $modcontext = context_module::instance($forum->coursemodule);
 269      if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
 270          $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
 271          foreach ($users as $user) {
 272              \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
 273          }
 274      }
 275  
 276      forum_update_calendar($forum, $forum->coursemodule);
 277      forum_grade_item_update($forum);
 278  
 279      $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
 280      \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
 281  
 282      return true;
 283  }
 284  
 285  
 286  /**
 287   * Given an ID of an instance of this module,
 288   * this function will permanently delete the instance
 289   * and any data that depends on it.
 290   *
 291   * @global object
 292   * @param int $id forum instance id
 293   * @return bool success
 294   */
 295  function forum_delete_instance($id) {
 296      global $DB;
 297  
 298      if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
 299          return false;
 300      }
 301      if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
 302          return false;
 303      }
 304      if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
 305          return false;
 306      }
 307  
 308      $context = context_module::instance($cm->id);
 309  
 310      // now get rid of all files
 311      $fs = get_file_storage();
 312      $fs->delete_area_files($context->id);
 313  
 314      $result = true;
 315  
 316      \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
 317  
 318      // Delete digest and subscription preferences.
 319      $DB->delete_records('forum_digests', array('forum' => $forum->id));
 320      $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
 321      $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
 322  
 323      if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
 324          foreach ($discussions as $discussion) {
 325              if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
 326                  $result = false;
 327              }
 328          }
 329      }
 330  
 331      forum_tp_delete_read_records(-1, -1, -1, $forum->id);
 332  
 333      forum_grade_item_delete($forum);
 334  
 335      // We must delete the module record after we delete the grade item.
 336      if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
 337          $result = false;
 338      }
 339  
 340      return $result;
 341  }
 342  
 343  
 344  /**
 345   * Indicates API features that the forum supports.
 346   *
 347   * @uses FEATURE_GROUPS
 348   * @uses FEATURE_GROUPINGS
 349   * @uses FEATURE_MOD_INTRO
 350   * @uses FEATURE_COMPLETION_TRACKS_VIEWS
 351   * @uses FEATURE_COMPLETION_HAS_RULES
 352   * @uses FEATURE_GRADE_HAS_GRADE
 353   * @uses FEATURE_GRADE_OUTCOMES
 354   * @param string $feature
 355   * @return mixed True if yes (some features may use other values)
 356   */
 357  function forum_supports($feature) {
 358      switch($feature) {
 359          case FEATURE_GROUPS:                  return true;
 360          case FEATURE_GROUPINGS:               return true;
 361          case FEATURE_MOD_INTRO:               return true;
 362          case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
 363          case FEATURE_COMPLETION_HAS_RULES:    return true;
 364          case FEATURE_GRADE_HAS_GRADE:         return true;
 365          case FEATURE_GRADE_OUTCOMES:          return true;
 366          case FEATURE_RATE:                    return true;
 367          case FEATURE_BACKUP_MOODLE2:          return true;
 368          case FEATURE_SHOW_DESCRIPTION:        return true;
 369          case FEATURE_PLAGIARISM:              return true;
 370          case FEATURE_ADVANCED_GRADING:        return true;
 371  
 372          default: return null;
 373      }
 374  }
 375  
 376  /**
 377   * Create a message-id string to use in the custom headers of forum notification emails
 378   *
 379   * message-id is used by email clients to identify emails and to nest conversations
 380   *
 381   * @param int $postid The ID of the forum post we are notifying the user about
 382   * @param int $usertoid The ID of the user being notified
 383   * @return string A unique message-id
 384   */
 385  function forum_get_email_message_id($postid, $usertoid) {
 386      return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
 387  }
 388  
 389  /**
 390   *
 391   * @param object $course
 392   * @param object $user
 393   * @param object $mod TODO this is not used in this function, refactor
 394   * @param object $forum
 395   * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
 396   */
 397  function forum_user_outline($course, $user, $mod, $forum) {
 398      global $CFG;
 399      require_once("$CFG->libdir/gradelib.php");
 400  
 401      $gradeinfo = '';
 402      $gradetime = 0;
 403  
 404      $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
 405      if (!empty($grades->items[0]->grades)) {
 406          // Item 0 is the rating.
 407          $grade = reset($grades->items[0]->grades);
 408          $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
 409          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 410              $gradeinfo .= get_string('gradeforrating', 'forum', $grade) .  html_writer::empty_tag('br');
 411          } else {
 412              $gradeinfo .= get_string('gradeforratinghidden', 'forum') . html_writer::empty_tag('br');
 413          }
 414      }
 415  
 416      // Item 1 is the whole-forum grade.
 417      if (!empty($grades->items[1]->grades)) {
 418          $grade = reset($grades->items[1]->grades);
 419          $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
 420          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 421              $gradeinfo .= get_string('gradeforwholeforum', 'forum', $grade) .  html_writer::empty_tag('br');
 422          } else {
 423              $gradeinfo .= get_string('gradeforwholeforumhidden', 'forum') . html_writer::empty_tag('br');
 424          }
 425      }
 426  
 427      $count = forum_count_user_posts($forum->id, $user->id);
 428      if ($count && $count->postcount > 0) {
 429          $info = get_string("numposts", "forum", $count->postcount);
 430          $time = $count->lastpost;
 431  
 432          if ($gradeinfo) {
 433              $info .= ', ' . $gradeinfo;
 434              $time = max($time, $gradetime);
 435          }
 436  
 437          return (object) [
 438              'info' => $info,
 439              'time' => $time,
 440          ];
 441      } else if ($gradeinfo) {
 442          return (object) [
 443              'info' => $gradeinfo,
 444              'time' => $gradetime,
 445          ];
 446      }
 447  
 448      return null;
 449  }
 450  
 451  
 452  /**
 453   * @global object
 454   * @global object
 455   * @param object $coure
 456   * @param object $user
 457   * @param object $mod
 458   * @param object $forum
 459   */
 460  function forum_user_complete($course, $user, $mod, $forum) {
 461      global $CFG, $USER;
 462      require_once("$CFG->libdir/gradelib.php");
 463  
 464      $getgradeinfo = function($grades, string $type) use ($course): string {
 465          global $OUTPUT;
 466  
 467          if (empty($grades)) {
 468              return '';
 469          }
 470  
 471          $result = '';
 472          $grade = reset($grades);
 473          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 474              $result .= $OUTPUT->container(get_string("gradefor{$type}", "forum", $grade));
 475              if ($grade->str_feedback) {
 476                  $result .= $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
 477              }
 478          } else {
 479              $result .= $OUTPUT->container(get_string("gradefor{$type}hidden", "forum"));
 480          }
 481  
 482          return $result;
 483      };
 484  
 485      $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
 486  
 487      // Item 0 is the rating.
 488      if (!empty($grades->items[0]->grades)) {
 489          echo $getgradeinfo($grades->items[0]->grades, 'rating');
 490      }
 491  
 492      // Item 1 is the whole-forum grade.
 493      if (!empty($grades->items[1]->grades)) {
 494          echo $getgradeinfo($grades->items[1]->grades, 'wholeforum');
 495      }
 496  
 497      if ($posts = forum_get_user_posts($forum->id, $user->id)) {
 498          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
 499              print_error('invalidcoursemodule');
 500          }
 501          $context = context_module::instance($cm->id);
 502          $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
 503          $posts = array_filter($posts, function($post) use ($discussions) {
 504              return isset($discussions[$post->discussion]);
 505          });
 506          $entityfactory = mod_forum\local\container::get_entity_factory();
 507          $rendererfactory = mod_forum\local\container::get_renderer_factory();
 508          $postrenderer = $rendererfactory->get_posts_renderer();
 509  
 510          echo $postrenderer->render(
 511              $USER,
 512              [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
 513              array_map(function($discussion) use ($entityfactory) {
 514                  return $entityfactory->get_discussion_from_stdclass($discussion);
 515              }, $discussions),
 516              array_map(function($post) use ($entityfactory) {
 517                  return $entityfactory->get_post_from_stdclass($post);
 518              }, $posts)
 519          );
 520      } else {
 521          echo "<p>".get_string("noposts", "forum")."</p>";
 522      }
 523  }
 524  
 525  /**
 526   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
 527   */
 528  function forum_filter_user_groups_discussions() {
 529      throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.');
 530  }
 531  
 532  /**
 533   * Returns whether the discussion group is visible by the current user or not.
 534   *
 535   * @since Moodle 2.8, 2.7.1, 2.6.4
 536   * @param cm_info $cm The discussion course module
 537   * @param int $discussiongroupid The discussion groupid
 538   * @return bool
 539   */
 540  function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
 541  
 542      if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
 543          return true;
 544      }
 545  
 546      if (isguestuser()) {
 547          return false;
 548      }
 549  
 550      if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
 551              in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
 552          return true;
 553      }
 554  
 555      return false;
 556  }
 557  
 558  /**
 559   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
 560   */
 561  function forum_print_overview() {
 562      throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.');
 563  }
 564  
 565  /**
 566   * Given a course and a date, prints a summary of all the new
 567   * messages posted in the course since that date
 568   *
 569   * @global object
 570   * @global object
 571   * @global object
 572   * @uses CONTEXT_MODULE
 573   * @uses VISIBLEGROUPS
 574   * @param object $course
 575   * @param bool $viewfullnames capability
 576   * @param int $timestart
 577   * @return bool success
 578   */
 579  function forum_print_recent_activity($course, $viewfullnames, $timestart) {
 580      global $USER, $DB, $OUTPUT;
 581  
 582      // do not use log table if possible, it may be huge and is expensive to join with other tables
 583  
 584      $userfieldsapi = \core_user\fields::for_userpic();
 585      $allnamefields = $userfieldsapi->get_sql('u', false, '', 'duserid', false)->selects;
 586      if (!$posts = $DB->get_records_sql("SELECT p.*,
 587                                                f.course, f.type AS forumtype, f.name AS forumname, f.intro, f.introformat, f.duedate,
 588                                                f.cutoffdate, f.assessed AS forumassessed, f.assesstimestart, f.assesstimefinish,
 589                                                f.scale, f.grade_forum, f.maxbytes, f.maxattachments, f.forcesubscribe,
 590                                                f.trackingtype, f.rsstype, f.rssarticles, f.timemodified, f.warnafter, f.blockafter,
 591                                                f.blockperiod, f.completiondiscussions, f.completionreplies, f.completionposts,
 592                                                f.displaywordcount, f.lockdiscussionafter, f.grade_forum_notify,
 593                                                d.name AS discussionname, d.firstpost, d.userid AS discussionstarter,
 594                                                d.assessed AS discussionassessed, d.timemodified, d.usermodified, d.forum, d.groupid,
 595                                                d.timestart, d.timeend, d.pinned, d.timelocked,
 596                                                $allnamefields
 597                                           FROM {forum_posts} p
 598                                                JOIN {forum_discussions} d ON d.id = p.discussion
 599                                                JOIN {forum} f             ON f.id = d.forum
 600                                                JOIN {user} u              ON u.id = p.userid
 601                                          WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
 602                                       ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
 603           return false;
 604      }
 605  
 606      $modinfo = get_fast_modinfo($course);
 607  
 608      $strftimerecent = get_string('strftimerecent');
 609  
 610      $managerfactory = mod_forum\local\container::get_manager_factory();
 611      $entityfactory = mod_forum\local\container::get_entity_factory();
 612  
 613      $discussions = [];
 614      $capmanagers = [];
 615      $printposts = [];
 616      foreach ($posts as $post) {
 617          if (!isset($modinfo->instances['forum'][$post->forum])) {
 618              // not visible
 619              continue;
 620          }
 621          $cm = $modinfo->instances['forum'][$post->forum];
 622          if (!$cm->uservisible) {
 623              continue;
 624          }
 625  
 626          // Get the discussion. Cache if not yet available.
 627          if (!isset($discussions[$post->discussion])) {
 628              // Build the discussion record object from the post data.
 629              $discussionrecord = (object)[
 630                  'id' => $post->discussion,
 631                  'course' => $post->course,
 632                  'forum' => $post->forum,
 633                  'name' => $post->discussionname,
 634                  'firstpost' => $post->firstpost,
 635                  'userid' => $post->discussionstarter,
 636                  'groupid' => $post->groupid,
 637                  'assessed' => $post->discussionassessed,
 638                  'timemodified' => $post->timemodified,
 639                  'usermodified' => $post->usermodified,
 640                  'timestart' => $post->timestart,
 641                  'timeend' => $post->timeend,
 642                  'pinned' => $post->pinned,
 643                  'timelocked' => $post->timelocked
 644              ];
 645              // Build the discussion entity from the factory and cache it.
 646              $discussions[$post->discussion] = $entityfactory->get_discussion_from_stdclass($discussionrecord);
 647          }
 648          $discussionentity = $discussions[$post->discussion];
 649  
 650          // Get the capability manager. Cache if not yet available.
 651          if (!isset($capmanagers[$post->forum])) {
 652              $context = context_module::instance($cm->id);
 653              $coursemodule = $cm->get_course_module_record();
 654              // Build the forum record object from the post data.
 655              $forumrecord = (object)[
 656                  'id' => $post->forum,
 657                  'course' => $post->course,
 658                  'type' => $post->forumtype,
 659                  'name' => $post->forumname,
 660                  'intro' => $post->intro,
 661                  'introformat' => $post->introformat,
 662                  'duedate' => $post->duedate,
 663                  'cutoffdate' => $post->cutoffdate,
 664                  'assessed' => $post->forumassessed,
 665                  'assesstimestart' => $post->assesstimestart,
 666                  'assesstimefinish' => $post->assesstimefinish,
 667                  'scale' => $post->scale,
 668                  'grade_forum' => $post->grade_forum,
 669                  'maxbytes' => $post->maxbytes,
 670                  'maxattachments' => $post->maxattachments,
 671                  'forcesubscribe' => $post->forcesubscribe,
 672                  'trackingtype' => $post->trackingtype,
 673                  'rsstype' => $post->rsstype,
 674                  'rssarticles' => $post->rssarticles,
 675                  'timemodified' => $post->timemodified,
 676                  'warnafter' => $post->warnafter,
 677                  'blockafter' => $post->blockafter,
 678                  'blockperiod' => $post->blockperiod,
 679                  'completiondiscussions' => $post->completiondiscussions,
 680                  'completionreplies' => $post->completionreplies,
 681                  'completionposts' => $post->completionposts,
 682                  'displaywordcount' => $post->displaywordcount,
 683                  'lockdiscussionafter' => $post->lockdiscussionafter,
 684                  'grade_forum_notify' => $post->grade_forum_notify
 685              ];
 686              // Build the forum entity from the factory.
 687              $forumentity = $entityfactory->get_forum_from_stdclass($forumrecord, $context, $coursemodule, $course);
 688              // Get the capability manager of this forum and cache it.
 689              $capmanagers[$post->forum] = $managerfactory->get_capability_manager($forumentity);
 690          }
 691          $capabilitymanager = $capmanagers[$post->forum];
 692  
 693          // Get the post entity.
 694          $postentity = $entityfactory->get_post_from_stdclass($post);
 695  
 696          // Check if the user can view the post.
 697          if ($capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) {
 698              $printposts[] = $post;
 699          }
 700      }
 701      unset($posts);
 702  
 703      if (!$printposts) {
 704          return false;
 705      }
 706  
 707      echo $OUTPUT->heading(get_string('newforumposts', 'forum') . ':', 6);
 708      $list = html_writer::start_tag('ul', ['class' => 'unlist']);
 709  
 710      foreach ($printposts as $post) {
 711          $subjectclass = empty($post->parent) ? ' bold' : '';
 712          $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
 713  
 714          $list .= html_writer::start_tag('li');
 715          $list .= html_writer::start_div('head');
 716          $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date');
 717          if (!$authorhidden) {
 718              $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
 719          }
 720          $list .= html_writer::end_div(); // Head.
 721  
 722          $list .= html_writer::start_div('info' . $subjectclass);
 723          $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
 724          if (!empty($post->parent)) {
 725              $discussionurl->param('parent', $post->parent);
 726              $discussionurl->set_anchor('p'. $post->id);
 727          }
 728          $post->subject = break_up_long_words(format_string($post->subject, true));
 729          $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']);
 730          $list .= html_writer::end_div(); // Info.
 731          $list .= html_writer::end_tag('li');
 732      }
 733  
 734      $list .= html_writer::end_tag('ul');
 735      echo $list;
 736  
 737      return true;
 738  }
 739  
 740  /**
 741   * Update activity grades.
 742   *
 743   * @param object $forum
 744   * @param int $userid specific user only, 0 means all
 745   */
 746  function forum_update_grades($forum, $userid = 0): void {
 747      global $CFG, $DB;
 748      require_once($CFG->libdir.'/gradelib.php');
 749  
 750      $ratings = null;
 751      if ($forum->assessed) {
 752          require_once($CFG->dirroot.'/rating/lib.php');
 753  
 754          $cm = get_coursemodule_from_instance('forum', $forum->id);
 755  
 756          $rm = new rating_manager();
 757          $ratings = $rm->get_user_grades((object) [
 758              'component' => 'mod_forum',
 759              'ratingarea' => 'post',
 760              'contextid' => \context_module::instance($cm->id)->id,
 761  
 762              'modulename' => 'forum',
 763              'moduleid  ' => $forum->id,
 764              'userid' => $userid,
 765              'aggregationmethod' => $forum->assessed,
 766              'scaleid' => $forum->scale,
 767              'itemtable' => 'forum_posts',
 768              'itemtableusercolumn' => 'userid',
 769          ]);
 770      }
 771  
 772      $forumgrades = null;
 773      if ($forum->grade_forum) {
 774          $sql = <<<EOF
 775  SELECT
 776      g.userid,
 777      0 as datesubmitted,
 778      g.grade as rawgrade,
 779      g.timemodified as dategraded
 780    FROM {forum} f
 781    JOIN {forum_grades} g ON g.forum = f.id
 782   WHERE f.id = :forumid
 783  EOF;
 784  
 785          $params = [
 786              'forumid' => $forum->id,
 787          ];
 788  
 789          if ($userid) {
 790              $sql .= " AND g.userid = :userid";
 791              $params['userid'] = $userid;
 792          }
 793  
 794          $forumgrades = [];
 795          if ($grades = $DB->get_recordset_sql($sql, $params)) {
 796              foreach ($grades as $userid => $grade) {
 797                  if ($grade->rawgrade != -1) {
 798                      $forumgrades[$userid] = $grade;
 799                  }
 800              }
 801              $grades->close();
 802          }
 803      }
 804  
 805      forum_grade_item_update($forum, $ratings, $forumgrades);
 806  }
 807  
 808  /**
 809   * Create/update grade items for given forum.
 810   *
 811   * @param stdClass $forum Forum object with extra cmidnumber
 812   * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
 813   */
 814  function forum_grade_item_update($forum, $ratings = null, $forumgrades = null): void {
 815      global $CFG;
 816      require_once("{$CFG->libdir}/gradelib.php");
 817  
 818      // Update the rating.
 819      $item = [
 820          'itemname' => get_string('gradeitemnameforrating', 'forum', $forum),
 821          'idnumber' => $forum->cmidnumber,
 822      ];
 823  
 824      if (!$forum->assessed || $forum->scale == 0) {
 825          $item['gradetype'] = GRADE_TYPE_NONE;
 826      } else if ($forum->scale > 0) {
 827          $item['gradetype'] = GRADE_TYPE_VALUE;
 828          $item['grademax']  = $forum->scale;
 829          $item['grademin']  = 0;
 830      } else if ($forum->scale < 0) {
 831          $item['gradetype'] = GRADE_TYPE_SCALE;
 832          $item['scaleid']   = -$forum->scale;
 833      }
 834  
 835      if ($ratings === 'reset') {
 836          $item['reset'] = true;
 837          $ratings = null;
 838      }
 839      // Itemnumber 0 is the rating.
 840      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $ratings, $item);
 841  
 842      // Whole forum grade.
 843      $item = [
 844          'itemname' => get_string('gradeitemnameforwholeforum', 'forum', $forum),
 845          // Note: We do not need to store the idnumber here.
 846      ];
 847  
 848      if (!$forum->grade_forum) {
 849          $item['gradetype'] = GRADE_TYPE_NONE;
 850      } else if ($forum->grade_forum > 0) {
 851          $item['gradetype'] = GRADE_TYPE_VALUE;
 852          $item['grademax'] = $forum->grade_forum;
 853          $item['grademin'] = 0;
 854      } else if ($forum->grade_forum < 0) {
 855          $item['gradetype'] = GRADE_TYPE_SCALE;
 856          $item['scaleid'] = $forum->grade_forum * -1;
 857      }
 858  
 859      if ($forumgrades === 'reset') {
 860          $item['reset'] = true;
 861          $forumgrades = null;
 862      }
 863      // Itemnumber 1 is the whole forum grade.
 864      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, $forumgrades, $item);
 865  }
 866  
 867  /**
 868   * Delete grade item for given forum.
 869   *
 870   * @param stdClass $forum Forum object
 871   */
 872  function forum_grade_item_delete($forum) {
 873      global $CFG;
 874      require_once($CFG->libdir.'/gradelib.php');
 875  
 876      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, null, ['deleted' => 1]);
 877      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, null, ['deleted' => 1]);
 878  }
 879  
 880  /**
 881   * Checks if scale is being used by any instance of forum.
 882   *
 883   * This is used to find out if scale used anywhere.
 884   *
 885   * @param $scaleid int
 886   * @return boolean True if the scale is used by any forum
 887   */
 888  function forum_scale_used_anywhere(int $scaleid): bool {
 889      global $DB;
 890  
 891      if (empty($scaleid)) {
 892          return false;
 893      }
 894  
 895      return $DB->record_exists_select('forum', "scale = ? and assessed > 0", [$scaleid * -1]);
 896  }
 897  
 898  // SQL FUNCTIONS ///////////////////////////////////////////////////////////
 899  
 900  /**
 901   * Gets a post with all info ready for forum_print_post
 902   * Most of these joins are just to get the forum id
 903   *
 904   * @global object
 905   * @global object
 906   * @param int $postid
 907   * @return mixed array of posts or false
 908   */
 909  function forum_get_post_full($postid) {
 910      global $CFG, $DB;
 911  
 912      $userfieldsapi = \core_user\fields::for_name();
 913      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 914      return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
 915                               FROM {forum_posts} p
 916                                    JOIN {forum_discussions} d ON p.discussion = d.id
 917                                    LEFT JOIN {user} u ON p.userid = u.id
 918                              WHERE p.id = ?", array($postid));
 919  }
 920  
 921  /**
 922   * Gets all posts in discussion including top parent.
 923   *
 924   * @param   int     $discussionid   The Discussion to fetch.
 925   * @param   string  $sort           The sorting to apply.
 926   * @param   bool    $tracking       Whether the user tracks this forum.
 927   * @return  array                   The posts in the discussion.
 928   */
 929  function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) {
 930      global $CFG, $DB, $USER;
 931  
 932      $tr_sel  = "";
 933      $tr_join = "";
 934      $params = array();
 935  
 936      if ($tracking) {
 937          $tr_sel  = ", fr.id AS postread";
 938          $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
 939          $params[] = $USER->id;
 940      }
 941  
 942      $userfieldsapi = \core_user\fields::for_name();
 943      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 944      $params[] = $discussionid;
 945      if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
 946                                       FROM {forum_posts} p
 947                                            LEFT JOIN {user} u ON p.userid = u.id
 948                                            $tr_join
 949                                      WHERE p.discussion = ?
 950                                   ORDER BY $sort", $params)) {
 951          return array();
 952      }
 953  
 954      foreach ($posts as $pid=>$p) {
 955          if ($tracking) {
 956              if (forum_tp_is_post_old($p)) {
 957                   $posts[$pid]->postread = true;
 958              }
 959          }
 960          if (!$p->parent) {
 961              continue;
 962          }
 963          if (!isset($posts[$p->parent])) {
 964              continue; // parent does not exist??
 965          }
 966          if (!isset($posts[$p->parent]->children)) {
 967              $posts[$p->parent]->children = array();
 968          }
 969          $posts[$p->parent]->children[$pid] =& $posts[$pid];
 970      }
 971  
 972      // Start with the last child of the first post.
 973      $post = &$posts[reset($posts)->id];
 974  
 975      $lastpost = false;
 976      while (!$lastpost) {
 977          if (!isset($post->children)) {
 978              $post->lastpost = true;
 979              $lastpost = true;
 980          } else {
 981               // Go to the last child of this post.
 982              $post = &$posts[end($post->children)->id];
 983          }
 984      }
 985  
 986      return $posts;
 987  }
 988  
 989  /**
 990   * An array of forum objects that the user is allowed to read/search through.
 991   *
 992   * @global object
 993   * @global object
 994   * @global object
 995   * @param int $userid
 996   * @param int $courseid if 0, we look for forums throughout the whole site.
 997   * @return array of forum objects, or false if no matches
 998   *         Forum objects have the following attributes:
 999   *         id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1000   *         viewhiddentimedposts
1001   */
1002  function forum_get_readable_forums($userid, $courseid=0) {
1003  
1004      global $CFG, $DB, $USER;
1005      require_once($CFG->dirroot.'/course/lib.php');
1006  
1007      if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1008          print_error('notinstalled', 'forum');
1009      }
1010  
1011      if ($courseid) {
1012          $courses = $DB->get_records('course', array('id' => $courseid));
1013      } else {
1014          // If no course is specified, then the user can see SITE + his courses.
1015          $courses1 = $DB->get_records('course', array('id' => SITEID));
1016          $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1017          $courses = array_merge($courses1, $courses2);
1018      }
1019      if (!$courses) {
1020          return array();
1021      }
1022  
1023      $readableforums = array();
1024  
1025      foreach ($courses as $course) {
1026  
1027          $modinfo = get_fast_modinfo($course);
1028  
1029          if (empty($modinfo->instances['forum'])) {
1030              // hmm, no forums?
1031              continue;
1032          }
1033  
1034          $courseforums = $DB->get_records('forum', array('course' => $course->id));
1035  
1036          foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1037              if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1038                  continue;
1039              }
1040              $context = context_module::instance($cm->id);
1041              $forum = $courseforums[$forumid];
1042              $forum->context = $context;
1043              $forum->cm = $cm;
1044  
1045              if (!has_capability('mod/forum:viewdiscussion', $context)) {
1046                  continue;
1047              }
1048  
1049           /// group access
1050              if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1051  
1052                  $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1053                  $forum->onlygroups[] = -1;
1054              }
1055  
1056          /// hidden timed discussions
1057              $forum->viewhiddentimedposts = true;
1058              if (!empty($CFG->forum_enabletimedposts)) {
1059                  if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1060                      $forum->viewhiddentimedposts = false;
1061                  }
1062              }
1063  
1064          /// qanda access
1065              if ($forum->type == 'qanda'
1066                      && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1067  
1068                  // We need to check whether the user has posted in the qanda forum.
1069                  $forum->onlydiscussions = array();  // Holds discussion ids for the discussions
1070                                                      // the user is allowed to see in this forum.
1071                  if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1072                      foreach ($discussionspostedin as $d) {
1073                          $forum->onlydiscussions[] = $d->id;
1074                      }
1075                  }
1076              }
1077  
1078              $readableforums[$forum->id] = $forum;
1079          }
1080  
1081          unset($modinfo);
1082  
1083      } // End foreach $courses
1084  
1085      return $readableforums;
1086  }
1087  
1088  /**
1089   * Returns a list of posts found using an array of search terms.
1090   *
1091   * @global object
1092   * @global object
1093   * @global object
1094   * @param array $searchterms array of search terms, e.g. word +word -word
1095   * @param int $courseid if 0, we search through the whole site
1096   * @param int $limitfrom
1097   * @param int $limitnum
1098   * @param int &$totalcount
1099   * @param string $extrasql
1100   * @return array|bool Array of posts found or false
1101   */
1102  function forum_search_posts($searchterms, $courseid, $limitfrom, $limitnum,
1103                              &$totalcount, $extrasql='') {
1104      global $CFG, $DB, $USER;
1105      require_once($CFG->libdir.'/searchlib.php');
1106  
1107      $forums = forum_get_readable_forums($USER->id, $courseid);
1108  
1109      if (count($forums) == 0) {
1110          $totalcount = 0;
1111          return false;
1112      }
1113  
1114      $now = floor(time() / 60) * 60; // DB Cache Friendly.
1115  
1116      $fullaccess = array();
1117      $where = array();
1118      $params = array();
1119  
1120      foreach ($forums as $forumid => $forum) {
1121          $select = array();
1122  
1123          if (!$forum->viewhiddentimedposts) {
1124              $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1125              $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1126          }
1127  
1128          $cm = $forum->cm;
1129          $context = $forum->context;
1130  
1131          if ($forum->type == 'qanda'
1132              && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1133              if (!empty($forum->onlydiscussions)) {
1134                  list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
1135                  $params = array_merge($params, $discussionid_params);
1136                  $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1137              } else {
1138                  $select[] = "p.parent = 0";
1139              }
1140          }
1141  
1142          if (!empty($forum->onlygroups)) {
1143              list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
1144              $params = array_merge($params, $groupid_params);
1145              $select[] = "d.groupid $groupid_sql";
1146          }
1147  
1148          if ($select) {
1149              $selects = implode(" AND ", $select);
1150              $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1151              $params['forum'.$forumid] = $forumid;
1152          } else {
1153              $fullaccess[] = $forumid;
1154          }
1155      }
1156  
1157      if ($fullaccess) {
1158          list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
1159          $params = array_merge($params, $fullid_params);
1160          $where[] = "(d.forum $fullid_sql)";
1161      }
1162  
1163      $favjoin = "";
1164      if (in_array('starredonly:on', $searchterms)) {
1165          $usercontext = context_user::instance($USER->id);
1166          $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1167          list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions',
1168              "favourited", "d.id");
1169  
1170          $searchterms = array_values(array_diff($searchterms, array('starredonly:on')));
1171          $params = array_merge($params, $favparams);
1172          $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0";
1173      }
1174  
1175      $selectdiscussion = "(".implode(" OR ", $where).")";
1176  
1177      $messagesearch = '';
1178      $searchstring = '';
1179  
1180      // Need to concat these back together for parser to work.
1181      foreach($searchterms as $searchterm){
1182          if ($searchstring != '') {
1183              $searchstring .= ' ';
1184          }
1185          $searchstring .= $searchterm;
1186      }
1187  
1188      // We need to allow quoted strings for the search. The quotes *should* be stripped
1189      // by the parser, but this should be examined carefully for security implications.
1190      $searchstring = str_replace("\\\"","\"",$searchstring);
1191      $parser = new search_parser();
1192      $lexer = new search_lexer($parser);
1193  
1194      if ($lexer->parse($searchstring)) {
1195          $parsearray = $parser->get_parsed_array();
1196  
1197          $tagjoins = '';
1198          $tagfields = [];
1199          $tagfieldcount = 0;
1200          if ($parsearray) {
1201              foreach ($parsearray as $token) {
1202                  if ($token->getType() == TOKEN_TAGS) {
1203                      for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
1204                          // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1205                          if ($tagfieldcount > 10) {
1206                              continue;
1207                          }
1208                          $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
1209                                          ON p.id = ti_$tagfieldcount.itemid
1210                                              AND ti_$tagfieldcount.component = 'mod_forum'
1211                                              AND ti_$tagfieldcount.itemtype = 'forum_posts'";
1212                          $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1213                          $tagfields[] = "t_$tagfieldcount.rawname";
1214                          $tagfieldcount++;
1215                      }
1216                  }
1217              }
1218              list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1219                  'p.userid', 'u.id', 'u.firstname',
1220                  'u.lastname', 'p.modified', 'd.forum',
1221                  $tagfields);
1222  
1223              $params = ($msparams ? array_merge($params, $msparams) : $params);
1224          }
1225      }
1226  
1227      $fromsql = "{forum_posts} p
1228                    INNER JOIN {forum_discussions} d ON d.id = p.discussion
1229                    INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin";
1230  
1231      $selectsql = ($messagesearch ? $messagesearch . " AND " : "").
1232                  " p.discussion = d.id
1233                 AND p.userid = u.id
1234                 AND $selectdiscussion
1235                     $extrasql";
1236  
1237      $countsql = "SELECT COUNT(*)
1238                     FROM $fromsql
1239                    WHERE $selectsql";
1240  
1241      $userfieldsapi = \core_user\fields::for_name();
1242      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1243      $searchsql = "SELECT p.*,
1244                           d.forum,
1245                           $allnames,
1246                           u.email,
1247                           u.picture,
1248                           u.imagealt
1249                      FROM $fromsql
1250                     WHERE $selectsql
1251                  ORDER BY p.modified DESC";
1252  
1253      $totalcount = $DB->count_records_sql($countsql, $params);
1254  
1255      return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
1256  }
1257  
1258  /**
1259   * Get all the posts for a user in a forum suitable for forum_print_post
1260   *
1261   * @global object
1262   * @global object
1263   * @uses CONTEXT_MODULE
1264   * @return array
1265   */
1266  function forum_get_user_posts($forumid, $userid) {
1267      global $CFG, $DB;
1268  
1269      $timedsql = "";
1270      $params = array($forumid, $userid);
1271  
1272      if (!empty($CFG->forum_enabletimedposts)) {
1273          $cm = get_coursemodule_from_instance('forum', $forumid);
1274          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1275              $now = time();
1276              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1277              $params[] = $now;
1278              $params[] = $now;
1279          }
1280      }
1281  
1282      $userfieldsapi = \core_user\fields::for_name();
1283      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1284      return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1285                                FROM {forum} f
1286                                     JOIN {forum_discussions} d ON d.forum = f.id
1287                                     JOIN {forum_posts} p       ON p.discussion = d.id
1288                                     JOIN {user} u              ON u.id = p.userid
1289                               WHERE f.id = ?
1290                                     AND p.userid = ?
1291                                     $timedsql
1292                            ORDER BY p.modified ASC", $params);
1293  }
1294  
1295  /**
1296   * Get all the discussions user participated in
1297   *
1298   * @global object
1299   * @global object
1300   * @uses CONTEXT_MODULE
1301   * @param int $forumid
1302   * @param int $userid
1303   * @return array Array or false
1304   */
1305  function forum_get_user_involved_discussions($forumid, $userid) {
1306      global $CFG, $DB;
1307  
1308      $timedsql = "";
1309      $params = array($forumid, $userid);
1310      if (!empty($CFG->forum_enabletimedposts)) {
1311          $cm = get_coursemodule_from_instance('forum', $forumid);
1312          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1313              $now = time();
1314              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1315              $params[] = $now;
1316              $params[] = $now;
1317          }
1318      }
1319  
1320      return $DB->get_records_sql("SELECT DISTINCT d.*
1321                                FROM {forum} f
1322                                     JOIN {forum_discussions} d ON d.forum = f.id
1323                                     JOIN {forum_posts} p       ON p.discussion = d.id
1324                               WHERE f.id = ?
1325                                     AND p.userid = ?
1326                                     $timedsql", $params);
1327  }
1328  
1329  /**
1330   * Get all the posts for a user in a forum suitable for forum_print_post
1331   *
1332   * @global object
1333   * @global object
1334   * @param int $forumid
1335   * @param int $userid
1336   * @return array of counts or false
1337   */
1338  function forum_count_user_posts($forumid, $userid) {
1339      global $CFG, $DB;
1340  
1341      $timedsql = "";
1342      $params = array($forumid, $userid);
1343      if (!empty($CFG->forum_enabletimedposts)) {
1344          $cm = get_coursemodule_from_instance('forum', $forumid);
1345          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1346              $now = time();
1347              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1348              $params[] = $now;
1349              $params[] = $now;
1350          }
1351      }
1352  
1353      return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1354                               FROM {forum} f
1355                                    JOIN {forum_discussions} d ON d.forum = f.id
1356                                    JOIN {forum_posts} p       ON p.discussion = d.id
1357                                    JOIN {user} u              ON u.id = p.userid
1358                              WHERE f.id = ?
1359                                    AND p.userid = ?
1360                                    $timedsql", $params);
1361  }
1362  
1363  /**
1364   * Given a log entry, return the forum post details for it.
1365   *
1366   * @global object
1367   * @global object
1368   * @param object $log
1369   * @return array|null
1370   */
1371  function forum_get_post_from_log($log) {
1372      global $CFG, $DB;
1373  
1374      $userfieldsapi = \core_user\fields::for_name();
1375      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1376      if ($log->action == "add post") {
1377  
1378          return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1379                                   FROM {forum_discussions} d,
1380                                        {forum_posts} p,
1381                                        {forum} f,
1382                                        {user} u
1383                                  WHERE p.id = ?
1384                                    AND d.id = p.discussion
1385                                    AND p.userid = u.id
1386                                    AND u.deleted <> '1'
1387                                    AND f.id = d.forum", array($log->info));
1388  
1389  
1390      } else if ($log->action == "add discussion") {
1391  
1392          return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1393                                   FROM {forum_discussions} d,
1394                                        {forum_posts} p,
1395                                        {forum} f,
1396                                        {user} u
1397                                  WHERE d.id = ?
1398                                    AND d.firstpost = p.id
1399                                    AND p.userid = u.id
1400                                    AND u.deleted <> '1'
1401                                    AND f.id = d.forum", array($log->info));
1402      }
1403      return NULL;
1404  }
1405  
1406  /**
1407   * Given a discussion id, return the first post from the discussion
1408   *
1409   * @global object
1410   * @global object
1411   * @param int $dicsussionid
1412   * @return array
1413   */
1414  function forum_get_firstpost_from_discussion($discussionid) {
1415      global $CFG, $DB;
1416  
1417      return $DB->get_record_sql("SELECT p.*
1418                               FROM {forum_discussions} d,
1419                                    {forum_posts} p
1420                              WHERE d.id = ?
1421                                AND d.firstpost = p.id ", array($discussionid));
1422  }
1423  
1424  /**
1425   * Returns an array of counts of replies to each discussion
1426   *
1427   * @param   int     $forumid
1428   * @param   string  $forumsort
1429   * @param   int     $limit
1430   * @param   int     $page
1431   * @param   int     $perpage
1432   * @param   boolean $canseeprivatereplies   Whether the current user can see private replies.
1433   * @return  array
1434   */
1435  function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0,
1436                                          $canseeprivatereplies = false) {
1437      global $CFG, $DB, $USER;
1438  
1439      if ($limit > 0) {
1440          $limitfrom = 0;
1441          $limitnum  = $limit;
1442      } else if ($page != -1) {
1443          $limitfrom = $page*$perpage;
1444          $limitnum  = $perpage;
1445      } else {
1446          $limitfrom = 0;
1447          $limitnum  = 0;
1448      }
1449  
1450      if ($forumsort == "") {
1451          $orderby = "";
1452          $groupby = "";
1453  
1454      } else {
1455          $orderby = "ORDER BY $forumsort";
1456          $groupby = ", ".strtolower($forumsort);
1457          $groupby = str_replace('desc', '', $groupby);
1458          $groupby = str_replace('asc', '', $groupby);
1459      }
1460  
1461      $params = ['forumid' => $forumid];
1462  
1463      if (!$canseeprivatereplies) {
1464          $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)';
1465          $params['currentuser1'] = $USER->id;
1466          $params['currentuser2'] = $USER->id;
1467      } else {
1468          $privatewhere = '';
1469      }
1470  
1471      if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1472          $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
1473                    FROM {forum_posts} p
1474                         JOIN {forum_discussions} d ON p.discussion = d.id
1475                   WHERE p.parent > 0 AND d.forum = :forumid
1476                         $privatewhere
1477                GROUP BY p.discussion";
1478          return $DB->get_records_sql($sql, $params);
1479  
1480      } else {
1481          $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
1482                    FROM {forum_posts} p
1483                         JOIN {forum_discussions} d ON p.discussion = d.id
1484                   WHERE d.forum = :forumid
1485                         $privatewhere
1486                GROUP BY p.discussion $groupby $orderby";
1487          return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1488      }
1489  }
1490  
1491  /**
1492   * @global object
1493   * @global object
1494   * @global object
1495   * @staticvar array $cache
1496   * @param object $forum
1497   * @param object $cm
1498   * @param object $course
1499   * @return mixed
1500   */
1501  function forum_count_discussions($forum, $cm, $course) {
1502      global $CFG, $DB, $USER;
1503  
1504      static $cache = array();
1505  
1506      $now = floor(time() / 60) * 60; // DB Cache Friendly.
1507  
1508      $params = array($course->id);
1509  
1510      if (!isset($cache[$course->id])) {
1511          if (!empty($CFG->forum_enabletimedposts)) {
1512              $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1513              $params[] = $now;
1514              $params[] = $now;
1515          } else {
1516              $timedsql = "";
1517          }
1518  
1519          $sql = "SELECT f.id, COUNT(d.id) as dcount
1520                    FROM {forum} f
1521                         JOIN {forum_discussions} d ON d.forum = f.id
1522                   WHERE f.course = ?
1523                         $timedsql
1524                GROUP BY f.id";
1525  
1526          if ($counts = $DB->get_records_sql($sql, $params)) {
1527              foreach ($counts as $count) {
1528                  $counts[$count->id] = $count->dcount;
1529              }
1530              $cache[$course->id] = $counts;
1531          } else {
1532              $cache[$course->id] = array();
1533          }
1534      }
1535  
1536      if (empty($cache[$course->id][$forum->id])) {
1537          return 0;
1538      }
1539  
1540      $groupmode = groups_get_activity_groupmode($cm, $course);
1541  
1542      if ($groupmode != SEPARATEGROUPS) {
1543          return $cache[$course->id][$forum->id];
1544      }
1545  
1546      if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
1547          return $cache[$course->id][$forum->id];
1548      }
1549  
1550      require_once($CFG->dirroot.'/course/lib.php');
1551  
1552      $modinfo = get_fast_modinfo($course);
1553  
1554      $mygroups = $modinfo->get_groups($cm->groupingid);
1555  
1556      // add all groups posts
1557      $mygroups[-1] = -1;
1558  
1559      list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1560      $params[] = $forum->id;
1561  
1562      if (!empty($CFG->forum_enabletimedposts)) {
1563          $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
1564          $params[] = $now;
1565          $params[] = $now;
1566      } else {
1567          $timedsql = "";
1568      }
1569  
1570      $sql = "SELECT COUNT(d.id)
1571                FROM {forum_discussions} d
1572               WHERE d.groupid $mygroups_sql AND d.forum = ?
1573                     $timedsql";
1574  
1575      return $DB->get_field_sql($sql, $params);
1576  }
1577  
1578  /**
1579   * Get all discussions in a forum
1580   *
1581   * @global object
1582   * @global object
1583   * @global object
1584   * @uses CONTEXT_MODULE
1585   * @uses VISIBLEGROUPS
1586   * @param object $cm
1587   * @param string $forumsort
1588   * @param bool $fullpost
1589   * @param int $unused
1590   * @param int $limit
1591   * @param bool $userlastmodified
1592   * @param int $page
1593   * @param int $perpage
1594   * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1595   *                     Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
1596   * @param int $updatedsince retrieve only discussions updated since the given time
1597   * @return array
1598   */
1599  function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
1600                                  $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
1601                                  $updatedsince = 0) {
1602      global $CFG, $DB, $USER;
1603  
1604      $timelimit = '';
1605  
1606      $now = floor(time() / 60) * 60;
1607      $params = array($cm->instance);
1608  
1609      $modcontext = context_module::instance($cm->id);
1610  
1611      if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1612          return array();
1613      }
1614  
1615      if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
1616  
1617          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1618              $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1619              $params[] = $now;
1620              $params[] = $now;
1621              if (isloggedin()) {
1622                  $timelimit .= " OR d.userid = ?";
1623                  $params[] = $USER->id;
1624              }
1625              $timelimit .= ")";
1626          }
1627      }
1628  
1629      if ($limit > 0) {
1630          $limitfrom = 0;
1631          $limitnum  = $limit;
1632      } else if ($page != -1) {
1633          $limitfrom = $page*$perpage;
1634          $limitnum  = $perpage;
1635      } else {
1636          $limitfrom = 0;
1637          $limitnum  = 0;
1638      }
1639  
1640      $groupmode    = groups_get_activity_groupmode($cm);
1641  
1642      if ($groupmode) {
1643  
1644          if (empty($modcontext)) {
1645              $modcontext = context_module::instance($cm->id);
1646          }
1647  
1648          // Special case, we received a groupid to override currentgroup.
1649          if ($groupid > 0) {
1650              $course = get_course($cm->course);
1651              if (!groups_group_visible($groupid, $course, $cm)) {
1652                  // User doesn't belong to this group, return nothing.
1653                  return array();
1654              }
1655              $currentgroup = $groupid;
1656          } else if ($groupid === -1) {
1657              $currentgroup = groups_get_activity_group($cm);
1658          } else {
1659              // Get discussions for all groups current user can see.
1660              $currentgroup = null;
1661          }
1662  
1663          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1664              if ($currentgroup) {
1665                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1666                  $params[] = $currentgroup;
1667              } else {
1668                  $groupselect = "";
1669              }
1670  
1671          } else {
1672              // Separate groups.
1673  
1674              // Get discussions for all groups current user can see.
1675              if ($currentgroup === null) {
1676                  $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
1677                  if (empty($mygroups)) {
1678                       $groupselect = "AND d.groupid = -1";
1679                  } else {
1680                      list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1681                      $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1682                      $params = array_merge($params, $inparamsgroups);
1683                  }
1684              } else if ($currentgroup) {
1685                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1686                  $params[] = $currentgroup;
1687              } else {
1688                  $groupselect = "AND d.groupid = -1";
1689              }
1690          }
1691      } else {
1692          $groupselect = "";
1693      }
1694      if (empty($forumsort)) {
1695          $forumsort = forum_get_default_sort_order();
1696      }
1697      if (empty($fullpost)) {
1698          $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
1699      } else {
1700          $postdata = "p.*";
1701      }
1702  
1703      $userfieldsapi = \core_user\fields::for_name();
1704  
1705      if (empty($userlastmodified)) {  // We don't need to know this
1706          $umfields = "";
1707          $umtable  = "";
1708      } else {
1709          $umfields = $userfieldsapi->get_sql('um', false, 'um')->selects . ', um.email AS umemail, um.picture AS umpicture,
1710                          um.imagealt AS umimagealt';
1711          $umtable  = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
1712      }
1713  
1714      $updatedsincesql = '';
1715      if (!empty($updatedsince)) {
1716          $updatedsincesql = 'AND d.timemodified > ?';
1717          $params[] = $updatedsince;
1718      }
1719  
1720      $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
1721      " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked";
1722  
1723      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1724      $sql = "SELECT $postdata, $discussionfields,
1725                     $allnames, u.email, u.picture, u.imagealt, u.deleted AS userdeleted $umfields
1726                FROM {forum_discussions} d
1727                     JOIN {forum_posts} p ON p.discussion = d.id
1728                     JOIN {user} u ON p.userid = u.id
1729                     $umtable
1730               WHERE d.forum = ? AND p.parent = 0
1731                     $timelimit $groupselect $updatedsincesql
1732            ORDER BY $forumsort, d.id DESC";
1733  
1734      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1735  }
1736  
1737  /**
1738   * Gets the neighbours (previous and next) of a discussion.
1739   *
1740   * The calculation is based on the timemodified when time modified or time created is identical
1741   * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
1742   *
1743   * For blog-style forums, the calculation is based on the original creation time of the
1744   * blog post.
1745   *
1746   * Please note that this does not check whether or not the discussion passed is accessible
1747   * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1748   * the returned neighbours are checked and are accessible to the current user.
1749   *
1750   * @param object $cm The CM record.
1751   * @param object $discussion The discussion record.
1752   * @param object $forum The forum instance record.
1753   * @return array That always contains the keys 'prev' and 'next'. When there is a result
1754   *               they contain the record with minimal information such as 'id' and 'name'.
1755   *               When the neighbour is not found the value is false.
1756   */
1757  function forum_get_discussion_neighbours($cm, $discussion, $forum) {
1758      global $CFG, $DB, $USER;
1759  
1760      if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
1761          throw new coding_exception('Discussion is not part of the same forum.');
1762      }
1763  
1764      $neighbours = array('prev' => false, 'next' => false);
1765      $now = floor(time() / 60) * 60;
1766      $params = array();
1767  
1768      $modcontext = context_module::instance($cm->id);
1769      $groupmode    = groups_get_activity_groupmode($cm);
1770      $currentgroup = groups_get_activity_group($cm);
1771  
1772      // Users must fulfill timed posts.
1773      $timelimit = '';
1774      if (!empty($CFG->forum_enabletimedposts)) {
1775          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1776              $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1777              $params['tltimestart'] = $now;
1778              $params['tltimeend'] = $now;
1779              if (isloggedin()) {
1780                  $timelimit .= ' OR d.userid = :tluserid';
1781                  $params['tluserid'] = $USER->id;
1782              }
1783              $timelimit .= ')';
1784          }
1785      }
1786  
1787      // Limiting to posts accessible according to groups.
1788      $groupselect = '';
1789      if ($groupmode) {
1790          if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
1791              if ($currentgroup) {
1792                  $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1793                  $params['groupid'] = $currentgroup;
1794              }
1795          } else {
1796              if ($currentgroup) {
1797                  $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1798                  $params['groupid'] = $currentgroup;
1799              } else {
1800                  $groupselect = 'AND d.groupid = -1';
1801              }
1802          }
1803      }
1804  
1805      $params['forumid'] = $cm->instance;
1806      $params['discid1'] = $discussion->id;
1807      $params['discid2'] = $discussion->id;
1808      $params['discid3'] = $discussion->id;
1809      $params['discid4'] = $discussion->id;
1810      $params['disctimecompare1'] = $discussion->timemodified;
1811      $params['disctimecompare2'] = $discussion->timemodified;
1812      $params['pinnedstate1'] = (int) $discussion->pinned;
1813      $params['pinnedstate2'] = (int) $discussion->pinned;
1814      $params['pinnedstate3'] = (int) $discussion->pinned;
1815      $params['pinnedstate4'] = (int) $discussion->pinned;
1816  
1817      $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1818                FROM {forum_discussions} d
1819                JOIN {forum_posts} p ON d.firstpost = p.id
1820               WHERE d.forum = :forumid
1821                 AND d.id <> :discid1
1822                     $timelimit
1823                     $groupselect";
1824      $comparefield = "d.timemodified";
1825      $comparevalue = ":disctimecompare1";
1826      $comparevalue2  = ":disctimecompare2";
1827      if (!empty($CFG->forum_enabletimedposts)) {
1828          // Here we need to take into account the release time (timestart)
1829          // if one is set, of the neighbouring posts and compare it to the
1830          // timestart or timemodified of *this* post depending on if the
1831          // release date of this post is in the future or not.
1832          // This stops discussions that appear later because of the
1833          // timestart value from being buried under discussions that were
1834          // made afterwards.
1835          $comparefield = "CASE WHEN d.timemodified < d.timestart
1836                                  THEN d.timestart ELSE d.timemodified END";
1837          if ($discussion->timemodified < $discussion->timestart) {
1838              // Normally we would just use the timemodified for sorting
1839              // discussion posts. However, when timed discussions are enabled,
1840              // then posts need to be sorted base on the later of timemodified
1841              // or the release date of the post (timestart).
1842              $params['disctimecompare1'] = $discussion->timestart;
1843              $params['disctimecompare2'] = $discussion->timestart;
1844          }
1845      }
1846      $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1847      $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
1848  
1849      if ($forum->type === 'blog') {
1850           $subselect = "SELECT pp.created
1851                     FROM {forum_discussions} dd
1852                     JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
1853  
1854           $subselectwhere1 = " WHERE dd.id = :discid3";
1855           $subselectwhere2 = " WHERE dd.id = :discid4";
1856  
1857           $comparefield = "p.created";
1858  
1859           $sub1 = $subselect.$subselectwhere1;
1860           $comparevalue = "($sub1)";
1861  
1862           $sub2 = $subselect.$subselectwhere2;
1863           $comparevalue2 = "($sub2)";
1864  
1865           $orderbydesc = "d.pinned, p.created DESC";
1866           $orderbyasc = "d.pinned, p.created ASC";
1867      }
1868  
1869      $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1870                           OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1871                           OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1872                     ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
1873  
1874      $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1875                           OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1876                           OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1877                     ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
1878  
1879      $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
1880      $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
1881      return $neighbours;
1882  }
1883  
1884  /**
1885   * Get the sql to use in the ORDER BY clause for forum discussions.
1886   *
1887   * This has the ordering take timed discussion windows into account.
1888   *
1889   * @param bool $desc True for DESC, False for ASC.
1890   * @param string $compare The field in the SQL to compare to normally sort by.
1891   * @param string $prefix The prefix being used for the discussion table.
1892   * @param bool $pinned sort pinned posts to the top
1893   * @return string
1894   */
1895  function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1896      global $CFG;
1897  
1898      if (!empty($prefix)) {
1899          $prefix .= '.';
1900      }
1901  
1902      $dir = $desc ? 'DESC' : 'ASC';
1903  
1904      if ($pinned == true) {
1905          $pinned = "{$prefix}pinned DESC,";
1906      } else {
1907          $pinned = '';
1908      }
1909  
1910      $sort = "{$prefix}timemodified";
1911      if (!empty($CFG->forum_enabletimedposts)) {
1912          $sort = "CASE WHEN {$compare} < {$prefix}timestart
1913                   THEN {$prefix}timestart
1914                   ELSE {$compare}
1915                   END";
1916      }
1917      return "$pinned $sort $dir";
1918  }
1919  
1920  /**
1921   *
1922   * @global object
1923   * @global object
1924   * @global object
1925   * @uses CONTEXT_MODULE
1926   * @uses VISIBLEGROUPS
1927   * @param object $cm
1928   * @return array
1929   */
1930  function forum_get_discussions_unread($cm) {
1931      global $CFG, $DB, $USER;
1932  
1933      $now = floor(time() / 60) * 60;
1934      $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
1935  
1936      $params = array();
1937      $groupmode    = groups_get_activity_groupmode($cm);
1938      $currentgroup = groups_get_activity_group($cm);
1939  
1940      if ($groupmode) {
1941          $modcontext = context_module::instance($cm->id);
1942  
1943          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1944              if ($currentgroup) {
1945                  $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1946                  $params['currentgroup'] = $currentgroup;
1947              } else {
1948                  $groupselect = "";
1949              }
1950  
1951          } else {
1952              //separate groups without access all
1953              if ($currentgroup) {
1954                  $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1955                  $params['currentgroup'] = $currentgroup;
1956              } else {
1957                  $groupselect = "AND d.groupid = -1";
1958              }
1959          }
1960      } else {
1961          $groupselect = "";
1962      }
1963  
1964      if (!empty($CFG->forum_enabletimedposts)) {
1965          $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
1966          $params['now1'] = $now;
1967          $params['now2'] = $now;
1968      } else {
1969          $timedsql = "";
1970      }
1971  
1972      $sql = "SELECT d.id, COUNT(p.id) AS unread
1973                FROM {forum_discussions} d
1974                     JOIN {forum_posts} p     ON p.discussion = d.id
1975                     LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
1976               WHERE d.forum = {$cm->instance}
1977                     AND p.modified >= :cutoffdate AND r.id is NULL
1978                     $groupselect
1979                     $timedsql
1980            GROUP BY d.id";
1981      $params['cutoffdate'] = $cutoffdate;
1982  
1983      if ($unreads = $DB->get_records_sql($sql, $params)) {
1984          foreach ($unreads as $unread) {
1985              $unreads[$unread->id] = $unread->unread;
1986          }
1987          return $unreads;
1988      } else {
1989          return array();
1990      }
1991  }
1992  
1993  /**
1994   * @global object
1995   * @global object
1996   * @global object
1997   * @uses CONEXT_MODULE
1998   * @uses VISIBLEGROUPS
1999   * @param object $cm
2000   * @return array
2001   */
2002  function forum_get_discussions_count($cm) {
2003      global $CFG, $DB, $USER;
2004  
2005      $now = floor(time() / 60) * 60;
2006      $params = array($cm->instance);
2007      $groupmode    = groups_get_activity_groupmode($cm);
2008      $currentgroup = groups_get_activity_group($cm);
2009  
2010      if ($groupmode) {
2011          $modcontext = context_module::instance($cm->id);
2012  
2013          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2014              if ($currentgroup) {
2015                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2016                  $params[] = $currentgroup;
2017              } else {
2018                  $groupselect = "";
2019              }
2020  
2021          } else {
2022              //seprate groups without access all
2023              if ($currentgroup) {
2024                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2025                  $params[] = $currentgroup;
2026              } else {
2027                  $groupselect = "AND d.groupid = -1";
2028              }
2029          }
2030      } else {
2031          $groupselect = "";
2032      }
2033  
2034      $timelimit = "";
2035  
2036      if (!empty($CFG->forum_enabletimedposts)) {
2037  
2038          $modcontext = context_module::instance($cm->id);
2039  
2040          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2041              $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2042              $params[] = $now;
2043              $params[] = $now;
2044              if (isloggedin()) {
2045                  $timelimit .= " OR d.userid = ?";
2046                  $params[] = $USER->id;
2047              }
2048              $timelimit .= ")";
2049          }
2050      }
2051  
2052      $sql = "SELECT COUNT(d.id)
2053                FROM {forum_discussions} d
2054                     JOIN {forum_posts} p ON p.discussion = d.id
2055               WHERE d.forum = ? AND p.parent = 0
2056                     $groupselect $timelimit";
2057  
2058      return $DB->get_field_sql($sql, $params);
2059  }
2060  
2061  
2062  // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2063  
2064  
2065  /**
2066   * @global object
2067   * @global object
2068   * @param int $courseid
2069   * @param string $type
2070   */
2071  function forum_get_course_forum($courseid, $type) {
2072  // How to set up special 1-per-course forums
2073      global $CFG, $DB, $OUTPUT, $USER;
2074  
2075      if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2076          // There should always only be ONE, but with the right combination of
2077          // errors there might be more.  In this case, just return the oldest one (lowest ID).
2078          foreach ($forums as $forum) {
2079              return $forum;   // ie the first one
2080          }
2081      }
2082  
2083      // Doesn't exist, so create one now.
2084      $forum = new stdClass();
2085      $forum->course = $courseid;
2086      $forum->type = "$type";
2087      if (!empty($USER->htmleditor)) {
2088          $forum->introformat = $USER->htmleditor;
2089      }
2090      switch ($forum->type) {
2091          case "news":
2092              $forum->name  = get_string("namenews", "forum");
2093              $forum->intro = get_string("intronews", "forum");
2094              $forum->introformat = FORMAT_HTML;
2095              $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2096              $forum->assessed = 0;
2097              if ($courseid == SITEID) {
2098                  $forum->name  = get_string("sitenews");
2099                  $forum->forcesubscribe = 0;
2100              }
2101              break;
2102          case "social":
2103              $forum->name  = get_string("namesocial", "forum");
2104              $forum->intro = get_string("introsocial", "forum");
2105              $forum->introformat = FORMAT_HTML;
2106              $forum->assessed = 0;
2107              $forum->forcesubscribe = 0;
2108              break;
2109          case "blog":
2110              $forum->name = get_string('blogforum', 'forum');
2111              $forum->intro = get_string('introblog', 'forum');
2112              $forum->introformat = FORMAT_HTML;
2113              $forum->assessed = 0;
2114              $forum->forcesubscribe = 0;
2115              break;
2116          default:
2117              echo $OUTPUT->notification("That forum type doesn't exist!");
2118              return false;
2119              break;
2120      }
2121  
2122      $forum->timemodified = time();
2123      $forum->id = $DB->insert_record("forum", $forum);
2124  
2125      if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2126          echo $OUTPUT->notification("Could not find forum module!!");
2127          return false;
2128      }
2129      $mod = new stdClass();
2130      $mod->course = $courseid;
2131      $mod->module = $module->id;
2132      $mod->instance = $forum->id;
2133      $mod->section = 0;
2134      include_once("$CFG->dirroot/course/lib.php");
2135      if (! $mod->coursemodule = add_course_module($mod) ) {
2136          echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2137          return false;
2138      }
2139      $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
2140      return $DB->get_record("forum", array("id" => "$forum->id"));
2141  }
2142  
2143  /**
2144   * Return rating related permissions
2145   *
2146   * @param string $options the context id
2147   * @return array an associative array of the user's rating permissions
2148   */
2149  function forum_rating_permissions($contextid, $component, $ratingarea) {
2150      $context = context::instance_by_id($contextid, MUST_EXIST);
2151      if ($component != 'mod_forum' || $ratingarea != 'post') {
2152          // We don't know about this component/ratingarea so just return null to get the
2153          // default restrictive permissions.
2154          return null;
2155      }
2156      return array(
2157          'view'    => has_capability('mod/forum:viewrating', $context),
2158          'viewany' => has_capability('mod/forum:viewanyrating', $context),
2159          'viewall' => has_capability('mod/forum:viewallratings', $context),
2160          'rate'    => has_capability('mod/forum:rate', $context)
2161      );
2162  }
2163  
2164  /**
2165   * Validates a submitted rating
2166   * @param array $params submitted data
2167   *            context => object the context in which the rated items exists [required]
2168   *            component => The component for this module - should always be mod_forum [required]
2169   *            ratingarea => object the context in which the rated items exists [required]
2170   *
2171   *            itemid => int the ID of the object being rated [required]
2172   *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2173   *            rating => int the submitted rating [required]
2174   *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2175   *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
2176   * @return boolean true if the rating is valid. Will throw rating_exception if not
2177   */
2178  function forum_rating_validate($params) {
2179      global $DB, $USER;
2180  
2181      // Check the component is mod_forum
2182      if ($params['component'] != 'mod_forum') {
2183          throw new rating_exception('invalidcomponent');
2184      }
2185  
2186      // Check the ratingarea is post (the only rating area in forum)
2187      if ($params['ratingarea'] != 'post') {
2188          throw new rating_exception('invalidratingarea');
2189      }
2190  
2191      // Check the rateduserid is not the current user .. you can't rate your own posts
2192      if ($params['rateduserid'] == $USER->id) {
2193          throw new rating_exception('nopermissiontorate');
2194      }
2195  
2196      // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2197      $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
2198      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2199      $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2200      $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2201      $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2202      $context = context_module::instance($cm->id);
2203  
2204      // Make sure the context provided is the context of the forum
2205      if ($context->id != $params['context']->id) {
2206          throw new rating_exception('invalidcontext');
2207      }
2208  
2209      if ($forum->scale != $params['scaleid']) {
2210          //the scale being submitted doesnt match the one in the database
2211          throw new rating_exception('invalidscaleid');
2212      }
2213  
2214      // check the item we're rating was created in the assessable time window
2215      if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
2216          if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
2217              throw new rating_exception('notavailable');
2218          }
2219      }
2220  
2221      //check that the submitted rating is valid for the scale
2222  
2223      // lower limit
2224      if ($params['rating'] < 0  && $params['rating'] != RATING_UNSET_RATING) {
2225          throw new rating_exception('invalidnum');
2226      }
2227  
2228      // upper limit
2229      if ($forum->scale < 0) {
2230          //its a custom scale
2231          $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
2232          if ($scalerecord) {
2233              $scalearray = explode(',', $scalerecord->scale);
2234              if ($params['rating'] > count($scalearray)) {
2235                  throw new rating_exception('invalidnum');
2236              }
2237          } else {
2238              throw new rating_exception('invalidscaleid');
2239          }
2240      } else if ($params['rating'] > $forum->scale) {
2241          //if its numeric and submitted rating is above maximum
2242          throw new rating_exception('invalidnum');
2243      }
2244  
2245      // Make sure groups allow this user to see the item they're rating
2246      if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
2247          if (!groups_group_exists($discussion->groupid)) { // Can't find group
2248              throw new rating_exception('cannotfindgroup');//something is wrong
2249          }
2250  
2251          if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2252              // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
2253              throw new rating_exception('notmemberofgroup');
2254          }
2255      }
2256  
2257      // perform some final capability checks
2258      if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2259          throw new rating_exception('nopermissiontorate');
2260      }
2261  
2262      return true;
2263  }
2264  
2265  /**
2266   * Can the current user see ratings for a given itemid?
2267   *
2268   * @param array $params submitted data
2269   *            contextid => int contextid [required]
2270   *            component => The component for this module - should always be mod_forum [required]
2271   *            ratingarea => object the context in which the rated items exists [required]
2272   *            itemid => int the ID of the object being rated [required]
2273   *            scaleid => int scale id [optional]
2274   * @return bool
2275   * @throws coding_exception
2276   * @throws rating_exception
2277   */
2278  function mod_forum_rating_can_see_item_ratings($params) {
2279      global $DB, $USER;
2280  
2281      // Check the component is mod_forum.
2282      if (!isset($params['component']) || $params['component'] != 'mod_forum') {
2283          throw new rating_exception('invalidcomponent');
2284      }
2285  
2286      // Check the ratingarea is post (the only rating area in forum).
2287      if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
2288          throw new rating_exception('invalidratingarea');
2289      }
2290  
2291      if (!isset($params['itemid'])) {
2292          throw new rating_exception('invaliditemid');
2293      }
2294  
2295      $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
2296      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2297      $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2298      $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2299      $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2300  
2301      // Perform some final capability checks.
2302      if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2303          return false;
2304      }
2305  
2306      return true;
2307  }
2308  
2309  /**
2310   * This function prints the overview of a discussion in the forum listing.
2311   * It needs some discussion information and some post information, these
2312   * happen to be combined for efficiency in the $post parameter by the function
2313   * that calls this one: forum_print_latest_discussions()
2314   *
2315   * @global object
2316   * @global object
2317   * @param object $post The post object (passed by reference for speed).
2318   * @param object $forum The forum object.
2319   * @param int $group Current group.
2320   * @param string $datestring Format to use for the dates.
2321   * @param boolean $cantrack Is tracking enabled for this forum.
2322   * @param boolean $forumtracked Is the user tracking this forum.
2323   * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
2324   * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
2325   */
2326  function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2327                                          $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2328                                          $canviewhiddentimedposts = false) {
2329  
2330      global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
2331  
2332      static $rowcount;
2333      static $strmarkalldread;
2334  
2335      if (empty($modcontext)) {
2336          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2337              print_error('invalidcoursemodule');
2338          }
2339          $modcontext = context_module::instance($cm->id);
2340      }
2341  
2342      if (!isset($rowcount)) {
2343          $rowcount = 0;
2344          $strmarkalldread = get_string('markalldread', 'forum');
2345      } else {
2346          $rowcount = ($rowcount + 1) % 2;
2347      }
2348  
2349      $post->subject = format_string($post->subject,true);
2350  
2351      $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
2352      $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2353      $timedoutsidewindow = '';
2354      if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2355          $timedoutsidewindow = ' dimmed_text';
2356      }
2357  
2358      echo "\n\n";
2359      echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
2360  
2361      $topicclass = 'topic starter';
2362      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2363          $topicclass .= ' pinned';
2364      }
2365      echo '<td class="'.$topicclass.'">';
2366      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2367          echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2368      }
2369      $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2370      if ($timeddiscussion && $canalwaysseetimedpost) {
2371          echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2372      }
2373  
2374      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
2375      echo "</td>\n";
2376  
2377      // Picture
2378      $postuser = new stdClass();
2379      $postuserfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
2380      $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
2381      $postuser->id = $post->userid;
2382      echo '<td class="author">';
2383      echo '<div class="media">';
2384      echo '<span class="float-left">';
2385      echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
2386      echo '</span>';
2387      // User name
2388      echo '<div class="media-body">';
2389      $fullname = fullname($postuser, $canviewfullnames);
2390      echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
2391      echo '</div>';
2392      echo '</div>';
2393      echo "</td>\n";
2394  
2395      // Group picture
2396      if ($group !== -1) {  // Groups are active - group is a group data object or NULL
2397          echo '<td class="picture group">';
2398          if (!empty($group->picture)) {
2399              if ($canviewparticipants && $COURSE->groupmode) {
2400                  $picturelink = true;
2401              } else {
2402                  $picturelink = false;
2403              }
2404              print_group_picture($group, $forum->course, false, false, $picturelink);
2405          } else if (isset($group->id)) {
2406              if ($canviewparticipants && $COURSE->groupmode) {
2407                  echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
2408              } else {
2409                  echo $group->name;
2410              }
2411          }
2412          echo "</td>\n";
2413      }
2414  
2415      if (has_capability('mod/forum:viewdiscussion', $modcontext)) {   // Show the column with replies
2416          echo '<td class="replies">';
2417          echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2418          echo $post->replies.'</a>';
2419          echo "</td>\n";
2420  
2421          if ($cantrack) {
2422              echo '<td class="replies">';
2423              if ($forumtracked) {
2424                  if ($post->unread > 0) {
2425                      echo '<span class="unread">';
2426                      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2427                      echo $post->unread;
2428                      echo '</a>';
2429                      echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2430                           $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;return=/mod/forum/view.php&amp;sesskey=' .
2431                           sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
2432                      echo '</span>';
2433                  } else {
2434                      echo '<span class="read">';
2435                      echo $post->unread;
2436                      echo '</span>';
2437                  }
2438              } else {
2439                  echo '<span class="read">';
2440                  echo '-';
2441                  echo '</span>';
2442              }
2443              echo "</td>\n";
2444          }
2445      }
2446  
2447      echo '<td class="lastpost">';
2448      $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
2449      $parenturl = '';
2450      $usermodified = new stdClass();
2451      $usermodified->id = $post->usermodified;
2452      $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
2453  
2454      // In QA forums we check that the user can view participants.
2455      if ($forum->type !== 'qanda' || $canviewparticipants) {
2456          echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
2457               fullname($usermodified, $canviewfullnames).'</a><br />';
2458          $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
2459      }
2460  
2461      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
2462            userdate_htmltime($usedate, $datestring).'</a>';
2463      echo "</td>\n";
2464  
2465      // is_guest should be used here as this also checks whether the user is a guest in the current course.
2466      // Guests and visitors cannot subscribe - only enrolled users.
2467      if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
2468          // Discussion subscription.
2469          if (\mod_forum\subscriptions::is_subscribable($forum)) {
2470              echo '<td class="discussionsubscription">';
2471              echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2472              echo '</td>';
2473          }
2474      }
2475  
2476      echo "</tr>\n\n";
2477  
2478  }
2479  
2480  /**
2481   * Return the markup for the discussion subscription toggling icon.
2482   *
2483   * @param stdClass $forum The forum object.
2484   * @param int $discussionid The discussion to create an icon for.
2485   * @return string The generated markup.
2486   */
2487  function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2488      global $USER, $OUTPUT, $PAGE;
2489  
2490      if ($returnurl === null && $PAGE->url) {
2491          $returnurl = $PAGE->url->out();
2492      }
2493  
2494      $o = '';
2495      $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2496      $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2497          'sesskey' => sesskey(),
2498          'id' => $forum->id,
2499          'd' => $discussionid,
2500          'returnurl' => $returnurl,
2501      ));
2502  
2503      if ($includetext) {
2504          $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2505      }
2506  
2507      if ($subscriptionstatus) {
2508          $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2509          if ($includetext) {
2510              $output .= get_string('subscribed', 'mod_forum');
2511          }
2512  
2513          return html_writer::link($subscriptionlink, $output, array(
2514                  'title' => get_string('clicktounsubscribe', 'forum'),
2515                  'class' => 'discussiontoggle btn btn-link',
2516                  'data-forumid' => $forum->id,
2517                  'data-discussionid' => $discussionid,
2518                  'data-includetext' => $includetext,
2519              ));
2520  
2521      } else {
2522          $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2523          if ($includetext) {
2524              $output .= get_string('notsubscribed', 'mod_forum');
2525          }
2526  
2527          return html_writer::link($subscriptionlink, $output, array(
2528                  'title' => get_string('clicktosubscribe', 'forum'),
2529                  'class' => 'discussiontoggle btn btn-link',
2530                  'data-forumid' => $forum->id,
2531                  'data-discussionid' => $discussionid,
2532                  'data-includetext' => $includetext,
2533              ));
2534      }
2535  }
2536  
2537  /**
2538   * Return a pair of spans containing classes to allow the subscribe and
2539   * unsubscribe icons to be pre-loaded by a browser.
2540   *
2541   * @return string The generated markup
2542   */
2543  function forum_get_discussion_subscription_icon_preloaders() {
2544      $o = '';
2545      $o .= html_writer::span('&nbsp;', 'preload-subscribe');
2546      $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
2547      return $o;
2548  }
2549  
2550  /**
2551   * Print the drop down that allows the user to select how they want to have
2552   * the discussion displayed.
2553   *
2554   * @param int $id forum id if $forumtype is 'single',
2555   *              discussion id for any other forum type
2556   * @param mixed $mode forum layout mode
2557   * @param string $forumtype optional
2558   */
2559  function forum_print_mode_form($id, $mode, $forumtype='') {
2560      global $OUTPUT;
2561      $useexperimentalui = get_user_preferences('forum_useexperimentalui', false);
2562      if ($forumtype == 'single') {
2563          $select = new single_select(
2564              new moodle_url("/mod/forum/view.php",
2565              array('f' => $id)),
2566              'mode',
2567              forum_get_layout_modes($useexperimentalui),
2568              $mode,
2569              null,
2570              "mode"
2571          );
2572          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2573          $select->class = "forummode";
2574      } else {
2575          $select = new single_select(
2576              new moodle_url("/mod/forum/discuss.php",
2577              array('d' => $id)),
2578              'mode',
2579              forum_get_layout_modes($useexperimentalui),
2580              $mode,
2581              null,
2582              "mode"
2583          );
2584          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2585      }
2586      echo $OUTPUT->render($select);
2587  }
2588  
2589  /**
2590   * @global object
2591   * @param object $course
2592   * @param string $search
2593   * @return string
2594   */
2595  function forum_search_form($course, $search='') {
2596      global $CFG, $PAGE;
2597      $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2598      $output = $PAGE->get_renderer('mod_forum');
2599      return $output->render($forumsearch);
2600  }
2601  
2602  
2603  /**
2604   * @global object
2605   * @global object
2606   */
2607  function forum_set_return() {
2608      global $CFG, $SESSION;
2609  
2610      if (! isset($SESSION->fromdiscussion)) {
2611          $referer = get_local_referer(false);
2612          // If the referer is NOT a login screen then save it.
2613          if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2614              $SESSION->fromdiscussion = $referer;
2615          }
2616      }
2617  }
2618  
2619  
2620  /**
2621   * @global object
2622   * @param string|\moodle_url $default
2623   * @return string
2624   */
2625  function forum_go_back_to($default) {
2626      global $SESSION;
2627  
2628      if (!empty($SESSION->fromdiscussion)) {
2629          $returnto = $SESSION->fromdiscussion;
2630          unset($SESSION->fromdiscussion);
2631          return $returnto;
2632      } else {
2633          return $default;
2634      }
2635  }
2636  
2637  /**
2638   * Given a discussion object that is being moved to $forumto,
2639   * this function checks all posts in that discussion
2640   * for attachments, and if any are found, these are
2641   * moved to the new forum directory.
2642   *
2643   * @global object
2644   * @param object $discussion
2645   * @param int $forumfrom source forum id
2646   * @param int $forumto target forum id
2647   * @return bool success
2648   */
2649  function forum_move_attachments($discussion, $forumfrom, $forumto) {
2650      global $DB;
2651  
2652      $fs = get_file_storage();
2653  
2654      $newcm = get_coursemodule_from_instance('forum', $forumto);
2655      $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2656  
2657      $newcontext = context_module::instance($newcm->id);
2658      $oldcontext = context_module::instance($oldcm->id);
2659  
2660      // loop through all posts, better not use attachment flag ;-)
2661      if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
2662          foreach ($posts as $post) {
2663              $fs->move_area_files_to_new_context($oldcontext->id,
2664                      $newcontext->id, 'mod_forum', 'post', $post->id);
2665              $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2666                      $newcontext->id, 'mod_forum', 'attachment', $post->id);
2667              if ($attachmentsmoved > 0 && $post->attachment != '1') {
2668                  // Weird - let's fix it
2669                  $post->attachment = '1';
2670                  $DB->update_record('forum_posts', $post);
2671              } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2672                  // Weird - let's fix it
2673                  $post->attachment = '';
2674                  $DB->update_record('forum_posts', $post);
2675              }
2676          }
2677      }
2678  
2679      return true;
2680  }
2681  
2682  /**
2683   * Returns attachments as formated text/html optionally with separate images
2684   *
2685   * @global object
2686   * @global object
2687   * @global object
2688   * @param object $post
2689   * @param object $cm
2690   * @param string $type html/text/separateimages
2691   * @return mixed string or array of (html text withouth images and image HTML)
2692   */
2693  function forum_print_attachments($post, $cm, $type) {
2694      global $CFG, $DB, $USER, $OUTPUT;
2695  
2696      if (empty($post->attachment)) {
2697          return $type !== 'separateimages' ? '' : array('', '');
2698      }
2699  
2700      if (!in_array($type, array('separateimages', 'html', 'text'))) {
2701          return $type !== 'separateimages' ? '' : array('', '');
2702      }
2703  
2704      if (!$context = context_module::instance($cm->id)) {
2705          return $type !== 'separateimages' ? '' : array('', '');
2706      }
2707      $strattachment = get_string('attachment', 'forum');
2708  
2709      $fs = get_file_storage();
2710  
2711      $imagereturn = '';
2712      $output = '';
2713  
2714      $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
2715  
2716      if ($canexport) {
2717          require_once($CFG->libdir.'/portfoliolib.php');
2718      }
2719  
2720      // We retrieve all files according to the time that they were created.  In the case that several files were uploaded
2721      // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2722      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
2723      if ($files) {
2724          if ($canexport) {
2725              $button = new portfolio_add_button();
2726          }
2727          foreach ($files as $file) {
2728              $filename = $file->get_filename();
2729              $mimetype = $file->get_mimetype();
2730              $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2731              $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2732  
2733              if ($type == 'html') {
2734                  $output .= "<a href=\"$path\">$iconimage</a> ";
2735                  $output .= "<a href=\"$path\">".s($filename)."</a>";
2736                  if ($canexport) {
2737                      $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2738                      $button->set_format_by_file($file);
2739                      $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2740                  }
2741                  $output .= "<br />";
2742  
2743              } else if ($type == 'text') {
2744                  $output .= "$strattachment ".s($filename).":\n$path\n";
2745  
2746              } else { //'returnimages'
2747                  if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2748                      // Image attachments don't get printed as links
2749                      $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2750                      if ($canexport) {
2751                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2752                          $button->set_format_by_file($file);
2753                          $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2754                      }
2755                  } else {
2756                      $output .= "<a href=\"$path\">$iconimage</a> ";
2757                      $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
2758                      if ($canexport) {
2759                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2760                          $button->set_format_by_file($file);
2761                          $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2762                      }
2763                      $output .= '<br />';
2764                  }
2765              }
2766  
2767              if (!empty($CFG->enableplagiarism)) {
2768                  require_once($CFG->libdir.'/plagiarismlib.php');
2769                  $output .= plagiarism_get_links(array('userid' => $post->userid,
2770                      'file' => $file,
2771                      'cmid' => $cm->id,
2772                      'course' => $cm->course,
2773                      'forum' => $cm->instance));
2774                  $output .= '<br />';
2775              }
2776          }
2777      }
2778  
2779      if ($type !== 'separateimages') {
2780          return $output;
2781  
2782      } else {
2783          return array($output, $imagereturn);
2784      }
2785  }
2786  
2787  ////////////////////////////////////////////////////////////////////////////////
2788  // File API                                                                   //
2789  ////////////////////////////////////////////////////////////////////////////////
2790  
2791  /**
2792   * Lists all browsable file areas
2793   *
2794   * @package  mod_forum
2795   * @category files
2796   * @param stdClass $course course object
2797   * @param stdClass $cm course module object
2798   * @param stdClass $context context object
2799   * @return array
2800   */
2801  function forum_get_file_areas($course, $cm, $context) {
2802      return array(
2803          'attachment' => get_string('areaattachment', 'mod_forum'),
2804          'post' => get_string('areapost', 'mod_forum'),
2805      );
2806  }
2807  
2808  /**
2809   * File browsing support for forum module.
2810   *
2811   * @package  mod_forum
2812   * @category files
2813   * @param stdClass $browser file browser object
2814   * @param stdClass $areas file areas
2815   * @param stdClass $course course object
2816   * @param stdClass $cm course module
2817   * @param stdClass $context context module
2818   * @param string $filearea file area
2819   * @param int $itemid item ID
2820   * @param string $filepath file path
2821   * @param string $filename file name
2822   * @return file_info instance or null if not found
2823   */
2824  function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2825      global $CFG, $DB, $USER;
2826  
2827      if ($context->contextlevel != CONTEXT_MODULE) {
2828          return null;
2829      }
2830  
2831      // filearea must contain a real area
2832      if (!isset($areas[$filearea])) {
2833          return null;
2834      }
2835  
2836      // Note that forum_user_can_see_post() additionally allows access for parent roles
2837      // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2838      // course:managefiles, we will need to extend this.
2839      if (!has_capability('mod/forum:viewdiscussion', $context)) {
2840          return null;
2841      }
2842  
2843      if (is_null($itemid)) {
2844          require_once($CFG->dirroot.'/mod/forum/locallib.php');
2845          return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2846      }
2847  
2848      static $cached = array();
2849      // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2850      // is cleared between unit tests we check if this is the same session
2851      if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2852          $cached = array('sesskey' => sesskey());
2853      }
2854  
2855      if (isset($cached['post']) && $cached['post']->id == $itemid) {
2856          $post = $cached['post'];
2857      } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2858          $cached['post'] = $post;
2859      } else {
2860          return null;
2861      }
2862  
2863      if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2864          $discussion = $cached['discussion'];
2865      } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2866          $cached['discussion'] = $discussion;
2867      } else {
2868          return null;
2869      }
2870  
2871      if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2872          $forum = $cached['forum'];
2873      } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2874          $cached['forum'] = $forum;
2875      } else {
2876          return null;
2877      }
2878  
2879      $fs = get_file_storage();
2880      $filepath = is_null($filepath) ? '/' : $filepath;
2881      $filename = is_null($filename) ? '.' : $filename;
2882      if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2883          return null;
2884      }
2885  
2886      // Checks to see if the user can manage files or is the owner.
2887      // TODO MDL-33805 - Do not use userid here and move the capability check above.
2888      if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2889          return null;
2890      }
2891      // Make sure groups allow this user to see this file
2892      if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2893          $groupmode = groups_get_activity_groupmode($cm, $course);
2894          if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2895              return null;
2896          }
2897      }
2898  
2899      // Make sure we're allowed to see it...
2900      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2901          return null;
2902      }
2903  
2904      $urlbase = $CFG->wwwroot.'/pluginfile.php';
2905      return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2906  }
2907  
2908  /**
2909   * Serves the forum attachments. Implements needed access control ;-)
2910   *
2911   * @package  mod_forum
2912   * @category files
2913   * @param stdClass $course course object
2914   * @param stdClass $cm course module object
2915   * @param stdClass $context context object
2916   * @param string $filearea file area
2917   * @param array $args extra arguments
2918   * @param bool $forcedownload whether or not force download
2919   * @param array $options additional options affecting the file serving
2920   * @return bool false if file not found, does not return if found - justsend the file
2921   */
2922  function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2923      global $CFG, $DB;
2924  
2925      if ($context->contextlevel != CONTEXT_MODULE) {
2926          return false;
2927      }
2928  
2929      require_course_login($course, true, $cm);
2930  
2931      $areas = forum_get_file_areas($course, $cm, $context);
2932  
2933      // filearea must contain a real area
2934      if (!isset($areas[$filearea])) {
2935          return false;
2936      }
2937  
2938      $postid = (int)array_shift($args);
2939  
2940      if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2941          return false;
2942      }
2943  
2944      if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
2945          return false;
2946      }
2947  
2948      if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
2949          return false;
2950      }
2951  
2952      $fs = get_file_storage();
2953      $relativepath = implode('/', $args);
2954      $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
2955      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2956          return false;
2957      }
2958  
2959      // Make sure groups allow this user to see this file
2960      if ($discussion->groupid > 0) {
2961          $groupmode = groups_get_activity_groupmode($cm, $course);
2962          if ($groupmode == SEPARATEGROUPS) {
2963              if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2964                  return false;
2965              }
2966          }
2967      }
2968  
2969      // Make sure we're allowed to see it...
2970      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2971          return false;
2972      }
2973  
2974      // finally send the file
2975      send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
2976  }
2977  
2978  /**
2979   * If successful, this function returns the name of the file
2980   *
2981   * @global object
2982   * @param object $post is a full post record, including course and forum
2983   * @param object $forum
2984   * @param object $cm
2985   * @param mixed $mform
2986   * @param string $unused
2987   * @return bool
2988   */
2989  function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
2990      global $DB;
2991  
2992      if (empty($mform)) {
2993          return false;
2994      }
2995  
2996      if (empty($post->attachments)) {
2997          return true;   // Nothing to do
2998      }
2999  
3000      $context = context_module::instance($cm->id);
3001  
3002      $info = file_get_draft_area_info($post->attachments);
3003      $present = ($info['filecount']>0) ? '1' : '';
3004      file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
3005              mod_forum_post_form::attachment_options($forum));
3006  
3007      $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
3008  
3009      return true;
3010  }
3011  
3012  /**
3013   * Add a new post in an existing discussion.
3014   *
3015   * @param   stdClass    $post       The post data
3016   * @param   mixed       $mform      The submitted form
3017   * @param   string      $unused
3018   * @return int
3019   */
3020  function forum_add_new_post($post, $mform, $unused = null) {
3021      global $USER, $DB;
3022  
3023      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3024      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3025      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3026      $context    = context_module::instance($cm->id);
3027      $privatereplyto = 0;
3028  
3029      // Check whether private replies should be enabled for this post.
3030      if ($post->parent) {
3031          $parent = $DB->get_record('forum_posts', array('id' => $post->parent));
3032  
3033          if (!empty($parent->privatereplyto)) {
3034              throw new \coding_exception('It should not be possible to reply to a private reply');
3035          }
3036  
3037          if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) {
3038              $privatereplyto = $parent->userid;
3039          }
3040      }
3041  
3042      $post->created    = $post->modified = time();
3043      $post->mailed     = FORUM_MAILED_PENDING;
3044      $post->userid     = $USER->id;
3045      $post->privatereplyto = $privatereplyto;
3046      $post->attachment = "";
3047      if (!isset($post->totalscore)) {
3048          $post->totalscore = 0;
3049      }
3050      if (!isset($post->mailnow)) {
3051          $post->mailnow    = 0;
3052      }
3053  
3054      \mod_forum\local\entities\post::add_message_counts($post);
3055      $post->id = $DB->insert_record("forum_posts", $post);
3056      $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
3057              mod_forum_post_form::editor_options($context, null), $post->message);
3058      $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
3059      forum_add_attachment($post, $forum, $cm, $mform);
3060  
3061      // Update discussion modified date
3062      $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
3063      $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
3064  
3065      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3066          forum_tp_mark_post_read($post->userid, $post);
3067      }
3068  
3069      if (isset($post->tags)) {
3070          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
3071      }
3072  
3073      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3074      forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
3075  
3076      return $post->id;
3077  }
3078  
3079  /**
3080   * Trigger post updated event.
3081   *
3082   * @param object $post forum post object
3083   * @param object $discussion discussion object
3084   * @param object $context forum context object
3085   * @param object $forum forum object
3086   * @since Moodle 3.8
3087   * @return void
3088   */
3089  function forum_trigger_post_updated_event($post, $discussion, $context, $forum) {
3090      global $USER;
3091  
3092      $params = array(
3093          'context' => $context,
3094          'objectid' => $post->id,
3095          'other' => array(
3096              'discussionid' => $discussion->id,
3097              'forumid' => $forum->id,
3098              'forumtype' => $forum->type,
3099          )
3100      );
3101  
3102      if ($USER->id !== $post->userid) {
3103          $params['relateduserid'] = $post->userid;
3104      }
3105  
3106      $event = \mod_forum\event\post_updated::create($params);
3107      $event->add_record_snapshot('forum_discussions', $discussion);
3108      $event->trigger();
3109  }
3110  
3111  /**
3112   * Update a post.
3113   *
3114   * @param   stdClass    $newpost    The post to update
3115   * @param   mixed       $mform      The submitted form
3116   * @param   string      $unused
3117   * @return  bool
3118   */
3119  function forum_update_post($newpost, $mform, $unused = null) {
3120      global $DB, $USER;
3121  
3122      $post       = $DB->get_record('forum_posts', array('id' => $newpost->id));
3123      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3124      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3125      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3126      $context    = context_module::instance($cm->id);
3127  
3128      // Allowed modifiable fields.
3129      $modifiablefields = [
3130          'subject',
3131          'message',
3132          'messageformat',
3133          'messagetrust',
3134          'timestart',
3135          'timeend',
3136          'pinned',
3137          'attachments',
3138      ];
3139      foreach ($modifiablefields as $field) {
3140          if (isset($newpost->{$field})) {
3141              $post->{$field} = $newpost->{$field};
3142          }
3143      }
3144      $post->modified = time();
3145  
3146      if (!$post->parent) {   // Post is a discussion starter - update discussion title and times too
3147          $discussion->name      = $post->subject;
3148          $discussion->timestart = $post->timestart;
3149          $discussion->timeend   = $post->timeend;
3150  
3151          if (isset($post->pinned)) {
3152              $discussion->pinned = $post->pinned;
3153          }
3154      }
3155      $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
3156              mod_forum_post_form::editor_options($context, $post->id), $post->message);
3157      \mod_forum\local\entities\post::add_message_counts($post);
3158      $DB->update_record('forum_posts', $post);
3159      // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3160      $DB->update_record('forum_discussions', $discussion);
3161  
3162      forum_add_attachment($post, $forum, $cm, $mform);
3163  
3164      if ($forum->type == 'single' && $post->parent == '0') {
3165          // Updating first post of single discussion type -> updating forum intro.
3166          $forum->intro = $post->message;
3167          $forum->timemodified = time();
3168          $DB->update_record("forum", $forum);
3169      }
3170  
3171      if (isset($newpost->tags)) {
3172          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3173      }
3174  
3175      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3176          forum_tp_mark_post_read($USER->id, $post);
3177      }
3178  
3179      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3180      forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3181  
3182      return true;
3183  }
3184  
3185  /**
3186   * Given an object containing all the necessary data,
3187   * create a new discussion and return the id
3188   *
3189   * @param object $post
3190   * @param mixed $mform
3191   * @param string $unused
3192   * @param int $userid
3193   * @return object
3194   */
3195  function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3196      global $USER, $CFG, $DB;
3197  
3198      $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
3199  
3200      if (is_null($userid)) {
3201          $userid = $USER->id;
3202      }
3203  
3204      // The first post is stored as a real post, and linked
3205      // to from the discuss entry.
3206  
3207      $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
3208      $cm    = get_coursemodule_from_instance('forum', $forum->id);
3209  
3210      $post = new stdClass();
3211      $post->discussion    = 0;
3212      $post->parent        = 0;
3213      $post->privatereplyto = 0;
3214      $post->userid        = $userid;
3215      $post->created       = $timenow;
3216      $post->modified      = $timenow;
3217      $post->mailed        = FORUM_MAILED_PENDING;
3218      $post->subject       = $discussion->name;
3219      $post->message       = $discussion->message;
3220      $post->messageformat = $discussion->messageformat;
3221      $post->messagetrust  = $discussion->messagetrust;
3222      $post->attachments   = isset($discussion->attachments) ? $discussion->attachments : null;
3223      $post->forum         = $forum->id;     // speedup
3224      $post->course        = $forum->course; // speedup
3225      $post->mailnow       = $discussion->mailnow;
3226  
3227      \mod_forum\local\entities\post::add_message_counts($post);
3228      $post->id = $DB->insert_record("forum_posts", $post);
3229  
3230      // TODO: Fix the calling code so that there always is a $cm when this function is called
3231      if (!empty($cm->id) && !empty($discussion->itemid)) {   // In "single simple discussions" this may not exist yet
3232          $context = context_module::instance($cm->id);
3233          $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
3234                  mod_forum_post_form::editor_options($context, null), $post->message);
3235          $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
3236      }
3237  
3238      // Now do the main entry for the discussion, linking to this first post
3239  
3240      $discussion->firstpost    = $post->id;
3241      $discussion->timemodified = $timenow;
3242      $discussion->usermodified = $post->userid;
3243      $discussion->userid       = $userid;
3244      $discussion->assessed     = 0;
3245  
3246      $post->discussion = $DB->insert_record("forum_discussions", $discussion);
3247  
3248      // Finally, set the pointer on the post.
3249      $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
3250  
3251      if (!empty($cm->id)) {
3252          forum_add_attachment($post, $forum, $cm, $mform, $unused);
3253      }
3254  
3255      if (isset($discussion->tags)) {
3256          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
3257      }
3258  
3259      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3260          forum_tp_mark_post_read($post->userid, $post);
3261      }
3262  
3263      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3264      if (!empty($cm->id)) {
3265          forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3266      }
3267  
3268      return $post->discussion;
3269  }
3270  
3271  
3272  /**
3273   * Deletes a discussion and handles all associated cleanup.
3274   *
3275   * @global object
3276   * @param object $discussion Discussion to delete
3277   * @param bool $fulldelete True when deleting entire forum
3278   * @param object $course Course
3279   * @param object $cm Course-module
3280   * @param object $forum Forum
3281   * @return bool
3282   */
3283  function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3284      global $DB, $CFG;
3285      require_once($CFG->libdir.'/completionlib.php');
3286  
3287      $result = true;
3288  
3289      if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
3290          foreach ($posts as $post) {
3291              $post->course = $discussion->course;
3292              $post->forum  = $discussion->forum;
3293              if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3294                  $result = false;
3295              }
3296          }
3297      }
3298  
3299      forum_tp_delete_read_records(-1, -1, $discussion->id);
3300  
3301      // Discussion subscriptions must be removed before discussions because of key constraints.
3302      $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
3303      if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
3304          $result = false;
3305      }
3306  
3307      // Update completion state if we are tracking completion based on number of posts
3308      // But don't bother when deleting whole thing
3309      if (!$fulldelete) {
3310          $completion = new completion_info($course);
3311          if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3312             ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3313              $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
3314          }
3315      }
3316  
3317      $params = array(
3318          'objectid' => $discussion->id,
3319          'context' => context_module::instance($cm->id),
3320          'other' => array(
3321              'forumid' => $forum->id,
3322          )
3323      );
3324      $event = \mod_forum\event\discussion_deleted::create($params);
3325      $event->add_record_snapshot('forum_discussions', $discussion);
3326      $event->trigger();
3327  
3328      return $result;
3329  }
3330  
3331  
3332  /**
3333   * Deletes a single forum post.
3334   *
3335   * @global object
3336   * @param object $post Forum post object
3337   * @param mixed $children Whether to delete children. If false, returns false
3338   *   if there are any children (without deleting the post). If true,
3339   *   recursively deletes all children. If set to special value 'ignore', deletes
3340   *   post regardless of children (this is for use only when deleting all posts
3341   *   in a disussion).
3342   * @param object $course Course
3343   * @param object $cm Course-module
3344   * @param object $forum Forum
3345   * @param bool $skipcompletion True to skip updating completion state if it
3346   *   would otherwise be updated, i.e. when deleting entire forum anyway.
3347   * @return bool
3348   */
3349  function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3350      global $DB, $CFG, $USER;
3351      require_once($CFG->libdir.'/completionlib.php');
3352  
3353      $context = context_module::instance($cm->id);
3354  
3355      if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
3356         if ($children) {
3357             foreach ($childposts as $childpost) {
3358                 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3359             }
3360         } else {
3361             return false;
3362         }
3363      }
3364  
3365      // Delete ratings.
3366      require_once($CFG->dirroot.'/rating/lib.php');
3367      $delopt = new stdClass;
3368      $delopt->contextid = $context->id;
3369      $delopt->component = 'mod_forum';
3370      $delopt->ratingarea = 'post';
3371      $delopt->itemid = $post->id;
3372      $rm = new rating_manager();
3373      $rm->delete_ratings($delopt);
3374  
3375      // Delete attachments.
3376      $fs = get_file_storage();
3377      $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
3378      $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
3379  
3380      // Delete cached RSS feeds.
3381      if (!empty($CFG->enablerssfeeds)) {
3382          require_once($CFG->dirroot.'/mod/forum/rsslib.php');
3383          forum_rss_delete_file($forum);
3384      }
3385  
3386      if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
3387  
3388          forum_tp_delete_read_records(-1, $post->id);
3389  
3390      // Just in case we are deleting the last post
3391          forum_discussion_update_last_post($post->discussion);
3392  
3393          // Update completion state if we are tracking completion based on number of posts
3394          // But don't bother when deleting whole thing
3395  
3396          if (!$skipcompletion) {
3397              $completion = new completion_info($course);
3398              if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3399                 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3400                  $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
3401              }
3402          }
3403  
3404          $params = array(
3405              'context' => $context,
3406              'objectid' => $post->id,
3407              'other' => array(
3408                  'discussionid' => $post->discussion,
3409                  'forumid' => $forum->id,
3410                  'forumtype' => $forum->type,
3411              )
3412          );
3413          $post->deleted = 1;
3414          if ($post->userid !== $USER->id) {
3415              $params['relateduserid'] = $post->userid;
3416          }
3417          $event = \mod_forum\event\post_deleted::create($params);
3418          $event->add_record_snapshot('forum_posts', $post);
3419          $event->trigger();
3420  
3421          return true;
3422      }
3423      return false;
3424  }
3425  
3426  /**
3427   * Sends post content to plagiarism plugin
3428   * @param object $post Forum post object
3429   * @param object $cm Course-module
3430   * @param string $name
3431   * @return bool
3432  */
3433  function forum_trigger_content_uploaded_event($post, $cm, $name) {
3434      $context = context_module::instance($cm->id);
3435      $fs = get_file_storage();
3436      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
3437      $params = array(
3438          'context' => $context,
3439          'objectid' => $post->id,
3440          'other' => array(
3441              'content' => $post->message,
3442              'pathnamehashes' => array_keys($files),
3443              'discussionid' => $post->discussion,
3444              'triggeredfrom' => $name,
3445          )
3446      );
3447      $event = \mod_forum\event\assessable_uploaded::create($params);
3448      $event->trigger();
3449      return true;
3450  }
3451  
3452  /**
3453   * Given a new post, subscribes or unsubscribes as appropriate.
3454   * Returns some text which describes what happened.
3455   *
3456   * @param object $fromform The submitted form
3457   * @param stdClass $forum The forum record
3458   * @param stdClass $discussion The forum discussion record
3459   * @return string
3460   */
3461  function forum_post_subscription($fromform, $forum, $discussion) {
3462      global $USER;
3463  
3464      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3465          return "";
3466      } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
3467          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3468          if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
3469              // This user should not be subscribed to the forum.
3470              \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
3471          }
3472          return "";
3473      }
3474  
3475      $info = new stdClass();
3476      $info->name  = fullname($USER);
3477      $info->discussion = format_string($discussion->name);
3478      $info->forum = format_string($forum->name);
3479  
3480      if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
3481          if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
3482              return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3483          }
3484      } else {
3485          if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
3486              return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3487          }
3488      }
3489  
3490      return '';
3491  }
3492  
3493  /**
3494   * Generate and return the subscribe or unsubscribe link for a forum.
3495   *
3496   * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3497   * @param object $context the context object for this forum.
3498   * @param array $messages text used for the link in its various states
3499   *      (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3500   *      Any strings not passed in are taken from the $defaultmessages array
3501   *      at the top of the function.
3502   * @param bool $cantaccessagroup
3503   * @param bool $unused1
3504   * @param bool $backtoindex
3505   * @param array $unused2
3506   * @return string
3507   */
3508  function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3509      $backtoindex = false, $unused2 = null) {
3510      global $CFG, $USER, $PAGE, $OUTPUT;
3511      $defaultmessages = array(
3512          'subscribed' => get_string('unsubscribe', 'forum'),
3513          'unsubscribed' => get_string('subscribe', 'forum'),
3514          'cantaccessgroup' => get_string('no'),
3515          'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3516          'cantsubscribe' => get_string('disallowsubscribe','forum')
3517      );
3518      $messages = $messages + $defaultmessages;
3519  
3520      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3521          return $messages['forcesubscribed'];
3522      } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
3523              !has_capability('mod/forum:managesubscriptions', $context)) {
3524          return $messages['cantsubscribe'];
3525      } else if ($cantaccessagroup) {
3526          return $messages['cantaccessgroup'];
3527      } else {
3528          if (!is_enrolled($context, $USER, '', true)) {
3529              return '';
3530          }
3531  
3532          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3533          if ($subscribed) {
3534              $linktext = $messages['subscribed'];
3535              $linktitle = get_string('subscribestop', 'forum');
3536          } else {
3537              $linktext = $messages['unsubscribed'];
3538              $linktitle = get_string('subscribestart', 'forum');
3539          }
3540  
3541          $options = array();
3542          if ($backtoindex) {
3543              $backtoindexlink = '&amp;backtoindex=1';
3544              $options['backtoindex'] = 1;
3545          } else {
3546              $backtoindexlink = '';
3547          }
3548  
3549          $options['id'] = $forum->id;
3550          $options['sesskey'] = sesskey();
3551          $url = new moodle_url('/mod/forum/subscribe.php', $options);
3552          return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3553      }
3554  }
3555  
3556  /**
3557   * Returns true if user created new discussion already.
3558   *
3559   * @param int $forumid  The forum to check for postings
3560   * @param int $userid   The user to check for postings
3561   * @param int $groupid  The group to restrict the check to
3562   * @return bool
3563   */
3564  function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3565      global $CFG, $DB;
3566  
3567      $sql = "SELECT 'x'
3568                FROM {forum_discussions} d, {forum_posts} p
3569               WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3570  
3571      $params = [$forumid, $userid];
3572  
3573      if ($groupid) {
3574          $sql .= " AND d.groupid = ?";
3575          $params[] = $groupid;
3576      }
3577  
3578      return $DB->record_exists_sql($sql, $params);
3579  }
3580  
3581  /**
3582   * @global object
3583   * @global object
3584   * @param int $forumid
3585   * @param int $userid
3586   * @return array
3587   */
3588  function forum_discussions_user_has_posted_in($forumid, $userid) {
3589      global $CFG, $DB;
3590  
3591      $haspostedsql = "SELECT d.id AS id,
3592                              d.*
3593                         FROM {forum_posts} p,
3594                              {forum_discussions} d
3595                        WHERE p.discussion = d.id
3596                          AND d.forum = ?
3597                          AND p.userid = ?";
3598  
3599      return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3600  }
3601  
3602  /**
3603   * @global object
3604   * @global object
3605   * @param int $forumid
3606   * @param int $did
3607   * @param int $userid
3608   * @return bool
3609   */
3610  function forum_user_has_posted($forumid, $did, $userid) {
3611      global $DB;
3612  
3613      if (empty($did)) {
3614          // posted in any forum discussion?
3615          $sql = "SELECT 'x'
3616                    FROM {forum_posts} p
3617                    JOIN {forum_discussions} d ON d.id = p.discussion
3618                   WHERE p.userid = :userid AND d.forum = :forumid";
3619          return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3620      } else {
3621          return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3622      }
3623  }
3624  
3625  /**
3626   * Returns creation time of the first user's post in given discussion
3627   * @global object $DB
3628   * @param int $did Discussion id
3629   * @param int $userid User id
3630   * @return int|bool post creation time stamp or return false
3631   */
3632  function forum_get_user_posted_time($did, $userid) {
3633      global $DB;
3634  
3635      $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3636      if (empty($posttime)) {
3637          return false;
3638      }
3639      return $posttime;
3640  }
3641  
3642  /**
3643   * @global object
3644   * @param object $forum
3645   * @param object $currentgroup
3646   * @param int $unused
3647   * @param object $cm
3648   * @param object $context
3649   * @return bool
3650   */
3651  function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3652  // $forum is an object
3653      global $USER;
3654  
3655      // shortcut - guest and not-logged-in users can not post
3656      if (isguestuser() or !isloggedin()) {
3657          return false;
3658      }
3659  
3660      if (!$cm) {
3661          debugging('missing cm', DEBUG_DEVELOPER);
3662          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3663              print_error('invalidcoursemodule');
3664          }
3665      }
3666  
3667      if (!$context) {
3668          $context = context_module::instance($cm->id);
3669      }
3670  
3671      if (forum_is_cutoff_date_reached($forum)) {
3672          if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3673              return false;
3674          }
3675      }
3676  
3677      if ($currentgroup === null) {
3678          $currentgroup = groups_get_activity_group($cm);
3679      }
3680  
3681      $groupmode = groups_get_activity_groupmode($cm);
3682  
3683      if ($forum->type == 'news') {
3684          $capname = 'mod/forum:addnews';
3685      } else if ($forum->type == 'qanda') {
3686          $capname = 'mod/forum:addquestion';
3687      } else {
3688          $capname = 'mod/forum:startdiscussion';
3689      }
3690  
3691      if (!has_capability($capname, $context)) {
3692          return false;
3693      }
3694  
3695      if ($forum->type == 'single') {
3696          return false;
3697      }
3698  
3699      if ($forum->type == 'eachuser') {
3700          if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) {
3701              return false;
3702          }
3703      }
3704  
3705      if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
3706          return true;
3707      }
3708  
3709      if ($currentgroup) {
3710          return groups_is_member($currentgroup);
3711      } else {
3712          // no group membership and no accessallgroups means no new discussions
3713          // reverted to 1.7 behaviour in 1.9+,  buggy in 1.8.0-1.9.0
3714          return false;
3715      }
3716  }
3717  
3718  /**
3719   * This function checks whether the user can reply to posts in a forum
3720   * discussion. Use forum_user_can_post_discussion() to check whether the user
3721   * can start discussions.
3722   *
3723   * @global object
3724   * @global object
3725   * @uses DEBUG_DEVELOPER
3726   * @uses CONTEXT_MODULE
3727   * @uses VISIBLEGROUPS
3728   * @param object $forum forum object
3729   * @param object $discussion
3730   * @param object $user
3731   * @param object $cm
3732   * @param object $course
3733   * @param object $context
3734   * @return bool
3735   */
3736  function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
3737      global $USER, $DB;
3738      if (empty($user)) {
3739          $user = $USER;
3740      }
3741  
3742      // shortcut - guest and not-logged-in users can not post
3743      if (isguestuser($user) or empty($user->id)) {
3744          return false;
3745      }
3746  
3747      if (!isset($discussion->groupid)) {
3748          debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
3749          return false;
3750      }
3751  
3752      if (!$cm) {
3753          debugging('missing cm', DEBUG_DEVELOPER);
3754          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3755              print_error('invalidcoursemodule');
3756          }
3757      }
3758  
3759      if (!$course) {
3760          debugging('missing course', DEBUG_DEVELOPER);
3761          if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
3762              print_error('invalidcourseid');
3763          }
3764      }
3765  
3766      if (!$context) {
3767          $context = context_module::instance($cm->id);
3768      }
3769  
3770      if (forum_is_cutoff_date_reached($forum)) {
3771          if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3772              return false;
3773          }
3774      }
3775  
3776      // Check whether the discussion is locked.
3777      if (forum_discussion_is_locked($forum, $discussion)) {
3778          if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
3779              return false;
3780          }
3781      }
3782  
3783      // normal users with temporary guest access can not post, suspended users can not post either
3784      if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
3785          return false;
3786      }
3787  
3788      if ($forum->type == 'news') {
3789          $capname = 'mod/forum:replynews';
3790      } else {
3791          $capname = 'mod/forum:replypost';
3792      }
3793  
3794      if (!has_capability($capname, $context, $user->id)) {
3795          return false;
3796      }
3797  
3798      if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
3799          return true;
3800      }
3801  
3802      if (has_capability('moodle/site:accessallgroups', $context)) {
3803          return true;
3804      }
3805  
3806      if ($groupmode == VISIBLEGROUPS) {
3807          if ($discussion->groupid == -1) {
3808              // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
3809              return true;
3810          }
3811          return groups_is_member($discussion->groupid);
3812  
3813      } else {
3814          //separate groups
3815          if ($discussion->groupid == -1) {
3816              return false;
3817          }
3818          return groups_is_member($discussion->groupid);
3819      }
3820  }
3821  
3822  /**
3823  * Check to ensure a user can view a timed discussion.
3824  *
3825  * @param object $discussion
3826  * @param object $user
3827  * @param object $context
3828  * @return boolean returns true if they can view post, false otherwise
3829  */
3830  function forum_user_can_see_timed_discussion($discussion, $user, $context) {
3831      global $CFG;
3832  
3833      // Check that the user can view a discussion that is normally hidden due to access times.
3834      if (!empty($CFG->forum_enabletimedposts)) {
3835          $time = time();
3836          if (($discussion->timestart != 0 && $discussion->timestart > $time)
3837              || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
3838              if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
3839                  return false;
3840              }
3841          }
3842      }
3843  
3844      return true;
3845  }
3846  
3847  /**
3848  * Check to ensure a user can view a group discussion.
3849  *
3850  * @param object $discussion
3851  * @param object $cm
3852  * @param object $context
3853  * @return boolean returns true if they can view post, false otherwise
3854  */
3855  function forum_user_can_see_group_discussion($discussion, $cm, $context) {
3856  
3857      // If it's a grouped discussion, make sure the user is a member.
3858      if ($discussion->groupid > 0) {
3859          $groupmode = groups_get_activity_groupmode($cm);
3860          if ($groupmode == SEPARATEGROUPS) {
3861              return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
3862          }
3863      }
3864  
3865      return true;
3866  }
3867  
3868  /**
3869   * @global object
3870   * @global object
3871   * @uses DEBUG_DEVELOPER
3872   * @param object $forum
3873   * @param object $discussion
3874   * @param object $context
3875   * @param object $user
3876   * @return bool
3877   */
3878  function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
3879      global $USER, $DB;
3880  
3881      if (empty($user) || empty($user->id)) {
3882          $user = $USER;
3883      }
3884  
3885      // retrieve objects (yuk)
3886      if (is_numeric($forum)) {
3887          debugging('missing full forum', DEBUG_DEVELOPER);
3888          if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3889              return false;
3890          }
3891      }
3892      if (is_numeric($discussion)) {
3893          debugging('missing full discussion', DEBUG_DEVELOPER);
3894          if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3895              return false;
3896          }
3897      }
3898      if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3899          print_error('invalidcoursemodule');
3900      }
3901  
3902      if (!has_capability('mod/forum:viewdiscussion', $context)) {
3903          return false;
3904      }
3905  
3906      if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
3907          return false;
3908      }
3909  
3910      if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
3911          return false;
3912      }
3913  
3914      return true;
3915  }
3916  
3917  /**
3918   * Check whether a user can see the specified post.
3919   *
3920   * @param   \stdClass $forum The forum to chcek
3921   * @param   \stdClass $discussion The discussion the post is in
3922   * @param   \stdClass $post The post in question
3923   * @param   \stdClass $user The user to test - if not specified, the current user is checked.
3924   * @param   \stdClass $cm The Course Module that the forum is in (required).
3925   * @param   bool      $checkdeleted Whether to check the deleted flag on the post.
3926   * @return  bool
3927   */
3928  function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) {
3929      global $CFG, $USER, $DB;
3930  
3931      // retrieve objects (yuk)
3932      if (is_numeric($forum)) {
3933          debugging('missing full forum', DEBUG_DEVELOPER);
3934          if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3935              return false;
3936          }
3937      }
3938  
3939      if (is_numeric($discussion)) {
3940          debugging('missing full discussion', DEBUG_DEVELOPER);
3941          if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3942              return false;
3943          }
3944      }
3945      if (is_numeric($post)) {
3946          debugging('missing full post', DEBUG_DEVELOPER);
3947          if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
3948              return false;
3949          }
3950      }
3951  
3952      if (!isset($post->id) && isset($post->parent)) {
3953          $post->id = $post->parent;
3954      }
3955  
3956      if ($checkdeleted && !empty($post->deleted)) {
3957          return false;
3958      }
3959  
3960      if (!$cm) {
3961          debugging('missing cm', DEBUG_DEVELOPER);
3962          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3963              print_error('invalidcoursemodule');
3964          }
3965      }
3966  
3967      // Context used throughout function.
3968      $modcontext = context_module::instance($cm->id);
3969  
3970      if (empty($user) || empty($user->id)) {
3971          $user = $USER;
3972      }
3973  
3974      $canviewdiscussion = (isset($cm->cache) && !empty($cm->cache->caps['mod/forum:viewdiscussion']))
3975          || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
3976      if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
3977          return false;
3978      }
3979  
3980      if (!forum_post_is_visible_privately($post, $cm)) {
3981          return false;
3982      }
3983  
3984      if (isset($cm->uservisible)) {
3985          if (!$cm->uservisible) {
3986              return false;
3987          }
3988      } else {
3989          if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
3990              return false;
3991          }
3992      }
3993  
3994      if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
3995          return false;
3996      }
3997  
3998      if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
3999          return false;
4000      }
4001  
4002      if ($forum->type == 'qanda') {
4003          if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id) || $post->userid == $user->id
4004                  || (isset($discussion->firstpost) && $discussion->firstpost == $post->id)) {
4005              return true;
4006          }
4007          $firstpost = forum_get_firstpost_from_discussion($discussion->id);
4008          if ($firstpost->userid == $user->id) {
4009              return true;
4010          }
4011          $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
4012          return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)));
4013      }
4014      return true;
4015  }
4016  
4017  /**
4018   * Returns all forum posts since a given time in specified forum.
4019   *
4020   * @todo Document this functions args
4021   * @global object
4022   * @global object
4023   * @global object
4024   * @global object
4025   */
4026  function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
4027      global $CFG, $COURSE, $USER, $DB;
4028  
4029      if ($COURSE->id == $courseid) {
4030          $course = $COURSE;
4031      } else {
4032          $course = $DB->get_record('course', array('id' => $courseid));
4033      }
4034  
4035      $modinfo = get_fast_modinfo($course);
4036  
4037      $cm = $modinfo->cms[$cmid];
4038      $params = array($timestart, $cm->instance);
4039  
4040      if ($userid) {
4041          $userselect = "AND u.id = ?";
4042          $params[] = $userid;
4043      } else {
4044          $userselect = "";
4045      }
4046  
4047      if ($groupid) {
4048          $groupselect = "AND d.groupid = ?";
4049          $params[] = $groupid;
4050      } else {
4051          $groupselect = "";
4052      }
4053  
4054      $userfieldsapi = \core_user\fields::for_name();
4055      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4056      if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
4057                                                d.timestart, d.timeend, d.userid AS duserid,
4058                                                $allnames, u.email, u.picture, u.imagealt, u.email
4059                                           FROM {forum_posts} p
4060                                                JOIN {forum_discussions} d ON d.id = p.discussion
4061                                                JOIN {forum} f             ON f.id = d.forum
4062                                                JOIN {user} u              ON u.id = p.userid
4063                                          WHERE p.created > ? AND f.id = ?
4064                                                $userselect $groupselect
4065                                       ORDER BY p.id ASC", $params)) { // order by initial posting date
4066           return;
4067      }
4068  
4069      $groupmode       = groups_get_activity_groupmode($cm, $course);
4070      $cm_context      = context_module::instance($cm->id);
4071      $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
4072      $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
4073  
4074      $printposts = array();
4075      foreach ($posts as $post) {
4076  
4077          if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
4078            and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
4079              if (!$viewhiddentimed) {
4080                  continue;
4081              }
4082          }
4083  
4084          if ($groupmode) {
4085              if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
4086                  // oki (Open discussions have groupid -1)
4087              } else {
4088                  // separate mode
4089                  if (isguestuser()) {
4090                      // shortcut
4091                      continue;
4092                  }
4093  
4094                  if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
4095                      continue;
4096                  }
4097              }
4098          }
4099  
4100          $printposts[] = $post;
4101      }
4102  
4103      if (!$printposts) {
4104          return;
4105      }
4106  
4107      $aname = format_string($cm->name,true);
4108  
4109      foreach ($printposts as $post) {
4110          $tmpactivity = new stdClass();
4111  
4112          $tmpactivity->type         = 'forum';
4113          $tmpactivity->cmid         = $cm->id;
4114          $tmpactivity->name         = $aname;
4115          $tmpactivity->sectionnum   = $cm->sectionnum;
4116          $tmpactivity->timestamp    = $post->modified;
4117  
4118          $tmpactivity->content = new stdClass();
4119          $tmpactivity->content->id         = $post->id;
4120          $tmpactivity->content->discussion = $post->discussion;
4121          $tmpactivity->content->subject    = format_string($post->subject);
4122          $tmpactivity->content->parent     = $post->parent;
4123          $tmpactivity->content->forumtype  = $post->forumtype;
4124  
4125          $tmpactivity->user = new stdClass();
4126          $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
4127          $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
4128          $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
4129          $tmpactivity->user->id = $post->userid;
4130  
4131          $activities[$index++] = $tmpactivity;
4132      }
4133  
4134      return;
4135  }
4136  
4137  /**
4138   * Outputs the forum post indicated by $activity.
4139   *
4140   * @param object $activity      the activity object the forum resides in
4141   * @param int    $courseid      the id of the course the forum resides in
4142   * @param bool   $detail        not used, but required for compatibilty with other modules
4143   * @param int    $modnames      not used, but required for compatibilty with other modules
4144   * @param bool   $viewfullnames not used, but required for compatibilty with other modules
4145   */
4146  function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
4147      global $OUTPUT;
4148  
4149      $content = $activity->content;
4150      if ($content->parent) {
4151          $class = 'reply';
4152      } else {
4153          $class = 'discussion';
4154      }
4155  
4156      $tableoptions = [
4157          'border' => '0',
4158          'cellpadding' => '3',
4159          'cellspacing' => '0',
4160          'class' => 'forum-recent'
4161      ];
4162      $output = html_writer::start_tag('table', $tableoptions);
4163      $output .= html_writer::start_tag('tr');
4164  
4165      $post = (object) ['parent' => $content->parent];
4166      $forum = (object) ['type' => $content->forumtype];
4167      $authorhidden = forum_is_author_hidden($post, $forum);
4168  
4169      // Show user picture if author should not be hidden.
4170      if (!$authorhidden) {
4171          $pictureoptions = [
4172              'courseid' => $courseid,
4173              'link' => $authorhidden,
4174              'alttext' => $authorhidden,
4175          ];
4176          $picture = $OUTPUT->user_picture($activity->user, $pictureoptions);
4177          $output .= html_writer::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
4178      }
4179  
4180      // Discussion title and author.
4181      $output .= html_writer::start_tag('td', ['class' => $class]);
4182      if ($content->parent) {
4183          $class = 'title';
4184      } else {
4185          // Bold the title of new discussions so they stand out.
4186          $class = 'title bold';
4187      }
4188  
4189      $output .= html_writer::start_div($class);
4190      if ($detail) {
4191          $aname = s($activity->name);
4192          $output .= $OUTPUT->image_icon('icon', $aname, $activity->type);
4193      }
4194      $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion]);
4195      $discussionurl->set_anchor('p' . $activity->content->id);
4196      $output .= html_writer::link($discussionurl, $content->subject);
4197      $output .= html_writer::end_div();
4198  
4199      $timestamp = userdate_htmltime($activity->timestamp);
4200      if ($authorhidden) {
4201          $authornamedate = $timestamp;
4202      } else {
4203          $fullname = fullname($activity->user, $viewfullnames);
4204          $userurl = new moodle_url('/user/view.php');
4205          $userurl->params(['id' => $activity->user->id, 'course' => $courseid]);
4206          $by = new stdClass();
4207          $by->name = html_writer::link($userurl, $fullname);
4208          $by->date = $timestamp;
4209          $authornamedate = get_string('bynameondate', 'forum', $by);
4210      }
4211      $output .= html_writer::div($authornamedate, 'user');
4212      $output .= html_writer::end_tag('td');
4213      $output .= html_writer::end_tag('tr');
4214      $output .= html_writer::end_tag('table');
4215  
4216      echo $output;
4217  }
4218  
4219  /**
4220   * recursively sets the discussion field to $discussionid on $postid and all its children
4221   * used when pruning a post
4222   *
4223   * @global object
4224   * @param int $postid
4225   * @param int $discussionid
4226   * @return bool
4227   */
4228  function forum_change_discussionid($postid, $discussionid) {
4229      global $DB;
4230      $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
4231      if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
4232          foreach ($posts as $post) {
4233              forum_change_discussionid($post->id, $discussionid);
4234          }
4235      }
4236      return true;
4237  }
4238  
4239  /**
4240   * Prints the editing button on subscribers page
4241   *
4242   * @global object
4243   * @global object
4244   * @param int $courseid
4245   * @param int $forumid
4246   * @return string
4247   */
4248  function forum_update_subscriptions_button($courseid, $forumid) {
4249      global $CFG, $USER;
4250  
4251      if (!empty($USER->subscriptionsediting)) {
4252          $string = get_string('managesubscriptionsoff', 'forum');
4253          $edit = "off";
4254      } else {
4255          $string = get_string('managesubscriptionson', 'forum');
4256          $edit = "on";
4257      }
4258  
4259      $subscribers = html_writer::start_tag('form', array('action' => $CFG->wwwroot . '/mod/forum/subscribers.php',
4260          'method' => 'get', 'class' => 'form-inline'));
4261      $subscribers .= html_writer::empty_tag('input', array('type' => 'submit', 'value' => $string,
4262          'class' => 'btn btn-secondary'));
4263      $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $forumid));
4264      $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'edit', 'value' => $edit));
4265      $subscribers .= html_writer::end_tag('form');
4266  
4267      return $subscribers;
4268  }
4269  
4270  // Functions to do with read tracking.
4271  
4272  /**
4273   * Mark posts as read.
4274   *
4275   * @global object
4276   * @global object
4277   * @param object $user object
4278   * @param array $postids array of post ids
4279   * @return boolean success
4280   */
4281  function forum_tp_mark_posts_read($user, $postids) {
4282      global $CFG, $DB;
4283  
4284      if (!forum_tp_can_track_forums(false, $user)) {
4285          return true;
4286      }
4287  
4288      $status = true;
4289  
4290      $now = time();
4291      $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
4292  
4293      if (empty($postids)) {
4294          return true;
4295  
4296      } else if (count($postids) > 200) {
4297          while ($part = array_splice($postids, 0, 200)) {
4298              $status = forum_tp_mark_posts_read($user, $part) && $status;
4299          }
4300          return $status;
4301      }
4302  
4303      list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid');
4304  
4305      $insertparams = array(
4306          'userid1' => $user->id,
4307          'userid2' => $user->id,
4308          'userid3' => $user->id,
4309          'firstread' => $now,
4310          'lastread' => $now,
4311          'cutoffdate' => $cutoffdate,
4312      );
4313      $params = array_merge($postidparams, $insertparams);
4314  
4315      if ($CFG->forum_allowforcedreadtracking) {
4316          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
4317                          OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))";
4318      } else {
4319          $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL."  OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4320                              AND tf.id IS NULL)";
4321      }
4322  
4323      // First insert any new entries.
4324      $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4325  
4326              SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
4327                  FROM {forum_posts} p
4328                      JOIN {forum_discussions} d       ON d.id = p.discussion
4329                      JOIN {forum} f                   ON f.id = d.forum
4330                      LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
4331                      LEFT JOIN {forum_read} fr        ON (
4332                              fr.userid = :userid3
4333                          AND fr.postid = p.id
4334                          AND fr.discussionid = d.id
4335                          AND fr.forumid = f.id
4336                      )
4337                  WHERE p.id $usql
4338                      AND p.modified >= :cutoffdate
4339                      $trackingsql
4340                      AND fr.id IS NULL";
4341  
4342      $status = $DB->execute($sql, $params) && $status;
4343  
4344      // Then update all records.
4345      $updateparams = array(
4346          'userid' => $user->id,
4347          'lastread' => $now,
4348      );
4349      $params = array_merge($postidparams, $updateparams);
4350      $status = $DB->set_field_select('forum_read', 'lastread', $now, '
4351                  userid      =  :userid
4352              AND lastread    <> :lastread
4353              AND postid      ' . $usql,
4354              $params) && $status;
4355  
4356      return $status;
4357  }
4358  
4359  /**
4360   * Mark post as read.
4361   * @global object
4362   * @global object
4363   * @param int $userid
4364   * @param int $postid
4365   */
4366  function forum_tp_add_read_record($userid, $postid) {
4367      global $CFG, $DB;
4368  
4369      $now = time();
4370      $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
4371  
4372      if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
4373          $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4374  
4375                  SELECT ?, p.id, p.discussion, d.forum, ?, ?
4376                    FROM {forum_posts} p
4377                         JOIN {forum_discussions} d ON d.id = p.discussion
4378                   WHERE p.id = ? AND p.modified >= ?";
4379          return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
4380  
4381      } else {
4382          $sql = "UPDATE {forum_read}
4383                     SET lastread = ?
4384                   WHERE userid = ? AND postid = ?";
4385          return $DB->execute($sql, array($now, $userid, $userid));
4386      }
4387  }
4388  
4389  /**
4390   * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
4391   *
4392   * @param   int     $userid The ID of the user to mark posts read for.
4393   * @param   object  $post   The post record for the post to mark as read.
4394   * @param   mixed   $unused
4395   * @return bool
4396   */
4397  function forum_tp_mark_post_read($userid, $post, $unused = null) {
4398      if (!forum_tp_is_post_old($post)) {
4399          return forum_tp_add_read_record($userid, $post->id);
4400      } else {
4401          return true;
4402      }
4403  }
4404  
4405  /**
4406   * Marks a whole forum as read, for a given user
4407   *
4408   * @global object
4409   * @global object
4410   * @param object $user
4411   * @param int $forumid
4412   * @param int|bool $groupid
4413   * @return bool
4414   */
4415  function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
4416      global $CFG, $DB;
4417  
4418      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4419  
4420      $groupsel = "";
4421      $params = array($user->id, $forumid, $cutoffdate);
4422  
4423      if ($groupid !== false) {
4424          $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
4425          $params[] = $groupid;
4426      }
4427  
4428      $sql = "SELECT p.id
4429                FROM {forum_posts} p
4430                     LEFT JOIN {forum_discussions} d ON d.id = p.discussion
4431                     LEFT JOIN {forum_read} r        ON (r.postid = p.id AND r.userid = ?)
4432               WHERE d.forum = ?
4433                     AND p.modified >= ? AND r.id is NULL
4434                     $groupsel";
4435  
4436      if ($posts = $DB->get_records_sql($sql, $params)) {
4437          $postids = array_keys($posts);
4438          return forum_tp_mark_posts_read($user, $postids);
4439      }
4440  
4441      return true;
4442  }
4443  
4444  /**
4445   * Marks a whole discussion as read, for a given user
4446   *
4447   * @global object
4448   * @global object
4449   * @param object $user
4450   * @param int $discussionid
4451   * @return bool
4452   */
4453  function forum_tp_mark_discussion_read($user, $discussionid) {
4454      global $CFG, $DB;
4455  
4456      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4457  
4458      $sql = "SELECT p.id
4459                FROM {forum_posts} p
4460                     LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
4461               WHERE p.discussion = ?
4462                     AND p.modified >= ? AND r.id is NULL";
4463  
4464      if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) {
4465          $postids = array_keys($posts);
4466          return forum_tp_mark_posts_read($user, $postids);
4467      }
4468  
4469      return true;
4470  }
4471  
4472  /**
4473   * @global object
4474   * @param int $userid
4475   * @param object $post
4476   */
4477  function forum_tp_is_post_read($userid, $post) {
4478      global $DB;
4479      return (forum_tp_is_post_old($post) ||
4480              $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id)));
4481  }
4482  
4483  /**
4484   * @global object
4485   * @param object $post
4486   * @param int $time Defautls to time()
4487   */
4488  function forum_tp_is_post_old($post, $time=null) {
4489      global $CFG;
4490  
4491      if (is_null($time)) {
4492          $time = time();
4493      }
4494      return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600)));
4495  }
4496  
4497  /**
4498   * Returns the count of records for the provided user and course.
4499   * Please note that group access is ignored!
4500   *
4501   * @global object
4502   * @global object
4503   * @param int $userid
4504   * @param int $courseid
4505   * @return array
4506   */
4507  function forum_tp_get_course_unread_posts($userid, $courseid) {
4508      global $CFG, $DB;
4509  
4510      $modinfo = get_fast_modinfo($courseid);
4511      $forumcms = $modinfo->get_instances_of('forum');
4512      if (empty($forumcms)) {
4513          // Return early if the course doesn't have any forum. Will save us a DB query.
4514          return [];
4515      }
4516  
4517      $now = floor(time() / MINSECS) * MINSECS; // DB cache friendliness.
4518      $cutoffdate = $now - ($CFG->forum_oldpostdays * DAYSECS);
4519      $params = [
4520          'privatereplyto' => $userid,
4521          'modified' => $cutoffdate,
4522          'readuserid' => $userid,
4523          'trackprefsuser' => $userid,
4524          'courseid' => $courseid,
4525          'trackforumuser' => $userid,
4526      ];
4527  
4528      if (!empty($CFG->forum_enabletimedposts)) {
4529          $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4530          $params['timestart'] = $now;
4531          $params['timeend'] = $now;
4532      } else {
4533          $timedsql = "";
4534      }
4535  
4536      if ($CFG->forum_allowforcedreadtracking) {
4537          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
4538                              OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL
4539                                  AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1))";
4540      } else {
4541          $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4542                              AND tf.id IS NULL
4543                              AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1)";
4544      }
4545  
4546      $sql = "SELECT f.id, COUNT(p.id) AS unread,
4547                     COUNT(p.privatereply) as privatereplies,
4548                     COUNT(p.privatereplytouser) as privaterepliestouser
4549                FROM (
4550                          SELECT
4551                              id,
4552                              discussion,
4553                              CASE WHEN privatereplyto <> 0 THEN 1 END privatereply,
4554                              CASE WHEN privatereplyto = :privatereplyto THEN 1 END privatereplytouser
4555                          FROM {forum_posts}
4556                          WHERE modified >= :modified
4557                     ) p
4558                     JOIN {forum_discussions} d       ON d.id = p.discussion
4559                     JOIN {forum} f                   ON f.id = d.forum
4560                     JOIN {course} c                  ON c.id = f.course
4561                     LEFT JOIN {forum_read} r         ON (r.postid = p.id AND r.userid = :readuserid)
4562                     LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :trackprefsuser AND tf.forumid = f.id)
4563               WHERE f.course = :courseid
4564                     AND r.id is NULL
4565                     $trackingsql
4566                     $timedsql
4567            GROUP BY f.id";
4568  
4569      $results = [];
4570      if ($records = $DB->get_records_sql($sql, $params)) {
4571          // Loop through each forum instance to check for capability and count the number of unread posts.
4572          foreach ($forumcms as $cm) {
4573              // Check that the forum instance exists in the query results.
4574              if (!isset($records[$cm->instance])) {
4575                  continue;
4576              }
4577  
4578              $record = $records[$cm->instance];
4579              $unread = $record->unread;
4580  
4581              // Check if the user has the capability to read private replies for this forum instance.
4582              $forumcontext = context_module::instance($cm->id);
4583              if (!has_capability('mod/forum:readprivatereplies', $forumcontext, $userid)) {
4584                  // The real unread count would be the total of unread count minus the number of unread private replies plus
4585                  // the total unread private replies to the user.
4586                  $unread = $record->unread - $record->privatereplies + $record->privaterepliestouser;
4587              }
4588  
4589              // Build and add the object to the array of results to be returned.
4590              $results[$record->id] = (object)[
4591                  'id' => $record->id,
4592                  'unread' => $unread,
4593              ];
4594          }
4595      }
4596  
4597      return $results;
4598  }
4599  
4600  /**
4601   * Returns the count of records for the provided user and forum and [optionally] group.
4602   *
4603   * @global object
4604   * @global object
4605   * @global object
4606   * @param object $cm
4607   * @param object $course
4608   * @param bool   $resetreadcache optional, true to reset the function static $readcache var
4609   * @return int
4610   */
4611  function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) {
4612      global $CFG, $USER, $DB;
4613  
4614      static $readcache = array();
4615  
4616      if ($resetreadcache) {
4617          $readcache = array();
4618      }
4619  
4620      $forumid = $cm->instance;
4621  
4622      if (!isset($readcache[$course->id])) {
4623          $readcache[$course->id] = array();
4624          if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
4625              foreach ($counts as $count) {
4626                  $readcache[$course->id][$count->id] = $count->unread;
4627              }
4628          }
4629      }
4630  
4631      if (empty($readcache[$course->id][$forumid])) {
4632          // no need to check group mode ;-)
4633          return 0;
4634      }
4635  
4636      $groupmode = groups_get_activity_groupmode($cm, $course);
4637  
4638      if ($groupmode != SEPARATEGROUPS) {
4639          return $readcache[$course->id][$forumid];
4640      }
4641  
4642      $forumcontext = context_module::instance($cm->id);
4643      if (has_any_capability(['moodle/site:accessallgroups', 'mod/forum:readprivatereplies'], $forumcontext)) {
4644          return $readcache[$course->id][$forumid];
4645      }
4646  
4647      require_once($CFG->dirroot.'/course/lib.php');
4648  
4649      $modinfo = get_fast_modinfo($course);
4650  
4651      $mygroups = $modinfo->get_groups($cm->groupingid);
4652  
4653      // add all groups posts
4654      $mygroups[-1] = -1;
4655  
4656      list ($groupssql, $groupsparams) = $DB->get_in_or_equal($mygroups, SQL_PARAMS_NAMED);
4657  
4658      $now = floor(time() / MINSECS) * MINSECS; // DB Cache friendliness.
4659      $cutoffdate = $now - ($CFG->forum_oldpostdays * DAYSECS);
4660      $params = [
4661          'readuser' => $USER->id,
4662          'forum' => $forumid,
4663          'cutoffdate' => $cutoffdate,
4664          'privatereplyto' => $USER->id,
4665      ];
4666  
4667      if (!empty($CFG->forum_enabletimedposts)) {
4668          $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4669          $params['timestart'] = $now;
4670          $params['timeend'] = $now;
4671      } else {
4672          $timedsql = "";
4673      }
4674  
4675      $params = array_merge($params, $groupsparams);
4676  
4677      $sql = "SELECT COUNT(p.id)
4678                FROM {forum_posts} p
4679                JOIN {forum_discussions} d ON p.discussion = d.id
4680           LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = :readuser)
4681               WHERE d.forum = :forum
4682                     AND p.modified >= :cutoffdate AND r.id is NULL
4683                     $timedsql
4684                     AND d.groupid $groupssql
4685                     AND (p.privatereplyto = 0 OR p.privatereplyto = :privatereplyto)";
4686  
4687      return $DB->get_field_sql($sql, $params);
4688  }
4689  
4690  /**
4691   * Deletes read records for the specified index. At least one parameter must be specified.
4692   *
4693   * @global object
4694   * @param int $userid
4695   * @param int $postid
4696   * @param int $discussionid
4697   * @param int $forumid
4698   * @return bool
4699   */
4700  function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
4701      global $DB;
4702      $params = array();
4703  
4704      $select = '';
4705      if ($userid > -1) {
4706          if ($select != '') $select .= ' AND ';
4707          $select .= 'userid = ?';
4708          $params[] = $userid;
4709      }
4710      if ($postid > -1) {
4711          if ($select != '') $select .= ' AND ';
4712          $select .= 'postid = ?';
4713          $params[] = $postid;
4714      }
4715      if ($discussionid > -1) {
4716          if ($select != '') $select .= ' AND ';
4717          $select .= 'discussionid = ?';
4718          $params[] = $discussionid;
4719      }
4720      if ($forumid > -1) {
4721          if ($select != '') $select .= ' AND ';
4722          $select .= 'forumid = ?';
4723          $params[] = $forumid;
4724      }
4725      if ($select == '') {
4726          return false;
4727      }
4728      else {
4729          return $DB->delete_records_select('forum_read', $select, $params);
4730      }
4731  }
4732  /**
4733   * Get a list of forums not tracked by the user.
4734   *
4735   * @global object
4736   * @global object
4737   * @param int $userid The id of the user to use.
4738   * @param int $courseid The id of the course being checked.
4739   * @return mixed An array indexed by forum id, or false.
4740   */
4741  function forum_tp_get_untracked_forums($userid, $courseid) {
4742      global $CFG, $DB;
4743  
4744      if ($CFG->forum_allowforcedreadtracking) {
4745          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
4746                              OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL
4747                                  OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4748      } else {
4749          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
4750                              OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4751                                  AND (ft.id IS NOT NULL
4752                                      OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4753      }
4754  
4755      $sql = "SELECT f.id
4756                FROM {forum} f
4757                     LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
4758               WHERE f.course = ?
4759                     $trackingsql";
4760  
4761      if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
4762          foreach ($forums as $forum) {
4763              $forums[$forum->id] = $forum;
4764          }
4765          return $forums;
4766  
4767      } else {
4768          return array();
4769      }
4770  }
4771  
4772  /**
4773   * Determine if a user can track forums and optionally a particular forum.
4774   * Checks the site settings, the user settings and the forum settings (if
4775   * requested).
4776   *
4777   * @global object
4778   * @global object
4779   * @global object
4780   * @param mixed $forum The forum object to test, or the int id (optional).
4781   * @param mixed $userid The user object to check for (optional).
4782   * @return boolean
4783   */
4784  function forum_tp_can_track_forums($forum=false, $user=false) {
4785      global $USER, $CFG, $DB;
4786  
4787      // if possible, avoid expensive
4788      // queries
4789      if (empty($CFG->forum_trackreadposts)) {
4790          return false;
4791      }
4792  
4793      if ($user === false) {
4794          $user = $USER;
4795      }
4796  
4797      if (isguestuser($user) or empty($user->id)) {
4798          return false;
4799      }
4800  
4801      if ($forum === false) {
4802          if ($CFG->forum_allowforcedreadtracking) {
4803              // Since we can force tracking, assume yes without a specific forum.
4804              return true;
4805          } else {
4806              return (bool)$user->trackforums;
4807          }
4808      }
4809  
4810      // Work toward always passing an object...
4811      if (is_numeric($forum)) {
4812          debugging('Better use proper forum object.', DEBUG_DEVELOPER);
4813          $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
4814      }
4815  
4816      $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
4817      $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
4818  
4819      if ($CFG->forum_allowforcedreadtracking) {
4820          // If we allow forcing, then forced forums takes procidence over user setting.
4821          return ($forumforced || ($forumallows  && (!empty($user->trackforums) && (bool)$user->trackforums)));
4822      } else {
4823          // If we don't allow forcing, user setting trumps.
4824          return ($forumforced || $forumallows)  && !empty($user->trackforums);
4825      }
4826  }
4827  
4828  /**
4829   * Tells whether a specific forum is tracked by the user. A user can optionally
4830   * be specified. If not specified, the current user is assumed.
4831   *
4832   * @global object
4833   * @global object
4834   * @global object
4835   * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
4836   * @param int $userid The id of the user being checked (optional).
4837   * @return boolean
4838   */
4839  function forum_tp_is_tracked($forum, $user=false) {
4840      global $USER, $CFG, $DB;
4841  
4842      if ($user === false) {
4843          $user = $USER;
4844      }
4845  
4846      if (isguestuser($user) or empty($user->id)) {
4847          return false;
4848      }
4849  
4850      $cache = cache::make('mod_forum', 'forum_is_tracked');
4851      $forumid = is_numeric($forum) ? $forum : $forum->id;
4852      $key = $forumid . '_' . $user->id;
4853      if ($cachedvalue = $cache->get($key)) {
4854          return $cachedvalue == 'tracked';
4855      }
4856  
4857      // Work toward always passing an object...
4858      if (is_numeric($forum)) {
4859          debugging('Better use proper forum object.', DEBUG_DEVELOPER);
4860          $forum = $DB->get_record('forum', array('id' => $forum));
4861      }
4862  
4863      if (!forum_tp_can_track_forums($forum, $user)) {
4864          return false;
4865      }
4866  
4867      $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
4868      $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
4869      $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id));
4870  
4871      if ($CFG->forum_allowforcedreadtracking) {
4872          $istracked = $forumforced || ($forumallows && $userpref === false);
4873      } else {
4874          $istracked = ($forumallows || $forumforced) && $userpref === false;
4875      }
4876  
4877      // We have to store a string here because the cache API returns false
4878      // when it can't find the key which would be confused with our legitimate
4879      // false value. *sigh*.
4880      $cache->set($key, $istracked ? 'tracked' : 'not');
4881  
4882      return $istracked;
4883  }
4884  
4885  /**
4886   * @global object
4887   * @global object
4888   * @param int $forumid
4889   * @param int $userid
4890   */
4891  function forum_tp_start_tracking($forumid, $userid=false) {
4892      global $USER, $DB;
4893  
4894      if ($userid === false) {
4895          $userid = $USER->id;
4896      }
4897  
4898      return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
4899  }
4900  
4901  /**
4902   * @global object
4903   * @global object
4904   * @param int $forumid
4905   * @param int $userid
4906   */
4907  function forum_tp_stop_tracking($forumid, $userid=false) {
4908      global $USER, $DB;
4909  
4910      if ($userid === false) {
4911          $userid = $USER->id;
4912      }
4913  
4914      if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
4915          $track_prefs = new stdClass();
4916          $track_prefs->userid = $userid;
4917          $track_prefs->forumid = $forumid;
4918          $DB->insert_record('forum_track_prefs', $track_prefs);
4919      }
4920  
4921      return forum_tp_delete_read_records($userid, -1, -1, $forumid);
4922  }
4923  
4924  
4925  /**
4926   * Clean old records from the forum_read table.
4927   * @global object
4928   * @global object
4929   * @return void
4930   */
4931  function forum_tp_clean_read_records() {
4932      global $CFG, $DB;
4933  
4934      if (!isset($CFG->forum_oldpostdays)) {
4935          return;
4936      }
4937  // Look for records older than the cutoffdate that are still in the forum_read table.
4938      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4939  
4940      //first get the oldest tracking present - we need tis to speedup the next delete query
4941      $sql = "SELECT MIN(fp.modified) AS first
4942                FROM {forum_posts} fp
4943                     JOIN {forum_read} fr ON fr.postid=fp.id";
4944      if (!$first = $DB->get_field_sql($sql)) {
4945          // nothing to delete;
4946          return;
4947      }
4948  
4949      // now delete old tracking info
4950      $sql = "DELETE
4951                FROM {forum_read}
4952               WHERE postid IN (SELECT fp.id
4953                                  FROM {forum_posts} fp
4954                                 WHERE fp.modified >= ? AND fp.modified < ?)";
4955      $DB->execute($sql, array($first, $cutoffdate));
4956  }
4957  
4958  /**
4959   * Sets the last post for a given discussion
4960   *
4961   * @global object
4962   * @global object
4963   * @param into $discussionid
4964   * @return bool|int
4965   **/
4966  function forum_discussion_update_last_post($discussionid) {
4967      global $CFG, $DB;
4968  
4969  // Check the given discussion exists
4970      if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
4971          return false;
4972      }
4973  
4974  // Use SQL to find the last post for this discussion
4975      $sql = "SELECT id, userid, modified
4976                FROM {forum_posts}
4977               WHERE discussion=?
4978               ORDER BY modified DESC";
4979  
4980  // Lets go find the last post
4981      if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
4982          $lastpost = reset($lastposts);
4983          $discussionobject = new stdClass();
4984          $discussionobject->id           = $discussionid;
4985          $discussionobject->usermodified = $lastpost->userid;
4986          $discussionobject->timemodified = $lastpost->modified;
4987          $DB->update_record('forum_discussions', $discussionobject);
4988          return $lastpost->id;
4989      }
4990  
4991  // To get here either we couldn't find a post for the discussion (weird)
4992  // or we couldn't update the discussion record (weird x2)
4993      return false;
4994  }
4995  
4996  
4997  /**
4998   * List the actions that correspond to a view of this module.
4999   * This is used by the participation report.
5000   *
5001   * Note: This is not used by new logging system. Event with
5002   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
5003   *       be considered as view action.
5004   *
5005   * @return array
5006   */
5007  function forum_get_view_actions() {
5008      return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
5009  }
5010  
5011  /**
5012   * List the options for forum subscription modes.
5013   * This is used by the settings page and by the mod_form page.
5014   *
5015   * @return array
5016   */
5017  function forum_get_subscriptionmode_options() {
5018      $options = array();
5019      $options[FORUM_CHOOSESUBSCRIBE] = get_string('subscriptionoptional', 'forum');
5020      $options[FORUM_FORCESUBSCRIBE] = get_string('subscriptionforced', 'forum');
5021      $options[FORUM_INITIALSUBSCRIBE] = get_string('subscriptionauto', 'forum');
5022      $options[FORUM_DISALLOWSUBSCRIBE] = get_string('subscriptiondisabled', 'forum');
5023      return $options;
5024  }
5025  
5026  /**
5027   * List the actions that correspond to a post of this module.
5028   * This is used by the participation report.
5029   *
5030   * Note: This is not used by new logging system. Event with
5031   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
5032   *       will be considered as post action.
5033   *
5034   * @return array
5035   */
5036  function forum_get_post_actions() {
5037      return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
5038  }
5039  
5040  /**
5041   * Returns a warning object if a user has reached the number of posts equal to
5042   * the warning/blocking setting, or false if there is no warning to show.
5043   *
5044   * @param int|stdClass $forum the forum id or the forum object
5045   * @param stdClass $cm the course module
5046   * @return stdClass|bool returns an object with the warning information, else
5047   *         returns false if no warning is required.
5048   */
5049  function forum_check_throttling($forum, $cm = null) {
5050      global $CFG, $DB, $USER;
5051  
5052      if (is_numeric($forum)) {
5053          $forum = $DB->get_record('forum', ['id' => $forum], 'id, course, blockperiod, blockafter, warnafter', MUST_EXIST);
5054      }
5055  
5056      if (!is_object($forum) || !isset($forum->id) || !isset($forum->course)) {
5057          // The passed forum parameter is invalid. This can happen if:
5058          // - a non-object and non-numeric forum is passed; or
5059          // - the forum object does not have an ID or course attributes.
5060          // This is unlikely to happen with properly formed forum record fetched from the database,
5061          // so it's most likely a dev error if we hit such this case.
5062          throw new coding_exception('Invalid forum parameter passed');
5063      }
5064  
5065      if (empty($forum->blockafter)) {
5066          return false;
5067      }
5068  
5069      if (empty($forum->blockperiod)) {
5070          return false;
5071      }
5072  
5073      if (!$cm) {
5074          // Try to fetch the $cm object via get_fast_modinfo() so we don't incur DB reads.
5075          $modinfo = get_fast_modinfo($forum->course);
5076          $forumcms = $modinfo->get_instances_of('forum');
5077          foreach ($forumcms as $tmpcm) {
5078              if ($tmpcm->instance == $forum->id) {
5079                  $cm = $tmpcm;
5080                  break;
5081              }
5082          }
5083          // Last resort. Try to fetch via get_coursemodule_from_instance().
5084          if (!$cm) {
5085              $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST);
5086          }
5087      }
5088  
5089      $modcontext = context_module::instance($cm->id);
5090      if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
5091          return false;
5092      }
5093  
5094      // Get the number of posts in the last period we care about.
5095      $timenow = time();
5096      $timeafter = $timenow - $forum->blockperiod;
5097      $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
5098                                          JOIN {forum_discussions} d
5099                                          ON p.discussion = d.id WHERE d.forum = ?
5100                                          AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter));
5101  
5102      $a = new stdClass();
5103      $a->blockafter = $forum->blockafter;
5104      $a->numposts = $numposts;
5105      $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
5106  
5107      if ($forum->blockafter <= $numposts) {
5108          $warning = new stdClass();
5109          $warning->canpost = false;
5110          $warning->errorcode = 'forumblockingtoomanyposts';
5111          $warning->module = 'error';
5112          $warning->additional = $a;
5113          $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id;
5114  
5115          return $warning;
5116      }
5117  
5118      if ($forum->warnafter <= $numposts) {
5119          $warning = new stdClass();
5120          $warning->canpost = true;
5121          $warning->errorcode = 'forumblockingalmosttoomanyposts';
5122          $warning->module = 'forum';
5123          $warning->additional = $a;
5124          $warning->link = null;
5125  
5126          return $warning;
5127      }
5128  
5129      // No warning needs to be shown yet.
5130      return false;
5131  }
5132  
5133  /**
5134   * Throws an error if the user is no longer allowed to post due to having reached
5135   * or exceeded the number of posts specified in 'Post threshold for blocking'
5136   * setting.
5137   *
5138   * @since Moodle 2.5
5139   * @param stdClass $thresholdwarning the warning information returned
5140   *        from the function forum_check_throttling.
5141   */
5142  function forum_check_blocking_threshold($thresholdwarning) {
5143      if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
5144          print_error($thresholdwarning->errorcode,
5145                      $thresholdwarning->module,
5146                      $thresholdwarning->link,
5147                      $thresholdwarning->additional);
5148      }
5149  }
5150  
5151  
5152  /**
5153   * Removes all grades from gradebook
5154   *
5155   * @global object
5156   * @global object
5157   * @param int $courseid
5158   * @param string $type optional
5159   */
5160  function forum_reset_gradebook($courseid, $type='') {
5161      global $CFG, $DB;
5162  
5163      $wheresql = '';
5164      $params = array($courseid);
5165      if ($type) {
5166          $wheresql = "AND f.type=?";
5167          $params[] = $type;
5168      }
5169  
5170      $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
5171                FROM {forum} f, {course_modules} cm, {modules} m
5172               WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
5173  
5174      if ($forums = $DB->get_records_sql($sql, $params)) {
5175          foreach ($forums as $forum) {
5176              forum_grade_item_update($forum, 'reset', 'reset');
5177          }
5178      }
5179  }
5180  
5181  /**
5182   * This function is used by the reset_course_userdata function in moodlelib.
5183   * This function will remove all posts from the specified forum
5184   * and clean up any related data.
5185   *
5186   * @global object
5187   * @global object
5188   * @param $data the data submitted from the reset course.
5189   * @return array status array
5190   */
5191  function forum_reset_userdata($data) {
5192      global $CFG, $DB;
5193      require_once($CFG->dirroot.'/rating/lib.php');
5194  
5195      $componentstr = get_string('modulenameplural', 'forum');
5196      $status = array();
5197  
5198      $params = array($data->courseid);
5199  
5200      $removeposts = false;
5201      $typesql     = "";
5202      if (!empty($data->reset_forum_all)) {
5203          $removeposts = true;
5204          $typesstr    = get_string('resetforumsall', 'forum');
5205          $types       = array();
5206      } else if (!empty($data->reset_forum_types)){
5207          $removeposts = true;
5208          $types       = array();
5209          $sqltypes    = array();
5210          $forum_types_all = forum_get_forum_types_all();
5211          foreach ($data->reset_forum_types as $type) {
5212              if (!array_key_exists($type, $forum_types_all)) {
5213                  continue;
5214              }
5215              $types[] = $forum_types_all[$type];
5216              $sqltypes[] = $type;
5217          }
5218          if (!empty($sqltypes)) {
5219              list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
5220              $typesql = " AND f.type " . $typesql;
5221              $params = array_merge($params, $typeparams);
5222          }
5223          $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
5224      }
5225      $alldiscussionssql = "SELECT fd.id
5226                              FROM {forum_discussions} fd, {forum} f
5227                             WHERE f.course=? AND f.id=fd.forum";
5228  
5229      $allforumssql      = "SELECT f.id
5230                              FROM {forum} f
5231                             WHERE f.course=?";
5232  
5233      $allpostssql       = "SELECT fp.id
5234                              FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
5235                             WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
5236  
5237      $forumssql = $forums = $rm = null;
5238  
5239      // Check if we need to get additional data.
5240      if ($removeposts || !empty($data->reset_forum_ratings) || !empty($data->reset_forum_tags)) {
5241          // Set this up if we have to remove ratings.
5242          $rm = new rating_manager();
5243          $ratingdeloptions = new stdClass;
5244          $ratingdeloptions->component = 'mod_forum';
5245          $ratingdeloptions->ratingarea = 'post';
5246  
5247          // Get the forums for actions that require it.
5248          $forumssql = "$allforumssql $typesql";
5249          $forums = $DB->get_records_sql($forumssql, $params);
5250      }
5251  
5252      if ($removeposts) {
5253          $discussionssql = "$alldiscussionssql $typesql";
5254          $postssql       = "$allpostssql $typesql";
5255  
5256          // now get rid of all attachments
5257          $fs = get_file_storage();
5258          if ($forums) {
5259              foreach ($forums as $forumid=>$unused) {
5260                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5261                      continue;
5262                  }
5263                  $context = context_module::instance($cm->id);
5264                  $fs->delete_area_files($context->id, 'mod_forum', 'attachment');
5265                  $fs->delete_area_files($context->id, 'mod_forum', 'post');
5266  
5267                  //remove ratings
5268                  $ratingdeloptions->contextid = $context->id;
5269                  $rm->delete_ratings($ratingdeloptions);
5270  
5271                  core_tag_tag::delete_instances('mod_forum', null, $context->id);
5272              }
5273          }
5274  
5275          // first delete all read flags
5276          $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
5277  
5278          // remove tracking prefs
5279          $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
5280  
5281          // remove posts from queue
5282          $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
5283  
5284          // all posts - initial posts must be kept in single simple discussion forums
5285          $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
5286          $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql AND f.type <> 'single') AND parent = 0", $params); // now the initial posts for non single simple
5287  
5288          // finally all discussions except single simple forums
5289          $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
5290  
5291          // remove all grades from gradebook
5292          if (empty($data->reset_gradebook_grades)) {
5293              if (empty($types)) {
5294                  forum_reset_gradebook($data->courseid);
5295              } else {
5296                  foreach ($types as $type) {
5297                      forum_reset_gradebook($data->courseid, $type);
5298                  }
5299              }
5300          }
5301  
5302          $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
5303      }
5304  
5305      // remove all ratings in this course's forums
5306      if (!empty($data->reset_forum_ratings)) {
5307          if ($forums) {
5308              foreach ($forums as $forumid=>$unused) {
5309                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5310                      continue;
5311                  }
5312                  $context = context_module::instance($cm->id);
5313  
5314                  //remove ratings
5315                  $ratingdeloptions->contextid = $context->id;
5316                  $rm->delete_ratings($ratingdeloptions);
5317              }
5318          }
5319  
5320          // remove all grades from gradebook
5321          if (empty($data->reset_gradebook_grades)) {
5322              forum_reset_gradebook($data->courseid);
5323          }
5324      }
5325  
5326      // Remove all the tags.
5327      if (!empty($data->reset_forum_tags)) {
5328          if ($forums) {
5329              foreach ($forums as $forumid => $unused) {
5330                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5331                      continue;
5332                  }
5333  
5334                  $context = context_module::instance($cm->id);
5335                  core_tag_tag::delete_instances('mod_forum', null, $context->id);
5336              }
5337          }
5338  
5339          $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false);
5340      }
5341  
5342      // remove all digest settings unconditionally - even for users still enrolled in course.
5343      if (!empty($data->reset_forum_digests)) {
5344          $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
5345          $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
5346      }
5347  
5348      // remove all subscriptions unconditionally - even for users still enrolled in course
5349      if (!empty($data->reset_forum_subscriptions)) {
5350          $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
5351          $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
5352          $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
5353      }
5354  
5355      // remove all tracking prefs unconditionally - even for users still enrolled in course
5356      if (!empty($data->reset_forum_track_prefs)) {
5357          $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
5358          $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
5359      }
5360  
5361      /// updating dates - shift may be negative too
5362      if ($data->timeshift) {
5363          // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
5364          // See MDL-9367.
5365          shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
5366          $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
5367      }
5368  
5369      return $status;
5370  }
5371  
5372  /**
5373   * Called by course/reset.php
5374   *
5375   * @param $mform form passed by reference
5376   */
5377  function forum_reset_course_form_definition(&$mform) {
5378      $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
5379  
5380      $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
5381  
5382      $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
5383      $mform->setAdvanced('reset_forum_types');
5384      $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
5385  
5386      $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
5387      $mform->setAdvanced('reset_forum_digests');
5388  
5389      $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
5390      $mform->setAdvanced('reset_forum_subscriptions');
5391  
5392      $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
5393      $mform->setAdvanced('reset_forum_track_prefs');
5394      $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
5395  
5396      $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
5397      $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
5398  
5399      $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum'));
5400      $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked');
5401  }
5402  
5403  /**
5404   * Course reset form defaults.
5405   * @return array
5406   */
5407  function forum_reset_course_form_defaults($course) {
5408      return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
5409  }
5410  
5411  /**
5412   * Returns array of forum layout modes
5413   *
5414   * @param bool $useexperimentalui use experimental layout modes or not
5415   * @return array
5416   */
5417  function forum_get_layout_modes(bool $useexperimentalui = false) {
5418      $modes = [
5419          FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
5420          FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
5421          FORUM_MODE_THREADED   => get_string('modethreaded', 'forum')
5422      ];
5423  
5424      if ($useexperimentalui) {
5425          $modes[FORUM_MODE_NESTED_V2] = get_string('modenestedv2', 'forum');
5426      } else {
5427          $modes[FORUM_MODE_NESTED] = get_string('modenested', 'forum');
5428      }
5429  
5430      return $modes;
5431  }
5432  
5433  /**
5434   * Returns array of forum types chooseable on the forum editing form
5435   *
5436   * @return array
5437   */
5438  function forum_get_forum_types() {
5439      return array ('general'  => get_string('generalforum', 'forum'),
5440                    'eachuser' => get_string('eachuserforum', 'forum'),
5441                    'single'   => get_string('singleforum', 'forum'),
5442                    'qanda'    => get_string('qandaforum', 'forum'),
5443                    'blog'     => get_string('blogforum', 'forum'));
5444  }
5445  
5446  /**
5447   * Returns array of all forum layout modes
5448   *
5449   * @return array
5450   */
5451  function forum_get_forum_types_all() {
5452      return array ('news'     => get_string('namenews','forum'),
5453                    'social'   => get_string('namesocial','forum'),
5454                    'general'  => get_string('generalforum', 'forum'),
5455                    'eachuser' => get_string('eachuserforum', 'forum'),
5456                    'single'   => get_string('singleforum', 'forum'),
5457                    'qanda'    => get_string('qandaforum', 'forum'),
5458                    'blog'     => get_string('blogforum', 'forum'));
5459  }
5460  
5461  /**
5462   * Returns all other caps used in module
5463   *
5464   * @return array
5465   */
5466  function forum_get_extra_capabilities() {
5467      return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate'];
5468  }
5469  
5470  /**
5471   * Adds module specific settings to the settings block
5472   *
5473   * @param settings_navigation $settings The settings navigation object
5474   * @param navigation_node $forumnode The node to add module settings to
5475   */
5476  function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
5477      global $USER, $PAGE, $CFG, $DB, $OUTPUT;
5478  
5479      if (empty($PAGE->cm->context)) {
5480          $PAGE->cm->context = context_module::instance($PAGE->cm->instance);
5481      }
5482  
5483      $vaultfactory = mod_forum\local\container::get_vault_factory();
5484      $managerfactory = mod_forum\local\container::get_manager_factory();
5485      $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
5486      $forumvault = $vaultfactory->get_forum_vault();
5487      $forumentity = $forumvault->get_from_id($PAGE->cm->instance);
5488      $forumobject = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forumentity);
5489  
5490      $params = $PAGE->url->params();
5491      if (!empty($params['d'])) {
5492          $discussionid = $params['d'];
5493      }
5494  
5495      // Display all forum reports user has access to.
5496      if (isloggedin() && !isguestuser()) {
5497          $reportnames = array_keys(core_component::get_plugin_list('forumreport'));
5498  
5499          foreach ($reportnames as $reportname) {
5500              if (has_capability("forumreport/{$reportname}:view", $PAGE->cm->context)) {
5501                  $reportlinkparams = [
5502                      'courseid' => $forumobject->course,
5503                      'forumid' => $forumobject->id,
5504                  ];
5505                  $reportlink = new moodle_url("/mod/forum/report/{$reportname}/index.php", $reportlinkparams);
5506                  $forumnode->add(get_string('nodetitle', "forumreport_{$reportname}"), $reportlink, navigation_node::TYPE_CONTAINER);
5507              }
5508          }
5509      }
5510  
5511      // For some actions you need to be enrolled, being admin is not enough sometimes here.
5512      $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
5513      $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);
5514  
5515      $canmanage  = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context);
5516      $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject);
5517      $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) &&
5518              (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage);
5519  
5520      if ($canmanage) {
5521          $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);
5522          $mode->add_class('subscriptionmode');
5523  
5524          $allowchoice = $mode->add(get_string('subscriptionoptional', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_CHOOSESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
5525          $forceforever = $mode->add(get_string("subscriptionforced", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_FORCESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
5526          $forceinitially = $mode->add(get_string("subscriptionauto", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_INITIALSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
5527          $disallowchoice = $mode->add(get_string('subscriptiondisabled', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_DISALLOWSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
5528  
5529          switch ($subscriptionmode) {
5530              case FORUM_CHOOSESUBSCRIBE : // 0
5531                  $allowchoice->action = null;
5532                  $allowchoice->add_class('activesetting');
5533                  $allowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
5534                  break;
5535              case FORUM_FORCESUBSCRIBE : // 1
5536                  $forceforever->action = null;
5537                  $forceforever->add_class('activesetting');
5538                  $forceforever->icon = new pix_icon('t/selected', '', 'mod_forum');
5539                  break;
5540              case FORUM_INITIALSUBSCRIBE : // 2
5541                  $forceinitially->action = null;
5542                  $forceinitially->add_class('activesetting');
5543                  $forceinitially->icon = new pix_icon('t/selected', '', 'mod_forum');
5544                  break;
5545              case FORUM_DISALLOWSUBSCRIBE : // 3
5546                  $disallowchoice->action = null;
5547                  $disallowchoice->add_class('activesetting');
5548                  $disallowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
5549                  break;
5550          }
5551  
5552      } else if ($activeenrolled) {
5553  
5554          switch ($subscriptionmode) {
5555              case FORUM_CHOOSESUBSCRIBE : // 0
5556                  $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
5557                  break;
5558              case FORUM_FORCESUBSCRIBE : // 1
5559                  $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
5560                  break;
5561              case FORUM_INITIALSUBSCRIBE : // 2
5562                  $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
5563                  break;
5564              case FORUM_DISALLOWSUBSCRIBE : // 3
5565                  $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
5566                  break;
5567          }
5568      }
5569  
5570      if ($cansubscribe) {
5571          if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, null, $PAGE->cm)) {
5572              $linktext = get_string('unsubscribe', 'forum');
5573          } else {
5574              $linktext = get_string('subscribe', 'forum');
5575          }
5576          $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey()));
5577          $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
5578  
5579          if (isset($discussionid)) {
5580              if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, $discussionid, $PAGE->cm)) {
5581                  $linktext = get_string('unsubscribediscussion', 'forum');
5582              } else {
5583                  $linktext = get_string('subscribediscussion', 'forum');
5584              }
5585              $url = new moodle_url('/mod/forum/subscribe.php', array(
5586                      'id' => $forumobject->id,
5587                      'sesskey' => sesskey(),
5588                      'd' => $discussionid,
5589                      'returnurl' => $PAGE->url->out(),
5590                  ));
5591              $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
5592          }
5593      }
5594  
5595      if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){
5596          $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id));
5597          $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING);
5598      }
5599  
5600      if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
5601          if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL
5602                  || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) {
5603              if (forum_tp_is_tracked($forumobject)) {
5604                  $linktext = get_string('notrackforum', 'forum');
5605              } else {
5606                  $linktext = get_string('trackforum', 'forum');
5607              }
5608              $url = new moodle_url('/mod/forum/settracking.php', array(
5609                      'id' => $forumobject->id,
5610                      'sesskey' => sesskey(),
5611                  ));
5612              $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
5613          }
5614      }
5615  
5616      if (!isloggedin() && $PAGE->course->id == SITEID) {
5617          $userid = guest_user()->id;
5618      } else {
5619          $userid = $USER->id;
5620      }
5621  
5622      $hascourseaccess = ($PAGE->course->id == SITEID) || can_access_course($PAGE->course, $userid);
5623      $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds);
5624  
5625      if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) {
5626  
5627          if (!function_exists('rss_get_url')) {
5628              require_once("$CFG->libdir/rsslib.php");
5629          }
5630  
5631          if ($forumobject->rsstype == 1) {
5632              $string = get_string('rsssubscriberssdiscussions','forum');
5633          } else {
5634              $string = get_string('rsssubscriberssposts','forum');
5635          }
5636  
5637          $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id));
5638          $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
5639      }
5640  
5641      $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
5642      if ($capabilitymanager->can_export_forum($USER)) {
5643          $url = new moodle_url('/mod/forum/export.php', ['id' => $forumobject->id]);
5644          $forumnode->add(get_string('export', 'mod_forum'), $url, navigation_node::TYPE_SETTING);
5645      }
5646  }
5647  
5648  /**
5649   * Adds information about unread messages, that is only required for the course view page (and
5650   * similar), to the course-module object.
5651   * @param cm_info $cm Course-module object
5652   */
5653  function forum_cm_info_view(cm_info $cm) {
5654      global $CFG;
5655  
5656      if (forum_tp_can_track_forums()) {
5657          if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
5658              $out = '<span class="unread"> <a href="' . $cm->url . '#unread">';
5659              if ($unread == 1) {
5660                  $out .= get_string('unreadpostsone', 'forum');
5661              } else {
5662                  $out .= get_string('unreadpostsnumber', 'forum', $unread);
5663              }
5664              $out .= '</a></span>';
5665              $cm->set_after_link($out);
5666          }
5667      }
5668  }
5669  
5670  /**
5671   * Return a list of page types
5672   * @param string $pagetype current page type
5673   * @param stdClass $parentcontext Block's parent context
5674   * @param stdClass $currentcontext Current context of block
5675   */
5676  function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
5677      $forum_pagetype = array(
5678          'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
5679          'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
5680          'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
5681      );
5682      return $forum_pagetype;
5683  }
5684  
5685  /**
5686   * Gets all of the courses where the provided user has posted in a forum.
5687   *
5688   * @global moodle_database $DB The database connection
5689   * @param stdClass $user The user who's posts we are looking for
5690   * @param bool $discussionsonly If true only look for discussions started by the user
5691   * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
5692   * @param int $limitfrom The offset of records to return
5693   * @param int $limitnum The number of records to return
5694   * @return array An array of courses
5695   */
5696  function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
5697      global $DB;
5698  
5699      // If we are only after discussions we need only look at the forum_discussions
5700      // table and join to the userid there. If we are looking for posts then we need
5701      // to join to the forum_posts table.
5702      if (!$discussionsonly) {
5703          $subquery = "(SELECT DISTINCT fd.course
5704                           FROM {forum_discussions} fd
5705                           JOIN {forum_posts} fp ON fp.discussion = fd.id
5706                          WHERE fp.userid = :userid )";
5707      } else {
5708          $subquery= "(SELECT DISTINCT fd.course
5709                           FROM {forum_discussions} fd
5710                          WHERE fd.userid = :userid )";
5711      }
5712  
5713      $params = array('userid' => $user->id);
5714  
5715      // Join to the context table so that we can preload contexts if required.
5716      if ($includecontexts) {
5717          $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
5718          $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
5719          $params['contextlevel'] = CONTEXT_COURSE;
5720      } else {
5721          $ctxselect = '';
5722          $ctxjoin = '';
5723      }
5724  
5725      // Now we need to get all of the courses to search.
5726      // All courses where the user has posted within a forum will be returned.
5727      $sql = "SELECT c.* $ctxselect
5728              FROM {course} c
5729              $ctxjoin
5730              WHERE c.id IN ($subquery)";
5731      $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5732      if ($includecontexts) {
5733          array_map('context_helper::preload_from_record', $courses);
5734      }
5735      return $courses;
5736  }
5737  
5738  /**
5739   * Gets all of the forums a user has posted in for one or more courses.
5740   *
5741   * @global moodle_database $DB
5742   * @param stdClass $user
5743   * @param array $courseids An array of courseids to search or if not provided
5744   *                       all courses the user has posted within
5745   * @param bool $discussionsonly If true then only forums where the user has started
5746   *                       a discussion will be returned.
5747   * @param int $limitfrom The offset of records to return
5748   * @param int $limitnum The number of records to return
5749   * @return array An array of forums the user has posted within in the provided courses
5750   */
5751  function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
5752      global $DB;
5753  
5754      if (!is_null($courseids)) {
5755          list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid');
5756          $coursewhere = ' AND f.course '.$coursewhere;
5757      } else {
5758          $coursewhere = '';
5759          $params = array();
5760      }
5761      $params['userid'] = $user->id;
5762      $params['forum'] = 'forum';
5763  
5764      if ($discussionsonly) {
5765          $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
5766      } else {
5767          $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
5768                   JOIN {forum_posts} ff ON ff.discussion = fd.id';
5769      }
5770  
5771      $sql = "SELECT f.*, cm.id AS cmid
5772                FROM {forum} f
5773                JOIN {course_modules} cm ON cm.instance = f.id
5774                JOIN {modules} m ON m.id = cm.module
5775                JOIN (
5776                    SELECT f.id
5777                      FROM {forum} f
5778                      {$join}
5779                     WHERE ff.userid = :userid
5780                  GROUP BY f.id
5781                     ) j ON j.id = f.id
5782               WHERE m.name = :forum
5783                   {$coursewhere}";
5784  
5785      $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5786      return $courseforums;
5787  }
5788  
5789  /**
5790   * Returns posts made by the selected user in the requested courses.
5791   *
5792   * This method can be used to return all of the posts made by the requested user
5793   * within the given courses.
5794   * For each course the access of the current user and requested user is checked
5795   * and then for each post access to the post and forum is checked as well.
5796   *
5797   * This function is safe to use with usercapabilities.
5798   *
5799   * @global moodle_database $DB
5800   * @param stdClass $user The user whose posts we want to get
5801   * @param array $courses The courses to search
5802   * @param bool $musthaveaccess If set to true errors will be thrown if the user
5803   *                             cannot access one or more of the courses to search
5804   * @param bool $discussionsonly If set to true only discussion starting posts
5805   *                              will be returned.
5806   * @param int $limitfrom The offset of records to return
5807   * @param int $limitnum The number of records to return
5808   * @return stdClass An object the following properties
5809   *               ->totalcount: the total number of posts made by the requested user
5810   *                             that the current user can see.
5811   *               ->courses: An array of courses the current user can see that the
5812   *                          requested user has posted in.
5813   *               ->forums: An array of forums relating to the posts returned in the
5814   *                         property below.
5815   *               ->posts: An array containing the posts to show for this request.
5816   */
5817  function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
5818      global $DB, $USER, $CFG;
5819  
5820      $return = new stdClass;
5821      $return->totalcount = 0;    // The total number of posts that the current user is able to view
5822      $return->courses = array(); // The courses the current user can access
5823      $return->forums = array();  // The forums that the current user can access that contain posts
5824      $return->posts = array();   // The posts to display
5825  
5826      // First up a small sanity check. If there are no courses to check we can
5827      // return immediately, there is obviously nothing to search.
5828      if (empty($courses)) {
5829          return $return;
5830      }
5831  
5832      // A couple of quick setups
5833      $isloggedin = isloggedin();
5834      $isguestuser = $isloggedin && isguestuser();
5835      $iscurrentuser = $isloggedin && $USER->id == $user->id;
5836  
5837      // Checkout whether or not the current user has capabilities over the requested
5838      // user and if so they have the capabilities required to view the requested
5839      // users content.
5840      $usercontext = context_user::instance($user->id, MUST_EXIST);
5841      $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
5842      $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
5843  
5844      // Before we actually search each course we need to check the user's access to the
5845      // course. If the user doesn't have the appropraite access then we either throw an
5846      // error if a particular course was requested or we just skip over the course.
5847      foreach ($courses as $course) {
5848          $coursecontext = context_course::instance($course->id, MUST_EXIST);
5849          if ($iscurrentuser || $hascapsonuser) {
5850              // If it is the current user, or the current user has capabilities to the
5851              // requested user then all we need to do is check the requested users
5852              // current access to the course.
5853              // Note: There is no need to check group access or anything of the like
5854              // as either the current user is the requested user, or has granted
5855              // capabilities on the requested user. Either way they can see what the
5856              // requested user posted, although its VERY unlikely in the `parent` situation
5857              // that the current user will be able to view the posts in context.
5858              if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
5859                  // Need to have full access to a course to see the rest of own info
5860                  if ($musthaveaccess) {
5861                      print_error('errorenrolmentrequired', 'forum');
5862                  }
5863                  continue;
5864              }
5865          } else {
5866              // Check whether the current user is enrolled or has access to view the course
5867              // if they don't we immediately have a problem.
5868              if (!can_access_course($course)) {
5869                  if ($musthaveaccess) {
5870                      print_error('errorenrolmentrequired', 'forum');
5871                  }
5872                  continue;
5873              }
5874  
5875              // If groups are in use and enforced throughout the course then make sure
5876              // we can meet in at least one course level group.
5877              // Note that we check if either the current user or the requested user have
5878              // the capability to access all groups. This is because with that capability
5879              // a user in group A could post in the group B forum. Grrrr.
5880              if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
5881                && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
5882                  // If its the guest user to bad... the guest user cannot access groups
5883                  if (!$isloggedin or $isguestuser) {
5884                      // do not use require_login() here because we might have already used require_login($course)
5885                      if ($musthaveaccess) {
5886                          redirect(get_login_url());
5887                      }
5888                      continue;
5889                  }
5890                  // Get the groups of the current user
5891                  $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
5892                  // Get the groups the requested user is a member of
5893                  $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
5894                  // Check whether they are members of the same group. If they are great.
5895                  $intersect = array_intersect($mygroups, $usergroups);
5896                  if (empty($intersect)) {
5897                      // But they're not... if it was a specific course throw an error otherwise
5898                      // just skip this course so that it is not searched.
5899                      if ($musthaveaccess) {
5900                          print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
5901                      }
5902                      continue;
5903                  }
5904              }
5905          }
5906          // Woo hoo we got this far which means the current user can search this
5907          // this course for the requested user. Although this is only the course accessibility
5908          // handling that is complete, the forum accessibility tests are yet to come.
5909          $return->courses[$course->id] = $course;
5910      }
5911      // No longer beed $courses array - lose it not it may be big
5912      unset($courses);
5913  
5914      // Make sure that we have some courses to search
5915      if (empty($return->courses)) {
5916          // If we don't have any courses to search then the reality is that the current
5917          // user doesn't have access to any courses is which the requested user has posted.
5918          // Although we do know at this point that the requested user has posts.
5919          if ($musthaveaccess) {
5920              print_error('permissiondenied');
5921          } else {
5922              return $return;
5923          }
5924      }
5925  
5926      // Next step: Collect all of the forums that we will want to search.
5927      // It is important to note that this step isn't actually about searching, it is
5928      // about determining which forums we can search by testing accessibility.
5929      $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);
5930  
5931      // Will be used to build the where conditions for the search
5932      $forumsearchwhere = array();
5933      // Will be used to store the where condition params for the search
5934      $forumsearchparams = array();
5935      // Will record forums where the user can freely access everything
5936      $forumsearchfullaccess = array();
5937      // DB caching friendly
5938      $now = floor(time() / 60) * 60;
5939      // For each course to search we want to find the forums the user has posted in
5940      // and providing the current user can access the forum create a search condition
5941      // for the forum to get the requested users posts.
5942      foreach ($return->courses as $course) {
5943          // Now we need to get the forums
5944          $modinfo = get_fast_modinfo($course);
5945          if (empty($modinfo->instances['forum'])) {
5946              // hmmm, no forums? well at least its easy... skip!
5947              continue;
5948          }
5949          // Iterate
5950          foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
5951              if (!$cm->uservisible or !isset($forums[$forumid])) {
5952                  continue;
5953              }
5954              // Get the forum in question
5955              $forum = $forums[$forumid];
5956  
5957              // This is needed for functionality later on in the forum code. It is converted to an object
5958              // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
5959              // code were expecting an writeable object. See {@link forum_print_post()}.
5960              $forum->cm = new stdClass();
5961              foreach ($cm as $key => $value) {
5962                  $forum->cm->$key = $value;
5963              }
5964  
5965              // Check that either the current user can view the forum, or that the
5966              // current user has capabilities over the requested user and the requested
5967              // user can view the discussion
5968              if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
5969                  continue;
5970              }
5971  
5972              // This will contain forum specific where clauses
5973              $forumsearchselect = array();
5974              if (!$iscurrentuser && !$hascapsonuser) {
5975                  // Make sure we check group access
5976                  if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
5977                      $groups = $modinfo->get_groups($cm->groupingid);
5978                      $groups[] = -1;
5979                      list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
5980                      $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
5981                      $forumsearchselect[] = "d.groupid $groupid_sql";
5982                  }
5983  
5984                  // hidden timed discussions
5985                  if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
5986                      $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
5987                      $forumsearchparams['userid'.$forumid] = $user->id;
5988                      $forumsearchparams['timestart'.$forumid] = $now;
5989                      $forumsearchparams['timeend'.$forumid] = $now;
5990                  }
5991  
5992                  // qanda access
5993                  if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
5994                      // We need to check whether the user has posted in the qanda forum.
5995                      $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
5996                      if (!empty($discussionspostedin)) {
5997                          $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
5998                          foreach ($discussionspostedin as $d) {
5999                              $forumonlydiscussions[] = $d->id;
6000                          }
6001                          list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
6002                          $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
6003                          $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
6004                      } else {
6005                          $forumsearchselect[] = "p.parent = 0";
6006                      }
6007  
6008                  }
6009  
6010                  if (count($forumsearchselect) > 0) {
6011                      $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
6012                      $forumsearchparams['forum'.$forumid] = $forumid;
6013                  } else {
6014                      $forumsearchfullaccess[] = $forumid;
6015                  }
6016              } else {
6017                  // The current user/parent can see all of their own posts
6018                  $forumsearchfullaccess[] = $forumid;
6019              }
6020          }
6021      }
6022  
6023      // If we dont have any search conditions, and we don't have any forums where
6024      // the user has full access then we just return the default.
6025      if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
6026          return $return;
6027      }
6028  
6029      // Prepare a where condition for the full access forums.
6030      if (count($forumsearchfullaccess) > 0) {
6031          list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
6032          $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
6033          $forumsearchwhere[] = "(d.forum $fullidsql)";
6034      }
6035  
6036      // Prepare SQL to both count and search.
6037      // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
6038      // oracle and mssql.
6039      $userfieldsapi = \core_user\fields::for_userpic();
6040      $userfields = $userfieldsapi->get_sql('u', false, '', 'useridx', false)->selects;
6041      $countsql = 'SELECT COUNT(*) ';
6042      $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
6043      $wheresql = implode(" OR ", $forumsearchwhere);
6044  
6045      if ($discussionsonly) {
6046          if ($wheresql == '') {
6047              $wheresql = 'p.parent = 0';
6048          } else {
6049              $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
6050          }
6051      }
6052  
6053      $sql = "FROM {forum_posts} p
6054              JOIN {forum_discussions} d ON d.id = p.discussion
6055              JOIN {user} u ON u.id = p.userid
6056             WHERE ($wheresql)
6057               AND p.userid = :userid ";
6058      $orderby = "ORDER BY p.modified DESC";
6059      $forumsearchparams['userid'] = $user->id;
6060  
6061      // Set the total number posts made by the requested user that the current user can see
6062      $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
6063      // Set the collection of posts that has been requested
6064      $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
6065  
6066      // We need to build an array of forums for which posts will be displayed.
6067      // We do this here to save the caller needing to retrieve them themselves before
6068      // printing these forums posts. Given we have the forums already there is
6069      // practically no overhead here.
6070      foreach ($return->posts as $post) {
6071          if (!array_key_exists($post->forum, $return->forums)) {
6072              $return->forums[$post->forum] = $forums[$post->forum];
6073          }
6074      }
6075  
6076      return $return;
6077  }
6078  
6079  /**
6080   * Set the per-forum maildigest option for the specified user.
6081   *
6082   * @param stdClass $forum The forum to set the option for.
6083   * @param int $maildigest The maildigest option.
6084   * @param stdClass $user The user object. This defaults to the global $USER object.
6085   * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
6086   */
6087  function forum_set_user_maildigest($forum, $maildigest, $user = null) {
6088      global $DB, $USER;
6089  
6090      if (is_number($forum)) {
6091          $forum = $DB->get_record('forum', array('id' => $forum));
6092      }
6093  
6094      if ($user === null) {
6095          $user = $USER;
6096      }
6097  
6098      $course  = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
6099      $cm      = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
6100      $context = context_module::instance($cm->id);
6101  
6102      // User must be allowed to see this forum.
6103      require_capability('mod/forum:viewdiscussion', $context, $user->id);
6104  
6105      // Validate the maildigest setting.
6106      $digestoptions = forum_get_user_digest_options($user);
6107  
6108      if (!isset($digestoptions[$maildigest])) {
6109          throw new moodle_exception('invaliddigestsetting', 'mod_forum');
6110      }
6111  
6112      // Attempt to retrieve any existing forum digest record.
6113      $subscription = $DB->get_record('forum_digests', array(
6114          'userid' => $user->id,
6115          'forum' => $forum->id,
6116      ));
6117  
6118      // Create or Update the existing maildigest setting.
6119      if ($subscription) {
6120          if ($maildigest == -1) {
6121              $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id));
6122          } else if ($maildigest !== $subscription->maildigest) {
6123              // Only update the maildigest setting if it's changed.
6124  
6125              $subscription->maildigest = $maildigest;
6126              $DB->update_record('forum_digests', $subscription);
6127          }
6128      } else {
6129          if ($maildigest != -1) {
6130              // Only insert the maildigest setting if it's non-default.
6131  
6132              $subscription = new stdClass();
6133              $subscription->forum = $forum->id;
6134              $subscription->userid = $user->id;
6135              $subscription->maildigest = $maildigest;
6136              $subscription->id = $DB->insert_record('forum_digests', $subscription);
6137          }
6138      }
6139  }
6140  
6141  /**
6142   * Determine the maildigest setting for the specified user against the
6143   * specified forum.
6144   *
6145   * @param Array $digests An array of forums and user digest settings.
6146   * @param stdClass $user The user object containing the id and maildigest default.
6147   * @param int $forumid The ID of the forum to check.
6148   * @return int The calculated maildigest setting for this user and forum.
6149   */
6150  function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
6151      if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) {
6152          $maildigest = $digests[$forumid][$user->id];
6153          if ($maildigest === -1) {
6154              $maildigest = $user->maildigest;
6155          }
6156      } else {
6157          $maildigest = $user->maildigest;
6158      }
6159      return $maildigest;
6160  }
6161  
6162  /**
6163   * Retrieve the list of available user digest options.
6164   *
6165   * @param stdClass $user The user object. This defaults to the global $USER object.
6166   * @return array The mapping of values to digest options.
6167   */
6168  function forum_get_user_digest_options($user = null) {
6169      global $USER;
6170  
6171      // Revert to the global user object.
6172      if ($user === null) {
6173          $user = $USER;
6174      }
6175  
6176      $digestoptions = array();
6177      $digestoptions['0']  = get_string('emaildigestoffshort', 'mod_forum');
6178      $digestoptions['1']  = get_string('emaildigestcompleteshort', 'mod_forum');
6179      $digestoptions['2']  = get_string('emaildigestsubjectsshort', 'mod_forum');
6180  
6181      // We need to add the default digest option at the end - it relies on
6182      // the contents of the existing values.
6183      $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
6184              $digestoptions[$user->maildigest]);
6185  
6186      // Resort the options to be in a sensible order.
6187      ksort($digestoptions);
6188  
6189      return $digestoptions;
6190  }
6191  
6192  /**
6193   * Determine the current context if one was not already specified.
6194   *
6195   * If a context of type context_module is specified, it is immediately
6196   * returned and not checked.
6197   *
6198   * @param int $forumid The ID of the forum
6199   * @param context_module $context The current context.
6200   * @return context_module The context determined
6201   */
6202  function forum_get_context($forumid, $context = null) {
6203      global $PAGE;
6204  
6205      if (!$context || !($context instanceof context_module)) {
6206          // Find out forum context. First try to take current page context to save on DB query.
6207          if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid
6208                  && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) {
6209              $context = $PAGE->context;
6210          } else {
6211              $cm = get_coursemodule_from_instance('forum', $forumid);
6212              $context = \context_module::instance($cm->id);
6213          }
6214      }
6215  
6216      return $context;
6217  }
6218  
6219  /**
6220   * Mark the activity completed (if required) and trigger the course_module_viewed event.
6221   *
6222   * @param  stdClass $forum   forum object
6223   * @param  stdClass $course  course object
6224   * @param  stdClass $cm      course module object
6225   * @param  stdClass $context context object
6226   * @since Moodle 2.9
6227   */
6228  function forum_view($forum, $course, $cm, $context) {
6229  
6230      // Completion.
6231      $completion = new completion_info($course);
6232      $completion->set_module_viewed($cm);
6233  
6234      // Trigger course_module_viewed event.
6235  
6236      $params = array(
6237          'context' => $context,
6238          'objectid' => $forum->id
6239      );
6240  
6241      $event = \mod_forum\event\course_module_viewed::create($params);
6242      $event->add_record_snapshot('course_modules', $cm);
6243      $event->add_record_snapshot('course', $course);
6244      $event->add_record_snapshot('forum', $forum);
6245      $event->trigger();
6246  }
6247  
6248  /**
6249   * Trigger the discussion viewed event
6250   *
6251   * @param  stdClass $modcontext module context object
6252   * @param  stdClass $forum      forum object
6253   * @param  stdClass $discussion discussion object
6254   * @since Moodle 2.9
6255   */
6256  function forum_discussion_view($modcontext, $forum, $discussion) {
6257      $params = array(
6258          'context' => $modcontext,
6259          'objectid' => $discussion->id,
6260      );
6261  
6262      $event = \mod_forum\event\discussion_viewed::create($params);
6263      $event->add_record_snapshot('forum_discussions', $discussion);
6264      $event->add_record_snapshot('forum', $forum);
6265      $event->trigger();
6266  }
6267  
6268  /**
6269   * Set the discussion to pinned and trigger the discussion pinned event
6270   *
6271   * @param  stdClass $modcontext module context object
6272   * @param  stdClass $forum      forum object
6273   * @param  stdClass $discussion discussion object
6274   * @since Moodle 3.1
6275   */
6276  function forum_discussion_pin($modcontext, $forum, $discussion) {
6277      global $DB;
6278  
6279      $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED, array('id' => $discussion->id));
6280  
6281      $params = array(
6282          'context' => $modcontext,
6283          'objectid' => $discussion->id,
6284          'other' => array('forumid' => $forum->id)
6285      );
6286  
6287      $event = \mod_forum\event\discussion_pinned::create($params);
6288      $event->add_record_snapshot('forum_discussions', $discussion);
6289      $event->trigger();
6290  }
6291  
6292  /**
6293   * Set discussion to unpinned and trigger the discussion unpin event
6294   *
6295   * @param  stdClass $modcontext module context object
6296   * @param  stdClass $forum      forum object
6297   * @param  stdClass $discussion discussion object
6298   * @since Moodle 3.1
6299   */
6300  function forum_discussion_unpin($modcontext, $forum, $discussion) {
6301      global $DB;
6302  
6303      $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED, array('id' => $discussion->id));
6304  
6305      $params = array(
6306          'context' => $modcontext,
6307          'objectid' => $discussion->id,
6308          'other' => array('forumid' => $forum->id)
6309      );
6310  
6311      $event = \mod_forum\event\discussion_unpinned::create($params);
6312      $event->add_record_snapshot('forum_discussions', $discussion);
6313      $event->trigger();
6314  }
6315  
6316  /**
6317   * Add nodes to myprofile page.
6318   *
6319   * @param \core_user\output\myprofile\tree $tree Tree object
6320   * @param stdClass $user user object
6321   * @param bool $iscurrentuser
6322   * @param stdClass $course Course object
6323   *
6324   * @return bool
6325   */
6326  function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
6327      if (isguestuser($user)) {
6328          // The guest user cannot post, so it is not possible to view any posts.
6329          // May as well just bail aggressively here.
6330          return false;
6331      }
6332      $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id));
6333      if (!empty($course)) {
6334          $postsurl->param('course', $course->id);
6335      }
6336      $string = get_string('forumposts', 'mod_forum');
6337      $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl);
6338      $tree->add_node($node);
6339  
6340      $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions'));
6341      if (!empty($course)) {
6342          $discussionssurl->param('course', $course->id);
6343      }
6344      $string = get_string('myprofileotherdis', 'mod_forum');
6345      $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null,
6346          $discussionssurl);
6347      $tree->add_node($node);
6348  
6349      return true;
6350  }
6351  
6352  /**
6353   * Checks whether the author's name and picture for a given post should be hidden or not.
6354   *
6355   * @param object $post The forum post.
6356   * @param object $forum The forum object.
6357   * @return bool
6358   * @throws coding_exception
6359   */
6360  function forum_is_author_hidden($post, $forum) {
6361      if (!isset($post->parent)) {
6362          throw new coding_exception('$post->parent must be set.');
6363      }
6364      if (!isset($forum->type)) {
6365          throw new coding_exception('$forum->type must be set.');
6366      }
6367      if ($forum->type === 'single' && empty($post->parent)) {
6368          return true;
6369      }
6370      return false;
6371  }
6372  
6373  /**
6374   * Manage inplace editable saves.
6375   *
6376   * @param   string      $itemtype       The type of item.
6377   * @param   int         $itemid         The ID of the item.
6378   * @param   mixed       $newvalue       The new value
6379   * @return  string
6380   */
6381  function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) {
6382      global $DB, $PAGE;
6383  
6384      if ($itemtype === 'digestoptions') {
6385          // The itemid is the forumid.
6386          $forum   = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST);
6387          $course  = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
6388          $cm      = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
6389          $context = context_module::instance($cm->id);
6390  
6391          $PAGE->set_context($context);
6392          require_login($course, false, $cm);
6393          forum_set_user_maildigest($forum, $newvalue);
6394  
6395          $renderer = $PAGE->get_renderer('mod_forum');
6396          return $renderer->render_digest_options($forum, $newvalue);
6397      }
6398  }
6399  
6400  /**
6401   * Determine whether the specified forum's cutoff date is reached.
6402   *
6403   * @param stdClass $forum The forum
6404   * @return bool
6405   */
6406  function forum_is_cutoff_date_reached($forum) {
6407      $entityfactory = \mod_forum\local\container::get_entity_factory();
6408      $coursemoduleinfo = get_fast_modinfo($forum->course);
6409      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6410      $forumentity = $entityfactory->get_forum_from_stdclass(
6411              $forum,
6412              context_module::instance($cminfo->id),
6413              $cminfo->get_course_module_record(),
6414              $cminfo->get_course()
6415      );
6416  
6417      return $forumentity->is_cutoff_date_reached();
6418  }
6419  
6420  /**
6421   * Determine whether the specified forum's due date is reached.
6422   *
6423   * @param stdClass $forum The forum
6424   * @return bool
6425   */
6426  function forum_is_due_date_reached($forum) {
6427      $entityfactory = \mod_forum\local\container::get_entity_factory();
6428      $coursemoduleinfo = get_fast_modinfo($forum->course);
6429      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6430      $forumentity = $entityfactory->get_forum_from_stdclass(
6431              $forum,
6432              context_module::instance($cminfo->id),
6433              $cminfo->get_course_module_record(),
6434              $cminfo->get_course()
6435      );
6436  
6437      return $forumentity->is_due_date_reached();
6438  }
6439  
6440  /**
6441   * Determine whether the specified discussion is time-locked.
6442   *
6443   * @param   stdClass    $forum          The forum that the discussion belongs to
6444   * @param   stdClass    $discussion     The discussion to test
6445   * @return  bool
6446   */
6447  function forum_discussion_is_locked($forum, $discussion) {
6448      $entityfactory = \mod_forum\local\container::get_entity_factory();
6449      $coursemoduleinfo = get_fast_modinfo($forum->course);
6450      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6451      $forumentity = $entityfactory->get_forum_from_stdclass(
6452          $forum,
6453          context_module::instance($cminfo->id),
6454          $cminfo->get_course_module_record(),
6455          $cminfo->get_course()
6456      );
6457      $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
6458  
6459      return $forumentity->is_discussion_locked($discussionentity);
6460  }
6461  
6462  /**
6463   * Check if the module has any update that affects the current user since a given time.
6464   *
6465   * @param  cm_info $cm course module data
6466   * @param  int $from the time to check updates from
6467   * @param  array $filter  if we need to check only specific updates
6468   * @return stdClass an object with the different type of areas indicating if they were updated or not
6469   * @since Moodle 3.2
6470   */
6471  function forum_check_updates_since(cm_info $cm, $from, $filter = array()) {
6472  
6473      $context = $cm->context;
6474      $updates = new stdClass();
6475      if (!has_capability('mod/forum:viewdiscussion', $context)) {
6476          return $updates;
6477      }
6478  
6479      $updates = course_check_module_updates_since($cm, $from, array(), $filter);
6480  
6481      // Check if there are new discussions in the forum.
6482      $updates->discussions = (object) array('updated' => false);
6483      $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS, $from);
6484      if (!empty($discussions)) {
6485          $updates->discussions->updated = true;
6486          $updates->discussions->itemids = array_keys($discussions);
6487      }
6488  
6489      return $updates;
6490  }
6491  
6492  /**
6493   * Check if the user can create attachments in a forum.
6494   * @param  stdClass $forum   forum object
6495   * @param  stdClass $context context object
6496   * @return bool true if the user can create attachments, false otherwise
6497   * @since  Moodle 3.3
6498   */
6499  function forum_can_create_attachment($forum, $context) {
6500      // If maxbytes == 1 it means no attachments at all.
6501      if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
6502              !has_capability('mod/forum:createattachment', $context)) {
6503          return false;
6504      }
6505      return true;
6506  }
6507  
6508  /**
6509   * Get icon mapping for font-awesome.
6510   *
6511   * @return  array
6512   */
6513  function mod_forum_get_fontawesome_icon_map() {
6514      return [
6515          'mod_forum:i/pinned' => 'fa-map-pin',
6516          'mod_forum:t/selected' => 'fa-check',
6517          'mod_forum:t/subscribed' => 'fa-envelope-o',
6518          'mod_forum:t/unsubscribed' => 'fa-envelope-open-o',
6519          'mod_forum:t/star' => 'fa-star',
6520      ];
6521  }
6522  
6523  /**
6524   * Callback function that determines whether an action event should be showing its item count
6525   * based on the event type and the item count.
6526   *
6527   * @param calendar_event $event The calendar event.
6528   * @param int $itemcount The item count associated with the action event.
6529   * @return bool
6530   */
6531  function mod_forum_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
6532      // Always show item count for forums if item count is greater than 1.
6533      // If only one action is required than it is obvious and we don't show it for other modules.
6534      return $itemcount > 1;
6535  }
6536  
6537  /**
6538   * This function receives a calendar event and returns the action associated with it, or null if there is none.
6539   *
6540   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
6541   * is not displayed on the block.
6542   *
6543   * @param calendar_event $event
6544   * @param \core_calendar\action_factory $factory
6545   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
6546   * @return \core_calendar\local\event\entities\action_interface|null
6547   */
6548  function mod_forum_core_calendar_provide_event_action(calendar_event $event,
6549                                                        \core_calendar\action_factory $factory,
6550                                                        int $userid = 0) {
6551      global $DB, $USER;
6552  
6553      if (!$userid) {
6554          $userid = $USER->id;
6555      }
6556  
6557      $cm = get_fast_modinfo($event->courseid, $userid)->instances['forum'][$event->instance];
6558  
6559      if (!$cm->uservisible) {
6560          // The module is not visible to the user for any reason.
6561          return null;
6562      }
6563  
6564      $context = context_module::instance($cm->id);
6565  
6566      if (!has_capability('mod/forum:viewdiscussion', $context, $userid)) {
6567          return null;
6568      }
6569  
6570      $completion = new \completion_info($cm->get_course());
6571  
6572      $completiondata = $completion->get_data($cm, false, $userid);
6573  
6574      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
6575          return null;
6576      }
6577  
6578      // Get action itemcount.
6579      $itemcount = 0;
6580      $forum = $DB->get_record('forum', array('id' => $cm->instance));
6581      $postcountsql = "
6582                  SELECT
6583                      COUNT(1)
6584                    FROM
6585                      {forum_posts} fp
6586                      INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
6587                   WHERE
6588                      fp.userid=:userid AND fd.forum=:forumid";
6589      $postcountparams = array('userid' => $userid, 'forumid' => $forum->id);
6590  
6591      if ($forum->completiondiscussions) {
6592          $count = $DB->count_records('forum_discussions', array('forum' => $forum->id, 'userid' => $userid));
6593          $itemcount += ($forum->completiondiscussions >= $count) ? ($forum->completiondiscussions - $count) : 0;
6594      }
6595  
6596      if ($forum->completionreplies) {
6597          $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams);
6598          $itemcount += ($forum->completionreplies >= $count) ? ($forum->completionreplies - $count) : 0;
6599      }
6600  
6601      if ($forum->completionposts) {
6602          $count = $DB->get_field_sql($postcountsql, $postcountparams);
6603          $itemcount += ($forum->completionposts >= $count) ? ($forum->completionposts - $count) : 0;
6604      }
6605  
6606      // Well there is always atleast one actionable item (view forum, etc).
6607      $itemcount = $itemcount > 0 ? $itemcount : 1;
6608  
6609      return $factory->create_instance(
6610          get_string('view'),
6611          new \moodle_url('/mod/forum/view.php', ['id' => $cm->id]),
6612          $itemcount,
6613          true
6614      );
6615  }
6616  
6617  /**
6618   * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information
6619   * for the course (see resource).
6620   *
6621   * Given a course_module object, this function returns any "extra" information that may be needed
6622   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
6623   *
6624   * @param stdClass $coursemodule The coursemodule object (record).
6625   * @return cached_cm_info An object on information that the courses
6626   *                        will know about (most noticeably, an icon).
6627   */
6628  function forum_get_coursemodule_info($coursemodule) {
6629      global $DB;
6630  
6631      $dbparams = ['id' => $coursemodule->instance];
6632      $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies, duedate, cutoffdate';
6633      if (!$forum = $DB->get_record('forum', $dbparams, $fields)) {
6634          return false;
6635      }
6636  
6637      $result = new cached_cm_info();
6638      $result->name = $forum->name;
6639  
6640      if ($coursemodule->showdescription) {
6641          // Convert intro to html. Do not filter cached version, filters run at display time.
6642          $result->content = format_module_intro('forum', $forum, $coursemodule->id, false);
6643      }
6644  
6645      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
6646      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
6647          $result->customdata['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions;
6648          $result->customdata['customcompletionrules']['completionreplies'] = $forum->completionreplies;
6649          $result->customdata['customcompletionrules']['completionposts'] = $forum->completionposts;
6650      }
6651  
6652      // Populate some other values that can be used in calendar or on dashboard.
6653      if ($forum->duedate) {
6654          $result->customdata['duedate'] = $forum->duedate;
6655      }
6656      if ($forum->cutoffdate) {
6657          $result->customdata['cutoffdate'] = $forum->cutoffdate;
6658      }
6659  
6660      return $result;
6661  }
6662  
6663  /**
6664   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
6665   *
6666   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
6667   * @return array $descriptions the array of descriptions for the custom rules.
6668   */
6669  function mod_forum_get_completion_active_rule_descriptions($cm) {
6670      // Values will be present in cm_info, and we assume these are up to date.
6671      if (empty($cm->customdata['customcompletionrules'])
6672          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
6673          return [];
6674      }
6675  
6676      $descriptions = [];
6677      foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
6678          switch ($key) {
6679              case 'completiondiscussions':
6680                  if (!empty($val)) {
6681                      $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val);
6682                  }
6683                  break;
6684              case 'completionreplies':
6685                  if (!empty($val)) {
6686                      $descriptions[] = get_string('completionrepliesdesc', 'forum', $val);
6687                  }
6688                  break;
6689              case 'completionposts':
6690                  if (!empty($val)) {
6691                      $descriptions[] = get_string('completionpostsdesc', 'forum', $val);
6692                  }
6693                  break;
6694              default:
6695                  break;
6696          }
6697      }
6698      return $descriptions;
6699  }
6700  
6701  /**
6702   * Check whether the forum post is a private reply visible to this user.
6703   *
6704   * @param   stdClass    $post   The post to check.
6705   * @param   cm_info     $cm     The context module instance.
6706   * @return  bool                Whether the post is visible in terms of private reply configuration.
6707   */
6708  function forum_post_is_visible_privately($post, $cm) {
6709      global $USER;
6710  
6711      if (!empty($post->privatereplyto)) {
6712          // Allow the user to see the private reply if:
6713          // * they hold the permission;
6714          // * they are the author; or
6715          // * they are the intended recipient.
6716          $cansee = false;
6717          $cansee = $cansee || ($post->userid == $USER->id);
6718          $cansee = $cansee || ($post->privatereplyto == $USER->id);
6719          $cansee = $cansee || has_capability('mod/forum:readprivatereplies', context_module::instance($cm->id));
6720          return $cansee;
6721      }
6722  
6723      return true;
6724  }
6725  
6726  /**
6727   * Check whether the user can reply privately to the parent post.
6728   *
6729   * @param   \context_module $context
6730   * @param   \stdClass   $parent
6731   * @return  bool
6732   */
6733  function forum_user_can_reply_privately(\context_module $context, \stdClass $parent) : bool {
6734      if ($parent->privatereplyto) {
6735          // You cannot reply privately to a post which is, itself, a private reply.
6736          return false;
6737      }
6738  
6739      return has_capability('mod/forum:postprivatereply', $context);
6740  }
6741  
6742  /**
6743   * This function calculates the minimum and maximum cutoff values for the timestart of
6744   * the given event.
6745   *
6746   * It will return an array with two values, the first being the minimum cutoff value and
6747   * the second being the maximum cutoff value. Either or both values can be null, which
6748   * indicates there is no minimum or maximum, respectively.
6749   *
6750   * If a cutoff is required then the function must return an array containing the cutoff
6751   * timestamp and error string to display to the user if the cutoff value is violated.
6752   *
6753   * A minimum and maximum cutoff return value will look like:
6754   * [
6755   *     [1505704373, 'The date must be after this date'],
6756   *     [1506741172, 'The date must be before this date']
6757   * ]
6758   *
6759   * @param calendar_event $event The calendar event to get the time range for
6760   * @param stdClass $forum The module instance to get the range from
6761   * @return array Returns an array with min and max date.
6762   */
6763  function mod_forum_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $forum) {
6764      global $CFG;
6765  
6766      require_once($CFG->dirroot . '/mod/forum/locallib.php');
6767  
6768      $mindate = null;
6769      $maxdate = null;
6770  
6771      if ($event->eventtype == FORUM_EVENT_TYPE_DUE) {
6772          if (!empty($forum->cutoffdate)) {
6773              $maxdate = [
6774                  $forum->cutoffdate,
6775                  get_string('cutoffdatevalidation', 'forum'),
6776              ];
6777          }
6778      }
6779  
6780      return [$mindate, $maxdate];
6781  }
6782  
6783  /**
6784   * This function will update the forum module according to the
6785   * event that has been modified.
6786   *
6787   * It will set the timeclose value of the forum instance
6788   * according to the type of event provided.
6789   *
6790   * @throws \moodle_exception
6791   * @param \calendar_event $event
6792   * @param stdClass $forum The module instance to get the range from
6793   */
6794  function mod_forum_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $forum) {
6795      global $CFG, $DB;
6796  
6797      require_once($CFG->dirroot . '/mod/forum/locallib.php');
6798  
6799      if ($event->eventtype != FORUM_EVENT_TYPE_DUE) {
6800          return;
6801      }
6802  
6803      $courseid = $event->courseid;
6804      $modulename = $event->modulename;
6805      $instanceid = $event->instance;
6806  
6807      // Something weird going on. The event is for a different module so
6808      // we should ignore it.
6809      if ($modulename != 'forum') {
6810          return;
6811      }
6812  
6813      if ($forum->id != $instanceid) {
6814          return;
6815      }
6816  
6817      $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
6818      $context = context_module::instance($coursemodule->id);
6819  
6820      // The user does not have the capability to modify this activity.
6821      if (!has_capability('moodle/course:manageactivities', $context)) {
6822          return;
6823      }
6824  
6825      if ($event->eventtype == FORUM_EVENT_TYPE_DUE) {
6826          if ($forum->duedate != $event->timestart) {
6827              $forum->duedate = $event->timestart;
6828              $forum->timemodified = time();
6829              // Persist the instance changes.
6830              $DB->update_record('forum', $forum);
6831              $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
6832              $event->trigger();
6833          }
6834      }
6835  }
6836  
6837  /**
6838   * Fetch the data used to display the discussions on the current page.
6839   *
6840   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6841   * @param   stdClass                         $user The user to render for
6842   * @param   int[]|null                       $groupid The group to render
6843   * @param   int|null                         $sortorder The sort order to use when selecting the discussions in the list
6844   * @param   int|null                         $pageno The zero-indexed page number to use
6845   * @param   int|null                         $pagesize The number of discussions to show on the page
6846   * @return  array                            The data to use for display
6847   */
6848  function mod_forum_get_discussion_summaries(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid, ?int $sortorder,
6849          ?int $pageno = 0, ?int $pagesize = 0) {
6850  
6851      $vaultfactory = mod_forum\local\container::get_vault_factory();
6852      $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6853      $managerfactory = mod_forum\local\container::get_manager_factory();
6854      $capabilitymanager = $managerfactory->get_capability_manager($forum);
6855  
6856      $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6857  
6858      if (null === $groupids) {
6859          return $discussions = $discussionvault->get_from_forum_id(
6860              $forum->get_id(),
6861              $capabilitymanager->can_view_hidden_posts($user),
6862              $user->id,
6863              $sortorder,
6864              $pagesize,
6865              $pageno * $pagesize);
6866      } else {
6867          return $discussions = $discussionvault->get_from_forum_id_and_group_id(
6868              $forum->get_id(),
6869              $groupids,
6870              $capabilitymanager->can_view_hidden_posts($user),
6871              $user->id,
6872              $sortorder,
6873              $pagesize,
6874              $pageno * $pagesize);
6875      }
6876  }
6877  
6878  /**
6879   * Get a count of all discussions in a forum.
6880   *
6881   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6882   * @param   stdClass                         $user The user to render for
6883   * @param   int                              $groupid The group to render
6884   * @return  int                              The number of discussions in a forum
6885   */
6886  function mod_forum_count_all_discussions(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) {
6887  
6888      $managerfactory = mod_forum\local\container::get_manager_factory();
6889      $capabilitymanager = $managerfactory->get_capability_manager($forum);
6890      $vaultfactory = mod_forum\local\container::get_vault_factory();
6891      $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6892  
6893      $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6894  
6895      if (null === $groupids) {
6896          return $discussionvault->get_total_discussion_count_from_forum_id(
6897              $forum->get_id(),
6898              $capabilitymanager->can_view_hidden_posts($user),
6899              $user->id);
6900      } else {
6901          return $discussionvault->get_total_discussion_count_from_forum_id_and_group_id(
6902              $forum->get_id(),
6903              $groupids,
6904              $capabilitymanager->can_view_hidden_posts($user),
6905              $user->id);
6906      }
6907  }
6908  
6909  /**
6910   * Get the list of groups to show based on the current user and requested groupid.
6911   *
6912   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6913   * @param   stdClass                         $user The user viewing
6914   * @param   int                              $groupid The groupid requested
6915   * @return  array                            The list of groups to show
6916   */
6917  function mod_forum_get_groups_from_groupid(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) : ?array {
6918  
6919      $effectivegroupmode = $forum->get_effective_group_mode();
6920      if (empty($effectivegroupmode)) {
6921          // This forum is not in a group mode. Show all posts always.
6922          return null;
6923      }
6924  
6925      if (null == $groupid) {
6926          $managerfactory = mod_forum\local\container::get_manager_factory();
6927          $capabilitymanager = $managerfactory->get_capability_manager($forum);
6928          // No group was specified.
6929          $showallgroups = (VISIBLEGROUPS == $effectivegroupmode);
6930          $showallgroups = $showallgroups || $capabilitymanager->can_access_all_groups($user);
6931          if ($showallgroups) {
6932              // Return null to show all groups.
6933              return null;
6934          } else {
6935              // No group was specified. Only show the users current groups.
6936              return array_keys(
6937                  groups_get_all_groups(
6938                      $forum->get_course_id(),
6939                      $user->id,
6940                      $forum->get_course_module_record()->groupingid
6941                  )
6942              );
6943          }
6944      } else {
6945          // A group was specified. Just show that group.
6946          return [$groupid];
6947      }
6948  }
6949  
6950  /**
6951   * Return a list of all the user preferences used by mod_forum.
6952   *
6953   * @return array
6954   */
6955  function mod_forum_user_preferences() {
6956      $vaultfactory = \mod_forum\local\container::get_vault_factory();
6957      $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
6958  
6959      $preferences = array();
6960      $preferences['forum_discussionlistsortorder'] = array(
6961          'null' => NULL_NOT_ALLOWED,
6962          'default' => $discussionlistvault::SORTORDER_LASTPOST_DESC,
6963          'type' => PARAM_INT,
6964          'choices' => array(
6965              $discussionlistvault::SORTORDER_LASTPOST_DESC,
6966              $discussionlistvault::SORTORDER_LASTPOST_ASC,
6967              $discussionlistvault::SORTORDER_CREATED_DESC,
6968              $discussionlistvault::SORTORDER_CREATED_ASC,
6969              $discussionlistvault::SORTORDER_REPLIES_DESC,
6970              $discussionlistvault::SORTORDER_REPLIES_ASC
6971          )
6972      );
6973      $preferences['forum_useexperimentalui'] = [
6974          'null' => NULL_NOT_ALLOWED,
6975          'default' => false,
6976          'type' => PARAM_BOOL
6977      ];
6978  
6979      return $preferences;
6980  }
6981  
6982  /**
6983   * Lists all gradable areas for the advanced grading methods gramework.
6984   *
6985   * @return array('string'=>'string') An array with area names as keys and descriptions as values
6986   */
6987  function forum_grading_areas_list() {
6988      return [
6989          'forum' => get_string('grade_forum_header', 'forum'),
6990      ];
6991  }
6992  
6993  /**
6994   * This callback will check the provided instance of this module
6995   * and make sure there are up-to-date events created for it.
6996   *
6997   * @param int $courseid Not used.
6998   * @param stdClass $instance Forum module instance.
6999   * @param stdClass $cm Course module object.
7000   */
7001  function forum_refresh_events(int $courseid, stdClass $instance, stdClass $cm): void {
7002      global $CFG;
7003  
7004      // This function is called by cron and we need to include the locallib for calls further down.
7005      require_once($CFG->dirroot . '/mod/forum/locallib.php');
7006  
7007      forum_update_calendar($instance, $cm->id);
7008  }