Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/mod/forum/ -> lib.php (source)

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

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