2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') || die();
25 /** Include required files */
26 require_once(__DIR__ . '/deprecatedlib.php');
27 require_once($CFG->libdir.'/filelib.php');
29 /// CONSTANTS ///////////////////////////////////////////////////////////
31 define('FORUM_MODE_FLATOLDEST', 1);
32 define('FORUM_MODE_FLATNEWEST', -1);
33 define('FORUM_MODE_THREADED', 2);
34 define('FORUM_MODE_NESTED', 3);
36 define('FORUM_CHOOSESUBSCRIBE', 0);
37 define('FORUM_FORCESUBSCRIBE', 1);
38 define('FORUM_INITIALSUBSCRIBE', 2);
39 define('FORUM_DISALLOWSUBSCRIBE',3);
42 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
44 define('FORUM_TRACKING_OFF', 0);
47 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
49 define('FORUM_TRACKING_OPTIONAL', 1);
52 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
53 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
55 define('FORUM_TRACKING_FORCED', 2);
57 define('FORUM_MAILED_PENDING', 0);
58 define('FORUM_MAILED_SUCCESS', 1);
59 define('FORUM_MAILED_ERROR', 2);
61 if (!defined('FORUM_CRON_USER_CACHE')) {
62 /** Defines how many full user records are cached in forum cron. */
63 define('FORUM_CRON_USER_CACHE', 5000);
67 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
69 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
71 define('FORUM_DISCUSSION_PINNED', 1);
72 define('FORUM_DISCUSSION_UNPINNED', 0);
74 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
77 * Given an object containing all the necessary data,
78 * (defined by the form in mod_form.php) this function
79 * will create a new instance and return the id number
80 * of the new instance.
82 * @param stdClass $forum add forum instance
83 * @param mod_forum_mod_form $mform
84 * @return int intance id
86 function forum_add_instance($forum, $mform = null) {
89 $forum->timemodified = time();
91 if (empty($forum->assessed)) {
95 if (empty($forum->ratingtime) or empty($forum->assessed)) {
96 $forum->assesstimestart = 0;
97 $forum->assesstimefinish = 0;
100 $forum->id = $DB->insert_record('forum', $forum);
101 $modcontext = context_module::instance($forum->coursemodule);
103 if ($forum->type == 'single') { // Create related discussion.
104 $discussion = new stdClass();
105 $discussion->course = $forum->course;
106 $discussion->forum = $forum->id;
107 $discussion->name = $forum->name;
108 $discussion->assessed = $forum->assessed;
109 $discussion->message = $forum->intro;
110 $discussion->messageformat = $forum->introformat;
111 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
112 $discussion->mailnow = false;
113 $discussion->groupid = -1;
117 $discussion->id = forum_add_discussion($discussion, null, $message);
119 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
120 // Ugly hack - we need to copy the files somehow.
121 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
122 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
124 $options = array('subdirs'=>true); // Use the same options as intro field!
125 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
126 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
130 forum_grade_item_update($forum);
132 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
133 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
139 * Handle changes following the creation of a forum instance.
140 * This function is typically called by the course_module_created observer.
142 * @param object $context the forum context
143 * @param stdClass $forum The forum object
146 function forum_instance_created($context, $forum) {
147 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
148 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
149 foreach ($users as $user) {
150 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
156 * Given an object containing all the necessary data,
157 * (defined by the form in mod_form.php) this function
158 * will update an existing instance with new data.
161 * @param object $forum forum instance (with magic quotes)
162 * @return bool success
164 function forum_update_instance($forum, $mform) {
165 global $DB, $OUTPUT, $USER;
167 $forum->timemodified = time();
168 $forum->id = $forum->instance;
170 if (empty($forum->assessed)) {
171 $forum->assessed = 0;
174 if (empty($forum->ratingtime) or empty($forum->assessed)) {
175 $forum->assesstimestart = 0;
176 $forum->assesstimefinish = 0;
179 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
181 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
182 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
183 // 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
184 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
185 forum_update_grades($forum); // recalculate grades for the forum
188 if ($forum->type == 'single') { // Update related discussion and post.
189 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
190 if (!empty($discussions)) {
191 if (count($discussions) > 1) {
192 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
194 $discussion = array_pop($discussions);
196 // try to recover by creating initial discussion - MDL-16262
197 $discussion = new stdClass();
198 $discussion->course = $forum->course;
199 $discussion->forum = $forum->id;
200 $discussion->name = $forum->name;
201 $discussion->assessed = $forum->assessed;
202 $discussion->message = $forum->intro;
203 $discussion->messageformat = $forum->introformat;
204 $discussion->messagetrust = true;
205 $discussion->mailnow = false;
206 $discussion->groupid = -1;
210 forum_add_discussion($discussion, null, $message);
212 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
213 print_error('cannotadd', 'forum');
216 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
217 print_error('cannotfindfirstpost', 'forum');
220 $cm = get_coursemodule_from_instance('forum', $forum->id);
221 $modcontext = context_module::instance($cm->id, MUST_EXIST);
223 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
224 $post->subject = $forum->name;
225 $post->message = $forum->intro;
226 $post->messageformat = $forum->introformat;
227 $post->messagetrust = trusttext_trusted($modcontext);
228 $post->modified = $forum->timemodified;
229 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
231 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
232 // Ugly hack - we need to copy the files somehow.
233 $options = array('subdirs'=>true); // Use the same options as intro field!
234 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
237 $DB->update_record('forum_posts', $post);
238 $discussion->name = $forum->name;
239 $DB->update_record('forum_discussions', $discussion);
242 $DB->update_record('forum', $forum);
244 $modcontext = context_module::instance($forum->coursemodule);
245 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
246 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
247 foreach ($users as $user) {
248 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
252 forum_grade_item_update($forum);
254 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
255 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
262 * Given an ID of an instance of this module,
263 * this function will permanently delete the instance
264 * and any data that depends on it.
267 * @param int $id forum instance id
268 * @return bool success
270 function forum_delete_instance($id) {
273 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
276 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
279 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
283 $context = context_module::instance($cm->id);
285 // now get rid of all files
286 $fs = get_file_storage();
287 $fs->delete_area_files($context->id);
291 \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
293 // Delete digest and subscription preferences.
294 $DB->delete_records('forum_digests', array('forum' => $forum->id));
295 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
296 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
298 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
299 foreach ($discussions as $discussion) {
300 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
306 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
308 forum_grade_item_delete($forum);
310 // We must delete the module record after we delete the grade item.
311 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
320 * Indicates API features that the forum supports.
322 * @uses FEATURE_GROUPS
323 * @uses FEATURE_GROUPINGS
324 * @uses FEATURE_MOD_INTRO
325 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
326 * @uses FEATURE_COMPLETION_HAS_RULES
327 * @uses FEATURE_GRADE_HAS_GRADE
328 * @uses FEATURE_GRADE_OUTCOMES
329 * @param string $feature
330 * @return mixed True if yes (some features may use other values)
332 function forum_supports($feature) {
334 case FEATURE_GROUPS: return true;
335 case FEATURE_GROUPINGS: return true;
336 case FEATURE_MOD_INTRO: return true;
337 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
338 case FEATURE_COMPLETION_HAS_RULES: return true;
339 case FEATURE_GRADE_HAS_GRADE: return true;
340 case FEATURE_GRADE_OUTCOMES: return true;
341 case FEATURE_RATE: return true;
342 case FEATURE_BACKUP_MOODLE2: return true;
343 case FEATURE_SHOW_DESCRIPTION: return true;
344 case FEATURE_PLAGIARISM: return true;
346 default: return null;
352 * Obtains the automatic completion state for this forum based on any conditions
357 * @param object $course Course
358 * @param object $cm Course-module
359 * @param int $userid User ID
360 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
361 * @return bool True if completed, false if not. (If no conditions, then return
362 * value depends on comparison type)
364 function forum_get_completion_state($course,$cm,$userid,$type) {
368 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
369 throw new Exception("Can't find forum {$cm->instance}");
372 $result=$type; // Default return value
374 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
380 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
382 fp.userid=:userid AND fd.forum=:forumid";
384 if ($forum->completiondiscussions) {
385 $value = $forum->completiondiscussions <=
386 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
387 if ($type == COMPLETION_AND) {
388 $result = $result && $value;
390 $result = $result || $value;
393 if ($forum->completionreplies) {
394 $value = $forum->completionreplies <=
395 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
396 if ($type==COMPLETION_AND) {
397 $result = $result && $value;
399 $result = $result || $value;
402 if ($forum->completionposts) {
403 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
404 if ($type == COMPLETION_AND) {
405 $result = $result && $value;
407 $result = $result || $value;
415 * Create a message-id string to use in the custom headers of forum notification emails
417 * message-id is used by email clients to identify emails and to nest conversations
419 * @param int $postid The ID of the forum post we are notifying the user about
420 * @param int $usertoid The ID of the user being notified
421 * @return string A unique message-id
423 function forum_get_email_message_id($postid, $usertoid) {
424 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
429 * @param object $course
430 * @param object $user
431 * @param object $mod TODO this is not used in this function, refactor
432 * @param object $forum
433 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
435 function forum_user_outline($course, $user, $mod, $forum) {
437 require_once("$CFG->libdir/gradelib.php");
438 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
439 if (empty($grades->items[0]->grades)) {
442 $grade = reset($grades->items[0]->grades);
445 $count = forum_count_user_posts($forum->id, $user->id);
447 if ($count && $count->postcount > 0) {
448 $result = new stdClass();
449 $result->info = get_string("numposts", "forum", $count->postcount);
450 $result->time = $count->lastpost;
452 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
453 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
455 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
460 $result = new stdClass();
461 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
462 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
464 $result->info = get_string('grade') . ': ' . get_string('hidden', 'grades');
467 //datesubmitted == time created. dategraded == time modified or time overridden
468 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
469 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
470 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
471 $result->time = $grade->dategraded;
473 $result->time = $grade->datesubmitted;
485 * @param object $coure
486 * @param object $user
488 * @param object $forum
490 function forum_user_complete($course, $user, $mod, $forum) {
491 global $CFG,$USER, $OUTPUT;
492 require_once("$CFG->libdir/gradelib.php");
494 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
495 if (!empty($grades->items[0]->grades)) {
496 $grade = reset($grades->items[0]->grades);
497 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
498 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
499 if ($grade->str_feedback) {
500 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
503 echo $OUTPUT->container(get_string('grade') . ': ' . get_string('hidden', 'grades'));
507 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
509 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
510 print_error('invalidcoursemodule');
512 $context = context_module::instance($cm->id);
513 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
514 $posts = array_filter($posts, function($post) use ($discussions) {
515 return isset($discussions[$post->discussion]);
517 $entityfactory = mod_forum\local\container::get_entity_factory();
518 $rendererfactory = mod_forum\local\container::get_renderer_factory();
519 $postrenderer = $rendererfactory->get_posts_renderer();
521 echo $postrenderer->render(
523 [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
524 array_map(function($discussion) use ($entityfactory) {
525 return $entityfactory->get_discussion_from_stdclass($discussion);
527 array_map(function($post) use ($entityfactory) {
528 return $entityfactory->get_post_from_stdclass($post);
532 echo "<p>".get_string("noposts", "forum")."</p>";
537 * Filters the forum discussions according to groups membership and config.
539 * @deprecated since 3.3
540 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
541 * @since Moodle 2.8, 2.7.1, 2.6.4
542 * @param array $discussions Discussions with new posts array
543 * @return array Forums with the number of new posts
545 function forum_filter_user_groups_discussions($discussions) {
547 debugging('The function forum_filter_user_groups_discussions() is now deprecated.', DEBUG_DEVELOPER);
549 // Group the remaining discussions posts by their forumid.
550 $filteredforums = array();
552 // Discard not visible groups.
553 foreach ($discussions as $discussion) {
555 // Course data is already cached.
556 $instances = get_fast_modinfo($discussion->course)->get_instances();
557 $forum = $instances['forum'][$discussion->forum];
559 // Continue if the user should not see this discussion.
560 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
564 // Grouping results by forum.
565 if (empty($filteredforums[$forum->instance])) {
566 $filteredforums[$forum->instance] = new stdClass();
567 $filteredforums[$forum->instance]->id = $forum->id;
568 $filteredforums[$forum->instance]->count = 0;
570 $filteredforums[$forum->instance]->count += $discussion->count;
574 return $filteredforums;
578 * Returns whether the discussion group is visible by the current user or not.
580 * @since Moodle 2.8, 2.7.1, 2.6.4
581 * @param cm_info $cm The discussion course module
582 * @param int $discussiongroupid The discussion groupid
585 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
587 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
595 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
596 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
604 * @deprecated since 3.3
605 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
609 * @param array $courses
610 * @param array $htmlarray
612 function forum_print_overview($courses,&$htmlarray) {
613 global $USER, $CFG, $DB, $SESSION;
615 debugging('The function forum_print_overview() is now deprecated.', DEBUG_DEVELOPER);
617 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
621 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
625 // Courses to search for new posts
626 $coursessqls = array();
628 foreach ($courses as $course) {
630 // If the user has never entered into the course all posts are pending
631 if ($course->lastaccess == 0) {
632 $coursessqls[] = '(d.course = ?)';
633 $params[] = $course->id;
635 // Only posts created after the course last access
637 $coursessqls[] = '(d.course = ? AND p.created > ?)';
638 $params[] = $course->id;
639 $params[] = $course->lastaccess;
642 $params[] = $USER->id;
643 $coursessql = implode(' OR ', $coursessqls);
645 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
646 .'FROM {forum_discussions} d '
647 .'JOIN {forum_posts} p ON p.discussion = d.id '
648 ."WHERE ($coursessql) "
649 .'AND p.deleted <> 1 '
650 .'AND p.userid != ? '
651 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
652 .'GROUP BY d.id, d.forum, d.course, d.groupid '
653 .'ORDER BY d.course, d.forum';
658 if (!$discussions = $DB->get_records_sql($sql, $params)) {
659 $discussions = array();
662 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
664 // also get all forum tracking stuff ONCE.
665 $trackingforums = array();
666 foreach ($forums as $forum) {
667 if (forum_tp_can_track_forums($forum)) {
668 $trackingforums[$forum->id] = $forum;
672 if (count($trackingforums) > 0) {
673 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
674 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
675 ' FROM {forum_posts} p '.
676 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
677 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE p.deleted <> 1 AND (';
678 $params = array($USER->id);
680 foreach ($trackingforums as $track) {
681 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
682 $params[] = $track->id;
683 if (isset($SESSION->currentgroup[$track->course])) {
684 $groupid = $SESSION->currentgroup[$track->course];
687 $groupids = groups_get_all_groups($track->course, $USER->id);
690 $groupid = key($groupids);
691 $SESSION->currentgroup[$track->course] = $groupid;
697 $params[] = $groupid;
699 $sql = substr($sql,0,-3); // take off the last OR
700 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
701 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
702 $sql .= 'GROUP BY d.forum,d.course';
703 $params[] = $cutoffdate;
707 if (!$unread = $DB->get_records_sql($sql, $params)) {
714 if (empty($unread) and empty($forumsnewposts)) {
718 $strforum = get_string('modulename','forum');
720 foreach ($forums as $forum) {
725 // either we have something from logs, or trackposts, or nothing.
726 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
727 $count = $forumsnewposts[$forum->id]->count;
729 if (array_key_exists($forum->id,$unread)) {
730 $thisunread = $unread[$forum->id]->count;
733 if ($count > 0 || $thisunread > 0) {
734 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
735 $forum->name.'</a></div>';
736 $str .= '<div class="info"><span class="postsincelogin">';
737 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
738 if (!empty($showunread)) {
739 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
741 $str .= '</div></div>';
744 if (!array_key_exists($forum->course,$htmlarray)) {
745 $htmlarray[$forum->course] = array();
747 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
748 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
750 $htmlarray[$forum->course]['forum'] .= $str;
756 * Given a course and a date, prints a summary of all the new
757 * messages posted in the course since that date
762 * @uses CONTEXT_MODULE
763 * @uses VISIBLEGROUPS
764 * @param object $course
765 * @param bool $viewfullnames capability
766 * @param int $timestart
767 * @return bool success
769 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
770 global $CFG, $USER, $DB, $OUTPUT;
772 // do not use log table if possible, it may be huge and is expensive to join with other tables
774 $allnamefields = user_picture::fields('u', null, 'duserid');
775 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
776 d.timestart, d.timeend, $allnamefields
778 JOIN {forum_discussions} d ON d.id = p.discussion
779 JOIN {forum} f ON f.id = d.forum
780 JOIN {user} u ON u.id = p.userid
781 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
782 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
786 $modinfo = get_fast_modinfo($course);
788 $groupmodes = array();
791 $strftimerecent = get_string('strftimerecent');
793 $printposts = array();
794 foreach ($posts as $post) {
795 if (!isset($modinfo->instances['forum'][$post->forum])) {
799 $cm = $modinfo->instances['forum'][$post->forum];
800 if (!$cm->uservisible) {
803 $context = context_module::instance($cm->id);
805 if (!has_capability('mod/forum:viewdiscussion', $context)) {
809 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
810 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
811 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
816 // Check that the user can see the discussion.
817 if (forum_is_user_group_discussion($cm, $post->groupid)) {
818 $printposts[] = $post;
828 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
829 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
831 foreach ($printposts as $post) {
832 $subjectclass = empty($post->parent) ? ' bold' : '';
833 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
835 $list .= html_writer::start_tag('li');
836 $list .= html_writer::start_div('head');
837 $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date');
838 if (!$authorhidden) {
839 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
841 $list .= html_writer::end_div(); // Head.
843 $list .= html_writer::start_div('info' . $subjectclass);
844 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
845 if (!empty($post->parent)) {
846 $discussionurl->param('parent', $post->parent);
847 $discussionurl->set_anchor('p'. $post->id);
849 $post->subject = break_up_long_words(format_string($post->subject, true));
850 $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']);
851 $list .= html_writer::end_div(); // Info.
852 $list .= html_writer::end_tag('li');
855 $list .= html_writer::end_tag('ul');
862 * Return grade for given user or all users.
866 * @param object $forum
867 * @param int $userid optional user id, 0 means all users
868 * @return array array of grades, false if none
870 function forum_get_user_grades($forum, $userid = 0) {
873 require_once($CFG->dirroot.'/rating/lib.php');
875 $ratingoptions = new stdClass;
876 $ratingoptions->component = 'mod_forum';
877 $ratingoptions->ratingarea = 'post';
879 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
880 $ratingoptions->modulename = 'forum';
881 $ratingoptions->moduleid = $forum->id;
882 $ratingoptions->userid = $userid;
883 $ratingoptions->aggregationmethod = $forum->assessed;
884 $ratingoptions->scaleid = $forum->scale;
885 $ratingoptions->itemtable = 'forum_posts';
886 $ratingoptions->itemtableusercolumn = 'userid';
888 $rm = new rating_manager();
889 return $rm->get_user_grades($ratingoptions);
893 * Update activity grades
896 * @param object $forum
897 * @param int $userid specific user only, 0 means all
898 * @param boolean $nullifnone return null if grade does not exist
901 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
903 require_once($CFG->libdir.'/gradelib.php');
905 if (!$forum->assessed) {
906 forum_grade_item_update($forum);
908 } else if ($grades = forum_get_user_grades($forum, $userid)) {
909 forum_grade_item_update($forum, $grades);
911 } else if ($userid and $nullifnone) {
912 $grade = new stdClass();
913 $grade->userid = $userid;
914 $grade->rawgrade = NULL;
915 forum_grade_item_update($forum, $grade);
918 forum_grade_item_update($forum);
923 * Create/update grade item for given forum
926 * @uses GRADE_TYPE_NONE
927 * @uses GRADE_TYPE_VALUE
928 * @uses GRADE_TYPE_SCALE
929 * @param stdClass $forum Forum object with extra cmidnumber
930 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
931 * @return int 0 if ok
933 function forum_grade_item_update($forum, $grades=NULL) {
935 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
936 require_once($CFG->libdir.'/gradelib.php');
939 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
941 if (!$forum->assessed or $forum->scale == 0) {
942 $params['gradetype'] = GRADE_TYPE_NONE;
944 } else if ($forum->scale > 0) {
945 $params['gradetype'] = GRADE_TYPE_VALUE;
946 $params['grademax'] = $forum->scale;
947 $params['grademin'] = 0;
949 } else if ($forum->scale < 0) {
950 $params['gradetype'] = GRADE_TYPE_SCALE;
951 $params['scaleid'] = -$forum->scale;
954 if ($grades === 'reset') {
955 $params['reset'] = true;
959 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
963 * Delete grade item for given forum
966 * @param stdClass $forum Forum object
969 function forum_grade_item_delete($forum) {
971 require_once($CFG->libdir.'/gradelib.php');
973 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
978 * This function returns if a scale is being used by one forum
981 * @param int $forumid
982 * @param int $scaleid negative number
985 function forum_scale_used ($forumid,$scaleid) {
989 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
991 if (!empty($rec) && !empty($scaleid)) {
999 * Checks if scale is being used by any instance of forum
1001 * This is used to find out if scale used anywhere
1004 * @param $scaleid int
1005 * @return boolean True if the scale is used by any forum
1007 function forum_scale_used_anywhere($scaleid) {
1009 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1016 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1019 * Gets a post with all info ready for forum_print_post
1020 * Most of these joins are just to get the forum id
1024 * @param int $postid
1025 * @return mixed array of posts or false
1027 function forum_get_post_full($postid) {
1030 $allnames = get_all_user_name_fields(true, 'u');
1031 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1032 FROM {forum_posts} p
1033 JOIN {forum_discussions} d ON p.discussion = d.id
1034 LEFT JOIN {user} u ON p.userid = u.id
1035 WHERE p.id = ?", array($postid));
1039 * Gets all posts in discussion including top parent.
1044 * @param int $discussionid
1045 * @param string $sort
1046 * @param bool $tracking does user track the forum?
1047 * @return array of posts
1049 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1050 global $CFG, $DB, $USER;
1057 $tr_sel = ", fr.id AS postread";
1058 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1059 $params[] = $USER->id;
1062 $allnames = get_all_user_name_fields(true, 'u');
1063 $params[] = $discussionid;
1064 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1065 FROM {forum_posts} p
1066 LEFT JOIN {user} u ON p.userid = u.id
1068 WHERE p.discussion = ?
1069 ORDER BY $sort", $params)) {
1073 foreach ($posts as $pid=>$p) {
1075 if (forum_tp_is_post_old($p)) {
1076 $posts[$pid]->postread = true;
1082 if (!isset($posts[$p->parent])) {
1083 continue; // parent does not exist??
1085 if (!isset($posts[$p->parent]->children)) {
1086 $posts[$p->parent]->children = array();
1088 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1091 // Start with the last child of the first post.
1092 $post = &$posts[reset($posts)->id];
1095 while (!$lastpost) {
1096 if (!isset($post->children)) {
1097 $post->lastpost = true;
1100 // Go to the last child of this post.
1101 $post = &$posts[end($post->children)->id];
1109 * An array of forum objects that the user is allowed to read/search through.
1114 * @param int $userid
1115 * @param int $courseid if 0, we look for forums throughout the whole site.
1116 * @return array of forum objects, or false if no matches
1117 * Forum objects have the following attributes:
1118 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1119 * viewhiddentimedposts
1121 function forum_get_readable_forums($userid, $courseid=0) {
1123 global $CFG, $DB, $USER;
1124 require_once($CFG->dirroot.'/course/lib.php');
1126 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1127 print_error('notinstalled', 'forum');
1131 $courses = $DB->get_records('course', array('id' => $courseid));
1133 // If no course is specified, then the user can see SITE + his courses.
1134 $courses1 = $DB->get_records('course', array('id' => SITEID));
1135 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1136 $courses = array_merge($courses1, $courses2);
1142 $readableforums = array();
1144 foreach ($courses as $course) {
1146 $modinfo = get_fast_modinfo($course);
1148 if (empty($modinfo->instances['forum'])) {
1153 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1155 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1156 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1159 $context = context_module::instance($cm->id);
1160 $forum = $courseforums[$forumid];
1161 $forum->context = $context;
1164 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1169 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1171 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1172 $forum->onlygroups[] = -1;
1175 /// hidden timed discussions
1176 $forum->viewhiddentimedposts = true;
1177 if (!empty($CFG->forum_enabletimedposts)) {
1178 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1179 $forum->viewhiddentimedposts = false;
1184 if ($forum->type == 'qanda'
1185 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1187 // We need to check whether the user has posted in the qanda forum.
1188 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1189 // the user is allowed to see in this forum.
1190 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1191 foreach ($discussionspostedin as $d) {
1192 $forum->onlydiscussions[] = $d->id;
1197 $readableforums[$forum->id] = $forum;
1202 } // End foreach $courses
1204 return $readableforums;
1208 * Returns a list of posts found using an array of search terms.
1213 * @param array $searchterms array of search terms, e.g. word +word -word
1214 * @param int $courseid if 0, we search through the whole site
1215 * @param int $limitfrom
1216 * @param int $limitnum
1217 * @param int &$totalcount
1218 * @param string $extrasql
1219 * @return array|bool Array of posts found or false
1221 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
1222 &$totalcount, $extrasql='') {
1223 global $CFG, $DB, $USER;
1224 require_once($CFG->libdir.'/searchlib.php');
1226 $forums = forum_get_readable_forums($USER->id, $courseid);
1228 if (count($forums) == 0) {
1233 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1235 $fullaccess = array();
1239 foreach ($forums as $forumid => $forum) {
1242 if (!$forum->viewhiddentimedposts) {
1243 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1244 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1248 $context = $forum->context;
1250 if ($forum->type == 'qanda'
1251 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1252 if (!empty($forum->onlydiscussions)) {
1253 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
1254 $params = array_merge($params, $discussionid_params);
1255 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1257 $select[] = "p.parent = 0";
1261 if (!empty($forum->onlygroups)) {
1262 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
1263 $params = array_merge($params, $groupid_params);
1264 $select[] = "d.groupid $groupid_sql";
1268 $selects = implode(" AND ", $select);
1269 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1270 $params['forum'.$forumid] = $forumid;
1272 $fullaccess[] = $forumid;
1277 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
1278 $params = array_merge($params, $fullid_params);
1279 $where[] = "(d.forum $fullid_sql)";
1282 $selectdiscussion = "(".implode(" OR ", $where).")";
1284 $messagesearch = '';
1287 // Need to concat these back together for parser to work.
1288 foreach($searchterms as $searchterm){
1289 if ($searchstring != '') {
1290 $searchstring .= ' ';
1292 $searchstring .= $searchterm;
1295 // We need to allow quoted strings for the search. The quotes *should* be stripped
1296 // by the parser, but this should be examined carefully for security implications.
1297 $searchstring = str_replace("\\\"","\"",$searchstring);
1298 $parser = new search_parser();
1299 $lexer = new search_lexer($parser);
1301 if ($lexer->parse($searchstring)) {
1302 $parsearray = $parser->get_parsed_array();
1307 foreach ($parsearray as $token) {
1308 if ($token->getType() == TOKEN_TAGS) {
1309 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
1310 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1311 if ($tagfieldcount > 10) {
1314 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
1315 ON p.id = ti_$tagfieldcount.itemid
1316 AND ti_$tagfieldcount.component = 'mod_forum'
1317 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
1318 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1319 $tagfields[] = "t_$tagfieldcount.rawname";
1324 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1325 'p.userid', 'u.id', 'u.firstname',
1326 'u.lastname', 'p.modified', 'd.forum',
1328 $params = array_merge($params, $msparams);
1331 $fromsql = "{forum_posts} p
1332 INNER JOIN {forum_discussions} d ON d.id = p.discussion
1333 INNER JOIN {user} u ON u.id = p.userid $tagjoins";
1335 $selectsql = " $messagesearch
1336 AND p.discussion = d.id
1338 AND $selectdiscussion
1341 $countsql = "SELECT COUNT(*)
1345 $allnames = get_all_user_name_fields(true, 'u');
1346 $searchsql = "SELECT p.*,
1354 ORDER BY p.modified DESC";
1356 $totalcount = $DB->count_records_sql($countsql, $params);
1358 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
1362 * Get all the posts for a user in a forum suitable for forum_print_post
1366 * @uses CONTEXT_MODULE
1369 function forum_get_user_posts($forumid, $userid) {
1373 $params = array($forumid, $userid);
1375 if (!empty($CFG->forum_enabletimedposts)) {
1376 $cm = get_coursemodule_from_instance('forum', $forumid);
1377 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1379 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1385 $allnames = get_all_user_name_fields(true, 'u');
1386 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1388 JOIN {forum_discussions} d ON d.forum = f.id
1389 JOIN {forum_posts} p ON p.discussion = d.id
1390 JOIN {user} u ON u.id = p.userid
1394 ORDER BY p.modified ASC", $params);
1398 * Get all the discussions user participated in
1402 * @uses CONTEXT_MODULE
1403 * @param int $forumid
1404 * @param int $userid
1405 * @return array Array or false
1407 function forum_get_user_involved_discussions($forumid, $userid) {
1411 $params = array($forumid, $userid);
1412 if (!empty($CFG->forum_enabletimedposts)) {
1413 $cm = get_coursemodule_from_instance('forum', $forumid);
1414 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1416 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1422 return $DB->get_records_sql("SELECT DISTINCT d.*
1424 JOIN {forum_discussions} d ON d.forum = f.id
1425 JOIN {forum_posts} p ON p.discussion = d.id
1428 $timedsql", $params);
1432 * Get all the posts for a user in a forum suitable for forum_print_post
1436 * @param int $forumid
1437 * @param int $userid
1438 * @return array of counts or false
1440 function forum_count_user_posts($forumid, $userid) {
1444 $params = array($forumid, $userid);
1445 if (!empty($CFG->forum_enabletimedposts)) {
1446 $cm = get_coursemodule_from_instance('forum', $forumid);
1447 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
1449 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1455 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1457 JOIN {forum_discussions} d ON d.forum = f.id
1458 JOIN {forum_posts} p ON p.discussion = d.id
1459 JOIN {user} u ON u.id = p.userid
1462 $timedsql", $params);
1466 * Given a log entry, return the forum post details for it.
1470 * @param object $log
1471 * @return array|null
1473 function forum_get_post_from_log($log) {
1476 $allnames = get_all_user_name_fields(true, 'u');
1477 if ($log->action == "add post") {
1479 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1480 FROM {forum_discussions} d,
1485 AND d.id = p.discussion
1487 AND u.deleted <> '1'
1488 AND f.id = d.forum", array($log->info));
1491 } else if ($log->action == "add discussion") {
1493 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
1494 FROM {forum_discussions} d,
1499 AND d.firstpost = p.id
1501 AND u.deleted <> '1'
1502 AND f.id = d.forum", array($log->info));
1508 * Given a discussion id, return the first post from the discussion
1512 * @param int $dicsussionid
1515 function forum_get_firstpost_from_discussion($discussionid) {
1518 return $DB->get_record_sql("SELECT p.*
1519 FROM {forum_discussions} d,
1522 AND d.firstpost = p.id ", array($discussionid));
1526 * Returns an array of counts of replies to each discussion
1530 * @param int $forumid
1531 * @param string $forumsort
1534 * @param int $perpage
1537 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
1543 } else if ($page != -1) {
1544 $limitfrom = $page*$perpage;
1545 $limitnum = $perpage;
1551 if ($forumsort == "") {
1556 $orderby = "ORDER BY $forumsort";
1557 $groupby = ", ".strtolower($forumsort);
1558 $groupby = str_replace('desc', '', $groupby);
1559 $groupby = str_replace('asc', '', $groupby);
1562 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1563 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
1564 FROM {forum_posts} p
1565 JOIN {forum_discussions} d ON p.discussion = d.id
1566 WHERE p.parent > 0 AND d.forum = ?
1567 GROUP BY p.discussion";
1568 return $DB->get_records_sql($sql, array($forumid));
1571 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
1572 FROM {forum_posts} p
1573 JOIN {forum_discussions} d ON p.discussion = d.id
1575 GROUP BY p.discussion $groupby $orderby";
1576 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
1584 * @staticvar array $cache
1585 * @param object $forum
1587 * @param object $course
1590 function forum_count_discussions($forum, $cm, $course) {
1591 global $CFG, $DB, $USER;
1593 static $cache = array();
1595 $now = floor(time() / 60) * 60; // DB Cache Friendly.
1597 $params = array($course->id);
1599 if (!isset($cache[$course->id])) {
1600 if (!empty($CFG->forum_enabletimedposts)) {
1601 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1608 $sql = "SELECT f.id, COUNT(d.id) as dcount
1610 JOIN {forum_discussions} d ON d.forum = f.id
1615 if ($counts = $DB->get_records_sql($sql, $params)) {
1616 foreach ($counts as $count) {
1617 $counts[$count->id] = $count->dcount;
1619 $cache[$course->id] = $counts;
1621 $cache[$course->id] = array();
1625 if (empty($cache[$course->id][$forum->id])) {
1629 $groupmode = groups_get_activity_groupmode($cm, $course);
1631 if ($groupmode != SEPARATEGROUPS) {
1632 return $cache[$course->id][$forum->id];
1635 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
1636 return $cache[$course->id][$forum->id];
1639 require_once($CFG->dirroot.'/course/lib.php');
1641 $modinfo = get_fast_modinfo($course);
1643 $mygroups = $modinfo->get_groups($cm->groupingid);
1645 // add all groups posts
1648 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1649 $params[] = $forum->id;
1651 if (!empty($CFG->forum_enabletimedposts)) {
1652 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
1659 $sql = "SELECT COUNT(d.id)
1660 FROM {forum_discussions} d
1661 WHERE d.groupid $mygroups_sql AND d.forum = ?
1664 return $DB->get_field_sql($sql, $params);
1668 * Get all discussions in a forum
1673 * @uses CONTEXT_MODULE
1674 * @uses VISIBLEGROUPS
1676 * @param string $forumsort
1677 * @param bool $fullpost
1678 * @param int $unused
1680 * @param bool $userlastmodified
1682 * @param int $perpage
1683 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1684 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
1685 * @param int $updatedsince retrieve only discussions updated since the given time
1688 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
1689 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
1690 $updatedsince = 0) {
1691 global $CFG, $DB, $USER;
1695 $now = floor(time() / 60) * 60;
1696 $params = array($cm->instance);
1698 $modcontext = context_module::instance($cm->id);
1700 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1704 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
1706 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1707 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1711 $timelimit .= " OR d.userid = ?";
1712 $params[] = $USER->id;
1721 } else if ($page != -1) {
1722 $limitfrom = $page*$perpage;
1723 $limitnum = $perpage;
1729 $groupmode = groups_get_activity_groupmode($cm);
1733 if (empty($modcontext)) {
1734 $modcontext = context_module::instance($cm->id);
1737 // Special case, we received a groupid to override currentgroup.
1739 $course = get_course($cm->course);
1740 if (!groups_group_visible($groupid, $course, $cm)) {
1741 // User doesn't belong to this group, return nothing.
1744 $currentgroup = $groupid;
1745 } else if ($groupid === -1) {
1746 $currentgroup = groups_get_activity_group($cm);
1748 // Get discussions for all groups current user can see.
1749 $currentgroup = null;
1752 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1753 if ($currentgroup) {
1754 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1755 $params[] = $currentgroup;
1763 // Get discussions for all groups current user can see.
1764 if ($currentgroup === null) {
1765 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
1766 if (empty($mygroups)) {
1767 $groupselect = "AND d.groupid = -1";
1769 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1770 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1771 $params = array_merge($params, $inparamsgroups);
1773 } else if ($currentgroup) {
1774 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1775 $params[] = $currentgroup;
1777 $groupselect = "AND d.groupid = -1";
1783 if (empty($forumsort)) {
1784 $forumsort = forum_get_default_sort_order();
1786 if (empty($fullpost)) {
1787 $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
1792 if (empty($userlastmodified)) { // We don't need to know this
1796 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
1797 um.imagealt AS umimagealt';
1798 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
1801 $updatedsincesql = '';
1802 if (!empty($updatedsince)) {
1803 $updatedsincesql = 'AND d.timemodified > ?';
1804 $params[] = $updatedsince;
1806 $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
1807 " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned";
1809 $allnames = get_all_user_name_fields(true, 'u');
1810 $sql = "SELECT $postdata, $discussionfields,
1811 $allnames, u.email, u.picture, u.imagealt $umfields
1812 FROM {forum_discussions} d
1813 JOIN {forum_posts} p ON p.discussion = d.id
1814 JOIN {user} u ON p.userid = u.id
1816 WHERE d.forum = ? AND p.parent = 0
1817 $timelimit $groupselect $updatedsincesql
1818 ORDER BY $forumsort, d.id DESC";
1820 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1824 * Gets the neighbours (previous and next) of a discussion.
1826 * The calculation is based on the timemodified when time modified or time created is identical
1827 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
1829 * For blog-style forums, the calculation is based on the original creation time of the
1832 * Please note that this does not check whether or not the discussion passed is accessible
1833 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1834 * the returned neighbours are checked and are accessible to the current user.
1836 * @param object $cm The CM record.
1837 * @param object $discussion The discussion record.
1838 * @param object $forum The forum instance record.
1839 * @return array That always contains the keys 'prev' and 'next'. When there is a result
1840 * they contain the record with minimal information such as 'id' and 'name'.
1841 * When the neighbour is not found the value is false.
1843 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
1844 global $CFG, $DB, $USER;
1846 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
1847 throw new coding_exception('Discussion is not part of the same forum.');
1850 $neighbours = array('prev' => false, 'next' => false);
1851 $now = floor(time() / 60) * 60;
1854 $modcontext = context_module::instance($cm->id);
1855 $groupmode = groups_get_activity_groupmode($cm);
1856 $currentgroup = groups_get_activity_group($cm);
1858 // Users must fulfill timed posts.
1860 if (!empty($CFG->forum_enabletimedposts)) {
1861 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1862 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1863 $params['tltimestart'] = $now;
1864 $params['tltimeend'] = $now;
1866 $timelimit .= ' OR d.userid = :tluserid';
1867 $params['tluserid'] = $USER->id;
1873 // Limiting to posts accessible according to groups.
1876 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
1877 if ($currentgroup) {
1878 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1879 $params['groupid'] = $currentgroup;
1882 if ($currentgroup) {
1883 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1884 $params['groupid'] = $currentgroup;
1886 $groupselect = 'AND d.groupid = -1';
1891 $params['forumid'] = $cm->instance;
1892 $params['discid1'] = $discussion->id;
1893 $params['discid2'] = $discussion->id;
1894 $params['discid3'] = $discussion->id;
1895 $params['discid4'] = $discussion->id;
1896 $params['disctimecompare1'] = $discussion->timemodified;
1897 $params['disctimecompare2'] = $discussion->timemodified;
1898 $params['pinnedstate1'] = (int) $discussion->pinned;
1899 $params['pinnedstate2'] = (int) $discussion->pinned;
1900 $params['pinnedstate3'] = (int) $discussion->pinned;
1901 $params['pinnedstate4'] = (int) $discussion->pinned;
1903 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1904 FROM {forum_discussions} d
1905 JOIN {forum_posts} p ON d.firstpost = p.id
1906 WHERE d.forum = :forumid
1907 AND d.id <> :discid1
1910 $comparefield = "d.timemodified";
1911 $comparevalue = ":disctimecompare1";
1912 $comparevalue2 = ":disctimecompare2";
1913 if (!empty($CFG->forum_enabletimedposts)) {
1914 // Here we need to take into account the release time (timestart)
1915 // if one is set, of the neighbouring posts and compare it to the
1916 // timestart or timemodified of *this* post depending on if the
1917 // release date of this post is in the future or not.
1918 // This stops discussions that appear later because of the
1919 // timestart value from being buried under discussions that were
1921 $comparefield = "CASE WHEN d.timemodified < d.timestart
1922 THEN d.timestart ELSE d.timemodified END";
1923 if ($discussion->timemodified < $discussion->timestart) {
1924 // Normally we would just use the timemodified for sorting
1925 // discussion posts. However, when timed discussions are enabled,
1926 // then posts need to be sorted base on the later of timemodified
1927 // or the release date of the post (timestart).
1928 $params['disctimecompare1'] = $discussion->timestart;
1929 $params['disctimecompare2'] = $discussion->timestart;
1932 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1933 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
1935 if ($forum->type === 'blog') {
1936 $subselect = "SELECT pp.created
1937 FROM {forum_discussions} dd
1938 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
1940 $subselectwhere1 = " WHERE dd.id = :discid3";
1941 $subselectwhere2 = " WHERE dd.id = :discid4";
1943 $comparefield = "p.created";
1945 $sub1 = $subselect.$subselectwhere1;
1946 $comparevalue = "($sub1)";
1948 $sub2 = $subselect.$subselectwhere2;
1949 $comparevalue2 = "($sub2)";
1951 $orderbydesc = "d.pinned, p.created DESC";
1952 $orderbyasc = "d.pinned, p.created ASC";
1955 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1956 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1957 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1958 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
1960 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1961 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1962 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1963 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
1965 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
1966 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
1971 * Get the sql to use in the ORDER BY clause for forum discussions.
1973 * This has the ordering take timed discussion windows into account.
1975 * @param bool $desc True for DESC, False for ASC.
1976 * @param string $compare The field in the SQL to compare to normally sort by.
1977 * @param string $prefix The prefix being used for the discussion table.
1978 * @param bool $pinned sort pinned posts to the top
1981 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1984 if (!empty($prefix)) {
1988 $dir = $desc ? 'DESC' : 'ASC';
1990 if ($pinned == true) {
1991 $pinned = "{$prefix}pinned DESC,";
1996 $sort = "{$prefix}timemodified";
1997 if (!empty($CFG->forum_enabletimedposts)) {
1998 $sort = "CASE WHEN {$compare} < {$prefix}timestart
1999 THEN {$prefix}timestart
2003 return "$pinned $sort $dir";
2011 * @uses CONTEXT_MODULE
2012 * @uses VISIBLEGROUPS
2016 function forum_get_discussions_unread($cm) {
2017 global $CFG, $DB, $USER;
2019 $now = floor(time() / 60) * 60;
2020 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2023 $groupmode = groups_get_activity_groupmode($cm);
2024 $currentgroup = groups_get_activity_group($cm);
2027 $modcontext = context_module::instance($cm->id);
2029 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2030 if ($currentgroup) {
2031 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2032 $params['currentgroup'] = $currentgroup;
2038 //separate groups without access all
2039 if ($currentgroup) {
2040 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2041 $params['currentgroup'] = $currentgroup;
2043 $groupselect = "AND d.groupid = -1";
2050 if (!empty($CFG->forum_enabletimedposts)) {
2051 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2052 $params['now1'] = $now;
2053 $params['now2'] = $now;
2058 $sql = "SELECT d.id, COUNT(p.id) AS unread
2059 FROM {forum_discussions} d
2060 JOIN {forum_posts} p ON p.discussion = d.id
2061 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2062 WHERE d.forum = {$cm->instance}
2063 AND p.modified >= :cutoffdate AND r.id is NULL
2067 $params['cutoffdate'] = $cutoffdate;
2069 if ($unreads = $DB->get_records_sql($sql, $params)) {
2070 foreach ($unreads as $unread) {
2071 $unreads[$unread->id] = $unread->unread;
2083 * @uses CONEXT_MODULE
2084 * @uses VISIBLEGROUPS
2088 function forum_get_discussions_count($cm) {
2089 global $CFG, $DB, $USER;
2091 $now = floor(time() / 60) * 60;
2092 $params = array($cm->instance);
2093 $groupmode = groups_get_activity_groupmode($cm);
2094 $currentgroup = groups_get_activity_group($cm);
2097 $modcontext = context_module::instance($cm->id);
2099 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2100 if ($currentgroup) {
2101 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2102 $params[] = $currentgroup;
2108 //seprate groups without access all
2109 if ($currentgroup) {
2110 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2111 $params[] = $currentgroup;
2113 $groupselect = "AND d.groupid = -1";
2122 if (!empty($CFG->forum_enabletimedposts)) {
2124 $modcontext = context_module::instance($cm->id);
2126 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2127 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2131 $timelimit .= " OR d.userid = ?";
2132 $params[] = $USER->id;
2138 $sql = "SELECT COUNT(d.id)
2139 FROM {forum_discussions} d
2140 JOIN {forum_posts} p ON p.discussion = d.id
2141 WHERE d.forum = ? AND p.parent = 0
2142 $groupselect $timelimit";
2144 return $DB->get_field_sql($sql, $params);
2148 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2154 * @param int $courseid
2155 * @param string $type
2157 function forum_get_course_forum($courseid, $type) {
2158 // How to set up special 1-per-course forums
2159 global $CFG, $DB, $OUTPUT, $USER;
2161 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2162 // There should always only be ONE, but with the right combination of
2163 // errors there might be more. In this case, just return the oldest one (lowest ID).
2164 foreach ($forums as $forum) {
2165 return $forum; // ie the first one
2169 // Doesn't exist, so create one now.
2170 $forum = new stdClass();
2171 $forum->course = $courseid;
2172 $forum->type = "$type";
2173 if (!empty($USER->htmleditor)) {
2174 $forum->introformat = $USER->htmleditor;
2176 switch ($forum->type) {
2178 $forum->name = get_string("namenews", "forum");
2179 $forum->intro = get_string("intronews", "forum");
2180 $forum->introformat = FORMAT_HTML;
2181 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2182 $forum->assessed = 0;
2183 if ($courseid == SITEID) {
2184 $forum->name = get_string("sitenews");
2185 $forum->forcesubscribe = 0;
2189 $forum->name = get_string("namesocial", "forum");
2190 $forum->intro = get_string("introsocial", "forum");
2191 $forum->introformat = FORMAT_HTML;
2192 $forum->assessed = 0;
2193 $forum->forcesubscribe = 0;
2196 $forum->name = get_string('blogforum', 'forum');
2197 $forum->intro = get_string('introblog', 'forum');
2198 $forum->introformat = FORMAT_HTML;
2199 $forum->assessed = 0;
2200 $forum->forcesubscribe = 0;
2203 echo $OUTPUT->notification("That forum type doesn't exist!");
2208 $forum->timemodified = time();
2209 $forum->id = $DB->insert_record("forum", $forum);
2211 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2212 echo $OUTPUT->notification("Could not find forum module!!");
2215 $mod = new stdClass();
2216 $mod->course = $courseid;
2217 $mod->module = $module->id;
2218 $mod->instance = $forum->id;
2220 include_once("$CFG->dirroot/course/lib.php");
2221 if (! $mod->coursemodule = add_course_module($mod) ) {
2222 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2225 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
2226 return $DB->get_record("forum", array("id" => "$forum->id"));
2230 * Return rating related permissions
2232 * @param string $options the context id
2233 * @return array an associative array of the user's rating permissions
2235 function forum_rating_permissions($contextid, $component, $ratingarea) {
2236 $context = context::instance_by_id($contextid, MUST_EXIST);
2237 if ($component != 'mod_forum' || $ratingarea != 'post') {
2238 // We don't know about this component/ratingarea so just return null to get the
2239 // default restrictive permissions.
2243 'view' => has_capability('mod/forum:viewrating', $context),
2244 'viewany' => has_capability('mod/forum:viewanyrating', $context),
2245 'viewall' => has_capability('mod/forum:viewallratings', $context),
2246 'rate' => has_capability('mod/forum:rate', $context)
2251 * Validates a submitted rating
2252 * @param array $params submitted data
2253 * context => object the context in which the rated items exists [required]
2254 * component => The component for this module - should always be mod_forum [required]
2255 * ratingarea => object the context in which the rated items exists [required]
2257 * itemid => int the ID of the object being rated [required]
2258 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2259 * rating => int the submitted rating [required]
2260 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2261 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
2262 * @return boolean true if the rating is valid. Will throw rating_exception if not
2264 function forum_rating_validate($params) {
2267 // Check the component is mod_forum
2268 if ($params['component'] != 'mod_forum') {
2269 throw new rating_exception('invalidcomponent');
2272 // Check the ratingarea is post (the only rating area in forum)
2273 if ($params['ratingarea'] != 'post') {
2274 throw new rating_exception('invalidratingarea');
2277 // Check the rateduserid is not the current user .. you can't rate your own posts
2278 if ($params['rateduserid'] == $USER->id) {
2279 throw new rating_exception('nopermissiontorate');
2282 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2283 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
2284 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2285 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2286 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2287 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2288 $context = context_module::instance($cm->id);
2290 // Make sure the context provided is the context of the forum
2291 if ($context->id != $params['context']->id) {
2292 throw new rating_exception('invalidcontext');
2295 if ($forum->scale != $params['scaleid']) {
2296 //the scale being submitted doesnt match the one in the database
2297 throw new rating_exception('invalidscaleid');
2300 // check the item we're rating was created in the assessable time window
2301 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
2302 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
2303 throw new rating_exception('notavailable');
2307 //check that the submitted rating is valid for the scale
2310 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
2311 throw new rating_exception('invalidnum');
2315 if ($forum->scale < 0) {
2316 //its a custom scale
2317 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
2319 $scalearray = explode(',', $scalerecord->scale);
2320 if ($params['rating'] > count($scalearray)) {
2321 throw new rating_exception('invalidnum');
2324 throw new rating_exception('invalidscaleid');
2326 } else if ($params['rating'] > $forum->scale) {
2327 //if its numeric and submitted rating is above maximum
2328 throw new rating_exception('invalidnum');
2331 // Make sure groups allow this user to see the item they're rating
2332 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
2333 if (!groups_group_exists($discussion->groupid)) { // Can't find group
2334 throw new rating_exception('cannotfindgroup');//something is wrong
2337 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2338 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
2339 throw new rating_exception('notmemberofgroup');
2343 // perform some final capability checks
2344 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2345 throw new rating_exception('nopermissiontorate');
2352 * Can the current user see ratings for a given itemid?
2354 * @param array $params submitted data
2355 * contextid => int contextid [required]
2356 * component => The component for this module - should always be mod_forum [required]
2357 * ratingarea => object the context in which the rated items exists [required]
2358 * itemid => int the ID of the object being rated [required]
2359 * scaleid => int scale id [optional]
2361 * @throws coding_exception
2362 * @throws rating_exception
2364 function mod_forum_rating_can_see_item_ratings($params) {
2367 // Check the component is mod_forum.
2368 if (!isset($params['component']) || $params['component'] != 'mod_forum') {
2369 throw new rating_exception('invalidcomponent');
2372 // Check the ratingarea is post (the only rating area in forum).
2373 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
2374 throw new rating_exception('invalidratingarea');
2377 if (!isset($params['itemid'])) {
2378 throw new rating_exception('invaliditemid');
2381 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
2382 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2383 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2384 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2385 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2387 // Perform some final capability checks.
2388 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2396 * This function prints the overview of a discussion in the forum listing.
2397 * It needs some discussion information and some post information, these
2398 * happen to be combined for efficiency in the $post parameter by the function
2399 * that calls this one: forum_print_latest_discussions()
2403 * @param object $post The post object (passed by reference for speed).
2404 * @param object $forum The forum object.
2405 * @param int $group Current group.
2406 * @param string $datestring Format to use for the dates.
2407 * @param boolean $cantrack Is tracking enabled for this forum.
2408 * @param boolean $forumtracked Is the user tracking this forum.
2409 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
2410 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
2412 function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2413 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2414 $canviewhiddentimedposts = false) {
2416 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
2419 static $strmarkalldread;
2421 if (empty($modcontext)) {
2422 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2423 print_error('invalidcoursemodule');
2425 $modcontext = context_module::instance($cm->id);
2428 if (!isset($rowcount)) {
2430 $strmarkalldread = get_string('markalldread', 'forum');
2432 $rowcount = ($rowcount + 1) % 2;
2435 $post->subject = format_string($post->subject,true);
2437 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
2438 $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2439 $timedoutsidewindow = '';
2440 if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2441 $timedoutsidewindow = ' dimmed_text';
2445 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
2447 $topicclass = 'topic starter';
2448 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2449 $topicclass .= ' pinned';
2451 echo '<td class="'.$topicclass.'">';
2452 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2453 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2455 $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2456 if ($timeddiscussion && $canalwaysseetimedpost) {
2457 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2460 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
2464 $postuser = new stdClass();
2465 $postuserfields = explode(',', user_picture::fields());
2466 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
2467 $postuser->id = $post->userid;
2468 echo '<td class="author">';
2469 echo '<div class="media">';
2470 echo '<span class="pull-left">';
2471 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
2474 echo '<div class="media-body">';
2475 $fullname = fullname($postuser, $canviewfullnames);
2476 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&course='.$forum->course.'">'.$fullname.'</a>';
2482 if ($group !== -1) { // Groups are active - group is a group data object or NULL
2483 echo '<td class="picture group">';
2484 if (!empty($group->picture) and empty($group->hidepicture)) {
2485 if ($canviewparticipants && $COURSE->groupmode) {
2486 $picturelink = true;
2488 $picturelink = false;
2490 print_group_picture($group, $forum->course, false, false, $picturelink);
2491 } else if (isset($group->id)) {
2492 if ($canviewparticipants && $COURSE->groupmode) {
2493 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&group='.$group->id.'">'.$group->name.'</a>';
2501 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
2502 echo '<td class="replies">';
2503 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2504 echo $post->replies.'</a>';
2508 echo '<td class="replies">';
2509 if ($forumtracked) {
2510 if ($post->unread > 0) {
2511 echo '<span class="unread">';
2512 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2515 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2516 $forum->id.'&d='.$post->discussion.'&mark=read&return=/mod/forum/view.php&sesskey=' .
2517 sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
2520 echo '<span class="read">';
2525 echo '<span class="read">';
2533 echo '<td class="lastpost">';
2534 $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
2536 $usermodified = new stdClass();
2537 $usermodified->id = $post->usermodified;
2538 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
2540 // In QA forums we check that the user can view participants.
2541 if ($forum->type !== 'qanda' || $canviewparticipants) {
2542 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&course='.$forum->course.'">'.
2543 fullname($usermodified, $canviewfullnames).'</a><br />';
2544 $parenturl = (empty($post->lastpostid)) ? '' : '&parent='.$post->lastpostid;
2547 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
2548 userdate_htmltime($usedate, $datestring).'</a>';
2551 // is_guest should be used here as this also checks whether the user is a guest in the current course.
2552 // Guests and visitors cannot subscribe - only enrolled users.
2553 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
2554 // Discussion subscription.
2555 if (\mod_forum\subscriptions::is_subscribable($forum)) {
2556 echo '<td class="discussionsubscription">';
2557 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2567 * Return the markup for the discussion subscription toggling icon.
2569 * @param stdClass $forum The forum object.
2570 * @param int $discussionid The discussion to create an icon for.
2571 * @return string The generated markup.
2573 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
2574 global $USER, $OUTPUT, $PAGE;
2576 if ($returnurl === null && $PAGE->url) {
2577 $returnurl = $PAGE->url->out();
2581 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2582 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2583 'sesskey' => sesskey(),
2585 'd' => $discussionid,
2586 'returnurl' => $returnurl,
2590 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2593 if ($subscriptionstatus) {
2594 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2596 $output .= get_string('subscribed', 'mod_forum');
2599 return html_writer::link($subscriptionlink, $output, array(
2600 'title' => get_string('clicktounsubscribe', 'forum'),
2601 'class' => 'discussiontoggle iconsmall',
2602 'data-forumid' => $forum->id,
2603 'data-discussionid' => $discussionid,
2604 'data-includetext' => $includetext,
2608 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2610 $output .= get_string('notsubscribed', 'mod_forum');
2613 return html_writer::link($subscriptionlink, $output, array(
2614 'title' => get_string('clicktosubscribe', 'forum'),
2615 'class' => 'discussiontoggle iconsmall',
2616 'data-forumid' => $forum->id,
2617 'data-discussionid' => $discussionid,
2618 'data-includetext' => $includetext,
2624 * Return a pair of spans containing classes to allow the subscribe and
2625 * unsubscribe icons to be pre-loaded by a browser.
2627 * @return string The generated markup
2629 function forum_get_discussion_subscription_icon_preloaders() {
2631 $o .= html_writer::span(' ', 'preload-subscribe');
2632 $o .= html_writer::span(' ', 'preload-unsubscribe');
2637 * Print the drop down that allows the user to select how they want to have
2638 * the discussion displayed.
2640 * @param int $id forum id if $forumtype is 'single',
2641 * discussion id for any other forum type
2642 * @param mixed $mode forum layout mode
2643 * @param string $forumtype optional
2645 function forum_print_mode_form($id, $mode, $forumtype='') {
2647 if ($forumtype == 'single') {
2648 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
2649 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2650 $select->class = "forummode";
2652 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
2653 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
2655 echo $OUTPUT->render($select);
2660 * @param object $course
2661 * @param string $search
2664 function forum_search_form($course, $search='') {
2666 $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2667 $output = $PAGE->get_renderer('mod_forum');
2668 return $output->render($forumsearch);
2676 function forum_set_return() {
2677 global $CFG, $SESSION;
2679 if (! isset($SESSION->fromdiscussion)) {
2680 $referer = get_local_referer(false);
2681 // If the referer is NOT a login screen then save it.
2682 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
2683 $SESSION->fromdiscussion = $referer;
2691 * @param string|\moodle_url $default
2694 function forum_go_back_to($default) {
2697 if (!empty($SESSION->fromdiscussion)) {
2698 $returnto = $SESSION->fromdiscussion;
2699 unset($SESSION->fromdiscussion);
2707 * Given a discussion object that is being moved to $forumto,
2708 * this function checks all posts in that discussion
2709 * for attachments, and if any are found, these are
2710 * moved to the new forum directory.
2713 * @param object $discussion
2714 * @param int $forumfrom source forum id
2715 * @param int $forumto target forum id
2716 * @return bool success
2718 function forum_move_attachments($discussion, $forumfrom, $forumto) {
2721 $fs = get_file_storage();
2723 $newcm = get_coursemodule_from_instance('forum', $forumto);
2724 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
2726 $newcontext = context_module::instance($newcm->id);
2727 $oldcontext = context_module::instance($oldcm->id);
2729 // loop through all posts, better not use attachment flag ;-)
2730 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
2731 foreach ($posts as $post) {
2732 $fs->move_area_files_to_new_context($oldcontext->id,
2733 $newcontext->id, 'mod_forum', 'post', $post->id);
2734 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2735 $newcontext->id, 'mod_forum', 'attachment', $post->id);
2736 if ($attachmentsmoved > 0 && $post->attachment != '1') {
2737 // Weird - let's fix it
2738 $post->attachment = '1';
2739 $DB->update_record('forum_posts', $post);
2740 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2741 // Weird - let's fix it
2742 $post->attachment = '';
2743 $DB->update_record('forum_posts', $post);
2752 * Returns attachments as formated text/html optionally with separate images
2757 * @param object $post
2759 * @param string $type html/text/separateimages
2760 * @return mixed string or array of (html text withouth images and image HTML)
2762 function forum_print_attachments($post, $cm, $type) {
2763 global $CFG, $DB, $USER, $OUTPUT;
2765 if (empty($post->attachment)) {
2766 return $type !== 'separateimages' ? '' : array('', '');
2769 if (!in_array($type, array('separateimages', 'html', 'text'))) {
2770 return $type !== 'separateimages' ? '' : array('', '');
2773 if (!$context = context_module::instance($cm->id)) {
2774 return $type !== 'separateimages' ? '' : array('', '');
2776 $strattachment = get_string('attachment', 'forum');
2778 $fs = get_file_storage();
2783 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
2786 require_once($CFG->libdir.'/portfoliolib.php');
2789 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
2790 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2791 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
2794 $button = new portfolio_add_button();
2796 foreach ($files as $file) {
2797 $filename = $file->get_filename();
2798 $mimetype = $file->get_mimetype();
2799 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
2800 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2802 if ($type == 'html') {
2803 $output .= "<a href=\"$path\">$iconimage</a> ";
2804 $output .= "<a href=\"$path\">".s($filename)."</a>";
2806 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2807 $button->set_format_by_file($file);
2808 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2810 $output .= "<br />";
2812 } else if ($type == 'text') {
2813 $output .= "$strattachment ".s($filename).":\n$path\n";
2815 } else { //'returnimages'
2816 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2817 // Image attachments don't get printed as links
2818 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2820 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2821 $button->set_format_by_file($file);
2822 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2825 $output .= "<a href=\"$path\">$iconimage</a> ";
2826 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
2828 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
2829 $button->set_format_by_file($file);
2830 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2832 $output .= '<br />';
2836 if (!empty($CFG->enableplagiarism)) {
2837 require_once($CFG->libdir.'/plagiarismlib.php');
2838 $output .= plagiarism_get_links(array('userid' => $post->userid,
2841 'course' => $cm->course,
2842 'forum' => $cm->instance));
2843 $output .= '<br />';
2848 if ($type !== 'separateimages') {
2852 return array($output, $imagereturn);
2856 ////////////////////////////////////////////////////////////////////////////////
2858 ////////////////////////////////////////////////////////////////////////////////
2861 * Lists all browsable file areas
2863 * @package mod_forum
2865 * @param stdClass $course course object
2866 * @param stdClass $cm course module object
2867 * @param stdClass $context context object
2870 function forum_get_file_areas($course, $cm, $context) {
2872 'attachment' => get_string('areaattachment', 'mod_forum'),
2873 'post' => get_string('areapost', 'mod_forum'),
2878 * File browsing support for forum module.
2880 * @package mod_forum
2882 * @param stdClass $browser file browser object
2883 * @param stdClass $areas file areas
2884 * @param stdClass $course course object
2885 * @param stdClass $cm course module
2886 * @param stdClass $context context module
2887 * @param string $filearea file area
2888 * @param int $itemid item ID
2889 * @param string $filepath file path
2890 * @param string $filename file name
2891 * @return file_info instance or null if not found
2893 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2894 global $CFG, $DB, $USER;
2896 if ($context->contextlevel != CONTEXT_MODULE) {
2900 // filearea must contain a real area
2901 if (!isset($areas[$filearea])) {
2905 // Note that forum_user_can_see_post() additionally allows access for parent roles
2906 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2907 // course:managefiles, we will need to extend this.
2908 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2912 if (is_null($itemid)) {
2913 require_once($CFG->dirroot.'/mod/forum/locallib.php');
2914 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2917 static $cached = array();
2918 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2919 // is cleared between unit tests we check if this is the same session
2920 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2921 $cached = array('sesskey' => sesskey());
2924 if (isset($cached['post']) && $cached['post']->id == $itemid) {
2925 $post = $cached['post'];
2926 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2927 $cached['post'] = $post;
2932 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2933 $discussion = $cached['discussion'];
2934 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2935 $cached['discussion'] = $discussion;
2940 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2941 $forum = $cached['forum'];
2942 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2943 $cached['forum'] = $forum;
2948 $fs = get_file_storage();
2949 $filepath = is_null($filepath) ? '/' : $filepath;
2950 $filename = is_null($filename) ? '.' : $filename;
2951 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2955 // Checks to see if the user can manage files or is the owner.
2956 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2957 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2960 // Make sure groups allow this user to see this file
2961 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
2962 $groupmode = groups_get_activity_groupmode($cm, $course);
2963 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2968 // Make sure we're allowed to see it...
2969 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2973 $urlbase = $CFG->wwwroot.'/pluginfile.php';
2974 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2978 * Serves the forum attachments. Implements needed access control ;-)
2980 * @package mod_forum
2982 * @param stdClass $course course object
2983 * @param stdClass $cm course module object
2984 * @param stdClass $context context object
2985 * @param string $filearea file area
2986 * @param array $args extra arguments
2987 * @param bool $forcedownload whether or not force download
2988 * @param array $options additional options affecting the file serving
2989 * @return bool false if file not found, does not return if found - justsend the file
2991 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2994 if ($context->contextlevel != CONTEXT_MODULE) {
2998 require_course_login($course, true, $cm);
3000 $areas = forum_get_file_areas($course, $cm, $context);
3002 // filearea must contain a real area
3003 if (!isset($areas[$filearea])) {
3007 $postid = (int)array_shift($args);
3009 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
3013 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
3017 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
3021 $fs = get_file_storage();
3022 $relativepath = implode('/', $args);
3023 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
3024 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3028 // Make sure groups allow this user to see this file
3029 if ($discussion->groupid > 0) {
3030 $groupmode = groups_get_activity_groupmode($cm, $course);
3031 if ($groupmode == SEPARATEGROUPS) {
3032 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
3038 // Make sure we're allowed to see it...
3039 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3043 // finally send the file
3044 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3048 * If successful, this function returns the name of the file
3051 * @param object $post is a full post record, including course and forum
3052 * @param object $forum
3054 * @param mixed $mform
3055 * @param string $unused
3058 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
3061 if (empty($mform)) {
3065 if (empty($post->attachments)) {
3066 return true; // Nothing to do
3069 $context = context_module::instance($cm->id);
3071 $info = file_get_draft_area_info($post->attachments);
3072 $present = ($info['filecount']>0) ? '1' : '';
3073 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
3074 mod_forum_post_form::attachment_options($forum));
3076 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
3082 * Add a new post in an existing discussion.
3084 * @param stdClass $post The post data
3085 * @param mixed $mform The submitted form
3086 * @param string $unused
3089 function forum_add_new_post($post, $mform, $unused = null) {
3092 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3093 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
3094 $cm = get_coursemodule_from_instance('forum', $forum->id);
3095 $context = context_module::instance($cm->id);
3097 $post->created = $post->modified = time();
3098 $post->mailed = FORUM_MAILED_PENDING;
3099 $post->userid = $USER->id;
3100 $post->attachment = "";
3101 if (!isset($post->totalscore)) {
3102 $post->totalscore = 0;
3104 if (!isset($post->mailnow)) {
3108 $post->id = $DB->insert_record("forum_posts", $post);
3109 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
3110 mod_forum_post_form::editor_options($context, null), $post->message);
3111 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
3112 forum_add_attachment($post, $forum, $cm, $mform);
3114 // Update discussion modified date
3115 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
3116 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
3118 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3119 forum_tp_mark_post_read($post->userid, $post);
3122 if (isset($post->tags)) {
3123 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
3126 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3127 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
3135 * @param stdClass $newpost The post to update
3136 * @param mixed $mform The submitted form
3137 * @param string $unused
3140 function forum_update_post($newpost, $mform, $unused = null) {
3143 $post = $DB->get_record('forum_posts', array('id' => $newpost->id));
3144 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3145 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
3146 $cm = get_coursemodule_from_instance('forum', $forum->id);
3147 $context = context_module::instance($cm->id);
3149 // Allowed modifiable fields.
3150 $modifiablefields = [
3160 foreach ($modifiablefields as $field) {
3161 if (isset($newpost->{$field})) {
3162 $post->{$field} = $newpost->{$field};
3165 $post->modified = time();
3167 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
3168 $discussion->name = $post->subject;
3169 $discussion->timestart = $post->timestart;
3170 $discussion->timeend = $post->timeend;
3172 if (isset($post->pinned)) {
3173 $discussion->pinned = $post->pinned;
3176 $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
3177 mod_forum_post_form::editor_options($context, $post->id), $post->message);
3178 $DB->update_record('forum_posts', $post);
3179 // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
3180 $DB->update_record('forum_discussions', $discussion);
3182 forum_add_attachment($post, $forum, $cm, $mform);
3184 if (isset($newpost->tags)) {
3185 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3188 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3189 forum_tp_mark_post_read($USER->id, $post);
3192 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3193 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3199 * Given an object containing all the necessary data,
3200 * create a new discussion and return the id
3202 * @param object $post
3203 * @param mixed $mform
3204 * @param string $unused
3205 * @param int $userid
3208 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
3209 global $USER, $CFG, $DB;
3211 $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
3213 if (is_null($userid)) {
3214 $userid = $USER->id;
3217 // The first post is stored as a real post, and linked
3218 // to from the discuss entry.
3220 $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
3221 $cm = get_coursemodule_from_instance('forum', $forum->id);
3223 $post = new stdClass();
3224 $post->discussion = 0;
3226 $post->userid = $userid;
3227 $post->created = $timenow;
3228 $post->modified = $timenow;
3229 $post->mailed = FORUM_MAILED_PENDING;
3230 $post->subject = $discussion->name;
3231 $post->message = $discussion->message;
3232 $post->messageformat = $discussion->messageformat;
3233 $post->messagetrust = $discussion->messagetrust;
3234 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null;
3235 $post->forum = $forum->id; // speedup
3236 $post->course = $forum->course; // speedup
3237 $post->mailnow = $discussion->mailnow;
3239 $post->id = $DB->insert_record("forum_posts", $post);
3241 // TODO: Fix the calling code so that there always is a $cm when this function is called
3242 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet
3243 $context = context_module::instance($cm->id);
3244 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
3245 mod_forum_post_form::editor_options($context, null), $post->message);
3246 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
3249 // Now do the main entry for the discussion, linking to this first post
3251 $discussion->firstpost = $post->id;
3252 $discussion->timemodified = $timenow;
3253 $discussion->usermodified = $post->userid;
3254 $discussion->userid = $userid;
3255 $discussion->assessed = 0;
3257 $post->discussion = $DB->insert_record("forum_discussions", $discussion);
3259 // Finally, set the pointer on the post.
3260 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
3262 if (!empty($cm->id)) {
3263 forum_add_attachment($post, $forum, $cm, $mform, $unused);
3266 if (isset($discussion->tags)) {
3267 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
3270 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
3271 forum_tp_mark_post_read($post->userid, $post);
3274 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3275 if (!empty($cm->id)) {
3276 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
3279 return $post->discussion;
3284 * Deletes a discussion and handles all associated cleanup.
3287 * @param object $discussion Discussion to delete
3288 * @param bool $fulldelete True when deleting entire forum
3289 * @param object $course Course
3290 * @param object $cm Course-module
3291 * @param object $forum Forum
3294 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
3296 require_once($CFG->libdir.'/completionlib.php');
3300 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
3301 foreach ($posts as $post) {
3302 $post->course = $discussion->course;
3303 $post->forum = $discussion->forum;
3304 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
3310 forum_tp_delete_read_records(-1, -1, $discussion->id);
3312 // Discussion subscriptions must be removed before discussions because of key constraints.
3313 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
3314 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
3318 // Update completion state if we are tracking completion based on number of posts
3319 // But don't bother when deleting whole thing
3321 $completion = new completion_info($course);
3322 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3323 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3324 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
3333 * Deletes a single forum post.
3336 * @param object $post Forum post object
3337 * @param mixed $children Whether to delete children. If false, returns false
3338 * if there are any children (without deleting the post). If true,
3339 * recursively deletes all children. If set to special value 'ignore', deletes
3340 * post regardless of children (this is for use only when deleting all posts
3342 * @param object $course Course
3343 * @param object $cm Course-module
3344 * @param object $forum Forum
3345 * @param bool $skipcompletion True to skip updating completion state if it
3346 * would otherwise be updated, i.e. when deleting entire forum anyway.
3349 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
3350 global $DB, $CFG, $USER;
3351 require_once($CFG->libdir.'/completionlib.php');
3353 $context = context_module::instance($cm->id);
3355 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
3357 foreach ($childposts as $childpost) {
3358 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
3366 require_once($CFG->dirroot.'/rating/lib.php');
3367 $delopt = new stdClass;
3368 $delopt->contextid = $context->id;
3369 $delopt->component = 'mod_forum';
3370 $delopt->ratingarea = 'post';
3371 $delopt->itemid = $post->id;
3372 $rm = new rating_manager();
3373 $rm->delete_ratings($delopt);
3375 // Delete attachments.
3376 $fs = get_file_storage();
3377 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
3378 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
3380 // Delete cached RSS feeds.
3381 if (!empty($CFG->enablerssfeeds)) {
3382 require_once($CFG->dirroot.'/mod/forum/rsslib.php');
3383 forum_rss_delete_file($forum);
3386 if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
3388 forum_tp_delete_read_records(-1, $post->id);
3390 // Just in case we are deleting the last post
3391 forum_discussion_update_last_post($post->discussion);
3393 // Update completion state if we are tracking completion based on number of posts
3394 // But don't bother when deleting whole thing
3396 if (!$skipcompletion) {
3397 $completion = new completion_info($course);
3398 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
3399 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
3400 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
3405 'context' => $context,
3406 'objectid' => $post->id,
3408 'discussionid' => $post->discussion,
3409 'forumid' => $forum->id,
3410 'forumtype' => $forum->type,
3414 if ($post->userid !== $USER->id) {
3415 $params['relateduserid'] = $post->userid;
3417 $event = \mod_forum\event\post_deleted::create($params);
3418 $event->add_record_snapshot('forum_posts', $post);
3427 * Sends post content to plagiarism plugin
3428 * @param object $post Forum post object
3429 * @param object $cm Course-module
3430 * @param string $name
3433 function forum_trigger_content_uploaded_event($post, $cm, $name) {
3434 $context = context_module::instance($cm->id);
3435 $fs = get_file_storage();
3436 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
3438 'context' => $context,
3439 'objectid' => $post->id,
3441 'content' => $post->message,
3442 'pathnamehashes' => array_keys($files),
3443 'discussionid' => $post->discussion,
3444 'triggeredfrom' => $name,
3447 $event = \mod_forum\event\assessable_uploaded::create($params);
3454 * @param object $post
3455 * @param bool $children
3458 function forum_count_replies($post, $children=true) {
3463 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id))) {
3464 foreach ($childposts as $childpost) {
3465 $count ++; // For this child
3466 $count += forum_count_replies($childpost, true);
3470 $count += $DB->count_records('forum_posts', array('parent' => $post->id));
3477 * Given a new post, subscribes or unsubscribes as appropriate.
3478 * Returns some text which describes what happened.
3480 * @param object $fromform The submitted form
3481 * @param stdClass $forum The forum record
3482 * @param stdClass $discussion The forum discussion record
3485 function forum_post_subscription($fromform, $forum, $discussion) {
3488 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3490 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
3491 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3492 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
3493 // This user should not be subscribed to the forum.
3494 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
3499 $info = new stdClass();
3500 $info->name = fullname($USER);
3501 $info->discussion = format_string($discussion->name);
3502 $info->forum = format_string($forum->name);
3504 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
3505 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
3506 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
3509 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
3510 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
3518 * Generate and return the subscribe or unsubscribe link for a forum.
3520 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
3521 * @param object $context the context object for this forum.
3522 * @param array $messages text used for the link in its various states
3523 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
3524 * Any strings not passed in are taken from the $defaultmessages array
3525 * at the top of the function.
3526 * @param bool $cantaccessagroup
3527 * @param bool $unused1
3528 * @param bool $backtoindex
3529 * @param array $unused2
3532 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
3533 $backtoindex = false, $unused2 = null) {
3534 global $CFG, $USER, $PAGE, $OUTPUT;
3535 $defaultmessages = array(
3536 'subscribed' => get_string('unsubscribe', 'forum'),
3537 'unsubscribed' => get_string('subscribe', 'forum'),
3538 'cantaccessgroup' => get_string('no'),
3539 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
3540 'cantsubscribe' => get_string('disallowsubscribe','forum')
3542 $messages = $messages + $defaultmessages;
3544 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
3545 return $messages['forcesubscribed'];
3546 } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
3547 !has_capability('mod/forum:managesubscriptions', $context)) {
3548 return $messages['cantsubscribe'];
3549 } else if ($cantaccessagroup) {
3550 return $messages['cantaccessgroup'];
3552 if (!is_enrolled($context, $USER, '', true)) {
3556 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
3558 $linktext = $messages['subscribed'];
3559 $linktitle = get_string('subscribestop', 'forum');
3561 $linktext = $messages['unsubscribed'];
3562 $linktitle = get_string('subscribestart', 'forum');
3567 $backtoindexlink = '&backtoindex=1';
3568 $options['backtoindex'] = 1;
3570 $backtoindexlink = '';
3573 $options['id'] = $forum->id;
3574 $options['sesskey'] = sesskey();
3575 $url = new moodle_url('/mod/forum/subscribe.php', $options);
3576 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
3581 * Returns true if user created new discussion already.
3583 * @param int $forumid The forum to check for postings
3584 * @param int $userid The user to check for postings
3585 * @param int $groupid The group to restrict the check to
3588 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
3592 FROM {forum_discussions} d, {forum_posts} p
3593 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
3595 $params = [$forumid, $userid];
3598 $sql .= " AND d.groupid = ?";
3599 $params[] = $groupid;
3602 return $DB->record_exists_sql($sql, $params);
3608 * @param int $forumid
3609 * @param int $userid
3612 function forum_discussions_user_has_posted_in($forumid, $userid) {
3615 $haspostedsql = "SELECT d.id AS id,
3617 FROM {forum_posts} p,
3618 {forum_discussions} d
3619 WHERE p.discussion = d.id
3623 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
3629 * @param int $forumid
3631 * @param int $userid
3634 function forum_user_has_posted($forumid, $did, $userid) {
3638 // posted in any forum discussion?
3640 FROM {forum_posts} p
3641 JOIN {forum_discussions} d ON d.id = p.discussion
3642 WHERE p.userid = :userid AND d.forum = :forumid";
3643 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
3645 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
3650 * Returns creation time of the first user's post in given discussion
3651 * @global object $DB
3652 * @param int $did Discussion id
3653 * @param int $userid User id
3654 * @return int|bool post creation time stamp or return false
3656 function forum_get_user_posted_time($did, $userid) {
3659 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
3660 if (empty($posttime)) {
3668 * @param object $forum
3669 * @param object $currentgroup
3670 * @param int $unused
3672 * @param object $context
3675 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
3676 // $forum is an object
3679 // shortcut - guest and not-logged-in users can not post
3680 if (isguestuser() or !isloggedin()) {
3685 debugging('missing cm', DEBUG_DEVELOPER);
3686 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3687 print_error('invalidcoursemodule');
3692 $context = context_module::instance($cm->id);
3695 if ($currentgroup === null) {
3696 $currentgroup = groups_get_activity_group($cm);
3699 $groupmode = groups_get_activity_groupmode($cm);
3701 if ($forum->type == 'news') {
3702 $capname = 'mod/forum:addnews';
3703 } else if ($forum->type == 'qanda') {
3704 $capname = 'mod/forum:addquestion';
3706 $capname = 'mod/forum:startdiscussion';
3709 if (!has_capability($capname, $context)) {
3713 if ($forum->type == 'single') {
3717 if ($forum->type == 'eachuser') {
3718 if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) {
3723 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
3727 if ($currentgroup) {
3728 return groups_is_member($currentgroup);
3730 // no group membership and no accessallgroups means no new discussions
3731 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
3737 * This function checks whether the user can reply to posts in a forum
3738 * discussion. Use forum_user_can_post_discussion() to check whether the user
3739 * can start discussions.
3743 * @uses DEBUG_DEVELOPER
3744 * @uses CONTEXT_MODULE
3745 * @uses VISIBLEGROUPS
3746 * @param object $forum forum object
3747 * @param object $discussion
3748 * @param object $user
3750 * @param object $course
3751 * @param object $context
3754 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
3760 // shortcut - guest and not-logged-in users can not post
3761 if (isguestuser($user) or empty($user->id)) {
3765 if (!isset($discussion->groupid)) {
3766 debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
3771 debugging('missing cm', DEBUG_DEVELOPER);
3772 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3773 print_error('invalidcoursemodule');
3778 debugging('missing course', DEBUG_DEVELOPER);
3779 if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
3780 print_error('invalidcourseid');
3785 $context = context_module::instance($cm->id);
3788 // Check whether the discussion is locked.
3789 if (forum_discussion_is_locked($forum, $discussion)) {
3790 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
3795 // normal users with temporary guest access can not post, suspended users can not post either
3796 if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
3800 if ($forum->type == 'news') {
3801 $capname = 'mod/forum:replynews';
3803 $capname = 'mod/forum:replypost';
3806 if (!has_capability($capname, $context, $user->id)) {
3810 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
3814 if (has_capability('moodle/site:accessallgroups', $context)) {
3818 if ($groupmode == VISIBLEGROUPS) {
3819 if ($discussion->groupid == -1) {
3820 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
3823 return groups_is_member($discussion->groupid);
3827 if ($discussion->groupid == -1) {
3830 return groups_is_member($discussion->groupid);
3835 * Check to ensure a user can view a timed discussion.
3837 * @param object $discussion
3838 * @param object $user
3839 * @param object $context
3840 * @return boolean returns true if they can view post, false otherwise
3842 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
3845 // Check that the user can view a discussion that is normally hidden due to access times.
3846 if (!empty($CFG->forum_enabletimedposts)) {
3848 if (($discussion->timestart != 0 && $discussion->timestart > $time)
3849 || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
3850 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
3860 * Check to ensure a user can view a group discussion.
3862 * @param object $discussion
3864 * @param object $context
3865 * @return boolean returns true if they can view post, false otherwise
3867 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
3869 // If it's a grouped discussion, make sure the user is a member.
3870 if ($discussion->groupid > 0) {
3871 $groupmode = groups_get_activity_groupmode($cm);
3872 if ($groupmode == SEPARATEGROUPS) {
3873 return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
3883 * @uses DEBUG_DEVELOPER
3884 * @param object $forum
3885 * @param object $discussion
3886 * @param object $context
3887 * @param object $user
3890 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
3893 if (empty($user) || empty($user->id)) {
3897 // retrieve objects (yuk)
3898 if (is_numeric($forum)) {
3899 debugging('missing full forum', DEBUG_DEVELOPER);
3900 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3904 if (is_numeric($discussion)) {
3905 debugging('missing full discussion', DEBUG_DEVELOPER);
3906 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3910 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3911 print_error('invalidcoursemodule');
3914 if (!has_capability('mod/forum:viewdiscussion', $context)) {
3918 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
3922 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
3930 * Check whether a user can see the specified post.
3932 * @param \stdClass $forum The forum to chcek
3933 * @param \stdClass $discussion The discussion the post is in
3934 * @param \stdClass $post The post in question
3935 * @param \stdClass $user The user to test - if not specified, the current user is checked.
3936 * @param \stdClass $cm The Course Module that the forum is in (required).
3937 * @param bool $checkdeleted Whether to check the deleted flag on the post.
3940 function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) {
3941 global $CFG, $USER, $DB;
3943 // retrieve objects (yuk)
3944 if (is_numeric($forum)) {
3945 debugging('missing full forum', DEBUG_DEVELOPER);
3946 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
3951 if (is_numeric($discussion)) {
3952 debugging('missing full discussion', DEBUG_DEVELOPER);
3953 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
3957 if (is_numeric($post)) {
3958 debugging('missing full post', DEBUG_DEVELOPER);
3959 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
3964 if (!isset($post->id) && isset($post->parent)) {
3965 $post->id = $post->parent;
3968 if ($checkdeleted && !empty($post->deleted)) {
3973 debugging('missing cm', DEBUG_DEVELOPER);
3974 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3975 print_error('invalidcoursemodule');
3979 // Context used throughout function.
3980 $modcontext = context_module::instance($cm->id);
3982 if (empty($user) || empty($user->id)) {
3986 $canviewdiscussion = (isset($cm->cache) && !empty($cm->cache->caps['mod/forum:viewdiscussion']))
3987 || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
3988 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
3992 if (isset($cm->uservisible)) {
3993 if (!$cm->uservisible) {
3997 if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
4002 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
4006 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
4010 if ($forum->type == 'qanda') {
4011 if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id) || $post->userid == $user->id
4012 || (isset($discussion->firstpost) && $discussion->firstpost == $post->id)) {
4015 $firstpost = forum_get_firstpost_from_discussion($discussion->id);
4016 if ($firstpost->userid == $user->id) {
4019 $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
4020 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)));
4026 * Returns all forum posts since a given time in specified forum.
4028 * @todo Document this functions args
4034 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
4035 global $CFG, $COURSE, $USER, $DB;
4037 if ($COURSE->id == $courseid) {
4040 $course = $DB->get_record('course', array('id' => $courseid));
4043 $modinfo = get_fast_modinfo($course);
4045 $cm = $modinfo->cms[$cmid];
4046 $params = array($timestart, $cm->instance);
4049 $userselect = "AND u.id = ?";
4050 $params[] = $userid;
4056 $groupselect = "AND d.groupid = ?";
4057 $params[] = $groupid;
4062 $allnames = get_all_user_name_fields(true, 'u');
4063 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
4064 d.timestart, d.timeend, d.userid AS duserid,
4065 $allnames, u.email, u.picture, u.imagealt, u.email
4066 FROM {forum_posts} p
4067 JOIN {forum_discussions} d ON d.id = p.discussion
4068 JOIN {forum} f ON f.id = d.forum
4069 JOIN {user} u ON u.id = p.userid
4070 WHERE p.created > ? AND f.id = ?
4071 $userselect $groupselect
4072 ORDER BY p.id ASC", $params)) { // order by initial posting date
4076 $groupmode = groups_get_activity_groupmode($cm, $course);
4077 $cm_context = context_module::instance($cm->id);
4078 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
4079 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
4081 $printposts = array();
4082 foreach ($posts as $post) {
4084 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
4085 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
4086 if (!$viewhiddentimed) {
4092 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
4093 // oki (Open discussions have groupid -1)
4096 if (isguestuser()) {
4101 if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
4107 $printposts[] = $post;
4114 $aname = format_string($cm->name,true);
4116 foreach ($printposts as $post) {
4117 $tmpactivity = new stdClass();
4119 $tmpactivity->type = 'forum';
4120 $tmpactivity->cmid = $cm->id;
4121 $tmpactivity->name = $aname;
4122 $tmpactivity->sectionnum = $cm->sectionnum;
4123 $tmpactivity->timestamp = $post->modified;
4125 $tmpactivity->content = new stdClass();
4126 $tmpactivity->content->id = $post->id;
4127 $tmpactivity->content->discussion = $post->discussion;
4128 $tmpactivity->content->subject = format_string($post->subject);
4129 $tmpactivity->content->parent = $post->parent;
4130 $tmpactivity->content->forumtype = $post->forumtype;
4132 $tmpactivity->user = new stdClass();
4133 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
4134 $additionalfields = explode(',', user_picture::fields());
4135 $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
4136 $tmpactivity->user->id = $post->userid;
4138 $activities[$index++] = $tmpactivity;
4145 * Outputs the forum post indicated by $activity.
4147 * @param object $activity the activity object the forum resides in
4148 * @param int $courseid the id of the course the forum resides in
4149 * @param bool $detail not used, but required for compatibilty with other modules
4150 * @param int $modnames not used, but required for compatibilty with other modules
4151 * @param bool $viewfullnames not used, but required for compatibilty with other modules
4153 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
4156 $content = $activity->content;
4157 if ($content->parent) {
4160 $class = 'discussion';
4165 'cellpadding' => '3',
4166 'cellspacing' => '0',
4167 'class' => 'forum-recent'
4169 $output = html_writer::start_tag('table', $tableoptions);
4170 $output .= html_writer::start_tag('tr');
4172 $post = (object) ['parent' => $content->parent];
4173 $forum = (object) ['type' => $content->forumtype];
4174 $authorhidden = forum_is_author_hidden($post, $forum);
4176 // Show user picture if author should not be hidden.
4177 if (!$authorhidden) {
4179 'courseid' => $courseid,
4180 'link' => $authorhidden,
4181 'alttext' => $authorhidden,
4183 $picture = $OUTPUT->user_picture($activity->user, $pictureoptions);
4184 $output .= html_writer::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
4187 // Discussion title and author.
4188 $output .= html_writer::start_tag('td', ['class' => $class]);
4189 if ($content->parent) {
4192 // Bold the title of new discussions so they stand out.
4193 $class = 'title bold';
4196 $output .= html_writer::start_div($class);
4198 $aname = s($activity->name);
4199 $output .= $OUTPUT->image_icon('icon', $aname, $activity->type);
4201 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion]);
4202 $discussionurl->set_anchor('p' . $activity->content->id);
4203 $output .= html_writer::link($discussionurl, $content->subject);
4204 $output .= html_writer::end_div();
4206 $timestamp = userdate_htmltime($activity->timestamp);
4207 if ($authorhidden) {
4208 $authornamedate = $timestamp;
4210 $fullname = fullname($activity->user, $viewfullnames);
4211 $userurl = new moodle_url('/user/view.php');
4212 $userurl->params(['id' => $activity->user->id, 'course' => $courseid]);
4213 $by = new stdClass();
4214 $by->name = html_writer::link($userurl, $fullname);
4215 $by->date = $timestamp;
4216 $authornamedate = get_string('bynameondate', 'forum', $by);
4218 $output .= html_writer::div($authornamedate, 'user');
4219 $output .= html_writer::end_tag('td');
4220 $output .= html_writer::end_tag('tr');
4221 $output .= html_writer::end_tag('table');
4227 * recursively sets the discussion field to $discussionid on $postid and all its children
4228 * used when pruning a post
4231 * @param int $postid
4232 * @param int $discussionid
4235 function forum_change_discussionid($postid, $discussionid) {
4237 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
4238 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
4239 foreach ($posts as $post) {
4240 forum_change_discussionid($post->id, $discussionid);
4247 * Prints the editing button on subscribers page
4251 * @param int $courseid
4252 * @param int $forumid
4255 function forum_update_subscriptions_button($courseid, $forumid) {
4258 if (!empty($USER->subscriptionsediting)) {
4259 $string = get_string('managesubscriptionsoff', 'forum');
4262 $string = get_string('managesubscriptionson', 'forum');
4266 $subscribers = html_writer::start_tag('form', array('action' => $CFG->wwwroot . '/mod/forum/subscribers.php',
4267 'method' => 'get', 'class' => 'form-inline'));
4268 $subscribers .= html_writer::empty_tag('input', array('type' => 'submit', 'value' => $string,
4269 'class' => 'btn btn-secondary'));
4270 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $forumid));
4271 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'edit', 'value' => $edit));
4272 $subscribers .= html_writer::end_tag('form');
4274 return $subscribers;
4277 // Functions to do with read tracking.
4280 * Mark posts as read.
4284 * @param object $user object
4285 * @param array $postids array of post ids
4286 * @return boolean success
4288 function forum_tp_mark_posts_read($user, $postids) {
4291 if (!forum_tp_can_track_forums(false, $user)) {
4298 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
4300 if (empty($postids)) {