2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') || die();
25 /** Include required files */
26 require_once(__DIR__ . '/deprecatedlib.php');
27 require_once($CFG->libdir.'/filelib.php');
29 /// CONSTANTS ///////////////////////////////////////////////////////////
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_MODERN', 4);
37 define('FORUM_CHOOSESUBSCRIBE', 0);
38 define('FORUM_FORCESUBSCRIBE', 1);
39 define('FORUM_INITIALSUBSCRIBE', 2);
40 define('FORUM_DISALLOWSUBSCRIBE',3);
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
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);
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
70 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
72 define('FORUM_DISCUSSION_PINNED', 1);
73 define('FORUM_DISCUSSION_UNPINNED', 0);
75 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
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.
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
85 * @return int intance id
87 function forum_add_instance($forum, $mform = null) {
90 require_once($CFG->dirroot.'/mod/forum/locallib.php');
92 $forum->timemodified = time();
94 if (empty($forum->assessed)) {
98 if (empty($forum->ratingtime) or empty($forum->assessed)) {
99 $forum->assesstimestart = 0;
100 $forum->assesstimefinish = 0;
103 $forum->id = $DB->insert_record('forum', $forum);
104 $modcontext = context_module::instance($forum->coursemodule);
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;
120 $discussion->id = forum_add_discussion($discussion, null, $message);
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);
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));
133 forum_update_calendar($forum, $forum->coursemodule);
134 forum_grade_item_update($forum);
136 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
137 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
143 * Handle changes following the creation of a forum instance.
144 * This function is typically called by the course_module_created observer.
146 * @param object $context the forum context
147 * @param stdClass $forum The forum object
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);
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.
165 * @param object $forum forum instance (with magic quotes)
166 * @return bool success
168 function forum_update_instance($forum, $mform) {
169 global $CFG, $DB, $OUTPUT, $USER;
171 require_once($CFG->dirroot.'/mod/forum/locallib.php');
173 $forum->timemodified = time();
174 $forum->id = $forum->instance;
176 if (empty($forum->assessed)) {
177 $forum->assessed = 0;
180 if (empty($forum->ratingtime) or empty($forum->assessed)) {
181 $forum->assesstimestart = 0;
182 $forum->assesstimefinish = 0;
185 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
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 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
191 forum_update_grades($forum); // recalculate grades for the forum
194 if ($forum->type == 'single') { // Update related discussion and post.
195 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
196 if (!empty($discussions)) {
197 if (count($discussions) > 1) {
198 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
200 $discussion = array_pop($discussions);
202 // try to recover by creating initial discussion - MDL-16262
203 $discussion = new stdClass();
204 $discussion->course = $forum->course;
205 $discussion->forum = $forum->id;
206 $discussion->name = $forum->name;
207 $discussion->assessed = $forum->assessed;
208 $discussion->message = $forum->intro;
209 $discussion->messageformat = $forum->introformat;
210 $discussion->messagetrust = true;
211 $discussion->mailnow = false;
212 $discussion->groupid = -1;
216 forum_add_discussion($discussion, null, $message);
218 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
219 print_error('cannotadd', 'forum');
222 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
223 print_error('cannotfindfirstpost', 'forum');
226 $cm = get_coursemodule_from_instance('forum', $forum->id);
227 $modcontext = context_module::instance($cm->id, MUST_EXIST);
229 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
230 $post->subject = $forum->name;
231 $post->message = $forum->intro;
232 $post->messageformat = $forum->introformat;
233 $post->messagetrust = trusttext_trusted($modcontext);
234 $post->modified = $forum->timemodified;
235 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
237 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
238 // Ugly hack - we need to copy the files somehow.
239 $options = array('subdirs'=>true); // Use the same options as intro field!
240 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
243 \mod_forum\local\entities\post::add_message_counts($post);
244 $DB->update_record('forum_posts', $post);
245 $discussion->name = $forum->name;
246 $DB->update_record('forum_discussions', $discussion);
249 $DB->update_record('forum', $forum);
251 $modcontext = context_module::instance($forum->coursemodule);
252 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
253 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
254 foreach ($users as $user) {
255 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
259 forum_update_calendar($forum, $forum->coursemodule);
260 forum_grade_item_update($forum);
262 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
263 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
270 * Given an ID of an instance of this module,
271 * this function will permanently delete the instance
272 * and any data that depends on it.
275 * @param int $id forum instance id
276 * @return bool success
278 function forum_delete_instance($id) {
281 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
284 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
287 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
291 $context = context_module::instance($cm->id);
293 // now get rid of all files
294 $fs = get_file_storage();
295 $fs->delete_area_files($context->id);
299 \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
301 // Delete digest and subscription preferences.
302 $DB->delete_records('forum_digests', array('forum' => $forum->id));
303 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
304 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
306 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
307 foreach ($discussions as $discussion) {
308 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
314 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
316 forum_grade_item_delete($forum);
318 // We must delete the module record after we delete the grade item.
319 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
328 * Indicates API features that the forum supports.
330 * @uses FEATURE_GROUPS
331 * @uses FEATURE_GROUPINGS
332 * @uses FEATURE_MOD_INTRO
333 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
334 * @uses FEATURE_COMPLETION_HAS_RULES
335 * @uses FEATURE_GRADE_HAS_GRADE
336 * @uses FEATURE_GRADE_OUTCOMES
337 * @param string $feature
338 * @return mixed True if yes (some features may use other values)
340 function forum_supports($feature) {
342 case FEATURE_GROUPS: return true;
343 case FEATURE_GROUPINGS: return true;
344 case FEATURE_MOD_INTRO: return true;
345 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
346 case FEATURE_COMPLETION_HAS_RULES: return true;
347 case FEATURE_GRADE_HAS_GRADE: return true;
348 case FEATURE_GRADE_OUTCOMES: return true;
349 case FEATURE_RATE: return true;
350 case FEATURE_BACKUP_MOODLE2: return true;
351 case FEATURE_SHOW_DESCRIPTION: return true;
352 case FEATURE_PLAGIARISM: return true;
354 default: return null;
360 * Obtains the automatic completion state for this forum based on any conditions
365 * @param object $course Course
366 * @param object $cm Course-module
367 * @param int $userid User ID
368 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
369 * @return bool True if completed, false if not. (If no conditions, then return
370 * value depends on comparison type)
372 function forum_get_completion_state($course,$cm,$userid,$type) {
376 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
377 throw new Exception("Can't find forum {$cm->instance}");
380 $result=$type; // Default return value
382 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
388 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
390 fp.userid=:userid AND fd.forum=:forumid";
392 if ($forum->completiondiscussions) {
393 $value = $forum->completiondiscussions <=
394 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
395 if ($type == COMPLETION_AND) {
396 $result = $result && $value;
398 $result = $result || $value;
401 if ($forum->completionreplies) {
402 $value = $forum->completionreplies <=
403 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
404 if ($type==COMPLETION_AND) {
405 $result = $result && $value;
407 $result = $result || $value;
410 if ($forum->completionposts) {
411 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
412 if ($type == COMPLETION_AND) {
413 $result = $result && $value;
415 $result = $result || $value;
423 * Create a message-id string to use in the custom headers of forum notification emails
425 * message-id is used by email clients to identify emails and to nest conversations
427 * @param int $postid The ID of the forum post we are notifying the user about
428 * @param int $usertoid The ID of the user being notified
429 * @return string A unique message-id
431 function forum_get_email_message_id($postid, $usertoid) {
432 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
437 * @param object $course
438 * @param object $user
439 * @param object $mod TODO this is not used in this function, refactor
440 * @param object $forum
441 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
443 function forum_user_outline($course, $user, $mod, $forum) {
445 require_once("$CFG->libdir/gradelib.php");
446 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
447 if (empty($grades->items[0]->grades)) {
450 $grade = reset($grades->items[0]->grades);
453 $count = forum_count_user_posts($forum->id, $user->id);
455 if ($count && $count->postcount > 0) {
456 $result = new stdClass();
457 $result->info = get_string("numposts", "forum", $count->postcount);
458 $result->time = $count->lastpost;
460 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
461 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
463 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
469 'time' => grade_get_date_for_user_grade($grade, $user),
471 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
472 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
474 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
486 * @param object $coure
487 * @param object $user
489 * @param object $forum
491 function forum_user_complete($course, $user, $mod, $forum) {
492 global $CFG,$USER, $OUTPUT;
493 require_once("$CFG->libdir/gradelib.php");
495 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
496 if (!empty($grades->items[0]->grades)) {
497 $grade = reset($grades->items[0]->grades);
498 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
499 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
500 if ($grade->str_feedback) {
501 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
504 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
508 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
510 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
511 print_error('invalidcoursemodule');
513 $context = context_module::instance($cm->id);
514 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
515 $posts = array_filter($posts, function($post) use ($discussions) {
516 return isset($discussions[$post->discussion]);
518 $entityfactory = mod_forum\local\container::get_entity_factory();
519 $rendererfactory = mod_forum\local\container::get_renderer_factory();
520 $postrenderer = $rendererfactory->get_posts_renderer();
522 echo $postrenderer->render(
524 [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
525 array_map(function($discussion) use ($entityfactory) {
526 return $entityfactory->get_discussion_from_stdclass($discussion);
528 array_map(function($post) use ($entityfactory) {
529 return $entityfactory->get_post_from_stdclass($post);
533 echo "<p>".get_string("noposts", "forum")."</p>";
538 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
540 function forum_filter_user_groups_discussions() {
541 throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.');
545 * Returns whether the discussion group is visible by the current user or not.
547 * @since Moodle 2.8, 2.7.1, 2.6.4
548 * @param cm_info $cm The discussion course module
549 * @param int $discussiongroupid The discussion groupid
552 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
554 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
562 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
563 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
571 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
573 function forum_print_overview() {
574 throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.');
578 * Given a course and a date, prints a summary of all the new
579 * messages posted in the course since that date
584 * @uses CONTEXT_MODULE
585 * @uses VISIBLEGROUPS
586 * @param object $course
587 * @param bool $viewfullnames capability
588 * @param int $timestart
589 * @return bool success
591 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
592 global $CFG, $USER, $DB, $OUTPUT;
594 // do not use log table if possible, it may be huge and is expensive to join with other tables
596 $allnamefields = user_picture::fields('u', null, 'duserid');
597 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
598 d.timestart, d.timeend, $allnamefields
600 JOIN {forum_discussions} d ON d.id = p.discussion
601 JOIN {forum} f ON f.id = d.forum
602 JOIN {user} u ON u.id = p.userid
603 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
604 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
608 $modinfo = get_fast_modinfo($course);
610 $groupmodes = array();
613 $strftimerecent = get_string('strftimerecent');
615 $printposts = array();
616 foreach ($posts as $post) {
617 if (!isset($modinfo->instances['forum'][$post->forum])) {
621 $cm = $modinfo->instances['forum'][$post->forum];
622 if (!$cm->uservisible) {
625 $context = context_module::instance($cm->id);
627 if (!has_capability('mod/forum:viewdiscussion', $context)) {
631 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
632 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
633 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
638 if (!forum_post_is_visible_privately($post, $cm)) {
642 // Check that the user can see the discussion.
643 if (forum_is_user_group_discussion($cm, $post->groupid)) {
644 $printposts[] = $post;
654 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
655 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
657 foreach ($printposts as $post) {
658 $subjectclass = empty($post->parent) ? ' bold' : '';
659 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
661 $list .= html_writer::start_tag('li');
662 $list .= html_writer::start_div('head');
663 $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date');
664 if (!$authorhidden) {
665 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
667 $list .= html_writer::end_div(); // Head.
669 $list .= html_writer::start_div('info' . $subjectclass);
670 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
671 if (!empty($post->parent)) {
672 $discussionurl->param('parent', $post->parent);
673 $discussionurl->set_anchor('p'. $post->id);
675 $post->subject = break_up_long_words(format_string($post->subject, true));
676 $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']);
677 $list .= html_writer::end_div(); // Info.
678 $list .= html_writer::end_tag('li');
681 $list .= html_writer::end_tag('ul');
688 * Return grade for given user or all users.
692 * @param object $forum
693 * @param int $userid optional user id, 0 means all users
694 * @return array array of grades, false if none
696 function forum_get_user_grades($forum, $userid = 0) {
699 require_once($CFG->dirroot.'/rating/lib.php');
701 $ratingoptions = new stdClass;
702 $ratingoptions->component = 'mod_forum';
703 $ratingoptions->ratingarea = 'post';
705 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
706 $ratingoptions->modulename = 'forum';
707 $ratingoptions->moduleid = $forum->id;
708 $ratingoptions->userid = $userid;
709 $ratingoptions->aggregationmethod = $forum->assessed;
710 $ratingoptions->scaleid = $forum->scale;
711 $ratingoptions->itemtable = 'forum_posts';
712 $ratingoptions->itemtableusercolumn = 'userid';
714 $rm = new rating_manager();
715 return $rm->get_user_grades($ratingoptions);
719 * Update activity grades
722 * @param object $forum
723 * @param int $userid specific user only, 0 means all
724 * @param boolean $nullifnone return null if grade does not exist
727 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
729 require_once($CFG->libdir.'/gradelib.php');
731 if (!$forum->assessed) {
732 forum_grade_item_update($forum);
734 } else if ($grades = forum_get_user_grades($forum, $userid)) {
735 forum_grade_item_update($forum, $grades);
737 } else if ($userid and $nullifnone) {
738 $grade = new stdClass();
739 $grade->userid = $userid;
740 $grade->rawgrade = NULL;
741 forum_grade_item_update($forum, $grade);
744 forum_grade_item_update($forum);
749 * Create/update grade item for given forum
752 * @uses GRADE_TYPE_NONE
753 * @uses GRADE_TYPE_VALUE
754 * @uses GRADE_TYPE_SCALE
755 * @param stdClass $forum Forum object with extra cmidnumber
756 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
757 * @return int 0 if ok
759 function forum_grade_item_update($forum, $grades=NULL) {
761 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
762 require_once($CFG->libdir.'/gradelib.php');
765 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
767 if (!$forum->assessed or $forum->scale == 0) {
768 $params['gradetype'] = GRADE_TYPE_NONE;
770 } else if ($forum->scale > 0) {
771 $params['gradetype'] = GRADE_TYPE_VALUE;
772 $params['grademax'] = $forum->scale;
773 $params['grademin'] = 0;
775 } else if ($forum->scale < 0) {
776 $params['gradetype'] = GRADE_TYPE_SCALE;
777 $params['scaleid'] = -$forum->scale;
780 if ($grades === 'reset') {
781 $params['reset'] = true;
785 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
789 * Delete grade item for given forum
792 * @param stdClass $forum Forum object
795 function forum_grade_item_delete($forum) {
797 require_once($CFG->libdir.'/gradelib.php');
799 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
803 * Checks if scale is being used by any instance of forum
805 * This is used to find out if scale used anywhere
808 * @param $scaleid int
809 * @return boolean True if the scale is used by any forum
811 function forum_scale_used_anywhere($scaleid) {
813 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
820 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
823 * Gets a post with all info ready for forum_print_post
824 * Most of these joins are just to get the forum id
829 * @return mixed array of posts or false
831 function forum_get_post_full($postid) {
834 $allnames = get_all_user_name_fields(true, 'u');
835 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
837 JOIN {forum_discussions} d ON p.discussion = d.id
838 LEFT JOIN {user} u ON p.userid = u.id
839 WHERE p.id = ?", array($postid));
843 * Gets all posts in discussion including top parent.
845 * @param int $discussionid The Discussion to fetch.
846 * @param string $sort The sorting to apply.
847 * @param bool $tracking Whether the user tracks this forum.
848 * @return array The posts in the discussion.
850 function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) {
851 global $CFG, $DB, $USER;
858 $tr_sel = ", fr.id AS postread";
859 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
860 $params[] = $USER->id;
863 $allnames = get_all_user_name_fields(true, 'u');
864 $params[] = $discussionid;
865 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
867 LEFT JOIN {user} u ON p.userid = u.id
869 WHERE p.discussion = ?
870 ORDER BY $sort", $params)) {
874 foreach ($posts as $pid=>$p) {
876 if (forum_tp_is_post_old($p)) {
877 $posts[$pid]->postread = true;
883 if (!isset($posts[$p->parent])) {
884 continue; // parent does not exist??
886 if (!isset($posts[$p->parent]->children)) {
887 $posts[$p->parent]->children = array();
889 $posts[$p->parent]->children[$pid] =& $posts[$pid];
892 // Start with the last child of the first post.
893 $post = &$posts[reset($posts)->id];
897 if (!isset($post->children)) {
898 $post->lastpost = true;
901 // Go to the last child of this post.
902 $post = &$posts[end($post->children)->id];
910 * An array of forum objects that the user is allowed to read/search through.
916 * @param int $courseid if 0, we look for forums throughout the whole site.
917 * @return array of forum objects, or false if no matches
918 * Forum objects have the following attributes:
919 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
920 * viewhiddentimedposts
922 function forum_get_readable_forums($userid, $courseid=0) {
924 global $CFG, $DB, $USER;
925 require_once($CFG->dirroot.'/course/lib.php');
927 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
928 print_error('notinstalled', 'forum');
932 $courses = $DB->get_records('course', array('id' => $courseid));
934 // If no course is specified, then the user can see SITE + his courses.
935 $courses1 = $DB->get_records('course', array('id' => SITEID));
936 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
937 $courses = array_merge($courses1, $courses2);
943 $readableforums = array();
945 foreach ($courses as $course) {
947 $modinfo = get_fast_modinfo($course);
949 if (empty($modinfo->instances['forum'])) {
954 $courseforums = $DB->get_records('forum', array('course' => $course->id));
956 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
957 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
960 $context = context_module::instance($cm->id);
961 $forum = $courseforums[$forumid];
962 $forum->context = $context;
965 if (!has_capability('mod/forum:viewdiscussion', $context)) {
970 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
972 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
973 $forum->onlygroups[] = -1;
976 /// hidden timed discussions
977 $forum->viewhiddentimedposts = true;
978 if (!empty($CFG->forum_enabletimedposts)) {
979 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
980 $forum->viewhiddentimedposts = false;
985 if ($forum->type == 'qanda'
986 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
988 // We need to check whether the user has posted in the qanda forum.
989 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
990 // the user is allowed to see in this forum.
991 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
992 foreach ($discussionspostedin as $d) {
993 $forum->onlydiscussions[] = $d->id;
998 $readableforums[$forum->id] = $forum;
1003 } // End foreach $courses
1005 return $readableforums;
1009 * Returns a list of posts found using an array of search terms.
1014 * @param array $searchterms array of search terms, e.g. word +word -word
1015 * @param int $courseid if 0, we search through the whole site
1016 * @param int $limitfrom
1017 * @param int $limitnum
1018 * @param int &$totalcount
1019 * @param string $extrasql
1020 * @return array|bool Array of posts found or false
1022 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
1023 &$totalcount, $extrasql='') {
1024 global $CFG, $DB, $USER;
1025 require_once($CFG->libdir.'/searchlib.php');
1027 $forums = forum_get_readable_forums($USER->id, $courseid);
1029 if (count($forums) == 0) {
1034 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1036 $fullaccess = array();
1040 foreach ($forums as $forumid => $forum) {
1043 if (!$forum->viewhiddentimedposts) {
1044 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1045 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1049 $context = $forum->context;
1051 if ($forum->type == 'qanda'
1052 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1053 if (!empty($forum->onlydiscussions)) {
1054 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
1055 $params = array_merge($params, $discussionid_params);
1056 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1058 $select[] = "p.parent = 0";
1062 if (!empty($forum->onlygroups)) {
1063 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
1064 $params = array_merge($params, $groupid_params);
1065 $select[] = "d.groupid $groupid_sql";
1069 $selects = implode(" AND ", $select);
1070 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1071 $params['forum'.$forumid] = $forumid;
1073 $fullaccess[] = $forumid;
1078 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
1079 $params = array_merge($params, $fullid_params);
1080 $where[] = "(d.forum $fullid_sql)";
1084 if (in_array('starredonly:on', $searchterms)) {
1085 $usercontext = context_user::instance($USER->id);
1086 $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1087 list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions',
1088 "favourited", "d.id");
1090 $searchterms = array_values(array_diff($searchterms, array('starredonly:on')));
1091 $params = array_merge($params, $favparams);
1092 $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0";
1095 $selectdiscussion = "(".implode(" OR ", $where).")";
1097 $messagesearch = '';
1100 // Need to concat these back together for parser to work.
1101 foreach($searchterms as $searchterm){
1102 if ($searchstring != '') {
1103 $searchstring .= ' ';
1105 $searchstring .= $searchterm;
1108 // We need to allow quoted strings for the search. The quotes *should* be stripped
1109 // by the parser, but this should be examined carefully for security implications.
1110 $searchstring = str_replace("\\\"","\"",$searchstring);
1111 $parser = new search_parser();
1112 $lexer = new search_lexer($parser);
1114 if ($lexer->parse($searchstring)) {
1115 $parsearray = $parser->get_parsed_array();
1121 foreach ($parsearray as $token) {
1122 if ($token->getType() == TOKEN_TAGS) {
1123 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
1124 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1125 if ($tagfieldcount > 10) {
1128 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
1129 ON p.id = ti_$tagfieldcount.itemid
1130 AND ti_$tagfieldcount.component = 'mod_forum'
1131 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
1132 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1133 $tagfields[] = "t_$tagfieldcount.rawname";
1138 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1139 'p.userid', 'u.id', 'u.firstname',
1140 'u.lastname', 'p.modified', 'd.forum',
1143 $params = ($msparams ? array_merge($params, $msparams) : $params);
1147 $fromsql = "{forum_posts} p
1148 INNER JOIN {forum_discussions} d ON d.id = p.discussion
1149 INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin";
1151 $selectsql = ($messagesearch ? $messagesearch . " AND " : "").
1152 " p.discussion = d.id
1154 AND $selectdiscussion
1157 $countsql = "SELECT COUNT(*)
1161 $allnames = get_all_user_name_fields(true, 'u');
1162 $searchsql = "SELECT p.*,
1170 ORDER BY p.modified DESC";
1172 $totalcount = $DB->count_records_sql($countsql, $params);
1174 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
1178 * Get all the posts for a user in a forum suitable for forum_print_post
1182 * @uses CONTEXT_MODULE
1185 function forum_get_user_posts($forumid, $userid) {
1189 $params = array($forumid, $userid);
1191 if (!empty($CFG->forum_enabletimedposts)) {
1192 $cm = get_coursemodule_from_instance('forum', $forumid);
1193 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1195 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1201 $allnames = get_all_user_name_fields(true, 'u');
1202 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1204 JOIN {forum_discussions} d ON d.forum = f.id
1205 JOIN {forum_posts} p ON p.discussion = d.id
1206 JOIN {user} u ON u.id = p.userid
1210 ORDER BY p.modified ASC", $params);
1214 * Get all the discussions user participated in
1218 * @uses CONTEXT_MODULE
1219 * @param int $forumid
1220 * @param int $userid
1221 * @return array Array or false
1223 function forum_get_user_involved_discussions($forumid, $userid) {
1227 $params = array($forumid, $userid);
1228 if (!empty($CFG->forum_enabletimedposts)) {
1229 $cm = get_coursemodule_from_instance('forum', $forumid);
1230 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1232 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1238 return $DB->get_records_sql("SELECT DISTINCT d.*
1240 JOIN {forum_discussions} d ON d.forum = f.id
1241 JOIN {forum_posts} p ON p.discussion = d.id
1244 $timedsql", $params);
1248 * Get all the posts for a user in a forum suitable for forum_print_post
1252 * @param int $forumid
1253 * @param int $userid
1254 * @return array of counts or false
1256 function forum_count_user_posts($forumid, $userid) {
1260 $params = array($forumid, $userid);
1261 if (!empty($CFG->forum_enabletimedposts)) {
1262 $cm = get_coursemodule_from_instance('forum', $forumid);
1263 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1265 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1271 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1273 JOIN {forum_discussions} d ON d.forum = f.id
1274 JOIN {forum_posts} p ON p.discussion = d.id
1275 JOIN {user} u ON u.id = p.userid
1278 $timedsql", $params);
1282 * Given a log entry, return the forum post details for it.
1286 * @param object $log
1287 * @return array|null
1289 function forum_get_post_from_log($log) {
1292 $allnames = get_all_user_name_fields(true, 'u');
1293 if ($log->action == "add post") {
1295 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1296 FROM {forum_discussions} d,
1301 AND d.id = p.discussion
1303 AND u.deleted <> '1'
1304 AND f.id = d.forum", array($log->info));
1307 } else if ($log->action == "add discussion") {
1309 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1310 FROM {forum_discussions} d,
1315 AND d.firstpost = p.id
1317 AND u.deleted <> '1'
1318 AND f.id = d.forum", array($log->info));
1324 * Given a discussion id, return the first post from the discussion
1328 * @param int $dicsussionid
1331 function forum_get_firstpost_from_discussion($discussionid) {
1334 return $DB->get_record_sql("SELECT p.*
1335 FROM {forum_discussions} d,
1338 AND d.firstpost = p.id ", array($discussionid));
1342 * Returns an array of counts of replies to each discussion
1344 * @param int $forumid
1345 * @param string $forumsort
1348 * @param int $perpage
1349 * @param boolean $canseeprivatereplies Whether the current user can see private replies.
1352 function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0,
1353 $canseeprivatereplies = false) {
1354 global $CFG, $DB, $USER;
1359 } else if ($page != -1) {
1360 $limitfrom = $page*$perpage;
1361 $limitnum = $perpage;
1367 if ($forumsort == "") {
1372 $orderby = "ORDER BY $forumsort";
1373 $groupby = ", ".strtolower($forumsort);
1374 $groupby = str_replace('desc', '', $groupby);
1375 $groupby = str_replace('asc', '', $groupby);
1378 $params = ['forumid' => $forumid];
1380 if (!$canseeprivatereplies) {
1381 $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)';
1382 $params['currentuser1'] = $USER->id;
1383 $params['currentuser2'] = $USER->id;
1388 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1389 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
1390 FROM {forum_posts} p
1391 JOIN {forum_discussions} d ON p.discussion = d.id
1392 WHERE p.parent > 0 AND d.forum = :forumid
1394 GROUP BY p.discussion";
1395 return $DB->get_records_sql($sql, $params);
1398 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
1399 FROM {forum_posts} p
1400 JOIN {forum_discussions} d ON p.discussion = d.id
1401 WHERE d.forum = :forumid
1403 GROUP BY p.discussion $groupby $orderby";
1404 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1412 * @staticvar array $cache
1413 * @param object $forum
1415 * @param object $course
1418 function forum_count_discussions($forum, $cm, $course) {
1419 global $CFG, $DB, $USER;
1421 static $cache = array();
1423 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1425 $params = array($course->id);
1427 if (!isset($cache[$course->id])) {
1428 if (!empty($CFG->forum_enabletimedposts)) {
1429 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1436 $sql = "SELECT f.id, COUNT(d.id) as dcount
1438 JOIN {forum_discussions} d ON d.forum = f.id
1443 if ($counts = $DB->get_records_sql($sql, $params)) {
1444 foreach ($counts as $count) {
1445 $counts[$count->id] = $count->dcount;
1447 $cache[$course->id] = $counts;
1449 $cache[$course->id] = array();
1453 if (empty($cache[$course->id][$forum->id])) {
1457 $groupmode = groups_get_activity_groupmode($cm, $course);
1459 if ($groupmode != SEPARATEGROUPS) {
1460 return $cache[$course->id][$forum->id];
1463 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
1464 return $cache[$course->id][$forum->id];
1467 require_once($CFG->dirroot.'/course/lib.php');
1469 $modinfo = get_fast_modinfo($course);
1471 $mygroups = $modinfo->get_groups($cm->groupingid);
1473 // add all groups posts
1476 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1477 $params[] = $forum->id;
1479 if (!empty($CFG->forum_enabletimedposts)) {
1480 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
1487 $sql = "SELECT COUNT(d.id)
1488 FROM {forum_discussions} d
1489 WHERE d.groupid $mygroups_sql AND d.forum = ?
1492 return $DB->get_field_sql($sql, $params);
1496 * Get all discussions in a forum
1501 * @uses CONTEXT_MODULE
1502 * @uses VISIBLEGROUPS
1504 * @param string $forumsort
1505 * @param bool $fullpost
1506 * @param int $unused
1508 * @param bool $userlastmodified
1510 * @param int $perpage
1511 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1512 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
1513 * @param int $updatedsince retrieve only discussions updated since the given time
1516 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
1517 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
1518 $updatedsince = 0) {
1519 global $CFG, $DB, $USER;
1523 $now = floor(time() / 60) * 60;
1524 $params = array($cm->instance);
1526 $modcontext = context_module::instance($cm->id);
1528 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1532 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
1534 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1535 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1539 $timelimit .= " OR d.userid = ?";
1540 $params[] = $USER->id;
1549 } else if ($page != -1) {
1550 $limitfrom = $page*$perpage;
1551 $limitnum = $perpage;
1557 $groupmode = groups_get_activity_groupmode($cm);
1561 if (empty($modcontext)) {
1562 $modcontext = context_module::instance($cm->id);
1565 // Special case, we received a groupid to override currentgroup.
1567 $course = get_course($cm->course);
1568 if (!groups_group_visible($groupid, $course, $cm)) {
1569 // User doesn't belong to this group, return nothing.
1572 $currentgroup = $groupid;
1573 } else if ($groupid === -1) {
1574 $currentgroup = groups_get_activity_group($cm);
1576 // Get discussions for all groups current user can see.
1577 $currentgroup = null;
1580 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1581 if ($currentgroup) {
1582 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1583 $params[] = $currentgroup;
1591 // Get discussions for all groups current user can see.
1592 if ($currentgroup === null) {
1593 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
1594 if (empty($mygroups)) {
1595 $groupselect = "AND d.groupid = -1";
1597 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1598 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1599 $params = array_merge($params, $inparamsgroups);
1601 } else if ($currentgroup) {
1602 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1603 $params[] = $currentgroup;
1605 $groupselect = "AND d.groupid = -1";
1611 if (empty($forumsort)) {
1612 $forumsort = forum_get_default_sort_order();
1614 if (empty($fullpost)) {
1615 $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
1620 if (empty($userlastmodified)) { // We don't need to know this
1624 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
1625 um.imagealt AS umimagealt';
1626 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
1629 $updatedsincesql = '';
1630 if (!empty($updatedsince)) {
1631 $updatedsincesql = 'AND d.timemodified > ?';
1632 $params[] = $updatedsince;
1635 $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
1636 " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked";
1638 $allnames = get_all_user_name_fields(true, 'u');
1639 $sql = "SELECT $postdata, $discussionfields,
1640 $allnames, u.email, u.picture, u.imagealt $umfields
1641 FROM {forum_discussions} d
1642 JOIN {forum_posts} p ON p.discussion = d.id
1643 JOIN {user} u ON p.userid = u.id
1645 WHERE d.forum = ? AND p.parent = 0
1646 $timelimit $groupselect $updatedsincesql
1647 ORDER BY $forumsort, d.id DESC";
1649 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1653 * Gets the neighbours (previous and next) of a discussion.
1655 * The calculation is based on the timemodified when time modified or time created is identical
1656 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
1658 * For blog-style forums, the calculation is based on the original creation time of the
1661 * Please note that this does not check whether or not the discussion passed is accessible
1662 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1663 * the returned neighbours are checked and are accessible to the current user.
1665 * @param object $cm The CM record.
1666 * @param object $discussion The discussion record.
1667 * @param object $forum The forum instance record.
1668 * @return array That always contains the keys 'prev' and 'next'. When there is a result
1669 * they contain the record with minimal information such as 'id' and 'name'.
1670 * When the neighbour is not found the value is false.
1672 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
1673 global $CFG, $DB, $USER;
1675 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
1676 throw new coding_exception('Discussion is not part of the same forum.');
1679 $neighbours = array('prev' => false, 'next' => false);
1680 $now = floor(time() / 60) * 60;
1683 $modcontext = context_module::instance($cm->id);
1684 $groupmode = groups_get_activity_groupmode($cm);
1685 $currentgroup = groups_get_activity_group($cm);
1687 // Users must fulfill timed posts.
1689 if (!empty($CFG->forum_enabletimedposts)) {
1690 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1691 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1692 $params['tltimestart'] = $now;
1693 $params['tltimeend'] = $now;
1695 $timelimit .= ' OR d.userid = :tluserid';
1696 $params['tluserid'] = $USER->id;
1702 // Limiting to posts accessible according to groups.
1705 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
1706 if ($currentgroup) {
1707 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1708 $params['groupid'] = $currentgroup;
1711 if ($currentgroup) {
1712 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1713 $params['groupid'] = $currentgroup;
1715 $groupselect = 'AND d.groupid = -1';
1720 $params['forumid'] = $cm->instance;
1721 $params['discid1'] = $discussion->id;
1722 $params['discid2'] = $discussion->id;
1723 $params['discid3'] = $discussion->id;
1724 $params['discid4'] = $discussion->id;
1725 $params['disctimecompare1'] = $discussion->timemodified;
1726 $params['disctimecompare2'] = $discussion->timemodified;
1727 $params['pinnedstate1'] = (int) $discussion->pinned;
1728 $params['pinnedstate2'] = (int) $discussion->pinned;
1729 $params['pinnedstate3'] = (int) $discussion->pinned;
1730 $params['pinnedstate4'] = (int) $discussion->pinned;
1732 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1733 FROM {forum_discussions} d
1734 JOIN {forum_posts} p ON d.firstpost = p.id
1735 WHERE d.forum = :forumid
1736 AND d.id <> :discid1
1739 $comparefield = "d.timemodified";
1740 $comparevalue = ":disctimecompare1";
1741 $comparevalue2 = ":disctimecompare2";
1742 if (!empty($CFG->forum_enabletimedposts)) {
1743 // Here we need to take into account the release time (timestart)
1744 // if one is set, of the neighbouring posts and compare it to the
1745 // timestart or timemodified of *this* post depending on if the
1746 // release date of this post is in the future or not.
1747 // This stops discussions that appear later because of the
1748 // timestart value from being buried under discussions that were
1750 $comparefield = "CASE WHEN d.timemodified < d.timestart
1751 THEN d.timestart ELSE d.timemodified END";
1752 if ($discussion->timemodified < $discussion->timestart) {
1753 // Normally we would just use the timemodified for sorting
1754 // discussion posts. However, when timed discussions are enabled,
1755 // then posts need to be sorted base on the later of timemodified
1756 // or the release date of the post (timestart).
1757 $params['disctimecompare1'] = $discussion->timestart;
1758 $params['disctimecompare2'] = $discussion->timestart;
1761 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1762 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
1764 if ($forum->type === 'blog') {
1765 $subselect = "SELECT pp.created
1766 FROM {forum_discussions} dd
1767 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
1769 $subselectwhere1 = " WHERE dd.id = :discid3";
1770 $subselectwhere2 = " WHERE dd.id = :discid4";
1772 $comparefield = "p.created";
1774 $sub1 = $subselect.$subselectwhere1;
1775 $comparevalue = "($sub1)";
1777 $sub2 = $subselect.$subselectwhere2;
1778 $comparevalue2 = "($sub2)";
1780 $orderbydesc = "d.pinned, p.created DESC";
1781 $orderbyasc = "d.pinned, p.created ASC";
1784 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1785 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1786 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1787 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
1789 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1790 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1791 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1792 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
1794 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
1795 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
1800 * Get the sql to use in the ORDER BY clause for forum discussions.
1802 * This has the ordering take timed discussion windows into account.
1804 * @param bool $desc True for DESC, False for ASC.
1805 * @param string $compare The field in the SQL to compare to normally sort by.
1806 * @param string $prefix The prefix being used for the discussion table.
1807 * @param bool $pinned sort pinned posts to the top
1810 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1813 if (!empty($prefix)) {
1817 $dir = $desc ? 'DESC' : 'ASC';
1819 if ($pinned == true) {
1820 $pinned = "{$prefix}pinned DESC,";
1825 $sort = "{$prefix}timemodified";
1826 if (!empty($CFG->forum_enabletimedposts)) {
1827 $sort = "CASE WHEN {$compare} < {$prefix}timestart
1828 THEN {$prefix}timestart
1832 return "$pinned $sort $dir";
1840 * @uses CONTEXT_MODULE
1841 * @uses VISIBLEGROUPS
1845 function forum_get_discussions_unread($cm) {
1846 global $CFG, $DB, $USER;
1848 $now = floor(time() / 60) * 60;
1849 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
1852 $groupmode = groups_get_activity_groupmode($cm);
1853 $currentgroup = groups_get_activity_group($cm);
1856 $modcontext = context_module::instance($cm->id);
1858 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1859 if ($currentgroup) {
1860 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1861 $params['currentgroup'] = $currentgroup;
1867 //separate groups without access all
1868 if ($currentgroup) {
1869 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1870 $params['currentgroup'] = $currentgroup;
1872 $groupselect = "AND d.groupid = -1";
1879 if (!empty($CFG->forum_enabletimedposts)) {
1880 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
1881 $params['now1'] = $now;
1882 $params['now2'] = $now;
1887 $sql = "SELECT d.id, COUNT(p.id) AS unread
1888 FROM {forum_discussions} d
1889 JOIN {forum_posts} p ON p.discussion = d.id
1890 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
1891 WHERE d.forum = {$cm->instance}
1892 AND p.modified >= :cutoffdate AND r.id is NULL
1896 $params['cutoffdate'] = $cutoffdate;
1898 if ($unreads = $DB->get_records_sql($sql, $params)) {
1899 foreach ($unreads as $unread) {
1900 $unreads[$unread->id] = $unread->unread;
1912 * @uses CONEXT_MODULE
1913 * @uses VISIBLEGROUPS
1917 function forum_get_discussions_count($cm) {
1918 global $CFG, $DB, $USER;
1920 $now = floor(time() / 60) * 60;
1921 $params = array($cm->instance);
1922 $groupmode = groups_get_activity_groupmode($cm);
1923 $currentgroup = groups_get_activity_group($cm);
1926 $modcontext = context_module::instance($cm->id);
1928 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1929 if ($currentgroup) {
1930 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1931 $params[] = $currentgroup;
1937 //seprate groups without access all
1938 if ($currentgroup) {
1939 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1940 $params[] = $currentgroup;
1942 $groupselect = "AND d.groupid = -1";
1951 if (!empty($CFG->forum_enabletimedposts)) {
1953 $modcontext = context_module::instance($cm->id);
1955 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1956 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1960 $timelimit .= " OR d.userid = ?";
1961 $params[] = $USER->id;
1967 $sql = "SELECT COUNT(d.id)
1968 FROM {forum_discussions} d
1969 JOIN {forum_posts} p ON p.discussion = d.id
1970 WHERE d.forum = ? AND p.parent = 0
1971 $groupselect $timelimit";
1973 return $DB->get_field_sql($sql, $params);
1977 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
1983 * @param int $courseid
1984 * @param string $type
1986 function forum_get_course_forum($courseid, $type) {
1987 // How to set up special 1-per-course forums
1988 global $CFG, $DB, $OUTPUT, $USER;
1990 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
1991 // There should always only be ONE, but with the right combination of
1992 // errors there might be more. In this case, just return the oldest one (lowest ID).
1993 foreach ($forums as $forum) {
1994 return $forum; // ie the first one
1998 // Doesn't exist, so create one now.
1999 $forum = new stdClass();
2000 $forum->course = $courseid;
2001 $forum->type = "$type";
2002 if (!empty($USER->htmleditor)) {
2003 $forum->introformat = $USER->htmleditor;
2005 switch ($forum->type) {
2007 $forum->name = get_string("namenews", "forum");
2008 $forum->intro = get_string("intronews", "forum");
2009 $forum->introformat = FORMAT_HTML;
2010 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2011 $forum->assessed = 0;
2012 if ($courseid == SITEID) {
2013 $forum->name = get_string("sitenews");
2014 $forum->forcesubscribe = 0;
2018 $forum->name = get_string("namesocial", "forum");
2019 $forum->intro = get_string("introsocial", "forum");
2020 $forum->introformat = FORMAT_HTML;
2021 $forum->assessed = 0;
2022 $forum->forcesubscribe = 0;
2025 $forum->name = get_string('blogforum', 'forum');
2026 $forum->intro = get_string('introblog', 'forum');
2027 $forum->introformat = FORMAT_HTML;
2028 $forum->assessed = 0;
2029 $forum->forcesubscribe = 0;
2032 echo $OUTPUT->notification("That forum type doesn't exist!");
2037 $forum->timemodified = time();
2038 $forum->id = $DB->insert_record("forum", $forum);
2040 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2041 echo $OUTPUT->notification("Could not find forum module!!");
2044 $mod = new stdClass();
2045 $mod->course = $courseid;
2046 $mod->module = $module->id;
2047 $mod->instance = $forum->id;
2049 include_once("$CFG->dirroot/course/lib.php");
2050 if (! $mod->coursemodule = add_course_module($mod) ) {
2051 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2054 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
2055 return $DB->get_record("forum", array("id" => "$forum->id"));
2059 * Return rating related permissions
2061 * @param string $options the context id
2062 * @return array an associative array of the user's rating permissions
2064 function forum_rating_permissions($contextid, $component, $ratingarea) {
2065 $context = context::instance_by_id($contextid, MUST_EXIST);
2066 if ($component != 'mod_forum' || $ratingarea != 'post') {
2067 // We don't know about this component/ratingarea so just return null to get the
2068 // default restrictive permissions.
2072 'view' => has_capability('mod/forum:viewrating', $context),
2073 'viewany' => has_capability('mod/forum:viewanyrating', $context),
2074 'viewall' => has_capability('mod/forum:viewallratings', $context),
2075 'rate' => has_capability('mod/forum:rate', $context)
2080 * Validates a submitted rating
2081 * @param array $params submitted data
2082 * context => object the context in which the rated items exists [required]
2083 * component => The component for this module - should always be mod_forum [required]
2084 * ratingarea => object the context in which the rated items exists [required]
2086 * itemid => int the ID of the object being rated [required]
2087 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2088 * rating => int the submitted rating [required]
2089 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2090 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
2091 * @return boolean true if the rating is valid. Will throw rating_exception if not
2093 function forum_rating_validate($params) {
2096 // Check the component is mod_forum
2097 if ($params['component'] != 'mod_forum') {
2098 throw new rating_exception('invalidcomponent');
2101 // Check the ratingarea is post (the only rating area in forum)
2102 if ($params['ratingarea'] != 'post') {
2103 throw new rating_exception('invalidratingarea');
2106 // Check the rateduserid is not the current user .. you can't rate your own posts
2107 if ($params['rateduserid'] == $USER->id) {
2108 throw new rating_exception('nopermissiontorate');
2111 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2112 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
2113 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2114 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2115 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2116 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2117 $context = context_module::instance($cm->id);
2119 // Make sure the context provided is the context of the forum
2120 if ($context->id != $params['context']->id) {
2121 throw new rating_exception('invalidcontext');
2124 if ($forum->scale != $params['scaleid']) {
2125 //the scale being submitted doesnt match the one in the database
2126 throw new rating_exception('invalidscaleid');
2129 // check the item we're rating was created in the assessable time window
2130 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
2131 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
2132 throw new rating_exception('notavailable');
2136 //check that the submitted rating is valid for the scale
2139 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
2140 throw new rating_exception('invalidnum');
2144 if ($forum->scale < 0) {
2145 //its a custom scale
2146 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
2148 $scalearray = explode(',', $scalerecord->scale);
2149 if ($params['rating'] > count($scalearray)) {
2150 throw new rating_exception('invalidnum');
2153 throw new rating_exception('invalidscaleid');
2155 } else if ($params['rating'] > $forum->scale) {
2156 //if its numeric and submitted rating is above maximum
2157 throw new rating_exception('invalidnum');
2160 // Make sure groups allow this user to see the item they're rating
2161 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
2162 if (!groups_group_exists($discussion->groupid)) { // Can't find group
2163 throw new rating_exception('cannotfindgroup');//something is wrong
2166 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2167 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
2168 throw new rating_exception('notmemberofgroup');
2172 // perform some final capability checks
2173 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2174 throw new rating_exception('nopermissiontorate');
2181 * Can the current user see ratings for a given itemid?
2183 * @param array $params submitted data
2184 * contextid => int contextid [required]
2185 * component => The component for this module - should always be mod_forum [required]
2186 * ratingarea => object the context in which the rated items exists [required]
2187 * itemid => int the ID of the object being rated [required]
2188 * scaleid => int scale id [optional]
2190 * @throws coding_exception
2191 * @throws rating_exception
2193 function mod_forum_rating_can_see_item_ratings($params) {
2196 // Check the component is mod_forum.
2197 if (!isset($params['component']) || $params['component'] != 'mod_forum') {
2198 throw new rating_exception('invalidcomponent');
2201 // Check the ratingarea is post (the only rating area in forum).
2202 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
2203 throw new rating_exception('invalidratingarea');
2206 if (!isset($params['itemid'])) {
2207 throw new rating_exception('invaliditemid');
2210 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
2211 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2212 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2213 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2214 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2216 // Perform some final capability checks.
2217 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2225 * This function prints the overview of a discussion in the forum listing.
2226 * It needs some discussion information and some post information, these
2227 * happen to be combined for efficiency in the $post parameter by the function
2228 * that calls this one: forum_print_latest_discussions()
2232 * @param object $post The post object (passed by reference for speed).
2233 * @param object $forum The forum object.
2234 * @param int $group Current group.
2235 * @param string $datestring Format to use for the dates.
2236 * @param boolean $cantrack Is tracking enabled for this forum.
2237 * @param boolean $forumtracked Is the user tracking this forum.
2238 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
2239 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
2241 function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2242 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2243 $canviewhiddentimedposts = false) {
2245 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
2248 static $strmarkalldread;
2250 if (empty($modcontext)) {
2251 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2252 print_error('invalidcoursemodule');
2254 $modcontext = context_module::instance($cm->id);
2257 if (!isset($rowcount)) {
2259 $strmarkalldread = get_string('markalldread', 'forum');
2261 $rowcount = ($rowcount + 1) % 2;
2264 $post->subject = format_string($post->subject,true);
2266 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
2267 $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2268 $timedoutsidewindow = '';
2269 if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2270 $timedoutsidewindow = ' dimmed_text';
2274 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
2276 $topicclass = 'topic starter';
2277 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2278 $topicclass .= ' pinned';
2280 echo '<td class="'.$topicclass.'">';
2281 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2282 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2284 $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2285 if ($timeddiscussion && $canalwaysseetimedpost) {
2286 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2289 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
2293 $postuser = new stdClass();
2294 $postuserfields = explode(',', user_picture::fields());
2295 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
2296 $postuser->id = $post->userid;
2297 echo '<td class="author">';
2298 echo '<div class="media">';
2299 echo '<span class="float-left">';
2300 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
2303 echo '<div class="media-body">';
2304 $fullname = fullname($postuser, $canviewfullnames);
2305 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&course='.$forum->course.'">'.$fullname.'</a>';
2311 if ($group !== -1) { // Groups are active - group is a group data object or NULL
2312 echo '<td class="picture group">';
2313 if (!empty($group->picture) and empty($group->hidepicture)) {
2314 if ($canviewparticipants && $COURSE->groupmode) {
2315 $picturelink = true;
2317 $picturelink = false;
2319 print_group_picture($group, $forum->course, false, false, $picturelink);
2320 } else if (isset($group->id)) {
2321 if ($canviewparticipants && $COURSE->groupmode) {
2322 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&group='.$group->id.'">'.$group->name.'</a>';
2330 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
2331 echo '<td class="replies">';
2332 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2333 echo $post->replies.'</a>';
2337 echo '<td class="replies">';
2338 if ($forumtracked) {
2339 if ($post->unread > 0) {
2340 echo '<span class="unread">';
2341 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2344 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2345 $forum->id.'&d='.$post->discussion.'&mark=read&return=/mod/forum/view.php&sesskey=' .
2346 sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
2349 echo '<span class="read">';
2354 echo '<span class="read">';
2362 echo '<td class="lastpost">';
2363 $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
2365 $usermodified = new stdClass();
2366 $usermodified->id = $post->usermodified;
2367 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
2369 // In QA forums we check that the user can view participants.
2370 if ($forum->type !== 'qanda' || $canviewparticipants) {
2371 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&course='.$forum->course.'">'.
2372 fullname($usermodified, $canviewfullnames).'</a><br />';
2373 $parenturl = (empty($post->lastpostid)) ? '' : '&parent='.$post->lastpostid;
2376 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
2377 userdate_htmltime($usedate, $datestring).'</a>';
2380 // is_guest should be used here as this also checks whether the user is a guest in the current course.
2381 // Guests and visitors cannot subscribe - only enrolled users.
2382 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
2383 // Discussion subscription.
2384 if (\mod_forum\subscriptions::is_subscribable($forum)) {
2385 echo '<td class="discussionsubscription">';
2386 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2396 * Return the markup for the discussion subscription toggling icon.
2398 * @param stdClass $forum The forum object.
2399 * @param int $discussionid The discussion to create an icon for.
2400 * @return string The generated markup.
2402 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2403 global $USER, $OUTPUT, $PAGE;
2405 if ($returnurl === null && $PAGE->url) {
2406 $returnurl = $PAGE->url->out();
2410 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2411 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2412 'sesskey' => sesskey(),
2414 'd' => $discussionid,
2415 'returnurl' => $returnurl,
2419 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2422 if ($subscriptionstatus) {
2423 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2425 $output .= get_string('subscribed', 'mod_forum');
2428 return html_writer::link($subscriptionlink, $output, array(
2429 'title' => get_string('clicktounsubscribe', 'forum'),
2430 'class' => 'discussiontoggle btn btn-link',
2431 'data-forumid' => $forum->id,
2432 'data-discussionid' => $discussionid,
2433 'data-includetext' => $includetext,
2437 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2439 $output .= get_string('notsubscribed', 'mod_forum');
2442 return html_writer::link($subscriptionlink, $output, array(
2443 'title' => get_string('clicktosubscribe', 'forum'),
2444 'class' => 'discussiontoggle btn btn-link',
2445 'data-forumid' => $forum->id,
2446 'data-discussionid' => $discussionid,
2447 'data-includetext' => $includetext,
2453 * Return a pair of spans containing classes to allow the subscribe and
2454 * unsubscribe icons to be pre-loaded by a browser.
2456 * @return string The generated markup
2458 function forum_get_discussion_subscription_icon_preloaders() {
2460 $o .= html_writer::span(' ', 'preload-subscribe');
2461 $o .= html_writer::span(' ', 'preload-unsubscribe');
2466 * Print the drop down that allows the user to select how they want to have
2467 * the discussion displayed.
2469 * @param int $id forum id if $forumtype is 'single',
2470 * discussion id for any other forum type
2471 * @param mixed $mode forum layout mode
2472 * @param string $forumtype optional
2474 function forum_print_mode_form($id, $mode, $forumtype='') {
2476 if ($forumtype == 'single') {
2477 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
2478 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2479 $select->class = "forummode";
2481 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
2482 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2484 echo $OUTPUT->render($select);
2489 * @param object $course
2490 * @param string $search
2493 function forum_search_form($course, $search='') {
2495 $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2496 $output = $PAGE->get_renderer('mod_forum');
2497 return $output->render($forumsearch);
2505 function forum_set_return() {
2506 global $CFG, $SESSION;
2508 if (! isset($SESSION->fromdiscussion)) {
2509 $referer = get_local_referer(false);
2510 // If the referer is NOT a login screen then save it.
2511 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2512 $SESSION->fromdiscussion = $referer;
2520 * @param string|\moodle_url $default
2523 function forum_go_back_to($default) {
2526 if (!empty($SESSION->fromdiscussion)) {
2527 $returnto = $SESSION->fromdiscussion;
2528 unset($SESSION->fromdiscussion);
2536 * Given a discussion object that is being moved to $forumto,
2537 * this function checks all posts in that discussion
2538 * for attachments, and if any are found, these are
2539 * moved to the new forum directory.
2542 * @param object $discussion
2543 * @param int $forumfrom source forum id
2544 * @param int $forumto target forum id
2545 * @return bool success
2547 function forum_move_attachments($discussion, $forumfrom, $forumto) {
2550 $fs = get_file_storage();
2552 $newcm = get_coursemodule_from_instance('forum', $forumto);
2553 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2555 $newcontext = context_module::instance($newcm->id);
2556 $oldcontext = context_module::instance($oldcm->id);
2558 // loop through all posts, better not use attachment flag ;-)
2559 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
2560 foreach ($posts as $post) {
2561 $fs->move_area_files_to_new_context($oldcontext->id,
2562 $newcontext->id, 'mod_forum', 'post', $post->id);
2563 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2564 $newcontext->id, 'mod_forum', 'attachment', $post->id);
2565 if ($attachmentsmoved > 0 && $post->attachment != '1') {
2566 // Weird - let's fix it
2567 $post->attachment = '1';
2568 $DB->update_record('forum_posts', $post);
2569 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2570 // Weird - let's fix it
2571 $post->attachment = '';
2572 $DB->update_record('forum_posts', $post);
2581 * Returns attachments as formated text/html optionally with separate images
2586 * @param object $post
2588 * @param string $type html/text/separateimages
2589 * @return mixed string or array of (html text withouth images and image HTML)
2591 function forum_print_attachments($post, $cm, $type) {
2592 global $CFG, $DB, $USER, $OUTPUT;
2594 if (empty($post->attachment)) {
2595 return $type !== 'separateimages' ? '' : array('', '');
2598 if (!in_array($type, array('separateimages', 'html', 'text'))) {
2599 return $type !== 'separateimages' ? '' : array('', '');
2602 if (!$context = context_module::instance($cm->id)) {
2603 return $type !== 'separateimages' ? '' : array('', '');
2605 $strattachment = get_string('attachment', 'forum');
2607 $fs = get_file_storage();
2612 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
2615 require_once($CFG->libdir.'/portfoliolib.php');
2618 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
2619 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2620 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
2623 $button = new portfolio_add_button();
2625 foreach ($files as $file) {
2626 $filename = $file->get_filename();
2627 $mimetype = $file->get_mimetype();
2628 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2629 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2631 if ($type == 'html') {
2632 $output .= "<a href=\"$path\">$iconimage</a> ";
2633 $output .= "<a href=\"$path\">".s($filename)."</a>";
2635 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2636 $button->set_format_by_file($file);
2637 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2639 $output .= "<br />";
2641 } else if ($type == 'text') {
2642 $output .= "$strattachment ".s($filename).":\n$path\n";
2644 } else { //'returnimages'
2645 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2646 // Image attachments don't get printed as links
2647 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2649 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2650 $button->set_format_by_file($file);
2651 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2654 $output .= "<a href=\"$path\">$iconimage</a> ";
2655 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
2657 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2658 $button->set_format_by_file($file);
2659 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2661 $output .= '<br />';
2665 if (!empty($CFG->enableplagiarism)) {
2666 require_once($CFG->libdir.'/plagiarismlib.php');
2667 $output .= plagiarism_get_links(array('userid' => $post->userid,
2670 'course' => $cm->course,
2671 'forum' => $cm->instance));
2672 $output .= '<br />';
2677 if ($type !== 'separateimages') {
2681 return array($output, $imagereturn);
2685 ////////////////////////////////////////////////////////////////////////////////
2687 ////////////////////////////////////////////////////////////////////////////////
2690 * Lists all browsable file areas
2692 * @package mod_forum
2694 * @param stdClass $course course object
2695 * @param stdClass $cm course module object
2696 * @param stdClass $context context object
2699 function forum_get_file_areas($course, $cm, $context) {
2701 'attachment' => get_string('areaattachment', 'mod_forum'),
2702 'post' => get_string('areapost', 'mod_forum'),
2707 * File browsing support for forum module.
2709 * @package mod_forum
2711 * @param stdClass $browser file browser object
2712 * @param stdClass $areas file areas
2713 * @param stdClass $course course object
2714 * @param stdClass $cm course module
2715 * @param stdClass $context context module
2716 * @param string $filearea file area
2717 * @param int $itemid item ID
2718 * @param string $filepath file path
2719 * @param string $filename file name
2720 * @return file_info instance or null if not found
2722 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2723 global $CFG, $DB, $USER;
2725 if ($context->contextlevel != CONTEXT_MODULE) {
2729 // filearea must contain a real area
2730 if (!isset($areas[$filearea])) {
2734 // Note that forum_user_can_see_post() additionally allows access for parent roles
2735 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2736 // course:managefiles, we will need to extend this.
2737 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2741 if (is_null($itemid)) {
2742 require_once($CFG->dirroot.'/mod/forum/locallib.php');
2743 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2746 static $cached = array();
2747 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2748 // is cleared between unit tests we check if this is the same session
2749 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2750 $cached = array('sesskey' => sesskey());
2753 if (isset($cached['post']) && $cached['post']->id == $itemid) {
2754 $post = $cached['post'];
2755 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2756 $cached['post'] = $post;
2761 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2762 $discussion = $cached['discussion'];
2763 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2764 $cached['discussion'] = $discussion;
2769 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2770 $forum = $cached['forum'];
2771 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2772 $cached['forum'] = $forum;
2777 $fs = get_file_storage();
2778 $filepath = is_null($filepath) ? '/' : $filepath;
2779 $filename = is_null($filename) ? '.' : $filename;
2780 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2784 // Checks to see if the user can manage files or is the owner.
2785 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2786 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2789 // Make sure groups allow this user to see this file
2790 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2791 $groupmode = groups_get_activity_groupmode($cm, $course);
2792 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2797 // Make sure we're allowed to see it...
2798 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2802 $urlbase = $CFG->wwwroot.'/pluginfile.php';
2803 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2807 * Serves the forum attachments. Implements needed access control ;-)
2809 * @package mod_forum
2811 * @param stdClass $course course object
2812 * @param stdClass $cm course module object
2813 * @param stdClass $context context object
2814 * @param string $filearea file area
2815 * @param array $args extra arguments
2816 * @param bool $forcedownload whether or not force download
2817 * @param array $options additional options affecting the file serving
2818 * @return bool false if file not found, does not return if found - justsend the file
2820 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2823 if ($context->contextlevel != CONTEXT_MODULE) {
2827 require_course_login($course, true, $cm);
2829 $areas = forum_get_file_areas($course, $cm, $context);
2831 // filearea must contain a real area
2832 if (!isset($areas[$filearea])) {
2836 $postid = (int)array_shift($args);
2838 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2842 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
2846 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
2850 $fs = get_file_storage();
2851 $relativepath = implode('/', $args);
2852 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
2853 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2857 // Make sure groups allow this user to see this file
2858 if ($discussion->groupid > 0) {
2859 $groupmode = groups_get_activity_groupmode($cm, $course);
2860 if ($groupmode == SEPARATEGROUPS) {
2861 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2867 // Make sure we're allowed to see it...
2868 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2872 // finally send the file
2873 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
2877 * If successful, this function returns the name of the file
2880 * @param object $post is a full post record, including course and forum
2881 * @param object $forum
2883 * @param mixed $mform
2884 * @param string $unused
2887 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
2890 if (empty($mform)) {
2894 if (empty($post->attachments)) {
2895 return true; // Nothing to do
2898 $context = context_module::instance($cm->id);
2900 $info = file_get_draft_area_info($post->attachments);
2901 $present = ($info['filecount']>0) ? '1' : '';
2902 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
2903 mod_forum_post_form::attachment_options($forum));
2905 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
2911 * Add a new post in an existing discussion.
2913 * @param stdClass $post The post data
2914 * @param mixed $mform The submitted form
2915 * @param string $unused
2918 function forum_add_new_post($post, $mform, $unused = null) {
2921 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
2922 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
2923 $cm = get_coursemodule_from_instance('forum', $forum->id);
2924 $context = context_module::instance($cm->id);
2925 $privatereplyto = 0;
2927 // Check whether private replies should be enabled for this post.
2928 if ($post->parent) {
2929 $parent = $DB->get_record('forum_posts', array('id' => $post->parent));
2931 if (!empty($parent->privatereplyto)) {
2932 throw new \coding_exception('It should not be possible to reply to a private reply');
2935 if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) {
2936 $privatereplyto = $parent->userid;
2940 $post->created = $post->modified = time();
2941 $post->mailed = FORUM_MAILED_PENDING;
2942 $post->userid = $USER->id;
2943 $post->privatereplyto = $privatereplyto;
2944 $post->attachment = "";
2945 if (!isset($post->totalscore)) {
2946 $post->totalscore = 0;
2948 if (!isset($post->mailnow)) {
2952 \mod_forum\local\entities\post::add_message_counts($post);
2953 $post->id = $DB->insert_record("forum_posts", $post);
2954 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
2955 mod_forum_post_form::editor_options($context, null), $post->message);
2956 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
2957 forum_add_attachment($post, $forum, $cm, $mform);
2959 // Update discussion modified date
2960 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
2961 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
2963 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
2964 forum_tp_mark_post_read($post->userid, $post);
2967 if (isset($post->tags)) {
2968 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
2971 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
2972 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
2980 * @param stdClass $newpost The post to update
2981 * @param mixed $mform The submitted form
2982 * @param string $unused
2985 function forum_update_post($newpost, $mform, $unused = null) {
2988 $post = $DB->get_record('forum_posts', array('id' => $newpost->id));
2989 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
2990 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
2991 $cm = get_coursemodule_from_instance('forum', $forum->id);
2992 $context = context_module::instance($cm->id);
2994 // Allowed modifiable fields.
2995 $modifiablefields = [
3005 foreach ($modifiablefields as $field) {
3006 if (isset($newpost->{$field})) {
3007 $post->{$field} = $newpost->{$field};
3010 $post->modified = time();
3012 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
3013 $discussion->name = $post->subject;
3014 $discussion->timestart = $post->timestart;
3015 $discussion->timeend = $post->timeend;
3017 if (isset($post->pinned)) {
3018 $discussion->pinned = $post->pinned;
3021 $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
3022 mod_forum_post_form::editor_options($context, $post->id), $post->message);
3023 \mod_forum\local\entities\post::add_message_counts($post);
3024 $DB->update_record('forum_posts', $post);
3025 // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3026 $DB->update_record('forum_discussions', $discussion);
3028 forum_add_attachment($post, $forum, $cm, $mform);
3030 if (isset($newpost->tags)) {
3031 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3034 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3035 forum_tp_mark_post_read($USER->id, $post);
3038 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3039 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3045 * Given an object containing all the necessary data,
3046 * create a new discussion and return the id
3048 * @param object $post
3049 * @param mixed $mform
3050 * @param string $unused
3051 * @param int $userid
3054 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3055 global $USER, $CFG, $DB;
3057 $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
3059 if (is_null($userid)) {
3060 $userid = $USER->id;
3063 // The first post is stored as a real post, and linked
3064 // to from the discuss entry.
3066 $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
3067 $cm = get_coursemodule_from_instance('forum', $forum->id);
3069 $post = new stdClass();
3070 $post->discussion = 0;
3072 $post->privatereplyto = 0;
3073 $post->userid = $userid;
3074 $post->created = $timenow;
3075 $post->modified = $timenow;
3076 $post->mailed = FORUM_MAILED_PENDING;
3077 $post->subject = $discussion->name;
3078 $post->message = $discussion->message;
3079 $post->messageformat = $discussion->messageformat;
3080 $post->messagetrust = $discussion->messagetrust;
3081 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null;
3082 $post->forum = $forum->id; // speedup
3083 $post->course = $forum->course; // speedup
3084 $post->mailnow = $discussion->mailnow;
3086 \mod_forum\local\entities\post::add_message_counts($post);
3087 $post->id = $DB->insert_record("forum_posts", $post);
3089 // TODO: Fix the calling code so that there always is a $cm when this function is called
3090 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet
3091 $context = context_module::instance($cm->id);
3092 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
3093 mod_forum_post_form::editor_options($context, null), $post->message);
3094 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
3097 // Now do the main entry for the discussion, linking to this first post
3099 $discussion->firstpost = $post->id;
3100 $discussion->timemodified = $timenow;
3101 $discussion->usermodified = $post->userid;
3102 $discussion->userid = $userid;
3103 $discussion->assessed = 0;
3105 $post->discussion = $DB->insert_record("forum_discussions", $discussion);
3107 // Finally, set the pointer on the post.
3108 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
3110 if (!empty($cm->id)) {
3111 forum_add_attachment($post, $forum, $cm, $mform, $unused);
3114 if (isset($discussion->tags)) {
3115 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
3118 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3119 forum_tp_mark_post_read($post->userid, $post);
3122 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3123 if (!empty($cm->id)) {
3124 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3127 return $post->discussion;
3132 * Deletes a discussion and handles all associated cleanup.
3135 * @param object $discussion Discussion to delete
3136 * @param bool $fulldelete True when deleting entire forum
3137 * @param object $course Course
3138 * @param object $cm Course-module
3139 * @param object $forum Forum
3142 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3144 require_once($CFG->libdir.'/completionlib.php');
3148 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
3149 foreach ($posts as $post) {
3150 $post->course = $discussion->course;
3151 $post->forum = $discussion->forum;
3152 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3158 forum_tp_delete_read_records(-1, -1, $discussion->id);
3160 // Discussion subscriptions must be removed before discussions because of key constraints.
3161 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
3162 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
3166 // Update completion state if we are tracking completion based on number of posts
3167 // But don't bother when deleting whole thing
3169 $completion = new completion_info($course);
3170 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3171 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3172 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
3181 * Deletes a single forum post.
3184 * @param object $post Forum post object
3185 * @param mixed $children Whether to delete children. If false, returns false
3186 * if there are any children (without deleting the post). If true,
3187 * recursively deletes all children. If set to special value 'ignore', deletes
3188 * post regardless of children (this is for use only when deleting all posts
3190 * @param object $course Course
3191 * @param object $cm Course-module
3192 * @param object $forum Forum
3193 * @param bool $skipcompletion True to skip updating completion state if it
3194 * would otherwise be updated, i.e. when deleting entire forum anyway.
3197 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3198 global $DB, $CFG, $USER;
3199 require_once($CFG->libdir.'/completionlib.php');
3201 $context = context_module::instance($cm->id);
3203 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
3205 foreach ($childposts as $childpost) {
3206 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3214 require_once($CFG->dirroot.'/rating/lib.php');
3215 $delopt = new stdClass;
3216 $delopt->contextid = $context->id;
3217 $delopt->component = 'mod_forum';
3218 $delopt->ratingarea = 'post';
3219 $delopt->itemid = $post->id;
3220 $rm = new rating_manager();
3221 $rm->delete_ratings($delopt);
3223 // Delete attachments.
3224 $fs = get_file_storage();
3225 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
3226 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
3228 // Delete cached RSS feeds.
3229 if (!empty($CFG->enablerssfeeds)) {
3230 require_once($CFG->dirroot.'/mod/forum/rsslib.php');
3231 forum_rss_delete_file($forum);
3234 if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
3236 forum_tp_delete_read_records(-1, $post->id);
3238 // Just in case we are deleting the last post
3239 forum_discussion_update_last_post($post->discussion);
3241 // Update completion state if we are tracking completion based on number of posts
3242 // But don't bother when deleting whole thing
3244 if (!$skipcompletion) {
3245 $completion = new completion_info($course);
3246 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3247 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3248 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
3253 'context' => $context,
3254 'objectid' => $post->id,
3256 'discussionid' => $post->discussion,
3257 'forumid' => $forum->id,
3258 'forumtype' => $forum->type,
3262 if ($post->userid !== $USER->id) {
3263 $params['relateduserid'] = $post->userid;
3265 $event = \mod_forum\event\post_deleted::create($params);
3266 $event->add_record_snapshot('forum_posts', $post);
3275 * Sends post content to plagiarism plugin
3276 * @param object $post Forum post object
3277 * @param object $cm Course-module
3278 * @param string $name
3281 function forum_trigger_content_uploaded_event($post, $cm, $name) {
3282 $context = context_module::instance($cm->id);
3283 $fs = get_file_storage();
3284 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
3286 'context' => $context,
3287 'objectid' => $post->id,
3289 'content' => $post->message,
3290 'pathnamehashes' => array_keys($files),
3291 'discussionid' => $post->discussion,
3292 'triggeredfrom' => $name,
3295 $event = \mod_forum\event\assessable_uploaded::create($params);
3301 * Given a new post, subscribes or unsubscribes as appropriate.
3302 * Returns some text which describes what happened.
3304 * @param object $fromform The submitted form
3305 * @param stdClass $forum The forum record
3306 * @param stdClass $discussion The forum discussion record
3309 function forum_post_subscription($fromform, $forum, $discussion) {
3312 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3314 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
3315 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3316 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
3317 // This user should not be subscribed to the forum.
3318 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
3323 $info = new stdClass();
3324 $info->name = fullname($USER);
3325 $info->discussion = format_string($discussion->name);
3326 $info->forum = format_string($forum->name);
3328 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
3329 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
3330 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3333 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
3334 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3342 * Generate and return the subscribe or unsubscribe link for a forum.
3344 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3345 * @param object $context the context object for this forum.
3346 * @param array $messages text used for the link in its various states
3347 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3348 * Any strings not passed in are taken from the $defaultmessages array
3349 * at the top of the function.
3350 * @param bool $cantaccessagroup
3351 * @param bool $unused1
3352 * @param bool $backtoindex
3353 * @param array $unused2
3356 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3357 $backtoindex = false, $unused2 = null) {
3358 global $CFG, $USER, $PAGE, $OUTPUT;
3359 $defaultmessages = array(
3360 'subscribed' => get_string('unsubscribe', 'forum'),
3361 'unsubscribed' => get_string('subscribe', 'forum'),
3362 'cantaccessgroup' => get_string('no'),
3363 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3364 'cantsubscribe' => get_string('disallowsubscribe','forum')
3366 $messages = $messages + $defaultmessages;
3368 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3369 return $messages['forcesubscribed'];
3370 } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
3371 !has_capability('mod/forum:managesubscriptions', $context)) {
3372 return $messages['cantsubscribe'];
3373 } else if ($cantaccessagroup) {
3374 return $messages['cantaccessgroup'];
3376 if (!is_enrolled($context, $USER, '', true)) {
3380 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3382 $linktext = $messages['subscribed'];
3383 $linktitle = get_string('subscribestop', 'forum');
3385 $linktext = $messages['unsubscribed'];
3386 $linktitle = get_string('subscribestart', 'forum');
3391 $backtoindexlink = '&backtoindex=1';
3392 $options['backtoindex'] = 1;
3394 $backtoindexlink = '';
3397 $options['id'] = $forum->id;
3398 $options['sesskey'] = sesskey();
3399 $url = new moodle_url('/mod/forum/subscribe.php', $options);
3400 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3405 * Returns true if user created new discussion already.
3407 * @param int $forumid The forum to check for postings
3408 * @param int $userid The user to check for postings
3409 * @param int $groupid The group to restrict the check to
3412 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3416 FROM {forum_discussions} d, {forum_posts} p
3417 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3419 $params = [$forumid, $userid];
3422 $sql .= " AND d.groupid = ?";
3423 $params[] = $groupid;
3426 return $DB->record_exists_sql($sql, $params);
3432 * @param int $forumid
3433 * @param int $userid
3436 function forum_discussions_user_has_posted_in($forumid, $userid) {
3439 $haspostedsql = "SELECT d.id AS id,
3441 FROM {forum_posts} p,
3442 {forum_discussions} d
3443 WHERE p.discussion = d.id
3447 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3453 * @param int $forumid
3455 * @param int $userid
3458 function forum_user_has_posted($forumid, $did, $userid) {
3462 // posted in any forum discussion?
3464 FROM {forum_posts} p
3465 JOIN {forum_discussions} d ON d.id = p.discussion
3466 WHERE p.userid = :userid AND d.forum = :forumid";
3467 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3469 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3474 * Returns creation time of the first user's post in given discussion
3475 * @global object $DB
3476 * @param int $did Discussion id
3477 * @param int $userid User id
3478 * @return int|bool post creation time stamp or return false
3480 function forum_get_user_posted_time($did, $userid) {
3483 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3484 if (empty($posttime)) {
3492 * @param object $forum
3493 * @param object $currentgroup
3494 * @param int $unused
3496 * @param object $context
3499 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3500 // $forum is an object
3503 // shortcut - guest and not-logged-in users can not post
3504 if (isguestuser() or !isloggedin()) {
3509 debugging('missing cm', DEBUG_DEVELOPER);
3510 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3511 print_error('invalidcoursemodule');
3516 $context = context_module::instance($cm->id);
3519 if (forum_is_cutoff_date_reached($forum)) {
3520 if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3525 if ($currentgroup === null) {
3526 $currentgroup = groups_get_activity_group($cm);
3529 $groupmode = groups_get_activity_groupmode($cm);
3531 if ($forum->type == 'news') {
3532 $capname = 'mod/forum:addnews';
3533 } else if ($forum->type == 'qanda') {
3534 $capname = 'mod/forum:addquestion';
3536 $capname = 'mod/forum:startdiscussion';
3539 if (!has_capability($capname, $context)) {
3543 if ($forum->type == 'single') {
3547 if ($forum->type == 'eachuser') {
3548 if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) {
3553 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
3557 if ($currentgroup) {
3558 return groups_is_member($currentgroup);
3560 // no group membership and no accessallgroups means no new discussions
3561 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
3567 * This function checks whether the user can reply to posts in a forum
3568 * discussion. Use forum_user_can_post_discussion() to check whether the user
3569 * can start discussions.
3573 * @uses DEBUG_DEVELOPER
3574 * @uses CONTEXT_MODULE
3575 * @uses VISIBLEGROUPS
3576 * @param object $forum forum object
3577 * @param object $discussion
3578 * @param object $user
3580 * @param object $course
3581 * @param object $context
3584 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
3590 // shortcut - guest and not-logged-in users can not post
3591 if (isguestuser($user) or empty($user->id)) {
3595 if (!isset($discussion->groupid)) {
3596 debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
3601 debugging('missing cm', DEBUG_DEVELOPER);
3602 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3603 print_error('invalidcoursemodule');
3608 debugging('missing course', DEBUG_DEVELOPER);
3609 if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
3610 print_error('invalidcourseid');
3615 $context = context_module::instance($cm->id);
3618 if (forum_is_cutoff_date_reached($forum)) {
3619 if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3624 // Check whether the discussion is locked.
3625 if (forum_discussion_is_locked($forum, $discussion)) {
3626 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {