Search moodle.org's
Developer Documentation

See Release Notes

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

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [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   * This function prints the overview of a discussion in the forum listing.
2314   * It needs some discussion information and some post information, these
2315   * happen to be combined for efficiency in the $post parameter by the function
2316   * that calls this one: forum_print_latest_discussions()
2317   *
2318   * @global object
2319   * @global object
2320   * @param object $post The post object (passed by reference for speed).
2321   * @param object $forum The forum object.
2322   * @param int $group Current group.
2323   * @param string $datestring Format to use for the dates.
2324   * @param boolean $cantrack Is tracking enabled for this forum.
2325   * @param boolean $forumtracked Is the user tracking this forum.
2326   * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
2327   * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
2328   */
2329  function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2330                                          $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2331                                          $canviewhiddentimedposts = false) {
2332  
2333      global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
2334  
2335      static $rowcount;
2336      static $strmarkalldread;
2337  
2338      if (empty($modcontext)) {
2339          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2340              throw new \moodle_exception('invalidcoursemodule');
2341          }
2342          $modcontext = context_module::instance($cm->id);
2343      }
2344  
2345      if (!isset($rowcount)) {
2346          $rowcount = 0;
2347          $strmarkalldread = get_string('markalldread', 'forum');
2348      } else {
2349          $rowcount = ($rowcount + 1) % 2;
2350      }
2351  
2352      $post->subject = format_string($post->subject,true);
2353  
2354      $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
2355      $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2356      $timedoutsidewindow = '';
2357      if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2358          $timedoutsidewindow = ' dimmed_text';
2359      }
2360  
2361      echo "\n\n";
2362      echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
2363  
2364      $topicclass = 'topic starter';
2365      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2366          $topicclass .= ' pinned';
2367      }
2368      echo '<td class="'.$topicclass.'">';
2369      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2370          echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2371      }
2372      $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2373      if ($timeddiscussion && $canalwaysseetimedpost) {
2374          echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2375      }
2376  
2377      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
2378      echo "</td>\n";
2379  
2380      // Picture
2381      $postuser = new stdClass();
2382      $postuserfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
2383      $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
2384      $postuser->id = $post->userid;
2385      echo '<td class="author">';
2386      echo '<div class="media">';
2387      echo '<span class="float-left">';
2388      echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
2389      echo '</span>';
2390      // User name
2391      echo '<div class="media-body">';
2392      $fullname = fullname($postuser, $canviewfullnames);
2393      echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
2394      echo '</div>';
2395      echo '</div>';
2396      echo "</td>\n";
2397  
2398      // Group picture
2399      if ($group !== -1) {  // Groups are active - group is a group data object or NULL
2400          echo '<td class="picture group">';
2401          if (!empty($group->picture)) {
2402              if ($canviewparticipants && $COURSE->groupmode) {
2403                  $picturelink = true;
2404              } else {
2405                  $picturelink = false;
2406              }
2407              print_group_picture($group, $forum->course, false, false, $picturelink);
2408          } else if (isset($group->id)) {
2409              if ($canviewparticipants && $COURSE->groupmode) {
2410                  echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
2411              } else {
2412                  echo $group->name;
2413              }
2414          }
2415          echo "</td>\n";
2416      }
2417  
2418      if (has_capability('mod/forum:viewdiscussion', $modcontext)) {   // Show the column with replies
2419          echo '<td class="replies">';
2420          echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2421          echo $post->replies.'</a>';
2422          echo "</td>\n";
2423  
2424          if ($cantrack) {
2425              echo '<td class="replies">';
2426              if ($forumtracked) {
2427                  if ($post->unread > 0) {
2428                      echo '<span class="unread">';
2429                      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2430                      echo $post->unread;
2431                      echo '</a>';
2432                      echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2433                           $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;return=/mod/forum/view.php&amp;sesskey=' .
2434                           sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
2435                      echo '</span>';
2436                  } else {
2437                      echo '<span class="read">';
2438                      echo $post->unread;
2439                      echo '</span>';
2440                  }
2441              } else {
2442                  echo '<span class="read">';
2443                  echo '-';
2444                  echo '</span>';
2445              }
2446              echo "</td>\n";
2447          }
2448      }
2449  
2450      echo '<td class="lastpost">';
2451      $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
2452      $parenturl = '';
2453      $usermodified = new stdClass();
2454      $usermodified->id = $post->usermodified;
2455      $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
2456  
2457      // In QA forums we check that the user can view participants.
2458      if ($forum->type !== 'qanda' || $canviewparticipants) {
2459          echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
2460               fullname($usermodified, $canviewfullnames).'</a><br />';
2461          $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
2462      }
2463  
2464      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
2465            userdate_htmltime($usedate, $datestring).'</a>';
2466      echo "</td>\n";
2467  
2468      // is_guest should be used here as this also checks whether the user is a guest in the current course.
2469      // Guests and visitors cannot subscribe - only enrolled users.
2470      if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
2471          // Discussion subscription.
2472          if (\mod_forum\subscriptions::is_subscribable($forum)) {
2473              echo '<td class="discussionsubscription">';
2474              echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2475              echo '</td>';
2476          }
2477      }
2478  
2479      echo "</tr>\n\n";
2480  
2481  }
2482  
2483  /**
2484   * Return the markup for the discussion subscription toggling icon.
2485   *
2486   * @param stdClass $forum The forum object.
2487   * @param int $discussionid The discussion to create an icon for.
2488   * @return string The generated markup.
2489   */
2490  function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2491      global $USER, $OUTPUT, $PAGE;
2492  
2493      if ($returnurl === null && $PAGE->url) {
2494          $returnurl = $PAGE->url->out();
2495      }
2496  
2497      $o = '';
2498      $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2499      $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2500          'sesskey' => sesskey(),
2501          'id' => $forum->id,
2502          'd' => $discussionid,
2503          'returnurl' => $returnurl,
2504      ));
2505  
2506      if ($includetext) {
2507          $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2508      }
2509  
2510      if ($subscriptionstatus) {
2511          $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2512          if ($includetext) {
2513              $output .= get_string('subscribed', 'mod_forum');
2514          }
2515  
2516          return html_writer::link($subscriptionlink, $output, array(
2517                  'title' => get_string('clicktounsubscribe', 'forum'),
2518                  'class' => 'discussiontoggle btn btn-link',
2519                  'data-forumid' => $forum->id,
2520                  'data-discussionid' => $discussionid,
2521                  'data-includetext' => $includetext,
2522              ));
2523  
2524      } else {
2525          $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2526          if ($includetext) {
2527              $output .= get_string('notsubscribed', 'mod_forum');
2528          }
2529  
2530          return html_writer::link($subscriptionlink, $output, array(
2531                  'title' => get_string('clicktosubscribe', 'forum'),
2532                  'class' => 'discussiontoggle btn btn-link',
2533                  'data-forumid' => $forum->id,
2534                  'data-discussionid' => $discussionid,
2535                  'data-includetext' => $includetext,
2536              ));
2537      }
2538  }
2539  
2540  /**
2541   * Return a pair of spans containing classes to allow the subscribe and
2542   * unsubscribe icons to be pre-loaded by a browser.
2543   *
2544   * @return string The generated markup
2545   */
2546  function forum_get_discussion_subscription_icon_preloaders() {
2547      $o = '';
2548      $o .= html_writer::span('&nbsp;', 'preload-subscribe');
2549      $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
2550      return $o;
2551  }
2552  
2553  /**
2554   * Print the drop down that allows the user to select how they want to have
2555   * the discussion displayed.
2556   *
2557   * @param int $id forum id if $forumtype is 'single',
2558   *              discussion id for any other forum type
2559   * @param mixed $mode forum layout mode
2560   * @param string $forumtype optional
2561   */
2562  function forum_print_mode_form($id, $mode, $forumtype='') {
2563      global $OUTPUT;
2564      $useexperimentalui = get_user_preferences('forum_useexperimentalui', false);
2565      if ($forumtype == 'single') {
2566          $select = new single_select(
2567              new moodle_url("/mod/forum/view.php",
2568              array('f' => $id)),
2569              'mode',
2570              forum_get_layout_modes($useexperimentalui),
2571              $mode,
2572              null,
2573              "mode"
2574          );
2575          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2576          $select->class = "forummode";
2577      } else {
2578          $select = new single_select(
2579              new moodle_url("/mod/forum/discuss.php",
2580              array('d' => $id)),
2581              'mode',
2582              forum_get_layout_modes($useexperimentalui),
2583              $mode,
2584              null,
2585              "mode"
2586          );
2587          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2588      }
2589      echo $OUTPUT->render($select);
2590  }
2591  
2592  /**
2593   * @global object
2594   * @param object $course
2595   * @param string $search
2596   * @return string
2597   */
2598  function forum_search_form($course, $search='') {
2599      global $CFG, $PAGE;
2600      $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2601      $output = $PAGE->get_renderer('mod_forum');
2602      return $output->render($forumsearch);
2603  }
2604  
2605  /**
2606   * Retrieve HTML for the page action
2607   *
2608   * @param forum_entity|null $forum The forum entity.
2609   * @param mixed $groupid false if groups not used, int if groups used, 0 means all groups
2610   * @param stdClass $course The course object.
2611   * @param string $search The search string.
2612   * @return string rendered HTML string.
2613   */
2614  function forum_activity_actionbar(?forum_entity $forum, $groupid, stdClass $course, string $search=''): string {
2615      global $PAGE;
2616  
2617      $actionbar = new mod_forum\output\forum_actionbar($forum, $course, $groupid, $search);
2618      $output = $PAGE->get_renderer('mod_forum');
2619      return $output->render($actionbar);
2620  }
2621  
2622  /**
2623   * @global object
2624   * @global object
2625   */
2626  function forum_set_return() {
2627      global $CFG, $SESSION;
2628  
2629      if (! isset($SESSION->fromdiscussion)) {
2630          $referer = get_local_referer(false);
2631          // If the referer is NOT a login screen then save it.
2632          if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2633              $SESSION->fromdiscussion = $referer;
2634          }
2635      }
2636  }
2637  
2638  
2639  /**
2640   * @global object
2641   * @param string|\moodle_url $default
2642   * @return string
2643   */
2644  function forum_go_back_to($default) {
2645      global $SESSION;
2646  
2647      if (!empty($SESSION->fromdiscussion)) {
2648          $returnto = $SESSION->fromdiscussion;
2649          unset($SESSION->fromdiscussion);
2650          return $returnto;
2651      } else {
2652          return $default;
2653      }
2654  }
2655  
2656  /**
2657   * Given a discussion object that is being moved to $forumto,
2658   * this function checks all posts in that discussion
2659   * for attachments, and if any are found, these are
2660   * moved to the new forum directory.
2661   *
2662   * @global object
2663   * @param object $discussion
2664   * @param int $forumfrom source forum id
2665   * @param int $forumto target forum id
2666   * @return bool success
2667   */
2668  function forum_move_attachments($discussion, $forumfrom, $forumto) {
2669      global $DB;
2670  
2671      $fs = get_file_storage();
2672  
2673      $newcm = get_coursemodule_from_instance('forum', $forumto);
2674      $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2675  
2676      $newcontext = context_module::instance($newcm->id);
2677      $oldcontext = context_module::instance($oldcm->id);
2678  
2679      // loop through all posts, better not use attachment flag ;-)
2680      if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
2681          foreach ($posts as $post) {
2682              $fs->move_area_files_to_new_context($oldcontext->id,
2683                      $newcontext->id, 'mod_forum', 'post', $post->id);
2684              $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2685                      $newcontext->id, 'mod_forum', 'attachment', $post->id);
2686              if ($attachmentsmoved > 0 && $post->attachment != '1') {
2687                  // Weird - let's fix it
2688                  $post->attachment = '1';
2689                  $DB->update_record('forum_posts', $post);
2690              } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2691                  // Weird - let's fix it
2692                  $post->attachment = '';
2693                  $DB->update_record('forum_posts', $post);
2694              }
2695          }
2696      }
2697  
2698      return true;
2699  }
2700  
2701  /**
2702   * Returns attachments as formated text/html optionally with separate images
2703   *
2704   * @global object
2705   * @global object
2706   * @global object
2707   * @param object $post
2708   * @param object $cm
2709   * @param string $type html/text/separateimages
2710   * @return mixed string or array of (html text withouth images and image HTML)
2711   */
2712  function forum_print_attachments($post, $cm, $type) {
2713      global $CFG, $DB, $USER, $OUTPUT;
2714  
2715      if (empty($post->attachment)) {
2716          return $type !== 'separateimages' ? '' : array('', '');
2717      }
2718  
2719      if (!in_array($type, array('separateimages', 'html', 'text'))) {
2720          return $type !== 'separateimages' ? '' : array('', '');
2721      }
2722  
2723      if (!$context = context_module::instance($cm->id)) {
2724          return $type !== 'separateimages' ? '' : array('', '');
2725      }
2726      $strattachment = get_string('attachment', 'forum');
2727  
2728      $fs = get_file_storage();
2729  
2730      $imagereturn = '';
2731      $output = '';
2732  
2733      $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
2734  
2735      if ($canexport) {
2736          require_once($CFG->libdir.'/portfoliolib.php');
2737      }
2738  
2739      // We retrieve all files according to the time that they were created.  In the case that several files were uploaded
2740      // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2741      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
2742      if ($files) {
2743          if ($canexport) {
2744              $button = new portfolio_add_button();
2745          }
2746          foreach ($files as $file) {
2747              $filename = $file->get_filename();
2748              $mimetype = $file->get_mimetype();
2749              $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2750              $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2751  
2752              if ($type == 'html') {
2753                  $output .= "<a href=\"$path\">$iconimage</a> ";
2754                  $output .= "<a href=\"$path\">".s($filename)."</a>";
2755                  if ($canexport) {
2756                      $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2757                      $button->set_format_by_file($file);
2758                      $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2759                  }
2760                  $output .= "<br />";
2761  
2762              } else if ($type == 'text') {
2763                  $output .= "$strattachment ".s($filename).":\n$path\n";
2764  
2765              } else { //'returnimages'
2766                  if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2767                      // Image attachments don't get printed as links
2768                      $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2769                      if ($canexport) {
2770                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2771                          $button->set_format_by_file($file);
2772                          $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2773                      }
2774                  } else {
2775                      $output .= "<a href=\"$path\">$iconimage</a> ";
2776                      $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
2777                      if ($canexport) {
2778                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2779                          $button->set_format_by_file($file);
2780                          $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2781                      }
2782                      $output .= '<br />';
2783                  }
2784              }
2785  
2786              if (!empty($CFG->enableplagiarism)) {
2787                  require_once($CFG->libdir.'/plagiarismlib.php');
2788                  $output .= plagiarism_get_links(array('userid' => $post->userid,
2789                      'file' => $file,
2790                      'cmid' => $cm->id,
2791                      'course' => $cm->course,
2792                      'forum' => $cm->instance));
2793                  $output .= '<br />';
2794              }
2795          }
2796      }
2797  
2798      if ($type !== 'separateimages') {
2799          return $output;
2800  
2801      } else {
2802          return array($output, $imagereturn);
2803      }
2804  }
2805  
2806  ////////////////////////////////////////////////////////////////////////////////
2807  // File API                                                                   //
2808  ////////////////////////////////////////////////////////////////////////////////
2809  
2810  /**
2811   * Lists all browsable file areas
2812   *
2813   * @package  mod_forum
2814   * @category files
2815   * @param stdClass $course course object
2816   * @param stdClass $cm course module object
2817   * @param stdClass $context context object
2818   * @return array
2819   */
2820  function forum_get_file_areas($course, $cm, $context) {
2821      return array(
2822          'attachment' => get_string('areaattachment', 'mod_forum'),
2823          'post' => get_string('areapost', 'mod_forum'),
2824      );
2825  }
2826  
2827  /**
2828   * File browsing support for forum module.
2829   *
2830   * @package  mod_forum
2831   * @category files
2832   * @param stdClass $browser file browser object
2833   * @param stdClass $areas file areas
2834   * @param stdClass $course course object
2835   * @param stdClass $cm course module
2836   * @param stdClass $context context module
2837   * @param string $filearea file area
2838   * @param int $itemid item ID
2839   * @param string $filepath file path
2840   * @param string $filename file name
2841   * @return file_info instance or null if not found
2842   */
2843  function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2844      global $CFG, $DB, $USER;
2845  
2846      if ($context->contextlevel != CONTEXT_MODULE) {
2847          return null;
2848      }
2849  
2850      // filearea must contain a real area
2851      if (!isset($areas[$filearea])) {
2852          return null;
2853      }
2854  
2855      // Note that forum_user_can_see_post() additionally allows access for parent roles
2856      // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2857      // course:managefiles, we will need to extend this.
2858      if (!has_capability('mod/forum:viewdiscussion', $context)) {
2859          return null;
2860      }
2861  
2862      if (is_null($itemid)) {
2863          require_once($CFG->dirroot.'/mod/forum/locallib.php');
2864          return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2865      }
2866  
2867      static $cached = array();
2868      // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2869      // is cleared between unit tests we check if this is the same session
2870      if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2871          $cached = array('sesskey' => sesskey());
2872      }
2873  
2874      if (isset($cached['post']) && $cached['post']->id == $itemid) {
2875          $post = $cached['post'];
2876      } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2877          $cached['post'] = $post;
2878      } else {
2879          return null;
2880      }
2881  
2882      if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2883          $discussion = $cached['discussion'];
2884      } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2885          $cached['discussion'] = $discussion;
2886      } else {
2887          return null;
2888      }
2889  
2890      if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2891          $forum = $cached['forum'];
2892      } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2893          $cached['forum'] = $forum;
2894      } else {
2895          return null;
2896      }
2897  
2898      $fs = get_file_storage();
2899      $filepath = is_null($filepath) ? '/' : $filepath;
2900      $filename = is_null($filename) ? '.' : $filename;
2901      if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2902          return null;
2903      }
2904  
2905      // Checks to see if the user can manage files or is the owner.
2906      // TODO MDL-33805 - Do not use userid here and move the capability check above.
2907      if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2908          return null;
2909      }
2910      // Make sure groups allow this user to see this file
2911      if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2912          $groupmode = groups_get_activity_groupmode($cm, $course);
2913          if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2914              return null;
2915          }
2916      }
2917  
2918      // Make sure we're allowed to see it...
2919      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2920          return null;
2921      }
2922  
2923      $urlbase = $CFG->wwwroot.'/pluginfile.php';
2924      return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2925  }
2926  
2927  /**
2928   * Serves the forum attachments. Implements needed access control ;-)
2929   *
2930   * @package  mod_forum
2931   * @category files
2932   * @param stdClass $course course object
2933   * @param stdClass $cm course module object
2934   * @param stdClass $context context object
2935   * @param string $filearea file area
2936   * @param array $args extra arguments
2937   * @param bool $forcedownload whether or not force download
2938   * @param array $options additional options affecting the file serving
2939   * @return bool false if file not found, does not return if found - justsend the file
2940   */
2941  function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2942      global $CFG, $DB;
2943  
2944      if ($context->contextlevel != CONTEXT_MODULE) {
2945          return false;
2946      }
2947  
2948      require_course_login($course, true, $cm);
2949  
2950      $areas = forum_get_file_areas($course, $cm, $context);
2951  
2952      // filearea must contain a real area
2953      if (!isset($areas[$filearea])) {
2954          return false;
2955      }
2956  
2957      $postid = (int)array_shift($args);
2958  
2959      if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2960          return false;
2961      }
2962  
2963      if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
2964          return false;
2965      }
2966  
2967      if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
2968          return false;
2969      }
2970  
2971      $fs = get_file_storage();
2972      $relativepath = implode('/', $args);
2973      $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
2974      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2975          return false;
2976      }
2977  
2978      // Make sure groups allow this user to see this file
2979      if ($discussion->groupid > 0) {
2980          $groupmode = groups_get_activity_groupmode($cm, $course);
2981          if ($groupmode == SEPARATEGROUPS) {
2982              if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2983                  return false;
2984              }
2985          }
2986      }
2987  
2988      // Make sure we're allowed to see it...
2989      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2990          return false;
2991      }
2992  
2993      // finally send the file
2994      send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
2995  }
2996  
2997  /**
2998   * If successful, this function returns the name of the file
2999   *
3000   * @global object
3001   * @param object $post is a full post record, including course and forum
3002   * @param object $forum
3003   * @param object $cm
3004   * @param mixed $mform
3005   * @param string $unused
3006   * @return bool
3007   */
3008  function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
3009      global $DB;
3010  
3011      if (empty($mform)) {
3012          return false;
3013      }
3014  
3015      if (empty($post->attachments)) {
3016          return true;   // Nothing to do
3017      }
3018  
3019      $context = context_module::instance($cm->id);
3020  
3021      $info = file_get_draft_area_info($post->attachments);
3022      $present = ($info['filecount']>0) ? '1' : '';
3023      file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
3024              mod_forum_post_form::attachment_options($forum));
3025  
3026      $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
3027  
3028      return true;
3029  }
3030  
3031  /**
3032   * Add a new post in an existing discussion.
3033   *
3034   * @param   stdClass    $post       The post data
3035   * @param   mixed       $mform      The submitted form
3036   * @param   string      $unused
3037   * @return int
3038   */
3039  function forum_add_new_post($post, $mform, $unused = null) {
3040      global $USER, $DB;
3041  
3042      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3043      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3044      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3045      $context    = context_module::instance($cm->id);
3046      $privatereplyto = 0;
3047  
3048      // Check whether private replies should be enabled for this post.
3049      if ($post->parent) {
3050          $parent = $DB->get_record('forum_posts', array('id' => $post->parent));
3051  
3052          if (!empty($parent->privatereplyto)) {
3053              throw new \coding_exception('It should not be possible to reply to a private reply');
3054          }
3055  
3056          if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) {
3057              $privatereplyto = $parent->userid;
3058          }
3059      }
3060  
3061      $post->created    = $post->modified = time();
3062      $post->mailed     = FORUM_MAILED_PENDING;
3063      $post->userid     = $USER->id;
3064      $post->privatereplyto = $privatereplyto;
3065      $post->attachment = "";
3066      if (!isset($post->totalscore)) {
3067          $post->totalscore = 0;
3068      }
3069      if (!isset($post->mailnow)) {
3070          $post->mailnow    = 0;
3071      }
3072  
3073      \mod_forum\local\entities\post::add_message_counts($post);
3074      $post->id = $DB->insert_record("forum_posts", $post);
3075      $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
3076              mod_forum_post_form::editor_options($context, null), $post->message);
3077      $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
3078      forum_add_attachment($post, $forum, $cm, $mform);
3079  
3080      // Update discussion modified date
3081      $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
3082      $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
3083  
3084      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3085          forum_tp_mark_post_read($post->userid, $post);
3086      }
3087  
3088      if (isset($post->tags)) {
3089          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
3090      }
3091  
3092      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3093      forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
3094  
3095      return $post->id;
3096  }
3097  
3098  /**
3099   * Trigger post updated event.
3100   *
3101   * @param object $post forum post object
3102   * @param object $discussion discussion object
3103   * @param object $context forum context object
3104   * @param object $forum forum object
3105   * @since Moodle 3.8
3106   * @return void
3107   */
3108  function forum_trigger_post_updated_event($post, $discussion, $context, $forum) {
3109      global $USER;
3110  
3111      $params = array(
3112          'context' => $context,
3113          'objectid' => $post->id,
3114          'other' => array(
3115              'discussionid' => $discussion->id,
3116              'forumid' => $forum->id,
3117              'forumtype' => $forum->type,
3118          )
3119      );
3120  
3121      if ($USER->id !== $post->userid) {
3122          $params['relateduserid'] = $post->userid;
3123      }
3124  
3125      $event = \mod_forum\event\post_updated::create($params);
3126      $event->add_record_snapshot('forum_discussions', $discussion);
3127      $event->trigger();
3128  }
3129  
3130  /**
3131   * Update a post.
3132   *
3133   * @param   stdClass    $newpost    The post to update
3134   * @param   mixed       $mform      The submitted form
3135   * @param   string      $unused
3136   * @return  bool
3137   */
3138  function forum_update_post($newpost, $mform, $unused = null) {
3139      global $DB, $USER;
3140  
3141      $post       = $DB->get_record('forum_posts', array('id' => $newpost->id));
3142      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3143      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3144      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3145      $context    = context_module::instance($cm->id);
3146  
3147      // Allowed modifiable fields.
3148      $modifiablefields = [
3149          'subject',
3150          'message',
3151          'messageformat',
3152          'messagetrust',
3153          'timestart',
3154          'timeend',
3155          'pinned',
3156          'attachments',
3157      ];
3158      foreach ($modifiablefields as $field) {
3159          if (isset($newpost->{$field})) {
3160              $post->{$field} = $newpost->{$field};
3161          }
3162      }
3163      $post->modified = time();
3164  
3165      if (!$post->parent) {   // Post is a discussion starter - update discussion title and times too
3166          $discussion->name      = $post->subject;
3167          $discussion->timestart = $post->timestart;
3168          $discussion->timeend   = $post->timeend;
3169  
3170          if (isset($post->pinned)) {
3171              $discussion->pinned = $post->pinned;
3172          }
3173      }
3174      $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
3175              mod_forum_post_form::editor_options($context, $post->id), $post->message);
3176      \mod_forum\local\entities\post::add_message_counts($post);
3177      $DB->update_record('forum_posts', $post);
3178      // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3179      $DB->update_record('forum_discussions', $discussion);
3180  
3181      forum_add_attachment($post, $forum, $cm, $mform);
3182  
3183      if ($forum->type == 'single' && $post->parent == '0') {
3184          // Updating first post of single discussion type -> updating forum intro.
3185          $forum->intro = $post->message;
3186          $forum->timemodified = time();
3187          $DB->update_record("forum", $forum);
3188      }
3189  
3190      if (isset($newpost->tags)) {
3191          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3192      }
3193  
3194      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3195          forum_tp_mark_post_read($USER->id, $post);
3196      }
3197  
3198      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3199      forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3200  
3201      return true;
3202  }
3203  
3204  /**
3205   * Given an object containing all the necessary data,
3206   * create a new discussion and return the id
3207   *
3208   * @param object $post
3209   * @param mixed $mform
3210   * @param string $unused
3211   * @param int $userid
3212   * @return object
3213   */
3214  function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3215      global $USER, $CFG, $DB;
3216  
3217      $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
3218  
3219      if (is_null($userid)) {
3220          $userid = $USER->id;
3221      }
3222  
3223      // The first post is stored as a real post, and linked
3224      // to from the discuss entry.
3225  
3226      $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
3227      $cm    = get_coursemodule_from_instance('forum', $forum->id);
3228  
3229      $post = new stdClass();
3230      $post->discussion    = 0;
3231      $post->parent        = 0;
3232      $post->privatereplyto = 0;
3233      $post->userid        = $userid;
3234      $post->created       = $timenow;
3235      $post->modified      = $timenow;
3236      $post->mailed        = FORUM_MAILED_PENDING;
3237      $post->subject       = $discussion->name;
3238      $post->message       = $discussion->message;
3239      $post->messageformat = $discussion->messageformat;
3240      $post->messagetrust  = $discussion->messagetrust;
3241      $post->attachments   = isset($discussion->attachments) ? $discussion->attachments : null;
3242      $post->forum         = $forum->id;     // speedup
3243      $post->course        = $forum->course; // speedup
3244      $post->mailnow       = $discussion->mailnow;
3245  
3246      \mod_forum\local\entities\post::add_message_counts($post);
3247      $post->id = $DB->insert_record("forum_posts", $post);
3248  
3249      // TODO: Fix the calling code so that there always is a $cm when this function is called
3250      if (!empty($cm->id) && !empty($discussion->itemid)) {   // In "single simple discussions" this may not exist yet
3251          $context = context_module::instance($cm->id);
3252          $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
3253                  mod_forum_post_form::editor_options($context, null), $post->message);
3254          $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
3255      }
3256  
3257      // Now do the main entry for the discussion, linking to this first post
3258  
3259      $discussion->firstpost    = $post->id;
3260      $discussion->timemodified = $timenow;
3261      $discussion->usermodified = $post->userid;
3262      $discussion->userid       = $userid;
3263      $discussion->assessed     = 0;
3264  
3265      $post->discussion = $DB->insert_record("forum_discussions", $discussion);
3266  
3267      // Finally, set the pointer on the post.
3268      $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
3269  
3270      if (!empty($cm->id)) {
3271          forum_add_attachment($post, $forum, $cm, $mform, $unused);
3272      }
3273  
3274      if (isset($discussion->tags)) {
3275          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
3276      }
3277  
3278      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3279          forum_tp_mark_post_read($post->userid, $post);
3280      }
3281  
3282      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3283      if (!empty($cm->id)) {
3284          forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3285      }
3286  
3287      return $post->discussion;
3288  }
3289  
3290  
3291  /**
3292   * Deletes a discussion and handles all associated cleanup.
3293   *
3294   * @global object
3295   * @param object $discussion Discussion to delete
3296   * @param bool $fulldelete True when deleting entire forum
3297   * @param object $course Course
3298   * @param object $cm Course-module
3299   * @param object $forum Forum
3300   * @return bool
3301   */
3302  function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3303      global $DB, $CFG;
3304      require_once($CFG->libdir.'/completionlib.php');
3305  
3306      $result = true;
3307  
3308      if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
3309          foreach ($posts as $post) {
3310              $post->course = $discussion->course;
3311              $post->forum  = $discussion->forum;
3312              if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3313                  $result = false;
3314              }
3315          }
3316      }
3317  
3318      forum_tp_delete_read_records(-1, -1, $discussion->id);
3319  
3320      // Discussion subscriptions must be removed before discussions because of key constraints.
3321      $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
3322      if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
3323          $result = false;
3324      }
3325  
3326      // Update completion state if we are tracking completion based on number of posts
3327      // But don't bother when deleting whole thing
3328      if (!$fulldelete) {
3329          $completion = new completion_info($course);
3330          if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3331             ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3332              $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
3333          }
3334      }
3335  
3336      $params = array(
3337          'objectid' => $discussion->id,
3338          'context' => context_module::instance($cm->id),
3339          'other' => array(
3340              'forumid' => $forum->id,
3341          )
3342      );
3343      $event = \mod_forum\event\discussion_deleted::create($params);
3344      $event->add_record_snapshot('forum_discussions', $discussion);
3345      $event->trigger();
3346  
3347      return $result;
3348  }
3349  
3350  
3351  /**
3352   * Deletes a single forum post.
3353   *
3354   * @global object
3355   * @param object $post Forum post object
3356   * @param mixed $children Whether to delete children. If false, returns false
3357   *   if there are any children (without deleting the post). If true,
3358   *   recursively deletes all children. If set to special value 'ignore', deletes
3359   *   post regardless of children (this is for use only when deleting all posts
3360   *   in a disussion).
3361   * @param object $course Course
3362   * @param object $cm Course-module
3363   * @param object $forum Forum
3364   * @param bool $skipcompletion True to skip updating completion state if it
3365   *   would otherwise be updated, i.e. when deleting entire forum anyway.
3366   * @return bool
3367   */
3368  function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3369      global $DB, $CFG, $USER;
3370      require_once($CFG->libdir.'/completionlib.php');
3371  
3372      $context = context_module::instance($cm->id);
3373  
3374      if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
3375         if ($children) {
3376             foreach ($childposts as $childpost) {
3377                 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3378             }
3379         } else {
3380             return false;
3381         }
3382      }
3383  
3384      // Delete ratings.
3385      require_once($CFG->dirroot.'/rating/lib.php');
3386      $delopt = new stdClass;
3387      $delopt->contextid = $context->id;
3388      $delopt->component = 'mod_forum';
3389      $delopt->ratingarea = 'post';
3390      $delopt->itemid = $post->id;
3391      $rm = new rating_manager();
3392      $rm->delete_ratings($delopt);
3393  
3394      // Delete attachments.
3395      $fs = get_file_storage();
3396      $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
3397      $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
3398  
3399      // Delete cached RSS feeds.
3400      if (!empty($CFG->enablerssfeeds)) {
3401          require_once($CFG->dirroot.'/mod/forum/rsslib.php');
3402          forum_rss_delete_file($forum);
3403      }
3404  
3405      if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
3406  
3407          forum_tp_delete_read_records(-1, $post->id);
3408  
3409      // Just in case we are deleting the last post
3410          forum_discussion_update_last_post($post->discussion);
3411  
3412          // Update completion state if we are tracking completion based on number of posts
3413          // But don't bother when deleting whole thing
3414  
3415          if (!$skipcompletion) {
3416              $completion = new completion_info($course);
3417              if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3418                 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3419                  $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
3420              }
3421          }
3422  
3423          $params = array(
3424              'context' => $context,
3425              'objectid' => $post->id,
3426              'other' => array(
3427                  'discussionid' => $post->discussion,
3428                  'forumid' => $forum->id,
3429                  'forumtype' => $forum->type,
3430              )
3431          );
3432          $post->deleted = 1;
3433          if ($post->userid !== $USER->id) {
3434              $params['relateduserid'] = $post->userid;
3435          }
3436          $event = \mod_forum\event\post_deleted::create($params);
3437          $event->add_record_snapshot('forum_posts', $post);
3438          $event->trigger();
3439  
3440          return true;
3441      }
3442      return false;
3443  }
3444  
3445  /**
3446   * Sends post content to plagiarism plugin
3447   * @param object $post Forum post object
3448   * @param object $cm Course-module
3449   * @param string $name
3450   * @return bool
3451  */
3452  function forum_trigger_content_uploaded_event($post, $cm, $name) {
3453      $context = context_module::instance($cm->id);
3454      $fs = get_file_storage();
3455      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
3456      $params = array(
3457          'context' => $context,
3458          'objectid' => $post->id,
3459          'other' => array(
3460              'content' => $post->message,
3461              'pathnamehashes' => array_keys($files),
3462              'discussionid' => $post->discussion,
3463              'triggeredfrom' => $name,
3464          )
3465      );
3466      $event = \mod_forum\event\assessable_uploaded::create($params);
3467      $event->trigger();
3468      return true;
3469  }
3470  
3471  /**
3472   * Given a new post, subscribes or unsubscribes as appropriate.
3473   * Returns some text which describes what happened.
3474   *
3475   * @param object $fromform The submitted form
3476   * @param stdClass $forum The forum record
3477   * @param stdClass $discussion The forum discussion record
3478   * @return string
3479   */
3480  function forum_post_subscription($fromform, $forum, $discussion) {
3481      global $USER;
3482  
3483      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3484          return "";
3485      } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
3486          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3487          if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
3488              // This user should not be subscribed to the forum.
3489              \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
3490          }
3491          return "";
3492      }
3493  
3494      $info = new stdClass();
3495      $info->name  = fullname($USER);
3496      $info->discussion = format_string($discussion->name);
3497      $info->forum = format_string($forum->name);
3498  
3499      if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
3500          if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
3501              return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3502          }
3503      } else {
3504          if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
3505              return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3506          }
3507      }
3508  
3509      return '';
3510  }
3511  
3512  /**
3513   * Generate and return the subscribe or unsubscribe link for a forum.
3514   *
3515   * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3516   * @param object $context the context object for this forum.
3517   * @param array $messages text used for the link in its various states
3518   *      (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3519   *      Any strings not passed in are taken from the $defaultmessages array
3520   *      at the top of the function.
3521   * @param bool $cantaccessagroup
3522   * @param bool $unused1
3523   * @param bool $backtoindex
3524   * @param array $unused2
3525   * @return string
3526   */
3527  function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3528      $backtoindex = false, $unused2 = null) {
3529      global $CFG, $USER, $PAGE, $OUTPUT;
3530      $defaultmessages = array(
3531          'subscribed' => get_string('unsubscribe', 'forum'),
3532          'unsubscribed' => get_string('subscribe', 'forum'),
3533          'cantaccessgroup' => get_string('no'),
3534          'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3535          'cantsubscribe' => get_string('disallowsubscribe','forum')
3536      );
3537      $messages = $messages + $defaultmessages;
3538  
3539      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3540          return $messages['forcesubscribed'];
3541      } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
3542              !has_capability('mod/forum:managesubscriptions', $context)) {
3543          return $messages['cantsubscribe'];
3544      } else if ($cantaccessagroup) {
3545          return $messages['cantaccessgroup'];
3546      } else {
3547          if (!is_enrolled($context, $USER, '', true)) {
3548              return '';
3549          }
3550  
3551          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3552          if ($subscribed) {
3553              $linktext = $messages['subscribed'];
3554              $linktitle = get_string('subscribestop', 'forum');
3555          } else {
3556              $linktext = $messages['unsubscribed'];
3557              $linktitle = get_string('subscribestart', 'forum');
3558          }
3559  
3560          $options = array();
3561          if ($backtoindex) {
3562              $backtoindexlink = '&amp;backtoindex=1';
3563              $options['backtoindex'] = 1;
3564          } else {
3565              $backtoindexlink = '';
3566          }
3567  
3568          $options['id'] = $forum->id;
3569          $options['sesskey'] = sesskey();
3570          $url = new moodle_url('/mod/forum/subscribe.php', $options);
3571          return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3572      }
3573  }
3574  
3575  /**
3576   * Returns true if user created new discussion already.
3577   *
3578   * @param int $forumid  The forum to check for postings
3579   * @param int $userid   The user to check for postings
3580   * @param int $groupid  The group to restrict the check to
3581   * @return bool
3582   */
3583  function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3584      global $CFG, $DB;
3585  
3586      $sql = "SELECT 'x'
3587                FROM {forum_discussions} d, {forum_posts} p
3588               WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3589  
3590      $params = [$forumid, $userid];
3591  
3592      if ($groupid) {
3593          $sql .= " AND d.groupid = ?";
3594          $params[] = $groupid;
3595      }
3596  
3597      return $DB->record_exists_sql($sql, $params);
3598  }
3599  
3600  /**
3601   * @global object
3602   * @global object
3603   * @param int $forumid
3604   * @param int $userid
3605   * @return array
3606   */
3607  function forum_discussions_user_has_posted_in($forumid, $userid) {
3608      global $CFG, $DB;
3609  
3610      $haspostedsql = "SELECT d.id AS id,
3611                              d.*
3612                         FROM {forum_posts} p,
3613                              {forum_discussions} d
3614                        WHERE p.discussion = d.id
3615                          AND d.forum = ?
3616                          AND p.userid = ?";
3617  
3618      return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3619  }
3620  
3621  /**
3622   * @global object
3623   * @global object
3624   * @param int $forumid
3625   * @param int $did
3626   * @param int $userid
3627   * @return bool
3628   */
3629  function forum_user_has_posted($forumid, $did, $userid) {
3630      global $DB;
3631  
3632      if (empty($did)) {
3633          // posted in any forum discussion?
3634          $sql = "SELECT 'x'
3635                    FROM {forum_posts} p
3636                    JOIN {forum_discussions} d ON d.id = p.discussion
3637                   WHERE p.userid = :userid AND d.forum = :forumid";
3638          return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3639      } else {
3640          return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3641      }
3642  }
3643  
3644  /**
3645   * Returns creation time of the first user's post in given discussion
3646   * @global object $DB
3647   * @param int $did Discussion id
3648   * @param int $userid User id
3649   * @return int|bool post creation time stamp or return false
3650   */
3651  function forum_get_user_posted_time($did, $userid) {
3652      global $DB;
3653  
3654      $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3655      if (empty($posttime)) {
3656          return false;
3657      }
3658      return $posttime;
3659  }
3660  
3661  /**
3662   * @global object
3663   * @param object $forum
3664   * @param object $currentgroup
3665   * @param int $unused
3666   * @param object $cm
3667   * @param object $context
3668   * @return bool
3669   */
3670  function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3671  // $forum is an object
3672      global $USER;
3673  
3674      // shortcut - guest and not-logged-in users can not post
3675      if (isguestuser() or !isloggedin()) {
3676          return false;
3677      }
3678  
3679      if (!$cm) {
3680          debugging('missing cm', DEBUG_DEVELOPER);
3681          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3682              throw new \moodle_exception('invalidcoursemodule');
3683          }
3684      }
3685  
3686      if (!$context) {
3687          $context = context_module::instance($cm->id);
3688      }
3689  
3690      if (forum_is_cutoff_date_reached($forum)) {
3691          if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3692              return false;
3693          }
3694      }
3695  
3696      if ($currentgroup === null) {
3697          $currentgroup = groups_get_activity_group($cm);
3698      }
3699  
3700      $groupmode = groups_get_activity_groupmode($cm);
3701  
3702      if ($forum->type == 'news') {
3703          $capname = 'mod/forum:addnews';
3704      } else if ($forum->type == 'qanda') {
3705          $capname = 'mod/forum:addquestion';
3706      } else {
3707          $capname = 'mod/forum:startdiscussion';
3708      }
3709  
3710      if (!has_capability($capname, $context)) {
3711          return false;
3712      }
3713  
3714      if ($forum->type == 'single') {
3715          return false;
3716      }
3717  
3718      if ($forum->type == 'eachuser') {
3719          if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) {
3720              return false;
3721          }
3722      }
3723  
3724      if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
3725          return true;
3726      }
3727  
3728      if ($currentgroup) {
3729          return groups_is_member($currentgroup);
3730      } else {
3731          // no group membership and no accessallgroups means no new discussions
3732          // reverted to 1.7 behaviour in 1.9+,  buggy in 1.8.0-1.9.0
3733          return false;
3734      }
3735  }
3736  
3737  /**
3738   * This function checks whether the user can reply to posts in a forum
3739   * discussion. Use forum_user_can_post_discussion() to check whether the user
3740   * can start discussions.
3741   *
3742   * @global object
3743   * @global object
3744   * @uses DEBUG_DEVELOPER
3745   * @uses CONTEXT_MODULE
3746   * @uses VISIBLEGROUPS
3747   * @param object $forum forum object
3748   * @param object $discussion
3749   * @param object $user
3750   * @param object $cm
3751   * @param object $course
3752   * @param object $context
3753   * @return bool
3754   */
3755  function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
3756      global $USER, $DB;
3757      if (empty($user)) {
3758          $user = $USER;
3759      }
3760  
3761      // shortcut - guest and not-logged-in users can not post
3762      if (isguestuser($user) or empty($user->id)) {
3763          return false;
3764      }
3765  
3766      if (!isset($discussion->groupid)) {
3767          debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
3768          return false;
3769      }
3770  
3771      if (!$cm) {
3772          debugging('missing cm', DEBUG_DEVELOPER);
3773          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3774              throw new \moodle_exception('invalidcoursemodule');
3775          }
3776      }
3777  
3778      if (!$course) {
3779          debugging('missing course', DEBUG_DEVELOPER);
3780          if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
3781              throw new \moodle_exception('invalidcourseid');
3782          }
3783      }
3784  
3785      if (!$context) {
3786          $context = context_module::instance($cm->id);
3787      }
3788  
3789      if (forum_is_cutoff_date_reached($forum)) {
3790          if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3791              return false;
3792          }
3793      }
3794  
3795      // Check whether the discussion is locked.
3796      if (forum_discussion_is_locked($forum, $discussion)) {
3797          if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
3798              return false;
3799          }
3800      }
3801  
3802      // normal users with temporary guest access can not post, suspended users can not post either
3803      if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
3804          return false;
3805      }
3806  
3807      if ($forum->type == 'news') {
3808          $capname = 'mod/forum:replynews';
3809      } else {
3810          $capname = 'mod/forum:replypost';
3811      }
3812  
3813      if (!has_capability($capname, $context, $user->id)) {
3814          return false;
3815      }
3816  
3817      if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
3818          return true;
3819      }
3820  
3821      if (has_capability('moodle/site:accessallgroups', $context)) {
3822          return true;
3823      }
3824  
3825      if ($groupmode == VISIBLEGROUPS) {
3826          if ($discussion->groupid == -1) {
3827              // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
3828              return true;
3829          }
3830          return groups_is_member($discussion->groupid);
3831  
3832      } else {
3833          //separate groups
3834          if ($discussion->groupid == -1) {
3835              return false;
3836          }
3837          return groups_is_member($discussion->groupid);
3838      }
3839  }
3840  
3841  /**
3842  * Check to ensure a user can view a timed discussion.
3843  *
3844  * @param object $discussion
3845  * @param object $user
3846  * @param object $context
3847  * @return boolean returns true if they can view post, false otherwise
3848  */
3849  function forum_user_can_see_timed_discussion($discussion, $user, $context) {
3850      global $CFG;
3851  
3852      // Check that the user can view a discussion that is normally hidden due to access times.
3853      if (!empty($CFG->forum_enabletimedposts)) {
3854          $time = time();
3855          if (($discussion->timestart != 0 && $discussion->timestart > $time)
3856              || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
3857              if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
3858                  return false;
3859              }
3860          }
3861      }
3862  
3863      return true;
3864  }
3865  
3866  /**
3867  * Check to ensure a user can view a group discussion.
3868  *
3869  * @param object $discussion
3870  * @param object $cm
3871  * @param object $context
3872  * @return boolean returns true if they can view post, false otherwise
3873  */
3874  function forum_user_can_see_group_discussion($discussion, $cm, $context) {
3875  
3876      // If it's a grouped discussion, make sure the user is a member.
3877      if ($discussion->groupid > 0) {
3878          $groupmode = groups_get_activity_groupmode($cm);
3879          if ($groupmode == SEPARATEGROUPS) {
3880              return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
3881          }
3882      }
3883  
3884      return true;
3885  }
3886  
3887  /**
3888   * @global object
3889   * @global object
3890   * @uses DEBUG_DEVELOPER
3891   * @param object $forum
3892   * @param object $discussion
3893   * @param object $context
3894   * @param object $user
3895   * @return bool
3896   */
3897  function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
3898      global $USER, $DB;
3899  
3900      if (empty($user) || empty($user->id)) {
3901          $user = $USER;
3902      }
3903  
3904      // retrieve objects (yuk)
3905      if (is_numeric($forum)) {
3906          debugging('missing full forum', DEBUG_DEVELOPER);
3907          if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3908              return false;
3909          }
3910      }
3911      if (is_numeric($discussion)) {
3912          debugging('missing full discussion', DEBUG_DEVELOPER);
3913          if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3914              return false;
3915          }
3916      }
3917      if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3918          throw new \moodle_exception('invalidcoursemodule');
3919      }
3920  
3921      if (!has_capability('mod/forum:viewdiscussion', $context)) {
3922          return false;
3923      }
3924  
3925      if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
3926          return false;
3927      }
3928  
3929      if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
3930          return false;
3931      }
3932  
3933      return true;
3934  }
3935  
3936  /**
3937   * Check whether a user can see the specified post.
3938   *
3939   * @param   \stdClass $forum The forum to chcek
3940   * @param   \stdClass $discussion The discussion the post is in
3941   * @param   \stdClass $post The post in question
3942   * @param   \stdClass $user The user to test - if not specified, the current user is checked.
3943   * @param   \stdClass $cm The Course Module that the forum is in (required).
3944   * @param   bool      $checkdeleted Whether to check the deleted flag on the post.
3945   * @return  bool
3946   */
3947  function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) {
3948      global $CFG, $USER, $DB;
3949  
3950      // retrieve objects (yuk)
3951      if (is_numeric($forum)) {
3952          debugging('missing full forum', DEBUG_DEVELOPER);
3953          if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3954              return false;
3955          }
3956      }
3957  
3958      if (is_numeric($discussion)) {
3959          debugging('missing full discussion', DEBUG_DEVELOPER);
3960          if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3961              return false;
3962          }
3963      }
3964      if (is_numeric($post)) {
3965          debugging('missing full post', DEBUG_DEVELOPER);
3966          if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
3967              return false;
3968          }
3969      }
3970  
3971      if (!isset($post->id) && isset($post->parent)) {
3972          $post->id = $post->parent;
3973      }
3974  
3975      if ($checkdeleted && !empty($post->deleted)) {
3976          return false;
3977      }
3978  
3979      if (!$cm) {
3980          debugging('missing cm', DEBUG_DEVELOPER);
3981          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3982              throw new \moodle_exception('invalidcoursemodule');
3983          }
3984      }
3985  
3986      // Context used throughout function.
3987      $modcontext = context_module::instance($cm->id);
3988  
3989      if (empty($user) || empty($user->id)) {
3990          $user = $USER;
3991      }
3992  
3993      $canviewdiscussion = (isset($cm->cache) && !empty($cm->cache->caps['mod/forum:viewdiscussion']))
3994          || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
3995      if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
3996          return false;
3997      }
3998  
3999      if (!forum_post_is_visible_privately($post, $cm)) {
4000          return false;
4001      }
4002  
4003      if (isset($cm->uservisible)) {
4004          if (!$cm->uservisible) {
4005              return false;
4006          }
4007      } else {
4008          if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
4009              return false;
4010          }
4011      }
4012  
4013      if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
4014          return false;
4015      }
4016  
4017      if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
4018          return false;
4019      }
4020  
4021      if ($forum->type == 'qanda') {
4022          if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id) || $post->userid == $user->id
4023                  || (isset($discussion->firstpost) && $discussion->firstpost == $post->id)) {
4024              return true;
4025          }
4026          $firstpost = forum_get_firstpost_from_discussion($discussion->id);
4027          if ($firstpost->userid == $user->id) {
4028              return true;
4029          }
4030          $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
4031          return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)));
4032      }
4033      return true;
4034  }
4035  
4036  /**
4037   * Returns all forum posts since a given time in specified forum.
4038   *
4039   * @todo Document this functions args
4040   * @global object
4041   * @global object
4042   * @global object
4043   * @global object
4044   */
4045  function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0)  {
4046      global $CFG, $COURSE, $USER, $DB;
4047  
4048      if ($COURSE->id == $courseid) {
4049          $course = $COURSE;
4050      } else {
4051          $course = $DB->get_record('course', array('id' => $courseid));
4052      }
4053  
4054      $modinfo = get_fast_modinfo($course);
4055  
4056      $cm = $modinfo->cms[$cmid];
4057      $params = array($timestart, $cm->instance);
4058  
4059      if ($userid) {
4060          $userselect = "AND u.id = ?";
4061          $params[] = $userid;
4062      } else {
4063          $userselect = "";
4064      }
4065  
4066      if ($groupid) {
4067          $groupselect = "AND d.groupid = ?";
4068          $params[] = $groupid;
4069      } else {
4070          $groupselect = "";
4071      }
4072  
4073      $userfieldsapi = \core_user\fields::for_name();
4074      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4075      if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
4076                                                d.timestart, d.timeend, d.userid AS duserid,
4077                                                $allnames, u.email, u.picture, u.imagealt, u.email
4078                                           FROM {forum_posts} p
4079                                                JOIN {forum_discussions} d ON d.id = p.discussion
4080                                                JOIN {forum} f             ON f.id = d.forum
4081                                                JOIN {user} u              ON u.id = p.userid
4082                                          WHERE p.created > ? AND f.id = ?
4083                                                $userselect $groupselect
4084                                       ORDER BY p.id ASC", $params)) { // order by initial posting date
4085           return;
4086      }
4087  
4088      $groupmode       = groups_get_activity_groupmode($cm, $course);
4089      $cm_context      = context_module::instance($cm->id);
4090      $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
4091      $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
4092  
4093      $printposts = array();
4094      foreach ($posts as $post) {
4095  
4096          if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
4097            and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
4098              if (!$viewhiddentimed) {
4099                  continue;
4100              }
4101          }
4102  
4103          if ($groupmode) {
4104              if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
4105                  // oki (Open discussions have groupid -1)
4106              } else {
4107                  // separate mode
4108                  if (isguestuser()) {
4109                      // shortcut
4110                      continue;
4111                  }
4112  
4113                  if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
4114                      continue;
4115                  }
4116              }
4117          }
4118  
4119          $printposts[] = $post;
4120      }
4121  
4122      if (!$printposts) {
4123          return;
4124      }
4125  
4126      $aname = format_string($cm->name,true);
4127  
4128      foreach ($printposts as $post) {
4129          $tmpactivity = new stdClass();
4130  
4131          $tmpactivity->type         = 'forum';
4132          $tmpactivity->cmid         = $cm->id;
4133          $tmpactivity->name         = $aname;
4134          $tmpactivity->sectionnum   = $cm->sectionnum;
4135          $tmpactivity->timestamp    = $post->modified;
4136  
4137          $tmpactivity->content = new stdClass();
4138          $tmpactivity->content->id         = $post->id;
4139          $tmpactivity->content->discussion = $post->discussion;
4140          $tmpactivity->content->subject    = format_string($post->subject);
4141          $tmpactivity->content->parent     = $post->parent;
4142          $tmpactivity->content->forumtype  = $post->forumtype;
4143  
4144          $tmpactivity->user = new stdClass();
4145          $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
4146          $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
4147          $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
4148          $tmpactivity->user->id = $post->userid;
4149  
4150          $activities[$index++] = $tmpactivity;
4151      }
4152  
4153      return;
4154  }
4155  
4156  /**
4157   * Outputs the forum post indicated by $activity.
4158   *
4159   * @param object $activity      the activity object the forum resides in
4160   * @param int    $courseid      the id of the course the forum resides in
4161   * @param bool   $detail        not used, but required for compatibilty with other modules
4162   * @param int    $modnames      not used, but required for compatibilty with other modules
4163   * @param bool   $viewfullnames not used, but required for compatibilty with other modules
4164   */
4165  function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
4166      global $OUTPUT;
4167  
4168      $content = $activity->content;
4169      if ($content->parent) {
4170          $class = 'reply';
4171      } else {
4172          $class = 'discussion';
4173      }
4174  
4175      $tableoptions = [
4176          'border' => '0',
4177          'cellpadding' => '3',
4178          'cellspacing' => '0',
4179          'class' => 'forum-recent'
4180      ];
4181      $output = html_writer::start_tag('table', $tableoptions);
4182      $output .= html_writer::start_tag('tr');
4183  
4184      $post = (object) ['parent' => $content->parent];
4185      $forum = (object) ['type' => $content->forumtype];
4186      $authorhidden = forum_is_author_hidden($post, $forum);
4187  
4188      // Show user picture if author should not be hidden.
4189      if (!$authorhidden) {
4190          $pictureoptions = [
4191              'courseid' => $courseid,
4192              'link' => $authorhidden,
4193              'alttext' => $authorhidden,
4194          ];
4195          $picture = $OUTPUT->user_picture($activity->user, $pictureoptions);
4196          $output .= html_writer::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
4197      }
4198  
4199      // Discussion title and author.
4200      $output .= html_writer::start_tag('td', ['class' => $class]);
4201      if ($content->parent) {
4202          $class = 'title';
4203      } else {
4204          // Bold the title of new discussions so they stand out.
4205          $class = 'title bold';
4206      }
4207  
4208      $output .= html_writer::start_div($class);
4209      if ($detail) {
4210          $aname = s($activity->name);
4211          $output .= $OUTPUT->image_icon('monologo', $aname, $activity->type);
4212      }
4213      $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion]);
4214      $discussionurl->set_anchor('p' . $activity->content->id);
4215      $output .= html_writer::link($discussionurl, $content->subject);
4216      $output .= html_writer::end_div();
4217  
4218      $timestamp = userdate_htmltime($activity->timestamp);
4219      if ($authorhidden) {
4220          $authornamedate = $timestamp;
4221      } else {
4222          $fullname = fullname($activity->user, $viewfullnames);
4223          $userurl = new moodle_url('/user/view.php');
4224          $userurl->params(['id' => $activity->user->id, 'course' => $courseid]);
4225          $by = new stdClass();
4226          $by->name = html_writer::link($userurl, $fullname);
4227          $by->date = $timestamp;
4228          $authornamedate = get_string('bynameondate', 'forum', $by);
4229      }
4230      $output .= html_writer::div($authornamedate, 'user');
4231      $output .= html_writer::end_tag('td');
4232      $output .= html_writer::end_tag('tr');
4233      $output .= html_writer::end_tag('table');
4234  
4235      echo $output;
4236  }
4237  
4238  /**
4239   * recursively sets the discussion field to $discussionid on $postid and all its children
4240   * used when pruning a post
4241   *
4242   * @global object
4243   * @param int $postid
4244   * @param int $discussionid
4245   * @return bool
4246   */
4247  function forum_change_discussionid($postid, $discussionid) {
4248      global $DB;
4249      $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
4250      if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
4251          foreach ($posts as $post) {
4252              forum_change_discussionid($post->id, $discussionid);
4253          }
4254      }
4255      return true;
4256  }
4257  
4258  // Functions to do with read tracking.
4259  
4260  /**
4261   * Mark posts as read.
4262   *
4263   * @global object
4264   * @global object
4265   * @param object $user object
4266   * @param array $postids array of post ids
4267   * @return boolean success
4268   */
4269  function forum_tp_mark_posts_read($user, $postids) {
4270      global $CFG, $DB;
4271  
4272      if (!forum_tp_can_track_forums(false, $user)) {
4273          return true;
4274      }
4275  
4276      $status = true;
4277  
4278      $now = time();
4279      $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
4280  
4281      if (empty($postids)) {
4282          return true;
4283  
4284      } else if (count($postids) > 200) {
4285          while ($part = array_splice($postids, 0, 200)) {
4286              $status = forum_tp_mark_posts_read($user, $part) && $status;
4287          }
4288          return $status;
4289      }
4290  
4291      list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid');
4292  
4293      $insertparams = array(
4294          'userid1' => $user->id,
4295          'userid2' => $user->id,
4296          'userid3' => $user->id,
4297          'firstread' => $now,
4298          'lastread' => $now,
4299          'cutoffdate' => $cutoffdate,
4300      );
4301      $params = array_merge($postidparams, $insertparams);
4302  
4303      if ($CFG->forum_allowforcedreadtracking) {
4304          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
4305                          OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))";
4306      } else {
4307          $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL."  OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4308                              AND tf.id IS NULL)";
4309      }
4310  
4311      // First insert any new entries.
4312      $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4313  
4314              SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
4315                  FROM {forum_posts} p
4316                      JOIN {forum_discussions} d       ON d.id = p.discussion
4317                      JOIN {forum} f                   ON f.id = d.forum
4318                      LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
4319                      LEFT JOIN {forum_read} fr        ON (
4320                              fr.userid = :userid3
4321                          AND fr.postid = p.id
4322                          AND fr.discussionid = d.id
4323                          AND fr.forumid = f.id
4324                      )
4325                  WHERE p.id $usql
4326                      AND p.modified >= :cutoffdate
4327                      $trackingsql
4328                      AND fr.id IS NULL";
4329  
4330      $status = $DB->execute($sql, $params) && $status;
4331  
4332      // Then update all records.
4333      $updateparams = array(
4334          'userid' => $user->id,
4335          'lastread' => $now,
4336      );
4337      $params = array_merge($postidparams, $updateparams);
4338      $status = $DB->set_field_select('forum_read', 'lastread', $now, '
4339                  userid      =  :userid
4340              AND lastread    <> :lastread
4341              AND postid      ' . $usql,
4342              $params) && $status;
4343  
4344      return $status;
4345  }
4346  
4347  /**
4348   * Mark post as read.
4349   * @global object
4350   * @global object
4351   * @param int $userid
4352   * @param int $postid
4353   */
4354  function forum_tp_add_read_record($userid, $postid) {
4355      global $CFG, $DB;
4356  
4357      $now = time();
4358      $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
4359  
4360      if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
4361          $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4362  
4363                  SELECT ?, p.id, p.discussion, d.forum, ?, ?
4364                    FROM {forum_posts} p
4365                         JOIN {forum_discussions} d ON d.id = p.discussion
4366                   WHERE p.id = ? AND p.modified >= ?";
4367          return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
4368  
4369      } else {
4370          $sql = "UPDATE {forum_read}
4371                     SET lastread = ?
4372                   WHERE userid = ? AND postid = ?";
4373          return $DB->execute($sql, array($now, $userid, $userid));
4374      }
4375  }
4376  
4377  /**
4378   * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
4379   *
4380   * @param   int     $userid The ID of the user to mark posts read for.
4381   * @param   object  $post   The post record for the post to mark as read.
4382   * @param   mixed   $unused
4383   * @return bool
4384   */
4385  function forum_tp_mark_post_read($userid, $post, $unused = null) {
4386      if (!forum_tp_is_post_old($post)) {
4387          return forum_tp_add_read_record($userid, $post->id);
4388      } else {
4389          return true;
4390      }
4391  }
4392  
4393  /**
4394   * Marks a whole forum as read, for a given user
4395   *
4396   * @global object
4397   * @global object
4398   * @param object $user
4399   * @param int $forumid
4400   * @param int|bool $groupid
4401   * @return bool
4402   */
4403  function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
4404      global $CFG, $DB;
4405  
4406      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4407  
4408      $groupsel = "";
4409      $params = array($user->id, $forumid, $cutoffdate);
4410  
4411      if ($groupid !== false) {
4412          $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
4413          $params[] = $groupid;
4414      }
4415  
4416      $sql = "SELECT p.id
4417                FROM {forum_posts} p
4418                     LEFT JOIN {forum_discussions} d ON d.id = p.discussion
4419                     LEFT JOIN {forum_read} r        ON (r.postid = p.id AND r.userid = ?)
4420               WHERE d.forum = ?
4421                     AND p.modified >= ? AND r.id is NULL
4422                     $groupsel";
4423  
4424      if ($posts = $DB->get_records_sql($sql, $params)) {
4425          $postids = array_keys($posts);
4426          return forum_tp_mark_posts_read($user, $postids);
4427      }
4428  
4429      return true;
4430  }
4431  
4432  /**
4433   * Marks a whole discussion as read, for a given user
4434   *
4435   * @global object
4436   * @global object
4437   * @param object $user
4438   * @param int $discussionid
4439   * @return bool
4440   */
4441  function forum_tp_mark_discussion_read($user, $discussionid) {
4442      global $CFG, $DB;
4443  
4444      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4445  
4446      $sql = "SELECT p.id
4447                FROM {forum_posts} p
4448                     LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
4449               WHERE p.discussion = ?
4450                     AND p.modified >= ? AND r.id is NULL";
4451  
4452      if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) {
4453          $postids = array_keys($posts);
4454          return forum_tp_mark_posts_read($user, $postids);
4455      }
4456  
4457      return true;
4458  }
4459  
4460  /**
4461   * @global object
4462   * @param int $userid
4463   * @param object $post
4464   */
4465  function forum_tp_is_post_read($userid, $post) {
4466      global $DB;
4467      return (forum_tp_is_post_old($post) ||
4468              $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id)));
4469  }
4470  
4471  /**
4472   * @global object
4473   * @param object $post
4474   * @param int $time Defautls to time()
4475   */
4476  function forum_tp_is_post_old($post, $time=null) {
4477      global $CFG;
4478  
4479      if (is_null($time)) {
4480          $time = time();
4481      }
4482      return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600)));
4483  }
4484  
4485  /**
4486   * Returns the count of records for the provided user and course.
4487   * Please note that group access is ignored!
4488   *
4489   * @global object
4490   * @global object
4491   * @param int $userid
4492   * @param int $courseid
4493   * @return array
4494   */
4495  function forum_tp_get_course_unread_posts($userid, $courseid) {
4496      global $CFG, $DB;
4497  
4498      $modinfo = get_fast_modinfo($courseid);
4499      $forumcms = $modinfo->get_instances_of('forum');
4500      if (empty($forumcms)) {
4501          // Return early if the course doesn't have any forum. Will save us a DB query.
4502          return [];
4503      }
4504  
4505      $now = floor(time() / MINSECS) * MINSECS; // DB cache friendliness.
4506      $cutoffdate = $now - ($CFG->forum_oldpostdays * DAYSECS);
4507      $params = [
4508          'privatereplyto' => $userid,
4509          'modified' => $cutoffdate,
4510          'readuserid' => $userid,
4511          'trackprefsuser' => $userid,
4512          'courseid' => $courseid,
4513          'trackforumuser' => $userid,
4514      ];
4515  
4516      if (!empty($CFG->forum_enabletimedposts)) {
4517          $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4518          $params['timestart'] = $now;
4519          $params['timeend'] = $now;
4520      } else {
4521          $timedsql = "";
4522      }
4523  
4524      if ($CFG->forum_allowforcedreadtracking) {
4525          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
4526                              OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL
4527                                  AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1))";
4528      } else {
4529          $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4530                              AND tf.id IS NULL
4531                              AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1)";
4532      }
4533  
4534      $sql = "SELECT f.id, COUNT(p.id) AS unread,
4535                     COUNT(p.privatereply) as privatereplies,
4536                     COUNT(p.privatereplytouser) as privaterepliestouser
4537                FROM (
4538                          SELECT
4539                              id,
4540                              discussion,
4541                              CASE WHEN privatereplyto <> 0 THEN 1 END privatereply,
4542                              CASE WHEN privatereplyto = :privatereplyto THEN 1 END privatereplytouser
4543                          FROM {forum_posts}
4544                          WHERE modified >= :modified
4545                     ) p
4546                     JOIN {forum_discussions} d       ON d.id = p.discussion
4547                     JOIN {forum} f                   ON f.id = d.forum
4548                     JOIN {course} c                  ON c.id = f.course
4549                     LEFT JOIN {forum_read} r         ON (r.postid = p.id AND r.userid = :readuserid)
4550                     LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :trackprefsuser AND tf.forumid = f.id)
4551               WHERE f.course = :courseid
4552                     AND r.id is NULL
4553                     $trackingsql
4554                     $timedsql
4555            GROUP BY f.id";
4556  
4557      $results = [];
4558      if ($records = $DB->get_records_sql($sql, $params)) {
4559          // Loop through each forum instance to check for capability and count the number of unread posts.
4560          foreach ($forumcms as $cm) {
4561              // Check that the forum instance exists in the query results.
4562              if (!isset($records[$cm->instance])) {
4563                  continue;
4564              }
4565  
4566              $record = $records[$cm->instance];
4567              $unread = $record->unread;
4568  
4569              // Check if the user has the capability to read private replies for this forum instance.
4570              $forumcontext = context_module::instance($cm->id);
4571              if (!has_capability('mod/forum:readprivatereplies', $forumcontext, $userid)) {
4572                  // The real unread count would be the total of unread count minus the number of unread private replies plus
4573                  // the total unread private replies to the user.
4574                  $unread = $record->unread - $record->privatereplies + $record->privaterepliestouser;
4575              }
4576  
4577              // Build and add the object to the array of results to be returned.
4578              $results[$record->id] = (object)[
4579                  'id' => $record->id,
4580                  'unread' => $unread,
4581              ];
4582          }
4583      }
4584  
4585      return $results;
4586  }
4587  
4588  /**
4589   * Returns the count of records for the provided user and forum and [optionally] group.
4590   *
4591   * @global object
4592   * @global object
4593   * @global object
4594   * @param object $cm
4595   * @param object $course
4596   * @param bool   $resetreadcache optional, true to reset the function static $readcache var
4597   * @return int
4598   */
4599  function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) {
4600      global $CFG, $USER, $DB;
4601  
4602      static $readcache = array();
4603  
4604      if ($resetreadcache) {
4605          $readcache = array();
4606      }
4607  
4608      $forumid = $cm->instance;
4609  
4610      if (!isset($readcache[$course->id])) {
4611          $readcache[$course->id] = array();
4612          if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
4613              foreach ($counts as $count) {
4614                  $readcache[$course->id][$count->id] = $count->unread;
4615              }
4616          }
4617      }
4618  
4619      if (empty($readcache[$course->id][$forumid])) {
4620          // no need to check group mode ;-)
4621          return 0;
4622      }
4623  
4624      $groupmode = groups_get_activity_groupmode($cm, $course);
4625  
4626      if ($groupmode != SEPARATEGROUPS) {
4627          return $readcache[$course->id][$forumid];
4628      }
4629  
4630      $forumcontext = context_module::instance($cm->id);
4631      if (has_any_capability(['moodle/site:accessallgroups', 'mod/forum:readprivatereplies'], $forumcontext)) {
4632          return $readcache[$course->id][$forumid];
4633      }
4634  
4635      require_once($CFG->dirroot.'/course/lib.php');
4636  
4637      $modinfo = get_fast_modinfo($course);
4638  
4639      $mygroups = $modinfo->get_groups($cm->groupingid);
4640  
4641      // add all groups posts
4642      $mygroups[-1] = -1;
4643  
4644      list ($groupssql, $groupsparams) = $DB->get_in_or_equal($mygroups, SQL_PARAMS_NAMED);
4645  
4646      $now = floor(time() / MINSECS) * MINSECS; // DB Cache friendliness.
4647      $cutoffdate = $now - ($CFG->forum_oldpostdays * DAYSECS);
4648      $params = [
4649          'readuser' => $USER->id,
4650          'forum' => $forumid,
4651          'cutoffdate' => $cutoffdate,
4652          'privatereplyto' => $USER->id,
4653      ];
4654  
4655      if (!empty($CFG->forum_enabletimedposts)) {
4656          $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4657          $params['timestart'] = $now;
4658          $params['timeend'] = $now;
4659      } else {
4660          $timedsql = "";
4661      }
4662  
4663      $params = array_merge($params, $groupsparams);
4664  
4665      $sql = "SELECT COUNT(p.id)
4666                FROM {forum_posts} p
4667                JOIN {forum_discussions} d ON p.discussion = d.id
4668           LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = :readuser)
4669               WHERE d.forum = :forum
4670                     AND p.modified >= :cutoffdate AND r.id is NULL
4671                     $timedsql
4672                     AND d.groupid $groupssql
4673                     AND (p.privatereplyto = 0 OR p.privatereplyto = :privatereplyto)";
4674  
4675      return $DB->get_field_sql($sql, $params);
4676  }
4677  
4678  /**
4679   * Deletes read records for the specified index. At least one parameter must be specified.
4680   *
4681   * @global object
4682   * @param int $userid
4683   * @param int $postid
4684   * @param int $discussionid
4685   * @param int $forumid
4686   * @return bool
4687   */
4688  function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
4689      global $DB;
4690      $params = array();
4691  
4692      $select = '';
4693      if ($userid > -1) {
4694          if ($select != '') $select .= ' AND ';
4695          $select .= 'userid = ?';
4696          $params[] = $userid;
4697      }
4698      if ($postid > -1) {
4699          if ($select != '') $select .= ' AND ';
4700          $select .= 'postid = ?';
4701          $params[] = $postid;
4702      }
4703      if ($discussionid > -1) {
4704          if ($select != '') $select .= ' AND ';
4705          $select .= 'discussionid = ?';
4706          $params[] = $discussionid;
4707      }
4708      if ($forumid > -1) {
4709          if ($select != '') $select .= ' AND ';
4710          $select .= 'forumid = ?';
4711          $params[] = $forumid;
4712      }
4713      if ($select == '') {
4714          return false;
4715      }
4716      else {
4717          return $DB->delete_records_select('forum_read', $select, $params);
4718      }
4719  }
4720  /**
4721   * Get a list of forums not tracked by the user.
4722   *
4723   * @global object
4724   * @global object
4725   * @param int $userid The id of the user to use.
4726   * @param int $courseid The id of the course being checked.
4727   * @return mixed An array indexed by forum id, or false.
4728   */
4729  function forum_tp_get_untracked_forums($userid, $courseid) {
4730      global $CFG, $DB;
4731  
4732      if ($CFG->forum_allowforcedreadtracking) {
4733          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
4734                              OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL
4735                                  OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4736      } else {
4737          $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
4738                              OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
4739                                  AND (ft.id IS NOT NULL
4740                                      OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4741      }
4742  
4743      $sql = "SELECT f.id
4744                FROM {forum} f
4745                     LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
4746               WHERE f.course = ?
4747                     $trackingsql";
4748  
4749      if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
4750          foreach ($forums as $forum) {
4751              $forums[$forum->id] = $forum;
4752          }
4753          return $forums;
4754  
4755      } else {
4756          return array();
4757      }
4758  }
4759  
4760  /**
4761   * Determine if a user can track forums and optionally a particular forum.
4762   * Checks the site settings, the user settings and the forum settings (if
4763   * requested).
4764   *
4765   * @global object
4766   * @global object
4767   * @global object
4768   * @param mixed $forum The forum object to test, or the int id (optional).
4769   * @param mixed $userid The user object to check for (optional).
4770   * @return boolean
4771   */
4772  function forum_tp_can_track_forums($forum=false, $user=false) {
4773      global $USER, $CFG, $DB;
4774  
4775      // if possible, avoid expensive
4776      // queries
4777      if (empty($CFG->forum_trackreadposts)) {
4778          return false;
4779      }
4780  
4781      if ($user === false) {
4782          $user = $USER;
4783      }
4784  
4785      if (isguestuser($user) or empty($user->id)) {
4786          return false;
4787      }
4788  
4789      if ($forum === false) {
4790          if ($CFG->forum_allowforcedreadtracking) {
4791              // Since we can force tracking, assume yes without a specific forum.
4792              return true;
4793          } else {
4794              return (bool)$user->trackforums;
4795          }
4796      }
4797  
4798      // Work toward always passing an object...
4799      if (is_numeric($forum)) {
4800          debugging('Better use proper forum object.', DEBUG_DEVELOPER);
4801          $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
4802      }
4803  
4804      $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
4805      $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
4806  
4807      if ($CFG->forum_allowforcedreadtracking) {
4808          // If we allow forcing, then forced forums takes procidence over user setting.
4809          return ($forumforced || ($forumallows  && (!empty($user->trackforums) && (bool)$user->trackforums)));
4810      } else {
4811          // If we don't allow forcing, user setting trumps.
4812          return ($forumforced || $forumallows)  && !empty($user->trackforums);
4813      }
4814  }
4815  
4816  /**
4817   * Tells whether a specific forum is tracked by the user. A user can optionally
4818   * be specified. If not specified, the current user is assumed.
4819   *
4820   * @global object
4821   * @global object
4822   * @global object
4823   * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
4824   * @param int $userid The id of the user being checked (optional).
4825   * @return boolean
4826   */
4827  function forum_tp_is_tracked($forum, $user=false) {
4828      global $USER, $CFG, $DB;
4829  
4830      if ($user === false) {
4831          $user = $USER;
4832      }
4833  
4834      if (isguestuser($user) or empty($user->id)) {
4835          return false;
4836      }
4837  
4838      $cache = cache::make('mod_forum', 'forum_is_tracked');
4839      $forumid = is_numeric($forum) ? $forum : $forum->id;
4840      $key = $forumid . '_' . $user->id;
4841      if ($cachedvalue = $cache->get($key)) {
4842          return $cachedvalue == 'tracked';
4843      }
4844  
4845      // Work toward always passing an object...
4846      if (is_numeric($forum)) {
4847          debugging('Better use proper forum object.', DEBUG_DEVELOPER);
4848          $forum = $DB->get_record('forum', array('id' => $forum));
4849      }
4850  
4851      if (!forum_tp_can_track_forums($forum, $user)) {
4852          return false;
4853      }
4854  
4855      $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
4856      $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
4857      $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id));
4858  
4859      if ($CFG->forum_allowforcedreadtracking) {
4860          $istracked = $forumforced || ($forumallows && $userpref === false);
4861      } else {
4862          $istracked = ($forumallows || $forumforced) && $userpref === false;
4863      }
4864  
4865      // We have to store a string here because the cache API returns false
4866      // when it can't find the key which would be confused with our legitimate
4867      // false value. *sigh*.
4868      $cache->set($key, $istracked ? 'tracked' : 'not');
4869  
4870      return $istracked;
4871  }
4872  
4873  /**
4874   * @global object
4875   * @global object
4876   * @param int $forumid
4877   * @param int $userid
4878   */
4879  function forum_tp_start_tracking($forumid, $userid=false) {
4880      global $USER, $DB;
4881  
4882      if ($userid === false) {
4883          $userid = $USER->id;
4884      }
4885  
4886      return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
4887  }
4888  
4889  /**
4890   * @global object
4891   * @global object
4892   * @param int $forumid
4893   * @param int $userid
4894   */
4895  function forum_tp_stop_tracking($forumid, $userid=false) {
4896      global $USER, $DB;
4897  
4898      if ($userid === false) {
4899          $userid = $USER->id;
4900      }
4901  
4902      if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
4903          $track_prefs = new stdClass();
4904          $track_prefs->userid = $userid;
4905          $track_prefs->forumid = $forumid;
4906          $DB->insert_record('forum_track_prefs', $track_prefs);
4907      }
4908  
4909      return forum_tp_delete_read_records($userid, -1, -1, $forumid);
4910  }
4911  
4912  
4913  /**
4914   * Clean old records from the forum_read table.
4915   * @global object
4916   * @global object
4917   * @return void
4918   */
4919  function forum_tp_clean_read_records() {
4920      global $CFG, $DB;
4921  
4922      if (!isset($CFG->forum_oldpostdays)) {
4923          return;
4924      }
4925  // Look for records older than the cutoffdate that are still in the forum_read table.
4926      $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
4927  
4928      //first get the oldest tracking present - we need tis to speedup the next delete query
4929      $sql = "SELECT MIN(fp.modified) AS first
4930                FROM {forum_posts} fp
4931                     JOIN {forum_read} fr ON fr.postid=fp.id";
4932      if (!$first = $DB->get_field_sql($sql)) {
4933          // nothing to delete;
4934          return;
4935      }
4936  
4937      // now delete old tracking info
4938      $sql = "DELETE
4939                FROM {forum_read}
4940               WHERE postid IN (SELECT fp.id
4941                                  FROM {forum_posts} fp
4942                                 WHERE fp.modified >= ? AND fp.modified < ?)";
4943      $DB->execute($sql, array($first, $cutoffdate));
4944  }
4945  
4946  /**
4947   * Sets the last post for a given discussion
4948   *
4949   * @global object
4950   * @global object
4951   * @param into $discussionid
4952   * @return bool|int
4953   **/
4954  function forum_discussion_update_last_post($discussionid) {
4955      global $CFG, $DB;
4956  
4957  // Check the given discussion exists
4958      if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
4959          return false;
4960      }
4961  
4962  // Use SQL to find the last post for this discussion
4963      $sql = "SELECT id, userid, modified
4964                FROM {forum_posts}
4965               WHERE discussion=?
4966               ORDER BY modified DESC";
4967  
4968  // Lets go find the last post
4969      if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
4970          $lastpost = reset($lastposts);
4971          $discussionobject = new stdClass();
4972          $discussionobject->id           = $discussionid;
4973          $discussionobject->usermodified = $lastpost->userid;
4974          $discussionobject->timemodified = $lastpost->modified;
4975          $DB->update_record('forum_discussions', $discussionobject);
4976          return $lastpost->id;
4977      }
4978  
4979  // To get here either we couldn't find a post for the discussion (weird)
4980  // or we couldn't update the discussion record (weird x2)
4981      return false;
4982  }
4983  
4984  
4985  /**
4986   * List the actions that correspond to a view of this module.
4987   * This is used by the participation report.
4988   *
4989   * Note: This is not used by new logging system. Event with
4990   *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
4991   *       be considered as view action.
4992   *
4993   * @return array
4994   */
4995  function forum_get_view_actions() {
4996      return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
4997  }
4998  
4999  /**
5000   * List the options for forum subscription modes.
5001   * This is used by the settings page and by the mod_form page.
5002   *
5003   * @return array
5004   */
5005  function forum_get_subscriptionmode_options() {
5006      $options = array();
5007      $options[FORUM_CHOOSESUBSCRIBE] = get_string('subscriptionoptional', 'forum');
5008      $options[FORUM_FORCESUBSCRIBE] = get_string('subscriptionforced', 'forum');
5009      $options[FORUM_INITIALSUBSCRIBE] = get_string('subscriptionauto', 'forum');
5010      $options[FORUM_DISALLOWSUBSCRIBE] = get_string('subscriptiondisabled', 'forum');
5011      return $options;
5012  }
5013  
5014  /**
5015   * List the actions that correspond to a post of this module.
5016   * This is used by the participation report.
5017   *
5018   * Note: This is not used by new logging system. Event with
5019   *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
5020   *       will be considered as post action.
5021   *
5022   * @return array
5023   */
5024  function forum_get_post_actions() {
5025      return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
5026  }
5027  
5028  /**
5029   * Returns a warning object if a user has reached the number of posts equal to
5030   * the warning/blocking setting, or false if there is no warning to show.
5031   *
5032   * @param int|stdClass $forum the forum id or the forum object
5033   * @param stdClass $cm the course module
5034   * @return stdClass|bool returns an object with the warning information, else
5035   *         returns false if no warning is required.
5036   */
5037  function forum_check_throttling($forum, $cm = null) {
5038      global $CFG, $DB, $USER;
5039  
5040      if (is_numeric($forum)) {
5041          $forum = $DB->get_record('forum', ['id' => $forum], 'id, course, blockperiod, blockafter, warnafter', MUST_EXIST);
5042      }
5043  
5044      if (!is_object($forum) || !isset($forum->id) || !isset($forum->course)) {
5045          // The passed forum parameter is invalid. This can happen if:
5046          // - a non-object and non-numeric forum is passed; or
5047          // - the forum object does not have an ID or course attributes.
5048          // This is unlikely to happen with properly formed forum record fetched from the database,
5049          // so it's most likely a dev error if we hit such this case.
5050          throw new coding_exception('Invalid forum parameter passed');
5051      }
5052  
5053      if (empty($forum->blockafter)) {
5054          return false;
5055      }
5056  
5057      if (empty($forum->blockperiod)) {
5058          return false;
5059      }
5060  
5061      if (!$cm) {
5062          // Try to fetch the $cm object via get_fast_modinfo() so we don't incur DB reads.
5063          $modinfo = get_fast_modinfo($forum->course);
5064          $forumcms = $modinfo->get_instances_of('forum');
5065          foreach ($forumcms as $tmpcm) {
5066              if ($tmpcm->instance == $forum->id) {
5067                  $cm = $tmpcm;
5068                  break;
5069              }
5070          }
5071          // Last resort. Try to fetch via get_coursemodule_from_instance().
5072          if (!$cm) {
5073              $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST);
5074          }
5075      }
5076  
5077      $modcontext = context_module::instance($cm->id);
5078      if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
5079          return false;
5080      }
5081  
5082      // Get the number of posts in the last period we care about.
5083      $timenow = time();
5084      $timeafter = $timenow - $forum->blockperiod;
5085      $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
5086                                          JOIN {forum_discussions} d
5087                                          ON p.discussion = d.id WHERE d.forum = ?
5088                                          AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter));
5089  
5090      $a = new stdClass();
5091      $a->blockafter = $forum->blockafter;
5092      $a->numposts = $numposts;
5093      $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
5094  
5095      if ($forum->blockafter <= $numposts) {
5096          $warning = new stdClass();
5097          $warning->canpost = false;
5098          $warning->errorcode = 'forumblockingtoomanyposts';
5099          $warning->module = 'error';
5100          $warning->additional = $a;
5101          $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id;
5102  
5103          return $warning;
5104      }
5105  
5106      if ($forum->warnafter <= $numposts) {
5107          $warning = new stdClass();
5108          $warning->canpost = true;
5109          $warning->errorcode = 'forumblockingalmosttoomanyposts';
5110          $warning->module = 'forum';
5111          $warning->additional = $a;
5112          $warning->link = null;
5113  
5114          return $warning;
5115      }
5116  
5117      // No warning needs to be shown yet.
5118      return false;
5119  }
5120  
5121  /**
5122   * Throws an error if the user is no longer allowed to post due to having reached
5123   * or exceeded the number of posts specified in 'Post threshold for blocking'
5124   * setting.
5125   *
5126   * @since Moodle 2.5
5127   * @param stdClass $thresholdwarning the warning information returned
5128   *        from the function forum_check_throttling.
5129   */
5130  function forum_check_blocking_threshold($thresholdwarning) {
5131      if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
5132          throw new \moodle_exception($thresholdwarning->errorcode,
5133                      $thresholdwarning->module,
5134                      $thresholdwarning->link,
5135                      $thresholdwarning->additional);
5136      }
5137  }
5138  
5139  
5140  /**
5141   * Removes all grades from gradebook
5142   *
5143   * @global object
5144   * @global object
5145   * @param int $courseid
5146   * @param string $type optional
5147   */
5148  function forum_reset_gradebook($courseid, $type='') {
5149      global $CFG, $DB;
5150  
5151      $wheresql = '';
5152      $params = array($courseid);
5153      if ($type) {
5154          $wheresql = "AND f.type=?";
5155          $params[] = $type;
5156      }
5157  
5158      $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
5159                FROM {forum} f, {course_modules} cm, {modules} m
5160               WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
5161  
5162      if ($forums = $DB->get_records_sql($sql, $params)) {
5163          foreach ($forums as $forum) {
5164              forum_grade_item_update($forum, 'reset', 'reset');
5165          }
5166      }
5167  }
5168  
5169  /**
5170   * This function is used by the reset_course_userdata function in moodlelib.
5171   * This function will remove all posts from the specified forum
5172   * and clean up any related data.
5173   *
5174   * @global object
5175   * @global object
5176   * @param $data the data submitted from the reset course.
5177   * @return array status array
5178   */
5179  function forum_reset_userdata($data) {
5180      global $CFG, $DB;
5181      require_once($CFG->dirroot.'/rating/lib.php');
5182  
5183      $componentstr = get_string('modulenameplural', 'forum');
5184      $status = array();
5185  
5186      $params = array($data->courseid);
5187  
5188      $removeposts = false;
5189      $typesql     = "";
5190      if (!empty($data->reset_forum_all)) {
5191          $removeposts = true;
5192          $typesstr    = get_string('resetforumsall', 'forum');
5193          $types       = array();
5194      } else if (!empty($data->reset_forum_types)){
5195          $removeposts = true;
5196          $types       = array();
5197          $sqltypes    = array();
5198          $forum_types_all = forum_get_forum_types_all();
5199          foreach ($data->reset_forum_types as $type) {
5200              if (!array_key_exists($type, $forum_types_all)) {
5201                  continue;
5202              }
5203              $types[] = $forum_types_all[$type];
5204              $sqltypes[] = $type;
5205          }
5206          if (!empty($sqltypes)) {
5207              list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
5208              $typesql = " AND f.type " . $typesql;
5209              $params = array_merge($params, $typeparams);
5210          }
5211          $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
5212      }
5213      $alldiscussionssql = "SELECT fd.id
5214                              FROM {forum_discussions} fd, {forum} f
5215                             WHERE f.course=? AND f.id=fd.forum";
5216  
5217      $allforumssql      = "SELECT f.id
5218                              FROM {forum} f
5219                             WHERE f.course=?";
5220  
5221      $allpostssql       = "SELECT fp.id
5222                              FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
5223                             WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
5224  
5225      $forumssql = $forums = $rm = null;
5226  
5227      // Check if we need to get additional data.
5228      if ($removeposts || !empty($data->reset_forum_ratings) || !empty($data->reset_forum_tags)) {
5229          // Set this up if we have to remove ratings.
5230          $rm = new rating_manager();
5231          $ratingdeloptions = new stdClass;
5232          $ratingdeloptions->component = 'mod_forum';
5233          $ratingdeloptions->ratingarea = 'post';
5234  
5235          // Get the forums for actions that require it.
5236          $forumssql = "$allforumssql $typesql";
5237          $forums = $DB->get_records_sql($forumssql, $params);
5238      }
5239  
5240      if ($removeposts) {
5241          $discussionssql = "$alldiscussionssql $typesql";
5242          $postssql       = "$allpostssql $typesql";
5243  
5244          // now get rid of all attachments
5245          $fs = get_file_storage();
5246          if ($forums) {
5247              foreach ($forums as $forumid=>$unused) {
5248                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5249                      continue;
5250                  }
5251                  $context = context_module::instance($cm->id);
5252                  $fs->delete_area_files($context->id, 'mod_forum', 'attachment');
5253                  $fs->delete_area_files($context->id, 'mod_forum', 'post');
5254  
5255                  //remove ratings
5256                  $ratingdeloptions->contextid = $context->id;
5257                  $rm->delete_ratings($ratingdeloptions);
5258  
5259                  core_tag_tag::delete_instances('mod_forum', null, $context->id);
5260              }
5261          }
5262  
5263          // first delete all read flags
5264          $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
5265  
5266          // remove tracking prefs
5267          $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
5268  
5269          // remove posts from queue
5270          $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
5271  
5272          // all posts - initial posts must be kept in single simple discussion forums
5273          $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
5274          $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
5275  
5276          // finally all discussions except single simple forums
5277          $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
5278  
5279          // remove all grades from gradebook
5280          if (empty($data->reset_gradebook_grades)) {
5281              if (empty($types)) {
5282                  forum_reset_gradebook($data->courseid);
5283              } else {
5284                  foreach ($types as $type) {
5285                      forum_reset_gradebook($data->courseid, $type);
5286                  }
5287              }
5288          }
5289  
5290          $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
5291      }
5292  
5293      // remove all ratings in this course's forums
5294      if (!empty($data->reset_forum_ratings)) {
5295          if ($forums) {
5296              foreach ($forums as $forumid=>$unused) {
5297                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5298                      continue;
5299                  }
5300                  $context = context_module::instance($cm->id);
5301  
5302                  //remove ratings
5303                  $ratingdeloptions->contextid = $context->id;
5304                  $rm->delete_ratings($ratingdeloptions);
5305              }
5306          }
5307  
5308          // remove all grades from gradebook
5309          if (empty($data->reset_gradebook_grades)) {
5310              forum_reset_gradebook($data->courseid);
5311          }
5312      }
5313  
5314      // Remove all the tags.
5315      if (!empty($data->reset_forum_tags)) {
5316          if ($forums) {
5317              foreach ($forums as $forumid => $unused) {
5318                  if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5319                      continue;
5320                  }
5321  
5322                  $context = context_module::instance($cm->id);
5323                  core_tag_tag::delete_instances('mod_forum', null, $context->id);
5324              }
5325          }
5326  
5327          $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false);
5328      }
5329  
5330      // remove all digest settings unconditionally - even for users still enrolled in course.
5331      if (!empty($data->reset_forum_digests)) {
5332          $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
5333          $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
5334      }
5335  
5336      // remove all subscriptions unconditionally - even for users still enrolled in course
5337      if (!empty($data->reset_forum_subscriptions)) {
5338          $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
5339          $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
5340          $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
5341      }
5342  
5343      // remove all tracking prefs unconditionally - even for users still enrolled in course
5344      if (!empty($data->reset_forum_track_prefs)) {
5345          $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
5346          $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
5347      }
5348  
5349      /// updating dates - shift may be negative too
5350      if ($data->timeshift) {
5351          // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
5352          // See MDL-9367.
5353          shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
5354          $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
5355      }
5356  
5357      return $status;
5358  }
5359  
5360  /**
5361   * Called by course/reset.php
5362   *
5363   * @param MoodleQuickForm $mform form passed by reference
5364   */
5365  function forum_reset_course_form_definition(&$mform) {
5366      $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
5367  
5368      $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
5369  
5370      $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
5371      $mform->setAdvanced('reset_forum_types');
5372      $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
5373  
5374      $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
5375      $mform->setAdvanced('reset_forum_digests');
5376  
5377      $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
5378      $mform->setAdvanced('reset_forum_subscriptions');
5379  
5380      $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
5381      $mform->setAdvanced('reset_forum_track_prefs');
5382      $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
5383  
5384      $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
5385      $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
5386  
5387      $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum'));
5388      $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked');
5389  }
5390  
5391  /**
5392   * Course reset form defaults.
5393   * @return array
5394   */
5395  function forum_reset_course_form_defaults($course) {
5396      return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
5397  }
5398  
5399  /**
5400   * Returns array of forum layout modes
5401   *
5402   * @param bool $useexperimentalui use experimental layout modes or not
5403   * @return array
5404   */
5405  function forum_get_layout_modes(bool $useexperimentalui = false) {
5406      $modes = [
5407          FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
5408          FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
5409          FORUM_MODE_THREADED   => get_string('modethreaded', 'forum')
5410      ];
5411  
5412      if ($useexperimentalui) {
5413          $modes[FORUM_MODE_NESTED_V2] = get_string('modenestedv2', 'forum');
5414      } else {
5415          $modes[FORUM_MODE_NESTED] = get_string('modenested', 'forum');
5416      }
5417  
5418      return $modes;
5419  }
5420  
5421  /**
5422   * Returns array of forum types chooseable on the forum editing form
5423   *
5424   * @return array
5425   */
5426  function forum_get_forum_types() {
5427      return array ('general'  => get_string('generalforum', 'forum'),
5428                    'eachuser' => get_string('eachuserforum', 'forum'),
5429                    'single'   => get_string('singleforum', 'forum'),
5430                    'qanda'    => get_string('qandaforum', 'forum'),
5431                    'blog'     => get_string('blogforum', 'forum'));
5432  }
5433  
5434  /**
5435   * Returns array of all forum layout modes
5436   *
5437   * @return array
5438   */
5439  function forum_get_forum_types_all() {
5440      return array ('news'     => get_string('namenews','forum'),
5441                    'social'   => get_string('namesocial','forum'),
5442                    'general'  => get_string('generalforum', 'forum'),
5443                    'eachuser' => get_string('eachuserforum', 'forum'),
5444                    'single'   => get_string('singleforum', 'forum'),
5445                    'qanda'    => get_string('qandaforum', 'forum'),
5446                    'blog'     => get_string('blogforum', 'forum'));
5447  }
5448  
5449  /**
5450   * Returns all other caps used in module
5451   *
5452   * @return array
5453   */
5454  function forum_get_extra_capabilities() {
5455      return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate'];
5456  }
5457  
5458  /**
5459   * Adds module specific settings to the settings block
5460   *
5461   * @param settings_navigation $settings The settings navigation object
5462   * @param navigation_node $forumnode The node to add module settings to
5463   */
5464  function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
5465      global $USER, $CFG;
5466  
5467      if (empty($settingsnav->get_page()->cm->context)) {
5468          $settingsnav->get_page()->cm->context = context_module::instance($settingsnav->get_page()->cm->instance);
5469      }
5470  
5471      $vaultfactory = mod_forum\local\container::get_vault_factory();
5472      $managerfactory = mod_forum\local\container::get_manager_factory();
5473      $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
5474      $forumvault = $vaultfactory->get_forum_vault();
5475      $forumentity = $forumvault->get_from_id($settingsnav->get_page()->cm->instance);
5476      $forumobject = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forumentity);
5477  
5478      $params = $settingsnav->get_page()->url->params();
5479      if (!empty($params['d'])) {
5480          $discussionid = $params['d'];
5481      }
5482  
5483      // For some actions you need to be enrolled, being admin is not enough sometimes here.
5484      $enrolled = is_enrolled($settingsnav->get_page()->context, $USER, '', false);
5485      $activeenrolled = is_enrolled($settingsnav->get_page()->context, $USER, '', true);
5486  
5487      $canmanage  = has_capability('mod/forum:managesubscriptions', $settingsnav->get_page()->context);
5488      $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject);
5489      $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) &&
5490              (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage);
5491  
5492      if ($canmanage) {
5493          $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);
5494          $mode->add_class('subscriptionmode');
5495          $mode->set_show_in_secondary_navigation(false);
5496  
5497          // Optional subscription mode.
5498          $allowchoicestring = get_string('subscriptionoptional', 'forum');
5499          $allowchoiceaction = new action_link(
5500              new moodle_url('/mod/forum/subscribe.php', [
5501                  'id' => $forumobject->id,
5502                  'mode' => FORUM_CHOOSESUBSCRIBE,
5503                  'sesskey' => sesskey(),
5504              ]),
5505              $allowchoicestring,
5506              new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $allowchoicestring))
5507          );
5508          $allowchoice = $mode->add($allowchoicestring, $allowchoiceaction, navigation_node::TYPE_SETTING);
5509  
5510          // Forced subscription mode.
5511          $forceforeverstring = get_string('subscriptionforced', 'forum');
5512          $forceforeveraction = new action_link(
5513              new moodle_url('/mod/forum/subscribe.php', [
5514                  'id' => $forumobject->id,
5515                  'mode' => FORUM_FORCESUBSCRIBE,
5516                  'sesskey' => sesskey(),
5517              ]),
5518              $forceforeverstring,
5519              new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $forceforeverstring))
5520          );
5521          $forceforever = $mode->add($forceforeverstring, $forceforeveraction, navigation_node::TYPE_SETTING);
5522  
5523          // Initial subscription mode.
5524          $forceinitiallystring = get_string('subscriptionauto', 'forum');
5525          $forceinitiallyaction = new action_link(
5526              new moodle_url('/mod/forum/subscribe.php', [
5527                  'id' => $forumobject->id,
5528                  'mode' => FORUM_INITIALSUBSCRIBE,
5529                  'sesskey' => sesskey(),
5530              ]),
5531              $forceinitiallystring,
5532              new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $forceinitiallystring))
5533          );
5534          $forceinitially = $mode->add($forceinitiallystring, $forceinitiallyaction, navigation_node::TYPE_SETTING);
5535  
5536          // Disabled subscription mode.
5537          $disallowchoicestring = get_string('subscriptiondisabled', 'forum');
5538          $disallowchoiceaction = new action_link(
5539              new moodle_url('/mod/forum/subscribe.php', [
5540                  'id' => $forumobject->id,
5541                  'mode' => FORUM_DISALLOWSUBSCRIBE,
5542                  'sesskey' => sesskey(),
5543              ]),
5544              $disallowchoicestring,
5545              new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $disallowchoicestring))
5546          );
5547          $disallowchoice = $mode->add($disallowchoicestring, $disallowchoiceaction, navigation_node::TYPE_SETTING);
5548  
5549          switch ($subscriptionmode) {
5550              case FORUM_CHOOSESUBSCRIBE : // 0
5551                  $allowchoice->action = null;
5552                  $allowchoice->add_class('activesetting');
5553                  $allowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
5554                  break;
5555              case FORUM_FORCESUBSCRIBE : // 1
5556                  $forceforever->action = null;
5557                  $forceforever->add_class('activesetting');
5558                  $forceforever->icon = new pix_icon('t/selected', '', 'mod_forum');
5559                  break;
5560              case FORUM_INITIALSUBSCRIBE : // 2
5561                  $forceinitially->action = null;
5562                  $forceinitially->add_class('activesetting');
5563                  $forceinitially->icon = new pix_icon('t/selected', '', 'mod_forum');
5564                  break;
5565              case FORUM_DISALLOWSUBSCRIBE : // 3
5566                  $disallowchoice->action = null;
5567                  $disallowchoice->add_class('activesetting');
5568                  $disallowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
5569                  break;
5570          }
5571  
5572      } else if ($activeenrolled) {
5573  
5574          switch ($subscriptionmode) {
5575              case FORUM_CHOOSESUBSCRIBE : // 0
5576                  $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
5577                  break;
5578              case FORUM_FORCESUBSCRIBE : // 1
5579                  $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
5580                  break;
5581              case FORUM_INITIALSUBSCRIBE : // 2
5582                  $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
5583                  break;
5584              case FORUM_DISALLOWSUBSCRIBE : // 3
5585                  $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
5586                  break;
5587          }
5588      }
5589  
5590      if (has_capability('mod/forum:viewsubscribers', $settingsnav->get_page()->context)) {
5591          $url = new moodle_url('/mod/forum/subscribers.php', ['id' => $forumobject->id, 'edit' => 'off']);
5592          $forumnode->add(get_string('subscriptions', 'forum'), $url, navigation_node::TYPE_SETTING, null, 'forumsubscriptions');
5593      }
5594  
5595      // Display all forum reports user has access to.
5596      if (isloggedin() && !isguestuser()) {
5597          $reportnames = array_keys(core_component::get_plugin_list('forumreport'));
5598  
5599          foreach ($reportnames as $reportname) {
5600              if (has_capability("forumreport/{$reportname}:view", $settingsnav->get_page()->context)) {
5601                  $reportlinkparams = [
5602                      'courseid' => $forumobject->course,
5603                      'forumid' => $forumobject->id,
5604                  ];
5605                  $reportlink = new moodle_url("/mod/forum/report/{$reportname}/index.php", $reportlinkparams);
5606                  $forumnode->add(get_string('reports'), $reportlink, navigation_node::TYPE_CONTAINER);
5607              }
5608          }
5609      }
5610  
5611      if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
5612          if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL
5613                  || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) {
5614              if (forum_tp_is_tracked($forumobject)) {
5615                  $linktext = get_string('notrackforum', 'forum');
5616              } else {
5617                  $linktext = get_string('trackforum', 'forum');
5618              }
5619              $url = new moodle_url('/mod/forum/settracking.php', array(
5620                      'id' => $forumobject->id,
5621                      'sesskey' => sesskey(),
5622                  ));
5623              $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
5624          }
5625      }
5626  
5627      if (!isloggedin() && $settingsnav->get_page()->course->id == SITEID) {
5628          $userid = guest_user()->id;
5629      } else {
5630          $userid = $USER->id;
5631      }
5632  
5633      $hascourseaccess = ($settingsnav->get_page()->course->id == SITEID) ||
5634          can_access_course($settingsnav->get_page()->course, $userid);
5635      $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds);
5636  
5637      if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) {
5638  
5639          if (!function_exists('rss_get_url')) {
5640              require_once("$CFG->libdir/rsslib.php");
5641          }
5642  
5643          if ($forumobject->rsstype == 1) {
5644              $string = get_string('rsssubscriberssdiscussions','forum');
5645          } else {
5646              $string = get_string('rsssubscriberssposts','forum');
5647          }
5648  
5649          $url = new moodle_url(rss_get_url($settingsnav->get_page()->cm->context->id, $userid, "mod_forum",
5650              $forumobject->id));
5651          $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
5652      }
5653  
5654      $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
5655      if ($capabilitymanager->can_export_forum($USER)) {
5656          $url = new moodle_url('/mod/forum/export.php', ['id' => $forumobject->id]);
5657          $forumnode->add(get_string('export', 'mod_forum'), $url, navigation_node::TYPE_SETTING);
5658      }
5659  }
5660  
5661  /**
5662   * Adds information about unread messages, that is only required for the course view page (and
5663   * similar), to the course-module object.
5664   * @param cm_info $cm Course-module object
5665   */
5666  function forum_cm_info_view(cm_info $cm) {
5667      global $CFG;
5668  
5669      if (forum_tp_can_track_forums()) {
5670          if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
5671              $out = '<span class="badge badge-secondary">';
5672              if ($unread == 1) {
5673                  $out .= get_string('unreadpostsone', 'forum');
5674              } else {
5675                  $out .= get_string('unreadpostsnumber', 'forum', $unread);
5676              }
5677              $out .= '</span>';
5678              $cm->set_after_link($out);
5679          }
5680      }
5681  }
5682  
5683  /**
5684   * Return a list of page types
5685   * @param string $pagetype current page type
5686   * @param stdClass $parentcontext Block's parent context
5687   * @param stdClass $currentcontext Current context of block
5688   */
5689  function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
5690      $forum_pagetype = array(
5691          'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
5692          'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
5693          'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
5694      );
5695      return $forum_pagetype;
5696  }
5697  
5698  /**
5699   * Gets all of the courses where the provided user has posted in a forum.
5700   *
5701   * @global moodle_database $DB The database connection
5702   * @param stdClass $user The user who's posts we are looking for
5703   * @param bool $discussionsonly If true only look for discussions started by the user
5704   * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
5705   * @param int $limitfrom The offset of records to return
5706   * @param int $limitnum The number of records to return
5707   * @return array An array of courses
5708   */
5709  function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
5710      global $DB;
5711  
5712      // If we are only after discussions we need only look at the forum_discussions
5713      // table and join to the userid there. If we are looking for posts then we need
5714      // to join to the forum_posts table.
5715      if (!$discussionsonly) {
5716          $subquery = "(SELECT DISTINCT fd.course
5717                           FROM {forum_discussions} fd
5718                           JOIN {forum_posts} fp ON fp.discussion = fd.id
5719                          WHERE fp.userid = :userid )";
5720      } else {
5721          $subquery= "(SELECT DISTINCT fd.course
5722                           FROM {forum_discussions} fd
5723                          WHERE fd.userid = :userid )";
5724      }
5725  
5726      $params = array('userid' => $user->id);
5727  
5728      // Join to the context table so that we can preload contexts if required.
5729      if ($includecontexts) {
5730          $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
5731          $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
5732          $params['contextlevel'] = CONTEXT_COURSE;
5733      } else {
5734          $ctxselect = '';
5735          $ctxjoin = '';
5736      }
5737  
5738      // Now we need to get all of the courses to search.
5739      // All courses where the user has posted within a forum will be returned.
5740      $sql = "SELECT c.* $ctxselect
5741              FROM {course} c
5742              $ctxjoin
5743              WHERE c.id IN ($subquery)";
5744      $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5745      if ($includecontexts) {
5746          array_map('context_helper::preload_from_record', $courses);
5747      }
5748      return $courses;
5749  }
5750  
5751  /**
5752   * Gets all of the forums a user has posted in for one or more courses.
5753   *
5754   * @global moodle_database $DB
5755   * @param stdClass $user
5756   * @param array $courseids An array of courseids to search or if not provided
5757   *                       all courses the user has posted within
5758   * @param bool $discussionsonly If true then only forums where the user has started
5759   *                       a discussion will be returned.
5760   * @param int $limitfrom The offset of records to return
5761   * @param int $limitnum The number of records to return
5762   * @return array An array of forums the user has posted within in the provided courses
5763   */
5764  function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
5765      global $DB;
5766  
5767      if (!is_null($courseids)) {
5768          list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid');
5769          $coursewhere = ' AND f.course '.$coursewhere;
5770      } else {
5771          $coursewhere = '';
5772          $params = array();
5773      }
5774      $params['userid'] = $user->id;
5775      $params['forum'] = 'forum';
5776  
5777      if ($discussionsonly) {
5778          $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
5779      } else {
5780          $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
5781                   JOIN {forum_posts} ff ON ff.discussion = fd.id';
5782      }
5783  
5784      $sql = "SELECT f.*, cm.id AS cmid
5785                FROM {forum} f
5786                JOIN {course_modules} cm ON cm.instance = f.id
5787                JOIN {modules} m ON m.id = cm.module
5788                JOIN (
5789                    SELECT f.id
5790                      FROM {forum} f
5791                      {$join}
5792                     WHERE ff.userid = :userid
5793                  GROUP BY f.id
5794                     ) j ON j.id = f.id
5795               WHERE m.name = :forum
5796                   {$coursewhere}";
5797  
5798      $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5799      return $courseforums;
5800  }
5801  
5802  /**
5803   * Returns posts made by the selected user in the requested courses.
5804   *
5805   * This method can be used to return all of the posts made by the requested user
5806   * within the given courses.
5807   * For each course the access of the current user and requested user is checked
5808   * and then for each post access to the post and forum is checked as well.
5809   *
5810   * This function is safe to use with usercapabilities.
5811   *
5812   * @global moodle_database $DB
5813   * @param stdClass $user The user whose posts we want to get
5814   * @param array $courses The courses to search
5815   * @param bool $musthaveaccess If set to true errors will be thrown if the user
5816   *                             cannot access one or more of the courses to search
5817   * @param bool $discussionsonly If set to true only discussion starting posts
5818   *                              will be returned.
5819   * @param int $limitfrom The offset of records to return
5820   * @param int $limitnum The number of records to return
5821   * @return stdClass An object the following properties
5822   *               ->totalcount: the total number of posts made by the requested user
5823   *                             that the current user can see.
5824   *               ->courses: An array of courses the current user can see that the
5825   *                          requested user has posted in.
5826   *               ->forums: An array of forums relating to the posts returned in the
5827   *                         property below.
5828   *               ->posts: An array containing the posts to show for this request.
5829   */
5830  function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
5831      global $DB, $USER, $CFG;
5832  
5833      $return = new stdClass;
5834      $return->totalcount = 0;    // The total number of posts that the current user is able to view
5835      $return->courses = array(); // The courses the current user can access
5836      $return->forums = array();  // The forums that the current user can access that contain posts
5837      $return->posts = array();   // The posts to display
5838  
5839      // First up a small sanity check. If there are no courses to check we can
5840      // return immediately, there is obviously nothing to search.
5841      if (empty($courses)) {
5842          return $return;
5843      }
5844  
5845      // A couple of quick setups
5846      $isloggedin = isloggedin();
5847      $isguestuser = $isloggedin && isguestuser();
5848      $iscurrentuser = $isloggedin && $USER->id == $user->id;
5849  
5850      // Checkout whether or not the current user has capabilities over the requested
5851      // user and if so they have the capabilities required to view the requested
5852      // users content.
5853      $usercontext = context_user::instance($user->id, MUST_EXIST);
5854      $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
5855      $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
5856  
5857      // Before we actually search each course we need to check the user's access to the
5858      // course. If the user doesn't have the appropraite access then we either throw an
5859      // error if a particular course was requested or we just skip over the course.
5860      foreach ($courses as $course) {
5861          $coursecontext = context_course::instance($course->id, MUST_EXIST);
5862          if ($iscurrentuser || $hascapsonuser) {
5863              // If it is the current user, or the current user has capabilities to the
5864              // requested user then all we need to do is check the requested users
5865              // current access to the course.
5866              // Note: There is no need to check group access or anything of the like
5867              // as either the current user is the requested user, or has granted
5868              // capabilities on the requested user. Either way they can see what the
5869              // requested user posted, although its VERY unlikely in the `parent` situation
5870              // that the current user will be able to view the posts in context.
5871              if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
5872                  // Need to have full access to a course to see the rest of own info
5873                  if ($musthaveaccess) {
5874                      throw new \moodle_exception('errorenrolmentrequired', 'forum');
5875                  }
5876                  continue;
5877              }
5878          } else {
5879              // Check whether the current user is enrolled or has access to view the course
5880              // if they don't we immediately have a problem.
5881              if (!can_access_course($course)) {
5882                  if ($musthaveaccess) {
5883                      throw new \moodle_exception('errorenrolmentrequired', 'forum');
5884                  }
5885                  continue;
5886              }
5887  
5888              // If groups are in use and enforced throughout the course then make sure
5889              // we can meet in at least one course level group.
5890              // Note that we check if either the current user or the requested user have
5891              // the capability to access all groups. This is because with that capability
5892              // a user in group A could post in the group B forum. Grrrr.
5893              if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
5894                && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
5895                  // If its the guest user to bad... the guest user cannot access groups
5896                  if (!$isloggedin or $isguestuser) {
5897                      // do not use require_login() here because we might have already used require_login($course)
5898                      if ($musthaveaccess) {
5899                          redirect(get_login_url());
5900                      }
5901                      continue;
5902                  }
5903                  // Get the groups of the current user
5904                  $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
5905                  // Get the groups the requested user is a member of
5906                  $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
5907                  // Check whether they are members of the same group. If they are great.
5908                  $intersect = array_intersect($mygroups, $usergroups);
5909                  if (empty($intersect)) {
5910                      // But they're not... if it was a specific course throw an error otherwise
5911                      // just skip this course so that it is not searched.
5912                      if ($musthaveaccess) {
5913                          throw new \moodle_exception("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
5914                      }
5915                      continue;
5916                  }
5917              }
5918          }
5919          // Woo hoo we got this far which means the current user can search this
5920          // this course for the requested user. Although this is only the course accessibility
5921          // handling that is complete, the forum accessibility tests are yet to come.
5922          $return->courses[$course->id] = $course;
5923      }
5924      // No longer beed $courses array - lose it not it may be big
5925      unset($courses);
5926  
5927      // Make sure that we have some courses to search
5928      if (empty($return->courses)) {
5929          // If we don't have any courses to search then the reality is that the current
5930          // user doesn't have access to any courses is which the requested user has posted.
5931          // Although we do know at this point that the requested user has posts.
5932          if ($musthaveaccess) {
5933              throw new \moodle_exception('permissiondenied');
5934          } else {
5935              return $return;
5936          }
5937      }
5938  
5939      // Next step: Collect all of the forums that we will want to search.
5940      // It is important to note that this step isn't actually about searching, it is
5941      // about determining which forums we can search by testing accessibility.
5942      $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);
5943  
5944      // Will be used to build the where conditions for the search
5945      $forumsearchwhere = array();
5946      // Will be used to store the where condition params for the search
5947      $forumsearchparams = array();
5948      // Will record forums where the user can freely access everything
5949      $forumsearchfullaccess = array();
5950      // DB caching friendly
5951      $now = floor(time() / 60) * 60;
5952      // For each course to search we want to find the forums the user has posted in
5953      // and providing the current user can access the forum create a search condition
5954      // for the forum to get the requested users posts.
5955      foreach ($return->courses as $course) {
5956          // Now we need to get the forums
5957          $modinfo = get_fast_modinfo($course);
5958          if (empty($modinfo->instances['forum'])) {
5959              // hmmm, no forums? well at least its easy... skip!
5960              continue;
5961          }
5962          // Iterate
5963          foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
5964              if (!$cm->uservisible or !isset($forums[$forumid])) {
5965                  continue;
5966              }
5967              // Get the forum in question
5968              $forum = $forums[$forumid];
5969  
5970              // This is needed for functionality later on in the forum code. It is converted to an object
5971              // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
5972              // code were expecting an writeable object. See {@link forum_print_post()}.
5973              $forum->cm = new stdClass();
5974              foreach ($cm as $key => $value) {
5975                  $forum->cm->$key = $value;
5976              }
5977  
5978              // Check that either the current user can view the forum, or that the
5979              // current user has capabilities over the requested user and the requested
5980              // user can view the discussion
5981              if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
5982                  continue;
5983              }
5984  
5985              // This will contain forum specific where clauses
5986              $forumsearchselect = array();
5987              if (!$iscurrentuser && !$hascapsonuser) {
5988                  // Make sure we check group access
5989                  if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
5990                      $groups = $modinfo->get_groups($cm->groupingid);
5991                      $groups[] = -1;
5992                      list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
5993                      $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
5994                      $forumsearchselect[] = "d.groupid $groupid_sql";
5995                  }
5996  
5997                  // hidden timed discussions
5998                  if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
5999                      $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
6000                      $forumsearchparams['userid'.$forumid] = $user->id;
6001                      $forumsearchparams['timestart'.$forumid] = $now;
6002                      $forumsearchparams['timeend'.$forumid] = $now;
6003                  }
6004  
6005                  // qanda access
6006                  if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
6007                      // We need to check whether the user has posted in the qanda forum.
6008                      $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
6009                      if (!empty($discussionspostedin)) {
6010                          $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
6011                          foreach ($discussionspostedin as $d) {
6012                              $forumonlydiscussions[] = $d->id;
6013                          }
6014                          list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
6015                          $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
6016                          $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
6017                      } else {
6018                          $forumsearchselect[] = "p.parent = 0";
6019                      }
6020  
6021                  }
6022  
6023                  if (count($forumsearchselect) > 0) {
6024                      $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
6025                      $forumsearchparams['forum'.$forumid] = $forumid;
6026                  } else {
6027                      $forumsearchfullaccess[] = $forumid;
6028                  }
6029              } else {
6030                  // The current user/parent can see all of their own posts
6031                  $forumsearchfullaccess[] = $forumid;
6032              }
6033          }
6034      }
6035  
6036      // If we dont have any search conditions, and we don't have any forums where
6037      // the user has full access then we just return the default.
6038      if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
6039          return $return;
6040      }
6041  
6042      // Prepare a where condition for the full access forums.
6043      if (count($forumsearchfullaccess) > 0) {
6044          list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
6045          $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
6046          $forumsearchwhere[] = "(d.forum $fullidsql)";
6047      }
6048  
6049      // Prepare SQL to both count and search.
6050      // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
6051      // oracle and mssql.
6052      $userfieldsapi = \core_user\fields::for_userpic();
6053      $userfields = $userfieldsapi->get_sql('u', false, '', 'useridx', false)->selects;
6054      $countsql = 'SELECT COUNT(*) ';
6055      $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
6056      $wheresql = implode(" OR ", $forumsearchwhere);
6057  
6058      if ($discussionsonly) {
6059          if ($wheresql == '') {
6060              $wheresql = 'p.parent = 0';
6061          } else {
6062              $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
6063          }
6064      }
6065  
6066      $sql = "FROM {forum_posts} p
6067              JOIN {forum_discussions} d ON d.id = p.discussion
6068              JOIN {user} u ON u.id = p.userid
6069             WHERE ($wheresql)
6070               AND p.userid = :userid ";
6071      $orderby = "ORDER BY p.modified DESC";
6072      $forumsearchparams['userid'] = $user->id;
6073  
6074      // Set the total number posts made by the requested user that the current user can see
6075      $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
6076      // Set the collection of posts that has been requested
6077      $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
6078  
6079      // We need to build an array of forums for which posts will be displayed.
6080      // We do this here to save the caller needing to retrieve them themselves before
6081      // printing these forums posts. Given we have the forums already there is
6082      // practically no overhead here.
6083      foreach ($return->posts as $post) {
6084          if (!array_key_exists($post->forum, $return->forums)) {
6085              $return->forums[$post->forum] = $forums[$post->forum];
6086          }
6087      }
6088  
6089      return $return;
6090  }
6091  
6092  /**
6093   * Set the per-forum maildigest option for the specified user.
6094   *
6095   * @param stdClass $forum The forum to set the option for.
6096   * @param int $maildigest The maildigest option.
6097   * @param stdClass $user The user object. This defaults to the global $USER object.
6098   * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
6099   */
6100  function forum_set_user_maildigest($forum, $maildigest, $user = null) {
6101      global $DB, $USER;
6102  
6103      if (is_number($forum)) {
6104          $forum = $DB->get_record('forum', array('id' => $forum));
6105      }
6106  
6107      if ($user === null) {
6108          $user = $USER;
6109      }
6110  
6111      $course  = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
6112      $cm      = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
6113      $context = context_module::instance($cm->id);
6114  
6115      // User must be allowed to see this forum.
6116      require_capability('mod/forum:viewdiscussion', $context, $user->id);
6117  
6118      // Validate the maildigest setting.
6119      $digestoptions = forum_get_user_digest_options($user);
6120  
6121      if (!isset($digestoptions[$maildigest])) {
6122          throw new moodle_exception('invaliddigestsetting', 'mod_forum');
6123      }
6124  
6125      // Attempt to retrieve any existing forum digest record.
6126      $subscription = $DB->get_record('forum_digests', array(
6127          'userid' => $user->id,
6128          'forum' => $forum->id,
6129      ));
6130  
6131      // Create or Update the existing maildigest setting.
6132      if ($subscription) {
6133          if ($maildigest == -1) {
6134              $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id));
6135          } else if ($maildigest !== $subscription->maildigest) {
6136              // Only update the maildigest setting if it's changed.
6137  
6138              $subscription->maildigest = $maildigest;
6139              $DB->update_record('forum_digests', $subscription);
6140          }
6141      } else {
6142          if ($maildigest != -1) {
6143              // Only insert the maildigest setting if it's non-default.
6144  
6145              $subscription = new stdClass();
6146              $subscription->forum = $forum->id;
6147              $subscription->userid = $user->id;
6148              $subscription->maildigest = $maildigest;
6149              $subscription->id = $DB->insert_record('forum_digests', $subscription);
6150          }
6151      }
6152  }
6153  
6154  /**
6155   * Determine the maildigest setting for the specified user against the
6156   * specified forum.
6157   *
6158   * @param Array $digests An array of forums and user digest settings.
6159   * @param stdClass $user The user object containing the id and maildigest default.
6160   * @param int $forumid The ID of the forum to check.
6161   * @return int The calculated maildigest setting for this user and forum.
6162   */
6163  function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
6164      if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) {
6165          $maildigest = $digests[$forumid][$user->id];
6166          if ($maildigest === -1) {
6167              $maildigest = $user->maildigest;
6168          }
6169      } else {
6170          $maildigest = $user->maildigest;
6171      }
6172      return $maildigest;
6173  }
6174  
6175  /**
6176   * Retrieve the list of available user digest options.
6177   *
6178   * @param stdClass $user The user object. This defaults to the global $USER object.
6179   * @return array The mapping of values to digest options.
6180   */
6181  function forum_get_user_digest_options($user = null) {
6182      global $USER;
6183  
6184      // Revert to the global user object.
6185      if ($user === null) {
6186          $user = $USER;
6187      }
6188  
6189      $digestoptions = array();
6190      $digestoptions['0']  = get_string('emaildigestoffshort', 'mod_forum');
6191      $digestoptions['1']  = get_string('emaildigestcompleteshort', 'mod_forum');
6192      $digestoptions['2']  = get_string('emaildigestsubjectsshort', 'mod_forum');
6193  
6194      // We need to add the default digest option at the end - it relies on
6195      // the contents of the existing values.
6196      $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
6197              $digestoptions[$user->maildigest]);
6198  
6199      // Resort the options to be in a sensible order.
6200      ksort($digestoptions);
6201  
6202      return $digestoptions;
6203  }
6204  
6205  /**
6206   * Determine the current context if one was not already specified.
6207   *
6208   * If a context of type context_module is specified, it is immediately
6209   * returned and not checked.
6210   *
6211   * @param int $forumid The ID of the forum
6212   * @param context_module $context The current context.
6213   * @return context_module The context determined
6214   */
6215  function forum_get_context($forumid, $context = null) {
6216      global $PAGE;
6217  
6218      if (!$context || !($context instanceof context_module)) {
6219          // Find out forum context. First try to take current page context to save on DB query.
6220          if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid
6221                  && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) {
6222              $context = $PAGE->context;
6223          } else {
6224              $cm = get_coursemodule_from_instance('forum', $forumid);
6225              $context = \context_module::instance($cm->id);
6226          }
6227      }
6228  
6229      return $context;
6230  }
6231  
6232  /**
6233   * Mark the activity completed (if required) and trigger the course_module_viewed event.
6234   *
6235   * @param  stdClass $forum   forum object
6236   * @param  stdClass $course  course object
6237   * @param  stdClass $cm      course module object
6238   * @param  stdClass $context context object
6239   * @since Moodle 2.9
6240   */
6241  function forum_view($forum, $course, $cm, $context) {
6242  
6243      // Completion.
6244      $completion = new completion_info($course);
6245      $completion->set_module_viewed($cm);
6246  
6247      // Trigger course_module_viewed event.
6248  
6249      $params = array(
6250          'context' => $context,
6251          'objectid' => $forum->id
6252      );
6253  
6254      $event = \mod_forum\event\course_module_viewed::create($params);
6255      $event->add_record_snapshot('course_modules', $cm);
6256      $event->add_record_snapshot('course', $course);
6257      $event->add_record_snapshot('forum', $forum);
6258      $event->trigger();
6259  }
6260  
6261  /**
6262   * Trigger the discussion viewed event
6263   *
6264   * @param  stdClass $modcontext module context object
6265   * @param  stdClass $forum      forum object
6266   * @param  stdClass $discussion discussion object
6267   * @since Moodle 2.9
6268   */
6269  function forum_discussion_view($modcontext, $forum, $discussion) {
6270      $params = array(
6271          'context' => $modcontext,
6272          'objectid' => $discussion->id,
6273      );
6274  
6275      $event = \mod_forum\event\discussion_viewed::create($params);
6276      $event->add_record_snapshot('forum_discussions', $discussion);
6277      $event->add_record_snapshot('forum', $forum);
6278      $event->trigger();
6279  }
6280  
6281  /**
6282   * Set the discussion to pinned and trigger the discussion pinned event
6283   *
6284   * @param  stdClass $modcontext module context object
6285   * @param  stdClass $forum      forum object
6286   * @param  stdClass $discussion discussion object
6287   * @since Moodle 3.1
6288   */
6289  function forum_discussion_pin($modcontext, $forum, $discussion) {
6290      global $DB;
6291  
6292      $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED, array('id' => $discussion->id));
6293  
6294      $params = array(
6295          'context' => $modcontext,
6296          'objectid' => $discussion->id,
6297          'other' => array('forumid' => $forum->id)
6298      );
6299  
6300      $event = \mod_forum\event\discussion_pinned::create($params);
6301      $event->add_record_snapshot('forum_discussions', $discussion);
6302      $event->trigger();
6303  }
6304  
6305  /**
6306   * Set discussion to unpinned and trigger the discussion unpin event
6307   *
6308   * @param  stdClass $modcontext module context object
6309   * @param  stdClass $forum      forum object
6310   * @param  stdClass $discussion discussion object
6311   * @since Moodle 3.1
6312   */
6313  function forum_discussion_unpin($modcontext, $forum, $discussion) {
6314      global $DB;
6315  
6316      $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED, array('id' => $discussion->id));
6317  
6318      $params = array(
6319          'context' => $modcontext,
6320          'objectid' => $discussion->id,
6321          'other' => array('forumid' => $forum->id)
6322      );
6323  
6324      $event = \mod_forum\event\discussion_unpinned::create($params);
6325      $event->add_record_snapshot('forum_discussions', $discussion);
6326      $event->trigger();
6327  }
6328  
6329  /**
6330   * Add nodes to myprofile page.
6331   *
6332   * @param \core_user\output\myprofile\tree $tree Tree object
6333   * @param stdClass $user user object
6334   * @param bool $iscurrentuser
6335   * @param stdClass $course Course object
6336   *
6337   * @return bool
6338   */
6339  function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
6340      if (isguestuser($user)) {
6341          // The guest user cannot post, so it is not possible to view any posts.
6342          // May as well just bail aggressively here.
6343          return false;
6344      }
6345      $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id));
6346      if (!empty($course)) {
6347          $postsurl->param('course', $course->id);
6348      }
6349      $string = get_string('forumposts', 'mod_forum');
6350      $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl);
6351      $tree->add_node($node);
6352  
6353      $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions'));
6354      if (!empty($course)) {
6355          $discussionssurl->param('course', $course->id);
6356      }
6357      $string = get_string('myprofileotherdis', 'mod_forum');
6358      $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null,
6359          $discussionssurl);
6360      $tree->add_node($node);
6361  
6362      return true;
6363  }
6364  
6365  /**
6366   * Checks whether the author's name and picture for a given post should be hidden or not.
6367   *
6368   * @param object $post The forum post.
6369   * @param object $forum The forum object.
6370   * @return bool
6371   * @throws coding_exception
6372   */
6373  function forum_is_author_hidden($post, $forum) {
6374      if (!isset($post->parent)) {
6375          throw new coding_exception('$post->parent must be set.');
6376      }
6377      if (!isset($forum->type)) {
6378          throw new coding_exception('$forum->type must be set.');
6379      }
6380      if ($forum->type === 'single' && empty($post->parent)) {
6381          return true;
6382      }
6383      return false;
6384  }
6385  
6386  /**
6387   * Manage inplace editable saves.
6388   *
6389   * @param   string      $itemtype       The type of item.
6390   * @param   int         $itemid         The ID of the item.
6391   * @param   mixed       $newvalue       The new value
6392   * @return  string
6393   */
6394  function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) {
6395      global $DB, $PAGE;
6396  
6397      if ($itemtype === 'digestoptions') {
6398          // The itemid is the forumid.
6399          $forum   = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST);
6400          $course  = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
6401          $cm      = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
6402          $context = context_module::instance($cm->id);
6403  
6404          $PAGE->set_context($context);
6405          require_login($course, false, $cm);
6406          forum_set_user_maildigest($forum, $newvalue);
6407  
6408          $renderer = $PAGE->get_renderer('mod_forum');
6409          return $renderer->render_digest_options($forum, $newvalue);
6410      }
6411  }
6412  
6413  /**
6414   * Determine whether the specified forum's cutoff date is reached.
6415   *
6416   * @param stdClass $forum The forum
6417   * @return bool
6418   */
6419  function forum_is_cutoff_date_reached($forum) {
6420      $entityfactory = \mod_forum\local\container::get_entity_factory();
6421      $coursemoduleinfo = get_fast_modinfo($forum->course);
6422      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6423      $forumentity = $entityfactory->get_forum_from_stdclass(
6424              $forum,
6425              context_module::instance($cminfo->id),
6426              $cminfo->get_course_module_record(),
6427              $cminfo->get_course()
6428      );
6429  
6430      return $forumentity->is_cutoff_date_reached();
6431  }
6432  
6433  /**
6434   * Determine whether the specified forum's due date is reached.
6435   *
6436   * @param stdClass $forum The forum
6437   * @return bool
6438   */
6439  function forum_is_due_date_reached($forum) {
6440      $entityfactory = \mod_forum\local\container::get_entity_factory();
6441      $coursemoduleinfo = get_fast_modinfo($forum->course);
6442      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6443      $forumentity = $entityfactory->get_forum_from_stdclass(
6444              $forum,
6445              context_module::instance($cminfo->id),
6446              $cminfo->get_course_module_record(),
6447              $cminfo->get_course()
6448      );
6449  
6450      return $forumentity->is_due_date_reached();
6451  }
6452  
6453  /**
6454   * Determine whether the specified discussion is time-locked.
6455   *
6456   * @param   stdClass    $forum          The forum that the discussion belongs to
6457   * @param   stdClass    $discussion     The discussion to test
6458   * @return  bool
6459   */
6460  function forum_discussion_is_locked($forum, $discussion) {
6461      $entityfactory = \mod_forum\local\container::get_entity_factory();
6462      $coursemoduleinfo = get_fast_modinfo($forum->course);
6463      $cminfo = $coursemoduleinfo->instances['forum'][$forum->id];
6464      $forumentity = $entityfactory->get_forum_from_stdclass(
6465          $forum,
6466          context_module::instance($cminfo->id),
6467          $cminfo->get_course_module_record(),
6468          $cminfo->get_course()
6469      );
6470      $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
6471  
6472      return $forumentity->is_discussion_locked($discussionentity);
6473  }
6474  
6475  /**
6476   * Check if the module has any update that affects the current user since a given time.
6477   *
6478   * @param  cm_info $cm course module data
6479   * @param  int $from the time to check updates from
6480   * @param  array $filter  if we need to check only specific updates
6481   * @return stdClass an object with the different type of areas indicating if they were updated or not
6482   * @since Moodle 3.2
6483   */
6484  function forum_check_updates_since(cm_info $cm, $from, $filter = array()) {
6485  
6486      $context = $cm->context;
6487      $updates = new stdClass();
6488      if (!has_capability('mod/forum:viewdiscussion', $context)) {
6489          return $updates;
6490      }
6491  
6492      $updates = course_check_module_updates_since($cm, $from, array(), $filter);
6493  
6494      // Check if there are new discussions in the forum.
6495      $updates->discussions = (object) array('updated' => false);
6496      $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS, $from);
6497      if (!empty($discussions)) {
6498          $updates->discussions->updated = true;
6499          $updates->discussions->itemids = array_keys($discussions);
6500      }
6501  
6502      return $updates;
6503  }
6504  
6505  /**
6506   * Check if the user can create attachments in a forum.
6507   * @param  stdClass $forum   forum object
6508   * @param  stdClass $context context object
6509   * @return bool true if the user can create attachments, false otherwise
6510   * @since  Moodle 3.3
6511   */
6512  function forum_can_create_attachment($forum, $context) {
6513      // If maxbytes == 1 it means no attachments at all.
6514      if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
6515              !has_capability('mod/forum:createattachment', $context)) {
6516          return false;
6517      }
6518      return true;
6519  }
6520  
6521  /**
6522   * Get icon mapping for font-awesome.
6523   *
6524   * @return  array
6525   */
6526  function mod_forum_get_fontawesome_icon_map() {
6527      return [
6528          'mod_forum:i/pinned' => 'fa-map-pin',
6529          'mod_forum:t/selected' => 'fa-check',
6530          'mod_forum:t/subscribed' => 'fa-envelope-o',
6531          'mod_forum:t/unsubscribed' => 'fa-envelope-open-o',
6532          'mod_forum:t/star' => 'fa-star',
6533      ];
6534  }
6535  
6536  /**
6537   * Callback function that determines whether an action event should be showing its item count
6538   * based on the event type and the item count.
6539   *
6540   * @param calendar_event $event The calendar event.
6541   * @param int $itemcount The item count associated with the action event.
6542   * @return bool
6543   */
6544  function mod_forum_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
6545      // Always show item count for forums if item count is greater than 1.
6546      // If only one action is required than it is obvious and we don't show it for other modules.
6547      return $itemcount > 1;
6548  }
6549  
6550  /**
6551   * This function receives a calendar event and returns the action associated with it, or null if there is none.
6552   *
6553   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
6554   * is not displayed on the block.
6555   *
6556   * @param calendar_event $event
6557   * @param \core_calendar\action_factory $factory
6558   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
6559   * @return \core_calendar\local\event\entities\action_interface|null
6560   */
6561  function mod_forum_core_calendar_provide_event_action(calendar_event $event,
6562                                                        \core_calendar\action_factory $factory,
6563                                                        int $userid = 0) {
6564      global $DB, $USER;
6565  
6566      if (!$userid) {
6567          $userid = $USER->id;
6568      }
6569  
6570      $cm = get_fast_modinfo($event->courseid, $userid)->instances['forum'][$event->instance];
6571  
6572      if (!$cm->uservisible) {
6573          // The module is not visible to the user for any reason.
6574          return null;
6575      }
6576  
6577      $context = context_module::instance($cm->id);
6578  
6579      if (!has_capability('mod/forum:viewdiscussion', $context, $userid)) {
6580          return null;
6581      }
6582  
6583      $completion = new \completion_info($cm->get_course());
6584  
6585      $completiondata = $completion->get_data($cm, false, $userid);
6586  
6587      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
6588          return null;
6589      }
6590  
6591      // Get action itemcount.
6592      $itemcount = 0;
6593      $forum = $DB->get_record('forum', array('id' => $cm->instance));
6594      $postcountsql = "
6595                  SELECT
6596                      COUNT(1)
6597                    FROM
6598                      {forum_posts} fp
6599                      INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
6600                   WHERE
6601                      fp.userid=:userid AND fd.forum=:forumid";
6602      $postcountparams = array('userid' => $userid, 'forumid' => $forum->id);
6603  
6604      if ($forum->completiondiscussions) {
6605          $count = $DB->count_records('forum_discussions', array('forum' => $forum->id, 'userid' => $userid));
6606          $itemcount += ($forum->completiondiscussions >= $count) ? ($forum->completiondiscussions - $count) : 0;
6607      }
6608  
6609      if ($forum->completionreplies) {
6610          $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams);
6611          $itemcount += ($forum->completionreplies >= $count) ? ($forum->completionreplies - $count) : 0;
6612      }
6613  
6614      if ($forum->completionposts) {
6615          $count = $DB->get_field_sql($postcountsql, $postcountparams);
6616          $itemcount += ($forum->completionposts >= $count) ? ($forum->completionposts - $count) : 0;
6617      }
6618  
6619      // Well there is always atleast one actionable item (view forum, etc).
6620      $itemcount = $itemcount > 0 ? $itemcount : 1;
6621  
6622      return $factory->create_instance(
6623          get_string('view'),
6624          new \moodle_url('/mod/forum/view.php', ['id' => $cm->id]),
6625          $itemcount,
6626          true
6627      );
6628  }
6629  
6630  /**
6631   * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information
6632   * for the course (see resource).
6633   *
6634   * Given a course_module object, this function returns any "extra" information that may be needed
6635   * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
6636   *
6637   * @param stdClass $coursemodule The coursemodule object (record).
6638   * @return cached_cm_info An object on information that the courses
6639   *                        will know about (most noticeably, an icon).
6640   */
6641  function forum_get_coursemodule_info($coursemodule) {
6642      global $DB;
6643  
6644      $dbparams = ['id' => $coursemodule->instance];
6645      $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies, duedate, cutoffdate';
6646      if (!$forum = $DB->get_record('forum', $dbparams, $fields)) {
6647          return false;
6648      }
6649  
6650      $result = new cached_cm_info();
6651      $result->name = $forum->name;
6652  
6653      if ($coursemodule->showdescription) {
6654          // Convert intro to html. Do not filter cached version, filters run at display time.
6655          $result->content = format_module_intro('forum', $forum, $coursemodule->id, false);
6656      }
6657  
6658      // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
6659      if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
6660          $result->customdata['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions;
6661          $result->customdata['customcompletionrules']['completionreplies'] = $forum->completionreplies;
6662          $result->customdata['customcompletionrules']['completionposts'] = $forum->completionposts;
6663      }
6664  
6665      // Populate some other values that can be used in calendar or on dashboard.
6666      if ($forum->duedate) {
6667          $result->customdata['duedate'] = $forum->duedate;
6668      }
6669      if ($forum->cutoffdate) {
6670          $result->customdata['cutoffdate'] = $forum->cutoffdate;
6671      }
6672  
6673      return $result;
6674  }
6675  
6676  /**
6677   * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
6678   *
6679   * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
6680   * @return array $descriptions the array of descriptions for the custom rules.
6681   */
6682  function mod_forum_get_completion_active_rule_descriptions($cm) {
6683      // Values will be present in cm_info, and we assume these are up to date.
6684      if (empty($cm->customdata['customcompletionrules'])
6685          || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
6686          return [];
6687      }
6688  
6689      $descriptions = [];
6690      foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
6691          switch ($key) {
6692              case 'completiondiscussions':
6693                  if (!empty($val)) {
6694                      $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val);
6695                  }
6696                  break;
6697              case 'completionreplies':
6698                  if (!empty($val)) {
6699                      $descriptions[] = get_string('completionrepliesdesc', 'forum', $val);
6700                  }
6701                  break;
6702              case 'completionposts':
6703                  if (!empty($val)) {
6704                      $descriptions[] = get_string('completionpostsdesc', 'forum', $val);
6705                  }
6706                  break;
6707              default:
6708                  break;
6709          }
6710      }
6711      return $descriptions;
6712  }
6713  
6714  /**
6715   * Check whether the forum post is a private reply visible to this user.
6716   *
6717   * @param   stdClass    $post   The post to check.
6718   * @param   cm_info     $cm     The context module instance.
6719   * @return  bool                Whether the post is visible in terms of private reply configuration.
6720   */
6721  function forum_post_is_visible_privately($post, $cm) {
6722      global $USER;
6723  
6724      if (!empty($post->privatereplyto)) {
6725          // Allow the user to see the private reply if:
6726          // * they hold the permission;
6727          // * they are the author; or
6728          // * they are the intended recipient.
6729          $cansee = false;
6730          $cansee = $cansee || ($post->userid == $USER->id);
6731          $cansee = $cansee || ($post->privatereplyto == $USER->id);
6732          $cansee = $cansee || has_capability('mod/forum:readprivatereplies', context_module::instance($cm->id));
6733          return $cansee;
6734      }
6735  
6736      return true;
6737  }
6738  
6739  /**
6740   * Check whether the user can reply privately to the parent post.
6741   *
6742   * @param   \context_module $context
6743   * @param   \stdClass   $parent
6744   * @return  bool
6745   */
6746  function forum_user_can_reply_privately(\context_module $context, \stdClass $parent) : bool {
6747      if ($parent->privatereplyto) {
6748          // You cannot reply privately to a post which is, itself, a private reply.
6749          return false;
6750      }
6751  
6752      return has_capability('mod/forum:postprivatereply', $context);
6753  }
6754  
6755  /**
6756   * This function calculates the minimum and maximum cutoff values for the timestart of
6757   * the given event.
6758   *
6759   * It will return an array with two values, the first being the minimum cutoff value and
6760   * the second being the maximum cutoff value. Either or both values can be null, which
6761   * indicates there is no minimum or maximum, respectively.
6762   *
6763   * If a cutoff is required then the function must return an array containing the cutoff
6764   * timestamp and error string to display to the user if the cutoff value is violated.
6765   *
6766   * A minimum and maximum cutoff return value will look like:
6767   * [
6768   *     [1505704373, 'The date must be after this date'],
6769   *     [1506741172, 'The date must be before this date']
6770   * ]
6771   *
6772   * @param calendar_event $event The calendar event to get the time range for
6773   * @param stdClass $forum The module instance to get the range from
6774   * @return array Returns an array with min and max date.
6775   */
6776  function mod_forum_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $forum) {
6777      global $CFG;
6778  
6779      require_once($CFG->dirroot . '/mod/forum/locallib.php');
6780  
6781      $mindate = null;
6782      $maxdate = null;
6783  
6784      if ($event->eventtype == FORUM_EVENT_TYPE_DUE) {
6785          if (!empty($forum->cutoffdate)) {
6786              $maxdate = [
6787                  $forum->cutoffdate,
6788                  get_string('cutoffdatevalidation', 'forum'),
6789              ];
6790          }
6791      }
6792  
6793      return [$mindate, $maxdate];
6794  }
6795  
6796  /**
6797   * This function will update the forum module according to the
6798   * event that has been modified.
6799   *
6800   * It will set the timeclose value of the forum instance
6801   * according to the type of event provided.
6802   *
6803   * @throws \moodle_exception
6804   * @param \calendar_event $event
6805   * @param stdClass $forum The module instance to get the range from
6806   */
6807  function mod_forum_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $forum) {
6808      global $CFG, $DB;
6809  
6810      require_once($CFG->dirroot . '/mod/forum/locallib.php');
6811  
6812      if ($event->eventtype != FORUM_EVENT_TYPE_DUE) {
6813          return;
6814      }
6815  
6816      $courseid = $event->courseid;
6817      $modulename = $event->modulename;
6818      $instanceid = $event->instance;
6819  
6820      // Something weird going on. The event is for a different module so
6821      // we should ignore it.
6822      if ($modulename != 'forum') {
6823          return;
6824      }
6825  
6826      if ($forum->id != $instanceid) {
6827          return;
6828      }
6829  
6830      $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
6831      $context = context_module::instance($coursemodule->id);
6832  
6833      // The user does not have the capability to modify this activity.
6834      if (!has_capability('moodle/course:manageactivities', $context)) {
6835          return;
6836      }
6837  
6838      if ($event->eventtype == FORUM_EVENT_TYPE_DUE) {
6839          if ($forum->duedate != $event->timestart) {
6840              $forum->duedate = $event->timestart;
6841              $forum->timemodified = time();
6842              // Persist the instance changes.
6843              $DB->update_record('forum', $forum);
6844              $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
6845              $event->trigger();
6846          }
6847      }
6848  }
6849  
6850  /**
6851   * Fetch the data used to display the discussions on the current page.
6852   *
6853   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6854   * @param   stdClass                         $user The user to render for
6855   * @param   int[]|null                       $groupid The group to render
6856   * @param   int|null                         $sortorder The sort order to use when selecting the discussions in the list
6857   * @param   int|null                         $pageno The zero-indexed page number to use
6858   * @param   int|null                         $pagesize The number of discussions to show on the page
6859   * @return  array                            The data to use for display
6860   */
6861  function mod_forum_get_discussion_summaries(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid, ?int $sortorder,
6862          ?int $pageno = 0, ?int $pagesize = 0) {
6863  
6864      $vaultfactory = mod_forum\local\container::get_vault_factory();
6865      $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6866      $managerfactory = mod_forum\local\container::get_manager_factory();
6867      $capabilitymanager = $managerfactory->get_capability_manager($forum);
6868  
6869      $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6870  
6871      if (null === $groupids) {
6872          return $discussions = $discussionvault->get_from_forum_id(
6873              $forum->get_id(),
6874              $capabilitymanager->can_view_hidden_posts($user),
6875              $user->id,
6876              $sortorder,
6877              $pagesize,
6878              $pageno * $pagesize);
6879      } else {
6880          return $discussions = $discussionvault->get_from_forum_id_and_group_id(
6881              $forum->get_id(),
6882              $groupids,
6883              $capabilitymanager->can_view_hidden_posts($user),
6884              $user->id,
6885              $sortorder,
6886              $pagesize,
6887              $pageno * $pagesize);
6888      }
6889  }
6890  
6891  /**
6892   * Get a count of all discussions in a forum.
6893   *
6894   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6895   * @param   stdClass                         $user The user to render for
6896   * @param   int                              $groupid The group to render
6897   * @return  int                              The number of discussions in a forum
6898   */
6899  function mod_forum_count_all_discussions(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) {
6900  
6901      $managerfactory = mod_forum\local\container::get_manager_factory();
6902      $capabilitymanager = $managerfactory->get_capability_manager($forum);
6903      $vaultfactory = mod_forum\local\container::get_vault_factory();
6904      $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6905  
6906      $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6907  
6908      if (null === $groupids) {
6909          return $discussionvault->get_total_discussion_count_from_forum_id(
6910              $forum->get_id(),
6911              $capabilitymanager->can_view_hidden_posts($user),
6912              $user->id);
6913      } else {
6914          return $discussionvault->get_total_discussion_count_from_forum_id_and_group_id(
6915              $forum->get_id(),
6916              $groupids,
6917              $capabilitymanager->can_view_hidden_posts($user),
6918              $user->id);
6919      }
6920  }
6921  
6922  /**
6923   * Get the list of groups to show based on the current user and requested groupid.
6924   *
6925   * @param   \mod_forum\local\entities\forum  $forum The forum entity
6926   * @param   stdClass                         $user The user viewing
6927   * @param   int                              $groupid The groupid requested
6928   * @return  array                            The list of groups to show
6929   */
6930  function mod_forum_get_groups_from_groupid(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) : ?array {
6931  
6932      $effectivegroupmode = $forum->get_effective_group_mode();
6933      if (empty($effectivegroupmode)) {
6934          // This forum is not in a group mode. Show all posts always.
6935          return null;
6936      }
6937  
6938      if (null == $groupid) {
6939          $managerfactory = mod_forum\local\container::get_manager_factory();
6940          $capabilitymanager = $managerfactory->get_capability_manager($forum);
6941          // No group was specified.
6942          $showallgroups = (VISIBLEGROUPS == $effectivegroupmode);
6943          $showallgroups = $showallgroups || $capabilitymanager->can_access_all_groups($user);
6944          if ($showallgroups) {
6945              // Return null to show all groups.
6946              return null;
6947          } else {
6948              // No group was specified. Only show the users current groups.
6949              return array_keys(
6950                  groups_get_all_groups(
6951                      $forum->get_course_id(),
6952                      $user->id,
6953                      $forum->get_course_module_record()->groupingid
6954                  )
6955              );
6956          }
6957      } else {
6958          // A group was specified. Just show that group.
6959          return [$groupid];
6960      }
6961  }
6962  
6963  /**
6964   * Return a list of all the user preferences used by mod_forum.
6965   *
6966   * @return array
6967   */
6968  function mod_forum_user_preferences() {
6969      $vaultfactory = \mod_forum\local\container::get_vault_factory();
6970      $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
6971  
6972      $preferences = array();
6973      $preferences['forum_discussionlistsortorder'] = array(
6974          'null' => NULL_NOT_ALLOWED,
6975          'default' => $discussionlistvault::SORTORDER_LASTPOST_DESC,
6976          'type' => PARAM_INT,
6977          'choices' => array(
6978              $discussionlistvault::SORTORDER_LASTPOST_DESC,
6979              $discussionlistvault::SORTORDER_LASTPOST_ASC,
6980              $discussionlistvault::SORTORDER_CREATED_DESC,
6981              $discussionlistvault::SORTORDER_CREATED_ASC,
6982              $discussionlistvault::SORTORDER_REPLIES_DESC,
6983              $discussionlistvault::SORTORDER_REPLIES_ASC
6984          )
6985      );
6986      $preferences['forum_useexperimentalui'] = [
6987          'null' => NULL_NOT_ALLOWED,
6988          'default' => false,
6989          'type' => PARAM_BOOL
6990      ];
6991  
6992      return $preferences;
6993  }
6994  
6995  /**
6996   * Lists all gradable areas for the advanced grading methods gramework.
6997   *
6998   * @return array('string'=>'string') An array with area names as keys and descriptions as values
6999   */
7000  function forum_grading_areas_list() {
7001      return [
7002          'forum' => get_string('grade_forum_header', 'forum'),
7003      ];
7004  }
7005  
7006  /**
7007   * Callback to fetch the activity event type lang string.
7008   *
7009   * @param string $eventtype The event type.
7010   * @return lang_string The event type lang string.
7011   */
7012  function mod_forum_core_calendar_get_event_action_string(string $eventtype): string {
7013      global $CFG;
7014      require_once($CFG->dirroot . '/mod/forum/locallib.php');
7015  
7016      $modulename = get_string('modulename', 'forum');
7017  
7018      if ($eventtype == FORUM_EVENT_TYPE_DUE) {
7019          return get_string('calendardue', 'forum', $modulename);
7020      } else {
7021          return get_string('requiresaction', 'calendar', $modulename);
7022      }
7023  }
7024  
7025  /**
7026   * This callback will check the provided instance of this module
7027   * and make sure there are up-to-date events created for it.
7028   *
7029   * @param int $courseid Not used.
7030   * @param stdClass $instance Forum module instance.
7031   * @param stdClass $cm Course module object.
7032   */
7033  function forum_refresh_events(int $courseid, stdClass $instance, stdClass $cm): void {
7034      global $CFG;
7035  
7036      // This function is called by cron and we need to include the locallib for calls further down.
7037      require_once($CFG->dirroot . '/mod/forum/locallib.php');
7038  
7039      forum_update_calendar($instance, $cm->id);
7040  }