Search moodle.org's
Developer Documentation

See Release Notes

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * @package   mod_forum
  19   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
  20   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21   */
  22  
  23  defined('MOODLE_INTERNAL') || die();
  24  
  25  /** Include required files */
  26  require_once (__DIR__ . '/deprecatedlib.php');
  27  require_once($CFG->libdir.'/filelib.php');
  28  
  29  /// CONSTANTS ///////////////////////////////////////////////////////////
  30  
  31  define('FORUM_MODE_FLATOLDEST', 1);
  32  define('FORUM_MODE_FLATNEWEST', -1);
  33  define('FORUM_MODE_THREADED', 2);
  34  define('FORUM_MODE_NESTED', 3);
  35  define('FORUM_MODE_NESTED_V2', 4);
  36  
  37  define('FORUM_CHOOSESUBSCRIBE', 0);
  38  define('FORUM_FORCESUBSCRIBE', 1);
  39  define('FORUM_INITIALSUBSCRIBE', 2);
  40  define('FORUM_DISALLOWSUBSCRIBE',3);
  41  
  42  /**
  43   * FORUM_TRACKING_OFF - Tracking is not available for this forum.
  44   */
  45  define('FORUM_TRACKING_OFF', 0);
  46  
  47  /**
  48   * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
  49   */
  50  define('FORUM_TRACKING_OPTIONAL', 1);
  51  
  52  /**
  53   * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
  54   * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
  55   */
  56  define('FORUM_TRACKING_FORCED', 2);
  57  
  58  define('FORUM_MAILED_PENDING', 0);
  59  define('FORUM_MAILED_SUCCESS', 1);
  60  define('FORUM_MAILED_ERROR', 2);
  61  
  62  if (!defined('FORUM_CRON_USER_CACHE')) {
  63      /** Defines how many full user records are cached in forum cron. */
  64      define('FORUM_CRON_USER_CACHE', 5000);
  65  }
  66  
  67  /**
  68   * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
  69   */
  70  define('FORUM_POSTS_ALL_USER_GROUPS', -2);
  71  
  72  define('FORUM_DISCUSSION_PINNED', 1);
  73  define('FORUM_DISCUSSION_UNPINNED', 0);
  74  
  75  /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
  76  
  77  /**
  78   * Given an object containing all the necessary data,
  79   * (defined by the form in mod_form.php) this function
  80   * will create a new instance and return the id number
  81   * of the new instance.
  82   *
  83   * @param stdClass $forum add forum instance
  84   * @param mod_forum_mod_form $mform
  85   * @return int intance id
  86   */
  87  function forum_add_instance($forum, $mform = null) {
  88      global $CFG, $DB;
  89  
  90      require_once($CFG->dirroot.'/mod/forum/locallib.php');
  91  
  92      $forum->timemodified = time();
  93  
  94      if (empty($forum->assessed)) {
  95          $forum->assessed = 0;
  96      }
  97  
  98      if (empty($forum->ratingtime) or empty($forum->assessed)) {
  99          $forum->assesstimestart  = 0;
 100          $forum->assesstimefinish = 0;
 101      }
 102  
 103      $forum->id = $DB->insert_record('forum', $forum);
 104      $modcontext = context_module::instance($forum->coursemodule);
 105  
 106      if ($forum->type == 'single') {  // Create related discussion.
 107          $discussion = new stdClass();
 108          $discussion->course        = $forum->course;
 109          $discussion->forum         = $forum->id;
 110          $discussion->name          = $forum->name;
 111          $discussion->assessed      = $forum->assessed;
 112          $discussion->message       = $forum->intro;
 113          $discussion->messageformat = $forum->introformat;
 114          $discussion->messagetrust  = trusttext_trusted(context_course::instance($forum->course));
 115          $discussion->mailnow       = false;
 116          $discussion->groupid       = -1;
 117  
 118          $message = '';
 119  
 120          $discussion->id = forum_add_discussion($discussion, null, $message);
 121  
 122          if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
 123              // Ugly hack - we need to copy the files somehow.
 124              $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
 125              $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
 126  
 127              $options = array('subdirs'=>true); // Use the same options as intro field!
 128              $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
 129              $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
 130          }
 131      }
 132  
 133      forum_update_calendar($forum, $forum->coursemodule);
 134      forum_grade_item_update($forum);
 135  
 136      $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
 137      \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
 138  
 139      return $forum->id;
 140  }
 141  
 142  /**
 143   * Handle changes following the creation of a forum instance.
 144   * This function is typically called by the course_module_created observer.
 145   *
 146   * @param object $context the forum context
 147   * @param stdClass $forum The forum object
 148   * @return void
 149   */
 150  function forum_instance_created($context, $forum) {
 151      if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
 152          $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
 153          foreach ($users as $user) {
 154              \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
 155          }
 156      }
 157  }
 158  
 159  /**
 160   * Given an object containing all the necessary data,
 161   * (defined by the form in mod_form.php) this function
 162   * will update an existing instance with new data.
 163   *
 164   * @global object
 165   * @param object $forum forum instance (with magic quotes)
 166   * @return bool success
 167   */
 168  function forum_update_instance($forum, $mform) {
 169      global $CFG, $DB, $OUTPUT, $USER;
 170  
 171      require_once($CFG->dirroot.'/mod/forum/locallib.php');
 172  
 173      $forum->timemodified = time();
 174      $forum->id           = $forum->instance;
 175  
 176      if (empty($forum->assessed)) {
 177          $forum->assessed = 0;
 178      }
 179  
 180      if (empty($forum->ratingtime) or empty($forum->assessed)) {
 181          $forum->assesstimestart  = 0;
 182          $forum->assesstimefinish = 0;
 183      }
 184  
 185      $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
 186  
 187      // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
 188      // if  scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
 189      // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
 190      $updategrades = false;
 191  
 192      if ($oldforum->assessed <> $forum->assessed) {
 193          // Whether this forum is rated.
 194          $updategrades = true;
 195      }
 196  
 197      if ($oldforum->scale <> $forum->scale) {
 198          // The scale currently in use.
 199          $updategrades = true;
 200      }
 201  
 202      if (empty($oldforum->grade_forum) || $oldforum->grade_forum <> $forum->grade_forum) {
 203          // The whole forum grading.
 204          $updategrades = true;
 205      }
 206  
 207      if ($updategrades) {
 208          forum_update_grades($forum); // Recalculate grades for the forum.
 209      }
 210  
 211      if ($forum->type == 'single') {  // Update related discussion and post.
 212          $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
 213          if (!empty($discussions)) {
 214              if (count($discussions) > 1) {
 215                  echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
 216              }
 217              $discussion = array_pop($discussions);
 218          } else {
 219              // try to recover by creating initial discussion - MDL-16262
 220              $discussion = new stdClass();
 221              $discussion->course          = $forum->course;
 222              $discussion->forum           = $forum->id;
 223              $discussion->name            = $forum->name;
 224              $discussion->assessed        = $forum->assessed;
 225              $discussion->message         = $forum->intro;
 226              $discussion->messageformat   = $forum->introformat;
 227              $discussion->messagetrust    = true;
 228              $discussion->mailnow         = false;
 229              $discussion->groupid         = -1;
 230  
 231              $message = '';
 232  
 233              forum_add_discussion($discussion, null, $message);
 234  
 235              if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
 236                  print_error('cannotadd', 'forum');
 237              }
 238          }
 239          if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
 240              print_error('cannotfindfirstpost', 'forum');
 241          }
 242  
 243          $cm         = get_coursemodule_from_instance('forum', $forum->id);
 244          $modcontext = context_module::instance($cm->id, MUST_EXIST);
 245  
 246          $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
 247          $post->subject       = $forum->name;
 248          $post->message       = $forum->intro;
 249          $post->messageformat = $forum->introformat;
 250          $post->messagetrust  = trusttext_trusted($modcontext);
 251          $post->modified      = $forum->timemodified;
 252          $post->userid        = $USER->id;    // MDL-18599, so that current teacher can take ownership of activities.
 253  
 254          if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
 255              // Ugly hack - we need to copy the files somehow.
 256              $options = array('subdirs'=>true); // Use the same options as intro field!
 257              $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
 258          }
 259  
 260          \mod_forum\local\entities\post::add_message_counts($post);
 261          $DB->update_record('forum_posts', $post);
 262          $discussion->name = $forum->name;
 263          $DB->update_record('forum_discussions', $discussion);
 264      }
 265  
 266      $DB->update_record('forum', $forum);
 267  
 268      $modcontext = context_module::instance($forum->coursemodule);
 269      if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
 270          $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
 271          foreach ($users as $user) {
 272              \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
 273          }
 274      }
 275  
 276      forum_update_calendar($forum, $forum->coursemodule);
 277      forum_grade_item_update($forum);
 278  
 279      $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
 280      \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
 281  
 282      return true;
 283  }
 284  
 285  
 286  /**
 287   * Given an ID of an instance of this module,
 288   * this function will permanently delete the instance
 289   * and any data that depends on it.
 290   *
 291   * @global object
 292   * @param int $id forum instance id
 293   * @return bool success
 294   */
 295  function forum_delete_instance($id) {
 296      global $DB;
 297  
 298      if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
 299          return false;
 300      }
 301      if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
 302          return false;
 303      }
 304      if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
 305          return false;
 306      }
 307  
 308      $context = context_module::instance($cm->id);
 309  
 310      // now get rid of all files
 311      $fs = get_file_storage();
 312      $fs->delete_area_files($context->id);
 313  
 314      $result = true;
 315  
 316      \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
 317  
 318      // Delete digest and subscription preferences.
 319      $DB->delete_records('forum_digests', array('forum' => $forum->id));
 320      $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
 321      $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
 322  
 323      if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
 324          foreach ($discussions as $discussion) {
 325              if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
 326                  $result = false;
 327              }
 328          }
 329      }
 330  
 331      forum_tp_delete_read_records(-1, -1, -1, $forum->id);
 332  
 333      forum_grade_item_delete($forum);
 334  
 335      // We must delete the module record after we delete the grade item.
 336      if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
 337          $result = false;
 338      }
 339  
 340      return $result;
 341  }
 342  
 343  
 344  /**
 345   * Indicates API features that the forum supports.
 346   *
 347   * @uses FEATURE_GROUPS
 348   * @uses FEATURE_GROUPINGS
 349   * @uses FEATURE_MOD_INTRO
 350   * @uses FEATURE_COMPLETION_TRACKS_VIEWS
 351   * @uses FEATURE_COMPLETION_HAS_RULES
 352   * @uses FEATURE_GRADE_HAS_GRADE
 353   * @uses FEATURE_GRADE_OUTCOMES
 354   * @param string $feature
 355   * @return mixed True if yes (some features may use other values)
 356   */
 357  function forum_supports($feature) {
 358      switch($feature) {
 359          case FEATURE_GROUPS:                  return true;
 360          case FEATURE_GROUPINGS:               return true;
 361          case FEATURE_MOD_INTRO:               return true;
 362          case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
 363          case FEATURE_COMPLETION_HAS_RULES:    return true;
 364          case FEATURE_GRADE_HAS_GRADE:         return true;
 365          case FEATURE_GRADE_OUTCOMES:          return true;
 366          case FEATURE_RATE:                    return true;
 367          case FEATURE_BACKUP_MOODLE2:          return true;
 368          case FEATURE_SHOW_DESCRIPTION:        return true;
 369          case FEATURE_PLAGIARISM:              return true;
 370          case FEATURE_ADVANCED_GRADING:        return true;
 371  
 372          default: return null;
 373      }
 374  }
 375  
 376  /**
 377   * Create a message-id string to use in the custom headers of forum notification emails
 378   *
 379   * message-id is used by email clients to identify emails and to nest conversations
 380   *
 381   * @param int $postid The ID of the forum post we are notifying the user about
 382   * @param int $usertoid The ID of the user being notified
 383   * @return string A unique message-id
 384   */
 385  function forum_get_email_message_id($postid, $usertoid) {
 386      return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
 387  }
 388  
 389  /**
 390   *
 391   * @param object $course
 392   * @param object $user
 393   * @param object $mod TODO this is not used in this function, refactor
 394   * @param object $forum
 395   * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
 396   */
 397  function forum_user_outline($course, $user, $mod, $forum) {
 398      global $CFG;
 399      require_once("$CFG->libdir/gradelib.php");
 400  
 401      $gradeinfo = '';
 402      $gradetime = 0;
 403  
 404      $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
 405      if (!empty($grades->items[0]->grades)) {
 406          // Item 0 is the rating.
 407          $grade = reset($grades->items[0]->grades);
 408          $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
 409          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 410              $gradeinfo .= get_string('gradeforrating', 'forum', $grade) .  html_writer::empty_tag('br');
 411          } else {
 412              $gradeinfo .= get_string('gradeforratinghidden', 'forum') . html_writer::empty_tag('br');
 413          }
 414      }
 415  
 416      // Item 1 is the whole-forum grade.
 417      if (!empty($grades->items[1]->grades)) {
 418          $grade = reset($grades->items[1]->grades);
 419          $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
 420          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 421              $gradeinfo .= get_string('gradeforwholeforum', 'forum', $grade) .  html_writer::empty_tag('br');
 422          } else {
 423              $gradeinfo .= get_string('gradeforwholeforumhidden', 'forum') . html_writer::empty_tag('br');
 424          }
 425      }
 426  
 427      $count = forum_count_user_posts($forum->id, $user->id);
 428      if ($count && $count->postcount > 0) {
 429          $info = get_string("numposts", "forum", $count->postcount);
 430          $time = $count->lastpost;
 431  
 432          if ($gradeinfo) {
 433              $info .= ', ' . $gradeinfo;
 434              $time = max($time, $gradetime);
 435          }
 436  
 437          return (object) [
 438              'info' => $info,
 439              'time' => $time,
 440          ];
 441      } else if ($gradeinfo) {
 442          return (object) [
 443              'info' => $gradeinfo,
 444              'time' => $gradetime,
 445          ];
 446      }
 447  
 448      return null;
 449  }
 450  
 451  
 452  /**
 453   * @global object
 454   * @global object
 455   * @param object $coure
 456   * @param object $user
 457   * @param object $mod
 458   * @param object $forum
 459   */
 460  function forum_user_complete($course, $user, $mod, $forum) {
 461      global $CFG, $USER;
 462      require_once("$CFG->libdir/gradelib.php");
 463  
 464      $getgradeinfo = function($grades, string $type) use ($course): string {
 465          global $OUTPUT;
 466  
 467          if (empty($grades)) {
 468              return '';
 469          }
 470  
 471          $result = '';
 472          $grade = reset($grades);
 473          if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
 474              $result .= $OUTPUT->container(get_string("gradefor{$type}", "forum", $grade));
 475              if ($grade->str_feedback) {
 476                  $result .= $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
 477              }
 478          } else {
 479              $result .= $OUTPUT->container(get_string("gradefor{$type}hidden", "forum"));
 480          }
 481  
 482          return $result;
 483      };
 484  
 485      $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
 486  
 487      // Item 0 is the rating.
 488      if (!empty($grades->items[0]->grades)) {
 489          echo $getgradeinfo($grades->items[0]->grades, 'rating');
 490      }
 491  
 492      // Item 1 is the whole-forum grade.
 493      if (!empty($grades->items[1]->grades)) {
 494          echo $getgradeinfo($grades->items[1]->grades, 'wholeforum');
 495      }
 496  
 497      if ($posts = forum_get_user_posts($forum->id, $user->id)) {
 498          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
 499              print_error('invalidcoursemodule');
 500          }
 501          $context = context_module::instance($cm->id);
 502          $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
 503          $posts = array_filter($posts, function($post) use ($discussions) {
 504              return isset($discussions[$post->discussion]);
 505          });
 506          $entityfactory = mod_forum\local\container::get_entity_factory();
 507          $rendererfactory = mod_forum\local\container::get_renderer_factory();
 508          $postrenderer = $rendererfactory->get_posts_renderer();
 509  
 510          echo $postrenderer->render(
 511              $USER,
 512              [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
 513              array_map(function($discussion) use ($entityfactory) {
 514                  return $entityfactory->get_discussion_from_stdclass($discussion);
 515              }, $discussions),
 516              array_map(function($post) use ($entityfactory) {
 517                  return $entityfactory->get_post_from_stdclass($post);
 518              }, $posts)
 519          );
 520      } else {
 521          echo "<p>".get_string("noposts", "forum")."</p>";
 522      }
 523  }
 524  
 525  /**
 526   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
 527   */
 528  function forum_filter_user_groups_discussions() {
 529      throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.');
 530  }
 531  
 532  /**
 533   * Returns whether the discussion group is visible by the current user or not.
 534   *
 535   * @since Moodle 2.8, 2.7.1, 2.6.4
 536   * @param cm_info $cm The discussion course module
 537   * @param int $discussiongroupid The discussion groupid
 538   * @return bool
 539   */
 540  function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
 541  
 542      if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
 543          return true;
 544      }
 545  
 546      if (isguestuser()) {
 547          return false;
 548      }
 549  
 550      if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
 551              in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
 552          return true;
 553      }
 554  
 555      return false;
 556  }
 557  
 558  /**
 559   * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
 560   */
 561  function forum_print_overview() {
 562      throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.');
 563  }
 564  
 565  /**
 566   * Given a course and a date, prints a summary of all the new
 567   * messages posted in the course since that date
 568   *
 569   * @global object
 570   * @global object
 571   * @global object
 572   * @uses CONTEXT_MODULE
 573   * @uses VISIBLEGROUPS
 574   * @param object $course
 575   * @param bool $viewfullnames capability
 576   * @param int $timestart
 577   * @return bool success
 578   */
 579  function forum_print_recent_activity($course, $viewfullnames, $timestart) {
 580      global $USER, $DB, $OUTPUT;
 581  
 582      // do not use log table if possible, it may be huge and is expensive to join with other tables
 583  
 584      $userfieldsapi = \core_user\fields::for_userpic();
 585      $allnamefields = $userfieldsapi->get_sql('u', false, '', 'duserid', false)->selects;
 586      if (!$posts = $DB->get_records_sql("SELECT p.*,
 587                                                f.course, f.type AS forumtype, f.name AS forumname, f.intro, f.introformat, f.duedate,
 588                                                f.cutoffdate, f.assessed AS forumassessed, f.assesstimestart, f.assesstimefinish,
 589                                                f.scale, f.grade_forum, f.maxbytes, f.maxattachments, f.forcesubscribe,
 590                                                f.trackingtype, f.rsstype, f.rssarticles, f.timemodified, f.warnafter, f.blockafter,
 591                                                f.blockperiod, f.completiondiscussions, f.completionreplies, f.completionposts,
 592                                                f.displaywordcount, f.lockdiscussionafter, f.grade_forum_notify,
 593                                                d.name AS discussionname, d.firstpost, d.userid AS discussionstarter,
 594                                                d.assessed AS discussionassessed, d.timemodified, d.usermodified, d.forum, d.groupid,
 595                                                d.timestart, d.timeend, d.pinned, d.timelocked,
 596                                                $allnamefields
 597                                           FROM {forum_posts} p
 598                                                JOIN {forum_discussions} d ON d.id = p.discussion
 599                                                JOIN {forum} f             ON f.id = d.forum
 600                                                JOIN {user} u              ON u.id = p.userid
 601                                          WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
 602                                       ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
 603           return false;
 604      }
 605  
 606      $modinfo = get_fast_modinfo($course);
 607  
 608      $strftimerecent = get_string('strftimerecent');
 609  
 610      $managerfactory = mod_forum\local\container::get_manager_factory();
 611      $entityfactory = mod_forum\local\container::get_entity_factory();
 612  
 613      $discussions = [];
 614      $capmanagers = [];
 615      $printposts = [];
 616      foreach ($posts as $post) {
 617          if (!isset($modinfo->instances['forum'][$post->forum])) {
 618              // not visible
 619              continue;
 620          }
 621          $cm = $modinfo->instances['forum'][$post->forum];
 622          if (!$cm->uservisible) {
 623              continue;
 624          }
 625  
 626          // Get the discussion. Cache if not yet available.
 627          if (!isset($discussions[$post->discussion])) {
 628              // Build the discussion record object from the post data.
 629              $discussionrecord = (object)[
 630                  'id' => $post->discussion,
 631                  'course' => $post->course,
 632                  'forum' => $post->forum,
 633                  'name' => $post->discussionname,
 634                  'firstpost' => $post->firstpost,
 635                  'userid' => $post->discussionstarter,
 636                  'groupid' => $post->groupid,
 637                  'assessed' => $post->discussionassessed,
 638                  'timemodified' => $post->timemodified,
 639                  'usermodified' => $post->usermodified,
 640                  'timestart' => $post->timestart,
 641                  'timeend' => $post->timeend,
 642                  'pinned' => $post->pinned,
 643                  'timelocked' => $post->timelocked
 644              ];
 645              // Build the discussion entity from the factory and cache it.
 646              $discussions[$post->discussion] = $entityfactory->get_discussion_from_stdclass($discussionrecord);
 647          }
 648          $discussionentity = $discussions[$post->discussion];
 649  
 650          // Get the capability manager. Cache if not yet available.
 651          if (!isset($capmanagers[$post->forum])) {
 652              $context = context_module::instance($cm->id);
 653              $coursemodule = $cm->get_course_module_record();
 654              // Build the forum record object from the post data.
 655              $forumrecord = (object)[
 656                  'id' => $post->forum,
 657                  'course' => $post->course,
 658                  'type' => $post->forumtype,
 659                  'name' => $post->forumname,
 660                  'intro' => $post->intro,
 661                  'introformat' => $post->introformat,
 662                  'duedate' => $post->duedate,
 663                  'cutoffdate' => $post->cutoffdate,
 664                  'assessed' => $post->forumassessed,
 665                  'assesstimestart' => $post->assesstimestart,
 666                  'assesstimefinish' => $post->assesstimefinish,
 667                  'scale' => $post->scale,
 668                  'grade_forum' => $post->grade_forum,
 669                  'maxbytes' => $post->maxbytes,
 670                  'maxattachments' => $post->maxattachments,
 671                  'forcesubscribe' => $post->forcesubscribe,
 672                  'trackingtype' => $post->trackingtype,
 673                  'rsstype' => $post->rsstype,
 674                  'rssarticles' => $post->rssarticles,
 675                  'timemodified' => $post->timemodified,
 676                  'warnafter' => $post->warnafter,
 677                  'blockafter' => $post->blockafter,
 678                  'blockperiod' => $post->blockperiod,
 679                  'completiondiscussions' => $post->completiondiscussions,
 680                  'completionreplies' => $post->completionreplies,
 681                  'completionposts' => $post->completionposts,
 682                  'displaywordcount' => $post->displaywordcount,
 683                  'lockdiscussionafter' => $post->lockdiscussionafter,
 684                  'grade_forum_notify' => $post->grade_forum_notify
 685              ];
 686              // Build the forum entity from the factory.
 687              $forumentity = $entityfactory->get_forum_from_stdclass($forumrecord, $context, $coursemodule, $course);
 688              // Get the capability manager of this forum and cache it.
 689              $capmanagers[$post->forum] = $managerfactory->get_capability_manager($forumentity);
 690          }
 691          $capabilitymanager = $capmanagers[$post->forum];
 692  
 693          // Get the post entity.
 694          $postentity = $entityfactory->get_post_from_stdclass($post);
 695  
 696          // Check if the user can view the post.
 697          if ($capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) {
 698              $printposts[] = $post;
 699          }
 700      }
 701      unset($posts);
 702  
 703      if (!$printposts) {
 704          return false;
 705      }
 706  
 707      echo $OUTPUT->heading(get_string('newforumposts', 'forum') . ':', 6);
 708      $list = html_writer::start_tag('ul', ['class' => 'unlist']);
 709  
 710      foreach ($printposts as $post) {
 711          $subjectclass = empty($post->parent) ? ' bold' : '';
 712          $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
 713  
 714          $list .= html_writer::start_tag('li');
 715          $list .= html_writer::start_div('head');
 716          $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date');
 717          if (!$authorhidden) {
 718              $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
 719          }
 720          $list .= html_writer::end_div(); // Head.
 721  
 722          $list .= html_writer::start_div('info' . $subjectclass);
 723          $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
 724          if (!empty($post->parent)) {
 725              $discussionurl->param('parent', $post->parent);
 726              $discussionurl->set_anchor('p'. $post->id);
 727          }
 728          $post->subject = break_up_long_words(format_string($post->subject, true));
 729          $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']);
 730          $list .= html_writer::end_div(); // Info.
 731          $list .= html_writer::end_tag('li');
 732      }
 733  
 734      $list .= html_writer::end_tag('ul');
 735      echo $list;
 736  
 737      return true;
 738  }
 739  
 740  /**
 741   * Update activity grades.
 742   *
 743   * @param object $forum
 744   * @param int $userid specific user only, 0 means all
 745   */
 746  function forum_update_grades($forum, $userid = 0): void {
 747      global $CFG, $DB;
 748      require_once($CFG->libdir.'/gradelib.php');
 749  
 750      $ratings = null;
 751      if ($forum->assessed) {
 752          require_once($CFG->dirroot.'/rating/lib.php');
 753  
 754          $cm = get_coursemodule_from_instance('forum', $forum->id);
 755  
 756          $rm = new rating_manager();
 757          $ratings = $rm->get_user_grades((object) [
 758              'component' => 'mod_forum',
 759              'ratingarea' => 'post',
 760              'contextid' => \context_module::instance($cm->id)->id,
 761  
 762              'modulename' => 'forum',
 763              'moduleid  ' => $forum->id,
 764              'userid' => $userid,
 765              'aggregationmethod' => $forum->assessed,
 766              'scaleid' => $forum->scale,
 767              'itemtable' => 'forum_posts',
 768              'itemtableusercolumn' => 'userid',
 769          ]);
 770      }
 771  
 772      $forumgrades = null;
 773      if ($forum->grade_forum) {
 774          $sql = <<<EOF
 775  SELECT
 776      g.userid,
 777      0 as datesubmitted,
 778      g.grade as rawgrade,
 779      g.timemodified as dategraded
 780    FROM {forum} f
 781    JOIN {forum_grades} g ON g.forum = f.id
 782   WHERE f.id = :forumid
 783  EOF;
 784  
 785          $params = [
 786              'forumid' => $forum->id,
 787          ];
 788  
 789          if ($userid) {
 790              $sql .= " AND g.userid = :userid";
 791              $params['userid'] = $userid;
 792          }
 793  
 794          $forumgrades = [];
 795          if ($grades = $DB->get_recordset_sql($sql, $params)) {
 796              foreach ($grades as $userid => $grade) {
 797                  if ($grade->rawgrade != -1) {
 798                      $forumgrades[$userid] = $grade;
 799                  }
 800              }
 801              $grades->close();
 802          }
 803      }
 804  
 805      forum_grade_item_update($forum, $ratings, $forumgrades);
 806  }
 807  
 808  /**
 809   * Create/update grade items for given forum.
 810   *
 811   * @param stdClass $forum Forum object with extra cmidnumber
 812   * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
 813   */
 814  function forum_grade_item_update($forum, $ratings = null, $forumgrades = null): void {
 815      global $CFG;
 816      require_once("{$CFG->libdir}/gradelib.php");
 817  
 818      // Update the rating.
 819      $item = [
 820          'itemname' => get_string('gradeitemnameforrating', 'forum', $forum),
 821          'idnumber' => $forum->cmidnumber,
 822      ];
 823  
 824      if (!$forum->assessed || $forum->scale == 0) {
 825          $item['gradetype'] = GRADE_TYPE_NONE;
 826      } else if ($forum->scale > 0) {
 827          $item['gradetype'] = GRADE_TYPE_VALUE;
 828          $item['grademax']  = $forum->scale;
 829          $item['grademin']  = 0;
 830      } else if ($forum->scale < 0) {
 831          $item['gradetype'] = GRADE_TYPE_SCALE;
 832          $item['scaleid']   = -$forum->scale;
 833      }
 834  
 835      if ($ratings === 'reset') {
 836          $item['reset'] = true;
 837          $ratings = null;
 838      }
 839      // Itemnumber 0 is the rating.
 840      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $ratings, $item);
 841  
 842      // Whole forum grade.
 843      $item = [
 844          'itemname' => get_string('gradeitemnameforwholeforum', 'forum', $forum),
 845          // Note: We do not need to store the idnumber here.
 846      ];
 847  
 848      if (!$forum->grade_forum) {
 849          $item['gradetype'] = GRADE_TYPE_NONE;
 850      } else if ($forum->grade_forum > 0) {
 851          $item['gradetype'] = GRADE_TYPE_VALUE;
 852          $item['grademax'] = $forum->grade_forum;
 853          $item['grademin'] = 0;
 854      } else if ($forum->grade_forum < 0) {
 855          $item['gradetype'] = GRADE_TYPE_SCALE;
 856          $item['scaleid'] = $forum->grade_forum * -1;
 857      }
 858  
 859      if ($forumgrades === 'reset') {
 860          $item['reset'] = true;
 861          $forumgrades = null;
 862      }
 863      // Itemnumber 1 is the whole forum grade.
 864      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, $forumgrades, $item);
 865  }
 866  
 867  /**
 868   * Delete grade item for given forum.
 869   *
 870   * @param stdClass $forum Forum object
 871   */
 872  function forum_grade_item_delete($forum) {
 873      global $CFG;
 874      require_once($CFG->libdir.'/gradelib.php');
 875  
 876      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, null, ['deleted' => 1]);
 877      grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, null, ['deleted' => 1]);
 878  }
 879  
 880  /**
 881   * Checks if scale is being used by any instance of forum.
 882   *
 883   * This is used to find out if scale used anywhere.
 884   *
 885   * @param $scaleid int
 886   * @return boolean True if the scale is used by any forum
 887   */
 888  function forum_scale_used_anywhere(int $scaleid): bool {
 889      global $DB;
 890  
 891      if (empty($scaleid)) {
 892          return false;
 893      }
 894  
 895      return $DB->record_exists_select('forum', "scale = ? and assessed > 0", [$scaleid * -1]);
 896  }
 897  
 898  // SQL FUNCTIONS ///////////////////////////////////////////////////////////
 899  
 900  /**
 901   * Gets a post with all info ready for forum_print_post
 902   * Most of these joins are just to get the forum id
 903   *
 904   * @global object
 905   * @global object
 906   * @param int $postid
 907   * @return mixed array of posts or false
 908   */
 909  function forum_get_post_full($postid) {
 910      global $CFG, $DB;
 911  
 912      $userfieldsapi = \core_user\fields::for_name();
 913      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 914      return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
 915                               FROM {forum_posts} p
 916                                    JOIN {forum_discussions} d ON p.discussion = d.id
 917                                    LEFT JOIN {user} u ON p.userid = u.id
 918                              WHERE p.id = ?", array($postid));
 919  }
 920  
 921  /**
 922   * Gets all posts in discussion including top parent.
 923   *
 924   * @param   int     $discussionid   The Discussion to fetch.
 925   * @param   string  $sort           The sorting to apply.
 926   * @param   bool    $tracking       Whether the user tracks this forum.
 927   * @return  array                   The posts in the discussion.
 928   */
 929  function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) {
 930      global $CFG, $DB, $USER;
 931  
 932      $tr_sel  = "";
 933      $tr_join = "";
 934      $params = array();
 935  
 936      if ($tracking) {
 937          $tr_sel  = ", fr.id AS postread";
 938          $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
 939          $params[] = $USER->id;
 940      }
 941  
 942      $userfieldsapi = \core_user\fields::for_name();
 943      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 944      $params[] = $discussionid;
 945      if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
 946                                       FROM {forum_posts} p
 947                                            LEFT JOIN {user} u ON p.userid = u.id
 948                                            $tr_join
 949                                      WHERE p.discussion = ?
 950                                   ORDER BY $sort", $params)) {
 951          return array();
 952      }
 953  
 954      foreach ($posts as $pid=>$p) {
 955          if ($tracking) {
 956              if (forum_tp_is_post_old($p)) {
 957                   $posts[$pid]->postread = true;
 958              }
 959          }
 960          if (!$p->parent) {
 961              continue;
 962          }
 963          if (!isset($posts[$p->parent])) {
 964              continue; // parent does not exist??
 965          }
 966          if (!isset($posts[$p->parent]->children)) {
 967              $posts[$p->parent]->children = array();
 968          }
 969          $posts[$p->parent]->children[$pid] =& $posts[$pid];
 970      }
 971  
 972      // Start with the last child of the first post.
 973      $post = &$posts[reset($posts)->id];
 974  
 975      $lastpost = false;
 976      while (!$lastpost) {
 977          if (!isset($post->children)) {
 978              $post->lastpost = true;
 979              $lastpost = true;
 980          } else {
 981               // Go to the last child of this post.
 982              $post = &$posts[end($post->children)->id];
 983          }
 984      }
 985  
 986      return $posts;
 987  }
 988  
 989  /**
 990   * An array of forum objects that the user is allowed to read/search through.
 991   *
 992   * @global object
 993   * @global object
 994   * @global object
 995   * @param int $userid
 996   * @param int $courseid if 0, we look for forums throughout the whole site.
 997   * @return array of forum objects, or false if no matches
 998   *         Forum objects have the following attributes:
 999   *         id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1000   *         viewhiddentimedposts
1001   */
1002  function forum_get_readable_forums($userid, $courseid=0) {
1003  
1004      global $CFG, $DB, $USER;
1005      require_once($CFG->dirroot.'/course/lib.php');
1006  
1007      if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1008          print_error('notinstalled', 'forum');
1009      }
1010  
1011      if ($courseid) {
1012          $courses = $DB->get_records('course', array('id' => $courseid));
1013      } else {
1014          // If no course is specified, then the user can see SITE + his courses.
1015          $courses1 = $DB->get_records('course', array('id' => SITEID));
1016          $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1017          $courses = array_merge($courses1, $courses2);
1018      }
1019      if (!$courses) {
1020          return array();
1021      }
1022  
1023      $readableforums = array();
1024  
1025      foreach ($courses as $course) {
1026  
1027          $modinfo = get_fast_modinfo($course);
1028  
1029          if (empty($modinfo->instances['forum'])) {
1030              // hmm, no forums?
1031              continue;
1032          }
1033  
1034          $courseforums = $DB->get_records('forum', array('course' => $course->id));
1035  
1036          foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1037              if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1038                  continue;
1039              }
1040              $context = context_module::instance($cm->id);
1041              $forum = $courseforums[$forumid];
1042              $forum->context = $context;
1043              $forum->cm = $cm;
1044  
1045              if (!has_capability('mod/forum:viewdiscussion', $context)) {
1046                  continue;
1047              }
1048  
1049           /// group access
1050              if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1051  
1052                  $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1053                  $forum->onlygroups[] = -1;
1054              }
1055  
1056          /// hidden timed discussions
1057              $forum->viewhiddentimedposts = true;
1058              if (!empty($CFG->forum_enabletimedposts)) {
1059                  if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1060                      $forum->viewhiddentimedposts = false;
1061                  }
1062              }
1063  
1064          /// qanda access
1065              if ($forum->type == 'qanda'
1066                      && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1067  
1068                  // We need to check whether the user has posted in the qanda forum.
1069                  $forum->onlydiscussions = array();  // Holds discussion ids for the discussions
1070                                                      // the user is allowed to see in this forum.
1071                  if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1072                      foreach ($discussionspostedin as $d) {
1073                          $forum->onlydiscussions[] = $d->id;
1074                      }
1075                  }
1076              }
1077  
1078              $readableforums[$forum->id] = $forum;
1079          }
1080  
1081          unset($modinfo);
1082  
1083      } // End foreach $courses
1084  
1085      return $readableforums;
1086  }
1087  
1088  /**
1089   * Returns a list of posts found using an array of search terms.
1090   *
1091   * @global object
1092   * @global object
1093   * @global object
1094   * @param array $searchterms array of search terms, e.g. word +word -word
1095   * @param int $courseid if 0, we search through the whole site
1096   * @param int $limitfrom
1097   * @param int $limitnum
1098   * @param int &$totalcount
1099   * @param string $extrasql
1100   * @return array|bool Array of posts found or false
1101   */
1102  function forum_search_posts($searchterms, $courseid, $limitfrom, $limitnum,
1103                              &$totalcount, $extrasql='') {
1104      global $CFG, $DB, $USER;
1105      require_once($CFG->libdir.'/searchlib.php');
1106  
1107      $forums = forum_get_readable_forums($USER->id, $courseid);
1108  
1109      if (count($forums) == 0) {
1110          $totalcount = 0;
1111          return false;
1112      }
1113  
1114      $now = floor(time() / 60) * 60; // DB Cache Friendly.
1115  
1116      $fullaccess = array();
1117      $where = array();
1118      $params = array();
1119  
1120      foreach ($forums as $forumid => $forum) {
1121          $select = array();
1122  
1123          if (!$forum->viewhiddentimedposts) {
1124              $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1125              $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1126          }
1127  
1128          $cm = $forum->cm;
1129          $context = $forum->context;
1130  
1131          if ($forum->type == 'qanda'
1132              && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1133              if (!empty($forum->onlydiscussions)) {
1134                  list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
1135                  $params = array_merge($params, $discussionid_params);
1136                  $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1137              } else {
1138                  $select[] = "p.parent = 0";
1139              }
1140          }
1141  
1142          if (!empty($forum->onlygroups)) {
1143              list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
1144              $params = array_merge($params, $groupid_params);
1145              $select[] = "d.groupid $groupid_sql";
1146          }
1147  
1148          if ($select) {
1149              $selects = implode(" AND ", $select);
1150              $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1151              $params['forum'.$forumid] = $forumid;
1152          } else {
1153              $fullaccess[] = $forumid;
1154          }
1155      }
1156  
1157      if ($fullaccess) {
1158          list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
1159          $params = array_merge($params, $fullid_params);
1160          $where[] = "(d.forum $fullid_sql)";
1161      }
1162  
1163      $favjoin = "";
1164      if (in_array('starredonly:on', $searchterms)) {
1165          $usercontext = context_user::instance($USER->id);
1166          $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1167          list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions',
1168              "favourited", "d.id");
1169  
1170          $searchterms = array_values(array_diff($searchterms, array('starredonly:on')));
1171          $params = array_merge($params, $favparams);
1172          $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0";
1173      }
1174  
1175      $selectdiscussion = "(".implode(" OR ", $where).")";
1176  
1177      $messagesearch = '';
1178      $searchstring = '';
1179  
1180      // Need to concat these back together for parser to work.
1181      foreach($searchterms as $searchterm){
1182          if ($searchstring != '') {
1183              $searchstring .= ' ';
1184          }
1185          $searchstring .= $searchterm;
1186      }
1187  
1188      // We need to allow quoted strings for the search. The quotes *should* be stripped
1189      // by the parser, but this should be examined carefully for security implications.
1190      $searchstring = str_replace("\\\"","\"",$searchstring);
1191      $parser = new search_parser();
1192      $lexer = new search_lexer($parser);
1193  
1194      if ($lexer->parse($searchstring)) {
1195          $parsearray = $parser->get_parsed_array();
1196  
1197          $tagjoins = '';
1198          $tagfields = [];
1199          $tagfieldcount = 0;
1200          if ($parsearray) {
1201              foreach ($parsearray as $token) {
1202                  if ($token->getType() == TOKEN_TAGS) {
1203                      for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
1204                          // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1205                          if ($tagfieldcount > 10) {
1206                              continue;
1207                          }
1208                          $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
1209                                          ON p.id = ti_$tagfieldcount.itemid
1210                                              AND ti_$tagfieldcount.component = 'mod_forum'
1211                                              AND ti_$tagfieldcount.itemtype = 'forum_posts'";
1212                          $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1213                          $tagfields[] = "t_$tagfieldcount.rawname";
1214                          $tagfieldcount++;
1215                      }
1216                  }
1217              }
1218              list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1219                  'p.userid', 'u.id', 'u.firstname',
1220                  'u.lastname', 'p.modified', 'd.forum',
1221                  $tagfields);
1222  
1223              $params = ($msparams ? array_merge($params, $msparams) : $params);
1224          }
1225      }
1226  
1227      $fromsql = "{forum_posts} p
1228                    INNER JOIN {forum_discussions} d ON d.id = p.discussion
1229                    INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin";
1230  
1231      $selectsql = ($messagesearch ? $messagesearch . " AND " : "").
1232                  " p.discussion = d.id
1233                 AND p.userid = u.id
1234                 AND $selectdiscussion
1235                     $extrasql";
1236  
1237      $countsql = "SELECT COUNT(*)
1238                     FROM $fromsql
1239                    WHERE $selectsql";
1240  
1241      $userfieldsapi = \core_user\fields::for_name();
1242      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1243      $searchsql = "SELECT p.*,
1244                           d.forum,
1245                           $allnames,
1246                           u.email,
1247                           u.picture,
1248                           u.imagealt
1249                      FROM $fromsql
1250                     WHERE $selectsql
1251                  ORDER BY p.modified DESC";
1252  
1253      $totalcount = $DB->count_records_sql($countsql, $params);
1254  
1255      return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
1256  }
1257  
1258  /**
1259   * Get all the posts for a user in a forum suitable for forum_print_post
1260   *
1261   * @global object
1262   * @global object
1263   * @uses CONTEXT_MODULE
1264   * @return array
1265   */
1266  function forum_get_user_posts($forumid, $userid) {
1267      global $CFG, $DB;
1268  
1269      $timedsql = "";
1270      $params = array($forumid, $userid);
1271  
1272      if (!empty($CFG->forum_enabletimedposts)) {
1273          $cm = get_coursemodule_from_instance('forum', $forumid);
1274          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1275              $now = time();
1276              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1277              $params[] = $now;
1278              $params[] = $now;
1279          }
1280      }
1281  
1282      $userfieldsapi = \core_user\fields::for_name();
1283      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1284      return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1285                                FROM {forum} f
1286                                     JOIN {forum_discussions} d ON d.forum = f.id
1287                                     JOIN {forum_posts} p       ON p.discussion = d.id
1288                                     JOIN {user} u              ON u.id = p.userid
1289                               WHERE f.id = ?
1290                                     AND p.userid = ?
1291                                     $timedsql
1292                            ORDER BY p.modified ASC", $params);
1293  }
1294  
1295  /**
1296   * Get all the discussions user participated in
1297   *
1298   * @global object
1299   * @global object
1300   * @uses CONTEXT_MODULE
1301   * @param int $forumid
1302   * @param int $userid
1303   * @return array Array or false
1304   */
1305  function forum_get_user_involved_discussions($forumid, $userid) {
1306      global $CFG, $DB;
1307  
1308      $timedsql = "";
1309      $params = array($forumid, $userid);
1310      if (!empty($CFG->forum_enabletimedposts)) {
1311          $cm = get_coursemodule_from_instance('forum', $forumid);
1312          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1313              $now = time();
1314              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1315              $params[] = $now;
1316              $params[] = $now;
1317          }
1318      }
1319  
1320      return $DB->get_records_sql("SELECT DISTINCT d.*
1321                                FROM {forum} f
1322                                     JOIN {forum_discussions} d ON d.forum = f.id
1323                                     JOIN {forum_posts} p       ON p.discussion = d.id
1324                               WHERE f.id = ?
1325                                     AND p.userid = ?
1326                                     $timedsql", $params);
1327  }
1328  
1329  /**
1330   * Get all the posts for a user in a forum suitable for forum_print_post
1331   *
1332   * @global object
1333   * @global object
1334   * @param int $forumid
1335   * @param int $userid
1336   * @return array of counts or false
1337   */
1338  function forum_count_user_posts($forumid, $userid) {
1339      global $CFG, $DB;
1340  
1341      $timedsql = "";
1342      $params = array($forumid, $userid);
1343      if (!empty($CFG->forum_enabletimedposts)) {
1344          $cm = get_coursemodule_from_instance('forum', $forumid);
1345          if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1346              $now = time();
1347              $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1348              $params[] = $now;
1349              $params[] = $now;
1350          }
1351      }
1352  
1353      return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1354                               FROM {forum} f
1355                                    JOIN {forum_discussions} d ON d.forum = f.id
1356                                    JOIN {forum_posts} p       ON p.discussion = d.id
1357                                    JOIN {user} u              ON u.id = p.userid
1358                              WHERE f.id = ?
1359                                    AND p.userid = ?
1360                                    $timedsql", $params);
1361  }
1362  
1363  /**
1364   * Given a log entry, return the forum post details for it.
1365   *
1366   * @global object
1367   * @global object
1368   * @param object $log
1369   * @return array|null
1370   */
1371  function forum_get_post_from_log($log) {
1372      global $CFG, $DB;
1373  
1374      $userfieldsapi = \core_user\fields::for_name();
1375      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1376      if ($log->action == "add post") {
1377  
1378          return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1379                                   FROM {forum_discussions} d,
1380                                        {forum_posts} p,
1381                                        {forum} f,
1382                                        {user} u
1383                                  WHERE p.id = ?
1384                                    AND d.id = p.discussion
1385                                    AND p.userid = u.id
1386                                    AND u.deleted <> '1'
1387                                    AND f.id = d.forum", array($log->info));
1388  
1389  
1390      } else if ($log->action == "add discussion") {
1391  
1392          return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1393                                   FROM {forum_discussions} d,
1394                                        {forum_posts} p,
1395                                        {forum} f,
1396                                        {user} u
1397                                  WHERE d.id = ?
1398                                    AND d.firstpost = p.id
1399                                    AND p.userid = u.id
1400                                    AND u.deleted <> '1'
1401                                    AND f.id = d.forum", array($log->info));
1402      }
1403      return NULL;
1404  }
1405  
1406  /**
1407   * Given a discussion id, return the first post from the discussion
1408   *
1409   * @global object
1410   * @global object
1411   * @param int $dicsussionid
1412   * @return array
1413   */
1414  function forum_get_firstpost_from_discussion($discussionid) {
1415      global $CFG, $DB;
1416  
1417      return $DB->get_record_sql("SELECT p.*
1418                               FROM {forum_discussions} d,
1419                                    {forum_posts} p
1420                              WHERE d.id = ?
1421                                AND d.firstpost = p.id ", array($discussionid));
1422  }
1423  
1424  /**
1425   * Returns an array of counts of replies to each discussion
1426   *
1427   * @param   int     $forumid
1428   * @param   string  $forumsort
1429   * @param   int     $limit
1430   * @param   int     $page
1431   * @param   int     $perpage
1432   * @param   boolean $canseeprivatereplies   Whether the current user can see private replies.
1433   * @return  array
1434   */
1435  function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0,
1436                                          $canseeprivatereplies = false) {
1437      global $CFG, $DB, $USER;
1438  
1439      if ($limit > 0) {
1440          $limitfrom = 0;
1441          $limitnum  = $limit;
1442      } else if ($page != -1) {
1443          $limitfrom = $page*$perpage;
1444          $limitnum  = $perpage;
1445      } else {
1446          $limitfrom = 0;
1447          $limitnum  = 0;
1448      }
1449  
1450      if ($forumsort == "") {
1451          $orderby = "";
1452          $groupby = "";
1453  
1454      } else {
1455          $orderby = "ORDER BY $forumsort";
1456          $groupby = ", ".strtolower($forumsort);
1457          $groupby = str_replace('desc', '', $groupby);
1458          $groupby = str_replace('asc', '', $groupby);
1459      }
1460  
1461      $params = ['forumid' => $forumid];
1462  
1463      if (!$canseeprivatereplies) {
1464          $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)';
1465          $params['currentuser1'] = $USER->id;
1466          $params['currentuser2'] = $USER->id;
1467      } else {
1468          $privatewhere = '';
1469      }
1470  
1471      if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1472          $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
1473                    FROM {forum_posts} p
1474                         JOIN {forum_discussions} d ON p.discussion = d.id
1475                   WHERE p.parent > 0 AND d.forum = :forumid
1476                         $privatewhere
1477                GROUP BY p.discussion";
1478          return $DB->get_records_sql($sql, $params);
1479  
1480      } else {
1481          $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
1482                    FROM {forum_posts} p
1483                         JOIN {forum_discussions} d ON p.discussion = d.id
1484                   WHERE d.forum = :forumid
1485                         $privatewhere
1486                GROUP BY p.discussion $groupby $orderby";
1487          return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1488      }
1489  }
1490  
1491  /**
1492   * @global object
1493   * @global object
1494   * @global object
1495   * @staticvar array $cache
1496   * @param object $forum
1497   * @param object $cm
1498   * @param object $course
1499   * @return mixed
1500   */
1501  function forum_count_discussions($forum, $cm, $course) {
1502      global $CFG, $DB, $USER;
1503  
1504      static $cache = array();
1505  
1506      $now = floor(time() / 60) * 60; // DB Cache Friendly.
1507  
1508      $params = array($course->id);
1509  
1510      if (!isset($cache[$course->id])) {
1511          if (!empty($CFG->forum_enabletimedposts)) {
1512              $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1513              $params[] = $now;
1514              $params[] = $now;
1515          } else {
1516              $timedsql = "";
1517          }
1518  
1519          $sql = "SELECT f.id, COUNT(d.id) as dcount
1520                    FROM {forum} f
1521                         JOIN {forum_discussions} d ON d.forum = f.id
1522                   WHERE f.course = ?
1523                         $timedsql
1524                GROUP BY f.id";
1525  
1526          if ($counts = $DB->get_records_sql($sql, $params)) {
1527              foreach ($counts as $count) {
1528                  $counts[$count->id] = $count->dcount;
1529              }
1530              $cache[$course->id] = $counts;
1531          } else {
1532              $cache[$course->id] = array();
1533          }
1534      }
1535  
1536      if (empty($cache[$course->id][$forum->id])) {
1537          return 0;
1538      }
1539  
1540      $groupmode = groups_get_activity_groupmode($cm, $course);
1541  
1542      if ($groupmode != SEPARATEGROUPS) {
1543          return $cache[$course->id][$forum->id];
1544      }
1545  
1546      if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
1547          return $cache[$course->id][$forum->id];
1548      }
1549  
1550      require_once($CFG->dirroot.'/course/lib.php');
1551  
1552      $modinfo = get_fast_modinfo($course);
1553  
1554      $mygroups = $modinfo->get_groups($cm->groupingid);
1555  
1556      // add all groups posts
1557      $mygroups[-1] = -1;
1558  
1559      list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1560      $params[] = $forum->id;
1561  
1562      if (!empty($CFG->forum_enabletimedposts)) {
1563          $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
1564          $params[] = $now;
1565          $params[] = $now;
1566      } else {
1567          $timedsql = "";
1568      }
1569  
1570      $sql = "SELECT COUNT(d.id)
1571                FROM {forum_discussions} d
1572               WHERE d.groupid $mygroups_sql AND d.forum = ?
1573                     $timedsql";
1574  
1575      return $DB->get_field_sql($sql, $params);
1576  }
1577  
1578  /**
1579   * Get all discussions in a forum
1580   *
1581   * @global object
1582   * @global object
1583   * @global object
1584   * @uses CONTEXT_MODULE
1585   * @uses VISIBLEGROUPS
1586   * @param object $cm
1587   * @param string $forumsort
1588   * @param bool $fullpost
1589   * @param int $unused
1590   * @param int $limit
1591   * @param bool $userlastmodified
1592   * @param int $page
1593   * @param int $perpage
1594   * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1595   *                     Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
1596   * @param int $updatedsince retrieve only discussions updated since the given time
1597   * @return array
1598   */
1599  function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
1600                                  $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
1601                                  $updatedsince = 0) {
1602      global $CFG, $DB, $USER;
1603  
1604      $timelimit = '';
1605  
1606      $now = floor(time() / 60) * 60;
1607      $params = array($cm->instance);
1608  
1609      $modcontext = context_module::instance($cm->id);
1610  
1611      if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1612          return array();
1613      }
1614  
1615      if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
1616  
1617          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1618              $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1619              $params[] = $now;
1620              $params[] = $now;
1621              if (isloggedin()) {
1622                  $timelimit .= " OR d.userid = ?";
1623                  $params[] = $USER->id;
1624              }
1625              $timelimit .= ")";
1626          }
1627      }
1628  
1629      if ($limit > 0) {
1630          $limitfrom = 0;
1631          $limitnum  = $limit;
1632      } else if ($page != -1) {
1633          $limitfrom = $page*$perpage;
1634          $limitnum  = $perpage;
1635      } else {
1636          $limitfrom = 0;
1637          $limitnum  = 0;
1638      }
1639  
1640      $groupmode    = groups_get_activity_groupmode($cm);
1641  
1642      if ($groupmode) {
1643  
1644          if (empty($modcontext)) {
1645              $modcontext = context_module::instance($cm->id);
1646          }
1647  
1648          // Special case, we received a groupid to override currentgroup.
1649          if ($groupid > 0) {
1650              $course = get_course($cm->course);
1651              if (!groups_group_visible($groupid, $course, $cm)) {
1652                  // User doesn't belong to this group, return nothing.
1653                  return array();
1654              }
1655              $currentgroup = $groupid;
1656          } else if ($groupid === -1) {
1657              $currentgroup = groups_get_activity_group($cm);
1658          } else {
1659              // Get discussions for all groups current user can see.
1660              $currentgroup = null;
1661          }
1662  
1663          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1664              if ($currentgroup) {
1665                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1666                  $params[] = $currentgroup;
1667              } else {
1668                  $groupselect = "";
1669              }
1670  
1671          } else {
1672              // Separate groups.
1673  
1674              // Get discussions for all groups current user can see.
1675              if ($currentgroup === null) {
1676                  $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
1677                  if (empty($mygroups)) {
1678                       $groupselect = "AND d.groupid = -1";
1679                  } else {
1680                      list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1681                      $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1682                      $params = array_merge($params, $inparamsgroups);
1683                  }
1684              } else if ($currentgroup) {
1685                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1686                  $params[] = $currentgroup;
1687              } else {
1688                  $groupselect = "AND d.groupid = -1";
1689              }
1690          }
1691      } else {
1692          $groupselect = "";
1693      }
1694      if (empty($forumsort)) {
1695          $forumsort = forum_get_default_sort_order();
1696      }
1697      if (empty($fullpost)) {
1698          $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
1699      } else {
1700          $postdata = "p.*";
1701      }
1702  
1703      $userfieldsapi = \core_user\fields::for_name();
1704  
1705      if (empty($userlastmodified)) {  // We don't need to know this
1706          $umfields = "";
1707          $umtable  = "";
1708      } else {
1709          $umfields = $userfieldsapi->get_sql('um', false, 'um')->selects . ', um.email AS umemail, um.picture AS umpicture,
1710                          um.imagealt AS umimagealt';
1711          $umtable  = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
1712      }
1713  
1714      $updatedsincesql = '';
1715      if (!empty($updatedsince)) {
1716          $updatedsincesql = 'AND d.timemodified > ?';
1717          $params[] = $updatedsince;
1718      }
1719  
1720      $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
1721      " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked";
1722  
1723      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1724      $sql = "SELECT $postdata, $discussionfields,
1725                     $allnames, u.email, u.picture, u.imagealt, u.deleted AS userdeleted $umfields
1726                FROM {forum_discussions} d
1727                     JOIN {forum_posts} p ON p.discussion = d.id
1728                     JOIN {user} u ON p.userid = u.id
1729                     $umtable
1730               WHERE d.forum = ? AND p.parent = 0
1731                     $timelimit $groupselect $updatedsincesql
1732            ORDER BY $forumsort, d.id DESC";
1733  
1734      return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1735  }
1736  
1737  /**
1738   * Gets the neighbours (previous and next) of a discussion.
1739   *
1740   * The calculation is based on the timemodified when time modified or time created is identical
1741   * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
1742   *
1743   * For blog-style forums, the calculation is based on the original creation time of the
1744   * blog post.
1745   *
1746   * Please note that this does not check whether or not the discussion passed is accessible
1747   * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1748   * the returned neighbours are checked and are accessible to the current user.
1749   *
1750   * @param object $cm The CM record.
1751   * @param object $discussion The discussion record.
1752   * @param object $forum The forum instance record.
1753   * @return array That always contains the keys 'prev' and 'next'. When there is a result
1754   *               they contain the record with minimal information such as 'id' and 'name'.
1755   *               When the neighbour is not found the value is false.
1756   */
1757  function forum_get_discussion_neighbours($cm, $discussion, $forum) {
1758      global $CFG, $DB, $USER;
1759  
1760      if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
1761          throw new coding_exception('Discussion is not part of the same forum.');
1762      }
1763  
1764      $neighbours = array('prev' => false, 'next' => false);
1765      $now = floor(time() / 60) * 60;
1766      $params = array();
1767  
1768      $modcontext = context_module::instance($cm->id);
1769      $groupmode    = groups_get_activity_groupmode($cm);
1770      $currentgroup = groups_get_activity_group($cm);
1771  
1772      // Users must fulfill timed posts.
1773      $timelimit = '';
1774      if (!empty($CFG->forum_enabletimedposts)) {
1775          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1776              $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1777              $params['tltimestart'] = $now;
1778              $params['tltimeend'] = $now;
1779              if (isloggedin()) {
1780                  $timelimit .= ' OR d.userid = :tluserid';
1781                  $params['tluserid'] = $USER->id;
1782              }
1783              $timelimit .= ')';
1784          }
1785      }
1786  
1787      // Limiting to posts accessible according to groups.
1788      $groupselect = '';
1789      if ($groupmode) {
1790          if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
1791              if ($currentgroup) {
1792                  $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1793                  $params['groupid'] = $currentgroup;
1794              }
1795          } else {
1796              if ($currentgroup) {
1797                  $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1798                  $params['groupid'] = $currentgroup;
1799              } else {
1800                  $groupselect = 'AND d.groupid = -1';
1801              }
1802          }
1803      }
1804  
1805      $params['forumid'] = $cm->instance;
1806      $params['discid1'] = $discussion->id;
1807      $params['discid2'] = $discussion->id;
1808      $params['discid3'] = $discussion->id;
1809      $params['discid4'] = $discussion->id;
1810      $params['disctimecompare1'] = $discussion->timemodified;
1811      $params['disctimecompare2'] = $discussion->timemodified;
1812      $params['pinnedstate1'] = (int) $discussion->pinned;
1813      $params['pinnedstate2'] = (int) $discussion->pinned;
1814      $params['pinnedstate3'] = (int) $discussion->pinned;
1815      $params['pinnedstate4'] = (int) $discussion->pinned;
1816  
1817      $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1818                FROM {forum_discussions} d
1819                JOIN {forum_posts} p ON d.firstpost = p.id
1820               WHERE d.forum = :forumid
1821                 AND d.id <> :discid1
1822                     $timelimit
1823                     $groupselect";
1824      $comparefield = "d.timemodified";
1825      $comparevalue = ":disctimecompare1";
1826      $comparevalue2  = ":disctimecompare2";
1827      if (!empty($CFG->forum_enabletimedposts)) {
1828          // Here we need to take into account the release time (timestart)
1829          // if one is set, of the neighbouring posts and compare it to the
1830          // timestart or timemodified of *this* post depending on if the
1831          // release date of this post is in the future or not.
1832          // This stops discussions that appear later because of the
1833          // timestart value from being buried under discussions that were
1834          // made afterwards.
1835          $comparefield = "CASE WHEN d.timemodified < d.timestart
1836                                  THEN d.timestart ELSE d.timemodified END";
1837          if ($discussion->timemodified < $discussion->timestart) {
1838              // Normally we would just use the timemodified for sorting
1839              // discussion posts. However, when timed discussions are enabled,
1840              // then posts need to be sorted base on the later of timemodified
1841              // or the release date of the post (timestart).
1842              $params['disctimecompare1'] = $discussion->timestart;
1843              $params['disctimecompare2'] = $discussion->timestart;
1844          }
1845      }
1846      $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1847      $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
1848  
1849      if ($forum->type === 'blog') {
1850           $subselect = "SELECT pp.created
1851                     FROM {forum_discussions} dd
1852                     JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
1853  
1854           $subselectwhere1 = " WHERE dd.id = :discid3";
1855           $subselectwhere2 = " WHERE dd.id = :discid4";
1856  
1857           $comparefield = "p.created";
1858  
1859           $sub1 = $subselect.$subselectwhere1;
1860           $comparevalue = "($sub1)";
1861  
1862           $sub2 = $subselect.$subselectwhere2;
1863           $comparevalue2 = "($sub2)";
1864  
1865           $orderbydesc = "d.pinned, p.created DESC";
1866           $orderbyasc = "d.pinned, p.created ASC";
1867      }
1868  
1869      $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1870                           OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1871                           OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1872                     ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
1873  
1874      $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1875                           OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1876                           OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1877                     ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
1878  
1879      $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
1880      $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
1881      return $neighbours;
1882  }
1883  
1884  /**
1885   * Get the sql to use in the ORDER BY clause for forum discussions.
1886   *
1887   * This has the ordering take timed discussion windows into account.
1888   *
1889   * @param bool $desc True for DESC, False for ASC.
1890   * @param string $compare The field in the SQL to compare to normally sort by.
1891   * @param string $prefix The prefix being used for the discussion table.
1892   * @param bool $pinned sort pinned posts to the top
1893   * @return string
1894   */
1895  function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1896      global $CFG;
1897  
1898      if (!empty($prefix)) {
1899          $prefix .= '.';
1900      }
1901  
1902      $dir = $desc ? 'DESC' : 'ASC';
1903  
1904      if ($pinned == true) {
1905          $pinned = "{$prefix}pinned DESC,";
1906      } else {
1907          $pinned = '';
1908      }
1909  
1910      $sort = "{$prefix}timemodified";
1911      if (!empty($CFG->forum_enabletimedposts)) {
1912          $sort = "CASE WHEN {$compare} < {$prefix}timestart
1913                   THEN {$prefix}timestart
1914                   ELSE {$compare}
1915                   END";
1916      }
1917      return "$pinned $sort $dir";
1918  }
1919  
1920  /**
1921   *
1922   * @global object
1923   * @global object
1924   * @global object
1925   * @uses CONTEXT_MODULE
1926   * @uses VISIBLEGROUPS
1927   * @param object $cm
1928   * @return array
1929   */
1930  function forum_get_discussions_unread($cm) {
1931      global $CFG, $DB, $USER;
1932  
1933      $now = floor(time() / 60) * 60;
1934      $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
1935  
1936      $params = array();
1937      $groupmode    = groups_get_activity_groupmode($cm);
1938      $currentgroup = groups_get_activity_group($cm);
1939  
1940      if ($groupmode) {
1941          $modcontext = context_module::instance($cm->id);
1942  
1943          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1944              if ($currentgroup) {
1945                  $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1946                  $params['currentgroup'] = $currentgroup;
1947              } else {
1948                  $groupselect = "";
1949              }
1950  
1951          } else {
1952              //separate groups without access all
1953              if ($currentgroup) {
1954                  $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1955                  $params['currentgroup'] = $currentgroup;
1956              } else {
1957                  $groupselect = "AND d.groupid = -1";
1958              }
1959          }
1960      } else {
1961          $groupselect = "";
1962      }
1963  
1964      if (!empty($CFG->forum_enabletimedposts)) {
1965          $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
1966          $params['now1'] = $now;
1967          $params['now2'] = $now;
1968      } else {
1969          $timedsql = "";
1970      }
1971  
1972      $sql = "SELECT d.id, COUNT(p.id) AS unread
1973                FROM {forum_discussions} d
1974                     JOIN {forum_posts} p     ON p.discussion = d.id
1975                     LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
1976               WHERE d.forum = {$cm->instance}
1977                     AND p.modified >= :cutoffdate AND r.id is NULL
1978                     $groupselect
1979                     $timedsql
1980            GROUP BY d.id";
1981      $params['cutoffdate'] = $cutoffdate;
1982  
1983      if ($unreads = $DB->get_records_sql($sql, $params)) {
1984          foreach ($unreads as $unread) {
1985              $unreads[$unread->id] = $unread->unread;
1986          }
1987          return $unreads;
1988      } else {
1989          return array();
1990      }
1991  }
1992  
1993  /**
1994   * @global object
1995   * @global object
1996   * @global object
1997   * @uses CONEXT_MODULE
1998   * @uses VISIBLEGROUPS
1999   * @param object $cm
2000   * @return array
2001   */
2002  function forum_get_discussions_count($cm) {
2003      global $CFG, $DB, $USER;
2004  
2005      $now = floor(time() / 60) * 60;
2006      $params = array($cm->instance);
2007      $groupmode    = groups_get_activity_groupmode($cm);
2008      $currentgroup = groups_get_activity_group($cm);
2009  
2010      if ($groupmode) {
2011          $modcontext = context_module::instance($cm->id);
2012  
2013          if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2014              if ($currentgroup) {
2015                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2016                  $params[] = $currentgroup;
2017              } else {
2018                  $groupselect = "";
2019              }
2020  
2021          } else {
2022              //seprate groups without access all
2023              if ($currentgroup) {
2024                  $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2025                  $params[] = $currentgroup;
2026              } else {
2027                  $groupselect = "AND d.groupid = -1";
2028              }
2029          }
2030      } else {
2031          $groupselect = "";
2032      }
2033  
2034      $timelimit = "";
2035  
2036      if (!empty($CFG->forum_enabletimedposts)) {
2037  
2038          $modcontext = context_module::instance($cm->id);
2039  
2040          if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2041              $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2042              $params[] = $now;
2043              $params[] = $now;
2044              if (isloggedin()) {
2045                  $timelimit .= " OR d.userid = ?";
2046                  $params[] = $USER->id;
2047              }
2048              $timelimit .= ")";
2049          }
2050      }
2051  
2052      $sql = "SELECT COUNT(d.id)
2053                FROM {forum_discussions} d
2054                     JOIN {forum_posts} p ON p.discussion = d.id
2055               WHERE d.forum = ? AND p.parent = 0
2056                     $groupselect $timelimit";
2057  
2058      return $DB->get_field_sql($sql, $params);
2059  }
2060  
2061  
2062  // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2063  
2064  
2065  /**
2066   * @global object
2067   * @global object
2068   * @param int $courseid
2069   * @param string $type
2070   */
2071  function forum_get_course_forum($courseid, $type) {
2072  // How to set up special 1-per-course forums
2073      global $CFG, $DB, $OUTPUT, $USER;
2074  
2075      if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2076          // There should always only be ONE, but with the right combination of
2077          // errors there might be more.  In this case, just return the oldest one (lowest ID).
2078          foreach ($forums as $forum) {
2079              return $forum;   // ie the first one
2080          }
2081      }
2082  
2083      // Doesn't exist, so create one now.
2084      $forum = new stdClass();
2085      $forum->course = $courseid;
2086      $forum->type = "$type";
2087      if (!empty($USER->htmleditor)) {
2088          $forum->introformat = $USER->htmleditor;
2089      }
2090      switch ($forum->type) {
2091          case "news":
2092              $forum->name  = get_string("namenews", "forum");
2093              $forum->intro = get_string("intronews", "forum");
2094              $forum->introformat = FORMAT_HTML;
2095              $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2096              $forum->assessed = 0;
2097              if ($courseid == SITEID) {
2098                  $forum->name  = get_string("sitenews");
2099                  $forum->forcesubscribe = 0;
2100              }
2101              break;
2102          case "social":
2103              $forum->name  = get_string("namesocial", "forum");
2104              $forum->intro = get_string("introsocial", "forum");
2105              $forum->introformat = FORMAT_HTML;
2106              $forum->assessed = 0;
2107              $forum->forcesubscribe = 0;
2108              break;
2109          case "blog":
2110              $forum->name = get_string('blogforum', 'forum');
2111              $forum->intro = get_string('introblog', 'forum');
2112              $forum->introformat = FORMAT_HTML;
2113              $forum->assessed = 0;
2114              $forum->forcesubscribe = 0;
2115              break;
2116          default:
2117              echo $OUTPUT->notification("That forum type doesn't exist!");
2118              return false;
2119              break;
2120      }
2121  
2122      $forum->timemodified = time();
2123      $forum->id = $DB->insert_record("forum", $forum);
2124  
2125      if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2126          echo $OUTPUT->notification("Could not find forum module!!");
2127          return false;
2128      }
2129      $mod = new stdClass();
2130      $mod->course = $courseid;
2131      $mod->module = $module->id;
2132      $mod->instance = $forum->id;
2133      $mod->section = 0;
2134      include_once("$CFG->dirroot/course/lib.php");
2135      if (! $mod->coursemodule = add_course_module($mod) ) {
2136          echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2137          return false;
2138      }
2139      $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
2140      return $DB->get_record("forum", array("id" => "$forum->id"));
2141  }
2142  
2143  /**
2144   * Return rating related permissions
2145   *
2146   * @param string $options the context id
2147   * @return array an associative array of the user's rating permissions
2148   */
2149  function forum_rating_permissions($contextid, $component, $ratingarea) {
2150      $context = context::instance_by_id($contextid, MUST_EXIST);
2151      if ($component != 'mod_forum' || $ratingarea != 'post') {
2152          // We don't know about this component/ratingarea so just return null to get the
2153          // default restrictive permissions.
2154          return null;
2155      }
2156      return array(
2157          'view'    => has_capability('mod/forum:viewrating', $context),
2158          'viewany' => has_capability('mod/forum:viewanyrating', $context),
2159          'viewall' => has_capability('mod/forum:viewallratings', $context),
2160          'rate'    => has_capability('mod/forum:rate', $context)
2161      );
2162  }
2163  
2164  /**
2165   * Validates a submitted rating
2166   * @param array $params submitted data
2167   *            context => object the context in which the rated items exists [required]
2168   *            component => The component for this module - should always be mod_forum [required]
2169   *            ratingarea => object the context in which the rated items exists [required]
2170   *
2171   *            itemid => int the ID of the object being rated [required]
2172   *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2173   *            rating => int the submitted rating [required]
2174   *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2175   *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
2176   * @return boolean true if the rating is valid. Will throw rating_exception if not
2177   */
2178  function forum_rating_validate($params) {
2179      global $DB, $USER;
2180  
2181      // Check the component is mod_forum
2182      if ($params['component'] != 'mod_forum') {
2183          throw new rating_exception('invalidcomponent');
2184      }
2185  
2186      // Check the ratingarea is post (the only rating area in forum)
2187      if ($params['ratingarea'] != 'post') {
2188          throw new rating_exception('invalidratingarea');
2189      }
2190  
2191      // Check the rateduserid is not the current user .. you can't rate your own posts
2192      if ($params['rateduserid'] == $USER->id) {
2193          throw new rating_exception('nopermissiontorate');
2194      }
2195  
2196      // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2197      $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
2198      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2199      $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2200      $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2201      $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2202      $context = context_module::instance($cm->id);
2203  
2204      // Make sure the context provided is the context of the forum
2205      if ($context->id != $params['context']->id) {
2206          throw new rating_exception('invalidcontext');
2207      }
2208  
2209      if ($forum->scale != $params['scaleid']) {
2210          //the scale being submitted doesnt match the one in the database
2211          throw new rating_exception('invalidscaleid');
2212      }
2213  
2214      // check the item we're rating was created in the assessable time window
2215      if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
2216          if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
2217              throw new rating_exception('notavailable');
2218          }
2219      }
2220  
2221      //check that the submitted rating is valid for the scale
2222  
2223      // lower limit
2224      if ($params['rating'] < 0  && $params['rating'] != RATING_UNSET_RATING) {
2225          throw new rating_exception('invalidnum');
2226      }
2227  
2228      // upper limit
2229      if ($forum->scale < 0) {
2230          //its a custom scale
2231          $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
2232          if ($scalerecord) {
2233              $scalearray = explode(',', $scalerecord->scale);
2234              if ($params['rating'] > count($scalearray)) {
2235                  throw new rating_exception('invalidnum');
2236              }
2237          } else {
2238              throw new rating_exception('invalidscaleid');
2239          }
2240      } else if ($params['rating'] > $forum->scale) {
2241          //if its numeric and submitted rating is above maximum
2242          throw new rating_exception('invalidnum');
2243      }
2244  
2245      // Make sure groups allow this user to see the item they're rating
2246      if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
2247          if (!groups_group_exists($discussion->groupid)) { // Can't find group
2248              throw new rating_exception('cannotfindgroup');//something is wrong
2249          }
2250  
2251          if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2252              // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
2253              throw new rating_exception('notmemberofgroup');
2254          }
2255      }
2256  
2257      // perform some final capability checks
2258      if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2259          throw new rating_exception('nopermissiontorate');
2260      }
2261  
2262      return true;
2263  }
2264  
2265  /**
2266   * Can the current user see ratings for a given itemid?
2267   *
2268   * @param array $params submitted data
2269   *            contextid => int contextid [required]
2270   *            component => The component for this module - should always be mod_forum [required]
2271   *            ratingarea => object the context in which the rated items exists [required]
2272   *            itemid => int the ID of the object being rated [required]
2273   *            scaleid => int scale id [optional]
2274   * @return bool
2275   * @throws coding_exception
2276   * @throws rating_exception
2277   */
2278  function mod_forum_rating_can_see_item_ratings($params) {
2279      global $DB, $USER;
2280  
2281      // Check the component is mod_forum.
2282      if (!isset($params['component']) || $params['component'] != 'mod_forum') {
2283          throw new rating_exception('invalidcomponent');
2284      }
2285  
2286      // Check the ratingarea is post (the only rating area in forum).
2287      if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
2288          throw new rating_exception('invalidratingarea');
2289      }
2290  
2291      if (!isset($params['itemid'])) {
2292          throw new rating_exception('invaliditemid');
2293      }
2294  
2295      $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
2296      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2297      $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2298      $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2299      $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2300  
2301      // Perform some final capability checks.
2302      if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2303          return false;
2304      }
2305  
2306      return true;
2307  }
2308  
2309  /**
2310   * This function prints the overview of a discussion in the forum listing.
2311   * It needs some discussion information and some post information, these
2312   * happen to be combined for efficiency in the $post parameter by the function
2313   * that calls this one: forum_print_latest_discussions()
2314   *
2315   * @global object
2316   * @global object
2317   * @param object $post The post object (passed by reference for speed).
2318   * @param object $forum The forum object.
2319   * @param int $group Current group.
2320   * @param string $datestring Format to use for the dates.
2321   * @param boolean $cantrack Is tracking enabled for this forum.
2322   * @param boolean $forumtracked Is the user tracking this forum.
2323   * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
2324   * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
2325   */
2326  function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2327                                          $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2328                                          $canviewhiddentimedposts = false) {
2329  
2330      global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
2331  
2332      static $rowcount;
2333      static $strmarkalldread;
2334  
2335      if (empty($modcontext)) {
2336          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2337              print_error('invalidcoursemodule');
2338          }
2339          $modcontext = context_module::instance($cm->id);
2340      }
2341  
2342      if (!isset($rowcount)) {
2343          $rowcount = 0;
2344          $strmarkalldread = get_string('markalldread', 'forum');
2345      } else {
2346          $rowcount = ($rowcount + 1) % 2;
2347      }
2348  
2349      $post->subject = format_string($post->subject,true);
2350  
2351      $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
2352      $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2353      $timedoutsidewindow = '';
2354      if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2355          $timedoutsidewindow = ' dimmed_text';
2356      }
2357  
2358      echo "\n\n";
2359      echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
2360  
2361      $topicclass = 'topic starter';
2362      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2363          $topicclass .= ' pinned';
2364      }
2365      echo '<td class="'.$topicclass.'">';
2366      if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2367          echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2368      }
2369      $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2370      if ($timeddiscussion && $canalwaysseetimedpost) {
2371          echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2372      }
2373  
2374      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
2375      echo "</td>\n";
2376  
2377      // Picture
2378      $postuser = new stdClass();
2379      $postuserfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
2380      $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
2381      $postuser->id = $post->userid;
2382      echo '<td class="author">';
2383      echo '<div class="media">';
2384      echo '<span class="float-left">';
2385      echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
2386      echo '</span>';
2387      // User name
2388      echo '<div class="media-body">';
2389      $fullname = fullname($postuser, $canviewfullnames);
2390      echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
2391      echo '</div>';
2392      echo '</div>';
2393      echo "</td>\n";
2394  
2395      // Group picture
2396      if ($group !== -1) {  // Groups are active - group is a group data object or NULL
2397          echo '<td class="picture group">';
2398          if (!empty($group->picture)) {
2399              if ($canviewparticipants && $COURSE->groupmode) {
2400                  $picturelink = true;
2401              } else {
2402                  $picturelink = false;
2403              }
2404              print_group_picture($group, $forum->course, false, false, $picturelink);
2405          } else if (isset($group->id)) {
2406              if ($canviewparticipants && $COURSE->groupmode) {
2407                  echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
2408              } else {
2409                  echo $group->name;
2410              }
2411          }
2412          echo "</td>\n";
2413      }
2414  
2415      if (has_capability('mod/forum:viewdiscussion', $modcontext)) {   // Show the column with replies
2416          echo '<td class="replies">';
2417          echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2418          echo $post->replies.'</a>';
2419          echo "</td>\n";
2420  
2421          if ($cantrack) {
2422              echo '<td class="replies">';
2423              if ($forumtracked) {
2424                  if ($post->unread > 0) {
2425                      echo '<span class="unread">';
2426                      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2427                      echo $post->unread;
2428                      echo '</a>';
2429                      echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2430                           $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;return=/mod/forum/view.php&amp;sesskey=' .
2431                           sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
2432                      echo '</span>';
2433                  } else {
2434                      echo '<span class="read">';
2435                      echo $post->unread;
2436                      echo '</span>';
2437                  }
2438              } else {
2439                  echo '<span class="read">';
2440                  echo '-';
2441                  echo '</span>';
2442              }
2443              echo "</td>\n";
2444          }
2445      }
2446  
2447      echo '<td class="lastpost">';
2448      $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
2449      $parenturl = '';
2450      $usermodified = new stdClass();
2451      $usermodified->id = $post->usermodified;
2452      $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
2453  
2454      // In QA forums we check that the user can view participants.
2455      if ($forum->type !== 'qanda' || $canviewparticipants) {
2456          echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
2457               fullname($usermodified, $canviewfullnames).'</a><br />';
2458          $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
2459      }
2460  
2461      echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
2462            userdate_htmltime($usedate, $datestring).'</a>';
2463      echo "</td>\n";
2464  
2465      // is_guest should be used here as this also checks whether the user is a guest in the current course.
2466      // Guests and visitors cannot subscribe - only enrolled users.
2467      if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
2468          // Discussion subscription.
2469          if (\mod_forum\subscriptions::is_subscribable($forum)) {
2470              echo '<td class="discussionsubscription">';
2471              echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2472              echo '</td>';
2473          }
2474      }
2475  
2476      echo "</tr>\n\n";
2477  
2478  }
2479  
2480  /**
2481   * Return the markup for the discussion subscription toggling icon.
2482   *
2483   * @param stdClass $forum The forum object.
2484   * @param int $discussionid The discussion to create an icon for.
2485   * @return string The generated markup.
2486   */
2487  function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2488      global $USER, $OUTPUT, $PAGE;
2489  
2490      if ($returnurl === null && $PAGE->url) {
2491          $returnurl = $PAGE->url->out();
2492      }
2493  
2494      $o = '';
2495      $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2496      $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2497          'sesskey' => sesskey(),
2498          'id' => $forum->id,
2499          'd' => $discussionid,
2500          'returnurl' => $returnurl,
2501      ));
2502  
2503      if ($includetext) {
2504          $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2505      }
2506  
2507      if ($subscriptionstatus) {
2508          $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2509          if ($includetext) {
2510              $output .= get_string('subscribed', 'mod_forum');
2511          }
2512  
2513          return html_writer::link($subscriptionlink, $output, array(
2514                  'title' => get_string('clicktounsubscribe', 'forum'),
2515                  'class' => 'discussiontoggle btn btn-link',
2516                  'data-forumid' => $forum->id,
2517                  'data-discussionid' => $discussionid,
2518                  'data-includetext' => $includetext,
2519              ));
2520  
2521      } else {
2522          $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2523          if ($includetext) {
2524              $output .= get_string('notsubscribed', 'mod_forum');
2525          }
2526  
2527          return html_writer::link($subscriptionlink, $output, array(
2528                  'title' => get_string('clicktosubscribe', 'forum'),
2529                  'class' => 'discussiontoggle btn btn-link',
2530                  'data-forumid' => $forum->id,
2531                  'data-discussionid' => $discussionid,
2532                  'data-includetext' => $includetext,
2533              ));
2534      }
2535  }
2536  
2537  /**
2538   * Return a pair of spans containing classes to allow the subscribe and
2539   * unsubscribe icons to be pre-loaded by a browser.
2540   *
2541   * @return string The generated markup
2542   */
2543  function forum_get_discussion_subscription_icon_preloaders() {
2544      $o = '';
2545      $o .= html_writer::span('&nbsp;', 'preload-subscribe');
2546      $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
2547      return $o;
2548  }
2549  
2550  /**
2551   * Print the drop down that allows the user to select how they want to have
2552   * the discussion displayed.
2553   *
2554   * @param int $id forum id if $forumtype is 'single',
2555   *              discussion id for any other forum type
2556   * @param mixed $mode forum layout mode
2557   * @param string $forumtype optional
2558   */
2559  function forum_print_mode_form($id, $mode, $forumtype='') {
2560      global $OUTPUT;
2561      $useexperimentalui = get_user_preferences('forum_useexperimentalui', false);
2562      if ($forumtype == 'single') {
2563          $select = new single_select(
2564              new moodle_url("/mod/forum/view.php",
2565              array('f' => $id)),
2566              'mode',
2567              forum_get_layout_modes($useexperimentalui),
2568              $mode,
2569              null,
2570              "mode"
2571          );
2572          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2573          $select->class = "forummode";
2574      } else {
2575          $select = new single_select(
2576              new moodle_url("/mod/forum/discuss.php",
2577              array('d' => $id)),
2578              'mode',
2579              forum_get_layout_modes($useexperimentalui),
2580              $mode,
2581              null,
2582              "mode"
2583          );
2584          $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2585      }
2586      echo $OUTPUT->render($select);
2587  }
2588  
2589  /**
2590   * @global object
2591   * @param object $course
2592   * @param string $search
2593   * @return string
2594   */
2595  function forum_search_form($course, $search='') {
2596      global $CFG, $PAGE;
2597      $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2598      $output = $PAGE->get_renderer('mod_forum');
2599      return $output->render($forumsearch);
2600  }
2601  
2602  
2603  /**
2604   * @global object
2605   * @global object
2606   */
2607  function forum_set_return() {
2608      global $CFG, $SESSION;
2609  
2610      if (! isset($SESSION->fromdiscussion)) {
2611          $referer = get_local_referer(false);
2612          // If the referer is NOT a login screen then save it.
2613          if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2614              $SESSION->fromdiscussion = $referer;
2615          }
2616      }
2617  }
2618  
2619  
2620  /**
2621   * @global object
2622   * @param string|\moodle_url $default
2623   * @return string
2624   */
2625  function forum_go_back_to($default) {
2626      global $SESSION;
2627  
2628      if (!empty($SESSION->fromdiscussion)) {
2629          $returnto = $SESSION->fromdiscussion;
2630          unset($SESSION->fromdiscussion);
2631          return $returnto;
2632      } else {
2633          return $default;
2634      }
2635  }
2636  
2637  /**
2638   * Given a discussion object that is being moved to $forumto,
2639   * this function checks all posts in that discussion
2640   * for attachments, and if any are found, these are
2641   * moved to the new forum directory.
2642   *
2643   * @global object
2644   * @param object $discussion
2645   * @param int $forumfrom source forum id
2646   * @param int $forumto target forum id
2647   * @return bool success
2648   */
2649  function forum_move_attachments($discussion, $forumfrom, $forumto) {
2650      global $DB;
2651  
2652      $fs = get_file_storage();
2653  
2654      $newcm = get_coursemodule_from_instance('forum', $forumto);
2655      $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2656  
2657      $newcontext = context_module::instance($newcm->id);
2658      $oldcontext = context_module::instance($oldcm->id);
2659  
2660      // loop through all posts, better not use attachment flag ;-)
2661      if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
2662          foreach ($posts as $post) {
2663              $fs->move_area_files_to_new_context($oldcontext->id,
2664                      $newcontext->id, 'mod_forum', 'post', $post->id);
2665              $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2666                      $newcontext->id, 'mod_forum', 'attachment', $post->id);
2667              if ($attachmentsmoved > 0 && $post->attachment != '1') {
2668                  // Weird - let's fix it
2669                  $post->attachment = '1';
2670                  $DB->update_record('forum_posts', $post);
2671              } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2672                  // Weird - let's fix it
2673                  $post->attachment = '';
2674                  $DB->update_record('forum_posts', $post);
2675              }
2676          }
2677      }
2678  
2679      return true;
2680  }
2681  
2682  /**
2683   * Returns attachments as formated text/html optionally with separate images
2684   *
2685   * @global object
2686   * @global object
2687   * @global object
2688   * @param object $post
2689   * @param object $cm
2690   * @param string $type html/text/separateimages
2691   * @return mixed string or array of (html text withouth images and image HTML)
2692   */
2693  function forum_print_attachments($post, $cm, $type) {
2694      global $CFG, $DB, $USER, $OUTPUT;
2695  
2696      if (empty($post->attachment)) {
2697          return $type !== 'separateimages' ? '' : array('', '');
2698      }
2699  
2700      if (!in_array($type, array('separateimages', 'html', 'text'))) {
2701          return $type !== 'separateimages' ? '' : array('', '');
2702      }
2703  
2704      if (!$context = context_module::instance($cm->id)) {
2705          return $type !== 'separateimages' ? '' : array('', '');
2706      }
2707      $strattachment = get_string('attachment', 'forum');
2708  
2709      $fs = get_file_storage();
2710  
2711      $imagereturn = '';
2712      $output = '';
2713  
2714      $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
2715  
2716      if ($canexport) {
2717          require_once($CFG->libdir.'/portfoliolib.php');
2718      }
2719  
2720      // We retrieve all files according to the time that they were created.  In the case that several files were uploaded
2721      // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2722      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
2723      if ($files) {
2724          if ($canexport) {
2725              $button = new portfolio_add_button();
2726          }
2727          foreach ($files as $file) {
2728              $filename = $file->get_filename();
2729              $mimetype = $file->get_mimetype();
2730              $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2731              $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2732  
2733              if ($type == 'html') {
2734                  $output .= "<a href=\"$path\">$iconimage</a> ";
2735                  $output .= "<a href=\"$path\">".s($filename)."</a>";
2736                  if ($canexport) {
2737                      $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2738                      $button->set_format_by_file($file);
2739                      $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2740                  }
2741                  $output .= "<br />";
2742  
2743              } else if ($type == 'text') {
2744                  $output .= "$strattachment ".s($filename).":\n$path\n";
2745  
2746              } else { //'returnimages'
2747                  if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2748                      // Image attachments don't get printed as links
2749                      $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2750                      if ($canexport) {
2751                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2752                          $button->set_format_by_file($file);
2753                          $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2754                      }
2755                  } else {
2756                      $output .= "<a href=\"$path\">$iconimage</a> ";
2757                      $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
2758                      if ($canexport) {
2759                          $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2760                          $button->set_format_by_file($file);
2761                          $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2762                      }
2763                      $output .= '<br />';
2764                  }
2765              }
2766  
2767              if (!empty($CFG->enableplagiarism)) {
2768                  require_once($CFG->libdir.'/plagiarismlib.php');
2769                  $output .= plagiarism_get_links(array('userid' => $post->userid,
2770                      'file' => $file,
2771                      'cmid' => $cm->id,
2772                      'course' => $cm->course,
2773                      'forum' => $cm->instance));
2774                  $output .= '<br />';
2775              }
2776          }
2777      }
2778  
2779      if ($type !== 'separateimages') {
2780          return $output;
2781  
2782      } else {
2783          return array($output, $imagereturn);
2784      }
2785  }
2786  
2787  ////////////////////////////////////////////////////////////////////////////////
2788  // File API                                                                   //
2789  ////////////////////////////////////////////////////////////////////////////////
2790  
2791  /**
2792   * Lists all browsable file areas
2793   *
2794   * @package  mod_forum
2795   * @category files
2796   * @param stdClass $course course object
2797   * @param stdClass $cm course module object
2798   * @param stdClass $context context object
2799   * @return array
2800   */
2801  function forum_get_file_areas($course, $cm, $context) {
2802      return array(
2803          'attachment' => get_string('areaattachment', 'mod_forum'),
2804          'post' => get_string('areapost', 'mod_forum'),
2805      );
2806  }
2807  
2808  /**
2809   * File browsing support for forum module.
2810   *
2811   * @package  mod_forum
2812   * @category files
2813   * @param stdClass $browser file browser object
2814   * @param stdClass $areas file areas
2815   * @param stdClass $course course object
2816   * @param stdClass $cm course module
2817   * @param stdClass $context context module
2818   * @param string $filearea file area
2819   * @param int $itemid item ID
2820   * @param string $filepath file path
2821   * @param string $filename file name
2822   * @return file_info instance or null if not found
2823   */
2824  function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2825      global $CFG, $DB, $USER;
2826  
2827      if ($context->contextlevel != CONTEXT_MODULE) {
2828          return null;
2829      }
2830  
2831      // filearea must contain a real area
2832      if (!isset($areas[$filearea])) {
2833          return null;
2834      }
2835  
2836      // Note that forum_user_can_see_post() additionally allows access for parent roles
2837      // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2838      // course:managefiles, we will need to extend this.
2839      if (!has_capability('mod/forum:viewdiscussion', $context)) {
2840          return null;
2841      }
2842  
2843      if (is_null($itemid)) {
2844          require_once($CFG->dirroot.'/mod/forum/locallib.php');
2845          return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2846      }
2847  
2848      static $cached = array();
2849      // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2850      // is cleared between unit tests we check if this is the same session
2851      if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2852          $cached = array('sesskey' => sesskey());
2853      }
2854  
2855      if (isset($cached['post']) && $cached['post']->id == $itemid) {
2856          $post = $cached['post'];
2857      } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2858          $cached['post'] = $post;
2859      } else {
2860          return null;
2861      }
2862  
2863      if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2864          $discussion = $cached['discussion'];
2865      } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2866          $cached['discussion'] = $discussion;
2867      } else {
2868          return null;
2869      }
2870  
2871      if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2872          $forum = $cached['forum'];
2873      } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2874          $cached['forum'] = $forum;
2875      } else {
2876          return null;
2877      }
2878  
2879      $fs = get_file_storage();
2880      $filepath = is_null($filepath) ? '/' : $filepath;
2881      $filename = is_null($filename) ? '.' : $filename;
2882      if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2883          return null;
2884      }
2885  
2886      // Checks to see if the user can manage files or is the owner.
2887      // TODO MDL-33805 - Do not use userid here and move the capability check above.
2888      if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2889          return null;
2890      }
2891      // Make sure groups allow this user to see this file
2892      if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2893          $groupmode = groups_get_activity_groupmode($cm, $course);
2894          if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2895              return null;
2896          }
2897      }
2898  
2899      // Make sure we're allowed to see it...
2900      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2901          return null;
2902      }
2903  
2904      $urlbase = $CFG->wwwroot.'/pluginfile.php';
2905      return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2906  }
2907  
2908  /**
2909   * Serves the forum attachments. Implements needed access control ;-)
2910   *
2911   * @package  mod_forum
2912   * @category files
2913   * @param stdClass $course course object
2914   * @param stdClass $cm course module object
2915   * @param stdClass $context context object
2916   * @param string $filearea file area
2917   * @param array $args extra arguments
2918   * @param bool $forcedownload whether or not force download
2919   * @param array $options additional options affecting the file serving
2920   * @return bool false if file not found, does not return if found - justsend the file
2921   */
2922  function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2923      global $CFG, $DB;
2924  
2925      if ($context->contextlevel != CONTEXT_MODULE) {
2926          return false;
2927      }
2928  
2929      require_course_login($course, true, $cm);
2930  
2931      $areas = forum_get_file_areas($course, $cm, $context);
2932  
2933      // filearea must contain a real area
2934      if (!isset($areas[$filearea])) {
2935          return false;
2936      }
2937  
2938      $postid = (int)array_shift($args);
2939  
2940      if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2941          return false;
2942      }
2943  
2944      if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
2945          return false;
2946      }
2947  
2948      if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
2949          return false;
2950      }
2951  
2952      $fs = get_file_storage();
2953      $relativepath = implode('/', $args);
2954      $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
2955      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2956          return false;
2957      }
2958  
2959      // Make sure groups allow this user to see this file
2960      if ($discussion->groupid > 0) {
2961          $groupmode = groups_get_activity_groupmode($cm, $course);
2962          if ($groupmode == SEPARATEGROUPS) {
2963              if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2964                  return false;
2965              }
2966          }
2967      }
2968  
2969      // Make sure we're allowed to see it...
2970      if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2971          return false;
2972      }
2973  
2974      // finally send the file
2975      send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
2976  }
2977  
2978  /**
2979   * If successful, this function returns the name of the file
2980   *
2981   * @global object
2982   * @param object $post is a full post record, including course and forum
2983   * @param object $forum
2984   * @param object $cm
2985   * @param mixed $mform
2986   * @param string $unused
2987   * @return bool
2988   */
2989  function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
2990      global $DB;
2991  
2992      if (empty($mform)) {
2993          return false;
2994      }
2995  
2996      if (empty($post->attachments)) {
2997          return true;   // Nothing to do
2998      }
2999  
3000      $context = context_module::instance($cm->id);
3001  
3002      $info = file_get_draft_area_info($post->attachments);
3003      $present = ($info['filecount']>0) ? '1' : '';
3004      file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
3005              mod_forum_post_form::attachment_options($forum));
3006  
3007      $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
3008  
3009      return true;
3010  }
3011  
3012  /**
3013   * Add a new post in an existing discussion.
3014   *
3015   * @param   stdClass    $post       The post data
3016   * @param   mixed       $mform      The submitted form
3017   * @param   string      $unused
3018   * @return int
3019   */
3020  function forum_add_new_post($post, $mform, $unused = null) {
3021      global $USER, $DB;
3022  
3023      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3024      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3025      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3026      $context    = context_module::instance($cm->id);
3027      $privatereplyto = 0;
3028  
3029      // Check whether private replies should be enabled for this post.
3030      if ($post->parent) {
3031          $parent = $DB->get_record('forum_posts', array('id' => $post->parent));
3032  
3033          if (!empty($parent->privatereplyto)) {
3034              throw new \coding_exception('It should not be possible to reply to a private reply');
3035          }
3036  
3037          if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) {
3038              $privatereplyto = $parent->userid;
3039          }
3040      }
3041  
3042      $post->created    = $post->modified = time();
3043      $post->mailed     = FORUM_MAILED_PENDING;
3044      $post->userid     = $USER->id;
3045      $post->privatereplyto = $privatereplyto;
3046      $post->attachment = "";
3047      if (!isset($post->totalscore)) {
3048          $post->totalscore = 0;
3049      }
3050      if (!isset($post->mailnow)) {
3051          $post->mailnow    = 0;
3052      }
3053  
3054      \mod_forum\local\entities\post::add_message_counts($post);
3055      $post->id = $DB->insert_record("forum_posts", $post);
3056      $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
3057              mod_forum_post_form::editor_options($context, null), $post->message);
3058      $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
3059      forum_add_attachment($post, $forum, $cm, $mform);
3060  
3061      // Update discussion modified date
3062      $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
3063      $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
3064  
3065      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3066          forum_tp_mark_post_read($post->userid, $post);
3067      }
3068  
3069      if (isset($post->tags)) {
3070          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
3071      }
3072  
3073      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3074      forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
3075  
3076      return $post->id;
3077  }
3078  
3079  /**
3080   * Trigger post updated event.
3081   *
3082   * @param object $post forum post object
3083   * @param object $discussion discussion object
3084   * @param object $context forum context object
3085   * @param object $forum forum object
3086   * @since Moodle 3.8
3087   * @return void
3088   */
3089  function forum_trigger_post_updated_event($post, $discussion, $context, $forum) {
3090      global $USER;
3091  
3092      $params = array(
3093          'context' => $context,
3094          'objectid' => $post->id,
3095          'other' => array(
3096              'discussionid' => $discussion->id,
3097              'forumid' => $forum->id,
3098              'forumtype' => $forum->type,
3099          )
3100      );
3101  
3102      if ($USER->id !== $post->userid) {
3103          $params['relateduserid'] = $post->userid;
3104      }
3105  
3106      $event = \mod_forum\event\post_updated::create($params);
3107      $event->add_record_snapshot('forum_discussions', $discussion);
3108      $event->trigger();
3109  }
3110  
3111  /**
3112   * Update a post.
3113   *
3114   * @param   stdClass    $newpost    The post to update
3115   * @param   mixed       $mform      The submitted form
3116   * @param   string      $unused
3117   * @return  bool
3118   */
3119  function forum_update_post($newpost, $mform, $unused = null) {
3120      global $DB, $USER;
3121  
3122      $post       = $DB->get_record('forum_posts', array('id' => $newpost->id));
3123      $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3124      $forum      = $DB->get_record('forum', array('id' => $discussion->forum));
3125      $cm         = get_coursemodule_from_instance('forum', $forum->id);
3126      $context    = context_module::instance($cm->id);
3127  
3128      // Allowed modifiable fields.
3129      $modifiablefields = [
3130          'subject',
3131          'message',
3132          'messageformat',
3133          'messagetrust',
3134          'timestart',
3135          'timeend',
3136          'pinned',
3137          'attachments',
3138      ];
3139      foreach ($modifiablefields as $field) {
3140          if (isset($newpost->{$field})) {
3141              $post->{$field} = $newpost->{$field};
3142          }
3143      }
3144      $post->modified = time();
3145  
3146      if (!$post->parent) {   // Post is a discussion starter - update discussion title and times too
3147          $discussion->name      = $post->subject;
3148          $discussion->timestart = $post->timestart;
3149          $discussion->timeend   = $post->timeend;
3150  
3151          if (isset($post->pinned)) {
3152              $discussion->pinned = $post->pinned;
3153          }
3154      }
3155      $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
3156              mod_forum_post_form::editor_options($context, $post->id), $post->message);
3157      \mod_forum\local\entities\post::add_message_counts($post);
3158      $DB->update_record('forum_posts', $post);
3159      // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3160      $DB->update_record('forum_discussions', $discussion);
3161  
3162      forum_add_attachment($post, $forum, $cm, $mform);
3163  
3164      if ($forum->type == 'single' && $post->parent == '0') {
3165          // Updating first post of single discussion type -> updating forum intro.
3166          $forum->intro = $post->message;
3167          $forum->timemodified = time();
3168          $DB->update_record("forum", $forum);
3169      }
3170  
3171      if (isset($newpost->tags)) {
3172          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3173      }
3174  
3175      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3176          forum_tp_mark_post_read($USER->id, $post);
3177      }
3178  
3179      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3180      forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3181  
3182      return true;
3183  }
3184  
3185  /**
3186   * Given an object containing all the necessary data,
3187   * create a new discussion and return the id
3188   *
3189   * @param object $post
3190   * @param mixed $mform
3191   * @param string $unused
3192   * @param int $userid
3193   * @return object
3194   */
3195  function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3196      global $USER, $CFG, $DB;
3197  
3198      $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
3199  
3200      if (is_null($userid)) {
3201          $userid = $USER->id;
3202      }
3203  
3204      // The first post is stored as a real post, and linked
3205      // to from the discuss entry.
3206  
3207      $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
3208      $cm    = get_coursemodule_from_instance('forum', $forum->id);
3209  
3210      $post = new stdClass();
3211      $post->discussion    = 0;
3212      $post->parent        = 0;
3213      $post->privatereplyto = 0;
3214      $post->userid        = $userid;
3215      $post->created       = $timenow;
3216      $post->modified      = $timenow;
3217      $post->mailed        = FORUM_MAILED_PENDING;
3218      $post->subject       = $discussion->name;
3219      $post->message       = $discussion->message;
3220      $post->messageformat = $discussion->messageformat;
3221      $post->messagetrust  = $discussion->messagetrust;
3222      $post->attachments   = isset($discussion->attachments) ? $discussion->attachments : null;
3223      $post->forum         = $forum->id;     // speedup
3224      $post->course        = $forum->course; // speedup
3225      $post->mailnow       = $discussion->mailnow;
3226  
3227      \mod_forum\local\entities\post::add_message_counts($post);
3228      $post->id = $DB->insert_record("forum_posts", $post);
3229  
3230      // TODO: Fix the calling code so that there always is a $cm when this function is called
3231      if (!empty($cm->id) && !empty($discussion->itemid)) {   // In "single simple discussions" this may not exist yet
3232          $context = context_module::instance($cm->id);
3233          $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
3234                  mod_forum_post_form::editor_options($context, null), $post->message);
3235          $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
3236      }
3237  
3238      // Now do the main entry for the discussion, linking to this first post
3239  
3240      $discussion->firstpost    = $post->id;
3241      $discussion->timemodified = $timenow;
3242      $discussion->usermodified = $post->userid;
3243      $discussion->userid       = $userid;
3244      $discussion->assessed     = 0;
3245  
3246      $post->discussion = $DB->insert_record("forum_discussions", $discussion);
3247  
3248      // Finally, set the pointer on the post.
3249      $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
3250  
3251      if (!empty($cm->id)) {
3252          forum_add_attachment($post, $forum, $cm, $mform, $unused);
3253      }
3254  
3255      if (isset($discussion->tags)) {
3256          core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
3257      }
3258  
3259      if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3260          forum_tp_mark_post_read($post->userid, $post);
3261      }
3262  
3263      // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3264      if (!empty($cm->id)) {
3265          forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3266      }
3267  
3268      return $post->discussion;
3269  }
3270  
3271  
3272  /**
3273   * Deletes a discussion and handles all associated cleanup.
3274   *
3275   * @global object
3276   * @param object $discussion Discussion to delete
3277   * @param bool $fulldelete True when deleting entire forum
3278   * @param object $course Course
3279   * @param object $cm Course-module
3280   * @param object $forum Forum
3281   * @return bool
3282   */
3283  function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3284      global $DB, $CFG;
3285      require_once($CFG->libdir.'/completionlib.php');
3286  
3287      $result = true;
3288  
3289      if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
3290          foreach ($posts as $post) {
3291              $post->course = $discussion->course;
3292              $post->forum  = $discussion->forum;
3293              if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3294                  $result = false;
3295              }
3296          }
3297      }
3298  
3299      forum_tp_delete_read_records(-1, -1, $discussion->id);
3300  
3301      // Discussion subscriptions must be removed before discussions because of key constraints.
3302      $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
3303      if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
3304          $result = false;
3305      }
3306  
3307      // Update completion state if we are tracking completion based on number of posts
3308      // But don't bother when deleting whole thing
3309      if (!$fulldelete) {
3310          $completion = new completion_info($course);
3311          if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3312             ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3313              $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
3314          }
3315      }
3316  
3317      $params = array(
3318          'objectid' => $discussion->id,
3319          'context' => context_module::instance($cm->id),
3320          'other' => array(
3321              'forumid' => $forum->id,
3322          )
3323      );
3324      $event = \mod_forum\event\discussion_deleted::create($params);
3325      $event->add_record_snapshot('forum_discussions', $discussion);
3326      $event->trigger();
3327  
3328      return $result;
3329  }
3330  
3331  
3332  /**
3333   * Deletes a single forum post.
3334   *
3335   * @global object
3336   * @param object $post Forum post object
3337   * @param mixed $children Whether to delete children. If false, returns false
3338   *   if there are any children (without deleting the post). If true,
3339   *   recursively deletes all children. If set to special value 'ignore', deletes
3340   *   post regardless of children (this is for use only when deleting all posts
3341   *   in a disussion).
3342   * @param object $course Course
3343   * @param object $cm Course-module
3344   * @param object $forum Forum
3345   * @param bool $skipcompletion True to skip updating completion state if it
3346   *   would otherwise be updated, i.e. when deleting entire forum anyway.
3347   * @return bool
3348   */
3349  function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3350      global $DB, $CFG, $USER;
3351      require_once($CFG->libdir.'/completionlib.php');
3352  
3353      $context = context_module::instance($cm->id);
3354  
3355      if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
3356         if ($children) {
3357             foreach ($childposts as $childpost) {
3358                 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3359             }
3360         } else {
3361             return false;
3362         }
3363      }
3364  
3365      // Delete ratings.
3366      require_once($CFG->dirroot.'/rating/lib.php');
3367      $delopt = new stdClass;
3368      $delopt->contextid = $context->id;
3369      $delopt->component = 'mod_forum';
3370      $delopt->ratingarea = 'post';
3371      $delopt->itemid = $post->id;
3372      $rm = new rating_manager();
3373      $rm->delete_ratings($delopt);
3374  
3375      // Delete attachments.
3376      $fs = get_file_storage();
3377      $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
3378      $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
3379  
3380      // Delete cached RSS feeds.
3381      if (!empty($CFG->enablerssfeeds)) {
3382          require_once($CFG->dirroot.'/mod/forum/rsslib.php');
3383          forum_rss_delete_file($forum);
3384      }
3385  
3386      if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
3387  
3388          forum_tp_delete_read_records(-1, $post->id);
3389  
3390      // Just in case we are deleting the last post
3391          forum_discussion_update_last_post($post->discussion);
3392  
3393          // Update completion state if we are tracking completion based on number of posts
3394          // But don't bother when deleting whole thing
3395  
3396          if (!$skipcompletion) {
3397              $completion = new completion_info($course);
3398              if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3399                 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3400                  $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
3401              }
3402          }
3403  
3404          $params = array(
3405              'context' => $context,
3406              'objectid' => $post->id,
3407              'other' => array(
3408                  'discussionid' => $post->discussion,
3409                  'forumid' => $forum->id,
3410                  'forumtype' => $forum->type,
3411              )
3412          );
3413          $post->deleted = 1;
3414          if ($post->userid !== $USER->id) {
3415              $params['relateduserid'] = $post->userid;
3416          }
3417          $event = \mod_forum\event\post_deleted::create($params);
3418          $event->add_record_snapshot('forum_posts', $post);
3419          $event->trigger();
3420  
3421          return true;
3422      }
3423      return false;
3424  }
3425  
3426  /**
3427   * Sends post content to plagiarism plugin
3428   * @param object $post Forum post object
3429   * @param object $cm Course-module
3430   * @param string $name
3431   * @return bool
3432  */
3433  function forum_trigger_content_uploaded_event($post, $cm, $name) {
3434      $context = context_module::instance($cm->id);
3435      $fs = get_file_storage();
3436      $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
3437      $params = array(
3438          'context' => $context,
3439          'objectid' => $post->id,
3440          'other' => array(
3441              'content' => $post->message,
3442              'pathnamehashes' => array_keys($files),
3443              'discussionid' => $post->discussion,
3444              'triggeredfrom' => $name,
3445          )
3446      );
3447      $event = \mod_forum\event\assessable_uploaded::create($params);
3448      $event->trigger();
3449      return true;
3450  }
3451  
3452  /**
3453   * Given a new post, subscribes or unsubscribes as appropriate.
3454   * Returns some text which describes what happened.
3455   *
3456   * @param object $fromform The submitted form
3457   * @param stdClass $forum The forum record
3458   * @param stdClass $discussion The forum discussion record
3459   * @return string
3460   */
3461  function forum_post_subscription($fromform, $forum, $discussion) {
3462      global $USER;
3463  
3464      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3465          return "";
3466      } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
3467          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3468          if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
3469              // This user should not be subscribed to the forum.
3470              \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
3471          }
3472          return "";
3473      }
3474  
3475      $info = new stdClass();
3476      $info->name  = fullname($USER);
3477      $info->discussion = format_string($discussion->name);
3478      $info->forum = format_string($forum->name);
3479  
3480      if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
3481          if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
3482              return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3483          }
3484      } else {
3485          if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
3486              return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3487          }
3488      }
3489  
3490      return '';
3491  }
3492  
3493  /**
3494   * Generate and return the subscribe or unsubscribe link for a forum.
3495   *
3496   * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3497   * @param object $context the context object for this forum.
3498   * @param array $messages text used for the link in its various states
3499   *      (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3500   *      Any strings not passed in are taken from the $defaultmessages array
3501   *      at the top of the function.
3502   * @param bool $cantaccessagroup
3503   * @param bool $unused1
3504   * @param bool $backtoindex
3505   * @param array $unused2
3506   * @return string
3507   */
3508  function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3509      $backtoindex = false, $unused2 = null) {
3510      global $CFG, $USER, $PAGE, $OUTPUT;
3511      $defaultmessages = array(
3512          'subscribed' => get_string('unsubscribe', 'forum'),
3513          'unsubscribed' => get_string('subscribe', 'forum'),
3514          'cantaccessgroup' => get_string('no'),
3515          'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3516          'cantsubscribe' => get_string('disallowsubscribe','forum')
3517      );
3518      $messages = $messages + $defaultmessages;
3519  
3520      if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3521          return $messages['forcesubscribed'];
3522      } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
3523              !has_capability('mod/forum:managesubscriptions', $context)) {
3524          return $messages['cantsubscribe'];
3525      } else if ($cantaccessagroup) {
3526          return $messages['cantaccessgroup'];
3527      } else {
3528          if (!is_enrolled($context, $USER, '', true)) {
3529              return '';
3530          }
3531  
3532          $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3533          if ($subscribed) {
3534              $linktext = $messages['subscribed'];
3535              $linktitle = get_string('subscribestop', 'forum');
3536          } else {
3537              $linktext = $messages['unsubscribed'];
3538              $linktitle = get_string('subscribestart', 'forum');
3539          }
3540  
3541          $options = array();
3542          if ($backtoindex) {
3543              $backtoindexlink = '&amp;backtoindex=1';
3544              $options['backtoindex'] = 1;
3545          } else {
3546              $backtoindexlink = '';
3547          }
3548  
3549          $options['id'] = $forum->id;
3550          $options['sesskey'] = sesskey();
3551          $url = new moodle_url('/mod/forum/subscribe.php', $options);
3552          return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3553      }
3554  }
3555  
3556  /**
3557   * Returns true if user created new discussion already.
3558   *
3559   * @param int $forumid  The forum to check for postings
3560   * @param int $userid   The user to check for postings
3561   * @param int $groupid  The group to restrict the check to
3562   * @return bool
3563   */
3564  function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3565      global $CFG, $DB;
3566  
3567      $sql = "SELECT 'x'
3568                FROM {forum_discussions} d, {forum_posts} p
3569               WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3570  
3571      $params = [$forumid, $userid];
3572  
3573      if ($groupid) {
3574          $sql .= " AND d.groupid = ?";
3575          $params[] = $groupid;
3576      }
3577  
3578      return $DB->record_exists_sql($sql, $params);
3579  }
3580  
3581  /**
3582   * @global object
3583   * @global object
3584   * @param int $forumid
3585   * @param int $userid
3586   * @return array
3587   */
3588  function forum_discussions_user_has_posted_in($forumid, $userid) {
3589      global $CFG, $DB;
3590  
3591      $haspostedsql = "SELECT d.id AS id,
3592                              d.*
3593                         FROM {forum_posts} p,
3594                              {forum_discussions} d
3595                        WHERE p.discussion = d.id
3596                          AND d.forum = ?
3597                          AND p.userid = ?";
3598  
3599      return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3600  }
3601  
3602  /**
3603   * @global object
3604   * @global object
3605   * @param int $forumid
3606   * @param int $did
3607   * @param int $userid
3608   * @return bool
3609   */
3610  function forum_user_has_posted($forumid, $did, $userid) {
3611      global $DB;
3612  
3613      if (empty($did)) {
3614          // posted in any forum discussion?
3615          $sql = "SELECT 'x'
3616                    FROM {forum_posts} p
3617                    JOIN {forum_discussions} d ON d.id = p.discussion
3618                   WHERE p.userid = :userid AND d.forum = :forumid";
3619          return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3620      } else {
3621          return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3622      }
3623  }
3624  
3625  /**
3626   * Returns creation time of the first user's post in given discussion
3627   * @global object $DB
3628   * @param int $did Discussion id
3629   * @param int $userid User id
3630   * @return int|bool post creation time stamp or return false
3631   */
3632  function forum_get_user_posted_time($did, $userid) {
3633      global $DB;
3634  
3635      $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3636      if (empty($posttime)) {
3637          return false;
3638      }
3639      return $posttime;
3640  }
3641  
3642  /**
3643   * @global object
3644   * @param object $forum
3645   * @param object $currentgroup
3646   * @param int $unused
3647   * @param object $cm
3648   * @param object $context
3649   * @return bool
3650   */
3651  function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3652  // $forum is an object
3653      global $USER;
3654  
3655      // shortcut - guest and not-logged-in users can not post
3656      if (isguestuser() or !isloggedin()) {
3657          return false;
3658      }
3659  
3660      if (!$cm) {
3661          debugging('missing cm', DEBUG_DEVELOPER);
3662          if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3663