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 use mod_forum\local\entities\forum
as forum_entity
;
25 defined('MOODLE_INTERNAL') ||
die();
27 /** Include required files */
28 require_once(__DIR__
. '/deprecatedlib.php');
29 require_once($CFG->libdir
.'/filelib.php');
31 /// CONSTANTS ///////////////////////////////////////////////////////////
33 define('FORUM_MODE_FLATOLDEST', 1);
34 define('FORUM_MODE_FLATNEWEST', -1);
35 define('FORUM_MODE_THREADED', 2);
36 define('FORUM_MODE_NESTED', 3);
37 define('FORUM_MODE_NESTED_V2', 4);
39 define('FORUM_CHOOSESUBSCRIBE', 0);
40 define('FORUM_FORCESUBSCRIBE', 1);
41 define('FORUM_INITIALSUBSCRIBE', 2);
42 define('FORUM_DISALLOWSUBSCRIBE',3);
45 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
47 define('FORUM_TRACKING_OFF', 0);
50 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
52 define('FORUM_TRACKING_OPTIONAL', 1);
55 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
56 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
58 define('FORUM_TRACKING_FORCED', 2);
60 define('FORUM_MAILED_PENDING', 0);
61 define('FORUM_MAILED_SUCCESS', 1);
62 define('FORUM_MAILED_ERROR', 2);
64 if (!defined('FORUM_CRON_USER_CACHE')) {
65 /** Defines how many full user records are cached in forum cron. */
66 define('FORUM_CRON_USER_CACHE', 5000);
70 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
72 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
74 define('FORUM_DISCUSSION_PINNED', 1);
75 define('FORUM_DISCUSSION_UNPINNED', 0);
77 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
80 * Given an object containing all the necessary data,
81 * (defined by the form in mod_form.php) this function
82 * will create a new instance and return the id number
83 * of the new instance.
85 * @param stdClass $forum add forum instance
86 * @param mod_forum_mod_form $mform
87 * @return int intance id
89 function forum_add_instance($forum, $mform = null) {
92 require_once($CFG->dirroot
.'/mod/forum/locallib.php');
94 $forum->timemodified
= time();
96 if (empty($forum->assessed
)) {
100 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
101 $forum->assesstimestart
= 0;
102 $forum->assesstimefinish
= 0;
105 $forum->id
= $DB->insert_record('forum', $forum);
106 $modcontext = context_module
::instance($forum->coursemodule
);
108 if ($forum->type
== 'single') { // Create related discussion.
109 $discussion = new stdClass();
110 $discussion->course
= $forum->course
;
111 $discussion->forum
= $forum->id
;
112 $discussion->name
= $forum->name
;
113 $discussion->assessed
= $forum->assessed
;
114 $discussion->message
= $forum->intro
;
115 $discussion->messageformat
= $forum->introformat
;
116 $discussion->messagetrust
= trusttext_trusted(context_course
::instance($forum->course
));
117 $discussion->mailnow
= false;
118 $discussion->groupid
= -1;
122 $discussion->id
= forum_add_discussion($discussion, null, $message);
124 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
125 // Ugly hack - we need to copy the files somehow.
126 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id
), '*', MUST_EXIST
);
127 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
129 $options = array('subdirs'=>true); // Use the same options as intro field!
130 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
131 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
135 forum_update_calendar($forum, $forum->coursemodule
);
136 forum_grade_item_update($forum);
138 $completiontimeexpected = !empty($forum->completionexpected
) ?
$forum->completionexpected
: null;
139 \core_completion\api
::update_completion_date_event($forum->coursemodule
, 'forum', $forum->id
, $completiontimeexpected);
145 * Handle changes following the creation of a forum instance.
146 * This function is typically called by the course_module_created observer.
148 * @param object $context the forum context
149 * @param stdClass $forum The forum object
152 function forum_instance_created($context, $forum) {
153 if ($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) {
154 $users = \mod_forum\subscriptions
::get_potential_subscribers($context, 0, 'u.id, u.email');
155 foreach ($users as $user) {
156 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $context);
162 * Given an object containing all the necessary data,
163 * (defined by the form in mod_form.php) this function
164 * will update an existing instance with new data.
167 * @param object $forum forum instance (with magic quotes)
168 * @return bool success
170 function forum_update_instance($forum, $mform) {
171 global $CFG, $DB, $OUTPUT, $USER;
173 require_once($CFG->dirroot
.'/mod/forum/locallib.php');
175 $forum->timemodified
= time();
176 $forum->id
= $forum->instance
;
178 if (empty($forum->assessed
)) {
179 $forum->assessed
= 0;
182 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
183 $forum->assesstimestart
= 0;
184 $forum->assesstimefinish
= 0;
187 $oldforum = $DB->get_record('forum', array('id'=>$forum->id
));
189 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
190 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
191 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
192 $updategrades = false;
194 if ($oldforum->assessed
<> $forum->assessed
) {
195 // Whether this forum is rated.
196 $updategrades = true;
199 if ($oldforum->scale
<> $forum->scale
) {
200 // The scale currently in use.
201 $updategrades = true;
204 if (empty($oldforum->grade_forum
) ||
$oldforum->grade_forum
<> $forum->grade_forum
) {
205 // The whole forum grading.
206 $updategrades = true;
210 forum_update_grades($forum); // Recalculate grades for the forum.
213 if ($forum->type
== 'single') { // Update related discussion and post.
214 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
), 'timemodified ASC');
215 if (!empty($discussions)) {
216 if (count($discussions) > 1) {
217 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
219 $discussion = array_pop($discussions);
221 // try to recover by creating initial discussion - MDL-16262
222 $discussion = new stdClass();
223 $discussion->course
= $forum->course
;
224 $discussion->forum
= $forum->id
;
225 $discussion->name
= $forum->name
;
226 $discussion->assessed
= $forum->assessed
;
227 $discussion->message
= $forum->intro
;
228 $discussion->messageformat
= $forum->introformat
;
229 $discussion->messagetrust
= true;
230 $discussion->mailnow
= false;
231 $discussion->groupid
= -1;
235 forum_add_discussion($discussion, null, $message);
237 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id
))) {
238 throw new \
moodle_exception('cannotadd', 'forum');
241 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
))) {
242 throw new \
moodle_exception('cannotfindfirstpost', 'forum');
245 $cm = get_coursemodule_from_instance('forum', $forum->id
);
246 $modcontext = context_module
::instance($cm->id
, MUST_EXIST
);
248 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
249 $post->subject
= $forum->name
;
250 $post->message
= $forum->intro
;
251 $post->messageformat
= $forum->introformat
;
252 $post->messagetrust
= trusttext_trusted($modcontext);
253 $post->modified
= $forum->timemodified
;
254 $post->userid
= $USER->id
; // MDL-18599, so that current teacher can take ownership of activities.
256 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
257 // Ugly hack - we need to copy the files somehow.
258 $options = array('subdirs'=>true); // Use the same options as intro field!
259 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
262 \mod_forum\local\entities\post
::add_message_counts($post);
263 $DB->update_record('forum_posts', $post);
264 $discussion->name
= $forum->name
;
265 $DB->update_record('forum_discussions', $discussion);
268 $DB->update_record('forum', $forum);
270 $modcontext = context_module
::instance($forum->coursemodule
);
271 if (($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) && ($oldforum->forcesubscribe
<> $forum->forcesubscribe
)) {
272 $users = \mod_forum\subscriptions
::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
273 foreach ($users as $user) {
274 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $modcontext);
278 forum_update_calendar($forum, $forum->coursemodule
);
279 forum_grade_item_update($forum);
281 $completiontimeexpected = !empty($forum->completionexpected
) ?
$forum->completionexpected
: null;
282 \core_completion\api
::update_completion_date_event($forum->coursemodule
, 'forum', $forum->id
, $completiontimeexpected);
289 * Given an ID of an instance of this module,
290 * this function will permanently delete the instance
291 * and any data that depends on it.
294 * @param int $id forum instance id
295 * @return bool success
297 function forum_delete_instance($id) {
300 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
303 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
)) {
306 if (!$course = $DB->get_record('course', array('id'=>$cm->course
))) {
310 $context = context_module
::instance($cm->id
);
312 // now get rid of all files
313 $fs = get_file_storage();
314 $fs->delete_area_files($context->id
);
318 \core_completion\api
::update_completion_date_event($cm->id
, 'forum', $forum->id
, null);
320 // Delete digest and subscription preferences.
321 $DB->delete_records('forum_digests', array('forum' => $forum->id
));
322 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id
));
323 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id
));
325 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
))) {
326 foreach ($discussions as $discussion) {
327 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
333 forum_tp_delete_read_records(-1, -1, -1, $forum->id
);
335 forum_grade_item_delete($forum);
337 // We must delete the module record after we delete the grade item.
338 if (!$DB->delete_records('forum', array('id'=>$forum->id
))) {
347 * Indicates API features that the forum supports.
349 * @uses FEATURE_GROUPS
350 * @uses FEATURE_GROUPINGS
351 * @uses FEATURE_MOD_INTRO
352 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
353 * @uses FEATURE_COMPLETION_HAS_RULES
354 * @uses FEATURE_GRADE_HAS_GRADE
355 * @uses FEATURE_GRADE_OUTCOMES
356 * @param string $feature
357 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
359 function forum_supports($feature) {
361 case FEATURE_GROUPS
: return true;
362 case FEATURE_GROUPINGS
: return true;
363 case FEATURE_MOD_INTRO
: return true;
364 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
365 case FEATURE_COMPLETION_HAS_RULES
: return true;
366 case FEATURE_GRADE_HAS_GRADE
: return true;
367 case FEATURE_GRADE_OUTCOMES
: return true;
368 case FEATURE_RATE
: return true;
369 case FEATURE_BACKUP_MOODLE2
: return true;
370 case FEATURE_SHOW_DESCRIPTION
: return true;
371 case FEATURE_PLAGIARISM
: return true;
372 case FEATURE_ADVANCED_GRADING
: return true;
373 case FEATURE_MOD_PURPOSE
: return MOD_PURPOSE_COLLABORATION
;
375 default: return null;
380 * Create a message-id string to use in the custom headers of forum notification emails
382 * message-id is used by email clients to identify emails and to nest conversations
384 * @param int $postid The ID of the forum post we are notifying the user about
385 * @param int $usertoid The ID of the user being notified
386 * @return string A unique message-id
388 function forum_get_email_message_id($postid, $usertoid) {
389 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
394 * @param object $course
395 * @param object $user
396 * @param object $mod TODO this is not used in this function, refactor
397 * @param object $forum
398 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
400 function forum_user_outline($course, $user, $mod, $forum) {
402 require_once("$CFG->libdir/gradelib.php");
407 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
408 if (!empty($grades->items
[0]->grades
)) {
409 // Item 0 is the rating.
410 $grade = reset($grades->items
[0]->grades
);
411 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
412 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
413 $gradeinfo .= get_string('gradeforrating', 'forum', $grade) . html_writer
::empty_tag('br');
415 $gradeinfo .= get_string('gradeforratinghidden', 'forum') . html_writer
::empty_tag('br');
419 // Item 1 is the whole-forum grade.
420 if (!empty($grades->items
[1]->grades
)) {
421 $grade = reset($grades->items
[1]->grades
);
422 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
423 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
424 $gradeinfo .= get_string('gradeforwholeforum', 'forum', $grade) . html_writer
::empty_tag('br');
426 $gradeinfo .= get_string('gradeforwholeforumhidden', 'forum') . html_writer
::empty_tag('br');
430 $count = forum_count_user_posts($forum->id
, $user->id
);
431 if ($count && $count->postcount
> 0) {
432 $info = get_string("numposts", "forum", $count->postcount
);
433 $time = $count->lastpost
;
436 $info .= ', ' . $gradeinfo;
437 $time = max($time, $gradetime);
444 } else if ($gradeinfo) {
446 'info' => $gradeinfo,
447 'time' => $gradetime,
458 * @param object $coure
459 * @param object $user
461 * @param object $forum
463 function forum_user_complete($course, $user, $mod, $forum) {
465 require_once("$CFG->libdir/gradelib.php");
467 $getgradeinfo = function($grades, string $type) use ($course): string {
470 if (empty($grades)) {
475 $grade = reset($grades);
476 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
477 $result .= $OUTPUT->container(get_string("gradefor{$type}", "forum", $grade));
478 if ($grade->str_feedback
) {
479 $result .= $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
482 $result .= $OUTPUT->container(get_string("gradefor{$type}hidden", "forum"));
488 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
490 // Item 0 is the rating.
491 if (!empty($grades->items
[0]->grades
)) {
492 echo $getgradeinfo($grades->items
[0]->grades
, 'rating');
495 // Item 1 is the whole-forum grade.
496 if (!empty($grades->items
[1]->grades
)) {
497 echo $getgradeinfo($grades->items
[1]->grades
, 'wholeforum');
500 if ($posts = forum_get_user_posts($forum->id
, $user->id
)) {
501 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
)) {
502 throw new \
moodle_exception('invalidcoursemodule');
504 $context = context_module
::instance($cm->id
);
505 $discussions = forum_get_user_involved_discussions($forum->id
, $user->id
);
506 $posts = array_filter($posts, function($post) use ($discussions) {
507 return isset($discussions[$post->discussion
]);
509 $entityfactory = mod_forum\local\container
::get_entity_factory();
510 $rendererfactory = mod_forum\local\container
::get_renderer_factory();
511 $postrenderer = $rendererfactory->get_posts_renderer();
513 echo $postrenderer->render(
515 [$forum->id
=> $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
516 array_map(function($discussion) use ($entityfactory) {
517 return $entityfactory->get_discussion_from_stdclass($discussion);
519 array_map(function($post) use ($entityfactory) {
520 return $entityfactory->get_post_from_stdclass($post);
524 echo "<p>".get_string("noposts", "forum")."</p>";
529 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
531 function forum_filter_user_groups_discussions() {
532 throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.');
536 * Returns whether the discussion group is visible by the current user or not.
538 * @since Moodle 2.8, 2.7.1, 2.6.4
539 * @param cm_info $cm The discussion course module
540 * @param int $discussiongroupid The discussion groupid
543 function forum_is_user_group_discussion(cm_info
$cm, $discussiongroupid) {
545 if ($discussiongroupid == -1 ||
$cm->effectivegroupmode
!= SEPARATEGROUPS
) {
553 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
)) ||
554 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid
))) {
562 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
564 function forum_print_overview() {
565 throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.');
569 * Given a course and a date, prints a summary of all the new
570 * messages posted in the course since that date
575 * @uses CONTEXT_MODULE
576 * @uses VISIBLEGROUPS
577 * @param object $course
578 * @param bool $viewfullnames capability
579 * @param int $timestart
580 * @return bool success
582 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
583 global $USER, $DB, $OUTPUT;
585 // do not use log table if possible, it may be huge and is expensive to join with other tables
587 $userfieldsapi = \core_user\fields
::for_userpic();
588 $allnamefields = $userfieldsapi->get_sql('u', false, '', 'duserid', false)->selects
;
589 if (!$posts = $DB->get_records_sql("SELECT p.*,
590 f.course, f.type AS forumtype, f.name AS forumname, f.intro, f.introformat, f.duedate,
591 f.cutoffdate, f.assessed AS forumassessed, f.assesstimestart, f.assesstimefinish,
592 f.scale, f.grade_forum, f.maxbytes, f.maxattachments, f.forcesubscribe,
593 f.trackingtype, f.rsstype, f.rssarticles, f.timemodified, f.warnafter, f.blockafter,
594 f.blockperiod, f.completiondiscussions, f.completionreplies, f.completionposts,
595 f.displaywordcount, f.lockdiscussionafter, f.grade_forum_notify,
596 d.name AS discussionname, d.firstpost, d.userid AS discussionstarter,
597 d.assessed AS discussionassessed, d.timemodified, d.usermodified, d.forum, d.groupid,
598 d.timestart, d.timeend, d.pinned, d.timelocked,
601 JOIN {forum_discussions} d ON d.id = p.discussion
602 JOIN {forum} f ON f.id = d.forum
603 JOIN {user} u ON u.id = p.userid
604 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
605 ORDER BY p.id ASC", array($timestart, $course->id
))) { // order by initial posting date
609 $modinfo = get_fast_modinfo($course);
611 $strftimerecent = get_string('strftimerecent');
613 $managerfactory = mod_forum\local\container
::get_manager_factory();
614 $entityfactory = mod_forum\local\container
::get_entity_factory();
619 foreach ($posts as $post) {
620 if (!isset($modinfo->instances
['forum'][$post->forum
])) {
624 $cm = $modinfo->instances
['forum'][$post->forum
];
625 if (!$cm->uservisible
) {
629 // Get the discussion. Cache if not yet available.
630 if (!isset($discussions[$post->discussion
])) {
631 // Build the discussion record object from the post data.
632 $discussionrecord = (object)[
633 'id' => $post->discussion
,
634 'course' => $post->course
,
635 'forum' => $post->forum
,
636 'name' => $post->discussionname
,
637 'firstpost' => $post->firstpost
,
638 'userid' => $post->discussionstarter
,
639 'groupid' => $post->groupid
,
640 'assessed' => $post->discussionassessed
,
641 'timemodified' => $post->timemodified
,
642 'usermodified' => $post->usermodified
,
643 'timestart' => $post->timestart
,
644 'timeend' => $post->timeend
,
645 'pinned' => $post->pinned
,
646 'timelocked' => $post->timelocked
648 // Build the discussion entity from the factory and cache it.
649 $discussions[$post->discussion
] = $entityfactory->get_discussion_from_stdclass($discussionrecord);
651 $discussionentity = $discussions[$post->discussion
];
653 // Get the capability manager. Cache if not yet available.
654 if (!isset($capmanagers[$post->forum
])) {
655 $context = context_module
::instance($cm->id
);
656 $coursemodule = $cm->get_course_module_record();
657 // Build the forum record object from the post data.
658 $forumrecord = (object)[
659 'id' => $post->forum
,
660 'course' => $post->course
,
661 'type' => $post->forumtype
,
662 'name' => $post->forumname
,
663 'intro' => $post->intro
,
664 'introformat' => $post->introformat
,
665 'duedate' => $post->duedate
,
666 'cutoffdate' => $post->cutoffdate
,
667 'assessed' => $post->forumassessed
,
668 'assesstimestart' => $post->assesstimestart
,
669 'assesstimefinish' => $post->assesstimefinish
,
670 'scale' => $post->scale
,
671 'grade_forum' => $post->grade_forum
,
672 'maxbytes' => $post->maxbytes
,
673 'maxattachments' => $post->maxattachments
,
674 'forcesubscribe' => $post->forcesubscribe
,
675 'trackingtype' => $post->trackingtype
,
676 'rsstype' => $post->rsstype
,
677 'rssarticles' => $post->rssarticles
,
678 'timemodified' => $post->timemodified
,
679 'warnafter' => $post->warnafter
,
680 'blockafter' => $post->blockafter
,
681 'blockperiod' => $post->blockperiod
,
682 'completiondiscussions' => $post->completiondiscussions
,
683 'completionreplies' => $post->completionreplies
,
684 'completionposts' => $post->completionposts
,
685 'displaywordcount' => $post->displaywordcount
,
686 'lockdiscussionafter' => $post->lockdiscussionafter
,
687 'grade_forum_notify' => $post->grade_forum_notify
689 // Build the forum entity from the factory.
690 $forumentity = $entityfactory->get_forum_from_stdclass($forumrecord, $context, $coursemodule, $course);
691 // Get the capability manager of this forum and cache it.
692 $capmanagers[$post->forum
] = $managerfactory->get_capability_manager($forumentity);
694 $capabilitymanager = $capmanagers[$post->forum
];
696 // Get the post entity.
697 $postentity = $entityfactory->get_post_from_stdclass($post);
699 // Check if the user can view the post.
700 if ($capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) {
701 $printposts[] = $post;
710 echo $OUTPUT->heading(get_string('newforumposts', 'forum') . ':', 6);
711 $list = html_writer
::start_tag('ul', ['class' => 'unlist']);
713 foreach ($printposts as $post) {
714 $subjectclass = empty($post->parent
) ?
' bold' : '';
715 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype
]);
717 $list .= html_writer
::start_tag('li');
718 $list .= html_writer
::start_div('head');
719 $list .= html_writer
::div(userdate_htmltime($post->modified
, $strftimerecent), 'date');
720 if (!$authorhidden) {
721 $list .= html_writer
::div(fullname($post, $viewfullnames), 'name');
723 $list .= html_writer
::end_div(); // Head.
725 $list .= html_writer
::start_div('info' . $subjectclass);
726 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion
]);
727 if (!empty($post->parent
)) {
728 $discussionurl->param('parent', $post->parent
);
729 $discussionurl->set_anchor('p'. $post->id
);
731 $post->subject
= break_up_long_words(format_string($post->subject
, true));
732 $list .= html_writer
::link($discussionurl, $post->subject
, ['rel' => 'bookmark']);
733 $list .= html_writer
::end_div(); // Info.
734 $list .= html_writer
::end_tag('li');
737 $list .= html_writer
::end_tag('ul');
744 * Update activity grades.
746 * @param object $forum
747 * @param int $userid specific user only, 0 means all
749 function forum_update_grades($forum, $userid = 0): void
{
751 require_once($CFG->libdir
.'/gradelib.php');
754 if ($forum->assessed
) {
755 require_once($CFG->dirroot
.'/rating/lib.php');
757 $cm = get_coursemodule_from_instance('forum', $forum->id
);
759 $rm = new rating_manager();
760 $ratings = $rm->get_user_grades((object) [
761 'component' => 'mod_forum',
762 'ratingarea' => 'post',
763 'contextid' => \context_module
::instance($cm->id
)->id
,
765 'modulename' => 'forum',
766 'moduleid ' => $forum->id
,
768 'aggregationmethod' => $forum->assessed
,
769 'scaleid' => $forum->scale
,
770 'itemtable' => 'forum_posts',
771 'itemtableusercolumn' => 'userid',
776 if ($forum->grade_forum
) {
782 g.timemodified as dategraded
784 JOIN {forum_grades} g ON g.forum = f.id
785 WHERE f.id = :forumid
789 'forumid' => $forum->id
,
793 $sql .= " AND g.userid = :userid";
794 $params['userid'] = $userid;
798 if ($grades = $DB->get_recordset_sql($sql, $params)) {
799 foreach ($grades as $userid => $grade) {
800 if ($grade->rawgrade
!= -1) {
801 $forumgrades[$userid] = $grade;
808 forum_grade_item_update($forum, $ratings, $forumgrades);
812 * Create/update grade items for given forum.
814 * @param stdClass $forum Forum object with extra cmidnumber
815 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
817 function forum_grade_item_update($forum, $ratings = null, $forumgrades = null): void
{
819 require_once("{$CFG->libdir}/gradelib.php");
821 // Update the rating.
823 'itemname' => get_string('gradeitemnameforrating', 'forum', $forum),
824 'idnumber' => $forum->cmidnumber
,
827 if (!$forum->assessed ||
$forum->scale
== 0) {
828 $item['gradetype'] = GRADE_TYPE_NONE
;
829 } else if ($forum->scale
> 0) {
830 $item['gradetype'] = GRADE_TYPE_VALUE
;
831 $item['grademax'] = $forum->scale
;
832 $item['grademin'] = 0;
833 } else if ($forum->scale
< 0) {
834 $item['gradetype'] = GRADE_TYPE_SCALE
;
835 $item['scaleid'] = -$forum->scale
;
838 if ($ratings === 'reset') {
839 $item['reset'] = true;
842 // Itemnumber 0 is the rating.
843 grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, $ratings, $item);
845 // Whole forum grade.
847 'itemname' => get_string('gradeitemnameforwholeforum', 'forum', $forum),
848 // Note: We do not need to store the idnumber here.
851 if (!$forum->grade_forum
) {
852 $item['gradetype'] = GRADE_TYPE_NONE
;
853 } else if ($forum->grade_forum
> 0) {
854 $item['gradetype'] = GRADE_TYPE_VALUE
;
855 $item['grademax'] = $forum->grade_forum
;
856 $item['grademin'] = 0;
857 } else if ($forum->grade_forum
< 0) {
858 $item['gradetype'] = GRADE_TYPE_SCALE
;
859 $item['scaleid'] = $forum->grade_forum
* -1;
862 if ($forumgrades === 'reset') {
863 $item['reset'] = true;
866 // Itemnumber 1 is the whole forum grade.
867 grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 1, $forumgrades, $item);
871 * Delete grade item for given forum.
873 * @param stdClass $forum Forum object
875 function forum_grade_item_delete($forum) {
877 require_once($CFG->libdir
.'/gradelib.php');
879 grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, null, ['deleted' => 1]);
880 grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 1, null, ['deleted' => 1]);
884 * Checks if scale is being used by any instance of forum.
886 * This is used to find out if scale used anywhere.
888 * @param $scaleid int
889 * @return boolean True if the scale is used by any forum
891 function forum_scale_used_anywhere(int $scaleid): bool {
894 if (empty($scaleid)) {
898 return $DB->record_exists_select('forum', "scale = ? and assessed > 0", [$scaleid * -1]);
901 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
904 * Gets a post with all info ready for forum_print_post
905 * Most of these joins are just to get the forum id
910 * @return mixed array of posts or false
912 function forum_get_post_full($postid) {
915 $userfieldsapi = \core_user\fields
::for_name();
916 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
917 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
919 JOIN {forum_discussions} d ON p.discussion = d.id
920 LEFT JOIN {user} u ON p.userid = u.id
921 WHERE p.id = ?", array($postid));
925 * Gets all posts in discussion including top parent.
927 * @param int $discussionid The Discussion to fetch.
928 * @param string $sort The sorting to apply.
929 * @param bool $tracking Whether the user tracks this forum.
930 * @return array The posts in the discussion.
932 function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) {
933 global $CFG, $DB, $USER;
940 $tr_sel = ", fr.id AS postread";
941 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
942 $params[] = $USER->id
;
945 $userfieldsapi = \core_user\fields
::for_name();
946 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
947 $params[] = $discussionid;
948 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
950 LEFT JOIN {user} u ON p.userid = u.id
952 WHERE p.discussion = ?
953 ORDER BY $sort", $params)) {
957 foreach ($posts as $pid=>$p) {
959 if (forum_tp_is_post_old($p)) {
960 $posts[$pid]->postread
= true;
966 if (!isset($posts[$p->parent
])) {
967 continue; // parent does not exist??
969 if (!isset($posts[$p->parent
]->children
)) {
970 $posts[$p->parent
]->children
= array();
972 $posts[$p->parent
]->children
[$pid] =& $posts[$pid];
975 // Start with the last child of the first post.
976 $post = &$posts[reset($posts)->id
];
980 if (!isset($post->children
)) {
981 $post->lastpost
= true;
984 // Go to the last child of this post.
985 $post = &$posts[end($post->children
)->id
];
993 * An array of forum objects that the user is allowed to read/search through.
999 * @param int $courseid if 0, we look for forums throughout the whole site.
1000 * @return array of forum objects, or false if no matches
1001 * Forum objects have the following attributes:
1002 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1003 * viewhiddentimedposts
1005 function forum_get_readable_forums($userid, $courseid=0) {
1007 global $CFG, $DB, $USER;
1008 require_once($CFG->dirroot
.'/course/lib.php');
1010 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1011 throw new \
moodle_exception('notinstalled', 'forum');
1015 $courses = $DB->get_records('course', array('id' => $courseid));
1017 // If no course is specified, then the user can see SITE + his courses.
1018 $courses1 = $DB->get_records('course', array('id' => SITEID
));
1019 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1020 $courses = array_merge($courses1, $courses2);
1026 $readableforums = array();
1028 foreach ($courses as $course) {
1030 $modinfo = get_fast_modinfo($course);
1032 if (empty($modinfo->instances
['forum'])) {
1037 $courseforums = $DB->get_records('forum', array('course' => $course->id
));
1039 foreach ($modinfo->instances
['forum'] as $forumid => $cm) {
1040 if (!$cm->uservisible
or !isset($courseforums[$forumid])) {
1043 $context = context_module
::instance($cm->id
);
1044 $forum = $courseforums[$forumid];
1045 $forum->context
= $context;
1048 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1053 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
1055 $forum->onlygroups
= $modinfo->get_groups($cm->groupingid
);
1056 $forum->onlygroups
[] = -1;
1059 /// hidden timed discussions
1060 $forum->viewhiddentimedposts
= true;
1061 if (!empty($CFG->forum_enabletimedposts
)) {
1062 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1063 $forum->viewhiddentimedposts
= false;
1068 if ($forum->type
== 'qanda'
1069 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1071 // We need to check whether the user has posted in the qanda forum.
1072 $forum->onlydiscussions
= array(); // Holds discussion ids for the discussions
1073 // the user is allowed to see in this forum.
1074 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $USER->id
)) {
1075 foreach ($discussionspostedin as $d) {
1076 $forum->onlydiscussions
[] = $d->id
;
1081 $readableforums[$forum->id
] = $forum;
1086 } // End foreach $courses
1088 return $readableforums;
1092 * Returns a list of posts found using an array of search terms.
1097 * @param array $searchterms array of search terms, e.g. word +word -word
1098 * @param int $courseid if 0, we search through the whole site
1099 * @param int $limitfrom
1100 * @param int $limitnum
1101 * @param int &$totalcount
1102 * @param string $extrasql
1103 * @return array|bool Array of posts found or false
1105 function forum_search_posts($searchterms, $courseid, $limitfrom, $limitnum,
1106 &$totalcount, $extrasql='') {
1107 global $CFG, $DB, $USER;
1108 require_once($CFG->libdir
.'/searchlib.php');
1110 $forums = forum_get_readable_forums($USER->id
, $courseid);
1112 if (count($forums) == 0) {
1117 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1119 $fullaccess = array();
1123 foreach ($forums as $forumid => $forum) {
1126 if (!$forum->viewhiddentimedposts
) {
1127 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1128 $params = array_merge($params, array('userid'.$forumid=>$USER->id
, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1132 $context = $forum->context
;
1134 if ($forum->type
== 'qanda'
1135 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1136 if (!empty($forum->onlydiscussions
)) {
1137 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions
, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
1138 $params = array_merge($params, $discussionid_params);
1139 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1141 $select[] = "p.parent = 0";
1145 if (!empty($forum->onlygroups
)) {
1146 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups
, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
1147 $params = array_merge($params, $groupid_params);
1148 $select[] = "d.groupid $groupid_sql";
1152 $selects = implode(" AND ", $select);
1153 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1154 $params['forum'.$forumid] = $forumid;
1156 $fullaccess[] = $forumid;
1161 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED
, 'fula');
1162 $params = array_merge($params, $fullid_params);
1163 $where[] = "(d.forum $fullid_sql)";
1167 if (in_array('starredonly:on', $searchterms)) {
1168 $usercontext = context_user
::instance($USER->id
);
1169 $ufservice = \core_favourites\service_factory
::get_service_for_user_context($usercontext);
1170 list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions',
1171 "favourited", "d.id");
1173 $searchterms = array_values(array_diff($searchterms, array('starredonly:on')));
1174 $params = array_merge($params, $favparams);
1175 $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0";
1178 $selectdiscussion = "(".implode(" OR ", $where).")";
1180 $messagesearch = '';
1183 // Need to concat these back together for parser to work.
1184 foreach($searchterms as $searchterm){
1185 if ($searchstring != '') {
1186 $searchstring .= ' ';
1188 $searchstring .= $searchterm;
1191 // We need to allow quoted strings for the search. The quotes *should* be stripped
1192 // by the parser, but this should be examined carefully for security implications.
1193 $searchstring = str_replace("\\\"","\"",$searchstring);
1194 $parser = new search_parser();
1195 $lexer = new search_lexer($parser);
1197 if ($lexer->parse($searchstring)) {
1198 $parsearray = $parser->get_parsed_array();
1204 foreach ($parsearray as $token) {
1205 if ($token->getType() == TOKEN_TAGS
) {
1206 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++
) {
1207 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1208 if ($tagfieldcount > 10) {
1211 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
1212 ON p.id = ti_$tagfieldcount.itemid
1213 AND ti_$tagfieldcount.component = 'mod_forum'
1214 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
1215 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1216 $tagfields[] = "t_$tagfieldcount.rawname";
1221 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1222 'p.userid', 'u.id', 'u.firstname',
1223 'u.lastname', 'p.modified', 'd.forum',
1226 $params = ($msparams ?
array_merge($params, $msparams) : $params);
1230 $fromsql = "{forum_posts} p
1231 INNER JOIN {forum_discussions} d ON d.id = p.discussion
1232 INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin";
1234 $selectsql = ($messagesearch ?
$messagesearch . " AND " : "").
1235 " p.discussion = d.id
1237 AND $selectdiscussion
1240 $countsql = "SELECT COUNT(*)
1244 $userfieldsapi = \core_user\fields
::for_name();
1245 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
1246 $searchsql = "SELECT p.*,
1254 ORDER BY p.modified DESC";
1256 $totalcount = $DB->count_records_sql($countsql, $params);
1258 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
1262 * Get all the posts for a user in a forum suitable for forum_print_post
1266 * @uses CONTEXT_MODULE
1269 function forum_get_user_posts($forumid, $userid) {
1273 $params = array($forumid, $userid);
1275 if (!empty($CFG->forum_enabletimedposts
)) {
1276 $cm = get_coursemodule_from_instance('forum', $forumid);
1277 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
1279 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1285 $userfieldsapi = \core_user\fields
::for_name();
1286 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
1287 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1289 JOIN {forum_discussions} d ON d.forum = f.id
1290 JOIN {forum_posts} p ON p.discussion = d.id
1291 JOIN {user} u ON u.id = p.userid
1295 ORDER BY p.modified ASC", $params);
1299 * Get all the discussions user participated in
1303 * @uses CONTEXT_MODULE
1304 * @param int $forumid
1305 * @param int $userid
1306 * @return array Array or false
1308 function forum_get_user_involved_discussions($forumid, $userid) {
1312 $params = array($forumid, $userid);
1313 if (!empty($CFG->forum_enabletimedposts
)) {
1314 $cm = get_coursemodule_from_instance('forum', $forumid);
1315 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
1317 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1323 return $DB->get_records_sql("SELECT DISTINCT d.*
1325 JOIN {forum_discussions} d ON d.forum = f.id
1326 JOIN {forum_posts} p ON p.discussion = d.id
1329 $timedsql", $params);
1333 * Get all the posts for a user in a forum suitable for forum_print_post
1337 * @param int $forumid
1338 * @param int $userid
1339 * @return stdClass|false collection of counts or false
1341 function forum_count_user_posts($forumid, $userid) {
1345 $params = array($forumid, $userid);
1346 if (!empty($CFG->forum_enabletimedposts
)) {
1347 $cm = get_coursemodule_from_instance('forum', $forumid);
1348 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
1350 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1356 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1358 JOIN {forum_discussions} d ON d.forum = f.id
1359 JOIN {forum_posts} p ON p.discussion = d.id
1360 JOIN {user} u ON u.id = p.userid
1363 $timedsql", $params);
1367 * Given a log entry, return the forum post details for it.
1371 * @param object $log
1372 * @return array|null
1374 function forum_get_post_from_log($log) {
1377 $userfieldsapi = \core_user\fields
::for_name();
1378 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
1379 if ($log->action
== "add post") {
1381 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1382 FROM {forum_discussions} d,
1387 AND d.id = p.discussion
1389 AND u.deleted <> '1'
1390 AND f.id = d.forum", array($log->info
));
1393 } else if ($log->action
== "add discussion") {
1395 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1396 FROM {forum_discussions} d,
1401 AND d.firstpost = p.id
1403 AND u.deleted <> '1'
1404 AND f.id = d.forum", array($log->info
));
1410 * Given a discussion id, return the first post from the discussion
1414 * @param int $dicsussionid
1417 function forum_get_firstpost_from_discussion($discussionid) {
1420 return $DB->get_record_sql("SELECT p.*
1421 FROM {forum_discussions} d,
1424 AND d.firstpost = p.id ", array($discussionid));
1428 * Returns an array of counts of replies to each discussion
1430 * @param int $forumid
1431 * @param string $forumsort
1434 * @param int $perpage
1435 * @param boolean $canseeprivatereplies Whether the current user can see private replies.
1438 function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0,
1439 $canseeprivatereplies = false) {
1440 global $CFG, $DB, $USER;
1445 } else if ($page != -1) {
1446 $limitfrom = $page*$perpage;
1447 $limitnum = $perpage;
1453 if ($forumsort == "") {
1458 $orderby = "ORDER BY $forumsort";
1459 $groupby = ", ".strtolower($forumsort);
1460 $groupby = str_replace('desc', '', $groupby);
1461 $groupby = str_replace('asc', '', $groupby);
1464 $params = ['forumid' => $forumid];
1466 if (!$canseeprivatereplies) {
1467 $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)';
1468 $params['currentuser1'] = $USER->id
;
1469 $params['currentuser2'] = $USER->id
;
1474 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1475 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
1476 FROM {forum_posts} p
1477 JOIN {forum_discussions} d ON p.discussion = d.id
1478 WHERE p.parent > 0 AND d.forum = :forumid
1480 GROUP BY p.discussion";
1481 return $DB->get_records_sql($sql, $params);
1484 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
1485 FROM {forum_posts} p
1486 JOIN {forum_discussions} d ON p.discussion = d.id
1487 WHERE d.forum = :forumid
1489 GROUP BY p.discussion $groupby $orderby";
1490 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1498 * @param object $forum
1500 * @param object $course
1503 function forum_count_discussions($forum, $cm, $course) {
1504 global $CFG, $DB, $USER;
1506 $cache = cache
::make('mod_forum', 'forum_count_discussions');
1507 $cachedcounts = $cache->get($course->id
);
1508 if ($cachedcounts === false) {
1512 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1514 $params = array($course->id
);
1516 if (!isset($cachedcounts[$forum->id
])) {
1517 // Initialize the cachedcounts for this forum id to 0 by default. After the
1518 // database query, if there are discussions then it should update the count.
1519 $cachedcounts[$forum->id
] = 0;
1521 if (!empty($CFG->forum_enabletimedposts
)) {
1522 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1529 $sql = "SELECT f.id, COUNT(d.id) as dcount
1531 JOIN {forum_discussions} d ON d.forum = f.id
1536 if ($counts = $DB->get_records_sql($sql, $params)) {
1537 foreach ($counts as $count) {
1538 $cachedcounts[$count->id
] = $count->dcount
;
1541 $cache->set($course->id
, $cachedcounts);
1543 $cache->set($course->id
, $cachedcounts);
1544 return $cachedcounts[$forum->id
];
1548 $groupmode = groups_get_activity_groupmode($cm, $course);
1550 if ($groupmode != SEPARATEGROUPS
) {
1551 return $cachedcounts[$forum->id
];
1554 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
1555 return $cachedcounts[$forum->id
];
1558 require_once($CFG->dirroot
.'/course/lib.php');
1560 $modinfo = get_fast_modinfo($course);
1562 $mygroups = $modinfo->get_groups($cm->groupingid
);
1564 // add all groups posts
1567 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1568 $params[] = $forum->id
;
1570 if (!empty($CFG->forum_enabletimedposts
)) {
1571 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
1578 $sql = "SELECT COUNT(d.id)
1579 FROM {forum_discussions} d
1580 WHERE d.groupid $mygroups_sql AND d.forum = ?
1583 return $DB->get_field_sql($sql, $params);
1587 * Get all discussions in a forum
1592 * @uses CONTEXT_MODULE
1593 * @uses VISIBLEGROUPS
1595 * @param string $forumsort
1596 * @param bool $fullpost
1597 * @param int $unused
1599 * @param bool $userlastmodified
1601 * @param int $perpage
1602 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1603 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
1604 * @param int $updatedsince retrieve only discussions updated since the given time
1607 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
1608 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
1609 $updatedsince = 0) {
1610 global $CFG, $DB, $USER;
1614 $now = floor(time() / 60) * 60;
1615 $params = array($cm->instance
);
1617 $modcontext = context_module
::instance($cm->id
);
1619 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1623 if (!empty($CFG->forum_enabletimedposts
)) { /// Users must fulfill timed posts
1625 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1626 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1630 $timelimit .= " OR d.userid = ?";
1631 $params[] = $USER->id
;
1640 } else if ($page != -1) {
1641 $limitfrom = $page*$perpage;
1642 $limitnum = $perpage;
1648 $groupmode = groups_get_activity_groupmode($cm);
1652 if (empty($modcontext)) {
1653 $modcontext = context_module
::instance($cm->id
);
1656 // Special case, we received a groupid to override currentgroup.
1658 $course = get_course($cm->course
);
1659 if (!groups_group_visible($groupid, $course, $cm)) {
1660 // User doesn't belong to this group, return nothing.
1663 $currentgroup = $groupid;
1664 } else if ($groupid === -1) {
1665 $currentgroup = groups_get_activity_group($cm);
1667 // Get discussions for all groups current user can see.
1668 $currentgroup = null;
1671 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
1672 if ($currentgroup) {
1673 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1674 $params[] = $currentgroup;
1682 // Get discussions for all groups current user can see.
1683 if ($currentgroup === null) {
1684 $mygroups = array_keys(groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
, 'g.id'));
1685 if (empty($mygroups)) {
1686 $groupselect = "AND d.groupid = -1";
1688 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1689 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1690 $params = array_merge($params, $inparamsgroups);
1692 } else if ($currentgroup) {
1693 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1694 $params[] = $currentgroup;
1696 $groupselect = "AND d.groupid = -1";
1702 if (empty($forumsort)) {
1703 $forumsort = forum_get_default_sort_order();
1705 if (empty($fullpost)) {
1706 $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
1711 $userfieldsapi = \core_user\fields
::for_name();
1713 if (empty($userlastmodified)) { // We don't need to know this
1717 $umfields = $userfieldsapi->get_sql('um', false, 'um')->selects
. ', um.email AS umemail, um.picture AS umpicture,
1718 um.imagealt AS umimagealt';
1719 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
1722 $updatedsincesql = '';
1723 if (!empty($updatedsince)) {
1724 $updatedsincesql = 'AND d.timemodified > ?';
1725 $params[] = $updatedsince;
1728 $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
1729 " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked";
1731 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
1732 $sql = "SELECT $postdata, $discussionfields,
1733 $allnames, u.email, u.picture, u.imagealt, u.deleted AS userdeleted $umfields
1734 FROM {forum_discussions} d
1735 JOIN {forum_posts} p ON p.discussion = d.id
1736 JOIN {user} u ON p.userid = u.id
1738 WHERE d.forum = ? AND p.parent = 0
1739 $timelimit $groupselect $updatedsincesql
1740 ORDER BY $forumsort, d.id DESC";
1742 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1746 * Gets the neighbours (previous and next) of a discussion.
1748 * The calculation is based on the timemodified when time modified or time created is identical
1749 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
1751 * For blog-style forums, the calculation is based on the original creation time of the
1754 * Please note that this does not check whether or not the discussion passed is accessible
1755 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1756 * the returned neighbours are checked and are accessible to the current user.
1758 * @param object $cm The CM record.
1759 * @param object $discussion The discussion record.
1760 * @param object $forum The forum instance record.
1761 * @return array That always contains the keys 'prev' and 'next'. When there is a result
1762 * they contain the record with minimal information such as 'id' and 'name'.
1763 * When the neighbour is not found the value is false.
1765 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
1766 global $CFG, $DB, $USER;
1768 if ($cm->instance
!= $discussion->forum
or $discussion->forum
!= $forum->id
or $forum->id
!= $cm->instance
) {
1769 throw new coding_exception('Discussion is not part of the same forum.');
1772 $neighbours = array('prev' => false, 'next' => false);
1773 $now = floor(time() / 60) * 60;
1776 $modcontext = context_module
::instance($cm->id
);
1777 $groupmode = groups_get_activity_groupmode($cm);
1778 $currentgroup = groups_get_activity_group($cm);
1780 // Users must fulfill timed posts.
1782 if (!empty($CFG->forum_enabletimedposts
)) {
1783 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1784 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1785 $params['tltimestart'] = $now;
1786 $params['tltimeend'] = $now;
1788 $timelimit .= ' OR d.userid = :tluserid';
1789 $params['tluserid'] = $USER->id
;
1795 // Limiting to posts accessible according to groups.
1798 if ($groupmode == VISIBLEGROUPS ||
has_capability('moodle/site:accessallgroups', $modcontext)) {
1799 if ($currentgroup) {
1800 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1801 $params['groupid'] = $currentgroup;
1804 if ($currentgroup) {
1805 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1806 $params['groupid'] = $currentgroup;
1808 $groupselect = 'AND d.groupid = -1';
1813 $params['forumid'] = $cm->instance
;
1814 $params['discid1'] = $discussion->id
;
1815 $params['discid2'] = $discussion->id
;
1816 $params['discid3'] = $discussion->id
;
1817 $params['discid4'] = $discussion->id
;
1818 $params['disctimecompare1'] = $discussion->timemodified
;
1819 $params['disctimecompare2'] = $discussion->timemodified
;
1820 $params['pinnedstate1'] = (int) $discussion->pinned
;
1821 $params['pinnedstate2'] = (int) $discussion->pinned
;
1822 $params['pinnedstate3'] = (int) $discussion->pinned
;
1823 $params['pinnedstate4'] = (int) $discussion->pinned
;
1825 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1826 FROM {forum_discussions} d
1827 JOIN {forum_posts} p ON d.firstpost = p.id
1828 WHERE d.forum = :forumid
1829 AND d.id <> :discid1
1832 $comparefield = "d.timemodified";
1833 $comparevalue = ":disctimecompare1";
1834 $comparevalue2 = ":disctimecompare2";
1835 if (!empty($CFG->forum_enabletimedposts
)) {
1836 // Here we need to take into account the release time (timestart)
1837 // if one is set, of the neighbouring posts and compare it to the
1838 // timestart or timemodified of *this* post depending on if the
1839 // release date of this post is in the future or not.
1840 // This stops discussions that appear later because of the
1841 // timestart value from being buried under discussions that were
1843 $comparefield = "CASE WHEN d.timemodified < d.timestart
1844 THEN d.timestart ELSE d.timemodified END";
1845 if ($discussion->timemodified
< $discussion->timestart
) {
1846 // Normally we would just use the timemodified for sorting
1847 // discussion posts. However, when timed discussions are enabled,
1848 // then posts need to be sorted base on the later of timemodified
1849 // or the release date of the post (timestart).
1850 $params['disctimecompare1'] = $discussion->timestart
;
1851 $params['disctimecompare2'] = $discussion->timestart
;
1854 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1855 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
1857 if ($forum->type
=== 'blog') {
1858 $subselect = "SELECT pp.created
1859 FROM {forum_discussions} dd
1860 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
1862 $subselectwhere1 = " WHERE dd.id = :discid3";
1863 $subselectwhere2 = " WHERE dd.id = :discid4";
1865 $comparefield = "p.created";
1867 $sub1 = $subselect.$subselectwhere1;
1868 $comparevalue = "($sub1)";
1870 $sub2 = $subselect.$subselectwhere2;
1871 $comparevalue2 = "($sub2)";
1873 $orderbydesc = "d.pinned, p.created DESC";
1874 $orderbyasc = "d.pinned, p.created ASC";
1877 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1878 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1879 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1880 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
1882 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1883 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1884 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1885 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
1887 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE
);
1888 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE
);
1893 * Get the sql to use in the ORDER BY clause for forum discussions.
1895 * This has the ordering take timed discussion windows into account.
1897 * @param bool $desc True for DESC, False for ASC.
1898 * @param string $compare The field in the SQL to compare to normally sort by.
1899 * @param string $prefix The prefix being used for the discussion table.
1900 * @param bool $pinned sort pinned posts to the top
1903 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1906 if (!empty($prefix)) {
1910 $dir = $desc ?
'DESC' : 'ASC';
1912 if ($pinned == true) {
1913 $pinned = "{$prefix}pinned DESC,";
1918 $sort = "{$prefix}timemodified";
1919 if (!empty($CFG->forum_enabletimedposts
)) {
1920 $sort = "CASE WHEN {$compare} < {$prefix}timestart
1921 THEN {$prefix}timestart
1925 return "$pinned $sort $dir";
1933 * @uses CONTEXT_MODULE
1934 * @uses VISIBLEGROUPS
1938 function forum_get_discussions_unread($cm) {
1939 global $CFG, $DB, $USER;
1941 $now = floor(time() / 60) * 60;
1942 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
1945 $groupmode = groups_get_activity_groupmode($cm);
1946 $currentgroup = groups_get_activity_group($cm);
1949 $modcontext = context_module
::instance($cm->id
);
1951 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
1952 if ($currentgroup) {
1953 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1954 $params['currentgroup'] = $currentgroup;
1960 //separate groups without access all
1961 if ($currentgroup) {
1962 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1963 $params['currentgroup'] = $currentgroup;
1965 $groupselect = "AND d.groupid = -1";
1972 if (!empty($CFG->forum_enabletimedposts
)) {
1973 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
1974 $params['now1'] = $now;
1975 $params['now2'] = $now;
1980 $sql = "SELECT d.id, COUNT(p.id) AS unread
1981 FROM {forum_discussions} d
1982 JOIN {forum_posts} p ON p.discussion = d.id
1983 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
1984 WHERE d.forum = {$cm->instance}
1985 AND p.modified >= :cutoffdate AND r.id is NULL
1989 $params['cutoffdate'] = $cutoffdate;
1991 if ($unreads = $DB->get_records_sql($sql, $params)) {
1992 foreach ($unreads as $unread) {
1993 $unreads[$unread->id
] = $unread->unread
;
2005 * @uses CONEXT_MODULE
2006 * @uses VISIBLEGROUPS
2010 function forum_get_discussions_count($cm) {
2011 global $CFG, $DB, $USER;
2013 $now = floor(time() / 60) * 60;
2014 $params = array($cm->instance
);
2015 $groupmode = groups_get_activity_groupmode($cm);
2016 $currentgroup = groups_get_activity_group($cm);
2019 $modcontext = context_module
::instance($cm->id
);
2021 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2022 if ($currentgroup) {
2023 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2024 $params[] = $currentgroup;
2030 //seprate groups without access all
2031 if ($currentgroup) {
2032 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2033 $params[] = $currentgroup;
2035 $groupselect = "AND d.groupid = -1";
2044 if (!empty($CFG->forum_enabletimedposts
)) {
2046 $modcontext = context_module
::instance($cm->id
);
2048 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2049 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2053 $timelimit .= " OR d.userid = ?";
2054 $params[] = $USER->id
;
2060 $sql = "SELECT COUNT(d.id)
2061 FROM {forum_discussions} d
2062 JOIN {forum_posts} p ON p.discussion = d.id
2063 WHERE d.forum = ? AND p.parent = 0
2064 $groupselect $timelimit";
2066 return $DB->get_field_sql($sql, $params);
2070 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2076 * @param int $courseid
2077 * @param string $type
2079 function forum_get_course_forum($courseid, $type) {
2080 // How to set up special 1-per-course forums
2081 global $CFG, $DB, $OUTPUT, $USER;
2083 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2084 // There should always only be ONE, but with the right combination of
2085 // errors there might be more. In this case, just return the oldest one (lowest ID).
2086 foreach ($forums as $forum) {
2087 return $forum; // ie the first one
2091 // Doesn't exist, so create one now.
2092 $forum = new stdClass();
2093 $forum->course
= $courseid;
2094 $forum->type
= "$type";
2095 if (!empty($USER->htmleditor
)) {
2096 $forum->introformat
= $USER->htmleditor
;
2098 switch ($forum->type
) {
2100 $forum->name
= get_string("namenews", "forum");
2101 $forum->intro
= get_string("intronews", "forum");
2102 $forum->introformat
= FORMAT_HTML
;
2103 $forum->forcesubscribe
= $CFG->forum_announcementsubscription
;
2104 $forum->maxattachments
= $CFG->forum_announcementmaxattachments
;
2105 $forum->assessed
= 0;
2106 if ($courseid == SITEID
) {
2107 $forum->name
= get_string("sitenews");
2108 $forum->forcesubscribe
= 0;
2112 $forum->name
= get_string("namesocial", "forum");
2113 $forum->intro
= get_string("introsocial", "forum");
2114 $forum->introformat
= FORMAT_HTML
;
2115 $forum->assessed
= 0;
2116 $forum->forcesubscribe
= 0;
2119 $forum->name
= get_string('blogforum', 'forum');
2120 $forum->intro
= get_string('introblog', 'forum');
2121 $forum->introformat
= FORMAT_HTML
;
2122 $forum->assessed
= 0;
2123 $forum->forcesubscribe
= 0;
2126 echo $OUTPUT->notification("That forum type doesn't exist!");
2131 $forum->timemodified
= time();
2132 $forum->id
= $DB->insert_record("forum", $forum);
2134 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2135 echo $OUTPUT->notification("Could not find forum module!!");
2138 $mod = new stdClass();
2139 $mod->course
= $courseid;
2140 $mod->module
= $module->id
;
2141 $mod->instance
= $forum->id
;
2143 include_once("$CFG->dirroot/course/lib.php");
2144 if (! $mod->coursemodule
= add_course_module($mod) ) {
2145 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2148 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule
, 0);
2149 return $DB->get_record("forum", array("id" => "$forum->id"));
2153 * Return rating related permissions
2155 * @param string $options the context id
2156 * @return array an associative array of the user's rating permissions
2158 function forum_rating_permissions($contextid, $component, $ratingarea) {
2159 $context = context
::instance_by_id($contextid, MUST_EXIST
);
2160 if ($component != 'mod_forum' ||
$ratingarea != 'post') {
2161 // We don't know about this component/ratingarea so just return null to get the
2162 // default restrictive permissions.
2166 'view' => has_capability('mod/forum:viewrating', $context),
2167 'viewany' => has_capability('mod/forum:viewanyrating', $context),
2168 'viewall' => has_capability('mod/forum:viewallratings', $context),
2169 'rate' => has_capability('mod/forum:rate', $context)
2174 * Validates a submitted rating
2175 * @param array $params submitted data
2176 * context => object the context in which the rated items exists [required]
2177 * component => The component for this module - should always be mod_forum [required]
2178 * ratingarea => object the context in which the rated items exists [required]
2180 * itemid => int the ID of the object being rated [required]
2181 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2182 * rating => int the submitted rating [required]
2183 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2184 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
2185 * @return boolean true if the rating is valid. Will throw rating_exception if not
2187 function forum_rating_validate($params) {
2190 // Check the component is mod_forum
2191 if ($params['component'] != 'mod_forum') {
2192 throw new rating_exception('invalidcomponent');
2195 // Check the ratingarea is post (the only rating area in forum)
2196 if ($params['ratingarea'] != 'post') {
2197 throw new rating_exception('invalidratingarea');
2200 // Check the rateduserid is not the current user .. you can't rate your own posts
2201 if ($params['rateduserid'] == $USER->id
) {
2202 throw new rating_exception('nopermissiontorate');
2205 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2206 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST
);
2207 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
), '*', MUST_EXIST
);
2208 $forum = $DB->get_record('forum', array('id' => $discussion->forum
), '*', MUST_EXIST
);
2209 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
2210 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
2211 $context = context_module
::instance($cm->id
);
2213 // Make sure the context provided is the context of the forum
2214 if ($context->id
!= $params['context']->id
) {
2215 throw new rating_exception('invalidcontext');
2218 if ($forum->scale
!= $params['scaleid']) {
2219 //the scale being submitted doesnt match the one in the database
2220 throw new rating_exception('invalidscaleid');
2223 // check the item we're rating was created in the assessable time window
2224 if (!empty($forum->assesstimestart
) && !empty($forum->assesstimefinish
)) {
2225 if ($post->created
< $forum->assesstimestart ||
$post->created
> $forum->assesstimefinish
) {
2226 throw new rating_exception('notavailable');
2230 //check that the submitted rating is valid for the scale
2233 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
2234 throw new rating_exception('invalidnum');
2238 if ($forum->scale
< 0) {
2239 //its a custom scale
2240 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale
));
2242 $scalearray = explode(',', $scalerecord->scale
);
2243 if ($params['rating'] > count($scalearray)) {
2244 throw new rating_exception('invalidnum');
2247 throw new rating_exception('invalidscaleid');
2249 } else if ($params['rating'] > $forum->scale
) {
2250 //if its numeric and submitted rating is above maximum
2251 throw new rating_exception('invalidnum');
2254 // Make sure groups allow this user to see the item they're rating
2255 if ($discussion->groupid
> 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
2256 if (!groups_group_exists($discussion->groupid
)) { // Can't find group
2257 throw new rating_exception('cannotfindgroup');//something is wrong
2260 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
2261 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
2262 throw new rating_exception('notmemberofgroup');
2266 // perform some final capability checks
2267 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2268 throw new rating_exception('nopermissiontorate');
2275 * Can the current user see ratings for a given itemid?
2277 * @param array $params submitted data
2278 * contextid => int contextid [required]
2279 * component => The component for this module - should always be mod_forum [required]
2280 * ratingarea => object the context in which the rated items exists [required]
2281 * itemid => int the ID of the object being rated [required]
2282 * scaleid => int scale id [optional]
2284 * @throws coding_exception
2285 * @throws rating_exception
2287 function mod_forum_rating_can_see_item_ratings($params) {
2290 // Check the component is mod_forum.
2291 if (!isset($params['component']) ||
$params['component'] != 'mod_forum') {
2292 throw new rating_exception('invalidcomponent');
2295 // Check the ratingarea is post (the only rating area in forum).
2296 if (!isset($params['ratingarea']) ||
$params['ratingarea'] != 'post') {
2297 throw new rating_exception('invalidratingarea');
2300 if (!isset($params['itemid'])) {
2301 throw new rating_exception('invaliditemid');
2304 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST
);
2305 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
), '*', MUST_EXIST
);
2306 $forum = $DB->get_record('forum', array('id' => $discussion->forum
), '*', MUST_EXIST
);
2307 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
2308 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
2310 // Perform some final capability checks.
2311 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2319 * Return the markup for the discussion subscription toggling icon.
2321 * @param stdClass $forum The forum object.
2322 * @param int $discussionid The discussion to create an icon for.
2323 * @return string The generated markup.
2325 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2326 global $USER, $OUTPUT, $PAGE;
2328 if ($returnurl === null && $PAGE->url
) {
2329 $returnurl = $PAGE->url
->out();
2333 $subscriptionstatus = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum, $discussionid);
2334 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2335 'sesskey' => sesskey(),
2337 'd' => $discussionid,
2338 'returnurl' => $returnurl,
2342 $o .= $subscriptionstatus ?
get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2345 if ($subscriptionstatus) {
2346 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2348 $output .= get_string('subscribed', 'mod_forum');
2351 return html_writer
::link($subscriptionlink, $output, array(
2352 'title' => get_string('clicktounsubscribe', 'forum'),
2353 'class' => 'discussiontoggle btn btn-link',
2354 'data-forumid' => $forum->id
,
2355 'data-discussionid' => $discussionid,
2356 'data-includetext' => $includetext,
2360 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2362 $output .= get_string('notsubscribed', 'mod_forum');
2365 return html_writer
::link($subscriptionlink, $output, array(
2366 'title' => get_string('clicktosubscribe', 'forum'),
2367 'class' => 'discussiontoggle btn btn-link',
2368 'data-forumid' => $forum->id
,
2369 'data-discussionid' => $discussionid,
2370 'data-includetext' => $includetext,
2376 * Return a pair of spans containing classes to allow the subscribe and
2377 * unsubscribe icons to be pre-loaded by a browser.
2379 * @return string The generated markup
2381 function forum_get_discussion_subscription_icon_preloaders() {
2383 $o .= html_writer
::span(' ', 'preload-subscribe');
2384 $o .= html_writer
::span(' ', 'preload-unsubscribe');
2389 * Print the drop down that allows the user to select how they want to have
2390 * the discussion displayed.
2392 * @param int $id forum id if $forumtype is 'single',
2393 * discussion id for any other forum type
2394 * @param mixed $mode forum layout mode
2395 * @param string $forumtype optional
2397 function forum_print_mode_form($id, $mode, $forumtype='') {
2399 $useexperimentalui = get_user_preferences('forum_useexperimentalui', false);
2400 if ($forumtype == 'single') {
2401 $select = new single_select(
2402 new moodle_url("/mod/forum/view.php",
2405 forum_get_layout_modes($useexperimentalui),
2410 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2411 $select->class = "forummode";
2413 $select = new single_select(
2414 new moodle_url("/mod/forum/discuss.php",
2417 forum_get_layout_modes($useexperimentalui),
2422 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2424 echo $OUTPUT->render($select);
2429 * @param object $course
2430 * @param string $search
2433 function forum_search_form($course, $search='') {
2435 $forumsearch = new \mod_forum\output\
quick_search_form($course->id
, $search);
2436 $output = $PAGE->get_renderer('mod_forum');
2437 return $output->render($forumsearch);
2441 * Retrieve HTML for the page action
2443 * @param forum_entity|null $forum The forum entity.
2444 * @param mixed $groupid false if groups not used, int if groups used, 0 means all groups
2445 * @param stdClass $course The course object.
2446 * @param string $search The search string.
2447 * @return string rendered HTML string.
2449 function forum_activity_actionbar(?forum_entity
$forum, $groupid, stdClass
$course, string $search=''): string {
2452 $actionbar = new mod_forum\output\forum_actionbar
($forum, $course, $groupid, $search);
2453 $output = $PAGE->get_renderer('mod_forum');
2454 return $output->render($actionbar);
2461 function forum_set_return() {
2462 global $CFG, $SESSION;
2464 if (! isset($SESSION->fromdiscussion
)) {
2465 $referer = get_local_referer(false);
2466 // If the referer is NOT a login screen then save it.
2467 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2468 $SESSION->fromdiscussion
= $referer;
2476 * @param string|\moodle_url $default
2479 function forum_go_back_to($default) {
2482 if (!empty($SESSION->fromdiscussion
)) {
2483 $returnto = $SESSION->fromdiscussion
;
2484 unset($SESSION->fromdiscussion
);
2492 * Given a discussion object that is being moved to $forumto,
2493 * this function checks all posts in that discussion
2494 * for attachments, and if any are found, these are
2495 * moved to the new forum directory.
2498 * @param object $discussion
2499 * @param int $forumfrom source forum id
2500 * @param int $forumto target forum id
2501 * @return bool success
2503 function forum_move_attachments($discussion, $forumfrom, $forumto) {
2506 $fs = get_file_storage();
2508 $newcm = get_coursemodule_from_instance('forum', $forumto);
2509 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2511 $newcontext = context_module
::instance($newcm->id
);
2512 $oldcontext = context_module
::instance($oldcm->id
);
2514 // loop through all posts, better not use attachment flag ;-)
2515 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id
), '', 'id, attachment')) {
2516 foreach ($posts as $post) {
2517 $fs->move_area_files_to_new_context($oldcontext->id
,
2518 $newcontext->id
, 'mod_forum', 'post', $post->id
);
2519 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id
,
2520 $newcontext->id
, 'mod_forum', 'attachment', $post->id
);
2521 if ($attachmentsmoved > 0 && $post->attachment
!= '1') {
2522 // Weird - let's fix it
2523 $post->attachment
= '1';
2524 $DB->update_record('forum_posts', $post);
2525 } else if ($attachmentsmoved == 0 && $post->attachment
!= '') {
2526 // Weird - let's fix it
2527 $post->attachment
= '';
2528 $DB->update_record('forum_posts', $post);
2537 * Returns attachments as formated text/html optionally with separate images
2542 * @param object $post
2544 * @param string $type html/text/separateimages
2545 * @return mixed string or array of (html text withouth images and image HTML)
2547 function forum_print_attachments($post, $cm, $type) {
2548 global $CFG, $DB, $USER, $OUTPUT;
2550 if (empty($post->attachment
)) {
2551 return $type !== 'separateimages' ?
'' : array('', '');
2554 if (!in_array($type, array('separateimages', 'html', 'text'))) {
2555 return $type !== 'separateimages' ?
'' : array('', '');
2558 if (!$context = context_module
::instance($cm->id
)) {
2559 return $type !== 'separateimages' ?
'' : array('', '');
2561 $strattachment = get_string('attachment', 'forum');
2563 $fs = get_file_storage();
2568 $canexport = !empty($CFG->enableportfolios
) && (has_capability('mod/forum:exportpost', $context) ||
($post->userid
== $USER->id
&& has_capability('mod/forum:exportownpost', $context)));
2571 require_once($CFG->libdir
.'/portfoliolib.php');
2574 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
2575 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2576 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "filename", false);
2579 $button = new portfolio_add_button();
2581 foreach ($files as $file) {
2582 $filename = $file->get_filename();
2583 $mimetype = $file->get_mimetype();
2584 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2585 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_forum/attachment/'.$post->id
.'/'.$filename);
2587 if ($type == 'html') {
2588 $output .= "<a href=\"$path\">$iconimage</a> ";
2589 $output .= "<a href=\"$path\">".s($filename)."</a>";
2591 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
2592 $button->set_format_by_file($file);
2593 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
2595 $output .= "<br />";
2597 } else if ($type == 'text') {
2598 $output .= "$strattachment ".s($filename).":\n$path\n";
2600 } else { //'returnimages'
2601 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2602 // Image attachments don't get printed as links
2603 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2605 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
2606 $button->set_format_by_file($file);
2607 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
2610 $output .= "<a href=\"$path\">$iconimage</a> ";
2611 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
2613 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
2614 $button->set_format_by_file($file);
2615 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
2617 $output .= '<br />';
2621 if (!empty($CFG->enableplagiarism
)) {
2622 require_once($CFG->libdir
.'/plagiarismlib.php');
2623 $output .= plagiarism_get_links(array('userid' => $post->userid
,
2626 'course' => $cm->course
,
2627 'forum' => $cm->instance
));
2628 $output .= '<br />';
2633 if ($type !== 'separateimages') {
2637 return array($output, $imagereturn);
2641 ////////////////////////////////////////////////////////////////////////////////
2643 ////////////////////////////////////////////////////////////////////////////////
2646 * Lists all browsable file areas
2648 * @package mod_forum
2650 * @param stdClass $course course object
2651 * @param stdClass $cm course module object
2652 * @param stdClass $context context object
2655 function forum_get_file_areas($course, $cm, $context) {
2657 'attachment' => get_string('areaattachment', 'mod_forum'),
2658 'post' => get_string('areapost', 'mod_forum'),
2663 * File browsing support for forum module.
2665 * @package mod_forum
2667 * @param stdClass $browser file browser object
2668 * @param stdClass $areas file areas
2669 * @param stdClass $course course object
2670 * @param stdClass $cm course module
2671 * @param stdClass $context context module
2672 * @param string $filearea file area
2673 * @param int $itemid item ID
2674 * @param string $filepath file path
2675 * @param string $filename file name
2676 * @return file_info instance or null if not found
2678 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2679 global $CFG, $DB, $USER;
2681 if ($context->contextlevel
!= CONTEXT_MODULE
) {
2685 // filearea must contain a real area
2686 if (!isset($areas[$filearea])) {
2690 // Note that forum_user_can_see_post() additionally allows access for parent roles
2691 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2692 // course:managefiles, we will need to extend this.
2693 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2697 if (is_null($itemid)) {
2698 require_once($CFG->dirroot
.'/mod/forum/locallib.php');
2699 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2702 static $cached = array();
2703 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2704 // is cleared between unit tests we check if this is the same session
2705 if (!isset($cached['sesskey']) ||
$cached['sesskey'] != sesskey()) {
2706 $cached = array('sesskey' => sesskey());
2709 if (isset($cached['post']) && $cached['post']->id
== $itemid) {
2710 $post = $cached['post'];
2711 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2712 $cached['post'] = $post;
2717 if (isset($cached['discussion']) && $cached['discussion']->id
== $post->discussion
) {
2718 $discussion = $cached['discussion'];
2719 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
))) {
2720 $cached['discussion'] = $discussion;
2725 if (isset($cached['forum']) && $cached['forum']->id
== $cm->instance
) {
2726 $forum = $cached['forum'];
2727 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance
))) {
2728 $cached['forum'] = $forum;
2733 $fs = get_file_storage();
2734 $filepath = is_null($filepath) ?
'/' : $filepath;
2735 $filename = is_null($filename) ?
'.' : $filename;
2736 if (!($storedfile = $fs->get_file($context->id
, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2740 // Checks to see if the user can manage files or is the owner.
2741 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2742 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
2745 // Make sure groups allow this user to see this file
2746 if ($discussion->groupid
> 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2747 $groupmode = groups_get_activity_groupmode($cm, $course);
2748 if ($groupmode == SEPARATEGROUPS
&& !groups_is_member($discussion->groupid
)) {
2753 // Make sure we're allowed to see it...
2754 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2758 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
2759 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2763 * Serves the forum attachments. Implements needed access control ;-)
2765 * @package mod_forum
2767 * @param stdClass $course course object
2768 * @param stdClass $cm course module object
2769 * @param stdClass $context context object
2770 * @param string $filearea file area
2771 * @param array $args extra arguments
2772 * @param bool $forcedownload whether or not force download
2773 * @param array $options additional options affecting the file serving
2774 * @return bool false if file not found, does not return if found - justsend the file
2776 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2779 if ($context->contextlevel
!= CONTEXT_MODULE
) {
2783 require_course_login($course, true, $cm);
2785 $areas = forum_get_file_areas($course, $cm, $context);
2787 // filearea must contain a real area
2788 if (!isset($areas[$filearea])) {
2792 $postid = (int)array_shift($args);
2794 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2798 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion
))) {
2802 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance
))) {
2806 $fs = get_file_storage();
2807 $relativepath = implode('/', $args);
2808 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
2809 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2813 // Make sure groups allow this user to see this file
2814 if ($discussion->groupid
> 0) {
2815 $groupmode = groups_get_activity_groupmode($cm, $course);
2816 if ($groupmode == SEPARATEGROUPS
) {
2817 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
2823 // Make sure we're allowed to see it...
2824 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2828 // finally send the file
2829 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
2833 * If successful, this function returns the name of the file
2836 * @param object $post is a full post record, including course and forum
2837 * @param object $forum
2839 * @param mixed $mform
2840 * @param string $unused
2843 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
2846 if (empty($mform)) {
2850 if (empty($post->attachments
)) {
2851 return true; // Nothing to do
2854 $context = context_module
::instance($cm->id
);
2856 $info = file_get_draft_area_info($post->attachments
);
2857 $present = ($info['filecount']>0) ?
'1' : '';
2858 file_save_draft_area_files($post->attachments
, $context->id
, 'mod_forum', 'attachment', $post->id
,
2859 mod_forum_post_form
::attachment_options($forum));
2861 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id
));
2867 * Add a new post in an existing discussion.
2869 * @param stdClass $post The post data
2870 * @param mixed $mform The submitted form
2871 * @param string $unused
2874 function forum_add_new_post($post, $mform, $unused = null) {
2877 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
2878 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
2879 $cm = get_coursemodule_from_instance('forum', $forum->id
);
2880 $context = context_module
::instance($cm->id
);
2881 $privatereplyto = 0;
2883 // Check whether private replies should be enabled for this post.
2884 if ($post->parent
) {
2885 $parent = $DB->get_record('forum_posts', array('id' => $post->parent
));
2887 if (!empty($parent->privatereplyto
)) {
2888 throw new \
coding_exception('It should not be possible to reply to a private reply');
2891 if (!empty($post->isprivatereply
) && forum_user_can_reply_privately($context, $parent)) {
2892 $privatereplyto = $parent->userid
;
2896 $post->created
= $post->modified
= time();
2897 $post->mailed
= FORUM_MAILED_PENDING
;
2898 $post->userid
= $USER->id
;
2899 $post->privatereplyto
= $privatereplyto;
2900 $post->attachment
= "";
2901 if (!isset($post->totalscore
)) {
2902 $post->totalscore
= 0;
2904 if (!isset($post->mailnow
)) {
2908 \mod_forum\local\entities\post
::add_message_counts($post);
2909 $post->id
= $DB->insert_record("forum_posts", $post);
2910 $post->message
= file_save_draft_area_files($post->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
2911 mod_forum_post_form
::editor_options($context, null), $post->message
);
2912 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
2913 forum_add_attachment($post, $forum, $cm, $mform);
2915 // Update discussion modified date
2916 $DB->set_field("forum_discussions", "timemodified", $post->modified
, array("id" => $post->discussion
));
2917 $DB->set_field("forum_discussions", "usermodified", $post->userid
, array("id" => $post->discussion
));
2919 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
2920 forum_tp_mark_post_read($post->userid
, $post);
2923 if (isset($post->tags
)) {
2924 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, $context, $post->tags
);
2927 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
2928 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
2934 * Trigger post updated event.
2936 * @param object $post forum post object
2937 * @param object $discussion discussion object
2938 * @param object $context forum context object
2939 * @param object $forum forum object
2943 function forum_trigger_post_updated_event($post, $discussion, $context, $forum) {
2947 'context' => $context,
2948 'objectid' => $post->id
,
2950 'discussionid' => $discussion->id
,
2951 'forumid' => $forum->id
,
2952 'forumtype' => $forum->type
,
2956 if ($USER->id
!== $post->userid
) {
2957 $params['relateduserid'] = $post->userid
;
2960 $event = \mod_forum\event\post_updated
::create($params);
2961 $event->add_record_snapshot('forum_discussions', $discussion);
2968 * @param stdClass $newpost The post to update
2969 * @param mixed $mform The submitted form
2970 * @param string $unused
2973 function forum_update_post($newpost, $mform, $unused = null) {
2976 $post = $DB->get_record('forum_posts', array('id' => $newpost->id
));
2977 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
2978 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
2979 $cm = get_coursemodule_from_instance('forum', $forum->id
);
2980 $context = context_module
::instance($cm->id
);
2982 // Allowed modifiable fields.
2983 $modifiablefields = [
2993 foreach ($modifiablefields as $field) {
2994 if (isset($newpost->{$field})) {
2995 $post->{$field} = $newpost->{$field};
2998 $post->modified
= time();
3000 if (!$post->parent
) { // Post is a discussion starter - update discussion title and times too
3001 $discussion->name
= $post->subject
;
3002 $discussion->timestart
= $post->timestart
;
3003 $discussion->timeend
= $post->timeend
;
3005 if (isset($post->pinned
)) {
3006 $discussion->pinned
= $post->pinned
;
3009 $post->message
= file_save_draft_area_files($newpost->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
3010 mod_forum_post_form
::editor_options($context, $post->id
), $post->message
);
3011 \mod_forum\local\entities\post
::add_message_counts($post);
3012 $DB->update_record('forum_posts', $post);
3013 // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3014 $DB->update_record('forum_discussions', $discussion);
3016 forum_add_attachment($post, $forum, $cm, $mform);
3018 if ($forum->type
== 'single' && $post->parent
== '0') {
3019 // Updating first post of single discussion type -> updating forum intro.
3020 $forum->intro
= $post->message
;
3021 $forum->timemodified
= time();
3022 $DB->update_record("forum", $forum);
3025 if (isset($newpost->tags
)) {
3026 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, $context, $newpost->tags
);
3029 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3030 forum_tp_mark_post_read($USER->id
, $post);
3033 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3034 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3040 * Given an object containing all the necessary data,
3041 * create a new discussion and return the id
3043 * @param object $post
3044 * @param mixed $mform
3045 * @param string $unused
3046 * @param int $userid
3049 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3050 global $USER, $CFG, $DB;
3052 $timenow = isset($discussion->timenow
) ?
$discussion->timenow
: time();
3054 if (is_null($userid)) {
3055 $userid = $USER->id
;
3058 // The first post is stored as a real post, and linked
3059 // to from the discuss entry.
3061 $forum = $DB->get_record('forum', array('id'=>$discussion->forum
));
3062 $cm = get_coursemodule_from_instance('forum', $forum->id
);
3064 $post = new stdClass();
3065 $post->discussion
= 0;
3067 $post->privatereplyto
= 0;
3068 $post->userid
= $userid;
3069 $post->created
= $timenow;
3070 $post->modified
= $timenow;
3071 $post->mailed
= FORUM_MAILED_PENDING
;
3072 $post->subject
= $discussion->name
;
3073 $post->message
= $discussion->message
;
3074 $post->messageformat
= $discussion->messageformat
;
3075 $post->messagetrust
= $discussion->messagetrust
;
3076 $post->attachments
= isset($discussion->attachments
) ?
$discussion->attachments
: null;
3077 $post->forum
= $forum->id
; // speedup
3078 $post->course
= $forum->course
; // speedup
3079 $post->mailnow
= $discussion->mailnow
;
3081 \mod_forum\local\entities\post
::add_message_counts($post);
3082 $post->id
= $DB->insert_record("forum_posts", $post);
3084 // TODO: Fix the calling code so that there always is a $cm when this function is called
3085 if (!empty($cm->id
) && !empty($discussion->itemid
)) { // In "single simple discussions" this may not exist yet
3086 $context = context_module
::instance($cm->id
);
3087 $text = file_save_draft_area_files($discussion->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
3088 mod_forum_post_form
::editor_options($context, null), $post->message
);
3089 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id
));
3092 // Now do the main entry for the discussion, linking to this first post
3094 $discussion->firstpost
= $post->id
;
3095 $discussion->timemodified
= $timenow;
3096 $discussion->usermodified
= $post->userid
;
3097 $discussion->userid
= $userid;
3098 $discussion->assessed
= 0;
3100 $post->discussion
= $DB->insert_record("forum_discussions", $discussion);
3102 // Finally, set the pointer on the post.
3103 $DB->set_field("forum_posts", "discussion", $post->discussion
, array("id"=>$post->id
));
3105 if (!empty($cm->id
)) {
3106 forum_add_attachment($post, $forum, $cm, $mform, $unused);
3109 if (isset($discussion->tags
)) {
3110 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, context_module
::instance($cm->id
), $discussion->tags
);
3113 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3114 forum_tp_mark_post_read($post->userid
, $post);
3117 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3118 if (!empty($cm->id
)) {
3119 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3122 // Clear the discussion count cache just in case it's in the same request.
3123 \cache_helper
::purge_by_event('changesinforumdiscussions');
3125 return $post->discussion
;
3130 * Deletes a discussion and handles all associated cleanup.
3133 * @param object $discussion Discussion to delete
3134 * @param bool $fulldelete True when deleting entire forum
3135 * @param object $course Course
3136 * @param object $cm Course-module
3137 * @param object $forum Forum
3140 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3142 require_once($CFG->libdir
.'/completionlib.php');
3146 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id
))) {
3147 foreach ($posts as $post) {
3148 $post->course
= $discussion->course
;
3149 $post->forum
= $discussion->forum
;
3150 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3156 forum_tp_delete_read_records(-1, -1, $discussion->id
);
3158 // Discussion subscriptions must be removed before discussions because of key constraints.
3159 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id
));
3160 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id
))) {
3164 // Update completion state if we are tracking completion based on number of posts
3165 // But don't bother when deleting whole thing
3167 $completion = new completion_info($course);
3168 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
3169 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
3170 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $discussion->userid
);
3175 'objectid' => $discussion->id
,
3176 'context' => context_module
::instance($cm->id
),
3178 'forumid' => $forum->id
,
3181 $event = \mod_forum\event\discussion_deleted
::create($params);
3182 $event->add_record_snapshot('forum_discussions', $discussion);
3185 // Clear the discussion count cache just in case it's in the same request.
3186 \cache_helper
::purge_by_event('changesinforumdiscussions');
3193 * Deletes a single forum post.
3196 * @param object $post Forum post object
3197 * @param mixed $children Whether to delete children. If false, returns false
3198 * if there are any children (without deleting the post). If true,
3199 * recursively deletes all children. If set to special value 'ignore', deletes
3200 * post regardless of children (this is for use only when deleting all posts
3202 * @param object $course Course
3203 * @param object $cm Course-module
3204 * @param object $forum Forum
3205 * @param bool $skipcompletion True to skip updating completion state if it
3206 * would otherwise be updated, i.e. when deleting entire forum anyway.
3209 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3210 global $DB, $CFG, $USER;
3211 require_once($CFG->libdir
.'/completionlib.php');
3213 $context = context_module
::instance($cm->id
);
3215 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id
)))) {
3217 foreach ($childposts as $childpost) {
3218 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3226 require_once($CFG->dirroot
.'/rating/lib.php');
3227 $delopt = new stdClass
;
3228 $delopt->contextid
= $context->id
;
3229 $delopt->component
= 'mod_forum';
3230 $delopt->ratingarea
= 'post';
3231 $delopt->itemid
= $post->id
;
3232 $rm = new rating_manager();
3233 $rm->delete_ratings($delopt);
3235 // Delete attachments.
3236 $fs = get_file_storage();
3237 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment', $post->id
);
3238 $fs->delete_area_files($context->id
, 'mod_forum', 'post', $post->id
);
3240 // Delete cached RSS feeds.
3241 if (!empty($CFG->enablerssfeeds
)) {
3242 require_once($CFG->dirroot
.'/mod/forum/rsslib.php');
3243 forum_rss_delete_file($forum);
3246 if ($DB->delete_records("forum_posts", array("id" => $post->id
))) {
3248 forum_tp_delete_read_records(-1, $post->id
);
3250 // Just in case we are deleting the last post
3251 forum_discussion_update_last_post($post->discussion
);
3253 // Update completion state if we are tracking completion based on number of posts
3254 // But don't bother when deleting whole thing
3256 if (!$skipcompletion) {
3257 $completion = new completion_info($course);
3258 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
3259 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
3260 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $post->userid
);
3265 'context' => $context,
3266 'objectid' => $post->id
,
3268 'discussionid' => $post->discussion
,
3269 'forumid' => $forum->id
,
3270 'forumtype' => $forum->type
,
3274 if ($post->userid
!== $USER->id
) {
3275 $params['relateduserid'] = $post->userid
;
3277 $event = \mod_forum\event\post_deleted
::create($params);
3278 $event->add_record_snapshot('forum_posts', $post);
3287 * Sends post content to plagiarism plugin
3288 * @param object $post Forum post object
3289 * @param object $cm Course-module
3290 * @param string $name
3293 function forum_trigger_content_uploaded_event($post, $cm, $name) {
3294 $context = context_module
::instance($cm->id
);
3295 $fs = get_file_storage();
3296 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "timemodified", false);
3298 'context' => $context,
3299 'objectid' => $post->id
,
3301 'content' => $post->message
,
3302 'pathnamehashes' => array_keys($files),
3303 'discussionid' => $post->discussion
,
3304 'triggeredfrom' => $name,
3307 $event = \mod_forum\event\assessable_uploaded
::create($params);
3313 * Given a new post, subscribes or unsubscribes as appropriate.
3314 * Returns some text which describes what happened.
3316 * @param object $fromform The submitted form
3317 * @param stdClass $forum The forum record
3318 * @param stdClass $discussion The forum discussion record
3321 function forum_post_subscription($fromform, $forum, $discussion) {
3324 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
3326 } else if (\mod_forum\subscriptions
::subscription_disabled($forum)) {
3327 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
3328 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course
::instance($forum->course
), $USER->id
)) {
3329 // This user should not be subscribed to the forum.
3330 \mod_forum\subscriptions
::unsubscribe_user($USER->id
, $forum);
3335 $info = new stdClass();
3336 $info->name
= fullname($USER);
3337 $info->discussion
= format_string($discussion->name
);
3338 $info->forum
= format_string($forum->name
);
3340 if (isset($fromform->discussionsubscribe
) && $fromform->discussionsubscribe
) {
3341 if ($result = \mod_forum\subscriptions
::subscribe_user_to_discussion($USER->id
, $discussion)) {
3342 return html_writer
::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3345 if ($result = \mod_forum\subscriptions
::unsubscribe_user_from_discussion($USER->id
, $discussion)) {
3346 return html_writer
::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3354 * Generate and return the subscribe or unsubscribe link for a forum.
3356 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3357 * @param object $context the context object for this forum.
3358 * @param array $messages text used for the link in its various states
3359 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3360 * Any strings not passed in are taken from the $defaultmessages array
3361 * at the top of the function.
3362 * @param bool $cantaccessagroup
3363 * @param bool $unused1
3364 * @param bool $backtoindex
3365 * @param array $unused2
3368 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3369 $backtoindex = false, $unused2 = null) {
3370 global $CFG, $USER, $PAGE, $OUTPUT;
3371 $defaultmessages = array(
3372 'subscribed' => get_string('unsubscribe', 'forum'),
3373 'unsubscribed' => get_string('subscribe', 'forum'),
3374 'cantaccessgroup' => get_string('no'),
3375 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3376 'cantsubscribe' => get_string('disallowsubscribe','forum')
3378 $messages = $messages +
$defaultmessages;
3380 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
3381 return $messages['forcesubscribed'];
3382 } else if (\mod_forum\subscriptions
::subscription_disabled($forum) &&
3383 !has_capability('mod/forum:managesubscriptions', $context)) {
3384 return $messages['cantsubscribe'];
3385 } else if ($cantaccessagroup) {
3386 return $messages['cantaccessgroup'];
3388 if (!is_enrolled($context, $USER, '', true)) {
3392 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
3394 $linktext = $messages['subscribed'];
3395 $linktitle = get_string('subscribestop', 'forum');
3397 $linktext = $messages['unsubscribed'];
3398 $linktitle = get_string('subscribestart', 'forum');
3403 $backtoindexlink = '&backtoindex=1';
3404 $options['backtoindex'] = 1;
3406 $backtoindexlink = '';
3409 $options['id'] = $forum->id
;
3410 $options['sesskey'] = sesskey();
3411 $url = new moodle_url('/mod/forum/subscribe.php', $options);
3412 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3417 * Returns true if user created new discussion already.
3419 * @param int $forumid The forum to check for postings
3420 * @param int $userid The user to check for postings
3421 * @param int $groupid The group to restrict the check to
3424 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3428 FROM {forum_discussions} d, {forum_posts} p
3429 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3431 $params = [$forumid, $userid];
3434 $sql .= " AND d.groupid = ?";
3435 $params[] = $groupid;
3438 return $DB->record_exists_sql($sql, $params);
3444 * @param int $forumid
3445 * @param int $userid
3448 function forum_discussions_user_has_posted_in($forumid, $userid) {
3451 $haspostedsql = "SELECT d.id AS id,
3453 FROM {forum_posts} p,
3454 {forum_discussions} d
3455 WHERE p.discussion = d.id
3459 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3465 * @param int $forumid
3467 * @param int $userid
3470 function forum_user_has_posted($forumid, $did, $userid) {
3474 // posted in any forum discussion?
3476 FROM {forum_posts} p
3477 JOIN {forum_discussions} d ON d.id = p.discussion
3478 WHERE p.userid = :userid AND d.forum = :forumid";
3479 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3481 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3486 * Returns true if user posted with mailnow in given discussion
3487 * @param int $did Discussion id
3488 * @param int $userid User id
3491 function forum_get_user_posted_mailnow(int $did, int $userid): bool {
3494 $postmailnow = $DB->get_field('forum_posts', 'MAX(mailnow)', ['userid' => $userid, 'discussion' => $did]);
3495 return !empty($postmailnow);
3499 * Returns creation time of the first user's post in given discussion
3500 * @global object $DB
3501 * @param int $did Discussion id
3502 * @param int $userid User id
3503 * @return int|bool post creation time stamp or return false
3505 function forum_get_user_posted_time($did, $userid) {
3508 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3509 if (empty($posttime)) {
3517 * @param object $forum
3518 * @param object $currentgroup
3519 * @param int $unused
3521 * @param object $context
3524 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3525 // $forum is an object
3528 // shortcut - guest and not-logged-in users can not post
3529 if (isguestuser() or !isloggedin()) {
3534 debugging('missing cm', DEBUG_DEVELOPER
);
3535 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3536 throw new \
moodle_exception('invalidcoursemodule');
3541 $context = context_module
::instance($cm->id
);
3544 if (forum_is_cutoff_date_reached($forum)) {
3545 if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3550 if ($currentgroup === null) {
3551 $currentgroup = groups_get_activity_group($cm);
3554 $groupmode = groups_get_activity_groupmode($cm);
3556 if ($forum->type
== 'news') {
3557 $capname = 'mod/forum:addnews';
3558 } else if ($forum->type
== 'qanda') {
3559 $capname = 'mod/forum:addquestion';
3561 $capname = 'mod/forum:startdiscussion';
3564 if (!has_capability($capname, $context)) {
3568 if ($forum->type
== 'single') {
3572 if ($forum->type
== 'eachuser') {
3573 if (forum_user_has_posted_discussion($forum->id
, $USER->id
, $currentgroup)) {
3578 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
3582 if ($currentgroup) {
3583 return groups_is_member($currentgroup);
3585 // no group membership and no accessallgroups means no new discussions
3586 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
3592 * This function checks whether the user can reply to posts in a forum
3593 * discussion. Use forum_user_can_post_discussion() to check whether the user
3594 * can start discussions.
3598 * @uses DEBUG_DEVELOPER
3599 * @uses CONTEXT_MODULE
3600 * @uses VISIBLEGROUPS
3601 * @param object $forum forum object
3602 * @param object $discussion
3603 * @param object $user
3605 * @param object $course
3606 * @param object $context
3609 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
3615 // shortcut - guest and not-logged-in users can not post
3616 if (isguestuser($user) or empty($user->id
)) {
3620 if (!isset($discussion->groupid
)) {
3621 debugging('incorrect discussion parameter', DEBUG_DEVELOPER
);
3626 debugging('missing cm', DEBUG_DEVELOPER
);
3627 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3628 throw new \
moodle_exception('invalidcoursemodule');
3633 debugging('missing course', DEBUG_DEVELOPER
);
3634 if (!$course = $DB->get_record('course', array('id' => $forum->course
))) {
3635 throw new \
moodle_exception('invalidcourseid');
3640 $context = context_module
::instance($cm->id
);
3643 if (forum_is_cutoff_date_reached($forum)) {
3644 if (!has_capability('mod/forum:canoverridecutoff', $context)) {
3649 // Check whether the discussion is locked.
3650 if (forum_discussion_is_locked($forum, $discussion)) {
3651 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
3656 // normal users with temporary guest access can not post, suspended users can not post either
3657 if (!is_viewing($context, $user->id
) and !is_enrolled($context, $user->id
, '', true)) {
3661 if ($forum->type
== 'news') {
3662 $capname = 'mod/forum:replynews';
3664 $capname = 'mod/forum:replypost';
3667 if (!has_capability($capname, $context, $user->id
)) {
3671 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
3675 if (has_capability('moodle/site:accessallgroups', $context)) {
3679 if ($groupmode == VISIBLEGROUPS
) {
3680 if ($discussion->groupid
== -1) {
3681 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
3684 return groups_is_member($discussion->groupid
);
3688 if ($discussion->groupid
== -1) {
3691 return groups_is_member($discussion->groupid
);
3696 * Check to ensure a user can view a timed discussion.
3698 * @param object $discussion
3699 * @param object $user
3700 * @param object $context
3701 * @return boolean returns true if they can view post, false otherwise
3703 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
3706 // Check that the user can view a discussion that is normally hidden due to access times.
3707 if (!empty($CFG->forum_enabletimedposts
)) {
3709 if (($discussion->timestart
!= 0 && $discussion->timestart
> $time)
3710 ||
($discussion->timeend
!= 0 && $discussion->timeend
< $time)) {
3711 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id
)) {
3721 * Check to ensure a user can view a group discussion.
3723 * @param object $discussion
3725 * @param object $context
3726 * @return boolean returns true if they can view post, false otherwise
3728 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
3730 // If it's a grouped discussion, make sure the user is a member.
3731 if ($discussion->groupid
> 0) {
3732 $groupmode = groups_get_activity_groupmode($cm);
3733 if ($groupmode == SEPARATEGROUPS
) {
3734 return groups_is_member($discussion->groupid
) ||
has_capability('moodle/site:accessallgroups', $context);
3744 * @uses DEBUG_DEVELOPER
3745 * @param object $forum
3746 * @param object $discussion
3747 * @param object $context
3748 * @param object $user
3751 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
3754 if (empty($user) ||
empty($user->id
)) {
3758 // retrieve objects (yuk)
3759 if (is_numeric($forum)) {
3760 debugging('missing full forum', DEBUG_DEVELOPER
);
3761 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3765 if (is_numeric($discussion)) {
3766 debugging('missing full discussion', DEBUG_DEVELOPER
);
3767 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3771 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3772 throw new \
moodle_exception('invalidcoursemodule');
3775 if (!has_capability('mod/forum:viewdiscussion', $context)) {
3779 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
3783 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
3791 * Check whether a user can see the specified post.
3793 * @param \stdClass $forum The forum to chcek
3794 * @param \stdClass $discussion The discussion the post is in
3795 * @param \stdClass $post The post in question
3796 * @param \stdClass $user The user to test - if not specified, the current user is checked.
3797 * @param \stdClass $cm The Course Module that the forum is in (required).
3798 * @param bool $checkdeleted Whether to check the deleted flag on the post.
3801 function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) {
3802 global $CFG, $USER, $DB;
3804 // retrieve objects (yuk)
3805 if (is_numeric($forum)) {
3806 debugging('missing full forum', DEBUG_DEVELOPER
);
3807 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3812 if (is_numeric($discussion)) {
3813 debugging('missing full discussion', DEBUG_DEVELOPER
);
3814 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3818 if (is_numeric($post)) {
3819 debugging('missing full post', DEBUG_DEVELOPER
);
3820 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
3825 if (!isset($post->id
) && isset($post->parent
)) {
3826 $post->id
= $post->parent
;
3829 if ($checkdeleted && !empty($post->deleted
)) {
3834 debugging('missing cm', DEBUG_DEVELOPER
);
3835 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3836 throw new \
moodle_exception('invalidcoursemodule');
3840 // Context used throughout function.
3841 $modcontext = context_module
::instance($cm->id
);
3843 if (empty($user) ||
empty($user->id
)) {
3847 $canviewdiscussion = (isset($cm->cache
) && !empty($cm->cache
->caps
['mod/forum:viewdiscussion']))
3848 ||
has_capability('mod/forum:viewdiscussion', $modcontext, $user->id
);
3849 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user
::instance($post->userid
))) {
3853 if (!forum_post_is_visible_privately($post, $cm)) {
3857 if (isset($cm->uservisible
)) {
3858 if (!$cm->uservisible
) {
3862 if (!\core_availability\info_module
::is_user_visible($cm, $user->id
, false)) {
3867 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
3871 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
3875 if ($forum->type
== 'qanda') {
3876 if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id
) ||
$post->userid
== $user->id
3877 ||
(isset($discussion->firstpost
) && $discussion->firstpost
== $post->id
)) {
3880 $firstpost = forum_get_firstpost_from_discussion($discussion->id
);
3881 if ($firstpost->userid
== $user->id
) {
3884 $userpostmailnow = forum_get_user_posted_mailnow($discussion->id
, $user->id
);
3885 if ($userpostmailnow) {
3888 $userfirstpost = forum_get_user_posted_time($discussion->id
, $user->id
);
3889 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime
)));
3895 * Returns all forum posts since a given time in specified forum.
3897 * @todo Document this functions args
3903 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
3904 global $CFG, $COURSE, $USER, $DB;
3906 if ($COURSE->id
== $courseid) {
3909 $course = $DB->get_record('course', array('id' => $courseid));
3912 $modinfo = get_fast_modinfo($course);
3914 $cm = $modinfo->cms
[$cmid];
3915 $params = array($timestart, $cm->instance
);
3918 $userselect = "AND u.id = ?";
3919 $params[] = $userid;
3925 $groupselect = "AND d.groupid = ?";
3926 $params[] = $groupid;
3931 $userfieldsapi = \core_user\fields
::for_name();
3932 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
3933 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
3934 d.timestart, d.timeend, d.userid AS duserid,
3935 $allnames, u.email, u.picture, u.imagealt, u.email
3936 FROM {forum_posts} p
3937 JOIN {forum_discussions} d ON d.id = p.discussion
3938 JOIN {forum} f ON f.id = d.forum
3939 JOIN {user} u ON u.id = p.userid
3940 WHERE p.created > ? AND f.id = ?
3941 $userselect $groupselect
3942 ORDER BY p.id ASC", $params)) { // order by initial posting date
3946 $groupmode = groups_get_activity_groupmode($cm, $course);
3947 $cm_context = context_module
::instance($cm->id
);
3948 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
3949 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
3951 $printposts = array();
3952 foreach ($posts as $post) {
3954 if (!empty($CFG->forum_enabletimedposts
) and $USER->id
!= $post->duserid
3955 and (($post->timestart
> 0 and $post->timestart
> time()) or ($post->timeend
> 0 and $post->timeend
< time()))) {
3956 if (!$viewhiddentimed) {
3962 if ($post->groupid
== -1 or $groupmode == VISIBLEGROUPS
or $accessallgroups) {
3963 // oki (Open discussions have groupid -1)
3966 if (isguestuser()) {
3971 if (!in_array($post->groupid
, $modinfo->get_groups($cm->groupingid
))) {
3977 $printposts[] = $post;
3984 $aname = format_string($cm->name
,true);
3986 foreach ($printposts as $post) {
3987 $tmpactivity = new stdClass();
3989 $tmpactivity->type
= 'forum';
3990 $tmpactivity->cmid
= $cm->id
;
3991 $tmpactivity->name
= $aname;
3992 $tmpactivity->sectionnum
= $cm->sectionnum
;
3993 $tmpactivity->timestamp
= $post->modified
;
3995 $tmpactivity->content
= new stdClass();
3996 $tmpactivity->content
->id
= $post->id
;
3997 $tmpactivity->content
->discussion
= $post->discussion
;
3998 $tmpactivity->content
->subject
= format_string($post->subject
);
3999 $tmpactivity->content
->parent
= $post->parent
;
4000 $tmpactivity->content
->forumtype
= $post->forumtype
;
4002 $tmpactivity->user
= new stdClass();
4003 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
4004 $additionalfields = explode(',', implode(',', \core_user\fields
::get_picture_fields()));
4005 $tmpactivity->user
= username_load_fields_from_object($tmpactivity->user
, $post, null, $additionalfields);
4006 $tmpactivity->user
->id
= $post->userid
;
4008 $activities[$index++
] = $tmpactivity;
4015 * Outputs the forum post indicated by $activity.
4017 * @param object $activity the activity object the forum resides in
4018 * @param int $courseid the id of the course the forum resides in
4019 * @param bool $detail not used, but required for compatibilty with other modules
4020 * @param int $modnames not used, but required for compatibilty with other modules
4021 * @param bool $viewfullnames not used, but required for compatibilty with other modules
4023 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
4026 $content = $activity->content
;
4027 if ($content->parent
) {
4030 $class = 'discussion';
4035 'cellpadding' => '3',
4036 'cellspacing' => '0',
4037 'class' => 'forum-recent'
4039 $output = html_writer
::start_tag('table', $tableoptions);
4040 $output .= html_writer
::start_tag('tr');
4042 $post = (object) ['parent' => $content->parent
];
4043 $forum = (object) ['type' => $content->forumtype
];
4044 $authorhidden = forum_is_author_hidden($post, $forum);
4046 // Show user picture if author should not be hidden.
4047 if (!$authorhidden) {
4049 'courseid' => $courseid,
4050 'link' => $authorhidden,
4051 'alttext' => $authorhidden,
4053 $picture = $OUTPUT->user_picture($activity->user
, $pictureoptions);
4054 $output .= html_writer
::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
4057 // Discussion title and author.
4058 $output .= html_writer
::start_tag('td', ['class' => $class]);
4059 if ($content->parent
) {
4062 // Bold the title of new discussions so they stand out.
4063 $class = 'title bold';
4066 $output .= html_writer
::start_div($class);
4068 $aname = s($activity->name
);
4069 $output .= $OUTPUT->image_icon('monologo', $aname, $activity->type
);
4071 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion
]);
4072 $discussionurl->set_anchor('p' . $activity->content
->id
);
4073 $output .= html_writer
::link($discussionurl, $content->subject
);
4074 $output .= html_writer
::end_div();
4076 $timestamp = userdate_htmltime($activity->timestamp
);
4077 if ($authorhidden) {
4078 $authornamedate = $timestamp;
4080 $fullname = fullname($activity->user
, $viewfullnames);
4081 $userurl = new moodle_url('/user/view.php');
4082 $userurl->params(['id' => $activity->user
->id
, 'course' => $courseid]);
4083 $by = new stdClass();
4084 $by->name
= html_writer
::link($userurl, $fullname);
4085 $by->date
= $timestamp;
4086 $authornamedate = get_string('bynameondate', 'forum', $by);
4088 $output .= html_writer
::div($authornamedate, 'user');
4089 $output .= html_writer
::end_tag('td');
4090 $output .= html_writer
::end_tag('tr');
4091 $output .= html_writer
::end_tag('table');
4097 * recursively sets the discussion field to $discussionid on $postid and all its children
4098 * used when pruning a post
4101 * @param int $postid
4102 * @param int $discussionid
4105 function forum_change_discussionid($postid, $discussionid) {
4107 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
4108 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
4109 foreach ($posts as $post) {
4110 forum_change_discussionid($post->id
, $discussionid);
4116 // Functions to do with read tracking.
4119 * Mark posts as read.
4123 * @param object $user object
4124 * @param array $postids array of post ids
4125 * @return boolean success
4127 function forum_tp_mark_posts_read($user, $postids) {
4130 if (!forum_tp_can_track_forums(false, $user)) {
4137 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
4139 if (empty($postids)) {
4142 } else if (count($postids) > 200) {
4143 while ($part = array_splice($postids, 0, 200)) {
4144 $status = forum_tp_mark_posts_read($user, $part) && $status;
4149 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED
, 'postid');
4151 $insertparams = array(
4152 'userid1' => $user->id
,
4153 'userid2' => $user->id
,
4154 'userid3' => $user->id
,
4155 'firstread' => $now,
4157 'cutoffdate' => $cutoffdate,
4159 $params = array_merge($postidparams, $insertparams);
4161 if ($CFG->forum_allowforcedreadtracking
) {
4162 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
4163 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL))";
4165 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
4166 AND tf.id IS NULL)";
4169 // First insert any new entries.
4170 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4172 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
4173 FROM {forum_posts} p
4174 JOIN {forum_discussions} d ON d.id = p.discussion
4175 JOIN {forum} f ON f.id = d.forum
4176 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
4177 LEFT JOIN {forum_read} fr ON (
4178 fr.userid = :userid3
4179 AND fr.postid = p.id
4180 AND fr.discussionid = d.id
4181 AND fr.forumid = f.id
4184 AND p.modified >= :cutoffdate
4188 $status = $DB->execute($sql, $params) && $status;
4190 // Then update all records.
4191 $updateparams = array(
4192 'userid' => $user->id
,
4195 $params = array_merge($postidparams, $updateparams);
4196 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
4198 AND lastread <> :lastread
4199 AND postid ' . $usql,
4200 $params) && $status;
4206 * Mark post as read.
4209 * @param int $userid
4210 * @param int $postid
4212 function forum_tp_add_read_record($userid, $postid) {
4216 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
4218 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
4219 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
4221 SELECT ?, p.id, p.discussion, d.forum, ?, ?
4222 FROM {forum_posts} p
4223 JOIN {forum_discussions} d ON d.id = p.discussion
4224 WHERE p.id = ? AND p.modified >= ?";
4225 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
4228 $sql = "UPDATE {forum_read}
4230 WHERE userid = ? AND postid = ?";
4231 return $DB->execute($sql, array($now, $userid, $userid));
4236 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
4238 * @param int $userid The ID of the user to mark posts read for.
4239 * @param object $post The post record for the post to mark as read.
4240 * @param mixed $unused
4243 function forum_tp_mark_post_read($userid, $post, $unused = null) {
4244 if (!forum_tp_is_post_old($post)) {
4245 return forum_tp_add_read_record($userid, $post->id
);
4252 * Marks a whole forum as read, for a given user
4256 * @param object $user
4257 * @param int $forumid
4258 * @param int|bool $groupid
4261 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
4264 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
4267 $params = array($user->id
, $forumid, $cutoffdate);
4269 if ($groupid !== false) {
4270 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
4271 $params[] = $groupid;
4275 FROM {forum_posts} p
4276 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
4277 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
4279 AND p.modified >= ? AND r.id is NULL
4282 if ($posts = $DB->get_records_sql($sql, $params)) {
4283 $postids = array_keys($posts);
4284 return forum_tp_mark_posts_read($user, $postids);
4291 * Marks a whole discussion as read, for a given user
4295 * @param object $user
4296 * @param int $discussionid
4299 function forum_tp_mark_discussion_read($user, $discussionid) {
4302 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
4305 FROM {forum_posts} p
4306 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
4307 WHERE p.discussion = ?
4308 AND p.modified >= ? AND r.id is NULL";
4310 if ($posts = $DB->get_records_sql($sql, array($user->id
, $discussionid, $cutoffdate))) {
4311 $postids = array_keys($posts);
4312 return forum_tp_mark_posts_read($user, $postids);
4320 * @param int $userid
4321 * @param object $post
4323 function forum_tp_is_post_read($userid, $post) {
4325 return (forum_tp_is_post_old($post) ||
4326 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id
)));
4331 * @param object $post
4332 * @param int $time Defautls to time()
4334 function forum_tp_is_post_old($post, $time=null) {
4337 if (is_null($time)) {
4340 return ($post->modified
< ($time - ($CFG->forum_oldpostdays
* 24 * 3600)));
4344 * Returns the count of records for the provided user and course.
4345 * Please note that group access is ignored!
4349 * @param int $userid
4350 * @param int $courseid
4353 function forum_tp_get_course_unread_posts($userid, $courseid) {
4356 $modinfo = get_fast_modinfo($courseid);
4357 $forumcms = $modinfo->get_instances_of('forum');
4358 if (empty($forumcms)) {
4359 // Return early if the course doesn't have any forum. Will save us a DB query.
4363 $now = floor(time() / MINSECS
) * MINSECS
; // DB cache friendliness.
4364 $cutoffdate = $now - ($CFG->forum_oldpostdays
* DAYSECS
);
4366 'privatereplyto' => $userid,
4367 'modified' => $cutoffdate,
4368 'readuserid' => $userid,
4369 'trackprefsuser' => $userid,
4370 'courseid' => $courseid,
4371 'trackforumuser' => $userid,
4374 if (!empty($CFG->forum_enabletimedposts
)) {
4375 $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4376 $params['timestart'] = $now;
4377 $params['timeend'] = $now;
4382 if ($CFG->forum_allowforcedreadtracking
) {
4383 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
4384 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL
4385 AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1))";
4387 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
4389 AND (SELECT trackforums FROM {user} WHERE id = :trackforumuser) = 1)";
4392 $sql = "SELECT f.id, COUNT(p.id) AS unread,
4393 COUNT(p.privatereply) as privatereplies,
4394 COUNT(p.privatereplytouser) as privaterepliestouser
4399 CASE WHEN privatereplyto <> 0 THEN 1 END privatereply,
4400 CASE WHEN privatereplyto = :privatereplyto THEN 1 END privatereplytouser
4402 WHERE modified >= :modified
4404 JOIN {forum_discussions} d ON d.id = p.discussion
4405 JOIN {forum} f ON f.id = d.forum
4406 JOIN {course} c ON c.id = f.course
4407 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = :readuserid)
4408 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :trackprefsuser AND tf.forumid = f.id)
4409 WHERE f.course = :courseid
4416 if ($records = $DB->get_records_sql($sql, $params)) {
4417 // Loop through each forum instance to check for capability and count the number of unread posts.
4418 foreach ($forumcms as $cm) {
4419 // Check that the forum instance exists in the query results.
4420 if (!isset($records[$cm->instance
])) {
4424 $record = $records[$cm->instance
];
4425 $unread = $record->unread
;
4427 // Check if the user has the capability to read private replies for this forum instance.
4428 $forumcontext = context_module
::instance($cm->id
);
4429 if (!has_capability('mod/forum:readprivatereplies', $forumcontext, $userid)) {
4430 // The real unread count would be the total of unread count minus the number of unread private replies plus
4431 // the total unread private replies to the user.
4432 $unread = $record->unread
- $record->privatereplies +
$record->privaterepliestouser
;
4435 // Build and add the object to the array of results to be returned.
4436 $results[$record->id
] = (object)[
4437 'id' => $record->id
,
4438 'unread' => $unread,
4447 * Returns the count of records for the provided user and forum and [optionally] group.
4453 * @param object $course
4454 * @param bool $resetreadcache optional, true to reset the function static $readcache var
4457 function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) {
4458 global $CFG, $USER, $DB;
4460 static $readcache = array();
4462 if ($resetreadcache) {
4463 $readcache = array();
4466 $forumid = $cm->instance
;
4468 if (!isset($readcache[$course->id
])) {
4469 $readcache[$course->id
] = array();
4470 if ($counts = forum_tp_get_course_unread_posts($USER->id
, $course->id
)) {
4471 foreach ($counts as $count) {
4472 $readcache[$course->id
][$count->id
] = $count->unread
;
4477 if (empty($readcache[$course->id
][$forumid])) {
4478 // no need to check group mode ;-)
4482 $groupmode = groups_get_activity_groupmode($cm, $course);
4484 if ($groupmode != SEPARATEGROUPS
) {
4485 return $readcache[$course->id
][$forumid];
4488 $forumcontext = context_module
::instance($cm->id
);
4489 if (has_any_capability(['moodle/site:accessallgroups', 'mod/forum:readprivatereplies'], $forumcontext)) {
4490 return $readcache[$course->id
][$forumid];
4493 require_once($CFG->dirroot
.'/course/lib.php');
4495 $modinfo = get_fast_modinfo($course);
4497 $mygroups = $modinfo->get_groups($cm->groupingid
);
4499 // add all groups posts
4502 list ($groupssql, $groupsparams) = $DB->get_in_or_equal($mygroups, SQL_PARAMS_NAMED
);
4504 $now = floor(time() / MINSECS
) * MINSECS
; // DB Cache friendliness.
4505 $cutoffdate = $now - ($CFG->forum_oldpostdays
* DAYSECS
);
4507 'readuser' => $USER->id
,
4508 'forum' => $forumid,
4509 'cutoffdate' => $cutoffdate,
4510 'privatereplyto' => $USER->id
,
4513 if (!empty($CFG->forum_enabletimedposts
)) {
4514 $timedsql = "AND d.timestart < :timestart AND (d.timeend = 0 OR d.timeend > :timeend)";
4515 $params['timestart'] = $now;
4516 $params['timeend'] = $now;
4521 $params = array_merge($params, $groupsparams);
4523 $sql = "SELECT COUNT(p.id)
4524 FROM {forum_posts} p
4525 JOIN {forum_discussions} d ON p.discussion = d.id
4526 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = :readuser)
4527 WHERE d.forum = :forum
4528 AND p.modified >= :cutoffdate AND r.id is NULL
4530 AND d.groupid $groupssql
4531 AND (p.privatereplyto = 0 OR p.privatereplyto = :privatereplyto)";
4533 return $DB->get_field_sql($sql, $params);
4537 * Deletes read records for the specified index. At least one parameter must be specified.
4540 * @param int $userid
4541 * @param int $postid
4542 * @param int $discussionid
4543 * @param int $forumid
4546 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
4552 if ($select != '') $select .= ' AND ';
4553 $select .= 'userid = ?';
4554 $params[] = $userid;
4557 if ($select != '') $select .= ' AND ';
4558 $select .= 'postid = ?';
4559 $params[] = $postid;
4561 if ($discussionid > -1) {
4562 if ($select != '') $select .= ' AND ';
4563 $select .= 'discussionid = ?';
4564 $params[] = $discussionid;
4566 if ($forumid > -1) {
4567 if ($select != '') $select .= ' AND ';
4568 $select .= 'forumid = ?';
4569 $params[] = $forumid;
4571 if ($select == '') {
4575 return $DB->delete_records_select('forum_read', $select, $params);
4579 * Get a list of forums not tracked by the user.
4583 * @param int $userid The id of the user to use.
4584 * @param int $courseid The id of the course being checked.
4585 * @return mixed An array indexed by forum id, or false.
4587 function forum_tp_get_untracked_forums($userid, $courseid) {
4590 if ($CFG->forum_allowforcedreadtracking
) {
4591 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
4592 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND (ft.id IS NOT NULL
4593 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4595 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
4596 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
4597 AND (ft.id IS NOT NULL
4598 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
4603 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
4607 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
4608 foreach ($forums as $forum) {
4609 $forums[$forum->id
] = $forum;
4619 * Determine if a user can track forums and optionally a particular forum.
4620 * Checks the site settings, the user settings and the forum settings (if
4626 * @param mixed $forum The forum object to test, or the int id (optional).
4627 * @param mixed $userid The user object to check for (optional).
4630 function forum_tp_can_track_forums($forum=false, $user=false) {
4631 global $USER, $CFG, $DB;
4633 // if possible, avoid expensive
4635 if (empty($CFG->forum_trackreadposts
)) {
4639 if ($user === false) {
4643 if (isguestuser($user) or empty($user->id
)) {
4647 if ($forum === false) {
4648 if ($CFG->forum_allowforcedreadtracking
) {
4649 // Since we can force tracking, assume yes without a specific forum.
4652 return (bool)$user->trackforums
;
4656 // Work toward always passing an object...
4657 if (is_numeric($forum)) {
4658 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
4659 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
4662 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
4663 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
4665 if ($CFG->forum_allowforcedreadtracking
) {
4666 // If we allow forcing, then forced forums takes procidence over user setting.
4667 return ($forumforced ||
($forumallows && (!empty($user->trackforums
) && (bool)$user->trackforums
)));
4669 // If we don't allow forcing, user setting trumps.
4670 return ($forumforced ||
$forumallows) && !empty($user->trackforums
);
4675 * Tells whether a specific forum is tracked by the user. A user can optionally
4676 * be specified. If not specified, the current user is assumed.
4681 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
4682 * @param int $userid The id of the user being checked (optional).
4685 function forum_tp_is_tracked($forum, $user=false) {
4686 global $USER, $CFG, $DB;
4688 if ($user === false) {
4692 if (isguestuser($user) or empty($user->id
)) {
4696 $cache = cache
::make('mod_forum', 'forum_is_tracked');
4697 $forumid = is_numeric($forum) ?
$forum : $forum->id
;
4698 $key = $forumid . '_' . $user->id
;
4699 if ($cachedvalue = $cache->get($key)) {
4700 return $cachedvalue == 'tracked';
4703 // Work toward always passing an object...
4704 if (is_numeric($forum)) {
4705 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
4706 $forum = $DB->get_record('forum', array('id' => $forum));
4709 if (!forum_tp_can_track_forums($forum, $user)) {
4713 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
4714 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
4715 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id
, 'forumid' => $forum->id
));
4717 if ($CFG->forum_allowforcedreadtracking
) {
4718 $istracked = $forumforced ||
($forumallows && $userpref === false);
4720 $istracked = ($forumallows ||
$forumforced) && $userpref === false;
4723 // We have to store a string here because the cache API returns false
4724 // when it can't find the key which would be confused with our legitimate
4725 // false value. *sigh*.
4726 $cache->set($key, $istracked ?
'tracked' : 'not');
4734 * @param int $forumid
4735 * @param int $userid
4737 function forum_tp_start_tracking($forumid, $userid=false) {
4740 if ($userid === false) {
4741 $userid = $USER->id
;
4744 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
4750 * @param int $forumid
4751 * @param int $userid
4753 function forum_tp_stop_tracking($forumid, $userid=false) {
4756 if ($userid === false) {
4757 $userid = $USER->id
;
4760 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
4761 $track_prefs = new stdClass();
4762 $track_prefs->userid
= $userid;
4763 $track_prefs->forumid
= $forumid;
4764 $DB->insert_record('forum_track_prefs', $track_prefs);
4767 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
4772 * Clean old records from the forum_read table.
4777 function forum_tp_clean_read_records() {
4780 if (!isset($CFG->forum_oldpostdays
)) {
4783 // Look for records older than the cutoffdate that are still in the forum_read table.
4784 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
4786 //first get the oldest tracking present - we need tis to speedup the next delete query
4787 $sql = "SELECT MIN(fp.modified) AS first
4788 FROM {forum_posts} fp
4789 JOIN {forum_read} fr ON fr.postid=fp.id";
4790 if (!$first = $DB->get_field_sql($sql)) {
4791 // nothing to delete;
4795 // now delete old tracking info
4798 WHERE postid IN (SELECT fp.id
4799 FROM {forum_posts} fp
4800 WHERE fp.modified >= ? AND fp.modified < ?)";
4801 $DB->execute($sql, array($first, $cutoffdate));
4805 * Sets the last post for a given discussion
4809 * @param into $discussionid
4812 function forum_discussion_update_last_post($discussionid) {
4815 // Check the given discussion exists
4816 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
4820 // Use SQL to find the last post for this discussion
4821 $sql = "SELECT id, userid, modified
4824 ORDER BY modified DESC";
4826 // Lets go find the last post
4827 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
4828 $lastpost = reset($lastposts);
4829 $discussionobject = new stdClass();
4830 $discussionobject->id
= $discussionid;
4831 $discussionobject->usermodified
= $lastpost->userid
;
4832 $discussionobject->timemodified
= $lastpost->modified
;
4833 $DB->update_record('forum_discussions', $discussionobject);
4834 return $lastpost->id
;
4837 // To get here either we couldn't find a post for the discussion (weird)
4838 // or we couldn't update the discussion record (weird x2)
4844 * List the actions that correspond to a view of this module.
4845 * This is used by the participation report.
4847 * Note: This is not used by new logging system. Event with
4848 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
4849 * be considered as view action.
4853 function forum_get_view_actions() {
4854 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
4858 * List the options for forum subscription modes.
4859 * This is used by the settings page and by the mod_form page.
4863 function forum_get_subscriptionmode_options() {
4865 $options[FORUM_CHOOSESUBSCRIBE
] = get_string('subscriptionoptional', 'forum');
4866 $options[FORUM_FORCESUBSCRIBE
] = get_string('subscriptionforced', 'forum');
4867 $options[FORUM_INITIALSUBSCRIBE
] = get_string('subscriptionauto', 'forum');
4868 $options[FORUM_DISALLOWSUBSCRIBE
] = get_string('subscriptiondisabled', 'forum');
4873 * List the actions that correspond to a post of this module.
4874 * This is used by the participation report.
4876 * Note: This is not used by new logging system. Event with
4877 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
4878 * will be considered as post action.
4882 function forum_get_post_actions() {
4883 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
4887 * Returns a warning object if a user has reached the number of posts equal to
4888 * the warning/blocking setting, or false if there is no warning to show.
4890 * @param int|stdClass $forum the forum id or the forum object
4891 * @param stdClass $cm the course module
4892 * @return stdClass|bool returns an object with the warning information, else
4893 * returns false if no warning is required.
4895 function forum_check_throttling($forum, $cm = null) {
4896 global $CFG, $DB, $USER;
4898 if (is_numeric($forum)) {
4899 $forum = $DB->get_record('forum', ['id' => $forum], 'id, course, blockperiod, blockafter, warnafter', MUST_EXIST
);
4902 if (!is_object($forum) ||
!isset($forum->id
) ||
!isset($forum->course
)) {
4903 // The passed forum parameter is invalid. This can happen if:
4904 // - a non-object and non-numeric forum is passed; or
4905 // - the forum object does not have an ID or course attributes.
4906 // This is unlikely to happen with properly formed forum record fetched from the database,
4907 // so it's most likely a dev error if we hit such this case.
4908 throw new coding_exception('Invalid forum parameter passed');
4911 if (empty($forum->blockafter
)) {
4915 if (empty($forum->blockperiod
)) {
4920 // Try to fetch the $cm object via get_fast_modinfo() so we don't incur DB reads.
4921 $modinfo = get_fast_modinfo($forum->course
);
4922 $forumcms = $modinfo->get_instances_of('forum');
4923 foreach ($forumcms as $tmpcm) {
4924 if ($tmpcm->instance
== $forum->id
) {
4929 // Last resort. Try to fetch via get_coursemodule_from_instance().
4931 $cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
, false, MUST_EXIST
);
4935 $modcontext = context_module
::instance($cm->id
);
4936 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
4940 // Get the number of posts in the last period we care about.
4942 $timeafter = $timenow - $forum->blockperiod
;
4943 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
4944 JOIN {forum_discussions} d
4945 ON p.discussion = d.id WHERE d.forum = ?
4946 AND p.userid = ? AND p.created > ?', array($forum->id
, $USER->id
, $timeafter));
4948 $a = new stdClass();
4949 $a->blockafter
= $forum->blockafter
;
4950 $a->numposts
= $numposts;
4951 $a->blockperiod
= get_string('secondstotime'.$forum->blockperiod
);
4953 if ($forum->blockafter
<= $numposts) {
4954 $warning = new stdClass();
4955 $warning->canpost
= false;
4956 $warning->errorcode
= 'forumblockingtoomanyposts';
4957 $warning->module
= 'error';
4958 $warning->additional
= $a;
4959 $warning->link
= $CFG->wwwroot
. '/mod/forum/view.php?f=' . $forum->id
;
4964 if ($forum->warnafter
<= $numposts) {
4965 $warning = new stdClass();
4966 $warning->canpost
= true;
4967 $warning->errorcode
= 'forumblockingalmosttoomanyposts';
4968 $warning->module
= 'forum';
4969 $warning->additional
= $a;
4970 $warning->link
= null;
4975 // No warning needs to be shown yet.
4980 * Throws an error if the user is no longer allowed to post due to having reached
4981 * or exceeded the number of posts specified in 'Post threshold for blocking'
4985 * @param stdClass $thresholdwarning the warning information returned
4986 * from the function forum_check_throttling.
4988 function forum_check_blocking_threshold($thresholdwarning) {
4989 if (!empty($thresholdwarning) && !$thresholdwarning->canpost
) {
4990 throw new \
moodle_exception($thresholdwarning->errorcode
,
4991 $thresholdwarning->module
,
4992 $thresholdwarning->link
,
4993 $thresholdwarning->additional
);
4999 * Removes all grades from gradebook
5003 * @param int $courseid
5004 * @param string $type optional
5006 function forum_reset_gradebook($courseid, $type='') {
5010 $params = array($courseid);
5012 $wheresql = "AND f.type=?";
5016 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
5017 FROM {forum} f, {course_modules} cm, {modules} m
5018 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
5020 if ($forums = $DB->get_records_sql($sql, $params)) {
5021 foreach ($forums as $forum) {
5022 forum_grade_item_update($forum, 'reset', 'reset');
5028 * This function is used by the reset_course_userdata function in moodlelib.
5029 * This function will remove all posts from the specified forum
5030 * and clean up any related data.
5034 * @param $data the data submitted from the reset course.
5035 * @return array status array
5037 function forum_reset_userdata($data) {
5039 require_once($CFG->dirroot
.'/rating/lib.php');
5041 $componentstr = get_string('modulenameplural', 'forum');
5044 $params = array($data->courseid
);
5046 $removeposts = false;
5048 if (!empty($data->reset_forum_all
)) {
5049 $removeposts = true;
5050 $typesstr = get_string('resetforumsall', 'forum');
5052 } else if (!empty($data->reset_forum_types
)){
5053 $removeposts = true;
5055 $sqltypes = array();
5056 $forum_types_all = forum_get_forum_types_all();
5057 foreach ($data->reset_forum_types
as $type) {
5058 if (!array_key_exists($type, $forum_types_all)) {
5061 $types[] = $forum_types_all[$type];
5062 $sqltypes[] = $type;
5064 if (!empty($sqltypes)) {
5065 list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
5066 $typesql = " AND f.type " . $typesql;
5067 $params = array_merge($params, $typeparams);
5069 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
5071 $alldiscussionssql = "SELECT fd.id
5072 FROM {forum_discussions} fd, {forum} f
5073 WHERE f.course=? AND f.id=fd.forum";
5075 $allforumssql = "SELECT f.id
5079 $allpostssql = "SELECT fp.id
5080 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
5081 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
5083 $forumssql = $forums = $rm = null;
5085 // Check if we need to get additional data.
5086 if ($removeposts ||
!empty($data->reset_forum_ratings
) ||
!empty($data->reset_forum_tags
)) {
5087 // Set this up if we have to remove ratings.
5088 $rm = new rating_manager();
5089 $ratingdeloptions = new stdClass
;
5090 $ratingdeloptions->component
= 'mod_forum';
5091 $ratingdeloptions->ratingarea
= 'post';
5093 // Get the forums for actions that require it.
5094 $forumssql = "$allforumssql $typesql";
5095 $forums = $DB->get_records_sql($forumssql, $params);
5099 $discussionssql = "$alldiscussionssql $typesql";
5100 $postssql = "$allpostssql $typesql";
5102 // now get rid of all attachments
5103 $fs = get_file_storage();
5105 foreach ($forums as $forumid=>$unused) {
5106 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5109 $context = context_module
::instance($cm->id
);
5110 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment');
5111 $fs->delete_area_files($context->id
, 'mod_forum', 'post');
5114 $ratingdeloptions->contextid
= $context->id
;
5115 $rm->delete_ratings($ratingdeloptions);
5117 core_tag_tag
::delete_instances('mod_forum', null, $context->id
);
5121 // first delete all read flags
5122 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
5124 // remove tracking prefs
5125 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
5127 // remove posts from queue
5128 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
5130 // all posts - initial posts must be kept in single simple discussion forums
5131 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
5132 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql AND f.type <> 'single') AND parent = 0", $params); // now the initial posts for non single simple
5134 // finally all discussions except single simple forums
5135 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
5137 // remove all grades from gradebook
5138 if (empty($data->reset_gradebook_grades
)) {
5139 if (empty($types)) {
5140 forum_reset_gradebook($data->courseid
);
5142 foreach ($types as $type) {
5143 forum_reset_gradebook($data->courseid
, $type);
5148 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
5151 // remove all ratings in this course's forums
5152 if (!empty($data->reset_forum_ratings
)) {
5154 foreach ($forums as $forumid=>$unused) {
5155 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5158 $context = context_module
::instance($cm->id
);
5161 $ratingdeloptions->contextid
= $context->id
;
5162 $rm->delete_ratings($ratingdeloptions);
5166 // remove all grades from gradebook
5167 if (empty($data->reset_gradebook_grades
)) {
5168 forum_reset_gradebook($data->courseid
);
5172 // Remove all the tags.
5173 if (!empty($data->reset_forum_tags
)) {
5175 foreach ($forums as $forumid => $unused) {
5176 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
5180 $context = context_module
::instance($cm->id
);
5181 core_tag_tag
::delete_instances('mod_forum', null, $context->id
);
5185 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false);
5188 // remove all digest settings unconditionally - even for users still enrolled in course.
5189 if (!empty($data->reset_forum_digests
)) {
5190 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
5191 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
5194 // remove all subscriptions unconditionally - even for users still enrolled in course
5195 if (!empty($data->reset_forum_subscriptions
)) {
5196 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
5197 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
5198 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
5201 // remove all tracking prefs unconditionally - even for users still enrolled in course
5202 if (!empty($data->reset_forum_track_prefs
)) {
5203 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
5204 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
5207 /// updating dates - shift may be negative too
5208 if ($data->timeshift
) {
5209 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
5211 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
5212 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
5219 * Called by course/reset.php
5221 * @param MoodleQuickForm $mform form passed by reference
5223 function forum_reset_course_form_definition(&$mform) {
5224 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
5226 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
5228 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
5229 $mform->setAdvanced('reset_forum_types');
5230 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
5232 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
5233 $mform->setAdvanced('reset_forum_digests');
5235 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
5236 $mform->setAdvanced('reset_forum_subscriptions');
5238 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
5239 $mform->setAdvanced('reset_forum_track_prefs');
5240 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
5242 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
5243 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
5245 $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum'));
5246 $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked');
5250 * Course reset form defaults.
5253 function forum_reset_course_form_defaults($course) {
5254 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
5258 * Returns array of forum layout modes
5260 * @param bool $useexperimentalui use experimental layout modes or not
5263 function forum_get_layout_modes(bool $useexperimentalui = false) {
5265 FORUM_MODE_FLATOLDEST
=> get_string('modeflatoldestfirst', 'forum'),
5266 FORUM_MODE_FLATNEWEST
=> get_string('modeflatnewestfirst', 'forum'),
5267 FORUM_MODE_THREADED
=> get_string('modethreaded', 'forum')
5270 if ($useexperimentalui) {
5271 $modes[FORUM_MODE_NESTED_V2
] = get_string('modenestedv2', 'forum');
5273 $modes[FORUM_MODE_NESTED
] = get_string('modenested', 'forum');
5280 * Returns array of forum types chooseable on the forum editing form
5284 function forum_get_forum_types() {
5285 return array ('general' => get_string('generalforum', 'forum'),
5286 'eachuser' => get_string('eachuserforum', 'forum'),
5287 'single' => get_string('singleforum', 'forum'),
5288 'qanda' => get_string('qandaforum', 'forum'),
5289 'blog' => get_string('blogforum', 'forum'));
5293 * Returns array of all forum layout modes
5297 function forum_get_forum_types_all() {
5298 return array ('news' => get_string('namenews','forum'),
5299 'social' => get_string('namesocial','forum'),
5300 'general' => get_string('generalforum', 'forum'),
5301 'eachuser' => get_string('eachuserforum', 'forum'),
5302 'single' => get_string('singleforum', 'forum'),
5303 'qanda' => get_string('qandaforum', 'forum'),
5304 'blog' => get_string('blogforum', 'forum'));
5308 * Returns all other caps used in module
5312 function forum_get_extra_capabilities() {
5313 return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate'];
5317 * Adds module specific settings to the settings block
5319 * @param settings_navigation $settings The settings navigation object
5320 * @param navigation_node $forumnode The node to add module settings to
5322 function forum_extend_settings_navigation(settings_navigation
$settingsnav, navigation_node
$forumnode) {
5325 if (empty($settingsnav->get_page()->cm
->context
)) {
5326 $settingsnav->get_page()->cm
->context
= context_module
::instance($settingsnav->get_page()->cm
->instance
);
5329 $vaultfactory = mod_forum\local\container
::get_vault_factory();
5330 $managerfactory = mod_forum\local\container
::get_manager_factory();
5331 $legacydatamapperfactory = mod_forum\local\container
::get_legacy_data_mapper_factory();
5332 $forumvault = $vaultfactory->get_forum_vault();
5333 $forumentity = $forumvault->get_from_id($settingsnav->get_page()->cm
->instance
);
5334 $forumobject = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forumentity);
5336 $params = $settingsnav->get_page()->url
->params();
5337 if (!empty($params['d'])) {
5338 $discussionid = $params['d'];
5341 // For some actions you need to be enrolled, being admin is not enough sometimes here.
5342 $enrolled = is_enrolled($settingsnav->get_page()->context
, $USER, '', false);
5343 $activeenrolled = is_enrolled($settingsnav->get_page()->context
, $USER, '', true);
5345 $canmanage = has_capability('mod/forum:managesubscriptions', $settingsnav->get_page()->context
);
5346 $subscriptionmode = \mod_forum\subscriptions
::get_subscription_mode($forumobject);
5347 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions
::is_forcesubscribed($forumobject) &&
5348 (!\mod_forum\subscriptions
::subscription_disabled($forumobject) ||
$canmanage);
5351 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node
::TYPE_CONTAINER
);
5352 $mode->add_class('subscriptionmode');
5353 $mode->set_show_in_secondary_navigation(false);
5355 // Optional subscription mode.
5356 $allowchoicestring = get_string('subscriptionoptional', 'forum');
5357 $allowchoiceaction = new action_link(
5358 new moodle_url('/mod/forum/subscribe.php', [
5359 'id' => $forumobject->id
,
5360 'mode' => FORUM_CHOOSESUBSCRIBE
,
5361 'sesskey' => sesskey(),
5364 new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $allowchoicestring))
5366 $allowchoice = $mode->add($allowchoicestring, $allowchoiceaction, navigation_node
::TYPE_SETTING
);
5368 // Forced subscription mode.
5369 $forceforeverstring = get_string('subscriptionforced', 'forum');
5370 $forceforeveraction = new action_link(
5371 new moodle_url('/mod/forum/subscribe.php', [
5372 'id' => $forumobject->id
,
5373 'mode' => FORUM_FORCESUBSCRIBE
,
5374 'sesskey' => sesskey(),
5376 $forceforeverstring,
5377 new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $forceforeverstring))
5379 $forceforever = $mode->add($forceforeverstring, $forceforeveraction, navigation_node
::TYPE_SETTING
);
5381 // Initial subscription mode.
5382 $forceinitiallystring = get_string('subscriptionauto', 'forum');
5383 $forceinitiallyaction = new action_link(
5384 new moodle_url('/mod/forum/subscribe.php', [
5385 'id' => $forumobject->id
,
5386 'mode' => FORUM_INITIALSUBSCRIBE
,
5387 'sesskey' => sesskey(),
5389 $forceinitiallystring,
5390 new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $forceinitiallystring))
5392 $forceinitially = $mode->add($forceinitiallystring, $forceinitiallyaction, navigation_node
::TYPE_SETTING
);
5394 // Disabled subscription mode.
5395 $disallowchoicestring = get_string('subscriptiondisabled', 'forum');
5396 $disallowchoiceaction = new action_link(
5397 new moodle_url('/mod/forum/subscribe.php', [
5398 'id' => $forumobject->id
,
5399 'mode' => FORUM_DISALLOWSUBSCRIBE
,
5400 'sesskey' => sesskey(),
5402 $disallowchoicestring,
5403 new confirm_action(get_string('subscriptionmodeconfirm', 'mod_forum', $disallowchoicestring))
5405 $disallowchoice = $mode->add($disallowchoicestring, $disallowchoiceaction, navigation_node
::TYPE_SETTING
);
5407 switch ($subscriptionmode) {
5408 case FORUM_CHOOSESUBSCRIBE
: // 0
5409 $allowchoice->action
= null;
5410 $allowchoice->add_class('activesetting');
5411 $allowchoice->icon
= new pix_icon('t/selected', '', 'mod_forum');
5413 case FORUM_FORCESUBSCRIBE
: // 1
5414 $forceforever->action
= null;
5415 $forceforever->add_class('activesetting');
5416 $forceforever->icon
= new pix_icon('t/selected', '', 'mod_forum');
5418 case FORUM_INITIALSUBSCRIBE
: // 2
5419 $forceinitially->action
= null;
5420 $forceinitially->add_class('activesetting');
5421 $forceinitially->icon
= new pix_icon('t/selected', '', 'mod_forum');
5423 case FORUM_DISALLOWSUBSCRIBE
: // 3
5424 $disallowchoice->action
= null;
5425 $disallowchoice->add_class('activesetting');
5426 $disallowchoice->icon
= new pix_icon('t/selected', '', 'mod_forum');
5430 } else if ($activeenrolled) {
5432 switch ($subscriptionmode) {
5433 case FORUM_CHOOSESUBSCRIBE
: // 0
5434 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
5436 case FORUM_FORCESUBSCRIBE
: // 1
5437 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
5439 case FORUM_INITIALSUBSCRIBE
: // 2
5440 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
5442 case FORUM_DISALLOWSUBSCRIBE
: // 3
5443 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
5448 if (has_capability('mod/forum:viewsubscribers', $settingsnav->get_page()->context
)) {
5449 $url = new moodle_url('/mod/forum/subscribers.php', ['id' => $forumobject->id
, 'edit' => 'off']);
5450 $forumnode->add(get_string('subscriptions', 'forum'), $url, navigation_node
::TYPE_SETTING
, null, 'forumsubscriptions');
5453 // Display all forum reports user has access to.
5454 if (isloggedin() && !isguestuser()) {
5455 $reportnames = array_keys(core_component
::get_plugin_list('forumreport'));
5457 foreach ($reportnames as $reportname) {
5458 if (has_capability("forumreport/{$reportname}:view", $settingsnav->get_page()->context
)) {
5459 $reportlinkparams = [
5460 'courseid' => $forumobject->course
,
5461 'forumid' => $forumobject->id
,
5463 $reportlink = new moodle_url("/mod/forum/report/{$reportname}/index.php", $reportlinkparams);
5464 $forumnode->add(get_string('reports'), $reportlink, navigation_node
::TYPE_CONTAINER
);
5469 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
5470 if ($forumobject->trackingtype
== FORUM_TRACKING_OPTIONAL
5471 ||
((!$CFG->forum_allowforcedreadtracking
) && $forumobject->trackingtype
== FORUM_TRACKING_FORCED
)) {
5472 if (forum_tp_is_tracked($forumobject)) {
5473 $linktext = get_string('notrackforum', 'forum');
5475 $linktext = get_string('trackforum', 'forum');
5477 $url = new moodle_url('/mod/forum/settracking.php', array(
5478 'id' => $forumobject->id
,
5479 'sesskey' => sesskey(),
5481 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
5485 if (!isloggedin() && $settingsnav->get_page()->course
->id
== SITEID
) {
5486 $userid = guest_user()->id
;
5488 $userid = $USER->id
;
5491 $hascourseaccess = ($settingsnav->get_page()->course
->id
== SITEID
) ||
5492 can_access_course($settingsnav->get_page()->course
, $userid);
5493 $enablerssfeeds = !empty($CFG->enablerssfeeds
) && !empty($CFG->forum_enablerssfeeds
);
5495 if ($enablerssfeeds && $forumobject->rsstype
&& $forumobject->rssarticles
&& $hascourseaccess) {
5497 if (!function_exists('rss_get_url')) {
5498 require_once("$CFG->libdir/rsslib.php");
5501 if ($forumobject->rsstype
== 1) {
5502 $string = get_string('rsssubscriberssdiscussions','forum');
5504 $string = get_string('rsssubscriberssposts','forum');
5507 $url = new moodle_url(rss_get_url($settingsnav->get_page()->cm
->context
->id
, $userid, "mod_forum",
5509 $forumnode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
5512 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
5513 if ($capabilitymanager->can_export_forum($USER)) {
5514 $url = new moodle_url('/mod/forum/export.php', ['id' => $forumobject->id
]);
5515 $forumnode->add(get_string('export', 'mod_forum'), $url, navigation_node
::TYPE_SETTING
);
5520 * Return a list of page types
5521 * @param string $pagetype current page type
5522 * @param stdClass $parentcontext Block's parent context
5523 * @param stdClass $currentcontext Current context of block
5525 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
5526 $forum_pagetype = array(
5527 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
5528 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
5529 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
5531 return $forum_pagetype;
5535 * Gets all of the courses where the provided user has posted in a forum.
5537 * @global moodle_database $DB The database connection
5538 * @param stdClass $user The user who's posts we are looking for
5539 * @param bool $discussionsonly If true only look for discussions started by the user
5540 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
5541 * @param int $limitfrom The offset of records to return
5542 * @param int $limitnum The number of records to return
5543 * @return array An array of courses
5545 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
5548 // If we are only after discussions we need only look at the forum_discussions
5549 // table and join to the userid there. If we are looking for posts then we need
5550 // to join to the forum_posts table.
5551 if (!$discussionsonly) {
5552 $subquery = "(SELECT DISTINCT fd.course
5553 FROM {forum_discussions} fd
5554 JOIN {forum_posts} fp ON fp.discussion = fd.id
5555 WHERE fp.userid = :userid )";
5557 $subquery= "(SELECT DISTINCT fd.course
5558 FROM {forum_discussions} fd
5559 WHERE fd.userid = :userid )";
5562 $params = array('userid' => $user->id
);
5564 // Join to the context table so that we can preload contexts if required.
5565 if ($includecontexts) {
5566 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
5567 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
5568 $params['contextlevel'] = CONTEXT_COURSE
;
5574 // Now we need to get all of the courses to search.
5575 // All courses where the user has posted within a forum will be returned.
5576 $sql = "SELECT c.* $ctxselect
5579 WHERE c.id IN ($subquery)";
5580 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5581 if ($includecontexts) {
5582 array_map('context_helper::preload_from_record', $courses);
5588 * Gets all of the forums a user has posted in for one or more courses.
5590 * @global moodle_database $DB
5591 * @param stdClass $user
5592 * @param array $courseids An array of courseids to search or if not provided
5593 * all courses the user has posted within
5594 * @param bool $discussionsonly If true then only forums where the user has started
5595 * a discussion will be returned.
5596 * @param int $limitfrom The offset of records to return
5597 * @param int $limitnum The number of records to return
5598 * @return array An array of forums the user has posted within in the provided courses
5600 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
5603 if (!is_null($courseids)) {
5604 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
, 'courseid');
5605 $coursewhere = ' AND f.course '.$coursewhere;
5610 $params['userid'] = $user->id
;
5611 $params['forum'] = 'forum';
5613 if ($discussionsonly) {
5614 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
5616 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
5617 JOIN {forum_posts} ff ON ff.discussion = fd.id';
5620 $sql = "SELECT f.*, cm.id AS cmid
5622 JOIN {course_modules} cm ON cm.instance = f.id
5623 JOIN {modules} m ON m.id = cm.module
5628 WHERE ff.userid = :userid
5631 WHERE m.name = :forum
5634 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5635 return $courseforums;
5639 * Returns posts made by the selected user in the requested courses.
5641 * This method can be used to return all of the posts made by the requested user
5642 * within the given courses.
5643 * For each course the access of the current user and requested user is checked
5644 * and then for each post access to the post and forum is checked as well.
5646 * This function is safe to use with usercapabilities.
5648 * @global moodle_database $DB
5649 * @param stdClass $user The user whose posts we want to get
5650 * @param array $courses The courses to search
5651 * @param bool $musthaveaccess If set to true errors will be thrown if the user
5652 * cannot access one or more of the courses to search
5653 * @param bool $discussionsonly If set to true only discussion starting posts
5655 * @param int $limitfrom The offset of records to return
5656 * @param int $limitnum The number of records to return
5657 * @return stdClass An object the following properties
5658 * ->totalcount: the total number of posts made by the requested user
5659 * that the current user can see.
5660 * ->courses: An array of courses the current user can see that the
5661 * requested user has posted in.
5662 * ->forums: An array of forums relating to the posts returned in the
5664 * ->posts: An array containing the posts to show for this request.
5666 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
5667 global $DB, $USER, $CFG;
5669 $return = new stdClass
;
5670 $return->totalcount
= 0; // The total number of posts that the current user is able to view
5671 $return->courses
= array(); // The courses the current user can access
5672 $return->forums
= array(); // The forums that the current user can access that contain posts
5673 $return->posts
= array(); // The posts to display
5675 // First up a small sanity check. If there are no courses to check we can
5676 // return immediately, there is obviously nothing to search.
5677 if (empty($courses)) {
5681 // A couple of quick setups
5682 $isloggedin = isloggedin();
5683 $isguestuser = $isloggedin && isguestuser();
5684 $iscurrentuser = $isloggedin && $USER->id
== $user->id
;
5686 // Checkout whether or not the current user has capabilities over the requested
5687 // user and if so they have the capabilities required to view the requested
5689 $usercontext = context_user
::instance($user->id
, MUST_EXIST
);
5690 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
));
5691 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
5693 // Before we actually search each course we need to check the user's access to the
5694 // course. If the user doesn't have the appropraite access then we either throw an
5695 // error if a particular course was requested or we just skip over the course.
5696 foreach ($courses as $course) {
5697 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
5698 if ($iscurrentuser ||
$hascapsonuser) {
5699 // If it is the current user, or the current user has capabilities to the
5700 // requested user then all we need to do is check the requested users
5701 // current access to the course.
5702 // Note: There is no need to check group access or anything of the like
5703 // as either the current user is the requested user, or has granted
5704 // capabilities on the requested user. Either way they can see what the
5705 // requested user posted, although its VERY unlikely in the `parent` situation
5706 // that the current user will be able to view the posts in context.
5707 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
5708 // Need to have full access to a course to see the rest of own info
5709 if ($musthaveaccess) {
5710 throw new \
moodle_exception('errorenrolmentrequired', 'forum');
5715 // Check whether the current user is enrolled or has access to view the course
5716 // if they don't we immediately have a problem.
5717 if (!can_access_course($course)) {
5718 if ($musthaveaccess) {
5719 throw new \
moodle_exception('errorenrolmentrequired', 'forum');
5724 // If groups are in use and enforced throughout the course then make sure
5725 // we can meet in at least one course level group.
5726 // Note that we check if either the current user or the requested user have
5727 // the capability to access all groups. This is because with that capability
5728 // a user in group A could post in the group B forum. Grrrr.
5729 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&& $course->groupmodeforce
5730 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id
)) {
5731 // If its the guest user to bad... the guest user cannot access groups
5732 if (!$isloggedin or $isguestuser) {
5733 // do not use require_login() here because we might have already used require_login($course)
5734 if ($musthaveaccess) {
5735 redirect(get_login_url());
5739 // Get the groups of the current user
5740 $mygroups = array_keys(groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
, 'g.id, g.name'));
5741 // Get the groups the requested user is a member of
5742 $usergroups = array_keys(groups_get_all_groups($course->id
, $user->id
, $course->defaultgroupingid
, 'g.id, g.name'));
5743 // Check whether they are members of the same group. If they are great.
5744 $intersect = array_intersect($mygroups, $usergroups);
5745 if (empty($intersect)) {
5746 // But they're not... if it was a specific course throw an error otherwise
5747 // just skip this course so that it is not searched.
5748 if ($musthaveaccess) {
5749 throw new \
moodle_exception("groupnotamember", '', $CFG->wwwroot
."/course/view.php?id=$course->id");
5755 // Woo hoo we got this far which means the current user can search this
5756 // this course for the requested user. Although this is only the course accessibility
5757 // handling that is complete, the forum accessibility tests are yet to come.
5758 $return->courses
[$course->id
] = $course;
5760 // No longer beed $courses array - lose it not it may be big
5763 // Make sure that we have some courses to search
5764 if (empty($return->courses
)) {
5765 // If we don't have any courses to search then the reality is that the current
5766 // user doesn't have access to any courses is which the requested user has posted.
5767 // Although we do know at this point that the requested user has posts.
5768 if ($musthaveaccess) {
5769 throw new \
moodle_exception('permissiondenied');
5775 // Next step: Collect all of the forums that we will want to search.
5776 // It is important to note that this step isn't actually about searching, it is
5777 // about determining which forums we can search by testing accessibility.
5778 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses
), $discussionsonly);
5780 // Will be used to build the where conditions for the search
5781 $forumsearchwhere = array();
5782 // Will be used to store the where condition params for the search
5783 $forumsearchparams = array();
5784 // Will record forums where the user can freely access everything
5785 $forumsearchfullaccess = array();
5786 // DB caching friendly
5787 $now = floor(time() / 60) * 60;
5788 // For each course to search we want to find the forums the user has posted in
5789 // and providing the current user can access the forum create a search condition
5790 // for the forum to get the requested users posts.
5791 foreach ($return->courses
as $course) {
5792 // Now we need to get the forums
5793 $modinfo = get_fast_modinfo($course);
5794 if (empty($modinfo->instances
['forum'])) {
5795 // hmmm, no forums? well at least its easy... skip!
5799 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
5800 if (!$cm->uservisible
or !isset($forums[$forumid])) {
5803 // Get the forum in question
5804 $forum = $forums[$forumid];
5806 // This is needed for functionality later on in the forum code. It is converted to an object
5807 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
5808 // code were expecting an writeable object. See {@link forum_print_post()}.
5809 $forum->cm
= new stdClass();
5810 foreach ($cm as $key => $value) {
5811 $forum->cm
->$key = $value;
5814 // Check that either the current user can view the forum, or that the
5815 // current user has capabilities over the requested user and the requested
5816 // user can view the discussion
5817 if (!has_capability('mod/forum:viewdiscussion', $cm->context
) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context
, $user->id
))) {
5821 // This will contain forum specific where clauses
5822 $forumsearchselect = array();
5823 if (!$iscurrentuser && !$hascapsonuser) {
5824 // Make sure we check group access
5825 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $cm->context
)) {
5826 $groups = $modinfo->get_groups($cm->groupingid
);
5828 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
5829 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
5830 $forumsearchselect[] = "d.groupid $groupid_sql";
5833 // hidden timed discussions
5834 if (!empty($CFG->forum_enabletimedposts
) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context
)) {
5835 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
5836 $forumsearchparams['userid'.$forumid] = $user->id
;
5837 $forumsearchparams['timestart'.$forumid] = $now;
5838 $forumsearchparams['timeend'.$forumid] = $now;
5842 if ($forum->type
== 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context
)) {
5843 // We need to check whether the user has posted in the qanda forum.
5844 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $user->id
);
5845 if (!empty($discussionspostedin)) {
5846 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
5847 foreach ($discussionspostedin as $d) {
5848 $forumonlydiscussions[] = $d->id
;
5850 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
5851 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
5852 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
5854 $forumsearchselect[] = "p.parent = 0";
5859 if (count($forumsearchselect) > 0) {
5860 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
5861 $forumsearchparams['forum'.$forumid] = $forumid;
5863 $forumsearchfullaccess[] = $forumid;
5866 // The current user/parent can see all of their own posts
5867 $forumsearchfullaccess[] = $forumid;
5872 // If we dont have any search conditions, and we don't have any forums where
5873 // the user has full access then we just return the default.
5874 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
5878 // Prepare a where condition for the full access forums.
5879 if (count($forumsearchfullaccess) > 0) {
5880 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED
, 'fula');
5881 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
5882 $forumsearchwhere[] = "(d.forum $fullidsql)";
5885 // Prepare SQL to both count and search.
5886 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
5887 // oracle and mssql.
5888 $userfieldsapi = \core_user\fields
::for_userpic();
5889 $userfields = $userfieldsapi->get_sql('u', false, '', 'useridx', false)->selects
;
5890 $countsql = 'SELECT COUNT(*) ';
5891 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
5892 $wheresql = implode(" OR ", $forumsearchwhere);
5894 if ($discussionsonly) {
5895 if ($wheresql == '') {
5896 $wheresql = 'p.parent = 0';
5898 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
5902 $sql = "FROM {forum_posts} p
5903 JOIN {forum_discussions} d ON d.id = p.discussion
5904 JOIN {user} u ON u.id = p.userid
5906 AND p.userid = :userid ";
5907 $orderby = "ORDER BY p.modified DESC";
5908 $forumsearchparams['userid'] = $user->id
;
5910 // Set the total number posts made by the requested user that the current user can see
5911 $return->totalcount
= $DB->count_records_sql($countsql.$sql, $forumsearchparams);
5912 // Set the collection of posts that has been requested
5913 $return->posts
= $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
5915 // We need to build an array of forums for which posts will be displayed.
5916 // We do this here to save the caller needing to retrieve them themselves before
5917 // printing these forums posts. Given we have the forums already there is
5918 // practically no overhead here.
5919 foreach ($return->posts
as $post) {
5920 if (!array_key_exists($post->forum
, $return->forums
)) {
5921 $return->forums
[$post->forum
] = $forums[$post->forum
];
5929 * Set the per-forum maildigest option for the specified user.
5931 * @param stdClass $forum The forum to set the option for.
5932 * @param int $maildigest The maildigest option.
5933 * @param stdClass $user The user object. This defaults to the global $USER object.
5934 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
5936 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
5939 if (is_number($forum)) {
5940 $forum = $DB->get_record('forum', array('id' => $forum));
5943 if ($user === null) {
5947 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
5948 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
5949 $context = context_module
::instance($cm->id
);
5951 // User must be allowed to see this forum.
5952 require_capability('mod/forum:viewdiscussion', $context, $user->id
);
5954 // Validate the maildigest setting.
5955 $digestoptions = forum_get_user_digest_options($user);
5957 if (!isset($digestoptions[$maildigest])) {
5958 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
5961 // Attempt to retrieve any existing forum digest record.
5962 $subscription = $DB->get_record('forum_digests', array(
5963 'userid' => $user->id
,
5964 'forum' => $forum->id
,
5967 // Create or Update the existing maildigest setting.
5968 if ($subscription) {
5969 if ($maildigest == -1) {
5970 $DB->delete_records('forum_digests', array('forum' => $forum->id
, 'userid' => $user->id
));
5971 } else if ($maildigest !== $subscription->maildigest
) {
5972 // Only update the maildigest setting if it's changed.
5974 $subscription->maildigest
= $maildigest;
5975 $DB->update_record('forum_digests', $subscription);
5978 if ($maildigest != -1) {
5979 // Only insert the maildigest setting if it's non-default.
5981 $subscription = new stdClass();
5982 $subscription->forum
= $forum->id
;
5983 $subscription->userid
= $user->id
;
5984 $subscription->maildigest
= $maildigest;
5985 $subscription->id
= $DB->insert_record('forum_digests', $subscription);
5991 * Determine the maildigest setting for the specified user against the
5994 * @param Array $digests An array of forums and user digest settings.
5995 * @param stdClass $user The user object containing the id and maildigest default.
5996 * @param int $forumid The ID of the forum to check.
5997 * @return int The calculated maildigest setting for this user and forum.
5999 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
6000 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id
])) {
6001 $maildigest = $digests[$forumid][$user->id
];
6002 if ($maildigest === -1) {
6003 $maildigest = $user->maildigest
;
6006 $maildigest = $user->maildigest
;
6012 * Retrieve the list of available user digest options.
6014 * @param stdClass $user The user object. This defaults to the global $USER object.
6015 * @return array The mapping of values to digest options.
6017 function forum_get_user_digest_options($user = null) {
6020 // Revert to the global user object.
6021 if ($user === null) {
6025 $digestoptions = array();
6026 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
6027 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
6028 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
6030 // We need to add the default digest option at the end - it relies on
6031 // the contents of the existing values.
6032 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
6033 $digestoptions[$user->maildigest
]);
6035 // Resort the options to be in a sensible order.
6036 ksort($digestoptions);
6038 return $digestoptions;
6042 * Determine the current context if one was not already specified.
6044 * If a context of type context_module is specified, it is immediately
6045 * returned and not checked.
6047 * @param int $forumid The ID of the forum
6048 * @param context_module $context The current context.
6049 * @return context_module The context determined
6051 function forum_get_context($forumid, $context = null) {
6054 if (!$context ||
!($context instanceof context_module
)) {
6055 // Find out forum context. First try to take current page context to save on DB query.
6056 if ($PAGE->cm
&& $PAGE->cm
->modname
=== 'forum' && $PAGE->cm
->instance
== $forumid
6057 && $PAGE->context
->contextlevel
== CONTEXT_MODULE
&& $PAGE->context
->instanceid
== $PAGE->cm
->id
) {
6058 $context = $PAGE->context
;
6060 $cm = get_coursemodule_from_instance('forum', $forumid);
6061 $context = \context_module
::instance($cm->id
);
6069 * Mark the activity completed (if required) and trigger the course_module_viewed event.
6071 * @param stdClass $forum forum object
6072 * @param stdClass $course course object
6073 * @param stdClass $cm course module object
6074 * @param stdClass $context context object
6077 function forum_view($forum, $course, $cm, $context) {
6080 $completion = new completion_info($course);
6081 $completion->set_module_viewed($cm);
6083 // Trigger course_module_viewed event.
6086 'context' => $context,
6087 'objectid' => $forum->id
6090 $event = \mod_forum\event\course_module_viewed
::create($params);
6091 $event->add_record_snapshot('course_modules', $cm);
6092 $event->add_record_snapshot('course', $course);
6093 $event->add_record_snapshot('forum', $forum);
6098 * Trigger the discussion viewed event
6100 * @param stdClass $modcontext module context object
6101 * @param stdClass $forum forum object
6102 * @param stdClass $discussion discussion object
6105 function forum_discussion_view($modcontext, $forum, $discussion) {
6107 'context' => $modcontext,
6108 'objectid' => $discussion->id
,
6111 $event = \mod_forum\event\discussion_viewed
::create($params);
6112 $event->add_record_snapshot('forum_discussions', $discussion);
6113 $event->add_record_snapshot('forum', $forum);
6118 * Set the discussion to pinned and trigger the discussion pinned event
6120 * @param stdClass $modcontext module context object
6121 * @param stdClass $forum forum object
6122 * @param stdClass $discussion discussion object
6125 function forum_discussion_pin($modcontext, $forum, $discussion) {
6128 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED
, array('id' => $discussion->id
));
6131 'context' => $modcontext,
6132 'objectid' => $discussion->id
,
6133 'other' => array('forumid' => $forum->id
)
6136 $event = \mod_forum\event\discussion_pinned
::create($params);
6137 $event->add_record_snapshot('forum_discussions', $discussion);
6142 * Set discussion to unpinned and trigger the discussion unpin event
6144 * @param stdClass $modcontext module context object
6145 * @param stdClass $forum forum object
6146 * @param stdClass $discussion discussion object
6149 function forum_discussion_unpin($modcontext, $forum, $discussion) {
6152 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED
, array('id' => $discussion->id
));
6155 'context' => $modcontext,
6156 'objectid' => $discussion->id
,
6157 'other' => array('forumid' => $forum->id
)
6160 $event = \mod_forum\event\discussion_unpinned
::create($params);
6161 $event->add_record_snapshot('forum_discussions', $discussion);
6166 * Add nodes to myprofile page.
6168 * @param \core_user\output\myprofile\tree $tree Tree object
6169 * @param stdClass $user user object
6170 * @param bool $iscurrentuser
6171 * @param stdClass $course Course object
6175 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree
$tree, $user, $iscurrentuser, $course) {
6176 if (isguestuser($user)) {
6177 // The guest user cannot post, so it is not possible to view any posts.
6178 // May as well just bail aggressively here.
6181 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id
));
6182 if (!empty($course)) {
6183 $postsurl->param('course', $course->id
);
6185 $string = get_string('forumposts', 'mod_forum');
6186 $node = new core_user\output\myprofile\node
('miscellaneous', 'forumposts', $string, null, $postsurl);
6187 $tree->add_node($node);
6189 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id
, 'mode' => 'discussions'));
6190 if (!empty($course)) {
6191 $discussionssurl->param('course', $course->id
);
6193 $string = get_string('myprofileotherdis', 'mod_forum');
6194 $node = new core_user\output\myprofile\node
('miscellaneous', 'forumdiscussions', $string, null,
6196 $tree->add_node($node);
6202 * Checks whether the author's name and picture for a given post should be hidden or not.
6204 * @param object $post The forum post.
6205 * @param object $forum The forum object.
6207 * @throws coding_exception
6209 function forum_is_author_hidden($post, $forum) {
6210 if (!isset($post->parent
)) {
6211 throw new coding_exception('$post->parent must be set.');
6213 if (!isset($forum->type
)) {
6214 throw new coding_exception('$forum->type must be set.');
6216 if ($forum->type
=== 'single' && empty($post->parent
)) {
6223 * Manage inplace editable saves.
6225 * @param string $itemtype The type of item.
6226 * @param int $itemid The ID of the item.
6227 * @param mixed $newvalue The new value
6230 function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) {
6233 if ($itemtype === 'digestoptions') {
6234 // The itemid is the forumid.
6235 $forum = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST
);
6236 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
6237 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
6238 $context = context_module
::instance($cm->id
);
6240 $PAGE->set_context($context);
6241 require_login($course, false, $cm);
6242 forum_set_user_maildigest($forum, $newvalue);
6244 $renderer = $PAGE->get_renderer('mod_forum');
6245 return $renderer->render_digest_options($forum, $newvalue);
6250 * Determine whether the specified forum's cutoff date is reached.
6252 * @param stdClass $forum The forum
6255 function forum_is_cutoff_date_reached($forum) {
6256 $entityfactory = \mod_forum\local\container
::get_entity_factory();
6257 $coursemoduleinfo = get_fast_modinfo($forum->course
);
6258 $cminfo = $coursemoduleinfo->instances
['forum'][$forum->id
];
6259 $forumentity = $entityfactory->get_forum_from_stdclass(
6261 context_module
::instance($cminfo->id
),
6262 $cminfo->get_course_module_record(),
6263 $cminfo->get_course()
6266 return $forumentity->is_cutoff_date_reached();
6270 * Determine whether the specified forum's due date is reached.
6272 * @param stdClass $forum The forum
6275 function forum_is_due_date_reached($forum) {
6276 $entityfactory = \mod_forum\local\container
::get_entity_factory();
6277 $coursemoduleinfo = get_fast_modinfo($forum->course
);
6278 $cminfo = $coursemoduleinfo->instances
['forum'][$forum->id
];
6279 $forumentity = $entityfactory->get_forum_from_stdclass(
6281 context_module
::instance($cminfo->id
),
6282 $cminfo->get_course_module_record(),
6283 $cminfo->get_course()
6286 return $forumentity->is_due_date_reached();
6290 * Determine whether the specified discussion is time-locked.
6292 * @param stdClass $forum The forum that the discussion belongs to
6293 * @param stdClass $discussion The discussion to test
6296 function forum_discussion_is_locked($forum, $discussion) {
6297 $entityfactory = \mod_forum\local\container
::get_entity_factory();
6298 $coursemoduleinfo = get_fast_modinfo($forum->course
);
6299 $cminfo = $coursemoduleinfo->instances
['forum'][$forum->id
];
6300 $forumentity = $entityfactory->get_forum_from_stdclass(
6302 context_module
::instance($cminfo->id
),
6303 $cminfo->get_course_module_record(),
6304 $cminfo->get_course()
6306 $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
6308 return $forumentity->is_discussion_locked($discussionentity);
6312 * Check if the module has any update that affects the current user since a given time.
6314 * @param cm_info $cm course module data
6315 * @param int $from the time to check updates from
6316 * @param array $filter if we need to check only specific updates
6317 * @return stdClass an object with the different type of areas indicating if they were updated or not
6320 function forum_check_updates_since(cm_info
$cm, $from, $filter = array()) {
6322 $context = $cm->context
;
6323 $updates = new stdClass();
6324 if (!has_capability('mod/forum:viewdiscussion', $context)) {
6328 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
6330 // Check if there are new discussions in the forum.
6331 $updates->discussions
= (object) array('updated' => false);
6332 $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS
, $from);
6333 if (!empty($discussions)) {
6334 $updates->discussions
->updated
= true;
6335 $updates->discussions
->itemids
= array_keys($discussions);
6342 * Check if the user can create attachments in a forum.
6343 * @param stdClass $forum forum object
6344 * @param stdClass $context context object
6345 * @return bool true if the user can create attachments, false otherwise
6348 function forum_can_create_attachment($forum, $context) {
6349 // If maxbytes == 1 it means no attachments at all.
6350 if (empty($forum->maxattachments
) ||
$forum->maxbytes
== 1 ||
6351 !has_capability('mod/forum:createattachment', $context)) {
6358 * Get icon mapping for font-awesome.
6362 function mod_forum_get_fontawesome_icon_map() {
6364 'mod_forum:i/pinned' => 'fa-map-pin',
6365 'mod_forum:t/selected' => 'fa-check',
6366 'mod_forum:t/subscribed' => 'fa-envelope-o',
6367 'mod_forum:t/unsubscribed' => 'fa-envelope-open-o',
6368 'mod_forum:t/star' => 'fa-star',
6373 * Callback function that determines whether an action event should be showing its item count
6374 * based on the event type and the item count.
6376 * @param calendar_event $event The calendar event.
6377 * @param int $itemcount The item count associated with the action event.
6380 function mod_forum_core_calendar_event_action_shows_item_count(calendar_event
$event, $itemcount = 0) {
6381 // Always show item count for forums if item count is greater than 1.
6382 // If only one action is required than it is obvious and we don't show it for other modules.
6383 return $itemcount > 1;
6387 * This function receives a calendar event and returns the action associated with it, or null if there is none.
6389 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
6390 * is not displayed on the block.
6392 * @param calendar_event $event
6393 * @param \core_calendar\action_factory $factory
6394 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
6395 * @return \core_calendar\local\event\entities\action_interface|null
6397 function mod_forum_core_calendar_provide_event_action(calendar_event
$event,
6398 \core_calendar\action_factory
$factory,
6403 $userid = $USER->id
;
6406 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['forum'][$event->instance
];
6408 if (!$cm->uservisible
) {
6409 // The module is not visible to the user for any reason.
6413 $context = context_module
::instance($cm->id
);
6415 if (!has_capability('mod/forum:viewdiscussion', $context, $userid)) {
6419 $completion = new \
completion_info($cm->get_course());
6421 $completiondata = $completion->get_data($cm, false, $userid);
6423 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
6427 // Get action itemcount.
6429 $forum = $DB->get_record('forum', array('id' => $cm->instance
));
6435 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
6437 fp.userid=:userid AND fd.forum=:forumid";
6438 $postcountparams = array('userid' => $userid, 'forumid' => $forum->id
);
6440 if ($forum->completiondiscussions
) {
6441 $count = $DB->count_records('forum_discussions', array('forum' => $forum->id
, 'userid' => $userid));
6442 $itemcount +
= ($forum->completiondiscussions
>= $count) ?
($forum->completiondiscussions
- $count) : 0;
6445 if ($forum->completionreplies
) {
6446 $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams);
6447 $itemcount +
= ($forum->completionreplies
>= $count) ?
($forum->completionreplies
- $count) : 0;
6450 if ($forum->completionposts
) {
6451 $count = $DB->get_field_sql($postcountsql, $postcountparams);
6452 $itemcount +
= ($forum->completionposts
>= $count) ?
($forum->completionposts
- $count) : 0;
6455 // Well there is always atleast one actionable item (view forum, etc).
6456 $itemcount = $itemcount > 0 ?
$itemcount : 1;
6458 return $factory->create_instance(
6460 new \
moodle_url('/mod/forum/view.php', ['id' => $cm->id
]),
6467 * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information
6468 * for the course (see resource).
6470 * Given a course_module object, this function returns any "extra" information that may be needed
6471 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
6473 * @param stdClass $coursemodule The coursemodule object (record).
6474 * @return cached_cm_info An object on information that the courses
6475 * will know about (most noticeably, an icon).
6477 function forum_get_coursemodule_info($coursemodule) {
6480 $dbparams = ['id' => $coursemodule->instance
];
6481 $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies, duedate, cutoffdate, trackingtype';
6482 if (!$forum = $DB->get_record('forum', $dbparams, $fields)) {
6486 $result = new cached_cm_info();
6487 $result->name
= $forum->name
;
6489 if ($coursemodule->showdescription
) {
6490 // Convert intro to html. Do not filter cached version, filters run at display time.
6491 $result->content
= format_module_intro('forum', $forum, $coursemodule->id
, false);
6494 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
6495 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
6496 $result->customdata
['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions
;
6497 $result->customdata
['customcompletionrules']['completionreplies'] = $forum->completionreplies
;
6498 $result->customdata
['customcompletionrules']['completionposts'] = $forum->completionposts
;
6501 // Populate some other values that can be used in calendar or on dashboard.
6502 if ($forum->duedate
) {
6503 $result->customdata
['duedate'] = $forum->duedate
;
6505 if ($forum->cutoffdate
) {
6506 $result->customdata
['cutoffdate'] = $forum->cutoffdate
;
6508 // Add the forum type to the custom data for Web Services (core_course_get_contents).
6509 $result->customdata
['trackingtype'] = $forum->trackingtype
;
6515 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
6517 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
6518 * @return array $descriptions the array of descriptions for the custom rules.
6520 function mod_forum_get_completion_active_rule_descriptions($cm) {
6521 // Values will be present in cm_info, and we assume these are up to date.
6522 if (empty($cm->customdata
['customcompletionrules'])
6523 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
6528 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
6530 case 'completiondiscussions':
6532 $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val);
6535 case 'completionreplies':
6537 $descriptions[] = get_string('completionrepliesdesc', 'forum', $val);
6540 case 'completionposts':
6542 $descriptions[] = get_string('completionpostsdesc', 'forum', $val);
6549 return $descriptions;
6553 * Check whether the forum post is a private reply visible to this user.
6555 * @param stdClass $post The post to check.
6556 * @param cm_info $cm The context module instance.
6557 * @return bool Whether the post is visible in terms of private reply configuration.
6559 function forum_post_is_visible_privately($post, $cm) {
6562 if (!empty($post->privatereplyto
)) {
6563 // Allow the user to see the private reply if:
6564 // * they hold the permission;
6565 // * they are the author; or
6566 // * they are the intended recipient.
6568 $cansee = $cansee ||
($post->userid
== $USER->id
);
6569 $cansee = $cansee ||
($post->privatereplyto
== $USER->id
);
6570 $cansee = $cansee ||
has_capability('mod/forum:readprivatereplies', context_module
::instance($cm->id
));
6578 * Check whether the user can reply privately to the parent post.
6580 * @param \context_module $context
6581 * @param \stdClass $parent
6584 function forum_user_can_reply_privately(\context_module
$context, \stdClass
$parent): bool {
6585 if ($parent->privatereplyto
) {
6586 // You cannot reply privately to a post which is, itself, a private reply.
6590 return has_capability('mod/forum:postprivatereply', $context);
6594 * This function calculates the minimum and maximum cutoff values for the timestart of
6597 * It will return an array with two values, the first being the minimum cutoff value and
6598 * the second being the maximum cutoff value. Either or both values can be null, which
6599 * indicates there is no minimum or maximum, respectively.
6601 * If a cutoff is required then the function must return an array containing the cutoff
6602 * timestamp and error string to display to the user if the cutoff value is violated.
6604 * A minimum and maximum cutoff return value will look like:
6606 * [1505704373, 'The date must be after this date'],
6607 * [1506741172, 'The date must be before this date']
6610 * @param calendar_event $event The calendar event to get the time range for
6611 * @param stdClass $forum The module instance to get the range from
6612 * @return array Returns an array with min and max date.
6614 function mod_forum_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, \stdClass
$forum) {
6617 require_once($CFG->dirroot
. '/mod/forum/locallib.php');
6622 if ($event->eventtype
== FORUM_EVENT_TYPE_DUE
) {
6623 if (!empty($forum->cutoffdate
)) {
6626 get_string('cutoffdatevalidation', 'forum'),
6631 return [$mindate, $maxdate];
6635 * This function will update the forum module according to the
6636 * event that has been modified.
6638 * It will set the timeclose value of the forum instance
6639 * according to the type of event provided.
6641 * @throws \moodle_exception
6642 * @param \calendar_event $event
6643 * @param stdClass $forum The module instance to get the range from
6645 function mod_forum_core_calendar_event_timestart_updated(\calendar_event
$event, \stdClass
$forum) {
6648 require_once($CFG->dirroot
. '/mod/forum/locallib.php');
6650 if ($event->eventtype
!= FORUM_EVENT_TYPE_DUE
) {
6654 $courseid = $event->courseid
;
6655 $modulename = $event->modulename
;
6656 $instanceid = $event->instance
;
6658 // Something weird going on. The event is for a different module so
6659 // we should ignore it.
6660 if ($modulename != 'forum') {
6664 if ($forum->id
!= $instanceid) {
6668 $coursemodule = get_fast_modinfo($courseid)->instances
[$modulename][$instanceid];
6669 $context = context_module
::instance($coursemodule->id
);
6671 // The user does not have the capability to modify this activity.
6672 if (!has_capability('moodle/course:manageactivities', $context)) {
6676 if ($event->eventtype
== FORUM_EVENT_TYPE_DUE
) {
6677 if ($forum->duedate
!= $event->timestart
) {
6678 $forum->duedate
= $event->timestart
;
6679 $forum->timemodified
= time();
6680 // Persist the instance changes.
6681 $DB->update_record('forum', $forum);
6682 $event = \core\event\course_module_updated
::create_from_cm($coursemodule, $context);
6689 * Fetch the data used to display the discussions on the current page.
6691 * @param \mod_forum\local\entities\forum $forum The forum entity
6692 * @param stdClass $user The user to render for
6693 * @param int[]|null $groupid The group to render
6694 * @param int|null $sortorder The sort order to use when selecting the discussions in the list
6695 * @param int|null $pageno The zero-indexed page number to use
6696 * @param int|null $pagesize The number of discussions to show on the page
6697 * @return array The data to use for display
6699 function mod_forum_get_discussion_summaries(\mod_forum\local\entities\forum
$forum, stdClass
$user, ?
int $groupid, ?
int $sortorder,
6700 ?
int $pageno = 0, ?
int $pagesize = 0) {
6702 $vaultfactory = mod_forum\local\container
::get_vault_factory();
6703 $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6704 $managerfactory = mod_forum\local\container
::get_manager_factory();
6705 $capabilitymanager = $managerfactory->get_capability_manager($forum);
6707 $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6709 if (null === $groupids) {
6710 return $discussions = $discussionvault->get_from_forum_id(
6712 $capabilitymanager->can_view_hidden_posts($user),
6716 $pageno * $pagesize);
6718 return $discussions = $discussionvault->get_from_forum_id_and_group_id(
6721 $capabilitymanager->can_view_hidden_posts($user),
6725 $pageno * $pagesize);
6730 * Get a count of all discussions in a forum.
6732 * @param \mod_forum\local\entities\forum $forum The forum entity
6733 * @param stdClass $user The user to render for
6734 * @param int $groupid The group to render
6735 * @return int The number of discussions in a forum
6737 function mod_forum_count_all_discussions(\mod_forum\local\entities\forum
$forum, stdClass
$user, ?
int $groupid) {
6739 $managerfactory = mod_forum\local\container
::get_manager_factory();
6740 $capabilitymanager = $managerfactory->get_capability_manager($forum);
6741 $vaultfactory = mod_forum\local\container
::get_vault_factory();
6742 $discussionvault = $vaultfactory->get_discussions_in_forum_vault();
6744 $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid);
6746 if (null === $groupids) {
6747 return $discussionvault->get_total_discussion_count_from_forum_id(
6749 $capabilitymanager->can_view_hidden_posts($user),
6752 return $discussionvault->get_total_discussion_count_from_forum_id_and_group_id(
6755 $capabilitymanager->can_view_hidden_posts($user),
6761 * Get the list of groups to show based on the current user and requested groupid.
6763 * @param \mod_forum\local\entities\forum $forum The forum entity
6764 * @param stdClass $user The user viewing
6765 * @param int $groupid The groupid requested
6766 * @return array The list of groups to show
6768 function mod_forum_get_groups_from_groupid(\mod_forum\local\entities\forum
$forum, stdClass
$user, ?
int $groupid): ?
array {
6770 $effectivegroupmode = $forum->get_effective_group_mode();
6771 if (empty($effectivegroupmode)) {
6772 // This forum is not in a group mode. Show all posts always.
6776 if (null == $groupid) {
6777 $managerfactory = mod_forum\local\container
::get_manager_factory();
6778 $capabilitymanager = $managerfactory->get_capability_manager($forum);
6779 // No group was specified.
6780 $showallgroups = (VISIBLEGROUPS
== $effectivegroupmode);
6781 $showallgroups = $showallgroups ||
$capabilitymanager->can_access_all_groups($user);
6782 if ($showallgroups) {
6783 // Return null to show all groups.
6786 // No group was specified. Only show the users current groups.
6788 groups_get_all_groups(
6789 $forum->get_course_id(),
6791 $forum->get_course_module_record()->groupingid
6796 // A group was specified. Just show that group.
6802 * Return a list of all the user preferences used by mod_forum.
6806 function mod_forum_user_preferences() {
6807 $vaultfactory = \mod_forum\local\container
::get_vault_factory();
6808 $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
6810 $preferences = array();
6811 $preferences['forum_discussionlistsortorder'] = array(
6812 'null' => NULL_NOT_ALLOWED
,
6813 'default' => $discussionlistvault::SORTORDER_LASTPOST_DESC
,
6814 'type' => PARAM_INT
,
6816 $discussionlistvault::SORTORDER_LASTPOST_DESC
,
6817 $discussionlistvault::SORTORDER_LASTPOST_ASC
,
6818 $discussionlistvault::SORTORDER_CREATED_DESC
,
6819 $discussionlistvault::SORTORDER_CREATED_ASC
,
6820 $discussionlistvault::SORTORDER_REPLIES_DESC
,
6821 $discussionlistvault::SORTORDER_REPLIES_ASC
6824 $preferences['forum_useexperimentalui'] = [
6825 'null' => NULL_NOT_ALLOWED
,
6827 'type' => PARAM_BOOL
6830 return $preferences;
6834 * Lists all gradable areas for the advanced grading methods gramework.
6836 * @return array('string'=>'string') An array with area names as keys and descriptions as values
6838 function forum_grading_areas_list() {
6840 'forum' => get_string('grade_forum_header', 'forum'),
6845 * Callback to fetch the activity event type lang string.
6847 * @param string $eventtype The event type.
6848 * @return lang_string The event type lang string.
6850 function mod_forum_core_calendar_get_event_action_string(string $eventtype): string {
6852 require_once($CFG->dirroot
. '/mod/forum/locallib.php');
6854 $modulename = get_string('modulename', 'forum');
6856 if ($eventtype == FORUM_EVENT_TYPE_DUE
) {
6857 return get_string('calendardue', 'forum', $modulename);
6859 return get_string('requiresaction', 'calendar', $modulename);
6864 * This callback will check the provided instance of this module
6865 * and make sure there are up-to-date events created for it.
6867 * @param int $courseid Not used.
6868 * @param stdClass $instance Forum module instance.
6869 * @param stdClass $cm Course module object.
6871 function forum_refresh_events(int $courseid, stdClass
$instance, stdClass
$cm): void
{
6874 // This function is called by cron and we need to include the locallib for calls further down.
6875 require_once($CFG->dirroot
. '/mod/forum/locallib.php');
6877 forum_update_calendar($instance, $cm->id
);