MDL-60828 user: Reset current page when filtering/searching users
[moodle.git] / mod / forum / lib.php
blob43f5ca4bb0585a1e4a1d69e54561ae07780b59d1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
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/>.
17 /**
18 * @package mod_forum
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') || die();
25 /** Include required files */
26 require_once(__DIR__ . '/deprecatedlib.php');
27 require_once($CFG->libdir.'/filelib.php');
28 require_once($CFG->libdir.'/eventslib.php');
30 /// CONSTANTS ///////////////////////////////////////////////////////////
32 define('FORUM_MODE_FLATOLDEST', 1);
33 define('FORUM_MODE_FLATNEWEST', -1);
34 define('FORUM_MODE_THREADED', 2);
35 define('FORUM_MODE_NESTED', 3);
37 define('FORUM_CHOOSESUBSCRIBE', 0);
38 define('FORUM_FORCESUBSCRIBE', 1);
39 define('FORUM_INITIALSUBSCRIBE', 2);
40 define('FORUM_DISALLOWSUBSCRIBE',3);
42 /**
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
47 /**
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
52 /**
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
62 if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
67 /**
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
70 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
72 define('FORUM_DISCUSSION_PINNED', 1);
73 define('FORUM_DISCUSSION_UNPINNED', 0);
75 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
77 /**
78 * Given an object containing all the necessary data,
79 * (defined by the form in mod_form.php) this function
80 * will create a new instance and return the id number
81 * of the new instance.
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
85 * @return int intance id
87 function forum_add_instance($forum, $mform = null) {
88 global $CFG, $DB;
90 $forum->timemodified = time();
92 if (empty($forum->assessed)) {
93 $forum->assessed = 0;
96 if (empty($forum->ratingtime) or empty($forum->assessed)) {
97 $forum->assesstimestart = 0;
98 $forum->assesstimefinish = 0;
101 $forum->id = $DB->insert_record('forum', $forum);
102 $modcontext = context_module::instance($forum->coursemodule);
104 if ($forum->type == 'single') { // Create related discussion.
105 $discussion = new stdClass();
106 $discussion->course = $forum->course;
107 $discussion->forum = $forum->id;
108 $discussion->name = $forum->name;
109 $discussion->assessed = $forum->assessed;
110 $discussion->message = $forum->intro;
111 $discussion->messageformat = $forum->introformat;
112 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
113 $discussion->mailnow = false;
114 $discussion->groupid = -1;
116 $message = '';
118 $discussion->id = forum_add_discussion($discussion, null, $message);
120 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
121 // Ugly hack - we need to copy the files somehow.
122 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
123 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
125 $options = array('subdirs'=>true); // Use the same options as intro field!
126 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
127 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
131 forum_grade_item_update($forum);
133 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
134 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
136 return $forum->id;
140 * Handle changes following the creation of a forum instance.
141 * This function is typically called by the course_module_created observer.
143 * @param object $context the forum context
144 * @param stdClass $forum The forum object
145 * @return void
147 function forum_instance_created($context, $forum) {
148 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
149 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
150 foreach ($users as $user) {
151 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
157 * Given an object containing all the necessary data,
158 * (defined by the form in mod_form.php) this function
159 * will update an existing instance with new data.
161 * @global object
162 * @param object $forum forum instance (with magic quotes)
163 * @return bool success
165 function forum_update_instance($forum, $mform) {
166 global $DB, $OUTPUT, $USER;
168 $forum->timemodified = time();
169 $forum->id = $forum->instance;
171 if (empty($forum->assessed)) {
172 $forum->assessed = 0;
175 if (empty($forum->ratingtime) or empty($forum->assessed)) {
176 $forum->assesstimestart = 0;
177 $forum->assesstimefinish = 0;
180 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
182 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
183 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
184 // 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
185 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
186 forum_update_grades($forum); // recalculate grades for the forum
189 if ($forum->type == 'single') { // Update related discussion and post.
190 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
191 if (!empty($discussions)) {
192 if (count($discussions) > 1) {
193 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
195 $discussion = array_pop($discussions);
196 } else {
197 // try to recover by creating initial discussion - MDL-16262
198 $discussion = new stdClass();
199 $discussion->course = $forum->course;
200 $discussion->forum = $forum->id;
201 $discussion->name = $forum->name;
202 $discussion->assessed = $forum->assessed;
203 $discussion->message = $forum->intro;
204 $discussion->messageformat = $forum->introformat;
205 $discussion->messagetrust = true;
206 $discussion->mailnow = false;
207 $discussion->groupid = -1;
209 $message = '';
211 forum_add_discussion($discussion, null, $message);
213 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
214 print_error('cannotadd', 'forum');
217 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
218 print_error('cannotfindfirstpost', 'forum');
221 $cm = get_coursemodule_from_instance('forum', $forum->id);
222 $modcontext = context_module::instance($cm->id, MUST_EXIST);
224 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
225 $post->subject = $forum->name;
226 $post->message = $forum->intro;
227 $post->messageformat = $forum->introformat;
228 $post->messagetrust = trusttext_trusted($modcontext);
229 $post->modified = $forum->timemodified;
230 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
232 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
233 // Ugly hack - we need to copy the files somehow.
234 $options = array('subdirs'=>true); // Use the same options as intro field!
235 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
238 $DB->update_record('forum_posts', $post);
239 $discussion->name = $forum->name;
240 $DB->update_record('forum_discussions', $discussion);
243 $DB->update_record('forum', $forum);
245 $modcontext = context_module::instance($forum->coursemodule);
246 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
247 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
248 foreach ($users as $user) {
249 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
253 forum_grade_item_update($forum);
255 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
256 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
258 return true;
263 * Given an ID of an instance of this module,
264 * this function will permanently delete the instance
265 * and any data that depends on it.
267 * @global object
268 * @param int $id forum instance id
269 * @return bool success
271 function forum_delete_instance($id) {
272 global $DB;
274 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
275 return false;
277 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
278 return false;
280 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
281 return false;
284 $context = context_module::instance($cm->id);
286 // now get rid of all files
287 $fs = get_file_storage();
288 $fs->delete_area_files($context->id);
290 $result = true;
292 \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
294 // Delete digest and subscription preferences.
295 $DB->delete_records('forum_digests', array('forum' => $forum->id));
296 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
297 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
299 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
300 foreach ($discussions as $discussion) {
301 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
302 $result = false;
307 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
309 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
310 $result = false;
313 forum_grade_item_delete($forum);
315 return $result;
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) {
333 switch($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
353 * in forum settings.
355 * @global object
356 * @global object
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) {
365 global $CFG,$DB;
367 // Get forum details
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);
375 $postcountsql="
376 SELECT
377 COUNT(1)
378 FROM
379 {forum_posts} fp
380 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
381 WHERE
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;
389 } else {
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;
398 } else {
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;
406 } else {
407 $result = $result || $value;
411 return $result;
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));
428 * Removes properties from user record that are not necessary
429 * for sending post notifications.
430 * @param stdClass $user
431 * @return void, $user parameter is modified
433 function forum_cron_minimise_user_record(stdClass $user) {
435 // We store large amount of users in one huge array,
436 // make sure we do not store info there we do not actually need
437 // in mail generation code or messaging.
439 unset($user->institution);
440 unset($user->department);
441 unset($user->address);
442 unset($user->city);
443 unset($user->url);
444 unset($user->currentlogin);
445 unset($user->description);
446 unset($user->descriptionformat);
450 * Function to be run periodically according to the scheduled task.
452 * Finds all posts that have yet to be mailed out, and mails them
453 * out to all subscribers as well as other maintance tasks.
455 * NOTE: Since 2.7.2 this function is run by scheduled task rather
456 * than standard cron.
458 * @todo MDL-44734 The function will be split up into seperate tasks.
460 function forum_cron() {
461 global $CFG, $USER, $DB, $PAGE;
463 $site = get_site();
465 // The main renderers.
466 $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
467 $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
468 $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
469 $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
470 $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
471 $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
473 // All users that are subscribed to any post that needs sending,
474 // please increase $CFG->extramemorylimit on large sites that
475 // send notifications to a large number of users.
476 $users = array();
477 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
479 // Status arrays.
480 $mailcount = array();
481 $errorcount = array();
483 // caches
484 $discussions = array();
485 $forums = array();
486 $courses = array();
487 $coursemodules = array();
488 $subscribedusers = array();
489 $messageinboundhandlers = array();
491 // Posts older than 2 days will not be mailed. This is to avoid the problem where
492 // cron has not been running for a long time, and then suddenly people are flooded
493 // with mail from the past few weeks or months
494 $timenow = time();
495 $endtime = $timenow - $CFG->maxeditingtime;
496 $starttime = $endtime - 48 * 3600; // Two days earlier
498 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
499 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
500 $digests = array();
501 foreach ($digestsset as $thisrow) {
502 if (!isset($digests[$thisrow->forum])) {
503 $digests[$thisrow->forum] = array();
505 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
507 $digestsset->close();
509 // Create the generic messageinboundgenerator.
510 $messageinboundgenerator = new \core\message\inbound\address_manager();
511 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
513 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
514 // Mark them all now as being mailed. It's unlikely but possible there
515 // might be an error later so that a post is NOT actually mailed out,
516 // but since mail isn't crucial, we can accept this risk. Doing it now
517 // prevents the risk of duplicated mails, which is a worse problem.
519 if (!forum_mark_old_posts_as_mailed($endtime)) {
520 mtrace('Errors occurred while trying to mark some posts as being mailed.');
521 return false; // Don't continue trying to mail them, in case we are in a cron loop
524 // checking post validity, and adding users to loop through later
525 foreach ($posts as $pid => $post) {
527 $discussionid = $post->discussion;
528 if (!isset($discussions[$discussionid])) {
529 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
530 $discussions[$discussionid] = $discussion;
531 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
532 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
534 } else {
535 mtrace('Could not find discussion ' . $discussionid);
536 unset($posts[$pid]);
537 continue;
540 $forumid = $discussions[$discussionid]->forum;
541 if (!isset($forums[$forumid])) {
542 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
543 $forums[$forumid] = $forum;
544 } else {
545 mtrace('Could not find forum '.$forumid);
546 unset($posts[$pid]);
547 continue;
550 $courseid = $forums[$forumid]->course;
551 if (!isset($courses[$courseid])) {
552 if ($course = $DB->get_record('course', array('id' => $courseid))) {
553 $courses[$courseid] = $course;
554 } else {
555 mtrace('Could not find course '.$courseid);
556 unset($posts[$pid]);
557 continue;
560 if (!isset($coursemodules[$forumid])) {
561 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
562 $coursemodules[$forumid] = $cm;
563 } else {
564 mtrace('Could not find course module for forum '.$forumid);
565 unset($posts[$pid]);
566 continue;
570 $modcontext = context_module::instance($coursemodules[$forumid]->id);
572 // Save the Inbound Message datakey here to reduce DB queries later.
573 $messageinboundgenerator->set_data($pid);
574 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
576 // Caching subscribed users of each forum.
577 if (!isset($subscribedusers[$forumid])) {
578 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
580 foreach ($subusers as $postuser) {
581 // this user is subscribed to this forum
582 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
583 $userscount++;
584 if ($userscount > FORUM_CRON_USER_CACHE) {
585 // Store minimal user info.
586 $minuser = new stdClass();
587 $minuser->id = $postuser->id;
588 $users[$postuser->id] = $minuser;
589 } else {
590 // Cache full user record.
591 forum_cron_minimise_user_record($postuser);
592 $users[$postuser->id] = $postuser;
595 // Release memory.
596 unset($subusers);
597 unset($postuser);
600 $mailcount[$pid] = 0;
601 $errorcount[$pid] = 0;
605 if ($users && $posts) {
607 foreach ($users as $userto) {
608 // Terminate if processing of any account takes longer than 2 minutes.
609 core_php_time_limit::raise(120);
611 mtrace('Processing user ' . $userto->id);
613 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
614 if (isset($userto->username)) {
615 $userto = clone($userto);
616 } else {
617 $userto = $DB->get_record('user', array('id' => $userto->id));
618 forum_cron_minimise_user_record($userto);
620 $userto->viewfullnames = array();
621 $userto->canpost = array();
622 $userto->markposts = array();
624 // Setup this user so that the capabilities are cached, and environment matches receiving user.
625 cron_setup_user($userto);
627 // Reset the caches.
628 foreach ($coursemodules as $forumid => $unused) {
629 $coursemodules[$forumid]->cache = new stdClass();
630 $coursemodules[$forumid]->cache->caps = array();
631 unset($coursemodules[$forumid]->uservisible);
634 foreach ($posts as $pid => $post) {
635 $discussion = $discussions[$post->discussion];
636 $forum = $forums[$discussion->forum];
637 $course = $courses[$forum->course];
638 $cm =& $coursemodules[$forum->id];
640 // Do some checks to see if we can bail out now.
642 // Only active enrolled users are in the list of subscribers.
643 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
644 if (!isset($subscribedusers[$forum->id][$userto->id])) {
645 // The user does not subscribe to this forum.
646 continue;
649 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
650 // The user does not subscribe to this forum, or to this specific discussion.
651 continue;
654 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
655 // Skip posts if the user subscribed to the discussion after it was created.
656 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
657 continue;
661 // Don't send email if the forum is Q&A and the user has not posted.
662 // Initial topics are still mailed.
663 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
664 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
665 continue;
668 // Get info about the sending user.
669 if (array_key_exists($post->userid, $users)) {
670 // We might know the user already.
671 $userfrom = $users[$post->userid];
672 if (!isset($userfrom->idnumber)) {
673 // Minimalised user info, fetch full record.
674 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
675 forum_cron_minimise_user_record($userfrom);
678 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
679 forum_cron_minimise_user_record($userfrom);
680 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
681 if ($userscount <= FORUM_CRON_USER_CACHE) {
682 $userscount++;
683 $users[$userfrom->id] = $userfrom;
685 } else {
686 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
687 continue;
690 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
692 // Setup global $COURSE properly - needed for roles and languages.
693 cron_setup_user($userto, $course);
695 // Fill caches.
696 if (!isset($userto->viewfullnames[$forum->id])) {
697 $modcontext = context_module::instance($cm->id);
698 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
700 if (!isset($userto->canpost[$discussion->id])) {
701 $modcontext = context_module::instance($cm->id);
702 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
704 if (!isset($userfrom->groups[$forum->id])) {
705 if (!isset($userfrom->groups)) {
706 $userfrom->groups = array();
707 if (isset($users[$userfrom->id])) {
708 $users[$userfrom->id]->groups = array();
711 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
712 if (isset($users[$userfrom->id])) {
713 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
717 // Make sure groups allow this user to see this email.
718 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
719 // Groups are being used.
720 if (!groups_group_exists($discussion->groupid)) {
721 // Can't find group - be safe and don't this message.
722 continue;
725 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
726 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
727 continue;
731 // Make sure we're allowed to see the post.
732 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
733 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
734 continue;
737 // OK so we need to send the email.
739 // Does the user want this post in a digest? If so postpone it for now.
740 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
742 if ($maildigest > 0) {
743 // This user wants the mails to be in digest form.
744 $queue = new stdClass();
745 $queue->userid = $userto->id;
746 $queue->discussionid = $discussion->id;
747 $queue->postid = $post->id;
748 $queue->timemodified = $post->created;
749 $DB->insert_record('forum_queue', $queue);
750 continue;
753 // Prepare to actually send the post now, and build up the content.
755 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
757 $userfrom->customheaders = array (
758 // Headers to make emails easier to track.
759 'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id),
760 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
761 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id),
762 'X-Course-Id: ' . $course->id,
763 'X-Course-Name: ' . format_string($course->fullname, true),
765 // Headers to help prevent auto-responders.
766 'Precedence: Bulk',
767 'X-Auto-Response-Suppress: All',
768 'Auto-Submitted: auto-generated',
771 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
773 // Generate a reply-to address from using the Inbound Message handler.
774 $replyaddress = null;
775 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
776 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
777 $replyaddress = $messageinboundgenerator->generate($userto->id);
780 if (!isset($userto->canpost[$discussion->id])) {
781 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
782 } else {
783 $canreply = $userto->canpost[$discussion->id];
786 $data = new \mod_forum\output\forum_post_email(
787 $course,
788 $cm,
789 $forum,
790 $discussion,
791 $post,
792 $userfrom,
793 $userto,
794 $canreply
797 $userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>',
798 $data->get_unsubscribediscussionlink());
800 if (!isset($userto->viewfullnames[$forum->id])) {
801 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
802 } else {
803 $data->viewfullnames = $userto->viewfullnames[$forum->id];
806 // Not all of these variables are used in the default language
807 // string but are made available to support custom subjects.
808 $a = new stdClass();
809 $a->subject = $data->get_subject();
810 $a->forumname = $cleanforumname;
811 $a->sitefullname = format_string($site->fullname);
812 $a->siteshortname = format_string($site->shortname);
813 $a->courseidnumber = $data->get_courseidnumber();
814 $a->coursefullname = $data->get_coursefullname();
815 $a->courseshortname = $data->get_coursename();
816 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
818 $rootid = forum_get_email_message_id($discussion->firstpost, $userto->id);
820 if ($post->parent) {
821 // This post is a reply, so add reply header (RFC 2822).
822 $parentid = forum_get_email_message_id($post->parent, $userto->id);
823 $userfrom->customheaders[] = "In-Reply-To: $parentid";
825 // If the post is deeply nested we also reference the parent message id and
826 // the root message id (if different) to aid threading when parts of the email
827 // conversation have been deleted (RFC1036).
828 if ($post->parent != $discussion->firstpost) {
829 $userfrom->customheaders[] = "References: $rootid $parentid";
830 } else {
831 $userfrom->customheaders[] = "References: $parentid";
835 // MS Outlook / Office uses poorly documented and non standard headers, including
836 // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
837 $a->subject = $discussion->name;
838 $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
839 $userfrom->customheaders[] = "Thread-Topic: $threadtopic";
840 $userfrom->customheaders[] = "Thread-Index: " . substr($rootid, 1, 28);
842 // Send the post now!
843 mtrace('Sending ', '');
845 $eventdata = new \core\message\message();
846 $eventdata->courseid = $course->id;
847 $eventdata->component = 'mod_forum';
848 $eventdata->name = 'posts';
849 $eventdata->userfrom = $userfrom;
850 $eventdata->userto = $userto;
851 $eventdata->subject = $postsubject;
852 $eventdata->fullmessage = $textout->render($data);
853 $eventdata->fullmessageformat = FORMAT_PLAIN;
854 $eventdata->fullmessagehtml = $htmlout->render($data);
855 $eventdata->notification = 1;
856 $eventdata->replyto = $replyaddress;
857 if (!empty($replyaddress)) {
858 // Add extra text to email messages if they can reply back.
859 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
860 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
861 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
862 'fullmessagehtml' => array('footer' => $htmlfooter));
863 $eventdata->set_additional_content('email', $additionalcontent);
866 $smallmessagestrings = new stdClass();
867 $smallmessagestrings->user = fullname($userfrom);
868 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
869 $smallmessagestrings->message = $post->message;
871 // Make sure strings are in message recipients language.
872 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
874 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
875 $eventdata->contexturl = $contexturl->out();
876 $eventdata->contexturlname = $discussion->name;
878 $mailresult = message_send($eventdata);
879 if (!$mailresult) {
880 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
881 " ($userto->email) .. not trying again.");
882 $errorcount[$post->id]++;
883 } else {
884 $mailcount[$post->id]++;
886 // Mark post as read if forum_usermarksread is set off.
887 if (!$CFG->forum_usermarksread) {
888 $userto->markposts[$post->id] = $post->id;
892 mtrace('post ' . $post->id . ': ' . $post->subject);
895 // Mark processed posts as read.
896 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
897 forum_tp_mark_posts_read($userto, $userto->markposts);
900 unset($userto);
904 if ($posts) {
905 foreach ($posts as $post) {
906 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
907 if ($errorcount[$post->id]) {
908 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
913 // release some memory
914 unset($subscribedusers);
915 unset($mailcount);
916 unset($errorcount);
918 cron_setup_user();
920 $sitetimezone = core_date::get_server_timezone();
922 // Now see if there are any digest mails waiting to be sent, and if we should send them
924 mtrace('Starting digest processing...');
926 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
928 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
929 set_config('digestmailtimelast', 0);
932 $timenow = time();
933 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
935 // Delete any really old ones (normally there shouldn't be any)
936 $weekago = $timenow - (7 * 24 * 3600);
937 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
938 mtrace ('Cleaned old digest records');
940 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
942 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
944 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
946 if ($digestposts_rs->valid()) {
948 // We have work to do
949 $usermailcount = 0;
951 //caches - reuse the those filled before too
952 $discussionposts = array();
953 $userdiscussions = array();
955 foreach ($digestposts_rs as $digestpost) {
956 if (!isset($posts[$digestpost->postid])) {
957 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
958 $posts[$digestpost->postid] = $post;
959 } else {
960 continue;
963 $discussionid = $digestpost->discussionid;
964 if (!isset($discussions[$discussionid])) {
965 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
966 $discussions[$discussionid] = $discussion;
967 } else {
968 continue;
971 $forumid = $discussions[$discussionid]->forum;
972 if (!isset($forums[$forumid])) {
973 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
974 $forums[$forumid] = $forum;
975 } else {
976 continue;
980 $courseid = $forums[$forumid]->course;
981 if (!isset($courses[$courseid])) {
982 if ($course = $DB->get_record('course', array('id' => $courseid))) {
983 $courses[$courseid] = $course;
984 } else {
985 continue;
989 if (!isset($coursemodules[$forumid])) {
990 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
991 $coursemodules[$forumid] = $cm;
992 } else {
993 continue;
996 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
997 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
999 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
1001 // Data collected, start sending out emails to each user
1002 foreach ($userdiscussions as $userid => $thesediscussions) {
1004 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
1006 cron_setup_user();
1008 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
1010 // First of all delete all the queue entries for this user
1011 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
1013 // Init user caches - we keep the cache for one cycle only,
1014 // otherwise it would unnecessarily consume memory.
1015 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
1016 $userto = clone($users[$userid]);
1017 } else {
1018 $userto = $DB->get_record('user', array('id' => $userid));
1019 forum_cron_minimise_user_record($userto);
1021 $userto->viewfullnames = array();
1022 $userto->canpost = array();
1023 $userto->markposts = array();
1025 // Override the language and timezone of the "current" user, so that
1026 // mail is customised for the receiver.
1027 cron_setup_user($userto);
1029 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
1031 $headerdata = new stdClass();
1032 $headerdata->sitename = format_string($site->fullname, true);
1033 $headerdata->userprefs = $CFG->wwwroot.'/user/forum.php?id='.$userid.'&amp;course='.$site->id;
1035 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
1036 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
1038 $posthtml = '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p>'
1039 . '<br /><hr size="1" noshade="noshade" />';
1041 foreach ($thesediscussions as $discussionid) {
1043 core_php_time_limit::raise(120); // to be reset for each post
1045 $discussion = $discussions[$discussionid];
1046 $forum = $forums[$discussion->forum];
1047 $course = $courses[$forum->course];
1048 $cm = $coursemodules[$forum->id];
1050 //override language
1051 cron_setup_user($userto, $course);
1053 // Fill caches
1054 if (!isset($userto->viewfullnames[$forum->id])) {
1055 $modcontext = context_module::instance($cm->id);
1056 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
1058 if (!isset($userto->canpost[$discussion->id])) {
1059 $modcontext = context_module::instance($cm->id);
1060 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1063 $strforums = get_string('forums', 'forum');
1064 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1065 $canreply = $userto->canpost[$discussion->id];
1066 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1068 $posttext .= "\n \n";
1069 $posttext .= '=====================================================================';
1070 $posttext .= "\n \n";
1071 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1072 if ($discussion->name != $forum->name) {
1073 $posttext .= " -> ".format_string($discussion->name,true);
1075 $posttext .= "\n";
1076 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1077 $posttext .= "\n";
1079 $posthtml .= "<p><font face=\"sans-serif\">".
1080 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1081 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1082 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
1083 if ($discussion->name == $forum->name) {
1084 $posthtml .= "</font></p>";
1085 } else {
1086 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
1088 $posthtml .= '<p>';
1090 $postsarray = $discussionposts[$discussionid];
1091 sort($postsarray);
1092 $sentcount = 0;
1094 foreach ($postsarray as $postid) {
1095 $post = $posts[$postid];
1097 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1098 $userfrom = $users[$post->userid];
1099 if (!isset($userfrom->idnumber)) {
1100 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1101 forum_cron_minimise_user_record($userfrom);
1104 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1105 forum_cron_minimise_user_record($userfrom);
1106 if ($userscount <= FORUM_CRON_USER_CACHE) {
1107 $userscount++;
1108 $users[$userfrom->id] = $userfrom;
1111 } else {
1112 mtrace('Could not find user '.$post->userid);
1113 continue;
1116 if (!isset($userfrom->groups[$forum->id])) {
1117 if (!isset($userfrom->groups)) {
1118 $userfrom->groups = array();
1119 if (isset($users[$userfrom->id])) {
1120 $users[$userfrom->id]->groups = array();
1123 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1124 if (isset($users[$userfrom->id])) {
1125 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1129 // Headers to help prevent auto-responders.
1130 $userfrom->customheaders = array(
1131 "Precedence: Bulk",
1132 'X-Auto-Response-Suppress: All',
1133 'Auto-Submitted: auto-generated',
1136 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1137 if (!isset($userto->canpost[$discussion->id])) {
1138 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1139 } else {
1140 $canreply = $userto->canpost[$discussion->id];
1143 $data = new \mod_forum\output\forum_post_email(
1144 $course,
1145 $cm,
1146 $forum,
1147 $discussion,
1148 $post,
1149 $userfrom,
1150 $userto,
1151 $canreply
1154 if (!isset($userto->viewfullnames[$forum->id])) {
1155 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1156 } else {
1157 $data->viewfullnames = $userto->viewfullnames[$forum->id];
1160 if ($maildigest == 2) {
1161 // Subjects and link only.
1162 $posttext .= $textdigestbasicout->render($data);
1163 $posthtml .= $htmldigestbasicout->render($data);
1164 } else {
1165 // The full treatment.
1166 $posttext .= $textdigestfullout->render($data);
1167 $posthtml .= $htmldigestfullout->render($data);
1169 // Create an array of postid's for this user to mark as read.
1170 if (!$CFG->forum_usermarksread) {
1171 $userto->markposts[$post->id] = $post->id;
1174 $sentcount++;
1176 $footerlinks = array();
1177 if ($canunsubscribe) {
1178 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1179 } else {
1180 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1182 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1183 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode('&nbsp;', $footerlinks) . '</font></div>';
1184 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1187 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1188 // This user DOESN'T want to receive HTML
1189 $posthtml = '';
1192 $eventdata = new \core\message\message();
1193 $eventdata->courseid = SITEID;
1194 $eventdata->component = 'mod_forum';
1195 $eventdata->name = 'digests';
1196 $eventdata->userfrom = core_user::get_noreply_user();
1197 $eventdata->userto = $userto;
1198 $eventdata->subject = $postsubject;
1199 $eventdata->fullmessage = $posttext;
1200 $eventdata->fullmessageformat = FORMAT_PLAIN;
1201 $eventdata->fullmessagehtml = $posthtml;
1202 $eventdata->notification = 1;
1203 $eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $sentcount);
1204 $mailresult = message_send($eventdata);
1206 if (!$mailresult) {
1207 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1208 "($userto->email)... not trying again.");
1209 } else {
1210 mtrace("success.");
1211 $usermailcount++;
1213 // Mark post as read if forum_usermarksread is set off
1214 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
1215 forum_tp_mark_posts_read($userto, $userto->markposts);
1220 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1221 set_config('digestmailtimelast', $timenow);
1224 cron_setup_user();
1226 if (!empty($usermailcount)) {
1227 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1230 if (!empty($CFG->forum_lastreadclean)) {
1231 $timenow = time();
1232 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1233 set_config('forum_lastreadclean', $timenow);
1234 mtrace('Removing old forum read tracking info...');
1235 forum_tp_clean_read_records();
1237 } else {
1238 set_config('forum_lastreadclean', time());
1241 return true;
1246 * @param object $course
1247 * @param object $user
1248 * @param object $mod TODO this is not used in this function, refactor
1249 * @param object $forum
1250 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1252 function forum_user_outline($course, $user, $mod, $forum) {
1253 global $CFG;
1254 require_once("$CFG->libdir/gradelib.php");
1255 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1256 if (empty($grades->items[0]->grades)) {
1257 $grade = false;
1258 } else {
1259 $grade = reset($grades->items[0]->grades);
1262 $count = forum_count_user_posts($forum->id, $user->id);
1264 if ($count && $count->postcount > 0) {
1265 $result = new stdClass();
1266 $result->info = get_string("numposts", "forum", $count->postcount);
1267 $result->time = $count->lastpost;
1268 if ($grade) {
1269 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1271 return $result;
1272 } else if ($grade) {
1273 $result = new stdClass();
1274 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1276 //datesubmitted == time created. dategraded == time modified or time overridden
1277 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1278 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1279 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1280 $result->time = $grade->dategraded;
1281 } else {
1282 $result->time = $grade->datesubmitted;
1285 return $result;
1287 return NULL;
1292 * @global object
1293 * @global object
1294 * @param object $coure
1295 * @param object $user
1296 * @param object $mod
1297 * @param object $forum
1299 function forum_user_complete($course, $user, $mod, $forum) {
1300 global $CFG,$USER, $OUTPUT;
1301 require_once("$CFG->libdir/gradelib.php");
1303 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1304 if (!empty($grades->items[0]->grades)) {
1305 $grade = reset($grades->items[0]->grades);
1306 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1307 if ($grade->str_feedback) {
1308 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1312 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1314 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1315 print_error('invalidcoursemodule');
1317 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1319 foreach ($posts as $post) {
1320 if (!isset($discussions[$post->discussion])) {
1321 continue;
1323 $discussion = $discussions[$post->discussion];
1325 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1327 } else {
1328 echo "<p>".get_string("noposts", "forum")."</p>";
1333 * Filters the forum discussions according to groups membership and config.
1335 * @deprecated since 3.3
1336 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1337 * @since Moodle 2.8, 2.7.1, 2.6.4
1338 * @param array $discussions Discussions with new posts array
1339 * @return array Forums with the number of new posts
1341 function forum_filter_user_groups_discussions($discussions) {
1343 debugging('The function forum_filter_user_groups_discussions() is now deprecated.', DEBUG_DEVELOPER);
1345 // Group the remaining discussions posts by their forumid.
1346 $filteredforums = array();
1348 // Discard not visible groups.
1349 foreach ($discussions as $discussion) {
1351 // Course data is already cached.
1352 $instances = get_fast_modinfo($discussion->course)->get_instances();
1353 $forum = $instances['forum'][$discussion->forum];
1355 // Continue if the user should not see this discussion.
1356 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1357 continue;
1360 // Grouping results by forum.
1361 if (empty($filteredforums[$forum->instance])) {
1362 $filteredforums[$forum->instance] = new stdClass();
1363 $filteredforums[$forum->instance]->id = $forum->id;
1364 $filteredforums[$forum->instance]->count = 0;
1366 $filteredforums[$forum->instance]->count += $discussion->count;
1370 return $filteredforums;
1374 * Returns whether the discussion group is visible by the current user or not.
1376 * @since Moodle 2.8, 2.7.1, 2.6.4
1377 * @param cm_info $cm The discussion course module
1378 * @param int $discussiongroupid The discussion groupid
1379 * @return bool
1381 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1383 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1384 return true;
1387 if (isguestuser()) {
1388 return false;
1391 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1392 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1393 return true;
1396 return false;
1400 * @deprecated since 3.3
1401 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1402 * @global object
1403 * @global object
1404 * @global object
1405 * @param array $courses
1406 * @param array $htmlarray
1408 function forum_print_overview($courses,&$htmlarray) {
1409 global $USER, $CFG, $DB, $SESSION;
1411 debugging('The function forum_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1413 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1414 return array();
1417 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1418 return;
1421 // Courses to search for new posts
1422 $coursessqls = array();
1423 $params = array();
1424 foreach ($courses as $course) {
1426 // If the user has never entered into the course all posts are pending
1427 if ($course->lastaccess == 0) {
1428 $coursessqls[] = '(d.course = ?)';
1429 $params[] = $course->id;
1431 // Only posts created after the course last access
1432 } else {
1433 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1434 $params[] = $course->id;
1435 $params[] = $course->lastaccess;
1438 $params[] = $USER->id;
1439 $coursessql = implode(' OR ', $coursessqls);
1441 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1442 .'FROM {forum_discussions} d '
1443 .'JOIN {forum_posts} p ON p.discussion = d.id '
1444 ."WHERE ($coursessql) "
1445 .'AND p.userid != ? '
1446 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
1447 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1448 .'ORDER BY d.course, d.forum';
1449 $params[] = time();
1450 $params[] = time();
1452 // Avoid warnings.
1453 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1454 $discussions = array();
1457 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1459 // also get all forum tracking stuff ONCE.
1460 $trackingforums = array();
1461 foreach ($forums as $forum) {
1462 if (forum_tp_can_track_forums($forum)) {
1463 $trackingforums[$forum->id] = $forum;
1467 if (count($trackingforums) > 0) {
1468 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1469 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1470 ' FROM {forum_posts} p '.
1471 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1472 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1473 $params = array($USER->id);
1475 foreach ($trackingforums as $track) {
1476 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1477 $params[] = $track->id;
1478 if (isset($SESSION->currentgroup[$track->course])) {
1479 $groupid = $SESSION->currentgroup[$track->course];
1480 } else {
1481 // get first groupid
1482 $groupids = groups_get_all_groups($track->course, $USER->id);
1483 if ($groupids) {
1484 reset($groupids);
1485 $groupid = key($groupids);
1486 $SESSION->currentgroup[$track->course] = $groupid;
1487 } else {
1488 $groupid = 0;
1490 unset($groupids);
1492 $params[] = $groupid;
1494 $sql = substr($sql,0,-3); // take off the last OR
1495 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1496 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1497 $sql .= 'GROUP BY d.forum,d.course';
1498 $params[] = $cutoffdate;
1499 $params[] = time();
1500 $params[] = time();
1502 if (!$unread = $DB->get_records_sql($sql, $params)) {
1503 $unread = array();
1505 } else {
1506 $unread = array();
1509 if (empty($unread) and empty($forumsnewposts)) {
1510 return;
1513 $strforum = get_string('modulename','forum');
1515 foreach ($forums as $forum) {
1516 $str = '';
1517 $count = 0;
1518 $thisunread = 0;
1519 $showunread = false;
1520 // either we have something from logs, or trackposts, or nothing.
1521 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1522 $count = $forumsnewposts[$forum->id]->count;
1524 if (array_key_exists($forum->id,$unread)) {
1525 $thisunread = $unread[$forum->id]->count;
1526 $showunread = true;
1528 if ($count > 0 || $thisunread > 0) {
1529 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1530 $forum->name.'</a></div>';
1531 $str .= '<div class="info"><span class="postsincelogin">';
1532 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1533 if (!empty($showunread)) {
1534 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1536 $str .= '</div></div>';
1538 if (!empty($str)) {
1539 if (!array_key_exists($forum->course,$htmlarray)) {
1540 $htmlarray[$forum->course] = array();
1542 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1543 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1545 $htmlarray[$forum->course]['forum'] .= $str;
1551 * Given a course and a date, prints a summary of all the new
1552 * messages posted in the course since that date
1554 * @global object
1555 * @global object
1556 * @global object
1557 * @uses CONTEXT_MODULE
1558 * @uses VISIBLEGROUPS
1559 * @param object $course
1560 * @param bool $viewfullnames capability
1561 * @param int $timestart
1562 * @return bool success
1564 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1565 global $CFG, $USER, $DB, $OUTPUT;
1567 // do not use log table if possible, it may be huge and is expensive to join with other tables
1569 $allnamefields = user_picture::fields('u', null, 'duserid');
1570 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1571 d.timestart, d.timeend, $allnamefields
1572 FROM {forum_posts} p
1573 JOIN {forum_discussions} d ON d.id = p.discussion
1574 JOIN {forum} f ON f.id = d.forum
1575 JOIN {user} u ON u.id = p.userid
1576 WHERE p.created > ? AND f.course = ?
1577 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1578 return false;
1581 $modinfo = get_fast_modinfo($course);
1583 $groupmodes = array();
1584 $cms = array();
1586 $strftimerecent = get_string('strftimerecent');
1588 $printposts = array();
1589 foreach ($posts as $post) {
1590 if (!isset($modinfo->instances['forum'][$post->forum])) {
1591 // not visible
1592 continue;
1594 $cm = $modinfo->instances['forum'][$post->forum];
1595 if (!$cm->uservisible) {
1596 continue;
1598 $context = context_module::instance($cm->id);
1600 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1601 continue;
1604 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1605 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1606 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1607 continue;
1611 // Check that the user can see the discussion.
1612 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1613 $printposts[] = $post;
1617 unset($posts);
1619 if (!$printposts) {
1620 return false;
1623 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1624 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
1626 foreach ($printposts as $post) {
1627 $subjectclass = empty($post->parent) ? ' bold' : '';
1628 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
1630 $list .= html_writer::start_tag('li');
1631 $list .= html_writer::start_div('head');
1632 $list .= html_writer::div(userdate($post->modified, $strftimerecent), 'date');
1633 if (!$authorhidden) {
1634 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
1636 $list .= html_writer::end_div(); // Head.
1638 $list .= html_writer::start_div('info' . $subjectclass);
1639 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
1640 if (!empty($post->parent)) {
1641 $discussionurl->param('parent', $post->parent);
1642 $discussionurl->set_anchor('p'. $post->id);
1644 $post->subject = break_up_long_words(format_string($post->subject, true));
1645 $list .= html_writer::link($discussionurl, $post->subject);
1646 $list .= html_writer::end_div(); // Info.
1647 $list .= html_writer::end_tag('li');
1650 $list .= html_writer::end_tag('ul');
1651 echo $list;
1653 return true;
1657 * Return grade for given user or all users.
1659 * @global object
1660 * @global object
1661 * @param object $forum
1662 * @param int $userid optional user id, 0 means all users
1663 * @return array array of grades, false if none
1665 function forum_get_user_grades($forum, $userid = 0) {
1666 global $CFG;
1668 require_once($CFG->dirroot.'/rating/lib.php');
1670 $ratingoptions = new stdClass;
1671 $ratingoptions->component = 'mod_forum';
1672 $ratingoptions->ratingarea = 'post';
1674 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1675 $ratingoptions->modulename = 'forum';
1676 $ratingoptions->moduleid = $forum->id;
1677 $ratingoptions->userid = $userid;
1678 $ratingoptions->aggregationmethod = $forum->assessed;
1679 $ratingoptions->scaleid = $forum->scale;
1680 $ratingoptions->itemtable = 'forum_posts';
1681 $ratingoptions->itemtableusercolumn = 'userid';
1683 $rm = new rating_manager();
1684 return $rm->get_user_grades($ratingoptions);
1688 * Update activity grades
1690 * @category grade
1691 * @param object $forum
1692 * @param int $userid specific user only, 0 means all
1693 * @param boolean $nullifnone return null if grade does not exist
1694 * @return void
1696 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1697 global $CFG, $DB;
1698 require_once($CFG->libdir.'/gradelib.php');
1700 if (!$forum->assessed) {
1701 forum_grade_item_update($forum);
1703 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1704 forum_grade_item_update($forum, $grades);
1706 } else if ($userid and $nullifnone) {
1707 $grade = new stdClass();
1708 $grade->userid = $userid;
1709 $grade->rawgrade = NULL;
1710 forum_grade_item_update($forum, $grade);
1712 } else {
1713 forum_grade_item_update($forum);
1718 * Create/update grade item for given forum
1720 * @category grade
1721 * @uses GRADE_TYPE_NONE
1722 * @uses GRADE_TYPE_VALUE
1723 * @uses GRADE_TYPE_SCALE
1724 * @param stdClass $forum Forum object with extra cmidnumber
1725 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1726 * @return int 0 if ok
1728 function forum_grade_item_update($forum, $grades=NULL) {
1729 global $CFG;
1730 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1731 require_once($CFG->libdir.'/gradelib.php');
1734 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1736 if (!$forum->assessed or $forum->scale == 0) {
1737 $params['gradetype'] = GRADE_TYPE_NONE;
1739 } else if ($forum->scale > 0) {
1740 $params['gradetype'] = GRADE_TYPE_VALUE;
1741 $params['grademax'] = $forum->scale;
1742 $params['grademin'] = 0;
1744 } else if ($forum->scale < 0) {
1745 $params['gradetype'] = GRADE_TYPE_SCALE;
1746 $params['scaleid'] = -$forum->scale;
1749 if ($grades === 'reset') {
1750 $params['reset'] = true;
1751 $grades = NULL;
1754 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1758 * Delete grade item for given forum
1760 * @category grade
1761 * @param stdClass $forum Forum object
1762 * @return grade_item
1764 function forum_grade_item_delete($forum) {
1765 global $CFG;
1766 require_once($CFG->libdir.'/gradelib.php');
1768 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1773 * This function returns if a scale is being used by one forum
1775 * @global object
1776 * @param int $forumid
1777 * @param int $scaleid negative number
1778 * @return bool
1780 function forum_scale_used ($forumid,$scaleid) {
1781 global $DB;
1782 $return = false;
1784 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1786 if (!empty($rec) && !empty($scaleid)) {
1787 $return = true;
1790 return $return;
1794 * Checks if scale is being used by any instance of forum
1796 * This is used to find out if scale used anywhere
1798 * @global object
1799 * @param $scaleid int
1800 * @return boolean True if the scale is used by any forum
1802 function forum_scale_used_anywhere($scaleid) {
1803 global $DB;
1804 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1805 return true;
1806 } else {
1807 return false;
1811 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1814 * Gets a post with all info ready for forum_print_post
1815 * Most of these joins are just to get the forum id
1817 * @global object
1818 * @global object
1819 * @param int $postid
1820 * @return mixed array of posts or false
1822 function forum_get_post_full($postid) {
1823 global $CFG, $DB;
1825 $allnames = get_all_user_name_fields(true, 'u');
1826 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1827 FROM {forum_posts} p
1828 JOIN {forum_discussions} d ON p.discussion = d.id
1829 LEFT JOIN {user} u ON p.userid = u.id
1830 WHERE p.id = ?", array($postid));
1834 * Gets all posts in discussion including top parent.
1836 * @global object
1837 * @global object
1838 * @global object
1839 * @param int $discussionid
1840 * @param string $sort
1841 * @param bool $tracking does user track the forum?
1842 * @return array of posts
1844 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1845 global $CFG, $DB, $USER;
1847 $tr_sel = "";
1848 $tr_join = "";
1849 $params = array();
1851 if ($tracking) {
1852 $tr_sel = ", fr.id AS postread";
1853 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1854 $params[] = $USER->id;
1857 $allnames = get_all_user_name_fields(true, 'u');
1858 $params[] = $discussionid;
1859 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1860 FROM {forum_posts} p
1861 LEFT JOIN {user} u ON p.userid = u.id
1862 $tr_join
1863 WHERE p.discussion = ?
1864 ORDER BY $sort", $params)) {
1865 return array();
1868 foreach ($posts as $pid=>$p) {
1869 if ($tracking) {
1870 if (forum_tp_is_post_old($p)) {
1871 $posts[$pid]->postread = true;
1874 if (!$p->parent) {
1875 continue;
1877 if (!isset($posts[$p->parent])) {
1878 continue; // parent does not exist??
1880 if (!isset($posts[$p->parent]->children)) {
1881 $posts[$p->parent]->children = array();
1883 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1886 // Start with the last child of the first post.
1887 $post = &$posts[reset($posts)->id];
1889 $lastpost = false;
1890 while (!$lastpost) {
1891 if (!isset($post->children)) {
1892 $post->lastpost = true;
1893 $lastpost = true;
1894 } else {
1895 // Go to the last child of this post.
1896 $post = &$posts[end($post->children)->id];
1900 return $posts;
1904 * An array of forum objects that the user is allowed to read/search through.
1906 * @global object
1907 * @global object
1908 * @global object
1909 * @param int $userid
1910 * @param int $courseid if 0, we look for forums throughout the whole site.
1911 * @return array of forum objects, or false if no matches
1912 * Forum objects have the following attributes:
1913 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1914 * viewhiddentimedposts
1916 function forum_get_readable_forums($userid, $courseid=0) {
1918 global $CFG, $DB, $USER;
1919 require_once($CFG->dirroot.'/course/lib.php');
1921 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1922 print_error('notinstalled', 'forum');
1925 if ($courseid) {
1926 $courses = $DB->get_records('course', array('id' => $courseid));
1927 } else {
1928 // If no course is specified, then the user can see SITE + his courses.
1929 $courses1 = $DB->get_records('course', array('id' => SITEID));
1930 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1931 $courses = array_merge($courses1, $courses2);
1933 if (!$courses) {
1934 return array();
1937 $readableforums = array();
1939 foreach ($courses as $course) {
1941 $modinfo = get_fast_modinfo($course);
1943 if (empty($modinfo->instances['forum'])) {
1944 // hmm, no forums?
1945 continue;
1948 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1950 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1951 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1952 continue;
1954 $context = context_module::instance($cm->id);
1955 $forum = $courseforums[$forumid];
1956 $forum->context = $context;
1957 $forum->cm = $cm;
1959 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1960 continue;
1963 /// group access
1964 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1966 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1967 $forum->onlygroups[] = -1;
1970 /// hidden timed discussions
1971 $forum->viewhiddentimedposts = true;
1972 if (!empty($CFG->forum_enabletimedposts)) {
1973 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1974 $forum->viewhiddentimedposts = false;
1978 /// qanda access
1979 if ($forum->type == 'qanda'
1980 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1982 // We need to check whether the user has posted in the qanda forum.
1983 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1984 // the user is allowed to see in this forum.
1985 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1986 foreach ($discussionspostedin as $d) {
1987 $forum->onlydiscussions[] = $d->id;
1992 $readableforums[$forum->id] = $forum;
1995 unset($modinfo);
1997 } // End foreach $courses
1999 return $readableforums;
2003 * Returns a list of posts found using an array of search terms.
2005 * @global object
2006 * @global object
2007 * @global object
2008 * @param array $searchterms array of search terms, e.g. word +word -word
2009 * @param int $courseid if 0, we search through the whole site
2010 * @param int $limitfrom
2011 * @param int $limitnum
2012 * @param int &$totalcount
2013 * @param string $extrasql
2014 * @return array|bool Array of posts found or false
2016 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2017 &$totalcount, $extrasql='') {
2018 global $CFG, $DB, $USER;
2019 require_once($CFG->libdir.'/searchlib.php');
2021 $forums = forum_get_readable_forums($USER->id, $courseid);
2023 if (count($forums) == 0) {
2024 $totalcount = 0;
2025 return false;
2028 $now = floor(time() / 60) * 60; // DB Cache Friendly.
2030 $fullaccess = array();
2031 $where = array();
2032 $params = array();
2034 foreach ($forums as $forumid => $forum) {
2035 $select = array();
2037 if (!$forum->viewhiddentimedposts) {
2038 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2039 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2042 $cm = $forum->cm;
2043 $context = $forum->context;
2045 if ($forum->type == 'qanda'
2046 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2047 if (!empty($forum->onlydiscussions)) {
2048 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2049 $params = array_merge($params, $discussionid_params);
2050 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2051 } else {
2052 $select[] = "p.parent = 0";
2056 if (!empty($forum->onlygroups)) {
2057 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2058 $params = array_merge($params, $groupid_params);
2059 $select[] = "d.groupid $groupid_sql";
2062 if ($select) {
2063 $selects = implode(" AND ", $select);
2064 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2065 $params['forum'.$forumid] = $forumid;
2066 } else {
2067 $fullaccess[] = $forumid;
2071 if ($fullaccess) {
2072 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2073 $params = array_merge($params, $fullid_params);
2074 $where[] = "(d.forum $fullid_sql)";
2077 $selectdiscussion = "(".implode(" OR ", $where).")";
2079 $messagesearch = '';
2080 $searchstring = '';
2082 // Need to concat these back together for parser to work.
2083 foreach($searchterms as $searchterm){
2084 if ($searchstring != '') {
2085 $searchstring .= ' ';
2087 $searchstring .= $searchterm;
2090 // We need to allow quoted strings for the search. The quotes *should* be stripped
2091 // by the parser, but this should be examined carefully for security implications.
2092 $searchstring = str_replace("\\\"","\"",$searchstring);
2093 $parser = new search_parser();
2094 $lexer = new search_lexer($parser);
2096 if ($lexer->parse($searchstring)) {
2097 $parsearray = $parser->get_parsed_array();
2099 $tagjoins = '';
2100 $tagfields = [];
2101 $tagfieldcount = 0;
2102 foreach ($parsearray as $token) {
2103 if ($token->getType() == TOKEN_TAGS) {
2104 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
2105 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
2106 if ($tagfieldcount > 10) {
2107 continue;
2109 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
2110 ON p.id = ti_$tagfieldcount.itemid
2111 AND ti_$tagfieldcount.component = 'mod_forum'
2112 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
2113 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
2114 $tagfields[] = "t_$tagfieldcount.rawname";
2115 $tagfieldcount++;
2119 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2120 'p.userid', 'u.id', 'u.firstname',
2121 'u.lastname', 'p.modified', 'd.forum',
2122 $tagfields);
2123 $params = array_merge($params, $msparams);
2126 $fromsql = "{forum_posts} p
2127 INNER JOIN {forum_discussions} d ON d.id = p.discussion
2128 INNER JOIN {user} u ON u.id = p.userid $tagjoins";
2130 $selectsql = " $messagesearch
2131 AND p.discussion = d.id
2132 AND p.userid = u.id
2133 AND $selectdiscussion
2134 $extrasql";
2136 $countsql = "SELECT COUNT(*)
2137 FROM $fromsql
2138 WHERE $selectsql";
2140 $allnames = get_all_user_name_fields(true, 'u');
2141 $searchsql = "SELECT p.*,
2142 d.forum,
2143 $allnames,
2144 u.email,
2145 u.picture,
2146 u.imagealt
2147 FROM $fromsql
2148 WHERE $selectsql
2149 ORDER BY p.modified DESC";
2151 $totalcount = $DB->count_records_sql($countsql, $params);
2153 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2157 * Returns a list of all new posts that have not been mailed yet
2159 * @param int $starttime posts created after this time
2160 * @param int $endtime posts created before this
2161 * @param int $now used for timed discussions only
2162 * @return array
2164 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2165 global $CFG, $DB;
2167 $params = array();
2168 $params['mailed'] = FORUM_MAILED_PENDING;
2169 $params['ptimestart'] = $starttime;
2170 $params['ptimeend'] = $endtime;
2171 $params['mailnow'] = 1;
2173 if (!empty($CFG->forum_enabletimedposts)) {
2174 if (empty($now)) {
2175 $now = time();
2177 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2178 $params['pptimestart'] = $starttime;
2179 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2180 $params['dtimestart'] = $now;
2181 $params['dtimeend'] = $now;
2182 } else {
2183 $timedsql = "";
2184 $selectsql = "AND p.created >= :ptimestart";
2187 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2188 FROM {forum_posts} p
2189 JOIN {forum_discussions} d ON d.id = p.discussion
2190 WHERE p.mailed = :mailed
2191 $selectsql
2192 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2193 $timedsql
2194 ORDER BY p.modified ASC", $params);
2198 * Marks posts before a certain time as being mailed already
2200 * @global object
2201 * @global object
2202 * @param int $endtime
2203 * @param int $now Defaults to time()
2204 * @return bool
2206 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2207 global $CFG, $DB;
2209 if (empty($now)) {
2210 $now = time();
2213 $params = array();
2214 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2215 $params['now'] = $now;
2216 $params['endtime'] = $endtime;
2217 $params['mailnow'] = 1;
2218 $params['mailedpending'] = FORUM_MAILED_PENDING;
2220 if (empty($CFG->forum_enabletimedposts)) {
2221 return $DB->execute("UPDATE {forum_posts}
2222 SET mailed = :mailedsuccess
2223 WHERE (created < :endtime OR mailnow = :mailnow)
2224 AND mailed = :mailedpending", $params);
2225 } else {
2226 return $DB->execute("UPDATE {forum_posts}
2227 SET mailed = :mailedsuccess
2228 WHERE discussion NOT IN (SELECT d.id
2229 FROM {forum_discussions} d
2230 WHERE d.timestart > :now)
2231 AND (created < :endtime OR mailnow = :mailnow)
2232 AND mailed = :mailedpending", $params);
2237 * Get all the posts for a user in a forum suitable for forum_print_post
2239 * @global object
2240 * @global object
2241 * @uses CONTEXT_MODULE
2242 * @return array
2244 function forum_get_user_posts($forumid, $userid) {
2245 global $CFG, $DB;
2247 $timedsql = "";
2248 $params = array($forumid, $userid);
2250 if (!empty($CFG->forum_enabletimedposts)) {
2251 $cm = get_coursemodule_from_instance('forum', $forumid);
2252 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2253 $now = time();
2254 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2255 $params[] = $now;
2256 $params[] = $now;
2260 $allnames = get_all_user_name_fields(true, 'u');
2261 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2262 FROM {forum} f
2263 JOIN {forum_discussions} d ON d.forum = f.id
2264 JOIN {forum_posts} p ON p.discussion = d.id
2265 JOIN {user} u ON u.id = p.userid
2266 WHERE f.id = ?
2267 AND p.userid = ?
2268 $timedsql
2269 ORDER BY p.modified ASC", $params);
2273 * Get all the discussions user participated in
2275 * @global object
2276 * @global object
2277 * @uses CONTEXT_MODULE
2278 * @param int $forumid
2279 * @param int $userid
2280 * @return array Array or false
2282 function forum_get_user_involved_discussions($forumid, $userid) {
2283 global $CFG, $DB;
2285 $timedsql = "";
2286 $params = array($forumid, $userid);
2287 if (!empty($CFG->forum_enabletimedposts)) {
2288 $cm = get_coursemodule_from_instance('forum', $forumid);
2289 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2290 $now = time();
2291 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2292 $params[] = $now;
2293 $params[] = $now;
2297 return $DB->get_records_sql("SELECT DISTINCT d.*
2298 FROM {forum} f
2299 JOIN {forum_discussions} d ON d.forum = f.id
2300 JOIN {forum_posts} p ON p.discussion = d.id
2301 WHERE f.id = ?
2302 AND p.userid = ?
2303 $timedsql", $params);
2307 * Get all the posts for a user in a forum suitable for forum_print_post
2309 * @global object
2310 * @global object
2311 * @param int $forumid
2312 * @param int $userid
2313 * @return array of counts or false
2315 function forum_count_user_posts($forumid, $userid) {
2316 global $CFG, $DB;
2318 $timedsql = "";
2319 $params = array($forumid, $userid);
2320 if (!empty($CFG->forum_enabletimedposts)) {
2321 $cm = get_coursemodule_from_instance('forum', $forumid);
2322 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2323 $now = time();
2324 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2325 $params[] = $now;
2326 $params[] = $now;
2330 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2331 FROM {forum} f
2332 JOIN {forum_discussions} d ON d.forum = f.id
2333 JOIN {forum_posts} p ON p.discussion = d.id
2334 JOIN {user} u ON u.id = p.userid
2335 WHERE f.id = ?
2336 AND p.userid = ?
2337 $timedsql", $params);
2341 * Given a log entry, return the forum post details for it.
2343 * @global object
2344 * @global object
2345 * @param object $log
2346 * @return array|null
2348 function forum_get_post_from_log($log) {
2349 global $CFG, $DB;
2351 $allnames = get_all_user_name_fields(true, 'u');
2352 if ($log->action == "add post") {
2354 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2355 FROM {forum_discussions} d,
2356 {forum_posts} p,
2357 {forum} f,
2358 {user} u
2359 WHERE p.id = ?
2360 AND d.id = p.discussion
2361 AND p.userid = u.id
2362 AND u.deleted <> '1'
2363 AND f.id = d.forum", array($log->info));
2366 } else if ($log->action == "add discussion") {
2368 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2369 FROM {forum_discussions} d,
2370 {forum_posts} p,
2371 {forum} f,
2372 {user} u
2373 WHERE d.id = ?
2374 AND d.firstpost = p.id
2375 AND p.userid = u.id
2376 AND u.deleted <> '1'
2377 AND f.id = d.forum", array($log->info));
2379 return NULL;
2383 * Given a discussion id, return the first post from the discussion
2385 * @global object
2386 * @global object
2387 * @param int $dicsussionid
2388 * @return array
2390 function forum_get_firstpost_from_discussion($discussionid) {
2391 global $CFG, $DB;
2393 return $DB->get_record_sql("SELECT p.*
2394 FROM {forum_discussions} d,
2395 {forum_posts} p
2396 WHERE d.id = ?
2397 AND d.firstpost = p.id ", array($discussionid));
2401 * Returns an array of counts of replies to each discussion
2403 * @global object
2404 * @global object
2405 * @param int $forumid
2406 * @param string $forumsort
2407 * @param int $limit
2408 * @param int $page
2409 * @param int $perpage
2410 * @return array
2412 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2413 global $CFG, $DB;
2415 if ($limit > 0) {
2416 $limitfrom = 0;
2417 $limitnum = $limit;
2418 } else if ($page != -1) {
2419 $limitfrom = $page*$perpage;
2420 $limitnum = $perpage;
2421 } else {
2422 $limitfrom = 0;
2423 $limitnum = 0;
2426 if ($forumsort == "") {
2427 $orderby = "";
2428 $groupby = "";
2430 } else {
2431 $orderby = "ORDER BY $forumsort";
2432 $groupby = ", ".strtolower($forumsort);
2433 $groupby = str_replace('desc', '', $groupby);
2434 $groupby = str_replace('asc', '', $groupby);
2437 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2438 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2439 FROM {forum_posts} p
2440 JOIN {forum_discussions} d ON p.discussion = d.id
2441 WHERE p.parent > 0 AND d.forum = ?
2442 GROUP BY p.discussion";
2443 return $DB->get_records_sql($sql, array($forumid));
2445 } else {
2446 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2447 FROM {forum_posts} p
2448 JOIN {forum_discussions} d ON p.discussion = d.id
2449 WHERE d.forum = ?
2450 GROUP BY p.discussion $groupby $orderby";
2451 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2456 * @global object
2457 * @global object
2458 * @global object
2459 * @staticvar array $cache
2460 * @param object $forum
2461 * @param object $cm
2462 * @param object $course
2463 * @return mixed
2465 function forum_count_discussions($forum, $cm, $course) {
2466 global $CFG, $DB, $USER;
2468 static $cache = array();
2470 $now = floor(time() / 60) * 60; // DB Cache Friendly.
2472 $params = array($course->id);
2474 if (!isset($cache[$course->id])) {
2475 if (!empty($CFG->forum_enabletimedposts)) {
2476 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2477 $params[] = $now;
2478 $params[] = $now;
2479 } else {
2480 $timedsql = "";
2483 $sql = "SELECT f.id, COUNT(d.id) as dcount
2484 FROM {forum} f
2485 JOIN {forum_discussions} d ON d.forum = f.id
2486 WHERE f.course = ?
2487 $timedsql
2488 GROUP BY f.id";
2490 if ($counts = $DB->get_records_sql($sql, $params)) {
2491 foreach ($counts as $count) {
2492 $counts[$count->id] = $count->dcount;
2494 $cache[$course->id] = $counts;
2495 } else {
2496 $cache[$course->id] = array();
2500 if (empty($cache[$course->id][$forum->id])) {
2501 return 0;
2504 $groupmode = groups_get_activity_groupmode($cm, $course);
2506 if ($groupmode != SEPARATEGROUPS) {
2507 return $cache[$course->id][$forum->id];
2510 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2511 return $cache[$course->id][$forum->id];
2514 require_once($CFG->dirroot.'/course/lib.php');
2516 $modinfo = get_fast_modinfo($course);
2518 $mygroups = $modinfo->get_groups($cm->groupingid);
2520 // add all groups posts
2521 $mygroups[-1] = -1;
2523 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2524 $params[] = $forum->id;
2526 if (!empty($CFG->forum_enabletimedposts)) {
2527 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2528 $params[] = $now;
2529 $params[] = $now;
2530 } else {
2531 $timedsql = "";
2534 $sql = "SELECT COUNT(d.id)
2535 FROM {forum_discussions} d
2536 WHERE d.groupid $mygroups_sql AND d.forum = ?
2537 $timedsql";
2539 return $DB->get_field_sql($sql, $params);
2543 * Get all discussions in a forum
2545 * @global object
2546 * @global object
2547 * @global object
2548 * @uses CONTEXT_MODULE
2549 * @uses VISIBLEGROUPS
2550 * @param object $cm
2551 * @param string $forumsort
2552 * @param bool $fullpost
2553 * @param int $unused
2554 * @param int $limit
2555 * @param bool $userlastmodified
2556 * @param int $page
2557 * @param int $perpage
2558 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2559 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
2560 * @param int $updatedsince retrieve only discussions updated since the given time
2561 * @return array
2563 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
2564 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
2565 $updatedsince = 0) {
2566 global $CFG, $DB, $USER;
2568 $timelimit = '';
2570 $now = floor(time() / 60) * 60;
2571 $params = array($cm->instance);
2573 $modcontext = context_module::instance($cm->id);
2575 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2576 return array();
2579 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2581 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2582 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2583 $params[] = $now;
2584 $params[] = $now;
2585 if (isloggedin()) {
2586 $timelimit .= " OR d.userid = ?";
2587 $params[] = $USER->id;
2589 $timelimit .= ")";
2593 if ($limit > 0) {
2594 $limitfrom = 0;
2595 $limitnum = $limit;
2596 } else if ($page != -1) {
2597 $limitfrom = $page*$perpage;
2598 $limitnum = $perpage;
2599 } else {
2600 $limitfrom = 0;
2601 $limitnum = 0;
2604 $groupmode = groups_get_activity_groupmode($cm);
2606 if ($groupmode) {
2608 if (empty($modcontext)) {
2609 $modcontext = context_module::instance($cm->id);
2612 // Special case, we received a groupid to override currentgroup.
2613 if ($groupid > 0) {
2614 $course = get_course($cm->course);
2615 if (!groups_group_visible($groupid, $course, $cm)) {
2616 // User doesn't belong to this group, return nothing.
2617 return array();
2619 $currentgroup = $groupid;
2620 } else if ($groupid === -1) {
2621 $currentgroup = groups_get_activity_group($cm);
2622 } else {
2623 // Get discussions for all groups current user can see.
2624 $currentgroup = null;
2627 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2628 if ($currentgroup) {
2629 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2630 $params[] = $currentgroup;
2631 } else {
2632 $groupselect = "";
2635 } else {
2636 // Separate groups.
2638 // Get discussions for all groups current user can see.
2639 if ($currentgroup === null) {
2640 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
2641 if (empty($mygroups)) {
2642 $groupselect = "AND d.groupid = -1";
2643 } else {
2644 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2645 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2646 $params = array_merge($params, $inparamsgroups);
2648 } else if ($currentgroup) {
2649 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2650 $params[] = $currentgroup;
2651 } else {
2652 $groupselect = "AND d.groupid = -1";
2655 } else {
2656 $groupselect = "";
2658 if (empty($forumsort)) {
2659 $forumsort = forum_get_default_sort_order();
2661 if (empty($fullpost)) {
2662 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2663 } else {
2664 $postdata = "p.*";
2667 if (empty($userlastmodified)) { // We don't need to know this
2668 $umfields = "";
2669 $umtable = "";
2670 } else {
2671 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2672 um.imagealt AS umimagealt';
2673 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2676 $updatedsincesql = '';
2677 if (!empty($updatedsince)) {
2678 $updatedsincesql = 'AND d.timemodified > ?';
2679 $params[] = $updatedsince;
2682 $allnames = get_all_user_name_fields(true, 'u');
2683 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
2684 u.email, u.picture, u.imagealt $umfields
2685 FROM {forum_discussions} d
2686 JOIN {forum_posts} p ON p.discussion = d.id
2687 JOIN {user} u ON p.userid = u.id
2688 $umtable
2689 WHERE d.forum = ? AND p.parent = 0
2690 $timelimit $groupselect $updatedsincesql
2691 ORDER BY $forumsort, d.id DESC";
2693 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2697 * Gets the neighbours (previous and next) of a discussion.
2699 * The calculation is based on the timemodified when time modified or time created is identical
2700 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
2702 * For blog-style forums, the calculation is based on the original creation time of the
2703 * blog post.
2705 * Please note that this does not check whether or not the discussion passed is accessible
2706 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2707 * the returned neighbours are checked and are accessible to the current user.
2709 * @param object $cm The CM record.
2710 * @param object $discussion The discussion record.
2711 * @param object $forum The forum instance record.
2712 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2713 * they contain the record with minimal information such as 'id' and 'name'.
2714 * When the neighbour is not found the value is false.
2716 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
2717 global $CFG, $DB, $USER;
2719 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
2720 throw new coding_exception('Discussion is not part of the same forum.');
2723 $neighbours = array('prev' => false, 'next' => false);
2724 $now = floor(time() / 60) * 60;
2725 $params = array();
2727 $modcontext = context_module::instance($cm->id);
2728 $groupmode = groups_get_activity_groupmode($cm);
2729 $currentgroup = groups_get_activity_group($cm);
2731 // Users must fulfill timed posts.
2732 $timelimit = '';
2733 if (!empty($CFG->forum_enabletimedposts)) {
2734 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2735 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2736 $params['tltimestart'] = $now;
2737 $params['tltimeend'] = $now;
2738 if (isloggedin()) {
2739 $timelimit .= ' OR d.userid = :tluserid';
2740 $params['tluserid'] = $USER->id;
2742 $timelimit .= ')';
2746 // Limiting to posts accessible according to groups.
2747 $groupselect = '';
2748 if ($groupmode) {
2749 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2750 if ($currentgroup) {
2751 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2752 $params['groupid'] = $currentgroup;
2754 } else {
2755 if ($currentgroup) {
2756 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2757 $params['groupid'] = $currentgroup;
2758 } else {
2759 $groupselect = 'AND d.groupid = -1';
2764 $params['forumid'] = $cm->instance;
2765 $params['discid1'] = $discussion->id;
2766 $params['discid2'] = $discussion->id;
2767 $params['discid3'] = $discussion->id;
2768 $params['discid4'] = $discussion->id;
2769 $params['disctimecompare1'] = $discussion->timemodified;
2770 $params['disctimecompare2'] = $discussion->timemodified;
2771 $params['pinnedstate1'] = (int) $discussion->pinned;
2772 $params['pinnedstate2'] = (int) $discussion->pinned;
2773 $params['pinnedstate3'] = (int) $discussion->pinned;
2774 $params['pinnedstate4'] = (int) $discussion->pinned;
2776 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2777 FROM {forum_discussions} d
2778 JOIN {forum_posts} p ON d.firstpost = p.id
2779 WHERE d.forum = :forumid
2780 AND d.id <> :discid1
2781 $timelimit
2782 $groupselect";
2783 $comparefield = "d.timemodified";
2784 $comparevalue = ":disctimecompare1";
2785 $comparevalue2 = ":disctimecompare2";
2786 if (!empty($CFG->forum_enabletimedposts)) {
2787 // Here we need to take into account the release time (timestart)
2788 // if one is set, of the neighbouring posts and compare it to the
2789 // timestart or timemodified of *this* post depending on if the
2790 // release date of this post is in the future or not.
2791 // This stops discussions that appear later because of the
2792 // timestart value from being buried under discussions that were
2793 // made afterwards.
2794 $comparefield = "CASE WHEN d.timemodified < d.timestart
2795 THEN d.timestart ELSE d.timemodified END";
2796 if ($discussion->timemodified < $discussion->timestart) {
2797 // Normally we would just use the timemodified for sorting
2798 // discussion posts. However, when timed discussions are enabled,
2799 // then posts need to be sorted base on the later of timemodified
2800 // or the release date of the post (timestart).
2801 $params['disctimecompare1'] = $discussion->timestart;
2802 $params['disctimecompare2'] = $discussion->timestart;
2805 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2806 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
2808 if ($forum->type === 'blog') {
2809 $subselect = "SELECT pp.created
2810 FROM {forum_discussions} dd
2811 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
2813 $subselectwhere1 = " WHERE dd.id = :discid3";
2814 $subselectwhere2 = " WHERE dd.id = :discid4";
2816 $comparefield = "p.created";
2818 $sub1 = $subselect.$subselectwhere1;
2819 $comparevalue = "($sub1)";
2821 $sub2 = $subselect.$subselectwhere2;
2822 $comparevalue2 = "($sub2)";
2824 $orderbydesc = "d.pinned, p.created DESC";
2825 $orderbyasc = "d.pinned, p.created ASC";
2828 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2829 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2830 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2831 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
2833 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2834 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2835 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2836 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
2838 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2839 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2840 return $neighbours;
2844 * Get the sql to use in the ORDER BY clause for forum discussions.
2846 * This has the ordering take timed discussion windows into account.
2848 * @param bool $desc True for DESC, False for ASC.
2849 * @param string $compare The field in the SQL to compare to normally sort by.
2850 * @param string $prefix The prefix being used for the discussion table.
2851 * @param bool $pinned sort pinned posts to the top
2852 * @return string
2854 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
2855 global $CFG;
2857 if (!empty($prefix)) {
2858 $prefix .= '.';
2861 $dir = $desc ? 'DESC' : 'ASC';
2863 if ($pinned == true) {
2864 $pinned = "{$prefix}pinned DESC,";
2865 } else {
2866 $pinned = '';
2869 $sort = "{$prefix}timemodified";
2870 if (!empty($CFG->forum_enabletimedposts)) {
2871 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2872 THEN {$prefix}timestart
2873 ELSE {$compare}
2874 END";
2876 return "$pinned $sort $dir";
2881 * @global object
2882 * @global object
2883 * @global object
2884 * @uses CONTEXT_MODULE
2885 * @uses VISIBLEGROUPS
2886 * @param object $cm
2887 * @return array
2889 function forum_get_discussions_unread($cm) {
2890 global $CFG, $DB, $USER;
2892 $now = floor(time() / 60) * 60;
2893 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2895 $params = array();
2896 $groupmode = groups_get_activity_groupmode($cm);
2897 $currentgroup = groups_get_activity_group($cm);
2899 if ($groupmode) {
2900 $modcontext = context_module::instance($cm->id);
2902 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2903 if ($currentgroup) {
2904 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2905 $params['currentgroup'] = $currentgroup;
2906 } else {
2907 $groupselect = "";
2910 } else {
2911 //separate groups without access all
2912 if ($currentgroup) {
2913 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2914 $params['currentgroup'] = $currentgroup;
2915 } else {
2916 $groupselect = "AND d.groupid = -1";
2919 } else {
2920 $groupselect = "";
2923 if (!empty($CFG->forum_enabletimedposts)) {
2924 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2925 $params['now1'] = $now;
2926 $params['now2'] = $now;
2927 } else {
2928 $timedsql = "";
2931 $sql = "SELECT d.id, COUNT(p.id) AS unread
2932 FROM {forum_discussions} d
2933 JOIN {forum_posts} p ON p.discussion = d.id
2934 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2935 WHERE d.forum = {$cm->instance}
2936 AND p.modified >= :cutoffdate AND r.id is NULL
2937 $groupselect
2938 $timedsql
2939 GROUP BY d.id";
2940 $params['cutoffdate'] = $cutoffdate;
2942 if ($unreads = $DB->get_records_sql($sql, $params)) {
2943 foreach ($unreads as $unread) {
2944 $unreads[$unread->id] = $unread->unread;
2946 return $unreads;
2947 } else {
2948 return array();
2953 * @global object
2954 * @global object
2955 * @global object
2956 * @uses CONEXT_MODULE
2957 * @uses VISIBLEGROUPS
2958 * @param object $cm
2959 * @return array
2961 function forum_get_discussions_count($cm) {
2962 global $CFG, $DB, $USER;
2964 $now = floor(time() / 60) * 60;
2965 $params = array($cm->instance);
2966 $groupmode = groups_get_activity_groupmode($cm);
2967 $currentgroup = groups_get_activity_group($cm);
2969 if ($groupmode) {
2970 $modcontext = context_module::instance($cm->id);
2972 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2973 if ($currentgroup) {
2974 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2975 $params[] = $currentgroup;
2976 } else {
2977 $groupselect = "";
2980 } else {
2981 //seprate groups without access all
2982 if ($currentgroup) {
2983 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2984 $params[] = $currentgroup;
2985 } else {
2986 $groupselect = "AND d.groupid = -1";
2989 } else {
2990 $groupselect = "";
2993 $timelimit = "";
2995 if (!empty($CFG->forum_enabletimedposts)) {
2997 $modcontext = context_module::instance($cm->id);
2999 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
3000 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
3001 $params[] = $now;
3002 $params[] = $now;
3003 if (isloggedin()) {
3004 $timelimit .= " OR d.userid = ?";
3005 $params[] = $USER->id;
3007 $timelimit .= ")";
3011 $sql = "SELECT COUNT(d.id)
3012 FROM {forum_discussions} d
3013 JOIN {forum_posts} p ON p.discussion = d.id
3014 WHERE d.forum = ? AND p.parent = 0
3015 $groupselect $timelimit";
3017 return $DB->get_field_sql($sql, $params);
3021 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
3025 * @global object
3026 * @global object
3027 * @param int $courseid
3028 * @param string $type
3030 function forum_get_course_forum($courseid, $type) {
3031 // How to set up special 1-per-course forums
3032 global $CFG, $DB, $OUTPUT, $USER;
3034 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
3035 // There should always only be ONE, but with the right combination of
3036 // errors there might be more. In this case, just return the oldest one (lowest ID).
3037 foreach ($forums as $forum) {
3038 return $forum; // ie the first one
3042 // Doesn't exist, so create one now.
3043 $forum = new stdClass();
3044 $forum->course = $courseid;
3045 $forum->type = "$type";
3046 if (!empty($USER->htmleditor)) {
3047 $forum->introformat = $USER->htmleditor;
3049 switch ($forum->type) {
3050 case "news":
3051 $forum->name = get_string("namenews", "forum");
3052 $forum->intro = get_string("intronews", "forum");
3053 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
3054 $forum->assessed = 0;
3055 if ($courseid == SITEID) {
3056 $forum->name = get_string("sitenews");
3057 $forum->forcesubscribe = 0;
3059 break;
3060 case "social":
3061 $forum->name = get_string("namesocial", "forum");
3062 $forum->intro = get_string("introsocial", "forum");
3063 $forum->assessed = 0;
3064 $forum->forcesubscribe = 0;
3065 break;
3066 case "blog":
3067 $forum->name = get_string('blogforum', 'forum');
3068 $forum->intro = get_string('introblog', 'forum');
3069 $forum->assessed = 0;
3070 $forum->forcesubscribe = 0;
3071 break;
3072 default:
3073 echo $OUTPUT->notification("That forum type doesn't exist!");
3074 return false;
3075 break;
3078 $forum->timemodified = time();
3079 $forum->id = $DB->insert_record("forum", $forum);
3081 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
3082 echo $OUTPUT->notification("Could not find forum module!!");
3083 return false;
3085 $mod = new stdClass();
3086 $mod->course = $courseid;
3087 $mod->module = $module->id;
3088 $mod->instance = $forum->id;
3089 $mod->section = 0;
3090 include_once("$CFG->dirroot/course/lib.php");
3091 if (! $mod->coursemodule = add_course_module($mod) ) {
3092 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3093 return false;
3095 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3096 return $DB->get_record("forum", array("id" => "$forum->id"));
3100 * Print a forum post
3102 * @global object
3103 * @global object
3104 * @uses FORUM_MODE_THREADED
3105 * @uses PORTFOLIO_FORMAT_PLAINHTML
3106 * @uses PORTFOLIO_FORMAT_FILE
3107 * @uses PORTFOLIO_FORMAT_RICHHTML
3108 * @uses PORTFOLIO_ADD_TEXT_LINK
3109 * @uses CONTEXT_MODULE
3110 * @param object $post The post to print.
3111 * @param object $discussion
3112 * @param object $forum
3113 * @param object $cm
3114 * @param object $course
3115 * @param boolean $ownpost Whether this post belongs to the current user.
3116 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3117 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3118 * @param string $footer Extra stuff to print after the message.
3119 * @param string $highlight Space-separated list of terms to highlight.
3120 * @param int $post_read true, false or -99. If we already know whether this user
3121 * has read this post, pass that in, otherwise, pass in -99, and this
3122 * function will work it out.
3123 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3124 * the current user can't see this post, if this argument is true
3125 * (the default) then print a dummy 'you can't see this post' post.
3126 * If false, don't output anything at all.
3127 * @param bool|null $istracked
3128 * @return void
3130 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3131 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3132 global $USER, $CFG, $OUTPUT;
3134 require_once($CFG->libdir . '/filelib.php');
3136 // String cache
3137 static $str;
3138 // This is an extremely hacky way to ensure we only print the 'unread' anchor
3139 // the first time we encounter an unread post on a page. Ideally this would
3140 // be moved into the caller somehow, and be better testable. But at the time
3141 // of dealing with this bug, this static workaround was the most surgical and
3142 // it fits together with only printing th unread anchor id once on a given page.
3143 static $firstunreadanchorprinted = false;
3145 $modcontext = context_module::instance($cm->id);
3147 $post->course = $course->id;
3148 $post->forum = $forum->id;
3149 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3150 if (!empty($CFG->enableplagiarism)) {
3151 require_once($CFG->libdir.'/plagiarismlib.php');
3152 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3153 'content' => $post->message,
3154 'cmid' => $cm->id,
3155 'course' => $post->course,
3156 'forum' => $post->forum));
3159 // caching
3160 if (!isset($cm->cache)) {
3161 $cm->cache = new stdClass;
3164 if (!isset($cm->cache->caps)) {
3165 $cm->cache->caps = array();
3166 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3167 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3168 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3169 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3170 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3171 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3172 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3173 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3174 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3177 if (!isset($cm->uservisible)) {
3178 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3181 if ($istracked && is_null($postisread)) {
3182 $postisread = forum_tp_is_post_read($USER->id, $post);
3185 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3186 $output = '';
3187 if (!$dummyifcantsee) {
3188 if ($return) {
3189 return $output;
3191 echo $output;
3192 return;
3194 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3195 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3196 'role' => 'region',
3197 'aria-label' => get_string('hiddenforumpost', 'forum')));
3198 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3199 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3200 if ($post->parent) {
3201 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3202 } else {
3203 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3205 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3206 'role' => 'header')); // Subject.
3207 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3208 'role' => 'header')); // Author.
3209 $output .= html_writer::end_tag('div');
3210 $output .= html_writer::end_tag('div'); // row
3211 $output .= html_writer::start_tag('div', array('class'=>'row'));
3212 $output .= html_writer::tag('div', '&nbsp;', array('class'=>'left side')); // Groups
3213 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3214 $output .= html_writer::end_tag('div'); // row
3215 $output .= html_writer::end_tag('div'); // forumpost
3217 if ($return) {
3218 return $output;
3220 echo $output;
3221 return;
3224 if (empty($str)) {
3225 $str = new stdClass;
3226 $str->edit = get_string('edit', 'forum');
3227 $str->delete = get_string('delete', 'forum');
3228 $str->reply = get_string('reply', 'forum');
3229 $str->parent = get_string('parent', 'forum');
3230 $str->pruneheading = get_string('pruneheading', 'forum');
3231 $str->prune = get_string('prune', 'forum');
3232 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3233 $str->markread = get_string('markread', 'forum');
3234 $str->markunread = get_string('markunread', 'forum');
3237 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3239 // Build an object that represents the posting user
3240 $postuser = new stdClass;
3241 $postuserfields = explode(',', user_picture::fields());
3242 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3243 $postuser->id = $post->userid;
3244 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3245 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3247 // Prepare the groups the posting user belongs to
3248 if (isset($cm->cache->usersgroups)) {
3249 $groups = array();
3250 if (isset($cm->cache->usersgroups[$post->userid])) {
3251 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3252 $groups[$gid] = $cm->cache->groups[$gid];
3255 } else {
3256 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3259 // Prepare the attachements for the post, files then images
3260 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3262 // Determine if we need to shorten this post
3263 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3266 // Prepare an array of commands
3267 $commands = array();
3269 // Add a permalink.
3270 $permalink = new moodle_url($discussionlink);
3271 $permalink->set_anchor('p' . $post->id);
3272 $commands[] = array('url' => $permalink, 'text' => get_string('permalink', 'forum'));
3274 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3275 // Don't display the mark read / unread controls in this case.
3276 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3277 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3278 $text = $str->markunread;
3279 if (!$postisread) {
3280 $url->param('mark', 'read');
3281 $text = $str->markread;
3283 if ($str->displaymode == FORUM_MODE_THREADED) {
3284 $url->param('parent', $post->parent);
3285 } else {
3286 $url->set_anchor('p'.$post->id);
3288 $commands[] = array('url'=>$url, 'text'=>$text);
3291 // Zoom in to the parent specifically
3292 if ($post->parent) {
3293 $url = new moodle_url($discussionlink);
3294 if ($str->displaymode == FORUM_MODE_THREADED) {
3295 $url->param('parent', $post->parent);
3296 } else {
3297 $url->set_anchor('p'.$post->parent);
3299 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3302 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3303 $age = time() - $post->created;
3304 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3305 $age = 0;
3308 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3309 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3310 // The first post in single simple is the forum description.
3311 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3313 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3314 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3317 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3318 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3321 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3322 // Do not allow deleting of first post in single simple type.
3323 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3324 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3327 if ($reply) {
3328 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3331 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3332 $p = array('postid' => $post->id);
3333 require_once($CFG->libdir.'/portfoliolib.php');
3334 $button = new portfolio_add_button();
3335 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3336 if (empty($attachments)) {
3337 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3338 } else {
3339 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3342 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3343 if (!empty($porfoliohtml)) {
3344 $commands[] = $porfoliohtml;
3347 // Finished building commands
3350 // Begin output
3352 $output = '';
3354 if ($istracked) {
3355 if ($postisread) {
3356 $forumpostclass = ' read';
3357 } else {
3358 $forumpostclass = ' unread';
3359 // If this is the first unread post printed then give it an anchor and id of unread.
3360 if (!$firstunreadanchorprinted) {
3361 $output .= html_writer::tag('a', '', array('id' => 'unread'));
3362 $firstunreadanchorprinted = true;
3365 } else {
3366 // ignore trackign status if not tracked or tracked param missing
3367 $forumpostclass = '';
3370 $topicclass = '';
3371 if (empty($post->parent)) {
3372 $topicclass = ' firstpost starter';
3375 if (!empty($post->lastpost)) {
3376 $forumpostclass .= ' lastpost';
3379 // Flag to indicate whether we should hide the author or not.
3380 $authorhidden = forum_is_author_hidden($post, $forum);
3381 $postbyuser = new stdClass;
3382 $postbyuser->post = $post->subject;
3383 $postbyuser->user = $postuser->fullname;
3384 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3385 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3386 // Begin forum post.
3387 $output .= html_writer::start_div('forumpost clearfix' . $forumpostclass . $topicclass,
3388 ['role' => 'region', 'aria-label' => $discussionbyuser]);
3389 // Begin header row.
3390 $output .= html_writer::start_div('row header clearfix');
3392 // User picture.
3393 if (!$authorhidden) {
3394 $picture = $OUTPUT->user_picture($postuser, ['courseid' => $course->id]);
3395 $output .= html_writer::div($picture, 'left picture');
3396 $topicclass = 'topic' . $topicclass;
3399 // Begin topic column.
3400 $output .= html_writer::start_div($topicclass);
3401 $postsubject = $post->subject;
3402 if (empty($post->subjectnoformat)) {
3403 $postsubject = format_string($postsubject);
3405 $output .= html_writer::div($postsubject, 'subject', ['role' => 'heading', 'aria-level' => '2']);
3407 if ($authorhidden) {
3408 $bytext = userdate($post->modified);
3409 } else {
3410 $by = new stdClass();
3411 $by->date = userdate($post->modified);
3412 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3413 $bytext = get_string('bynameondate', 'forum', $by);
3415 $bytextoptions = [
3416 'role' => 'heading',
3417 'aria-level' => '2',
3419 $output .= html_writer::div($bytext, 'author', $bytextoptions);
3420 // End topic column.
3421 $output .= html_writer::end_div();
3423 // End header row.
3424 $output .= html_writer::end_div();
3426 // Row with the forum post content.
3427 $output .= html_writer::start_div('row maincontent clearfix');
3428 // Show if author is not hidden or we have groups.
3429 if (!$authorhidden || $groups) {
3430 $output .= html_writer::start_div('left');
3431 $groupoutput = '';
3432 if ($groups) {
3433 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3435 if (empty($groupoutput)) {
3436 $groupoutput = '&nbsp;';
3438 $output .= html_writer::div($groupoutput, 'grouppictures');
3439 $output .= html_writer::end_div(); // Left side.
3442 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3443 $output .= html_writer::start_tag('div', array('class'=>'content'));
3445 $options = new stdClass;
3446 $options->para = false;
3447 $options->trusted = $post->messagetrust;
3448 $options->context = $modcontext;
3449 if ($shortenpost) {
3450 // Prepare shortened version by filtering the text then shortening it.
3451 $postclass = 'shortenedpost';
3452 $postcontent = format_text($post->message, $post->messageformat, $options);
3453 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3454 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3455 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3456 array('class'=>'post-word-count'));
3457 } else {
3458 // Prepare whole post
3459 $postclass = 'fullpost';
3460 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3461 if (!empty($highlight)) {
3462 $postcontent = highlight($highlight, $postcontent);
3464 if (!empty($forum->displaywordcount)) {
3465 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3466 array('class'=>'post-word-count'));
3468 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3471 if (\core_tag_tag::is_enabled('mod_forum', 'forum_posts')) {
3472 $postcontent .= $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_forum', 'forum_posts', $post->id), null, 'forum-tags');
3475 // Output the post content
3476 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3477 $output .= html_writer::end_tag('div'); // Content
3478 $output .= html_writer::end_tag('div'); // Content mask
3479 $output .= html_writer::end_tag('div'); // Row
3481 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3482 $output .= html_writer::tag('div','&nbsp;', array('class'=>'left'));
3483 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3485 if (!empty($attachments)) {
3486 $output .= html_writer::tag('div', $attachments, array('class' => 'attachments'));
3489 // Output ratings
3490 if (!empty($post->rating)) {
3491 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3494 // Output the commands
3495 $commandhtml = array();
3496 foreach ($commands as $command) {
3497 if (is_array($command)) {
3498 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3499 } else {
3500 $commandhtml[] = $command;
3503 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3505 // Output link to post if required
3506 if ($link) {
3507 if (forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3508 $langstring = 'discussthistopic';
3509 } else {
3510 $langstring = 'viewthediscussion';
3512 if ($post->replies == 1) {
3513 $replystring = get_string('repliesone', 'forum', $post->replies);
3514 } else {
3515 $replystring = get_string('repliesmany', 'forum', $post->replies);
3517 if (!empty($discussion->unread) && $discussion->unread !== '-') {
3518 $replystring .= ' <span class="sep">/</span> <span class="unread">';
3519 $unreadlink = new moodle_url($discussionlink, null, 'unread');
3520 if ($discussion->unread == 1) {
3521 $replystring .= html_writer::link($unreadlink, get_string('unreadpostsone', 'forum'));
3522 } else {
3523 $replystring .= html_writer::link($unreadlink, get_string('unreadpostsnumber', 'forum', $discussion->unread));
3525 $replystring .= '</span>';
3528 $output .= html_writer::start_tag('div', array('class'=>'link'));
3529 $output .= html_writer::link($discussionlink, get_string($langstring, 'forum'));
3530 $output .= '&nbsp;('.$replystring.')';
3531 $output .= html_writer::end_tag('div'); // link
3534 // Output footer if required
3535 if ($footer) {
3536 $output .= html_writer::tag('div', $footer, array('class'=>'footer'));
3539 // Close remaining open divs
3540 $output .= html_writer::end_tag('div'); // content
3541 $output .= html_writer::end_tag('div'); // row
3542 $output .= html_writer::end_tag('div'); // forumpost
3544 // Mark the forum post as read if required
3545 if ($istracked && !$CFG->forum_usermarksread && !$postisread) {
3546 forum_tp_mark_post_read($USER->id, $post);
3549 if ($return) {
3550 return $output;
3552 echo $output;
3553 return;
3557 * Return rating related permissions
3559 * @param string $options the context id
3560 * @return array an associative array of the user's rating permissions
3562 function forum_rating_permissions($contextid, $component, $ratingarea) {
3563 $context = context::instance_by_id($contextid, MUST_EXIST);
3564 if ($component != 'mod_forum' || $ratingarea != 'post') {
3565 // We don't know about this component/ratingarea so just return null to get the
3566 // default restrictive permissions.
3567 return null;
3569 return array(
3570 'view' => has_capability('mod/forum:viewrating', $context),
3571 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3572 'viewall' => has_capability('mod/forum:viewallratings', $context),
3573 'rate' => has_capability('mod/forum:rate', $context)
3578 * Validates a submitted rating
3579 * @param array $params submitted data
3580 * context => object the context in which the rated items exists [required]
3581 * component => The component for this module - should always be mod_forum [required]
3582 * ratingarea => object the context in which the rated items exists [required]
3583 * itemid => int the ID of the object being rated [required]
3584 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3585 * rating => int the submitted rating [required]
3586 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3587 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3588 * @return boolean true if the rating is valid. Will throw rating_exception if not
3590 function forum_rating_validate($params) {
3591 global $DB, $USER;
3593 // Check the component is mod_forum
3594 if ($params['component'] != 'mod_forum') {
3595 throw new rating_exception('invalidcomponent');
3598 // Check the ratingarea is post (the only rating area in forum)
3599 if ($params['ratingarea'] != 'post') {
3600 throw new rating_exception('invalidratingarea');
3603 // Check the rateduserid is not the current user .. you can't rate your own posts
3604 if ($params['rateduserid'] == $USER->id) {
3605 throw new rating_exception('nopermissiontorate');
3608 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
3609 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
3610 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
3611 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
3612 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
3613 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
3614 $context = context_module::instance($cm->id);
3616 // Make sure the context provided is the context of the forum
3617 if ($context->id != $params['context']->id) {
3618 throw new rating_exception('invalidcontext');
3621 if ($forum->scale != $params['scaleid']) {
3622 //the scale being submitted doesnt match the one in the database
3623 throw new rating_exception('invalidscaleid');
3626 // check the item we're rating was created in the assessable time window
3627 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
3628 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
3629 throw new rating_exception('notavailable');
3633 //check that the submitted rating is valid for the scale
3635 // lower limit
3636 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
3637 throw new rating_exception('invalidnum');
3640 // upper limit
3641 if ($forum->scale < 0) {
3642 //its a custom scale
3643 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
3644 if ($scalerecord) {
3645 $scalearray = explode(',', $scalerecord->scale);
3646 if ($params['rating'] > count($scalearray)) {
3647 throw new rating_exception('invalidnum');
3649 } else {
3650 throw new rating_exception('invalidscaleid');
3652 } else if ($params['rating'] > $forum->scale) {
3653 //if its numeric and submitted rating is above maximum
3654 throw new rating_exception('invalidnum');
3657 // Make sure groups allow this user to see the item they're rating
3658 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
3659 if (!groups_group_exists($discussion->groupid)) { // Can't find group
3660 throw new rating_exception('cannotfindgroup');//something is wrong
3663 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
3664 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
3665 throw new rating_exception('notmemberofgroup');
3669 // perform some final capability checks
3670 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3671 throw new rating_exception('nopermissiontorate');
3674 return true;
3678 * Can the current user see ratings for a given itemid?
3680 * @param array $params submitted data
3681 * contextid => int contextid [required]
3682 * component => The component for this module - should always be mod_forum [required]
3683 * ratingarea => object the context in which the rated items exists [required]
3684 * itemid => int the ID of the object being rated [required]
3685 * scaleid => int scale id [optional]
3686 * @return bool
3687 * @throws coding_exception
3688 * @throws rating_exception
3690 function mod_forum_rating_can_see_item_ratings($params) {
3691 global $DB, $USER;
3693 // Check the component is mod_forum.
3694 if (!isset($params['component']) || $params['component'] != 'mod_forum') {
3695 throw new rating_exception('invalidcomponent');
3698 // Check the ratingarea is post (the only rating area in forum).
3699 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
3700 throw new rating_exception('invalidratingarea');
3703 if (!isset($params['itemid'])) {
3704 throw new rating_exception('invaliditemid');
3707 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
3708 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
3709 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
3710 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
3711 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
3713 // Perform some final capability checks.
3714 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3715 return false;
3717 return true;
3721 * This function prints the overview of a discussion in the forum listing.
3722 * It needs some discussion information and some post information, these
3723 * happen to be combined for efficiency in the $post parameter by the function
3724 * that calls this one: forum_print_latest_discussions()
3726 * @global object
3727 * @global object
3728 * @param object $post The post object (passed by reference for speed).
3729 * @param object $forum The forum object.
3730 * @param int $group Current group.
3731 * @param string $datestring Format to use for the dates.
3732 * @param boolean $cantrack Is tracking enabled for this forum.
3733 * @param boolean $forumtracked Is the user tracking this forum.
3734 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
3735 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
3737 function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
3738 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
3739 $canviewhiddentimedposts = false) {
3741 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
3743 static $rowcount;
3744 static $strmarkalldread;
3746 if (empty($modcontext)) {
3747 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3748 print_error('invalidcoursemodule');
3750 $modcontext = context_module::instance($cm->id);
3753 if (!isset($rowcount)) {
3754 $rowcount = 0;
3755 $strmarkalldread = get_string('markalldread', 'forum');
3756 } else {
3757 $rowcount = ($rowcount + 1) % 2;
3760 $post->subject = format_string($post->subject,true);
3762 $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
3763 $timedoutsidewindow = '';
3764 if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
3765 $timedoutsidewindow = ' dimmed_text';
3768 echo "\n\n";
3769 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
3771 $topicclass = 'topic starter';
3772 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
3773 $topicclass .= ' pinned';
3775 echo '<td class="'.$topicclass.'">';
3776 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
3777 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
3779 $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
3780 if ($timeddiscussion && $canalwaysseetimedpost) {
3781 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
3784 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
3785 echo "</td>\n";
3787 // Picture
3788 $postuser = new stdClass();
3789 $postuserfields = explode(',', user_picture::fields());
3790 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3791 $postuser->id = $post->userid;
3792 echo '<td class="author">';
3793 echo '<span class="picture">';
3794 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
3795 echo '</span>';
3796 echo '<span class="name">';
3797 // User name
3798 $fullname = fullname($postuser, has_capability('moodle/site:viewfullnames', $modcontext));
3799 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
3800 echo '</span>';
3801 echo "</td>\n";
3803 // Group picture
3804 if ($group !== -1) { // Groups are active - group is a group data object or NULL
3805 echo '<td class="picture group">';
3806 if (!empty($group->picture) and empty($group->hidepicture)) {
3807 if ($canviewparticipants && $COURSE->groupmode) {
3808 $picturelink = true;
3809 } else {
3810 $picturelink = false;
3812 print_group_picture($group, $forum->course, false, false, $picturelink);
3813 } else if (isset($group->id)) {
3814 if ($canviewparticipants && $COURSE->groupmode) {
3815 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
3816 } else {
3817 echo $group->name;
3820 echo "</td>\n";
3823 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
3824 echo '<td class="replies">';
3825 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
3826 echo $post->replies.'</a>';
3827 echo "</td>\n";
3829 if ($cantrack) {
3830 echo '<td class="replies">';
3831 if ($forumtracked) {
3832 if ($post->unread > 0) {
3833 echo '<span class="unread">';
3834 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
3835 echo $post->unread;
3836 echo '</a>';
3837 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
3838 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;returnpage=view.php&amp;sesskey=' . sesskey() . '">' .
3839 $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
3840 echo '</span>';
3841 } else {
3842 echo '<span class="read">';
3843 echo $post->unread;
3844 echo '</span>';
3846 } else {
3847 echo '<span class="read">';
3848 echo '-';
3849 echo '</span>';
3851 echo "</td>\n";
3855 echo '<td class="lastpost">';
3856 $usedate = (empty($post->timemodified)) ? $post->modified : $post->timemodified; // Just in case
3857 $parenturl = '';
3858 $usermodified = new stdClass();
3859 $usermodified->id = $post->usermodified;
3860 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
3862 // In QA forums we check that the user can view participants.
3863 if ($forum->type !== 'qanda' || $canviewparticipants) {
3864 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
3865 fullname($usermodified).'</a><br />';
3866 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
3869 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
3870 userdate($usedate, $datestring).'</a>';
3871 echo "</td>\n";
3873 // is_guest should be used here as this also checks whether the user is a guest in the current course.
3874 // Guests and visitors cannot subscribe - only enrolled users.
3875 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
3876 // Discussion subscription.
3877 if (\mod_forum\subscriptions::is_subscribable($forum)) {
3878 echo '<td class="discussionsubscription">';
3879 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
3880 echo '</td>';
3884 echo "</tr>\n\n";
3889 * Return the markup for the discussion subscription toggling icon.
3891 * @param stdClass $forum The forum object.
3892 * @param int $discussionid The discussion to create an icon for.
3893 * @return string The generated markup.
3895 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
3896 global $USER, $OUTPUT, $PAGE;
3898 if ($returnurl === null && $PAGE->url) {
3899 $returnurl = $PAGE->url->out();
3902 $o = '';
3903 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
3904 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
3905 'sesskey' => sesskey(),
3906 'id' => $forum->id,
3907 'd' => $discussionid,
3908 'returnurl' => $returnurl,
3911 if ($includetext) {
3912 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
3915 if ($subscriptionstatus) {
3916 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
3917 if ($includetext) {
3918 $output .= get_string('subscribed', 'mod_forum');
3921 return html_writer::link($subscriptionlink, $output, array(
3922 'title' => get_string('clicktounsubscribe', 'forum'),
3923 'class' => 'discussiontoggle iconsmall',
3924 'data-forumid' => $forum->id,
3925 'data-discussionid' => $discussionid,
3926 'data-includetext' => $includetext,
3929 } else {
3930 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
3931 if ($includetext) {
3932 $output .= get_string('notsubscribed', 'mod_forum');
3935 return html_writer::link($subscriptionlink, $output, array(
3936 'title' => get_string('clicktosubscribe', 'forum'),
3937 'class' => 'discussiontoggle iconsmall',
3938 'data-forumid' => $forum->id,
3939 'data-discussionid' => $discussionid,
3940 'data-includetext' => $includetext,
3946 * Return a pair of spans containing classes to allow the subscribe and
3947 * unsubscribe icons to be pre-loaded by a browser.
3949 * @return string The generated markup
3951 function forum_get_discussion_subscription_icon_preloaders() {
3952 $o = '';
3953 $o .= html_writer::span('&nbsp;', 'preload-subscribe');
3954 $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
3955 return $o;
3959 * Print the drop down that allows the user to select how they want to have
3960 * the discussion displayed.
3962 * @param int $id forum id if $forumtype is 'single',
3963 * discussion id for any other forum type
3964 * @param mixed $mode forum layout mode
3965 * @param string $forumtype optional
3967 function forum_print_mode_form($id, $mode, $forumtype='') {
3968 global $OUTPUT;
3969 if ($forumtype == 'single') {
3970 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3971 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3972 $select->class = "forummode";
3973 } else {
3974 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3975 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3977 echo $OUTPUT->render($select);
3981 * @global object
3982 * @param object $course
3983 * @param string $search
3984 * @return string
3986 function forum_search_form($course, $search='') {
3987 global $CFG, $PAGE;
3988 $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
3989 $output = $PAGE->get_renderer('mod_forum');
3990 return $output->render($forumsearch);
3995 * @global object
3996 * @global object
3998 function forum_set_return() {
3999 global $CFG, $SESSION;
4001 if (! isset($SESSION->fromdiscussion)) {
4002 $referer = get_local_referer(false);
4003 // If the referer is NOT a login screen then save it.
4004 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
4005 $SESSION->fromdiscussion = $referer;
4012 * @global object
4013 * @param string|\moodle_url $default
4014 * @return string
4016 function forum_go_back_to($default) {
4017 global $SESSION;
4019 if (!empty($SESSION->fromdiscussion)) {
4020 $returnto = $SESSION->fromdiscussion;
4021 unset($SESSION->fromdiscussion);
4022 return $returnto;
4023 } else {
4024 return $default;
4029 * Given a discussion object that is being moved to $forumto,
4030 * this function checks all posts in that discussion
4031 * for attachments, and if any are found, these are
4032 * moved to the new forum directory.
4034 * @global object
4035 * @param object $discussion
4036 * @param int $forumfrom source forum id
4037 * @param int $forumto target forum id
4038 * @return bool success
4040 function forum_move_attachments($discussion, $forumfrom, $forumto) {
4041 global $DB;
4043 $fs = get_file_storage();
4045 $newcm = get_coursemodule_from_instance('forum', $forumto);
4046 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
4048 $newcontext = context_module::instance($newcm->id);
4049 $oldcontext = context_module::instance($oldcm->id);
4051 // loop through all posts, better not use attachment flag ;-)
4052 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
4053 foreach ($posts as $post) {
4054 $fs->move_area_files_to_new_context($oldcontext->id,
4055 $newcontext->id, 'mod_forum', 'post', $post->id);
4056 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
4057 $newcontext->id, 'mod_forum', 'attachment', $post->id);
4058 if ($attachmentsmoved > 0 && $post->attachment != '1') {
4059 // Weird - let's fix it
4060 $post->attachment = '1';
4061 $DB->update_record('forum_posts', $post);
4062 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
4063 // Weird - let's fix it
4064 $post->attachment = '';
4065 $DB->update_record('forum_posts', $post);
4070 return true;
4074 * Returns attachments as formated text/html optionally with separate images
4076 * @global object
4077 * @global object
4078 * @global object
4079 * @param object $post
4080 * @param object $cm
4081 * @param string $type html/text/separateimages
4082 * @return mixed string or array of (html text withouth images and image HTML)
4084 function forum_print_attachments($post, $cm, $type) {
4085 global $CFG, $DB, $USER, $OUTPUT;
4087 if (empty($post->attachment)) {
4088 return $type !== 'separateimages' ? '' : array('', '');
4091 if (!in_array($type, array('separateimages', 'html', 'text'))) {
4092 return $type !== 'separateimages' ? '' : array('', '');
4095 if (!$context = context_module::instance($cm->id)) {
4096 return $type !== 'separateimages' ? '' : array('', '');
4098 $strattachment = get_string('attachment', 'forum');
4100 $fs = get_file_storage();
4102 $imagereturn = '';
4103 $output = '';
4105 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
4107 if ($canexport) {
4108 require_once($CFG->libdir.'/portfoliolib.php');
4111 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
4112 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
4113 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
4114 if ($files) {
4115 if ($canexport) {
4116 $button = new portfolio_add_button();
4118 foreach ($files as $file) {
4119 $filename = $file->get_filename();
4120 $mimetype = $file->get_mimetype();
4121 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
4122 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
4124 if ($type == 'html') {
4125 $output .= "<a href=\"$path\">$iconimage</a> ";
4126 $output .= "<a href=\"$path\">".s($filename)."</a>";
4127 if ($canexport) {
4128 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4129 $button->set_format_by_file($file);
4130 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4132 $output .= "<br />";
4134 } else if ($type == 'text') {
4135 $output .= "$strattachment ".s($filename).":\n$path\n";
4137 } else { //'returnimages'
4138 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
4139 // Image attachments don't get printed as links
4140 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
4141 if ($canexport) {
4142 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4143 $button->set_format_by_file($file);
4144 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4146 } else {
4147 $output .= "<a href=\"$path\">$iconimage</a> ";
4148 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
4149 if ($canexport) {
4150 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4151 $button->set_format_by_file($file);
4152 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4154 $output .= '<br />';
4158 if (!empty($CFG->enableplagiarism)) {
4159 require_once($CFG->libdir.'/plagiarismlib.php');
4160 $output .= plagiarism_get_links(array('userid' => $post->userid,
4161 'file' => $file,
4162 'cmid' => $cm->id,
4163 'course' => $cm->course,
4164 'forum' => $cm->instance));
4165 $output .= '<br />';
4170 if ($type !== 'separateimages') {
4171 return $output;
4173 } else {
4174 return array($output, $imagereturn);
4178 ////////////////////////////////////////////////////////////////////////////////
4179 // File API //
4180 ////////////////////////////////////////////////////////////////////////////////
4183 * Lists all browsable file areas
4185 * @package mod_forum
4186 * @category files
4187 * @param stdClass $course course object
4188 * @param stdClass $cm course module object
4189 * @param stdClass $context context object
4190 * @return array
4192 function forum_get_file_areas($course, $cm, $context) {
4193 return array(
4194 'attachment' => get_string('areaattachment', 'mod_forum'),
4195 'post' => get_string('areapost', 'mod_forum'),
4200 * File browsing support for forum module.
4202 * @package mod_forum
4203 * @category files
4204 * @param stdClass $browser file browser object
4205 * @param stdClass $areas file areas
4206 * @param stdClass $course course object
4207 * @param stdClass $cm course module
4208 * @param stdClass $context context module
4209 * @param string $filearea file area
4210 * @param int $itemid item ID
4211 * @param string $filepath file path
4212 * @param string $filename file name
4213 * @return file_info instance or null if not found
4215 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4216 global $CFG, $DB, $USER;
4218 if ($context->contextlevel != CONTEXT_MODULE) {
4219 return null;
4222 // filearea must contain a real area
4223 if (!isset($areas[$filearea])) {
4224 return null;
4227 // Note that forum_user_can_see_post() additionally allows access for parent roles
4228 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
4229 // course:managefiles, we will need to extend this.
4230 if (!has_capability('mod/forum:viewdiscussion', $context)) {
4231 return null;
4234 if (is_null($itemid)) {
4235 require_once($CFG->dirroot.'/mod/forum/locallib.php');
4236 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
4239 static $cached = array();
4240 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
4241 // is cleared between unit tests we check if this is the same session
4242 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
4243 $cached = array('sesskey' => sesskey());
4246 if (isset($cached['post']) && $cached['post']->id == $itemid) {
4247 $post = $cached['post'];
4248 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
4249 $cached['post'] = $post;
4250 } else {
4251 return null;
4254 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
4255 $discussion = $cached['discussion'];
4256 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
4257 $cached['discussion'] = $discussion;
4258 } else {
4259 return null;
4262 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
4263 $forum = $cached['forum'];
4264 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
4265 $cached['forum'] = $forum;
4266 } else {
4267 return null;
4270 $fs = get_file_storage();
4271 $filepath = is_null($filepath) ? '/' : $filepath;
4272 $filename = is_null($filename) ? '.' : $filename;
4273 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
4274 return null;
4277 // Checks to see if the user can manage files or is the owner.
4278 // TODO MDL-33805 - Do not use userid here and move the capability check above.
4279 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
4280 return null;
4282 // Make sure groups allow this user to see this file
4283 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
4284 $groupmode = groups_get_activity_groupmode($cm, $course);
4285 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
4286 return null;
4290 // Make sure we're allowed to see it...
4291 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4292 return null;
4295 $urlbase = $CFG->wwwroot.'/pluginfile.php';
4296 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
4300 * Serves the forum attachments. Implements needed access control ;-)
4302 * @package mod_forum
4303 * @category files
4304 * @param stdClass $course course object
4305 * @param stdClass $cm course module object
4306 * @param stdClass $context context object
4307 * @param string $filearea file area
4308 * @param array $args extra arguments
4309 * @param bool $forcedownload whether or not force download
4310 * @param array $options additional options affecting the file serving
4311 * @return bool false if file not found, does not return if found - justsend the file
4313 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
4314 global $CFG, $DB;
4316 if ($context->contextlevel != CONTEXT_MODULE) {
4317 return false;
4320 require_course_login($course, true, $cm);
4322 $areas = forum_get_file_areas($course, $cm, $context);
4324 // filearea must contain a real area
4325 if (!isset($areas[$filearea])) {
4326 return false;
4329 $postid = (int)array_shift($args);
4331 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
4332 return false;
4335 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
4336 return false;
4339 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
4340 return false;
4343 $fs = get_file_storage();
4344 $relativepath = implode('/', $args);
4345 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
4346 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4347 return false;
4350 // Make sure groups allow this user to see this file
4351 if ($discussion->groupid > 0) {
4352 $groupmode = groups_get_activity_groupmode($cm, $course);
4353 if ($groupmode == SEPARATEGROUPS) {
4354 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
4355 return false;
4360 // Make sure we're allowed to see it...
4361 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4362 return false;
4365 // finally send the file
4366 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
4370 * If successful, this function returns the name of the file
4372 * @global object
4373 * @param object $post is a full post record, including course and forum
4374 * @param object $forum
4375 * @param object $cm
4376 * @param mixed $mform
4377 * @param string $unused
4378 * @return bool
4380 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
4381 global $DB;
4383 if (empty($mform)) {
4384 return false;
4387 if (empty($post->attachments)) {
4388 return true; // Nothing to do
4391 $context = context_module::instance($cm->id);
4393 $info = file_get_draft_area_info($post->attachments);
4394 $present = ($info['filecount']>0) ? '1' : '';
4395 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
4396 mod_forum_post_form::attachment_options($forum));
4398 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
4400 return true;
4404 * Add a new post in an existing discussion.
4406 * @param stdClass $post The post data
4407 * @param mixed $mform The submitted form
4408 * @param string $unused
4409 * @return int
4411 function forum_add_new_post($post, $mform, $unused = null) {
4412 global $USER, $DB;
4414 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4415 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4416 $cm = get_coursemodule_from_instance('forum', $forum->id);
4417 $context = context_module::instance($cm->id);
4419 $post->created = $post->modified = time();
4420 $post->mailed = FORUM_MAILED_PENDING;
4421 $post->userid = $USER->id;
4422 $post->attachment = "";
4423 if (!isset($post->totalscore)) {
4424 $post->totalscore = 0;
4426 if (!isset($post->mailnow)) {
4427 $post->mailnow = 0;
4430 $post->id = $DB->insert_record("forum_posts", $post);
4431 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
4432 mod_forum_post_form::editor_options($context, null), $post->message);
4433 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
4434 forum_add_attachment($post, $forum, $cm, $mform);
4436 // Update discussion modified date
4437 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
4438 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
4440 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4441 forum_tp_mark_post_read($post->userid, $post);
4444 if (isset($post->tags)) {
4445 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
4448 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4449 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
4451 return $post->id;
4455 * Update a post.
4457 * @param stdClass $newpost The post to update
4458 * @param mixed $mform The submitted form
4459 * @param string $unused
4460 * @return bool
4462 function forum_update_post($newpost, $mform, $unused = null) {
4463 global $DB, $USER;
4465 $post = $DB->get_record('forum_posts', array('id' => $newpost->id));
4466 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4467 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4468 $cm = get_coursemodule_from_instance('forum', $forum->id);
4469 $context = context_module::instance($cm->id);
4471 // Allowed modifiable fields.
4472 $modifiablefields = [
4473 'subject',
4474 'message',
4475 'messageformat',
4476 'messagetrust',
4477 'timestart',
4478 'timeend',
4479 'pinned',
4480 'attachments',
4482 foreach ($modifiablefields as $field) {
4483 if (isset($newpost->{$field})) {
4484 $post->{$field} = $newpost->{$field};
4487 $post->modified = time();
4489 // Last post modified tracking.
4490 $discussion->timemodified = $post->modified;
4491 $discussion->usermodified = $post->userid;
4493 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
4494 $discussion->name = $post->subject;
4495 $discussion->timestart = $post->timestart;
4496 $discussion->timeend = $post->timeend;
4498 if (isset($post->pinned)) {
4499 $discussion->pinned = $post->pinned;
4502 $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
4503 mod_forum_post_form::editor_options($context, $post->id), $post->message);
4504 $DB->update_record('forum_posts', $post);
4505 $DB->update_record('forum_discussions', $discussion);
4507 forum_add_attachment($post, $forum, $cm, $mform);
4509 if (isset($newpost->tags)) {
4510 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
4513 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4514 forum_tp_mark_post_read($USER->id, $post);
4517 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4518 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
4520 return true;
4524 * Given an object containing all the necessary data,
4525 * create a new discussion and return the id
4527 * @param object $post
4528 * @param mixed $mform
4529 * @param string $unused
4530 * @param int $userid
4531 * @return object
4533 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
4534 global $USER, $CFG, $DB;
4536 $timenow = isset($discussion->timenow) ? $discussion->timenow : time();
4538 if (is_null($userid)) {
4539 $userid = $USER->id;
4542 // The first post is stored as a real post, and linked
4543 // to from the discuss entry.
4545 $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
4546 $cm = get_coursemodule_from_instance('forum', $forum->id);
4548 $post = new stdClass();
4549 $post->discussion = 0;
4550 $post->parent = 0;
4551 $post->userid = $userid;
4552 $post->created = $timenow;
4553 $post->modified = $timenow;
4554 $post->mailed = FORUM_MAILED_PENDING;
4555 $post->subject = $discussion->name;
4556 $post->message = $discussion->message;
4557 $post->messageformat = $discussion->messageformat;
4558 $post->messagetrust = $discussion->messagetrust;
4559 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null;
4560 $post->forum = $forum->id; // speedup
4561 $post->course = $forum->course; // speedup
4562 $post->mailnow = $discussion->mailnow;
4564 $post->id = $DB->insert_record("forum_posts", $post);
4566 // TODO: Fix the calling code so that there always is a $cm when this function is called
4567 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet
4568 $context = context_module::instance($cm->id);
4569 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
4570 mod_forum_post_form::editor_options($context, null), $post->message);
4571 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
4574 // Now do the main entry for the discussion, linking to this first post
4576 $discussion->firstpost = $post->id;
4577 $discussion->timemodified = $timenow;
4578 $discussion->usermodified = $post->userid;
4579 $discussion->userid = $userid;
4580 $discussion->assessed = 0;
4582 $post->discussion = $DB->insert_record("forum_discussions", $discussion);
4584 // Finally, set the pointer on the post.
4585 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
4587 if (!empty($cm->id)) {
4588 forum_add_attachment($post, $forum, $cm, $mform, $unused);
4591 if (isset($discussion->tags)) {
4592 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags);
4595 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4596 forum_tp_mark_post_read($post->userid, $post);
4599 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4600 if (!empty($cm->id)) {
4601 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
4604 return $post->discussion;
4609 * Deletes a discussion and handles all associated cleanup.
4611 * @global object
4612 * @param object $discussion Discussion to delete
4613 * @param bool $fulldelete True when deleting entire forum
4614 * @param object $course Course
4615 * @param object $cm Course-module
4616 * @param object $forum Forum
4617 * @return bool
4619 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
4620 global $DB, $CFG;
4621 require_once($CFG->libdir.'/completionlib.php');
4623 $result = true;
4625 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
4626 foreach ($posts as $post) {
4627 $post->course = $discussion->course;
4628 $post->forum = $discussion->forum;
4629 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
4630 $result = false;
4635 forum_tp_delete_read_records(-1, -1, $discussion->id);
4637 // Discussion subscriptions must be removed before discussions because of key constraints.
4638 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
4639 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
4640 $result = false;
4643 // Update completion state if we are tracking completion based on number of posts
4644 // But don't bother when deleting whole thing
4645 if (!$fulldelete) {
4646 $completion = new completion_info($course);
4647 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4648 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4649 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
4653 return $result;
4658 * Deletes a single forum post.
4660 * @global object
4661 * @param object $post Forum post object
4662 * @param mixed $children Whether to delete children. If false, returns false
4663 * if there are any children (without deleting the post). If true,
4664 * recursively deletes all children. If set to special value 'ignore', deletes
4665 * post regardless of children (this is for use only when deleting all posts
4666 * in a disussion).
4667 * @param object $course Course
4668 * @param object $cm Course-module
4669 * @param object $forum Forum
4670 * @param bool $skipcompletion True to skip updating completion state if it
4671 * would otherwise be updated, i.e. when deleting entire forum anyway.
4672 * @return bool
4674 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
4675 global $DB, $CFG, $USER;
4676 require_once($CFG->libdir.'/completionlib.php');
4678 $context = context_module::instance($cm->id);
4680 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
4681 if ($children) {
4682 foreach ($childposts as $childpost) {
4683 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
4685 } else {
4686 return false;
4690 // Delete ratings.
4691 require_once($CFG->dirroot.'/rating/lib.php');
4692 $delopt = new stdClass;
4693 $delopt->contextid = $context->id;
4694 $delopt->component = 'mod_forum';
4695 $delopt->ratingarea = 'post';
4696 $delopt->itemid = $post->id;
4697 $rm = new rating_manager();
4698 $rm->delete_ratings($delopt);
4700 // Delete attachments.
4701 $fs = get_file_storage();
4702 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
4703 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
4705 // Delete cached RSS feeds.
4706 if (!empty($CFG->enablerssfeeds)) {
4707 require_once($CFG->dirroot.'/mod/forum/rsslib.php');
4708 forum_rss_delete_file($forum);
4711 if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
4713 forum_tp_delete_read_records(-1, $post->id);
4715 // Just in case we are deleting the last post
4716 forum_discussion_update_last_post($post->discussion);
4718 // Update completion state if we are tracking completion based on number of posts
4719 // But don't bother when deleting whole thing
4721 if (!$skipcompletion) {
4722 $completion = new completion_info($course);
4723 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4724 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4725 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
4729 $params = array(
4730 'context' => $context,
4731 'objectid' => $post->id,
4732 'other' => array(
4733 'discussionid' => $post->discussion,
4734 'forumid' => $forum->id,
4735 'forumtype' => $forum->type,
4738 if ($post->userid !== $USER->id) {
4739 $params['relateduserid'] = $post->userid;
4741 $event = \mod_forum\event\post_deleted::create($params);
4742 $event->add_record_snapshot('forum_posts', $post);
4743 $event->trigger();
4745 return true;
4747 return false;
4751 * Sends post content to plagiarism plugin
4752 * @param object $post Forum post object
4753 * @param object $cm Course-module
4754 * @param string $name
4755 * @return bool
4757 function forum_trigger_content_uploaded_event($post, $cm, $name) {
4758 $context = context_module::instance($cm->id);
4759 $fs = get_file_storage();
4760 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
4761 $params = array(
4762 'context' => $context,
4763 'objectid' => $post->id,
4764 'other' => array(
4765 'content' => $post->message,
4766 'pathnamehashes' => array_keys($files),
4767 'discussionid' => $post->discussion,
4768 'triggeredfrom' => $name,
4771 $event = \mod_forum\event\assessable_uploaded::create($params);
4772 $event->trigger();
4773 return true;
4777 * @global object
4778 * @param object $post
4779 * @param bool $children
4780 * @return int
4782 function forum_count_replies($post, $children=true) {
4783 global $DB;
4784 $count = 0;
4786 if ($children) {
4787 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id))) {
4788 foreach ($childposts as $childpost) {
4789 $count ++; // For this child
4790 $count += forum_count_replies($childpost, true);
4793 } else {
4794 $count += $DB->count_records('forum_posts', array('parent' => $post->id));
4797 return $count;
4801 * Given a new post, subscribes or unsubscribes as appropriate.
4802 * Returns some text which describes what happened.
4804 * @param object $fromform The submitted form
4805 * @param stdClass $forum The forum record
4806 * @param stdClass $discussion The forum discussion record
4807 * @return string
4809 function forum_post_subscription($fromform, $forum, $discussion) {
4810 global $USER;
4812 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4813 return "";
4814 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
4815 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4816 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
4817 // This user should not be subscribed to the forum.
4818 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
4820 return "";
4823 $info = new stdClass();
4824 $info->name = fullname($USER);
4825 $info->discussion = format_string($discussion->name);
4826 $info->forum = format_string($forum->name);
4828 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
4829 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
4830 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
4832 } else {
4833 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
4834 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
4838 return '';
4842 * Generate and return the subscribe or unsubscribe link for a forum.
4844 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
4845 * @param object $context the context object for this forum.
4846 * @param array $messages text used for the link in its various states
4847 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
4848 * Any strings not passed in are taken from the $defaultmessages array
4849 * at the top of the function.
4850 * @param bool $cantaccessagroup
4851 * @param bool $unused1
4852 * @param bool $backtoindex
4853 * @param array $unused2
4854 * @return string
4856 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
4857 $backtoindex = false, $unused2 = null) {
4858 global $CFG, $USER, $PAGE, $OUTPUT;
4859 $defaultmessages = array(
4860 'subscribed' => get_string('unsubscribe', 'forum'),
4861 'unsubscribed' => get_string('subscribe', 'forum'),
4862 'cantaccessgroup' => get_string('no'),
4863 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
4864 'cantsubscribe' => get_string('disallowsubscribe','forum')
4866 $messages = $messages + $defaultmessages;
4868 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4869 return $messages['forcesubscribed'];
4870 } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
4871 !has_capability('mod/forum:managesubscriptions', $context)) {
4872 return $messages['cantsubscribe'];
4873 } else if ($cantaccessagroup) {
4874 return $messages['cantaccessgroup'];
4875 } else {
4876 if (!is_enrolled($context, $USER, '', true)) {
4877 return '';
4880 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4881 if ($subscribed) {
4882 $linktext = $messages['subscribed'];
4883 $linktitle = get_string('subscribestop', 'forum');
4884 } else {
4885 $linktext = $messages['unsubscribed'];
4886 $linktitle = get_string('subscribestart', 'forum');
4889 $options = array();
4890 if ($backtoindex) {
4891 $backtoindexlink = '&amp;backtoindex=1';
4892 $options['backtoindex'] = 1;
4893 } else {
4894 $backtoindexlink = '';
4897 $options['id'] = $forum->id;
4898 $options['sesskey'] = sesskey();
4899 $url = new moodle_url('/mod/forum/subscribe.php', $options);
4900 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
4905 * Returns true if user created new discussion already.
4907 * @param int $forumid The forum to check for postings
4908 * @param int $userid The user to check for postings
4909 * @param int $groupid The group to restrict the check to
4910 * @return bool
4912 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
4913 global $CFG, $DB;
4915 $sql = "SELECT 'x'
4916 FROM {forum_discussions} d, {forum_posts} p
4917 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
4919 $params = [$forumid, $userid];
4921 if ($groupid) {
4922 $sql .= " AND d.groupid = ?";
4923 $params[] = $groupid;
4926 return $DB->record_exists_sql($sql, $params);
4930 * @global object
4931 * @global object
4932 * @param int $forumid
4933 * @param int $userid
4934 * @return array
4936 function forum_discussions_user_has_posted_in($forumid, $userid) {
4937 global $CFG, $DB;
4939 $haspostedsql = "SELECT d.id AS id,
4941 FROM {forum_posts} p,
4942 {forum_discussions} d
4943 WHERE p.discussion = d.id
4944 AND d.forum = ?
4945 AND p.userid = ?";
4947 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
4951 * @global object
4952 * @global object
4953 * @param int $forumid
4954 * @param int $did
4955 * @param int $userid
4956 * @return bool
4958 function forum_user_has_posted($forumid, $did, $userid) {
4959 global $DB;
4961 if (empty($did)) {
4962 // posted in any forum discussion?
4963 $sql = "SELECT 'x'
4964 FROM {forum_posts} p
4965 JOIN {forum_discussions} d ON d.id = p.discussion
4966 WHERE p.userid = :userid AND d.forum = :forumid";
4967 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
4968 } else {
4969 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
4974 * Returns creation time of the first user's post in given discussion
4975 * @global object $DB
4976 * @param int $did Discussion id
4977 * @param int $userid User id
4978 * @return int|bool post creation time stamp or return false
4980 function forum_get_user_posted_time($did, $userid) {
4981 global $DB;
4983 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
4984 if (empty($posttime)) {
4985 return false;
4987 return $posttime;
4991 * @global object
4992 * @param object $forum
4993 * @param object $currentgroup
4994 * @param int $unused
4995 * @param object $cm
4996 * @param object $context
4997 * @return bool
4999 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
5000 // $forum is an object
5001 global $USER;
5003 // shortcut - guest and not-logged-in users can not post
5004 if (isguestuser() or !isloggedin()) {
5005 return false;
5008 if (!$cm) {
5009 debugging('missing cm', DEBUG_DEVELOPER);
5010 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5011 print_error('invalidcoursemodule');
5015 if (!$context) {
5016 $context = context_module::instance($cm->id);
5019 if ($currentgroup === null) {
5020 $currentgroup = groups_get_activity_group($cm);
5023 $groupmode = groups_get_activity_groupmode($cm);
5025 if ($forum->type == 'news') {
5026 $capname = 'mod/forum:addnews';
5027 } else if ($forum->type == 'qanda') {
5028 $capname = 'mod/forum:addquestion';
5029 } else {
5030 $capname = 'mod/forum:startdiscussion';
5033 if (!has_capability($capname, $context)) {
5034 return false;
5037 if ($forum->type == 'single') {
5038 return false;
5041 if ($forum->type == 'eachuser') {
5042 if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) {
5043 return false;
5047 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
5048 return true;
5051 if ($currentgroup) {
5052 return groups_is_member($currentgroup);
5053 } else {
5054 // no group membership and no accessallgroups means no new discussions
5055 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
5056 return false;
5061 * This function checks whether the user can reply to posts in a forum
5062 * discussion. Use forum_user_can_post_discussion() to check whether the user
5063 * can start discussions.
5065 * @global object
5066 * @global object
5067 * @uses DEBUG_DEVELOPER
5068 * @uses CONTEXT_MODULE
5069 * @uses VISIBLEGROUPS
5070 * @param object $forum forum object
5071 * @param object $discussion
5072 * @param object $user
5073 * @param object $cm
5074 * @param object $course
5075 * @param object $context
5076 * @return bool
5078 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
5079 global $USER, $DB;
5080 if (empty($user)) {
5081 $user = $USER;
5084 // shortcut - guest and not-logged-in users can not post
5085 if (isguestuser($user) or empty($user->id)) {
5086 return false;
5089 if (!isset($discussion->groupid)) {
5090 debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
5091 return false;
5094 if (!$cm) {
5095 debugging('missing cm', DEBUG_DEVELOPER);
5096 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5097 print_error('invalidcoursemodule');
5101 if (!$course) {
5102 debugging('missing course', DEBUG_DEVELOPER);
5103 if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
5104 print_error('invalidcourseid');
5108 if (!$context) {
5109 $context = context_module::instance($cm->id);
5112 // Check whether the discussion is locked.
5113 if (forum_discussion_is_locked($forum, $discussion)) {
5114 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
5115 return false;
5119 // normal users with temporary guest access can not post, suspended users can not post either
5120 if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
5121 return false;
5124 if ($forum->type == 'news') {
5125 $capname = 'mod/forum:replynews';
5126 } else {
5127 $capname = 'mod/forum:replypost';
5130 if (!has_capability($capname, $context, $user->id)) {
5131 return false;
5134 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
5135 return true;
5138 if (has_capability('moodle/site:accessallgroups', $context)) {
5139 return true;
5142 if ($groupmode == VISIBLEGROUPS) {
5143 if ($discussion->groupid == -1) {
5144 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
5145 return true;
5147 return groups_is_member($discussion->groupid);
5149 } else {
5150 //separate groups
5151 if ($discussion->groupid == -1) {
5152 return false;
5154 return groups_is_member($discussion->groupid);
5159 * Check to ensure a user can view a timed discussion.
5161 * @param object $discussion
5162 * @param object $user
5163 * @param object $context
5164 * @return boolean returns true if they can view post, false otherwise
5166 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
5167 global $CFG;
5169 // Check that the user can view a discussion that is normally hidden due to access times.
5170 if (!empty($CFG->forum_enabletimedposts)) {
5171 $time = time();
5172 if (($discussion->timestart != 0 && $discussion->timestart > $time)
5173 || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
5174 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
5175 return false;
5180 return true;
5184 * Check to ensure a user can view a group discussion.
5186 * @param object $discussion
5187 * @param object $cm
5188 * @param object $context
5189 * @return boolean returns true if they can view post, false otherwise
5191 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
5193 // If it's a grouped discussion, make sure the user is a member.
5194 if ($discussion->groupid > 0) {
5195 $groupmode = groups_get_activity_groupmode($cm);
5196 if ($groupmode == SEPARATEGROUPS) {
5197 return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
5201 return true;
5205 * @global object
5206 * @global object
5207 * @uses DEBUG_DEVELOPER
5208 * @param object $forum
5209 * @param object $discussion
5210 * @param object $context
5211 * @param object $user
5212 * @return bool
5214 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
5215 global $USER, $DB;
5217 if (empty($user) || empty($user->id)) {
5218 $user = $USER;
5221 // retrieve objects (yuk)
5222 if (is_numeric($forum)) {
5223 debugging('missing full forum', DEBUG_DEVELOPER);
5224 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5225 return false;
5228 if (is_numeric($discussion)) {
5229 debugging('missing full discussion', DEBUG_DEVELOPER);
5230 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5231 return false;
5234 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5235 print_error('invalidcoursemodule');
5238 if (!has_capability('mod/forum:viewdiscussion', $context)) {
5239 return false;
5242 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
5243 return false;
5246 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
5247 return false;
5250 return true;
5254 * @global object
5255 * @global object
5256 * @param object $forum
5257 * @param object $discussion
5258 * @param object $post
5259 * @param object $user
5260 * @param object $cm
5261 * @return bool
5263 function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NULL) {
5264 global $CFG, $USER, $DB;
5266 // Context used throughout function.
5267 $modcontext = context_module::instance($cm->id);
5269 // retrieve objects (yuk)
5270 if (is_numeric($forum)) {
5271 debugging('missing full forum', DEBUG_DEVELOPER);
5272 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5273 return false;
5277 if (is_numeric($discussion)) {
5278 debugging('missing full discussion', DEBUG_DEVELOPER);
5279 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5280 return false;
5283 if (is_numeric($post)) {
5284 debugging('missing full post', DEBUG_DEVELOPER);
5285 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
5286 return false;
5290 if (!isset($post->id) && isset($post->parent)) {
5291 $post->id = $post->parent;
5294 if (!$cm) {
5295 debugging('missing cm', DEBUG_DEVELOPER);
5296 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5297 print_error('invalidcoursemodule');
5301 if (empty($user) || empty($user->id)) {
5302 $user = $USER;
5305 $canviewdiscussion = (isset($cm->cache) && !empty($cm->cache->caps['mod/forum:viewdiscussion']))
5306 || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
5307 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
5308 return false;
5311 if (isset($cm->uservisible)) {
5312 if (!$cm->uservisible) {
5313 return false;
5315 } else {
5316 if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
5317 return false;
5321 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
5322 return false;
5325 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
5326 return false;
5329 if ($forum->type == 'qanda') {
5330 if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id) || $post->userid == $user->id
5331 || (isset($discussion->firstpost) && $discussion->firstpost == $post->id)) {
5332 return true;
5334 $firstpost = forum_get_firstpost_from_discussion($discussion->id);
5335 if ($firstpost->userid == $user->id) {
5336 return true;
5338 $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
5339 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)));
5341 return true;
5346 * Prints the discussion view screen for a forum.
5348 * @global object
5349 * @global object
5350 * @param object $course The current course object.
5351 * @param object $forum Forum to be printed.
5352 * @param int $maxdiscussions .
5353 * @param string $displayformat The display format to use (optional).
5354 * @param string $sort Sort arguments for database query (optional).
5355 * @param int $groupmode Group mode of the forum (optional).
5356 * @param void $unused (originally current group)
5357 * @param int $page Page mode, page to display (optional).
5358 * @param int $perpage The maximum number of discussions per page(optional)
5359 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
5362 function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '',
5363 $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null) {
5364 global $CFG, $USER, $OUTPUT;
5366 require_once($CFG->dirroot . '/course/lib.php');
5368 if (!$cm) {
5369 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5370 print_error('invalidcoursemodule');
5373 $context = context_module::instance($cm->id);
5375 if (empty($sort)) {
5376 $sort = forum_get_default_sort_order();
5379 $olddiscussionlink = false;
5381 // Sort out some defaults
5382 if ($perpage <= 0) {
5383 $perpage = 0;
5384 $page = -1;
5387 if ($maxdiscussions == 0) {
5388 // all discussions - backwards compatibility
5389 $page = -1;
5390 $perpage = 0;
5391 if ($displayformat == 'plain') {
5392 $displayformat = 'header'; // Abbreviate display by default
5395 } else if ($maxdiscussions > 0) {
5396 $page = -1;
5397 $perpage = $maxdiscussions;
5400 $fullpost = false;
5401 if ($displayformat == 'plain') {
5402 $fullpost = true;
5406 // Decide if current user is allowed to see ALL the current discussions or not
5408 // First check the group stuff
5409 if ($currentgroup == -1 or $groupmode == -1) {
5410 $groupmode = groups_get_activity_groupmode($cm, $course);
5411 $currentgroup = groups_get_activity_group($cm);
5414 $groups = array(); //cache
5416 // If the user can post discussions, then this is a good place to put the
5417 // button for it. We do not show the button if we are showing site news
5418 // and the current user is a guest.
5420 $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
5421 if (!$canstart and $forum->type !== 'news') {
5422 if (isguestuser() or !isloggedin()) {
5423 $canstart = true;
5425 if (!is_enrolled($context) and !is_viewing($context)) {
5426 // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
5427 // normal users with temporary guest access see this button too, they are asked to enrol instead
5428 // do not show the button to users with suspended enrolments here
5429 $canstart = enrol_selfenrol_available($course->id);
5433 if ($canstart) {
5434 switch ($forum->type) {
5435 case 'news':
5436 case 'blog':
5437 $buttonadd = get_string('addanewtopic', 'forum');
5438 break;
5439 case 'qanda':
5440 $buttonadd = get_string('addanewquestion', 'forum');
5441 break;
5442 default:
5443 $buttonadd = get_string('addanewdiscussion', 'forum');
5444 break;
5446 $button = new single_button(new moodle_url('/mod/forum/post.php', ['forum' => $forum->id]), $buttonadd, 'get');
5447 $button->class = 'singlebutton forumaddnew';
5448 $button->formid = 'newdiscussionform';
5449 echo $OUTPUT->render($button);
5451 } else if (isguestuser() or !isloggedin() or $forum->type == 'news' or
5452 $forum->type == 'qanda' and !has_capability('mod/forum:addquestion', $context) or
5453 $forum->type != 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
5454 // no button and no info
5456 } else if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
5457 // inform users why they can not post new discussion
5458 if (!$currentgroup) {
5459 echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
5460 } else if (!groups_is_member($currentgroup)) {
5461 echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
5465 // Get all the recent discussions we're allowed to see
5467 $getuserlastmodified = ($displayformat == 'header');
5469 if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
5470 echo '<div class="forumnodiscuss">';
5471 if ($forum->type == 'news') {
5472 echo '('.get_string('nonews', 'forum').')';
5473 } else if ($forum->type == 'qanda') {
5474 echo '('.get_string('noquestions','forum').')';
5475 } else {
5476 echo '('.get_string('nodiscussions', 'forum').')';
5478 echo "</div>\n";
5479 return;
5482 // If we want paging
5483 if ($page != -1) {
5484 ///Get the number of discussions found
5485 $numdiscussions = forum_get_discussions_count($cm);
5487 ///Show the paging bar
5488 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5489 if ($numdiscussions > 1000) {
5490 // saves some memory on sites with very large forums
5491 $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
5492 } else {
5493 $replies = forum_count_discussion_replies($forum->id);
5496 } else {
5497 $replies = forum_count_discussion_replies($forum->id);
5499 if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
5500 $olddiscussionlink = true;
5504 $canviewparticipants = course_can_view_participants($context);
5505 $canviewhiddentimedposts = has_capability('mod/forum:viewhiddentimedposts', $context);
5507 $strdatestring = get_string('strftimerecentfull');
5509 // Check if the forum is tracked.
5510 if ($cantrack = forum_tp_can_track_forums($forum)) {
5511 $forumtracked = forum_tp_is_tracked($forum);
5512 } else {
5513 $forumtracked = false;
5516 if ($forumtracked) {
5517 $unreads = forum_get_discussions_unread($cm);
5518 } else {
5519 $unreads = array();
5522 if ($displayformat == 'header') {
5523 echo '<table cellspacing="0" class="forumheaderlist">';
5524 echo '<thead>';
5525 echo '<tr>';
5526 echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
5527 echo '<th class="header author" scope="col">'.get_string('startedby', 'forum').'</th>';
5528 if ($groupmode > 0) {
5529 echo '<th class="header group" scope="col">'.get_string('group').'</th>';
5531 if (has_capability('mod/forum:viewdiscussion', $context)) {
5532 echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
5533 // If the forum can be tracked, display the unread column.
5534 if ($cantrack) {
5535 echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
5536 if ($forumtracked) {
5537 echo '<a title="'.get_string('markallread', 'forum').
5538 '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
5539 $forum->id.'&amp;mark=read&amp;returnpage=view.php&amp;sesskey=' . sesskey() . '">'.
5540 $OUTPUT->pix_icon('t/markasread', get_string('markallread', 'forum')) . '</a>';
5542 echo '</th>';
5545 echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
5546 if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $context)) {
5547 if (\mod_forum\subscriptions::is_subscribable($forum)) {
5548 echo '<th class="header discussionsubscription" scope="col">';
5549 echo forum_get_discussion_subscription_icon_preloaders();
5550 echo '</th>';
5553 echo '</tr>';
5554 echo '</thead>';
5555 echo '<tbody>';
5558 foreach ($discussions as $discussion) {
5559 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) &&
5560 !forum_user_has_posted($forum->id, $discussion->discussion, $USER->id)) {
5561 $canviewparticipants = false;
5564 if (!empty($replies[$discussion->discussion])) {
5565 $discussion->replies = $replies[$discussion->discussion]->replies;
5566 $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
5567 } else {
5568 $discussion->replies = 0;
5571 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
5572 // All posts are read in this case.
5573 if (!$forumtracked) {
5574 $discussion->unread = '-';
5575 } else if (empty($USER)) {
5576 $discussion->unread = 0;
5577 } else {
5578 if (empty($unreads[$discussion->discussion])) {
5579 $discussion->unread = 0;
5580 } else {
5581 $discussion->unread = $unreads[$discussion->discussion];
5585 if (isloggedin()) {
5586 $ownpost = ($discussion->userid == $USER->id);
5587 } else {
5588 $ownpost=false;
5590 // Use discussion name instead of subject of first post.
5591 $discussion->subject = $discussion->name;
5593 switch ($displayformat) {
5594 case 'header':
5595 if ($groupmode > 0) {
5596 if (isset($groups[$discussion->groupid])) {
5597 $group = $groups[$discussion->groupid];
5598 } else {
5599 $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
5601 } else {
5602 $group = -1;
5604 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
5605 $canviewparticipants, $context, $canviewhiddentimedposts);
5606 break;
5607 default:
5608 $link = false;
5610 if ($discussion->replies) {
5611 $link = true;
5612 } else {
5613 $modcontext = context_module::instance($cm->id);
5614 $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
5617 $discussion->forum = $forum->id;
5619 forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
5620 '', null, true, $forumtracked);
5621 break;
5625 if ($displayformat == "header") {
5626 echo '</tbody>';
5627 echo '</table>';
5630 if ($olddiscussionlink) {
5631 if ($forum->type == 'news') {
5632 $strolder = get_string('oldertopics', 'forum');
5633 } else {
5634 $strolder = get_string('olderdiscussions', 'forum');
5636 echo '<div class="forumolddiscuss">';
5637 echo '<a href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'&amp;showall=1">';
5638 echo $strolder.'</a> ...</div>';
5641 if ($page != -1) { ///Show the paging bar
5642 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5648 * Prints a forum discussion
5650 * @uses CONTEXT_MODULE
5651 * @uses FORUM_MODE_FLATNEWEST
5652 * @uses FORUM_MODE_FLATOLDEST
5653 * @uses FORUM_MODE_THREADED
5654 * @uses FORUM_MODE_NESTED
5655 * @param stdClass $course
5656 * @param stdClass $cm
5657 * @param stdClass $forum
5658 * @param stdClass $discussion
5659 * @param stdClass $post
5660 * @param int $mode
5661 * @param mixed $canreply
5662 * @param bool $canrate
5664 function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
5665 global $USER, $CFG;
5667 require_once($CFG->dirroot.'/rating/lib.php');
5669 $ownpost = (isloggedin() && $USER->id == $post->userid);
5671 $modcontext = context_module::instance($cm->id);
5672 if ($canreply === NULL) {
5673 $reply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
5674 } else {
5675 $reply = $canreply;
5678 // $cm holds general cache for forum functions
5679 $cm->cache = new stdClass;
5680 $cm->cache->groups = groups_get_all_groups($course->id, 0, $cm->groupingid);
5681 $cm->cache->usersgroups = array();
5683 $posters = array();
5685 // preload all posts - TODO: improve...
5686 if ($mode == FORUM_MODE_FLATNEWEST) {
5687 $sort = "p.created DESC";
5688 } else {
5689 $sort = "p.created ASC";
5692 $forumtracked = forum_tp_is_tracked($forum);
5693 $posts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
5694 $post = $posts[$post->id];
5696 foreach ($posts as $pid=>$p) {
5697 $posters[$p->userid] = $p->userid;
5700 // preload all groups of ppl that posted in this discussion
5701 if ($postersgroups = groups_get_all_groups($course->id, $posters, $cm->groupingid, 'gm.id, gm.groupid, gm.userid')) {
5702 foreach($postersgroups as $pg) {
5703 if (!isset($cm->cache->usersgroups[$pg->userid])) {
5704 $cm->cache->usersgroups[$pg->userid] = array();
5706 $cm->cache->usersgroups[$pg->userid][$pg->groupid] = $pg->groupid;
5708 unset($postersgroups);
5711 //load ratings
5712 if ($forum->assessed != RATING_AGGREGATE_NONE) {
5713 $ratingoptions = new stdClass;
5714 $ratingoptions->context = $modcontext;
5715 $ratingoptions->component = 'mod_forum';
5716 $ratingoptions->ratingarea = 'post';
5717 $ratingoptions->items = $posts;
5718 $ratingoptions->aggregate = $forum->assessed;//the aggregation method
5719 $ratingoptions->scaleid = $forum->scale;
5720 $ratingoptions->userid = $USER->id;
5721 if ($forum->type == 'single' or !$discussion->id) {
5722 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/view.php?id=$cm->id";
5723 } else {
5724 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id";
5726 $ratingoptions->assesstimestart = $forum->assesstimestart;
5727 $ratingoptions->assesstimefinish = $forum->assesstimefinish;
5729 $rm = new rating_manager();
5730 $posts = $rm->get_ratings($ratingoptions);
5734 $post->forum = $forum->id; // Add the forum id to the post object, later used by forum_print_post
5735 $post->forumtype = $forum->type;
5737 $post->subject = format_string($post->subject);
5739 $postread = !empty($post->postread);
5741 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false,
5742 '', '', $postread, true, $forumtracked);
5744 switch ($mode) {
5745 case FORUM_MODE_FLATOLDEST :
5746 case FORUM_MODE_FLATNEWEST :
5747 default:
5748 forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts);
5749 break;
5751 case FORUM_MODE_THREADED :
5752 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $reply, $forumtracked, $posts);
5753 break;
5755 case FORUM_MODE_NESTED :
5756 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5757 break;
5763 * @global object
5764 * @global object
5765 * @uses FORUM_MODE_FLATNEWEST
5766 * @param object $course
5767 * @param object $cm
5768 * @param object $forum
5769 * @param object $discussion
5770 * @param object $post
5771 * @param object $mode
5772 * @param bool $reply
5773 * @param bool $forumtracked
5774 * @param array $posts
5775 * @return void
5777 function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts) {
5778 global $USER, $CFG;
5780 $link = false;
5782 foreach ($posts as $post) {
5783 if (!$post->parent) {
5784 continue;
5786 $post->subject = format_string($post->subject);
5787 $ownpost = ($USER->id == $post->userid);
5789 $postread = !empty($post->postread);
5791 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5792 '', '', $postread, true, $forumtracked);
5797 * @todo Document this function
5799 * @global object
5800 * @global object
5801 * @uses CONTEXT_MODULE
5802 * @return void
5804 function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $reply, $forumtracked, $posts) {
5805 global $USER, $CFG;
5807 $link = false;
5809 if (!empty($posts[$parent->id]->children)) {
5810 $posts = $posts[$parent->id]->children;
5812 $modcontext = context_module::instance($cm->id);
5813 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
5815 foreach ($posts as $post) {
5817 echo '<div class="indent">';
5818 if ($depth > 0) {
5819 $ownpost = ($USER->id == $post->userid);
5820 $post->subject = format_string($post->subject);
5822 $postread = !empty($post->postread);
5824 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5825 '', '', $postread, true, $forumtracked);
5826 } else {
5827 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
5828 echo "</div>\n";
5829 continue;
5831 $by = new stdClass();
5832 $by->name = fullname($post, $canviewfullnames);
5833 $by->date = userdate($post->modified);
5835 if ($forumtracked) {
5836 if (!empty($post->postread)) {
5837 $style = '<span class="forumthread read">';
5838 } else {
5839 $style = '<span class="forumthread unread">';
5841 } else {
5842 $style = '<span class="forumthread">';
5844 echo $style."<a name=\"$post->id\"></a>".
5845 "<a href=\"discuss.php?d=$post->discussion&amp;parent=$post->id\">".format_string($post->subject,true)."</a> ";
5846 print_string("bynameondate", "forum", $by);
5847 echo "</span>";
5850 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $reply, $forumtracked, $posts);
5851 echo "</div>\n";
5857 * @todo Document this function
5858 * @global object
5859 * @global object
5860 * @return void
5862 function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $reply, $forumtracked, $posts) {
5863 global $USER, $CFG;
5865 $link = false;
5867 if (!empty($posts[$parent->id]->children)) {
5868 $posts = $posts[$parent->id]->children;
5870 foreach ($posts as $post) {
5872 echo '<div class="indent">';
5873 if (!isloggedin()) {
5874 $ownpost = false;
5875 } else {
5876 $ownpost = ($USER->id == $post->userid);
5879 $post->subject = format_string($post->subject);
5880 $postread = !empty($post->postread);
5882 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5883 '', '', $postread, true, $forumtracked);
5884 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5885 echo "</div>\n";
5891 * Returns all forum posts since a given time in specified forum.
5893 * @todo Document this functions args
5894 * @global object
5895 * @global object
5896 * @global object
5897 * @global object
5899 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
5900 global $CFG, $COURSE, $USER, $DB;
5902 if ($COURSE->id == $courseid) {
5903 $course = $COURSE;
5904 } else {
5905 $course = $DB->get_record('course', array('id' => $courseid));
5908 $modinfo = get_fast_modinfo($course);
5910 $cm = $modinfo->cms[$cmid];
5911 $params = array($timestart, $cm->instance);
5913 if ($userid) {
5914 $userselect = "AND u.id = ?";
5915 $params[] = $userid;
5916 } else {
5917 $userselect = "";
5920 if ($groupid) {
5921 $groupselect = "AND d.groupid = ?";
5922 $params[] = $groupid;
5923 } else {
5924 $groupselect = "";
5927 $allnames = get_all_user_name_fields(true, 'u');
5928 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
5929 d.timestart, d.timeend, d.userid AS duserid,
5930 $allnames, u.email, u.picture, u.imagealt, u.email
5931 FROM {forum_posts} p
5932 JOIN {forum_discussions} d ON d.id = p.discussion
5933 JOIN {forum} f ON f.id = d.forum
5934 JOIN {user} u ON u.id = p.userid
5935 WHERE p.created > ? AND f.id = ?
5936 $userselect $groupselect
5937 ORDER BY p.id ASC", $params)) { // order by initial posting date
5938 return;
5941 $groupmode = groups_get_activity_groupmode($cm, $course);
5942 $cm_context = context_module::instance($cm->id);
5943 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
5944 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
5946 $printposts = array();
5947 foreach ($posts as $post) {
5949 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
5950 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
5951 if (!$viewhiddentimed) {
5952 continue;
5956 if ($groupmode) {
5957 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
5958 // oki (Open discussions have groupid -1)
5959 } else {
5960 // separate mode
5961 if (isguestuser()) {
5962 // shortcut
5963 continue;
5966 if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
5967 continue;
5972 $printposts[] = $post;
5975 if (!$printposts) {
5976 return;
5979 $aname = format_string($cm->name,true);
5981 foreach ($printposts as $post) {
5982 $tmpactivity = new stdClass();
5984 $tmpactivity->type = 'forum';
5985 $tmpactivity->cmid = $cm->id;
5986 $tmpactivity->name = $aname;
5987 $tmpactivity->sectionnum = $cm->sectionnum;
5988 $tmpactivity->timestamp = $post->modified;
5990 $tmpactivity->content = new stdClass();
5991 $tmpactivity->content->id = $post->id;
5992 $tmpactivity->content->discussion = $post->discussion;
5993 $tmpactivity->content->subject = format_string($post->subject);
5994 $tmpactivity->content->parent = $post->parent;
5995 $tmpactivity->content->forumtype = $post->forumtype;
5997 $tmpactivity->user = new stdClass();
5998 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
5999 $additionalfields = explode(',', user_picture::fields());
6000 $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
6001 $tmpactivity->user->id = $post->userid;
6003 $activities[$index++] = $tmpactivity;
6006 return;
6010 * Outputs the forum post indicated by $activity.
6012 * @param object $activity the activity object the forum resides in
6013 * @param int $courseid the id of the course the forum resides in
6014 * @param bool $detail not used, but required for compatibilty with other modules
6015 * @param int $modnames not used, but required for compatibilty with other modules
6016 * @param bool $viewfullnames not used, but required for compatibilty with other modules
6018 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
6019 global $OUTPUT;
6021 $content = $activity->content;
6022 if ($content->parent) {
6023 $class = 'reply';
6024 } else {
6025 $class = 'discussion';
6028 $tableoptions = [
6029 'border' => '0',
6030 'cellpadding' => '3',
6031 'cellspacing' => '0',
6032 'class' => 'forum-recent'
6034 $output = html_writer::start_tag('table', $tableoptions);
6035 $output .= html_writer::start_tag('tr');
6037 $post = (object) ['parent' => $content->parent];
6038 $forum = (object) ['type' => $content->forumtype];
6039 $authorhidden = forum_is_author_hidden($post, $forum);
6041 // Show user picture if author should not be hidden.
6042 if (!$authorhidden) {
6043 $pictureoptions = [
6044 'courseid' => $courseid,
6045 'link' => $authorhidden,
6046 'alttext' => $authorhidden,
6048 $picture = $OUTPUT->user_picture($activity->user, $pictureoptions);
6049 $output .= html_writer::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
6052 // Discussion title and author.
6053 $output .= html_writer::start_tag('td', ['class' => $class]);
6054 if ($content->parent) {
6055 $class = 'title';
6056 } else {
6057 // Bold the title of new discussions so they stand out.
6058 $class = 'title bold';
6061 $output .= html_writer::start_div($class);
6062 if ($detail) {
6063 $aname = s($activity->name);
6064 $output .= $OUTPUT->image_icon('icon', $aname, $activity->type);
6066 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion]);
6067 $discussionurl->set_anchor('p' . $activity->content->id);
6068 $output .= html_writer::link($discussionurl, $content->subject);
6069 $output .= html_writer::end_div();
6071 $timestamp = userdate($activity->timestamp);
6072 if ($authorhidden) {
6073 $authornamedate = $timestamp;
6074 } else {
6075 $fullname = fullname($activity->user, $viewfullnames);
6076 $userurl = new moodle_url('/user/view.php');
6077 $userurl->params(['id' => $activity->user->id, 'course' => $courseid]);
6078 $by = new stdClass();
6079 $by->name = html_writer::link($userurl, $fullname);
6080 $by->date = $timestamp;
6081 $authornamedate = get_string('bynameondate', 'forum', $by);
6083 $output .= html_writer::div($authornamedate, 'user');
6084 $output .= html_writer::end_tag('td');
6085 $output .= html_writer::end_tag('tr');
6086 $output .= html_writer::end_tag('table');
6088 echo $output;
6092 * recursively sets the discussion field to $discussionid on $postid and all its children
6093 * used when pruning a post
6095 * @global object
6096 * @param int $postid
6097 * @param int $discussionid
6098 * @return bool
6100 function forum_change_discussionid($postid, $discussionid) {
6101 global $DB;
6102 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
6103 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
6104 foreach ($posts as $post) {
6105 forum_change_discussionid($post->id, $discussionid);
6108 return true;
6112 * Prints the editing button on subscribers page
6114 * @global object
6115 * @global object
6116 * @param int $courseid
6117 * @param int $forumid
6118 * @return string
6120 function forum_update_subscriptions_button($courseid, $forumid) {
6121 global $CFG, $USER;
6123 if (!empty($USER->subscriptionsediting)) {
6124 $string = get_string('managesubscriptionsoff', 'forum');
6125 $edit = "off";
6126 } else {
6127 $string = get_string('managesubscriptionson', 'forum');
6128 $edit = "on";
6131 $subscribers = html_writer::start_tag('form', array('action' => $CFG->wwwroot . '/mod/forum/subscribers.php',
6132 'method' => 'get', 'class' => 'form-inline'));
6133 $subscribers .= html_writer::empty_tag('input', array('type' => 'submit', 'value' => $string,
6134 'class' => 'btn btn-secondary'));
6135 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $forumid));
6136 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'edit', 'value' => $edit));
6137 $subscribers .= html_writer::end_tag('form');
6139 return $subscribers;
6142 // Functions to do with read tracking.
6145 * Mark posts as read.
6147 * @global object
6148 * @global object
6149 * @param object $user object
6150 * @param array $postids array of post ids
6151 * @return boolean success
6153 function forum_tp_mark_posts_read($user, $postids) {
6154 global $CFG, $DB;
6156 if (!forum_tp_can_track_forums(false, $user)) {
6157 return true;
6160 $status = true;
6162 $now = time();
6163 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6165 if (empty($postids)) {
6166 return true;
6168 } else if (count($postids) > 200) {
6169 while ($part = array_splice($postids, 0, 200)) {
6170 $status = forum_tp_mark_posts_read($user, $part) && $status;
6172 return $status;
6175 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid');
6177 $insertparams = array(
6178 'userid1' => $user->id,
6179 'userid2' => $user->id,
6180 'userid3' => $user->id,
6181 'firstread' => $now,
6182 'lastread' => $now,
6183 'cutoffdate' => $cutoffdate,
6185 $params = array_merge($postidparams, $insertparams);
6187 if ($CFG->forum_allowforcedreadtracking) {
6188 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6189 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))";
6190 } else {
6191 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6192 AND tf.id IS NULL)";
6195 // First insert any new entries.
6196 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6198 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
6199 FROM {forum_posts} p
6200 JOIN {forum_discussions} d ON d.id = p.discussion
6201 JOIN {forum} f ON f.id = d.forum
6202 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
6203 LEFT JOIN {forum_read} fr ON (
6204 fr.userid = :userid3
6205 AND fr.postid = p.id
6206 AND fr.discussionid = d.id
6207 AND fr.forumid = f.id
6209 WHERE p.id $usql
6210 AND p.modified >= :cutoffdate
6211 $trackingsql
6212 AND fr.id IS NULL";
6214 $status = $DB->execute($sql, $params) && $status;
6216 // Then update all records.
6217 $updateparams = array(
6218 'userid' => $user->id,
6219 'lastread' => $now,
6221 $params = array_merge($postidparams, $updateparams);
6222 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
6223 userid = :userid
6224 AND lastread <> :lastread
6225 AND postid ' . $usql,
6226 $params) && $status;
6228 return $status;
6232 * Mark post as read.
6233 * @global object
6234 * @global object
6235 * @param int $userid
6236 * @param int $postid
6238 function forum_tp_add_read_record($userid, $postid) {
6239 global $CFG, $DB;
6241 $now = time();
6242 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6244 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
6245 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6247 SELECT ?, p.id, p.discussion, d.forum, ?, ?
6248 FROM {forum_posts} p
6249 JOIN {forum_discussions} d ON d.id = p.discussion
6250 WHERE p.id = ? AND p.modified >= ?";
6251 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
6253 } else {
6254 $sql = "UPDATE {forum_read}
6255 SET lastread = ?
6256 WHERE userid = ? AND postid = ?";
6257 return $DB->execute($sql, array($now, $userid, $userid));
6262 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
6264 * @param int $userid The ID of the user to mark posts read for.
6265 * @param object $post The post record for the post to mark as read.
6266 * @param mixed $unused
6267 * @return bool
6269 function forum_tp_mark_post_read($userid, $post, $unused = null) {
6270 if (!forum_tp_is_post_old($post)) {
6271 return forum_tp_add_read_record($userid, $post->id);
6272 } else {
6273 return true;
6278 * Marks a whole forum as read, for a given user
6280 * @global object
6281 * @global object
6282 * @param object $user
6283 * @param int $forumid
6284 * @param int|bool $groupid
6285 * @return bool
6287 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
6288 global $CFG, $DB;
6290 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6292 $groupsel = "";
6293 $params = array($user->id, $forumid, $cutoffdate);
6295 if ($groupid !== false) {
6296 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
6297 $params[] = $groupid;
6300 $sql = "SELECT p.id
6301 FROM {forum_posts} p
6302 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
6303 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6304 WHERE d.forum = ?
6305 AND p.modified >= ? AND r.id is NULL
6306 $groupsel";
6308 if ($posts = $DB->get_records_sql($sql, $params)) {
6309 $postids = array_keys($posts);
6310 return forum_tp_mark_posts_read($user, $postids);
6313 return true;
6317 * Marks a whole discussion as read, for a given user
6319 * @global object
6320 * @global object
6321 * @param object $user
6322 * @param int $discussionid
6323 * @return bool
6325 function forum_tp_mark_discussion_read($user, $discussionid) {
6326 global $CFG, $DB;
6328 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6330 $sql = "SELECT p.id
6331 FROM {forum_posts} p
6332 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6333 WHERE p.discussion = ?
6334 AND p.modified >= ? AND r.id is NULL";
6336 if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) {
6337 $postids = array_keys($posts);
6338 return forum_tp_mark_posts_read($user, $postids);
6341 return true;
6345 * @global object
6346 * @param int $userid
6347 * @param object $post
6349 function forum_tp_is_post_read($userid, $post) {
6350 global $DB;
6351 return (forum_tp_is_post_old($post) ||
6352 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id)));
6356 * @global object
6357 * @param object $post
6358 * @param int $time Defautls to time()
6360 function forum_tp_is_post_old($post, $time=null) {
6361 global $CFG;
6363 if (is_null($time)) {
6364 $time = time();
6366 return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600)));
6370 * Returns the count of records for the provided user and course.
6371 * Please note that group access is ignored!
6373 * @global object
6374 * @global object
6375 * @param int $userid
6376 * @param int $courseid
6377 * @return array
6379 function forum_tp_get_course_unread_posts($userid, $courseid) {
6380 global $CFG, $DB;
6382 $now = floor(time() / 60) * 60; // DB cache friendliness.
6383 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 60 * 60);
6384 $params = array($userid, $userid, $courseid, $cutoffdate, $userid);
6386 if (!empty($CFG->forum_enabletimedposts)) {
6387 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6388 $params[] = $now;
6389 $params[] = $now;
6390 } else {
6391 $timedsql = "";
6394 if ($CFG->forum_allowforcedreadtracking) {
6395 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6396 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL
6397 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))";
6398 } else {
6399 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6400 AND tf.id IS NULL
6401 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)";
6404 $sql = "SELECT f.id, COUNT(p.id) AS unread
6405 FROM {forum_posts} p
6406 JOIN {forum_discussions} d ON d.id = p.discussion
6407 JOIN {forum} f ON f.id = d.forum
6408 JOIN {course} c ON c.id = f.course
6409 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6410 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id)
6411 WHERE f.course = ?
6412 AND p.modified >= ? AND r.id is NULL
6413 $trackingsql
6414 $timedsql
6415 GROUP BY f.id";
6417 if ($return = $DB->get_records_sql($sql, $params)) {
6418 return $return;
6421 return array();
6425 * Returns the count of records for the provided user and forum and [optionally] group.
6427 * @global object
6428 * @global object
6429 * @global object
6430 * @param object $cm
6431 * @param object $course
6432 * @param bool $resetreadcache optional, true to reset the function static $readcache var
6433 * @return int
6435 function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) {
6436 global $CFG, $USER, $DB;
6438 static $readcache = array();
6440 if ($resetreadcache) {
6441 $readcache = array();
6444 $forumid = $cm->instance;
6446 if (!isset($readcache[$course->id])) {
6447 $readcache[$course->id] = array();
6448 if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
6449 foreach ($counts as $count) {
6450 $readcache[$course->id][$count->id] = $count->unread;
6455 if (empty($readcache[$course->id][$forumid])) {
6456 // no need to check group mode ;-)
6457 return 0;
6460 $groupmode = groups_get_activity_groupmode($cm, $course);
6462 if ($groupmode != SEPARATEGROUPS) {
6463 return $readcache[$course->id][$forumid];
6466 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
6467 return $readcache[$course->id][$forumid];
6470 require_once($CFG->dirroot.'/course/lib.php');
6472 $modinfo = get_fast_modinfo($course);
6474 $mygroups = $modinfo->get_groups($cm->groupingid);
6476 // add all groups posts
6477 $mygroups[-1] = -1;
6479 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);
6481 $now = floor(time() / 60) * 60; // DB Cache friendliness.
6482 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
6483 $params = array($USER->id, $forumid, $cutoffdate);
6485 if (!empty($CFG->forum_enabletimedposts)) {
6486 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6487 $params[] = $now;
6488 $params[] = $now;
6489 } else {
6490 $timedsql = "";
6493 $params = array_merge($params, $groups_params);
6495 $sql = "SELECT COUNT(p.id)
6496 FROM {forum_posts} p
6497 JOIN {forum_discussions} d ON p.discussion = d.id
6498 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6499 WHERE d.forum = ?
6500 AND p.modified >= ? AND r.id is NULL
6501 $timedsql
6502 AND d.groupid $groups_sql";
6504 return $DB->get_field_sql($sql, $params);
6508 * Deletes read records for the specified index. At least one parameter must be specified.
6510 * @global object
6511 * @param int $userid
6512 * @param int $postid
6513 * @param int $discussionid
6514 * @param int $forumid
6515 * @return bool
6517 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
6518 global $DB;
6519 $params = array();
6521 $select = '';
6522 if ($userid > -1) {
6523 if ($select != '') $select .= ' AND ';
6524 $select .= 'userid = ?';
6525 $params[] = $userid;
6527 if ($postid > -1) {
6528 if ($select != '') $select .= ' AND ';
6529 $select .= 'postid = ?';
6530 $params[] = $postid;
6532 if ($discussionid > -1) {
6533 if ($select != '') $select .= ' AND ';
6534 $select .= 'discussionid = ?';
6535 $params[] = $discussionid;
6537 if ($forumid > -1) {
6538 if ($select != '') $select .= ' AND ';
6539 $select .= 'forumid = ?';
6540 $params[] = $forumid;
6542 if ($select == '') {
6543 return false;
6545 else {
6546 return $DB->delete_records_select('forum_read', $select, $params);
6550 * Get a list of forums not tracked by the user.
6552 * @global object
6553 * @global object
6554 * @param int $userid The id of the user to use.
6555 * @param int $courseid The id of the course being checked.
6556 * @return mixed An array indexed by forum id, or false.
6558 function forum_tp_get_untracked_forums($userid, $courseid) {
6559 global $CFG, $DB;
6561 if ($CFG->forum_allowforcedreadtracking) {
6562 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6563 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL
6564 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6565 } else {
6566 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6567 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6568 AND (ft.id IS NOT NULL
6569 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6572 $sql = "SELECT f.id
6573 FROM {forum} f
6574 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
6575 WHERE f.course = ?
6576 $trackingsql";
6578 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
6579 foreach ($forums as $forum) {
6580 $forums[$forum->id] = $forum;
6582 return $forums;
6584 } else {
6585 return array();
6590 * Determine if a user can track forums and optionally a particular forum.
6591 * Checks the site settings, the user settings and the forum settings (if
6592 * requested).
6594 * @global object
6595 * @global object
6596 * @global object
6597 * @param mixed $forum The forum object to test, or the int id (optional).
6598 * @param mixed $userid The user object to check for (optional).
6599 * @return boolean
6601 function forum_tp_can_track_forums($forum=false, $user=false) {
6602 global $USER, $CFG, $DB;
6604 // if possible, avoid expensive
6605 // queries
6606 if (empty($CFG->forum_trackreadposts)) {
6607 return false;
6610 if ($user === false) {
6611 $user = $USER;
6614 if (isguestuser($user) or empty($user->id)) {
6615 return false;
6618 if ($forum === false) {
6619 if ($CFG->forum_allowforcedreadtracking) {
6620 // Since we can force tracking, assume yes without a specific forum.
6621 return true;
6622 } else {
6623 return (bool)$user->trackforums;
6627 // Work toward always passing an object...
6628 if (is_numeric($forum)) {
6629 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6630 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
6633 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6634 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6636 if ($CFG->forum_allowforcedreadtracking) {
6637 // If we allow forcing, then forced forums takes procidence over user setting.
6638 return ($forumforced || ($forumallows && (!empty($user->trackforums) && (bool)$user->trackforums)));
6639 } else {
6640 // If we don't allow forcing, user setting trumps.
6641 return ($forumforced || $forumallows) && !empty($user->trackforums);
6646 * Tells whether a specific forum is tracked by the user. A user can optionally
6647 * be specified. If not specified, the current user is assumed.
6649 * @global object
6650 * @global object
6651 * @global object
6652 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
6653 * @param int $userid The id of the user being checked (optional).
6654 * @return boolean
6656 function forum_tp_is_tracked($forum, $user=false) {
6657 global $USER, $CFG, $DB;
6659 if ($user === false) {
6660 $user = $USER;
6663 if (isguestuser($user) or empty($user->id)) {
6664 return false;
6667 // Work toward always passing an object...
6668 if (is_numeric($forum)) {
6669 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6670 $forum = $DB->get_record('forum', array('id' => $forum));
6673 if (!forum_tp_can_track_forums($forum, $user)) {
6674 return false;
6677 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6678 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6679 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id));
6681 if ($CFG->forum_allowforcedreadtracking) {
6682 return $forumforced || ($forumallows && $userpref === false);
6683 } else {
6684 return ($forumallows || $forumforced) && $userpref === false;
6689 * @global object
6690 * @global object
6691 * @param int $forumid
6692 * @param int $userid
6694 function forum_tp_start_tracking($forumid, $userid=false) {
6695 global $USER, $DB;
6697 if ($userid === false) {
6698 $userid = $USER->id;
6701 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
6705 * @global object
6706 * @global object
6707 * @param int $forumid
6708 * @param int $userid
6710 function forum_tp_stop_tracking($forumid, $userid=false) {
6711 global $USER, $DB;
6713 if ($userid === false) {
6714 $userid = $USER->id;
6717 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
6718 $track_prefs = new stdClass();
6719 $track_prefs->userid = $userid;
6720 $track_prefs->forumid = $forumid;
6721 $DB->insert_record('forum_track_prefs', $track_prefs);
6724 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
6729 * Clean old records from the forum_read table.
6730 * @global object
6731 * @global object
6732 * @return void
6734 function forum_tp_clean_read_records() {
6735 global $CFG, $DB;
6737 if (!isset($CFG->forum_oldpostdays)) {
6738 return;
6740 // Look for records older than the cutoffdate that are still in the forum_read table.
6741 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6743 //first get the oldest tracking present - we need tis to speedup the next delete query
6744 $sql = "SELECT MIN(fp.modified) AS first
6745 FROM {forum_posts} fp
6746 JOIN {forum_read} fr ON fr.postid=fp.id";
6747 if (!$first = $DB->get_field_sql($sql)) {
6748 // nothing to delete;
6749 return;
6752 // now delete old tracking info
6753 $sql = "DELETE
6754 FROM {forum_read}
6755 WHERE postid IN (SELECT fp.id
6756 FROM {forum_posts} fp
6757 WHERE fp.modified >= ? AND fp.modified < ?)";
6758 $DB->execute($sql, array($first, $cutoffdate));
6762 * Sets the last post for a given discussion
6764 * @global object
6765 * @global object
6766 * @param into $discussionid
6767 * @return bool|int
6769 function forum_discussion_update_last_post($discussionid) {
6770 global $CFG, $DB;
6772 // Check the given discussion exists
6773 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
6774 return false;
6777 // Use SQL to find the last post for this discussion
6778 $sql = "SELECT id, userid, modified
6779 FROM {forum_posts}
6780 WHERE discussion=?
6781 ORDER BY modified DESC";
6783 // Lets go find the last post
6784 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
6785 $lastpost = reset($lastposts);
6786 $discussionobject = new stdClass();
6787 $discussionobject->id = $discussionid;
6788 $discussionobject->usermodified = $lastpost->userid;
6789 $discussionobject->timemodified = $lastpost->modified;
6790 $DB->update_record('forum_discussions', $discussionobject);
6791 return $lastpost->id;
6794 // To get here either we couldn't find a post for the discussion (weird)
6795 // or we couldn't update the discussion record (weird x2)
6796 return false;
6801 * List the actions that correspond to a view of this module.
6802 * This is used by the participation report.
6804 * Note: This is not used by new logging system. Event with
6805 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
6806 * be considered as view action.
6808 * @return array
6810 function forum_get_view_actions() {
6811 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
6815 * List the options for forum subscription modes.
6816 * This is used by the settings page and by the mod_form page.
6818 * @return array
6820 function forum_get_subscriptionmode_options() {
6821 $options = array();
6822 $options[FORUM_CHOOSESUBSCRIBE] = get_string('subscriptionoptional', 'forum');
6823 $options[FORUM_FORCESUBSCRIBE] = get_string('subscriptionforced', 'forum');
6824 $options[FORUM_INITIALSUBSCRIBE] = get_string('subscriptionauto', 'forum');
6825 $options[FORUM_DISALLOWSUBSCRIBE] = get_string('subscriptiondisabled', 'forum');
6826 return $options;
6830 * List the actions that correspond to a post of this module.
6831 * This is used by the participation report.
6833 * Note: This is not used by new logging system. Event with
6834 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
6835 * will be considered as post action.
6837 * @return array
6839 function forum_get_post_actions() {
6840 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
6844 * Returns a warning object if a user has reached the number of posts equal to
6845 * the warning/blocking setting, or false if there is no warning to show.
6847 * @param int|stdClass $forum the forum id or the forum object
6848 * @param stdClass $cm the course module
6849 * @return stdClass|bool returns an object with the warning information, else
6850 * returns false if no warning is required.
6852 function forum_check_throttling($forum, $cm = null) {
6853 global $CFG, $DB, $USER;
6855 if (is_numeric($forum)) {
6856 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST);
6859 if (!is_object($forum)) {
6860 return false; // This is broken.
6863 if (!$cm) {
6864 $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST);
6867 if (empty($forum->blockafter)) {
6868 return false;
6871 if (empty($forum->blockperiod)) {
6872 return false;
6875 $modcontext = context_module::instance($cm->id);
6876 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
6877 return false;
6880 // Get the number of posts in the last period we care about.
6881 $timenow = time();
6882 $timeafter = $timenow - $forum->blockperiod;
6883 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
6884 JOIN {forum_discussions} d
6885 ON p.discussion = d.id WHERE d.forum = ?
6886 AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter));
6888 $a = new stdClass();
6889 $a->blockafter = $forum->blockafter;
6890 $a->numposts = $numposts;
6891 $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
6893 if ($forum->blockafter <= $numposts) {
6894 $warning = new stdClass();
6895 $warning->canpost = false;
6896 $warning->errorcode = 'forumblockingtoomanyposts';
6897 $warning->module = 'error';
6898 $warning->additional = $a;
6899 $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id;
6901 return $warning;
6904 if ($forum->warnafter <= $numposts) {
6905 $warning = new stdClass();
6906 $warning->canpost = true;
6907 $warning->errorcode = 'forumblockingalmosttoomanyposts';
6908 $warning->module = 'forum';
6909 $warning->additional = $a;
6910 $warning->link = null;
6912 return $warning;
6917 * Throws an error if the user is no longer allowed to post due to having reached
6918 * or exceeded the number of posts specified in 'Post threshold for blocking'
6919 * setting.
6921 * @since Moodle 2.5
6922 * @param stdClass $thresholdwarning the warning information returned
6923 * from the function forum_check_throttling.
6925 function forum_check_blocking_threshold($thresholdwarning) {
6926 if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
6927 print_error($thresholdwarning->errorcode,
6928 $thresholdwarning->module,
6929 $thresholdwarning->link,
6930 $thresholdwarning->additional);
6936 * Removes all grades from gradebook
6938 * @global object
6939 * @global object
6940 * @param int $courseid
6941 * @param string $type optional
6943 function forum_reset_gradebook($courseid, $type='') {
6944 global $CFG, $DB;
6946 $wheresql = '';
6947 $params = array($courseid);
6948 if ($type) {
6949 $wheresql = "AND f.type=?";
6950 $params[] = $type;
6953 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
6954 FROM {forum} f, {course_modules} cm, {modules} m
6955 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
6957 if ($forums = $DB->get_records_sql($sql, $params)) {
6958 foreach ($forums as $forum) {
6959 forum_grade_item_update($forum, 'reset');
6965 * This function is used by the reset_course_userdata function in moodlelib.
6966 * This function will remove all posts from the specified forum
6967 * and clean up any related data.
6969 * @global object
6970 * @global object
6971 * @param $data the data submitted from the reset course.
6972 * @return array status array
6974 function forum_reset_userdata($data) {
6975 global $CFG, $DB;
6976 require_once($CFG->dirroot.'/rating/lib.php');
6978 $componentstr = get_string('modulenameplural', 'forum');
6979 $status = array();
6981 $params = array($data->courseid);
6983 $removeposts = false;
6984 $typesql = "";
6985 if (!empty($data->reset_forum_all)) {
6986 $removeposts = true;
6987 $typesstr = get_string('resetforumsall', 'forum');
6988 $types = array();
6989 } else if (!empty($data->reset_forum_types)){
6990 $removeposts = true;
6991 $types = array();
6992 $sqltypes = array();
6993 $forum_types_all = forum_get_forum_types_all();
6994 foreach ($data->reset_forum_types as $type) {
6995 if (!array_key_exists($type, $forum_types_all)) {
6996 continue;
6998 $types[] = $forum_types_all[$type];
6999 $sqltypes[] = $type;
7001 if (!empty($sqltypes)) {
7002 list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
7003 $typesql = " AND f.type " . $typesql;
7004 $params = array_merge($params, $typeparams);
7006 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
7008 $alldiscussionssql = "SELECT fd.id
7009 FROM {forum_discussions} fd, {forum} f
7010 WHERE f.course=? AND f.id=fd.forum";
7012 $allforumssql = "SELECT f.id
7013 FROM {forum} f
7014 WHERE f.course=?";
7016 $allpostssql = "SELECT fp.id
7017 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
7018 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
7020 $forumssql = $forums = $rm = null;
7022 // Check if we need to get additional data.
7023 if ($removeposts || !empty($data->reset_forum_ratings) || !empty($data->reset_forum_tags)) {
7024 // Set this up if we have to remove ratings.
7025 $rm = new rating_manager();
7026 $ratingdeloptions = new stdClass;
7027 $ratingdeloptions->component = 'mod_forum';
7028 $ratingdeloptions->ratingarea = 'post';
7030 // Get the forums for actions that require it.
7031 $forumssql = "$allforumssql $typesql";
7032 $forums = $DB->get_records_sql($forumssql, $params);
7035 if ($removeposts) {
7036 $discussionssql = "$alldiscussionssql $typesql";
7037 $postssql = "$allpostssql $typesql";
7039 // now get rid of all attachments
7040 $fs = get_file_storage();
7041 if ($forums) {
7042 foreach ($forums as $forumid=>$unused) {
7043 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7044 continue;
7046 $context = context_module::instance($cm->id);
7047 $fs->delete_area_files($context->id, 'mod_forum', 'attachment');
7048 $fs->delete_area_files($context->id, 'mod_forum', 'post');
7050 //remove ratings
7051 $ratingdeloptions->contextid = $context->id;
7052 $rm->delete_ratings($ratingdeloptions);
7054 core_tag_tag::delete_instances('mod_forum', null, $context->id);
7058 // first delete all read flags
7059 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
7061 // remove tracking prefs
7062 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
7064 // remove posts from queue
7065 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
7067 // all posts - initial posts must be kept in single simple discussion forums
7068 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
7069 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql AND f.type <> 'single') AND parent = 0", $params); // now the initial posts for non single simple
7071 // finally all discussions except single simple forums
7072 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
7074 // remove all grades from gradebook
7075 if (empty($data->reset_gradebook_grades)) {
7076 if (empty($types)) {
7077 forum_reset_gradebook($data->courseid);
7078 } else {
7079 foreach ($types as $type) {
7080 forum_reset_gradebook($data->courseid, $type);
7085 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
7088 // remove all ratings in this course's forums
7089 if (!empty($data->reset_forum_ratings)) {
7090 if ($forums) {
7091 foreach ($forums as $forumid=>$unused) {
7092 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7093 continue;
7095 $context = context_module::instance($cm->id);
7097 //remove ratings
7098 $ratingdeloptions->contextid = $context->id;
7099 $rm->delete_ratings($ratingdeloptions);
7103 // remove all grades from gradebook
7104 if (empty($data->reset_gradebook_grades)) {
7105 forum_reset_gradebook($data->courseid);
7109 // Remove all the tags.
7110 if (!empty($data->reset_forum_tags)) {
7111 if ($forums) {
7112 foreach ($forums as $forumid => $unused) {
7113 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7114 continue;
7117 $context = context_module::instance($cm->id);
7118 core_tag_tag::delete_instances('mod_forum', null, $context->id);
7122 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false);
7125 // remove all digest settings unconditionally - even for users still enrolled in course.
7126 if (!empty($data->reset_forum_digests)) {
7127 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
7128 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
7131 // remove all subscriptions unconditionally - even for users still enrolled in course
7132 if (!empty($data->reset_forum_subscriptions)) {
7133 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
7134 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
7135 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
7138 // remove all tracking prefs unconditionally - even for users still enrolled in course
7139 if (!empty($data->reset_forum_track_prefs)) {
7140 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
7141 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
7144 /// updating dates - shift may be negative too
7145 if ($data->timeshift) {
7146 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
7147 // See MDL-9367.
7148 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
7149 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
7152 return $status;
7156 * Called by course/reset.php
7158 * @param $mform form passed by reference
7160 function forum_reset_course_form_definition(&$mform) {
7161 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
7163 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
7165 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
7166 $mform->setAdvanced('reset_forum_types');
7167 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
7169 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
7170 $mform->setAdvanced('reset_forum_digests');
7172 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
7173 $mform->setAdvanced('reset_forum_subscriptions');
7175 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
7176 $mform->setAdvanced('reset_forum_track_prefs');
7177 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
7179 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
7180 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
7182 $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum'));
7183 $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked');
7187 * Course reset form defaults.
7188 * @return array
7190 function forum_reset_course_form_defaults($course) {
7191 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
7195 * Returns array of forum layout modes
7197 * @return array
7199 function forum_get_layout_modes() {
7200 return array (FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
7201 FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
7202 FORUM_MODE_THREADED => get_string('modethreaded', 'forum'),
7203 FORUM_MODE_NESTED => get_string('modenested', 'forum'));
7207 * Returns array of forum types chooseable on the forum editing form
7209 * @return array
7211 function forum_get_forum_types() {
7212 return array ('general' => get_string('generalforum', 'forum'),
7213 'eachuser' => get_string('eachuserforum', 'forum'),
7214 'single' => get_string('singleforum', 'forum'),
7215 'qanda' => get_string('qandaforum', 'forum'),
7216 'blog' => get_string('blogforum', 'forum'));
7220 * Returns array of all forum layout modes
7222 * @return array
7224 function forum_get_forum_types_all() {
7225 return array ('news' => get_string('namenews','forum'),
7226 'social' => get_string('namesocial','forum'),
7227 'general' => get_string('generalforum', 'forum'),
7228 'eachuser' => get_string('eachuserforum', 'forum'),
7229 'single' => get_string('singleforum', 'forum'),
7230 'qanda' => get_string('qandaforum', 'forum'),
7231 'blog' => get_string('blogforum', 'forum'));
7235 * Returns all other caps used in module
7237 * @return array
7239 function forum_get_extra_capabilities() {
7240 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate');
7244 * Adds module specific settings to the settings block
7246 * @param settings_navigation $settings The settings navigation object
7247 * @param navigation_node $forumnode The node to add module settings to
7249 function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
7250 global $USER, $PAGE, $CFG, $DB, $OUTPUT;
7252 $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm->instance));
7253 if (empty($PAGE->cm->context)) {
7254 $PAGE->cm->context = context_module::instance($PAGE->cm->instance);
7257 $params = $PAGE->url->params();
7258 if (!empty($params['d'])) {
7259 $discussionid = $params['d'];
7262 // for some actions you need to be enrolled, beiing admin is not enough sometimes here
7263 $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
7264 $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);
7266 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context);
7267 $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject);
7268 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) &&
7269 (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage);
7271 if ($canmanage) {
7272 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);
7273 $mode->add_class('subscriptionmode');
7275 $allowchoice = $mode->add(get_string('subscriptionoptional', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_CHOOSESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7276 $forceforever = $mode->add(get_string("subscriptionforced", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_FORCESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7277 $forceinitially = $mode->add(get_string("subscriptionauto", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_INITIALSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7278 $disallowchoice = $mode->add(get_string('subscriptiondisabled', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_DISALLOWSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7280 switch ($subscriptionmode) {
7281 case FORUM_CHOOSESUBSCRIBE : // 0
7282 $allowchoice->action = null;
7283 $allowchoice->add_class('activesetting');
7284 $allowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
7285 break;
7286 case FORUM_FORCESUBSCRIBE : // 1
7287 $forceforever->action = null;
7288 $forceforever->add_class('activesetting');
7289 $forceforever->icon = new pix_icon('t/selected', '', 'mod_forum');
7290 break;
7291 case FORUM_INITIALSUBSCRIBE : // 2
7292 $forceinitially->action = null;
7293 $forceinitially->add_class('activesetting');
7294 $forceinitially->icon = new pix_icon('t/selected', '', 'mod_forum');
7295 break;
7296 case FORUM_DISALLOWSUBSCRIBE : // 3
7297 $disallowchoice->action = null;
7298 $disallowchoice->add_class('activesetting');
7299 $disallowchoice->icon = new pix_icon('t/selected', '', 'mod_forum');
7300 break;
7303 } else if ($activeenrolled) {
7305 switch ($subscriptionmode) {
7306 case FORUM_CHOOSESUBSCRIBE : // 0
7307 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
7308 break;
7309 case FORUM_FORCESUBSCRIBE : // 1
7310 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
7311 break;
7312 case FORUM_INITIALSUBSCRIBE : // 2
7313 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
7314 break;
7315 case FORUM_DISALLOWSUBSCRIBE : // 3
7316 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
7317 break;
7321 if ($cansubscribe) {
7322 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, null, $PAGE->cm)) {
7323 $linktext = get_string('unsubscribe', 'forum');
7324 } else {
7325 $linktext = get_string('subscribe', 'forum');
7327 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey()));
7328 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7330 if (isset($discussionid)) {
7331 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, $discussionid, $PAGE->cm)) {
7332 $linktext = get_string('unsubscribediscussion', 'forum');
7333 } else {
7334 $linktext = get_string('subscribediscussion', 'forum');
7336 $url = new moodle_url('/mod/forum/subscribe.php', array(
7337 'id' => $forumobject->id,
7338 'sesskey' => sesskey(),
7339 'd' => $discussionid,
7340 'returnurl' => $PAGE->url->out(),
7342 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7346 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){
7347 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id));
7348 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING);
7351 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
7352 if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL
7353 || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) {
7354 if (forum_tp_is_tracked($forumobject)) {
7355 $linktext = get_string('notrackforum', 'forum');
7356 } else {
7357 $linktext = get_string('trackforum', 'forum');
7359 $url = new moodle_url('/mod/forum/settracking.php', array(
7360 'id' => $forumobject->id,
7361 'sesskey' => sesskey(),
7363 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7367 if (!isloggedin() && $PAGE->course->id == SITEID) {
7368 $userid = guest_user()->id;
7369 } else {
7370 $userid = $USER->id;
7373 $hascourseaccess = ($PAGE->course->id == SITEID) || can_access_course($PAGE->course, $userid);
7374 $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds);
7376 if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) {
7378 if (!function_exists('rss_get_url')) {
7379 require_once("$CFG->libdir/rsslib.php");
7382 if ($forumobject->rsstype == 1) {
7383 $string = get_string('rsssubscriberssdiscussions','forum');
7384 } else {
7385 $string = get_string('rsssubscriberssposts','forum');
7388 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id));
7389 $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
7394 * Adds information about unread messages, that is only required for the course view page (and
7395 * similar), to the course-module object.
7396 * @param cm_info $cm Course-module object
7398 function forum_cm_info_view(cm_info $cm) {
7399 global $CFG;
7401 if (forum_tp_can_track_forums()) {
7402 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
7403 $out = '<span class="unread"> <a href="' . $cm->url . '">';
7404 if ($unread == 1) {
7405 $out .= get_string('unreadpostsone', 'forum');
7406 } else {
7407 $out .= get_string('unreadpostsnumber', 'forum', $unread);
7409 $out .= '</a></span>';
7410 $cm->set_after_link($out);
7416 * Return a list of page types
7417 * @param string $pagetype current page type
7418 * @param stdClass $parentcontext Block's parent context
7419 * @param stdClass $currentcontext Current context of block
7421 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
7422 $forum_pagetype = array(
7423 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
7424 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
7425 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
7427 return $forum_pagetype;
7431 * Gets all of the courses where the provided user has posted in a forum.
7433 * @global moodle_database $DB The database connection
7434 * @param stdClass $user The user who's posts we are looking for
7435 * @param bool $discussionsonly If true only look for discussions started by the user
7436 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
7437 * @param int $limitfrom The offset of records to return
7438 * @param int $limitnum The number of records to return
7439 * @return array An array of courses
7441 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
7442 global $DB;
7444 // If we are only after discussions we need only look at the forum_discussions
7445 // table and join to the userid there. If we are looking for posts then we need
7446 // to join to the forum_posts table.
7447 if (!$discussionsonly) {
7448 $subquery = "(SELECT DISTINCT fd.course
7449 FROM {forum_discussions} fd
7450 JOIN {forum_posts} fp ON fp.discussion = fd.id
7451 WHERE fp.userid = :userid )";
7452 } else {
7453 $subquery= "(SELECT DISTINCT fd.course
7454 FROM {forum_discussions} fd
7455 WHERE fd.userid = :userid )";
7458 $params = array('userid' => $user->id);
7460 // Join to the context table so that we can preload contexts if required.
7461 if ($includecontexts) {
7462 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
7463 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
7464 $params['contextlevel'] = CONTEXT_COURSE;
7465 } else {
7466 $ctxselect = '';
7467 $ctxjoin = '';
7470 // Now we need to get all of the courses to search.
7471 // All courses where the user has posted within a forum will be returned.
7472 $sql = "SELECT c.* $ctxselect
7473 FROM {course} c
7474 $ctxjoin
7475 WHERE c.id IN ($subquery)";
7476 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7477 if ($includecontexts) {
7478 array_map('context_helper::preload_from_record', $courses);
7480 return $courses;
7484 * Gets all of the forums a user has posted in for one or more courses.
7486 * @global moodle_database $DB
7487 * @param stdClass $user
7488 * @param array $courseids An array of courseids to search or if not provided
7489 * all courses the user has posted within
7490 * @param bool $discussionsonly If true then only forums where the user has started
7491 * a discussion will be returned.
7492 * @param int $limitfrom The offset of records to return
7493 * @param int $limitnum The number of records to return
7494 * @return array An array of forums the user has posted within in the provided courses
7496 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
7497 global $DB;
7499 if (!is_null($courseids)) {
7500 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid');
7501 $coursewhere = ' AND f.course '.$coursewhere;
7502 } else {
7503 $coursewhere = '';
7504 $params = array();
7506 $params['userid'] = $user->id;
7507 $params['forum'] = 'forum';
7509 if ($discussionsonly) {
7510 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
7511 } else {
7512 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
7513 JOIN {forum_posts} ff ON ff.discussion = fd.id';
7516 $sql = "SELECT f.*, cm.id AS cmid
7517 FROM {forum} f
7518 JOIN {course_modules} cm ON cm.instance = f.id
7519 JOIN {modules} m ON m.id = cm.module
7520 JOIN (
7521 SELECT f.id
7522 FROM {forum} f
7523 {$join}
7524 WHERE ff.userid = :userid
7525 GROUP BY f.id
7526 ) j ON j.id = f.id
7527 WHERE m.name = :forum
7528 {$coursewhere}";
7530 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7531 return $courseforums;
7535 * Returns posts made by the selected user in the requested courses.
7537 * This method can be used to return all of the posts made by the requested user
7538 * within the given courses.
7539 * For each course the access of the current user and requested user is checked
7540 * and then for each post access to the post and forum is checked as well.
7542 * This function is safe to use with usercapabilities.
7544 * @global moodle_database $DB
7545 * @param stdClass $user The user whose posts we want to get
7546 * @param array $courses The courses to search
7547 * @param bool $musthaveaccess If set to true errors will be thrown if the user
7548 * cannot access one or more of the courses to search
7549 * @param bool $discussionsonly If set to true only discussion starting posts
7550 * will be returned.
7551 * @param int $limitfrom The offset of records to return
7552 * @param int $limitnum The number of records to return
7553 * @return stdClass An object the following properties
7554 * ->totalcount: the total number of posts made by the requested user
7555 * that the current user can see.
7556 * ->courses: An array of courses the current user can see that the
7557 * requested user has posted in.
7558 * ->forums: An array of forums relating to the posts returned in the
7559 * property below.
7560 * ->posts: An array containing the posts to show for this request.
7562 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
7563 global $DB, $USER, $CFG;
7565 $return = new stdClass;
7566 $return->totalcount = 0; // The total number of posts that the current user is able to view
7567 $return->courses = array(); // The courses the current user can access
7568 $return->forums = array(); // The forums that the current user can access that contain posts
7569 $return->posts = array(); // The posts to display
7571 // First up a small sanity check. If there are no courses to check we can
7572 // return immediately, there is obviously nothing to search.
7573 if (empty($courses)) {
7574 return $return;
7577 // A couple of quick setups
7578 $isloggedin = isloggedin();
7579 $isguestuser = $isloggedin && isguestuser();
7580 $iscurrentuser = $isloggedin && $USER->id == $user->id;
7582 // Checkout whether or not the current user has capabilities over the requested
7583 // user and if so they have the capabilities required to view the requested
7584 // users content.
7585 $usercontext = context_user::instance($user->id, MUST_EXIST);
7586 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
7587 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
7589 // Before we actually search each course we need to check the user's access to the
7590 // course. If the user doesn't have the appropraite access then we either throw an
7591 // error if a particular course was requested or we just skip over the course.
7592 foreach ($courses as $course) {
7593 $coursecontext = context_course::instance($course->id, MUST_EXIST);
7594 if ($iscurrentuser || $hascapsonuser) {
7595 // If it is the current user, or the current user has capabilities to the
7596 // requested user then all we need to do is check the requested users
7597 // current access to the course.
7598 // Note: There is no need to check group access or anything of the like
7599 // as either the current user is the requested user, or has granted
7600 // capabilities on the requested user. Either way they can see what the
7601 // requested user posted, although its VERY unlikely in the `parent` situation
7602 // that the current user will be able to view the posts in context.
7603 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
7604 // Need to have full access to a course to see the rest of own info
7605 if ($musthaveaccess) {
7606 print_error('errorenrolmentrequired', 'forum');
7608 continue;
7610 } else {
7611 // Check whether the current user is enrolled or has access to view the course
7612 // if they don't we immediately have a problem.
7613 if (!can_access_course($course)) {
7614 if ($musthaveaccess) {
7615 print_error('errorenrolmentrequired', 'forum');
7617 continue;
7620 // If groups are in use and enforced throughout the course then make sure
7621 // we can meet in at least one course level group.
7622 // Note that we check if either the current user or the requested user have
7623 // the capability to access all groups. This is because with that capability
7624 // a user in group A could post in the group B forum. Grrrr.
7625 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
7626 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
7627 // If its the guest user to bad... the guest user cannot access groups
7628 if (!$isloggedin or $isguestuser) {
7629 // do not use require_login() here because we might have already used require_login($course)
7630 if ($musthaveaccess) {
7631 redirect(get_login_url());
7633 continue;
7635 // Get the groups of the current user
7636 $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
7637 // Get the groups the requested user is a member of
7638 $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
7639 // Check whether they are members of the same group. If they are great.
7640 $intersect = array_intersect($mygroups, $usergroups);
7641 if (empty($intersect)) {
7642 // But they're not... if it was a specific course throw an error otherwise
7643 // just skip this course so that it is not searched.
7644 if ($musthaveaccess) {
7645 print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
7647 continue;
7651 // Woo hoo we got this far which means the current user can search this
7652 // this course for the requested user. Although this is only the course accessibility
7653 // handling that is complete, the forum accessibility tests are yet to come.
7654 $return->courses[$course->id] = $course;
7656 // No longer beed $courses array - lose it not it may be big
7657 unset($courses);
7659 // Make sure that we have some courses to search
7660 if (empty($return->courses)) {
7661 // If we don't have any courses to search then the reality is that the current
7662 // user doesn't have access to any courses is which the requested user has posted.
7663 // Although we do know at this point that the requested user has posts.
7664 if ($musthaveaccess) {
7665 print_error('permissiondenied');
7666 } else {
7667 return $return;
7671 // Next step: Collect all of the forums that we will want to search.
7672 // It is important to note that this step isn't actually about searching, it is
7673 // about determining which forums we can search by testing accessibility.
7674 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);
7676 // Will be used to build the where conditions for the search
7677 $forumsearchwhere = array();
7678 // Will be used to store the where condition params for the search
7679 $forumsearchparams = array();
7680 // Will record forums where the user can freely access everything
7681 $forumsearchfullaccess = array();
7682 // DB caching friendly
7683 $now = floor(time() / 60) * 60;
7684 // For each course to search we want to find the forums the user has posted in
7685 // and providing the current user can access the forum create a search condition
7686 // for the forum to get the requested users posts.
7687 foreach ($return->courses as $course) {
7688 // Now we need to get the forums
7689 $modinfo = get_fast_modinfo($course);
7690 if (empty($modinfo->instances['forum'])) {
7691 // hmmm, no forums? well at least its easy... skip!
7692 continue;
7694 // Iterate
7695 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
7696 if (!$cm->uservisible or !isset($forums[$forumid])) {
7697 continue;
7699 // Get the forum in question
7700 $forum = $forums[$forumid];
7702 // This is needed for functionality later on in the forum code. It is converted to an object
7703 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
7704 // code were expecting an writeable object. See {@link forum_print_post()}.
7705 $forum->cm = new stdClass();
7706 foreach ($cm as $key => $value) {
7707 $forum->cm->$key = $value;
7710 // Check that either the current user can view the forum, or that the
7711 // current user has capabilities over the requested user and the requested
7712 // user can view the discussion
7713 if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
7714 continue;
7717 // This will contain forum specific where clauses
7718 $forumsearchselect = array();
7719 if (!$iscurrentuser && !$hascapsonuser) {
7720 // Make sure we check group access
7721 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
7722 $groups = $modinfo->get_groups($cm->groupingid);
7723 $groups[] = -1;
7724 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
7725 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
7726 $forumsearchselect[] = "d.groupid $groupid_sql";
7729 // hidden timed discussions
7730 if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
7731 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
7732 $forumsearchparams['userid'.$forumid] = $user->id;
7733 $forumsearchparams['timestart'.$forumid] = $now;
7734 $forumsearchparams['timeend'.$forumid] = $now;
7737 // qanda access
7738 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
7739 // We need to check whether the user has posted in the qanda forum.
7740 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
7741 if (!empty($discussionspostedin)) {
7742 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
7743 foreach ($discussionspostedin as $d) {
7744 $forumonlydiscussions[] = $d->id;
7746 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
7747 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
7748 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
7749 } else {
7750 $forumsearchselect[] = "p.parent = 0";
7755 if (count($forumsearchselect) > 0) {
7756 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
7757 $forumsearchparams['forum'.$forumid] = $forumid;
7758 } else {
7759 $forumsearchfullaccess[] = $forumid;
7761 } else {
7762 // The current user/parent can see all of their own posts
7763 $forumsearchfullaccess[] = $forumid;
7768 // If we dont have any search conditions, and we don't have any forums where
7769 // the user has full access then we just return the default.
7770 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
7771 return $return;
7774 // Prepare a where condition for the full access forums.
7775 if (count($forumsearchfullaccess) > 0) {
7776 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
7777 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
7778 $forumsearchwhere[] = "(d.forum $fullidsql)";
7781 // Prepare SQL to both count and search.
7782 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
7783 // oracle and mssql.
7784 $userfields = user_picture::fields('u', null, 'useridx');
7785 $countsql = 'SELECT COUNT(*) ';
7786 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
7787 $wheresql = implode(" OR ", $forumsearchwhere);
7789 if ($discussionsonly) {
7790 if ($wheresql == '') {
7791 $wheresql = 'p.parent = 0';
7792 } else {
7793 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
7797 $sql = "FROM {forum_posts} p
7798 JOIN {forum_discussions} d ON d.id = p.discussion
7799 JOIN {user} u ON u.id = p.userid
7800 WHERE ($wheresql)
7801 AND p.userid = :userid ";
7802 $orderby = "ORDER BY p.modified DESC";
7803 $forumsearchparams['userid'] = $user->id;
7805 // Set the total number posts made by the requested user that the current user can see
7806 $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
7807 // Set the collection of posts that has been requested
7808 $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
7810 // We need to build an array of forums for which posts will be displayed.
7811 // We do this here to save the caller needing to retrieve them themselves before
7812 // printing these forums posts. Given we have the forums already there is
7813 // practically no overhead here.
7814 foreach ($return->posts as $post) {
7815 if (!array_key_exists($post->forum, $return->forums)) {
7816 $return->forums[$post->forum] = $forums[$post->forum];
7820 return $return;
7824 * Set the per-forum maildigest option for the specified user.
7826 * @param stdClass $forum The forum to set the option for.
7827 * @param int $maildigest The maildigest option.
7828 * @param stdClass $user The user object. This defaults to the global $USER object.
7829 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
7831 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
7832 global $DB, $USER;
7834 if (is_number($forum)) {
7835 $forum = $DB->get_record('forum', array('id' => $forum));
7838 if ($user === null) {
7839 $user = $USER;
7842 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
7843 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
7844 $context = context_module::instance($cm->id);
7846 // User must be allowed to see this forum.
7847 require_capability('mod/forum:viewdiscussion', $context, $user->id);
7849 // Validate the maildigest setting.
7850 $digestoptions = forum_get_user_digest_options($user);
7852 if (!isset($digestoptions[$maildigest])) {
7853 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
7856 // Attempt to retrieve any existing forum digest record.
7857 $subscription = $DB->get_record('forum_digests', array(
7858 'userid' => $user->id,
7859 'forum' => $forum->id,
7862 // Create or Update the existing maildigest setting.
7863 if ($subscription) {
7864 if ($maildigest == -1) {
7865 $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id));
7866 } else if ($maildigest !== $subscription->maildigest) {
7867 // Only update the maildigest setting if it's changed.
7869 $subscription->maildigest = $maildigest;
7870 $DB->update_record('forum_digests', $subscription);
7872 } else {
7873 if ($maildigest != -1) {
7874 // Only insert the maildigest setting if it's non-default.
7876 $subscription = new stdClass();
7877 $subscription->forum = $forum->id;
7878 $subscription->userid = $user->id;
7879 $subscription->maildigest = $maildigest;
7880 $subscription->id = $DB->insert_record('forum_digests', $subscription);
7886 * Determine the maildigest setting for the specified user against the
7887 * specified forum.
7889 * @param Array $digests An array of forums and user digest settings.
7890 * @param stdClass $user The user object containing the id and maildigest default.
7891 * @param int $forumid The ID of the forum to check.
7892 * @return int The calculated maildigest setting for this user and forum.
7894 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
7895 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) {
7896 $maildigest = $digests[$forumid][$user->id];
7897 if ($maildigest === -1) {
7898 $maildigest = $user->maildigest;
7900 } else {
7901 $maildigest = $user->maildigest;
7903 return $maildigest;
7907 * Retrieve the list of available user digest options.
7909 * @param stdClass $user The user object. This defaults to the global $USER object.
7910 * @return array The mapping of values to digest options.
7912 function forum_get_user_digest_options($user = null) {
7913 global $USER;
7915 // Revert to the global user object.
7916 if ($user === null) {
7917 $user = $USER;
7920 $digestoptions = array();
7921 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
7922 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
7923 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
7925 // We need to add the default digest option at the end - it relies on
7926 // the contents of the existing values.
7927 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
7928 $digestoptions[$user->maildigest]);
7930 // Resort the options to be in a sensible order.
7931 ksort($digestoptions);
7933 return $digestoptions;
7937 * Determine the current context if one was not already specified.
7939 * If a context of type context_module is specified, it is immediately
7940 * returned and not checked.
7942 * @param int $forumid The ID of the forum
7943 * @param context_module $context The current context.
7944 * @return context_module The context determined
7946 function forum_get_context($forumid, $context = null) {
7947 global $PAGE;
7949 if (!$context || !($context instanceof context_module)) {
7950 // Find out forum context. First try to take current page context to save on DB query.
7951 if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid
7952 && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) {
7953 $context = $PAGE->context;
7954 } else {
7955 $cm = get_coursemodule_from_instance('forum', $forumid);
7956 $context = \context_module::instance($cm->id);
7960 return $context;
7964 * Mark the activity completed (if required) and trigger the course_module_viewed event.
7966 * @param stdClass $forum forum object
7967 * @param stdClass $course course object
7968 * @param stdClass $cm course module object
7969 * @param stdClass $context context object
7970 * @since Moodle 2.9
7972 function forum_view($forum, $course, $cm, $context) {
7974 // Completion.
7975 $completion = new completion_info($course);
7976 $completion->set_module_viewed($cm);
7978 // Trigger course_module_viewed event.
7980 $params = array(
7981 'context' => $context,
7982 'objectid' => $forum->id
7985 $event = \mod_forum\event\course_module_viewed::create($params);
7986 $event->add_record_snapshot('course_modules', $cm);
7987 $event->add_record_snapshot('course', $course);
7988 $event->add_record_snapshot('forum', $forum);
7989 $event->trigger();
7993 * Trigger the discussion viewed event
7995 * @param stdClass $modcontext module context object
7996 * @param stdClass $forum forum object
7997 * @param stdClass $discussion discussion object
7998 * @since Moodle 2.9
8000 function forum_discussion_view($modcontext, $forum, $discussion) {
8001 $params = array(
8002 'context' => $modcontext,
8003 'objectid' => $discussion->id,
8006 $event = \mod_forum\event\discussion_viewed::create($params);
8007 $event->add_record_snapshot('forum_discussions', $discussion);
8008 $event->add_record_snapshot('forum', $forum);
8009 $event->trigger();
8013 * Set the discussion to pinned and trigger the discussion pinned event
8015 * @param stdClass $modcontext module context object
8016 * @param stdClass $forum forum object
8017 * @param stdClass $discussion discussion object
8018 * @since Moodle 3.1
8020 function forum_discussion_pin($modcontext, $forum, $discussion) {
8021 global $DB;
8023 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED, array('id' => $discussion->id));
8025 $params = array(
8026 'context' => $modcontext,
8027 'objectid' => $discussion->id,
8028 'other' => array('forumid' => $forum->id)
8031 $event = \mod_forum\event\discussion_pinned::create($params);
8032 $event->add_record_snapshot('forum_discussions', $discussion);
8033 $event->trigger();
8037 * Set discussion to unpinned and trigger the discussion unpin event
8039 * @param stdClass $modcontext module context object
8040 * @param stdClass $forum forum object
8041 * @param stdClass $discussion discussion object
8042 * @since Moodle 3.1
8044 function forum_discussion_unpin($modcontext, $forum, $discussion) {
8045 global $DB;
8047 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED, array('id' => $discussion->id));
8049 $params = array(
8050 'context' => $modcontext,
8051 'objectid' => $discussion->id,
8052 'other' => array('forumid' => $forum->id)
8055 $event = \mod_forum\event\discussion_unpinned::create($params);
8056 $event->add_record_snapshot('forum_discussions', $discussion);
8057 $event->trigger();
8061 * Add nodes to myprofile page.
8063 * @param \core_user\output\myprofile\tree $tree Tree object
8064 * @param stdClass $user user object
8065 * @param bool $iscurrentuser
8066 * @param stdClass $course Course object
8068 * @return bool
8070 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
8071 if (isguestuser($user)) {
8072 // The guest user cannot post, so it is not possible to view any posts.
8073 // May as well just bail aggressively here.
8074 return false;
8076 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id));
8077 if (!empty($course)) {
8078 $postsurl->param('course', $course->id);
8080 $string = get_string('forumposts', 'mod_forum');
8081 $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl);
8082 $tree->add_node($node);
8084 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions'));
8085 if (!empty($course)) {
8086 $discussionssurl->param('course', $course->id);
8088 $string = get_string('myprofileotherdis', 'mod_forum');
8089 $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null,
8090 $discussionssurl);
8091 $tree->add_node($node);
8093 return true;
8097 * Checks whether the author's name and picture for a given post should be hidden or not.
8099 * @param object $post The forum post.
8100 * @param object $forum The forum object.
8101 * @return bool
8102 * @throws coding_exception
8104 function forum_is_author_hidden($post, $forum) {
8105 if (!isset($post->parent)) {
8106 throw new coding_exception('$post->parent must be set.');
8108 if (!isset($forum->type)) {
8109 throw new coding_exception('$forum->type must be set.');
8111 if ($forum->type === 'single' && empty($post->parent)) {
8112 return true;
8114 return false;
8118 * Manage inplace editable saves.
8120 * @param string $itemtype The type of item.
8121 * @param int $itemid The ID of the item.
8122 * @param mixed $newvalue The new value
8123 * @return string
8125 function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) {
8126 global $DB, $PAGE;
8128 if ($itemtype === 'digestoptions') {
8129 // The itemid is the forumid.
8130 $forum = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST);
8131 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
8132 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
8133 $context = context_module::instance($cm->id);
8135 $PAGE->set_context($context);
8136 require_login($course, false, $cm);
8137 forum_set_user_maildigest($forum, $newvalue);
8139 $renderer = $PAGE->get_renderer('mod_forum');
8140 return $renderer->render_digest_options($forum, $newvalue);
8145 * Determine whether the specified discussion is time-locked.
8147 * @param stdClass $forum The forum that the discussion belongs to
8148 * @param stdClass $discussion The discussion to test
8149 * @return bool
8151 function forum_discussion_is_locked($forum, $discussion) {
8152 if (empty($forum->lockdiscussionafter)) {
8153 return false;
8156 if ($forum->type === 'single') {
8157 // It does not make sense to lock a single discussion forum.
8158 return false;
8161 if (($discussion->timemodified + $forum->lockdiscussionafter) < time()) {
8162 return true;
8165 return false;
8169 * Check if the module has any update that affects the current user since a given time.
8171 * @param cm_info $cm course module data
8172 * @param int $from the time to check updates from
8173 * @param array $filter if we need to check only specific updates
8174 * @return stdClass an object with the different type of areas indicating if they were updated or not
8175 * @since Moodle 3.2
8177 function forum_check_updates_since(cm_info $cm, $from, $filter = array()) {
8179 $context = $cm->context;
8180 $updates = new stdClass();
8181 if (!has_capability('mod/forum:viewdiscussion', $context)) {
8182 return $updates;
8185 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
8187 // Check if there are new discussions in the forum.
8188 $updates->discussions = (object) array('updated' => false);
8189 $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS, $from);
8190 if (!empty($discussions)) {
8191 $updates->discussions->updated = true;
8192 $updates->discussions->itemids = array_keys($discussions);
8195 return $updates;
8199 * Check if the user can create attachments in a forum.
8200 * @param stdClass $forum forum object
8201 * @param stdClass $context context object
8202 * @return bool true if the user can create attachments, false otherwise
8203 * @since Moodle 3.3
8205 function forum_can_create_attachment($forum, $context) {
8206 // If maxbytes == 1 it means no attachments at all.
8207 if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
8208 !has_capability('mod/forum:createattachment', $context)) {
8209 return false;
8211 return true;
8215 * Get icon mapping for font-awesome.
8217 * @return array
8219 function mod_forum_get_fontawesome_icon_map() {
8220 return [
8221 'mod_forum:i/pinned' => 'fa-map-pin',
8222 'mod_forum:t/selected' => 'fa-check',
8223 'mod_forum:t/subscribed' => 'fa-envelope-o',
8224 'mod_forum:t/unsubscribed' => 'fa-envelope-open-o',
8229 * Callback function that determines whether an action event should be showing its item count
8230 * based on the event type and the item count.
8232 * @param calendar_event $event The calendar event.
8233 * @param int $itemcount The item count associated with the action event.
8234 * @return bool
8236 function mod_forum_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
8237 // Always show item count for forums if item count is greater than 1.
8238 // If only one action is required than it is obvious and we don't show it for other modules.
8239 return $itemcount > 1;
8243 * This function receives a calendar event and returns the action associated with it, or null if there is none.
8245 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
8246 * is not displayed on the block.
8248 * @param calendar_event $event
8249 * @param \core_calendar\action_factory $factory
8250 * @return \core_calendar\local\event\entities\action_interface|null
8252 function mod_forum_core_calendar_provide_event_action(calendar_event $event,
8253 \core_calendar\action_factory $factory) {
8254 global $DB, $USER;
8256 $cm = get_fast_modinfo($event->courseid)->instances['forum'][$event->instance];
8257 $context = context_module::instance($cm->id);
8259 if (!has_capability('mod/forum:viewdiscussion', $context)) {
8260 return null;
8263 $completion = new \completion_info($cm->get_course());
8265 $completiondata = $completion->get_data($cm, false);
8267 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
8268 return null;
8271 // Get action itemcount.
8272 $itemcount = 0;
8273 $forum = $DB->get_record('forum', array('id' => $cm->instance));
8274 $postcountsql = "
8275 SELECT
8276 COUNT(1)
8277 FROM
8278 {forum_posts} fp
8279 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
8280 WHERE
8281 fp.userid=:userid AND fd.forum=:forumid";
8282 $postcountparams = array('userid' => $USER->id, 'forumid' => $forum->id);
8284 if ($forum->completiondiscussions) {
8285 $count = $DB->count_records('forum_discussions', array('forum' => $forum->id, 'userid' => $USER->id));
8286 $itemcount += ($forum->completiondiscussions >= $count) ? ($forum->completiondiscussions - $count) : 0;
8289 if ($forum->completionreplies) {
8290 $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams);
8291 $itemcount += ($forum->completionreplies >= $count) ? ($forum->completionreplies - $count) : 0;
8294 if ($forum->completionposts) {
8295 $count = $DB->get_field_sql($postcountsql, $postcountparams);
8296 $itemcount += ($forum->completionposts >= $count) ? ($forum->completionposts - $count) : 0;
8299 // Well there is always atleast one actionable item (view forum, etc).
8300 $itemcount = $itemcount > 0 ? $itemcount : 1;
8302 return $factory->create_instance(
8303 get_string('view'),
8304 new \moodle_url('/mod/forum/view.php', ['id' => $cm->id]),
8305 $itemcount,
8306 true
8311 * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information
8312 * for the course (see resource).
8314 * Given a course_module object, this function returns any "extra" information that may be needed
8315 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
8317 * @param stdClass $coursemodule The coursemodule object (record).
8318 * @return cached_cm_info An object on information that the courses
8319 * will know about (most noticeably, an icon).
8321 function forum_get_coursemodule_info($coursemodule) {
8322 global $DB;
8324 $dbparams = ['id' => $coursemodule->instance];
8325 $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies';
8326 if (!$forum = $DB->get_record('forum', $dbparams, $fields)) {
8327 return false;
8330 $result = new cached_cm_info();
8331 $result->name = $forum->name;
8333 if ($coursemodule->showdescription) {
8334 // Convert intro to html. Do not filter cached version, filters run at display time.
8335 $result->content = format_module_intro('forum', $forum, $coursemodule->id, false);
8338 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
8339 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
8340 $result->customdata['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions;
8341 $result->customdata['customcompletionrules']['completionreplies'] = $forum->completionreplies;
8342 $result->customdata['customcompletionrules']['completionposts'] = $forum->completionposts;
8345 return $result;
8349 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
8351 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
8352 * @return array $descriptions the array of descriptions for the custom rules.
8354 function mod_forum_get_completion_active_rule_descriptions($cm) {
8355 // Values will be present in cm_info, and we assume these are up to date.
8356 if (empty($cm->customdata['customcompletionrules'])
8357 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
8358 return [];
8361 $descriptions = [];
8362 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
8363 switch ($key) {
8364 case 'completiondiscussions':
8365 if (empty($val)) {
8366 continue;
8368 $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val);
8369 break;
8370 case 'completionreplies':
8371 if (empty($val)) {
8372 continue;
8374 $descriptions[] = get_string('completionrepliesdesc', 'forum', $val);
8375 break;
8376 case 'completionposts':
8377 if (empty($val)) {
8378 continue;
8380 $descriptions[] = get_string('completionpostsdesc', 'forum', $val);
8381 break;
8382 default:
8383 break;
8386 return $descriptions;