Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
/mod/forum/ -> lib.php (source)

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

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