2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') || die();
25 /** Include required files */
26 require_once(__DIR__ . '/deprecatedlib.php');
27 require_once($CFG->libdir.'/filelib.php');
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);
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
62 if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
70 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
72 define('FORUM_DISCUSSION_PINNED', 1);
73 define('FORUM_DISCUSSION_UNPINNED', 0);
75 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
78 * Given an object containing all the necessary data,
79 * (defined by the form in mod_form.php) this function
80 * will create a new instance and return the id number
81 * of the new instance.
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
85 * @return int intance id
87 function forum_add_instance($forum, $mform = null) {
90 $forum->timemodified = time();
92 if (empty($forum->assessed)) {
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;
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);
137 * Handle changes following the creation of a forum instance.
138 * This function is typically called by the course_module_created observer.
140 * @param object $context the forum context
141 * @param stdClass $forum The forum object
144 function forum_instance_created($context, $forum) {
145 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
146 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
147 foreach ($users as $user) {
148 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
154 * Given an object containing all the necessary data,
155 * (defined by the form in mod_form.php) this function
156 * will update an existing instance with new data.
159 * @param object $forum forum instance (with magic quotes)
160 * @return bool success
162 function forum_update_instance($forum, $mform) {
163 global $DB, $OUTPUT, $USER;
165 $forum->timemodified = time();
166 $forum->id = $forum->instance;
168 if (empty($forum->assessed)) {
169 $forum->assessed = 0;
172 if (empty($forum->ratingtime) or empty($forum->assessed)) {
173 $forum->assesstimestart = 0;
174 $forum->assesstimefinish = 0;
177 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
179 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
180 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
181 // 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
182 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
183 forum_update_grades($forum); // recalculate grades for the forum
186 if ($forum->type == 'single') { // Update related discussion and post.
187 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
188 if (!empty($discussions)) {
189 if (count($discussions) > 1) {
190 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
192 $discussion = array_pop($discussions);
194 // try to recover by creating initial discussion - MDL-16262
195 $discussion = new stdClass();
196 $discussion->course = $forum->course;
197 $discussion->forum = $forum->id;
198 $discussion->name = $forum->name;
199 $discussion->assessed = $forum->assessed;
200 $discussion->message = $forum->intro;
201 $discussion->messageformat = $forum->introformat;
202 $discussion->messagetrust = true;
203 $discussion->mailnow = false;
204 $discussion->groupid = -1;
208 forum_add_discussion($discussion, null, $message);
210 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
211 print_error('cannotadd', 'forum');
214 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
215 print_error('cannotfindfirstpost', 'forum');
218 $cm = get_coursemodule_from_instance('forum', $forum->id);
219 $modcontext = context_module::instance($cm->id, MUST_EXIST);
221 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
222 $post->subject = $forum->name;
223 $post->message = $forum->intro;
224 $post->messageformat = $forum->introformat;
225 $post->messagetrust = trusttext_trusted($modcontext);
226 $post->modified = $forum->timemodified;
227 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
229 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
230 // Ugly hack - we need to copy the files somehow.
231 $options = array('subdirs'=>true); // Use the same options as intro field!
232 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
235 $DB->update_record('forum_posts', $post);
236 $discussion->name = $forum->name;
237 $DB->update_record('forum_discussions', $discussion);
240 $DB->update_record('forum', $forum);
242 $modcontext = context_module::instance($forum->coursemodule);
243 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
244 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
245 foreach ($users as $user) {
246 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
250 forum_grade_item_update($forum);
257 * Given an ID of an instance of this module,
258 * this function will permanently delete the instance
259 * and any data that depends on it.
262 * @param int $id forum instance id
263 * @return bool success
265 function forum_delete_instance($id) {
268 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
271 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
274 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
278 $context = context_module::instance($cm->id);
280 // now get rid of all files
281 $fs = get_file_storage();
282 $fs->delete_area_files($context->id);
286 // Delete digest and subscription preferences.
287 $DB->delete_records('forum_digests', array('forum' => $forum->id));
288 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
289 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
291 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
292 foreach ($discussions as $discussion) {
293 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
299 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
301 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
305 forum_grade_item_delete($forum);
312 * Indicates API features that the forum supports.
314 * @uses FEATURE_GROUPS
315 * @uses FEATURE_GROUPINGS
316 * @uses FEATURE_MOD_INTRO
317 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
318 * @uses FEATURE_COMPLETION_HAS_RULES
319 * @uses FEATURE_GRADE_HAS_GRADE
320 * @uses FEATURE_GRADE_OUTCOMES
321 * @param string $feature
322 * @return mixed True if yes (some features may use other values)
324 function forum_supports($feature) {
326 case FEATURE_GROUPS: return true;
327 case FEATURE_GROUPINGS: return true;
328 case FEATURE_MOD_INTRO: return true;
329 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
330 case FEATURE_COMPLETION_HAS_RULES: return true;
331 case FEATURE_GRADE_HAS_GRADE: return true;
332 case FEATURE_GRADE_OUTCOMES: return true;
333 case FEATURE_RATE: return true;
334 case FEATURE_BACKUP_MOODLE2: return true;
335 case FEATURE_SHOW_DESCRIPTION: return true;
336 case FEATURE_PLAGIARISM: return true;
338 default: return null;
344 * Obtains the automatic completion state for this forum based on any conditions
349 * @param object $course Course
350 * @param object $cm Course-module
351 * @param int $userid User ID
352 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
353 * @return bool True if completed, false if not. (If no conditions, then return
354 * value depends on comparison type)
356 function forum_get_completion_state($course,$cm,$userid,$type) {
360 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
361 throw new Exception("Can't find forum {$cm->instance}");
364 $result=$type; // Default return value
366 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
372 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
374 fp.userid=:userid AND fd.forum=:forumid";
376 if ($forum->completiondiscussions) {
377 $value = $forum->completiondiscussions <=
378 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
379 if ($type == COMPLETION_AND) {
380 $result = $result && $value;
382 $result = $result || $value;
385 if ($forum->completionreplies) {
386 $value = $forum->completionreplies <=
387 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
388 if ($type==COMPLETION_AND) {
389 $result = $result && $value;
391 $result = $result || $value;
394 if ($forum->completionposts) {
395 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
396 if ($type == COMPLETION_AND) {
397 $result = $result && $value;
399 $result = $result || $value;
407 * Create a message-id string to use in the custom headers of forum notification emails
409 * message-id is used by email clients to identify emails and to nest conversations
411 * @param int $postid The ID of the forum post we are notifying the user about
412 * @param int $usertoid The ID of the user being notified
413 * @return string A unique message-id
415 function forum_get_email_message_id($postid, $usertoid) {
416 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
420 * Removes properties from user record that are not necessary
421 * for sending post notifications.
422 * @param stdClass $user
423 * @return void, $user parameter is modified
425 function forum_cron_minimise_user_record(stdClass $user) {
427 // We store large amount of users in one huge array,
428 // make sure we do not store info there we do not actually need
429 // in mail generation code or messaging.
431 unset($user->institution);
432 unset($user->department);
433 unset($user->address);
436 unset($user->currentlogin);
437 unset($user->description);
438 unset($user->descriptionformat);
442 * Function to be run periodically according to the scheduled task.
444 * Finds all posts that have yet to be mailed out, and mails them
445 * out to all subscribers as well as other maintance tasks.
447 * NOTE: Since 2.7.2 this function is run by scheduled task rather
448 * than standard cron.
450 * @todo MDL-44734 The function will be split up into seperate tasks.
452 function forum_cron() {
453 global $CFG, $USER, $DB, $PAGE;
457 // The main renderers.
458 $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
459 $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
460 $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
461 $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
462 $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
463 $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
465 // All users that are subscribed to any post that needs sending,
466 // please increase $CFG->extramemorylimit on large sites that
467 // send notifications to a large number of users.
469 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
472 $mailcount = array();
473 $errorcount = array();
476 $discussions = array();
479 $coursemodules = array();
480 $subscribedusers = array();
481 $messageinboundhandlers = array();
483 // Posts older than 2 days will not be mailed. This is to avoid the problem where
484 // cron has not been running for a long time, and then suddenly people are flooded
485 // with mail from the past few weeks or months
487 $endtime = $timenow - $CFG->maxeditingtime;
488 $starttime = $endtime - 48 * 3600; // Two days earlier
490 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
491 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
493 foreach ($digestsset as $thisrow) {
494 if (!isset($digests[$thisrow->forum])) {
495 $digests[$thisrow->forum] = array();
497 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
499 $digestsset->close();
501 // Create the generic messageinboundgenerator.
502 $messageinboundgenerator = new \core\message\inbound\address_manager();
503 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
505 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
506 // Mark them all now as being mailed. It's unlikely but possible there
507 // might be an error later so that a post is NOT actually mailed out,
508 // but since mail isn't crucial, we can accept this risk. Doing it now
509 // prevents the risk of duplicated mails, which is a worse problem.
511 if (!forum_mark_old_posts_as_mailed($endtime)) {
512 mtrace('Errors occurred while trying to mark some posts as being mailed.');
513 return false; // Don't continue trying to mail them, in case we are in a cron loop
516 // checking post validity, and adding users to loop through later
517 foreach ($posts as $pid => $post) {
519 $discussionid = $post->discussion;
520 if (!isset($discussions[$discussionid])) {
521 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
522 $discussions[$discussionid] = $discussion;
523 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
524 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
527 mtrace('Could not find discussion ' . $discussionid);
532 $forumid = $discussions[$discussionid]->forum;
533 if (!isset($forums[$forumid])) {
534 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
535 $forums[$forumid] = $forum;
537 mtrace('Could not find forum '.$forumid);
542 $courseid = $forums[$forumid]->course;
543 if (!isset($courses[$courseid])) {
544 if ($course = $DB->get_record('course', array('id' => $courseid))) {
545 $courses[$courseid] = $course;
547 mtrace('Could not find course '.$courseid);
552 if (!isset($coursemodules[$forumid])) {
553 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
554 $coursemodules[$forumid] = $cm;
556 mtrace('Could not find course module for forum '.$forumid);
562 // Save the Inbound Message datakey here to reduce DB queries later.
563 $messageinboundgenerator->set_data($pid);
564 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
566 // Caching subscribed users of each forum.
567 if (!isset($subscribedusers[$forumid])) {
568 $modcontext = context_module::instance($coursemodules[$forumid]->id);
569 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
571 foreach ($subusers as $postuser) {
572 // this user is subscribed to this forum
573 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
575 if ($userscount > FORUM_CRON_USER_CACHE) {
576 // Store minimal user info.
577 $minuser = new stdClass();
578 $minuser->id = $postuser->id;
579 $users[$postuser->id] = $minuser;
581 // Cache full user record.
582 forum_cron_minimise_user_record($postuser);
583 $users[$postuser->id] = $postuser;
591 $mailcount[$pid] = 0;
592 $errorcount[$pid] = 0;
596 if ($users && $posts) {
598 foreach ($users as $userto) {
599 // Terminate if processing of any account takes longer than 2 minutes.
600 core_php_time_limit::raise(120);
602 mtrace('Processing user ' . $userto->id);
604 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
605 if (isset($userto->username)) {
606 $userto = clone($userto);
608 $userto = $DB->get_record('user', array('id' => $userto->id));
609 forum_cron_minimise_user_record($userto);
611 $userto->viewfullnames = array();
612 $userto->canpost = array();
613 $userto->markposts = array();
615 // Setup this user so that the capabilities are cached, and environment matches receiving user.
616 cron_setup_user($userto);
619 foreach ($coursemodules as $forumid => $unused) {
620 $coursemodules[$forumid]->cache = new stdClass();
621 $coursemodules[$forumid]->cache->caps = array();
622 unset($coursemodules[$forumid]->uservisible);
625 foreach ($posts as $pid => $post) {
626 $discussion = $discussions[$post->discussion];
627 $forum = $forums[$discussion->forum];
628 $course = $courses[$forum->course];
629 $cm =& $coursemodules[$forum->id];
631 // Do some checks to see if we can bail out now.
633 // Only active enrolled users are in the list of subscribers.
634 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
635 if (!isset($subscribedusers[$forum->id][$userto->id])) {
636 // The user does not subscribe to this forum.
640 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
641 // The user does not subscribe to this forum, or to this specific discussion.
645 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
646 // Skip posts if the user subscribed to the discussion after it was created.
647 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
652 // Don't send email if the forum is Q&A and the user has not posted.
653 // Initial topics are still mailed.
654 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
655 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
659 // Get info about the sending user.
660 if (array_key_exists($post->userid, $users)) {
661 // We might know the user already.
662 $userfrom = $users[$post->userid];
663 if (!isset($userfrom->idnumber)) {
664 // Minimalised user info, fetch full record.
665 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
666 forum_cron_minimise_user_record($userfrom);
669 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
670 forum_cron_minimise_user_record($userfrom);
671 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
672 if ($userscount <= FORUM_CRON_USER_CACHE) {
674 $users[$userfrom->id] = $userfrom;
677 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
681 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
683 // Setup global $COURSE properly - needed for roles and languages.
684 cron_setup_user($userto, $course);
687 if (!isset($userto->viewfullnames[$forum->id])) {
688 $modcontext = context_module::instance($cm->id);
689 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
691 if (!isset($userto->canpost[$discussion->id])) {
692 $modcontext = context_module::instance($cm->id);
693 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
695 if (!isset($userfrom->groups[$forum->id])) {
696 if (!isset($userfrom->groups)) {
697 $userfrom->groups = array();
698 if (isset($users[$userfrom->id])) {
699 $users[$userfrom->id]->groups = array();
702 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
703 if (isset($users[$userfrom->id])) {
704 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
708 // Make sure groups allow this user to see this email.
709 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
710 // Groups are being used.
711 if (!groups_group_exists($discussion->groupid)) {
712 // Can't find group - be safe and don't this message.
716 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
717 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
722 // Make sure we're allowed to see the post.
723 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
724 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
728 // OK so we need to send the email.
730 // Does the user want this post in a digest? If so postpone it for now.
731 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
733 if ($maildigest > 0) {
734 // This user wants the mails to be in digest form.
735 $queue = new stdClass();
736 $queue->userid = $userto->id;
737 $queue->discussionid = $discussion->id;
738 $queue->postid = $post->id;
739 $queue->timemodified = $post->created;
740 $DB->insert_record('forum_queue', $queue);
744 // Prepare to actually send the post now, and build up the content.
746 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
748 $userfrom->customheaders = array (
749 // Headers to make emails easier to track.
750 'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id),
751 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
752 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id),
753 'X-Course-Id: ' . $course->id,
754 'X-Course-Name: ' . format_string($course->fullname, true),
756 // Headers to help prevent auto-responders.
758 'X-Auto-Response-Suppress: All',
759 'Auto-Submitted: auto-generated',
762 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
764 // Generate a reply-to address from using the Inbound Message handler.
765 $replyaddress = null;
766 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
767 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
768 $replyaddress = $messageinboundgenerator->generate($userto->id);
771 if (!isset($userto->canpost[$discussion->id])) {
772 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
774 $canreply = $userto->canpost[$discussion->id];
777 $data = new \mod_forum\output\forum_post_email(
788 $userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>',
789 $data->get_unsubscribediscussionlink());
791 if (!isset($userto->viewfullnames[$forum->id])) {
792 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
794 $data->viewfullnames = $userto->viewfullnames[$forum->id];
797 // Not all of these variables are used in the default language
798 // string but are made available to support custom subjects.
800 $a->subject = $data->get_subject();
801 $a->forumname = $cleanforumname;
802 $a->sitefullname = format_string($site->fullname);
803 $a->siteshortname = format_string($site->shortname);
804 $a->courseidnumber = $data->get_courseidnumber();
805 $a->coursefullname = $data->get_coursefullname();
806 $a->courseshortname = $data->get_coursename();
807 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
809 $rootid = forum_get_email_message_id($discussion->firstpost, $userto->id);
812 // This post is a reply, so add reply header (RFC 2822).
813 $parentid = forum_get_email_message_id($post->parent, $userto->id);
814 $userfrom->customheaders[] = "In-Reply-To: $parentid";
816 // If the post is deeply nested we also reference the parent message id and
817 // the root message id (if different) to aid threading when parts of the email
818 // conversation have been deleted (RFC1036).
819 if ($post->parent != $discussion->firstpost) {
820 $userfrom->customheaders[] = "References: $rootid $parentid";
822 $userfrom->customheaders[] = "References: $parentid";
826 // MS Outlook / Office uses poorly documented and non standard headers, including
827 // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
828 $a->subject = $discussion->name;
829 $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
830 $userfrom->customheaders[] = "Thread-Topic: $threadtopic";
831 $userfrom->customheaders[] = "Thread-Index: " . substr($rootid, 1, 28);
833 // Send the post now!
834 mtrace('Sending ', '');
836 $eventdata = new \core\message\message();
837 $eventdata->courseid = $course->id;
838 $eventdata->component = 'mod_forum';
839 $eventdata->name = 'posts';
840 $eventdata->userfrom = $userfrom;
841 $eventdata->userto = $userto;
842 $eventdata->subject = $postsubject;
843 $eventdata->fullmessage = $textout->render($data);
844 $eventdata->fullmessageformat = FORMAT_PLAIN;
845 $eventdata->fullmessagehtml = $htmlout->render($data);
846 $eventdata->notification = 1;
847 $eventdata->replyto = $replyaddress;
848 if (!empty($replyaddress)) {
849 // Add extra text to email messages if they can reply back.
850 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
851 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
852 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
853 'fullmessagehtml' => array('footer' => $htmlfooter));
854 $eventdata->set_additional_content('email', $additionalcontent);
857 $smallmessagestrings = new stdClass();
858 $smallmessagestrings->user = fullname($userfrom);
859 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
860 $smallmessagestrings->message = $post->message;
862 // Make sure strings are in message recipients language.
863 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
865 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
866 $eventdata->contexturl = $contexturl->out();
867 $eventdata->contexturlname = $discussion->name;
869 $mailresult = message_send($eventdata);
871 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
872 " ($userto->email) .. not trying again.");
873 $errorcount[$post->id]++;
875 $mailcount[$post->id]++;
877 // Mark post as read if forum_usermarksread is set off.
878 if (!$CFG->forum_usermarksread) {
879 $userto->markposts[$post->id] = $post->id;
883 mtrace('post ' . $post->id . ': ' . $post->subject);
886 // Mark processed posts as read.
887 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
888 forum_tp_mark_posts_read($userto, $userto->markposts);
896 foreach ($posts as $post) {
897 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
898 if ($errorcount[$post->id]) {
899 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
904 // release some memory
905 unset($subscribedusers);
911 $sitetimezone = core_date::get_server_timezone();
913 // Now see if there are any digest mails waiting to be sent, and if we should send them
915 mtrace('Starting digest processing...');
917 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
919 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
920 set_config('digestmailtimelast', 0);
924 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
926 // Delete any really old ones (normally there shouldn't be any)
927 $weekago = $timenow - (7 * 24 * 3600);
928 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
929 mtrace ('Cleaned old digest records');
931 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
933 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
935 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
937 if ($digestposts_rs->valid()) {
939 // We have work to do
942 //caches - reuse the those filled before too
943 $discussionposts = array();
944 $userdiscussions = array();
946 foreach ($digestposts_rs as $digestpost) {
947 if (!isset($posts[$digestpost->postid])) {
948 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
949 $posts[$digestpost->postid] = $post;
954 $discussionid = $digestpost->discussionid;
955 if (!isset($discussions[$discussionid])) {
956 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
957 $discussions[$discussionid] = $discussion;
962 $forumid = $discussions[$discussionid]->forum;
963 if (!isset($forums[$forumid])) {
964 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
965 $forums[$forumid] = $forum;
971 $courseid = $forums[$forumid]->course;
972 if (!isset($courses[$courseid])) {
973 if ($course = $DB->get_record('course', array('id' => $courseid))) {
974 $courses[$courseid] = $course;
980 if (!isset($coursemodules[$forumid])) {
981 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
982 $coursemodules[$forumid] = $cm;
987 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
988 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
990 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
992 // Data collected, start sending out emails to each user
993 foreach ($userdiscussions as $userid => $thesediscussions) {
995 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
999 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
1001 // First of all delete all the queue entries for this user
1002 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
1004 // Init user caches - we keep the cache for one cycle only,
1005 // otherwise it would unnecessarily consume memory.
1006 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
1007 $userto = clone($users[$userid]);
1009 $userto = $DB->get_record('user', array('id' => $userid));
1010 forum_cron_minimise_user_record($userto);
1012 $userto->viewfullnames = array();
1013 $userto->canpost = array();
1014 $userto->markposts = array();
1016 // Override the language and timezone of the "current" user, so that
1017 // mail is customised for the receiver.
1018 cron_setup_user($userto);
1020 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
1022 $headerdata = new stdClass();
1023 $headerdata->sitename = format_string($site->fullname, true);
1024 $headerdata->userprefs = $CFG->wwwroot.'/user/forum.php?id='.$userid.'&course='.$site->id;
1026 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
1027 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
1029 $posthtml = '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p>'
1030 . '<br /><hr size="1" noshade="noshade" />';
1032 foreach ($thesediscussions as $discussionid) {
1034 core_php_time_limit::raise(120); // to be reset for each post
1036 $discussion = $discussions[$discussionid];
1037 $forum = $forums[$discussion->forum];
1038 $course = $courses[$forum->course];
1039 $cm = $coursemodules[$forum->id];
1042 cron_setup_user($userto, $course);
1045 if (!isset($userto->viewfullnames[$forum->id])) {
1046 $modcontext = context_module::instance($cm->id);
1047 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
1049 if (!isset($userto->canpost[$discussion->id])) {
1050 $modcontext = context_module::instance($cm->id);
1051 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1054 $strforums = get_string('forums', 'forum');
1055 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1056 $canreply = $userto->canpost[$discussion->id];
1057 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1059 $posttext .= "\n \n";
1060 $posttext .= '=====================================================================';
1061 $posttext .= "\n \n";
1062 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1063 if ($discussion->name != $forum->name) {
1064 $posttext .= " -> ".format_string($discussion->name,true);
1067 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1070 $posthtml .= "<p><font face=\"sans-serif\">".
1071 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1072 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1073 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
1074 if ($discussion->name == $forum->name) {
1075 $posthtml .= "</font></p>";
1077 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
1081 $postsarray = $discussionposts[$discussionid];
1085 foreach ($postsarray as $postid) {
1086 $post = $posts[$postid];
1088 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1089 $userfrom = $users[$post->userid];
1090 if (!isset($userfrom->idnumber)) {
1091 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1092 forum_cron_minimise_user_record($userfrom);
1095 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1096 forum_cron_minimise_user_record($userfrom);
1097 if ($userscount <= FORUM_CRON_USER_CACHE) {
1099 $users[$userfrom->id] = $userfrom;
1103 mtrace('Could not find user '.$post->userid);
1107 if (!isset($userfrom->groups[$forum->id])) {
1108 if (!isset($userfrom->groups)) {
1109 $userfrom->groups = array();
1110 if (isset($users[$userfrom->id])) {
1111 $users[$userfrom->id]->groups = array();
1114 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1115 if (isset($users[$userfrom->id])) {
1116 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1120 // Headers to help prevent auto-responders.
1121 $userfrom->customheaders = array(
1123 'X-Auto-Response-Suppress: All',
1124 'Auto-Submitted: auto-generated',
1127 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1128 if (!isset($userto->canpost[$discussion->id])) {
1129 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1131 $canreply = $userto->canpost[$discussion->id];
1134 $data = new \mod_forum\output\forum_post_email(
1145 if (!isset($userto->viewfullnames[$forum->id])) {
1146 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1148 $data->viewfullnames = $userto->viewfullnames[$forum->id];
1151 if ($maildigest == 2) {
1152 // Subjects and link only.
1153 $posttext .= $textdigestbasicout->render($data);
1154 $posthtml .= $htmldigestbasicout->render($data);
1156 // The full treatment.
1157 $posttext .= $textdigestfullout->render($data);
1158 $posthtml .= $htmldigestfullout->render($data);
1160 // Create an array of postid's for this user to mark as read.
1161 if (!$CFG->forum_usermarksread) {
1162 $userto->markposts[$post->id] = $post->id;
1167 $footerlinks = array();
1168 if ($canunsubscribe) {
1169 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1171 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1173 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1174 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1175 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1178 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1179 // This user DOESN'T want to receive HTML
1183 $eventdata = new \core\message\message();
1184 $eventdata->courseid = SITEID;
1185 $eventdata->component = 'mod_forum';
1186 $eventdata->name = 'digests';
1187 $eventdata->userfrom = core_user::get_noreply_user();
1188 $eventdata->userto = $userto;
1189 $eventdata->subject = $postsubject;
1190 $eventdata->fullmessage = $posttext;
1191 $eventdata->fullmessageformat = FORMAT_PLAIN;
1192 $eventdata->fullmessagehtml = $posthtml;
1193 $eventdata->notification = 1;
1194 $eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $sentcount);
1195 $mailresult = message_send($eventdata);
1198 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1199 "($userto->email)... not trying again.");
1204 // Mark post as read if forum_usermarksread is set off
1205 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id) == 1) {
1206 forum_tp_mark_posts_read($userto, $userto->markposts);
1211 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1212 set_config('digestmailtimelast', $timenow);
1217 if (!empty($usermailcount)) {
1218 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1221 if (!empty($CFG->forum_lastreadclean)) {
1223 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1224 set_config('forum_lastreadclean', $timenow);
1225 mtrace('Removing old forum read tracking info...');
1226 forum_tp_clean_read_records();
1229 set_config('forum_lastreadclean', time());
1237 * @param object $course
1238 * @param object $user
1239 * @param object $mod TODO this is not used in this function, refactor
1240 * @param object $forum
1241 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1243 function forum_user_outline($course, $user, $mod, $forum) {
1245 require_once("$CFG->libdir/gradelib.php");
1246 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1247 if (empty($grades->items[0]->grades)) {
1250 $grade = reset($grades->items[0]->grades);
1253 $count = forum_count_user_posts($forum->id, $user->id);
1255 if ($count && $count->postcount > 0) {
1256 $result = new stdClass();
1257 $result->info = get_string("numposts", "forum", $count->postcount);
1258 $result->time = $count->lastpost;
1260 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1263 } else if ($grade) {
1264 $result = new stdClass();
1265 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1267 //datesubmitted == time created. dategraded == time modified or time overridden
1268 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1269 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1270 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1271 $result->time = $grade->dategraded;
1273 $result->time = $grade->datesubmitted;
1285 * @param object $coure
1286 * @param object $user
1287 * @param object $mod
1288 * @param object $forum
1290 function forum_user_complete($course, $user, $mod, $forum) {
1291 global $CFG,$USER, $OUTPUT;
1292 require_once("$CFG->libdir/gradelib.php");
1294 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1295 if (!empty($grades->items[0]->grades)) {
1296 $grade = reset($grades->items[0]->grades);
1297 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1298 if ($grade->str_feedback) {
1299 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1303 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1305 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1306 print_error('invalidcoursemodule');
1308 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1310 foreach ($posts as $post) {
1311 if (!isset($discussions[$post->discussion])) {
1314 $discussion = $discussions[$post->discussion];
1316 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1319 echo "<p>".get_string("noposts", "forum")."</p>";
1324 * Filters the forum discussions according to groups membership and config.
1326 * @since Moodle 2.8, 2.7.1, 2.6.4
1327 * @param array $discussions Discussions with new posts array
1328 * @return array Forums with the number of new posts
1330 function forum_filter_user_groups_discussions($discussions) {
1332 // Group the remaining discussions posts by their forumid.
1333 $filteredforums = array();
1335 // Discard not visible groups.
1336 foreach ($discussions as $discussion) {
1338 // Course data is already cached.
1339 $instances = get_fast_modinfo($discussion->course)->get_instances();
1340 $forum = $instances['forum'][$discussion->forum];
1342 // Continue if the user should not see this discussion.
1343 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1347 // Grouping results by forum.
1348 if (empty($filteredforums[$forum->instance])) {
1349 $filteredforums[$forum->instance] = new stdClass();
1350 $filteredforums[$forum->instance]->id = $forum->id;
1351 $filteredforums[$forum->instance]->count = 0;
1353 $filteredforums[$forum->instance]->count += $discussion->count;
1357 return $filteredforums;
1361 * Returns whether the discussion group is visible by the current user or not.
1363 * @since Moodle 2.8, 2.7.1, 2.6.4
1364 * @param cm_info $cm The discussion course module
1365 * @param int $discussiongroupid The discussion groupid
1368 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1370 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1374 if (isguestuser()) {
1378 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1379 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1390 * @param array $courses
1391 * @param array $htmlarray
1393 function forum_print_overview($courses,&$htmlarray) {
1394 global $USER, $CFG, $DB, $SESSION;
1396 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1400 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1404 // Courses to search for new posts
1405 $coursessqls = array();
1407 foreach ($courses as $course) {
1409 // If the user has never entered into the course all posts are pending
1410 if ($course->lastaccess == 0) {
1411 $coursessqls[] = '(d.course = ?)';
1412 $params[] = $course->id;
1414 // Only posts created after the course last access
1416 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1417 $params[] = $course->id;
1418 $params[] = $course->lastaccess;
1421 $params[] = $USER->id;
1422 $coursessql = implode(' OR ', $coursessqls);
1424 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1425 .'FROM {forum_discussions} d '
1426 .'JOIN {forum_posts} p ON p.discussion = d.id '
1427 ."WHERE ($coursessql) "
1428 .'AND p.userid != ? '
1429 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
1430 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1431 .'ORDER BY d.course, d.forum';
1436 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1437 $discussions = array();
1440 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1442 // also get all forum tracking stuff ONCE.
1443 $trackingforums = array();
1444 foreach ($forums as $forum) {
1445 if (forum_tp_can_track_forums($forum)) {
1446 $trackingforums[$forum->id] = $forum;
1450 if (count($trackingforums) > 0) {
1451 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1452 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1453 ' FROM {forum_posts} p '.
1454 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1455 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1456 $params = array($USER->id);
1458 foreach ($trackingforums as $track) {
1459 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1460 $params[] = $track->id;
1461 if (isset($SESSION->currentgroup[$track->course])) {
1462 $groupid = $SESSION->currentgroup[$track->course];
1464 // get first groupid
1465 $groupids = groups_get_all_groups($track->course, $USER->id);
1468 $groupid = key($groupids);
1469 $SESSION->currentgroup[$track->course] = $groupid;
1475 $params[] = $groupid;
1477 $sql = substr($sql,0,-3); // take off the last OR
1478 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1479 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1480 $sql .= 'GROUP BY d.forum,d.course';
1481 $params[] = $cutoffdate;
1485 if (!$unread = $DB->get_records_sql($sql, $params)) {
1492 if (empty($unread) and empty($forumsnewposts)) {
1496 $strforum = get_string('modulename','forum');
1498 foreach ($forums as $forum) {
1502 $showunread = false;
1503 // either we have something from logs, or trackposts, or nothing.
1504 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1505 $count = $forumsnewposts[$forum->id]->count;
1507 if (array_key_exists($forum->id,$unread)) {
1508 $thisunread = $unread[$forum->id]->count;
1511 if ($count > 0 || $thisunread > 0) {
1512 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1513 $forum->name.'</a></div>';
1514 $str .= '<div class="info"><span class="postsincelogin">';
1515 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1516 if (!empty($showunread)) {
1517 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1519 $str .= '</div></div>';
1522 if (!array_key_exists($forum->course,$htmlarray)) {
1523 $htmlarray[$forum->course] = array();
1525 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1526 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1528 $htmlarray[$forum->course]['forum'] .= $str;
1534 * Given a course and a date, prints a summary of all the new
1535 * messages posted in the course since that date
1540 * @uses CONTEXT_MODULE
1541 * @uses VISIBLEGROUPS
1542 * @param object $course
1543 * @param bool $viewfullnames capability
1544 * @param int $timestart
1545 * @return bool success
1547 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1548 global $CFG, $USER, $DB, $OUTPUT;
1550 // do not use log table if possible, it may be huge and is expensive to join with other tables
1552 $allnamefields = user_picture::fields('u', null, 'duserid');
1553 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1554 d.timestart, d.timeend, $allnamefields
1555 FROM {forum_posts} p
1556 JOIN {forum_discussions} d ON d.id = p.discussion
1557 JOIN {forum} f ON f.id = d.forum
1558 JOIN {user} u ON u.id = p.userid
1559 WHERE p.created > ? AND f.course = ?
1560 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1564 $modinfo = get_fast_modinfo($course);
1566 $groupmodes = array();
1569 $strftimerecent = get_string('strftimerecent');
1571 $printposts = array();
1572 foreach ($posts as $post) {
1573 if (!isset($modinfo->instances['forum'][$post->forum])) {
1577 $cm = $modinfo->instances['forum'][$post->forum];
1578 if (!$cm->uservisible) {
1581 $context = context_module::instance($cm->id);
1583 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1587 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1588 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1589 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1594 // Check that the user can see the discussion.
1595 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1596 $printposts[] = $post;
1606 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1607 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
1609 foreach ($printposts as $post) {
1610 $subjectclass = empty($post->parent) ? ' bold' : '';
1611 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
1613 $list .= html_writer::start_tag('li');
1614 $list .= html_writer::start_div('head');
1615 $list .= html_writer::div(userdate($post->modified, $strftimerecent), 'date');
1616 if (!$authorhidden) {
1617 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
1619 $list .= html_writer::end_div(); // Head.
1621 $list .= html_writer::start_div('info' . $subjectclass);
1622 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
1623 if (!empty($post->parent)) {
1624 $discussionurl->param('parent', $post->parent);
1625 $discussionurl->set_anchor('p'. $post->id);
1627 $post->subject = break_up_long_words(format_string($post->subject, true));
1628 $list .= html_writer::link($discussionurl, $post->subject);
1629 $list .= html_writer::end_div(); // Info.
1630 $list .= html_writer::end_tag('li');
1633 $list .= html_writer::end_tag('ul');
1640 * Return grade for given user or all users.
1644 * @param object $forum
1645 * @param int $userid optional user id, 0 means all users
1646 * @return array array of grades, false if none
1648 function forum_get_user_grades($forum, $userid = 0) {
1651 require_once($CFG->dirroot.'/rating/lib.php');
1653 $ratingoptions = new stdClass;
1654 $ratingoptions->component = 'mod_forum';
1655 $ratingoptions->ratingarea = 'post';
1657 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1658 $ratingoptions->modulename = 'forum';
1659 $ratingoptions->moduleid = $forum->id;
1660 $ratingoptions->userid = $userid;
1661 $ratingoptions->aggregationmethod = $forum->assessed;
1662 $ratingoptions->scaleid = $forum->scale;
1663 $ratingoptions->itemtable = 'forum_posts';
1664 $ratingoptions->itemtableusercolumn = 'userid';
1666 $rm = new rating_manager();
1667 return $rm->get_user_grades($ratingoptions);
1671 * Update activity grades
1674 * @param object $forum
1675 * @param int $userid specific user only, 0 means all
1676 * @param boolean $nullifnone return null if grade does not exist
1679 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1681 require_once($CFG->libdir.'/gradelib.php');
1683 if (!$forum->assessed) {
1684 forum_grade_item_update($forum);
1686 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1687 forum_grade_item_update($forum, $grades);
1689 } else if ($userid and $nullifnone) {
1690 $grade = new stdClass();
1691 $grade->userid = $userid;
1692 $grade->rawgrade = NULL;
1693 forum_grade_item_update($forum, $grade);
1696 forum_grade_item_update($forum);
1701 * Create/update grade item for given forum
1704 * @uses GRADE_TYPE_NONE
1705 * @uses GRADE_TYPE_VALUE
1706 * @uses GRADE_TYPE_SCALE
1707 * @param stdClass $forum Forum object with extra cmidnumber
1708 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1709 * @return int 0 if ok
1711 function forum_grade_item_update($forum, $grades=NULL) {
1713 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1714 require_once($CFG->libdir.'/gradelib.php');
1717 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1719 if (!$forum->assessed or $forum->scale == 0) {
1720 $params['gradetype'] = GRADE_TYPE_NONE;
1722 } else if ($forum->scale > 0) {
1723 $params['gradetype'] = GRADE_TYPE_VALUE;
1724 $params['grademax'] = $forum->scale;
1725 $params['grademin'] = 0;
1727 } else if ($forum->scale < 0) {
1728 $params['gradetype'] = GRADE_TYPE_SCALE;
1729 $params['scaleid'] = -$forum->scale;
1732 if ($grades === 'reset') {
1733 $params['reset'] = true;
1737 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1741 * Delete grade item for given forum
1744 * @param stdClass $forum Forum object
1745 * @return grade_item
1747 function forum_grade_item_delete($forum) {
1749 require_once($CFG->libdir.'/gradelib.php');
1751 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1756 * This function returns if a scale is being used by one forum
1759 * @param int $forumid
1760 * @param int $scaleid negative number
1763 function forum_scale_used ($forumid,$scaleid) {
1767 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1769 if (!empty($rec) && !empty($scaleid)) {
1777 * Checks if scale is being used by any instance of forum
1779 * This is used to find out if scale used anywhere
1782 * @param $scaleid int
1783 * @return boolean True if the scale is used by any forum
1785 function forum_scale_used_anywhere($scaleid) {
1787 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1794 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1797 * Gets a post with all info ready for forum_print_post
1798 * Most of these joins are just to get the forum id
1802 * @param int $postid
1803 * @return mixed array of posts or false
1805 function forum_get_post_full($postid) {
1808 $allnames = get_all_user_name_fields(true, 'u');
1809 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1810 FROM {forum_posts} p
1811 JOIN {forum_discussions} d ON p.discussion = d.id
1812 LEFT JOIN {user} u ON p.userid = u.id
1813 WHERE p.id = ?", array($postid));
1817 * Gets all posts in discussion including top parent.
1822 * @param int $discussionid
1823 * @param string $sort
1824 * @param bool $tracking does user track the forum?
1825 * @return array of posts
1827 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1828 global $CFG, $DB, $USER;
1835 $tr_sel = ", fr.id AS postread";
1836 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1837 $params[] = $USER->id;
1840 $allnames = get_all_user_name_fields(true, 'u');
1841 $params[] = $discussionid;
1842 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1843 FROM {forum_posts} p
1844 LEFT JOIN {user} u ON p.userid = u.id
1846 WHERE p.discussion = ?
1847 ORDER BY $sort", $params)) {
1851 foreach ($posts as $pid=>$p) {
1853 if (forum_tp_is_post_old($p)) {
1854 $posts[$pid]->postread = true;
1860 if (!isset($posts[$p->parent])) {
1861 continue; // parent does not exist??
1863 if (!isset($posts[$p->parent]->children)) {
1864 $posts[$p->parent]->children = array();
1866 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1869 // Start with the last child of the first post.
1870 $post = &$posts[reset($posts)->id];
1873 while (!$lastpost) {
1874 if (!isset($post->children)) {
1875 $post->lastpost = true;
1878 // Go to the last child of this post.
1879 $post = &$posts[end($post->children)->id];
1887 * An array of forum objects that the user is allowed to read/search through.
1892 * @param int $userid
1893 * @param int $courseid if 0, we look for forums throughout the whole site.
1894 * @return array of forum objects, or false if no matches
1895 * Forum objects have the following attributes:
1896 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1897 * viewhiddentimedposts
1899 function forum_get_readable_forums($userid, $courseid=0) {
1901 global $CFG, $DB, $USER;
1902 require_once($CFG->dirroot.'/course/lib.php');
1904 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1905 print_error('notinstalled', 'forum');
1909 $courses = $DB->get_records('course', array('id' => $courseid));
1911 // If no course is specified, then the user can see SITE + his courses.
1912 $courses1 = $DB->get_records('course', array('id' => SITEID));
1913 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1914 $courses = array_merge($courses1, $courses2);
1920 $readableforums = array();
1922 foreach ($courses as $course) {
1924 $modinfo = get_fast_modinfo($course);
1926 if (empty($modinfo->instances['forum'])) {
1931 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1933 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1934 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1937 $context = context_module::instance($cm->id);
1938 $forum = $courseforums[$forumid];
1939 $forum->context = $context;
1942 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1947 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1949 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1950 $forum->onlygroups[] = -1;
1953 /// hidden timed discussions
1954 $forum->viewhiddentimedposts = true;
1955 if (!empty($CFG->forum_enabletimedposts)) {
1956 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1957 $forum->viewhiddentimedposts = false;
1962 if ($forum->type == 'qanda'
1963 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1965 // We need to check whether the user has posted in the qanda forum.
1966 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1967 // the user is allowed to see in this forum.
1968 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1969 foreach ($discussionspostedin as $d) {
1970 $forum->onlydiscussions[] = $d->id;
1975 $readableforums[$forum->id] = $forum;
1980 } // End foreach $courses
1982 return $readableforums;
1986 * Returns a list of posts found using an array of search terms.
1991 * @param array $searchterms array of search terms, e.g. word +word -word
1992 * @param int $courseid if 0, we search through the whole site
1993 * @param int $limitfrom
1994 * @param int $limitnum
1995 * @param int &$totalcount
1996 * @param string $extrasql
1997 * @return array|bool Array of posts found or false
1999 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2000 &$totalcount, $extrasql='') {
2001 global $CFG, $DB, $USER;
2002 require_once($CFG->libdir.'/searchlib.php');
2004 $forums = forum_get_readable_forums($USER->id, $courseid);
2006 if (count($forums) == 0) {
2011 $now = round(time(), -2); // db friendly
2013 $fullaccess = array();
2017 foreach ($forums as $forumid => $forum) {
2020 if (!$forum->viewhiddentimedposts) {
2021 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2022 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2026 $context = $forum->context;
2028 if ($forum->type == 'qanda'
2029 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2030 if (!empty($forum->onlydiscussions)) {
2031 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2032 $params = array_merge($params, $discussionid_params);
2033 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2035 $select[] = "p.parent = 0";
2039 if (!empty($forum->onlygroups)) {
2040 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2041 $params = array_merge($params, $groupid_params);
2042 $select[] = "d.groupid $groupid_sql";
2046 $selects = implode(" AND ", $select);
2047 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2048 $params['forum'.$forumid] = $forumid;
2050 $fullaccess[] = $forumid;
2055 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2056 $params = array_merge($params, $fullid_params);
2057 $where[] = "(d.forum $fullid_sql)";
2060 $selectdiscussion = "(".implode(" OR ", $where).")";
2062 $messagesearch = '';
2065 // Need to concat these back together for parser to work.
2066 foreach($searchterms as $searchterm){
2067 if ($searchstring != '') {
2068 $searchstring .= ' ';
2070 $searchstring .= $searchterm;
2073 // We need to allow quoted strings for the search. The quotes *should* be stripped
2074 // by the parser, but this should be examined carefully for security implications.
2075 $searchstring = str_replace("\\\"","\"",$searchstring);
2076 $parser = new search_parser();
2077 $lexer = new search_lexer($parser);
2079 if ($lexer->parse($searchstring)) {
2080 $parsearray = $parser->get_parsed_array();
2081 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2082 'p.userid', 'u.id', 'u.firstname',
2083 'u.lastname', 'p.modified', 'd.forum');
2084 $params = array_merge($params, $msparams);
2087 $fromsql = "{forum_posts} p,
2088 {forum_discussions} d,
2091 $selectsql = " $messagesearch
2092 AND p.discussion = d.id
2094 AND $selectdiscussion
2097 $countsql = "SELECT COUNT(*)
2101 $allnames = get_all_user_name_fields(true, 'u');
2102 $searchsql = "SELECT p.*,
2110 ORDER BY p.modified DESC";
2112 $totalcount = $DB->count_records_sql($countsql, $params);
2114 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2118 * Returns a list of all new posts that have not been mailed yet
2120 * @param int $starttime posts created after this time
2121 * @param int $endtime posts created before this
2122 * @param int $now used for timed discussions only
2125 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2129 $params['mailed'] = FORUM_MAILED_PENDING;
2130 $params['ptimestart'] = $starttime;
2131 $params['ptimeend'] = $endtime;
2132 $params['mailnow'] = 1;
2134 if (!empty($CFG->forum_enabletimedposts)) {
2138 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2139 $params['pptimestart'] = $starttime;
2140 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2141 $params['dtimestart'] = $now;
2142 $params['dtimeend'] = $now;
2145 $selectsql = "AND p.created >= :ptimestart";
2148 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2149 FROM {forum_posts} p
2150 JOIN {forum_discussions} d ON d.id = p.discussion
2151 WHERE p.mailed = :mailed
2153 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2155 ORDER BY p.modified ASC", $params);
2159 * Marks posts before a certain time as being mailed already
2163 * @param int $endtime
2164 * @param int $now Defaults to time()
2167 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2175 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2176 $params['now'] = $now;
2177 $params['endtime'] = $endtime;
2178 $params['mailnow'] = 1;
2179 $params['mailedpending'] = FORUM_MAILED_PENDING;
2181 if (empty($CFG->forum_enabletimedposts)) {
2182 return $DB->execute("UPDATE {forum_posts}
2183 SET mailed = :mailedsuccess
2184 WHERE (created < :endtime OR mailnow = :mailnow)
2185 AND mailed = :mailedpending", $params);
2187 return $DB->execute("UPDATE {forum_posts}
2188 SET mailed = :mailedsuccess
2189 WHERE discussion NOT IN (SELECT d.id
2190 FROM {forum_discussions} d
2191 WHERE d.timestart > :now)
2192 AND (created < :endtime OR mailnow = :mailnow)
2193 AND mailed = :mailedpending", $params);
2198 * Get all the posts for a user in a forum suitable for forum_print_post
2202 * @uses CONTEXT_MODULE
2205 function forum_get_user_posts($forumid, $userid) {
2209 $params = array($forumid, $userid);
2211 if (!empty($CFG->forum_enabletimedposts)) {
2212 $cm = get_coursemodule_from_instance('forum', $forumid);
2213 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2215 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2221 $allnames = get_all_user_name_fields(true, 'u');
2222 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2224 JOIN {forum_discussions} d ON d.forum = f.id
2225 JOIN {forum_posts} p ON p.discussion = d.id
2226 JOIN {user} u ON u.id = p.userid
2230 ORDER BY p.modified ASC", $params);
2234 * Get all the discussions user participated in
2238 * @uses CONTEXT_MODULE
2239 * @param int $forumid
2240 * @param int $userid
2241 * @return array Array or false
2243 function forum_get_user_involved_discussions($forumid, $userid) {
2247 $params = array($forumid, $userid);
2248 if (!empty($CFG->forum_enabletimedposts)) {
2249 $cm = get_coursemodule_from_instance('forum', $forumid);
2250 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2252 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2258 return $DB->get_records_sql("SELECT DISTINCT d.*
2260 JOIN {forum_discussions} d ON d.forum = f.id
2261 JOIN {forum_posts} p ON p.discussion = d.id
2264 $timedsql", $params);
2268 * Get all the posts for a user in a forum suitable for forum_print_post
2272 * @param int $forumid
2273 * @param int $userid
2274 * @return array of counts or false
2276 function forum_count_user_posts($forumid, $userid) {
2280 $params = array($forumid, $userid);
2281 if (!empty($CFG->forum_enabletimedposts)) {
2282 $cm = get_coursemodule_from_instance('forum', $forumid);
2283 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2285 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2291 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2293 JOIN {forum_discussions} d ON d.forum = f.id
2294 JOIN {forum_posts} p ON p.discussion = d.id
2295 JOIN {user} u ON u.id = p.userid
2298 $timedsql", $params);
2302 * Given a log entry, return the forum post details for it.
2306 * @param object $log
2307 * @return array|null
2309 function forum_get_post_from_log($log) {
2312 $allnames = get_all_user_name_fields(true, 'u');
2313 if ($log->action == "add post") {
2315 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2316 FROM {forum_discussions} d,
2321 AND d.id = p.discussion
2323 AND u.deleted <> '1'
2324 AND f.id = d.forum", array($log->info));
2327 } else if ($log->action == "add discussion") {
2329 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2330 FROM {forum_discussions} d,
2335 AND d.firstpost = p.id
2337 AND u.deleted <> '1'
2338 AND f.id = d.forum", array($log->info));
2344 * Given a discussion id, return the first post from the discussion
2348 * @param int $dicsussionid
2351 function forum_get_firstpost_from_discussion($discussionid) {
2354 return $DB->get_record_sql("SELECT p.*
2355 FROM {forum_discussions} d,
2358 AND d.firstpost = p.id ", array($discussionid));
2362 * Returns an array of counts of replies to each discussion
2366 * @param int $forumid
2367 * @param string $forumsort
2370 * @param int $perpage
2373 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2379 } else if ($page != -1) {
2380 $limitfrom = $page*$perpage;
2381 $limitnum = $perpage;
2387 if ($forumsort == "") {
2392 $orderby = "ORDER BY $forumsort";
2393 $groupby = ", ".strtolower($forumsort);
2394 $groupby = str_replace('desc', '', $groupby);
2395 $groupby = str_replace('asc', '', $groupby);
2398 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2399 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2400 FROM {forum_posts} p
2401 JOIN {forum_discussions} d ON p.discussion = d.id
2402 WHERE p.parent > 0 AND d.forum = ?
2403 GROUP BY p.discussion";
2404 return $DB->get_records_sql($sql, array($forumid));
2407 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2408 FROM {forum_posts} p
2409 JOIN {forum_discussions} d ON p.discussion = d.id
2411 GROUP BY p.discussion $groupby $orderby";
2412 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2420 * @staticvar array $cache
2421 * @param object $forum
2423 * @param object $course
2426 function forum_count_discussions($forum, $cm, $course) {
2427 global $CFG, $DB, $USER;
2429 static $cache = array();
2431 $now = round(time(), -2); // db cache friendliness
2433 $params = array($course->id);
2435 if (!isset($cache[$course->id])) {
2436 if (!empty($CFG->forum_enabletimedposts)) {
2437 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2444 $sql = "SELECT f.id, COUNT(d.id) as dcount
2446 JOIN {forum_discussions} d ON d.forum = f.id
2451 if ($counts = $DB->get_records_sql($sql, $params)) {
2452 foreach ($counts as $count) {
2453 $counts[$count->id] = $count->dcount;
2455 $cache[$course->id] = $counts;
2457 $cache[$course->id] = array();
2461 if (empty($cache[$course->id][$forum->id])) {
2465 $groupmode = groups_get_activity_groupmode($cm, $course);
2467 if ($groupmode != SEPARATEGROUPS) {
2468 return $cache[$course->id][$forum->id];
2471 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2472 return $cache[$course->id][$forum->id];
2475 require_once($CFG->dirroot.'/course/lib.php');
2477 $modinfo = get_fast_modinfo($course);
2479 $mygroups = $modinfo->get_groups($cm->groupingid);
2481 // add all groups posts
2484 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2485 $params[] = $forum->id;
2487 if (!empty($CFG->forum_enabletimedposts)) {
2488 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2495 $sql = "SELECT COUNT(d.id)
2496 FROM {forum_discussions} d
2497 WHERE d.groupid $mygroups_sql AND d.forum = ?
2500 return $DB->get_field_sql($sql, $params);
2504 * Get all discussions in a forum
2509 * @uses CONTEXT_MODULE
2510 * @uses VISIBLEGROUPS
2512 * @param string $forumsort
2513 * @param bool $fullpost
2514 * @param int $unused
2516 * @param bool $userlastmodified
2518 * @param int $perpage
2519 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2520 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
2521 * @param int $updatedsince retrieve only discussions updated since the given time
2524 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
2525 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
2526 $updatedsince = 0) {
2527 global $CFG, $DB, $USER;
2531 $now = round(time(), -2);
2532 $params = array($cm->instance);
2534 $modcontext = context_module::instance($cm->id);
2536 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2540 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2542 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2543 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2547 $timelimit .= " OR d.userid = ?";
2548 $params[] = $USER->id;
2557 } else if ($page != -1) {
2558 $limitfrom = $page*$perpage;
2559 $limitnum = $perpage;
2565 $groupmode = groups_get_activity_groupmode($cm);
2569 if (empty($modcontext)) {
2570 $modcontext = context_module::instance($cm->id);
2573 // Special case, we received a groupid to override currentgroup.
2575 $course = get_course($cm->course);
2576 if (!groups_group_visible($groupid, $course, $cm)) {
2577 // User doesn't belong to this group, return nothing.
2580 $currentgroup = $groupid;
2581 } else if ($groupid === -1) {
2582 $currentgroup = groups_get_activity_group($cm);
2584 // Get discussions for all groups current user can see.
2585 $currentgroup = null;
2588 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2589 if ($currentgroup) {
2590 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2591 $params[] = $currentgroup;
2599 // Get discussions for all groups current user can see.
2600 if ($currentgroup === null) {
2601 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
2602 if (empty($mygroups)) {
2603 $groupselect = "AND d.groupid = -1";
2605 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2606 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2607 $params = array_merge($params, $inparamsgroups);
2609 } else if ($currentgroup) {
2610 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2611 $params[] = $currentgroup;
2613 $groupselect = "AND d.groupid = -1";
2619 if (empty($forumsort)) {
2620 $forumsort = forum_get_default_sort_order();
2622 if (empty($fullpost)) {
2623 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2628 if (empty($userlastmodified)) { // We don't need to know this
2632 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2633 um.imagealt AS umimagealt';
2634 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2637 $updatedsincesql = '';
2638 if (!empty($updatedsince)) {
2639 $updatedsincesql = 'AND d.timemodified > ?';
2640 $params[] = $updatedsince;
2643 $allnames = get_all_user_name_fields(true, 'u');
2644 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
2645 u.email, u.picture, u.imagealt $umfields
2646 FROM {forum_discussions} d
2647 JOIN {forum_posts} p ON p.discussion = d.id
2648 JOIN {user} u ON p.userid = u.id
2650 WHERE d.forum = ? AND p.parent = 0
2651 $timelimit $groupselect $updatedsincesql
2652 ORDER BY $forumsort, d.id DESC";
2654 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2658 * Gets the neighbours (previous and next) of a discussion.
2660 * The calculation is based on the timemodified when time modified or time created is identical
2661 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
2663 * For blog-style forums, the calculation is based on the original creation time of the
2666 * Please note that this does not check whether or not the discussion passed is accessible
2667 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2668 * the returned neighbours are checked and are accessible to the current user.
2670 * @param object $cm The CM record.
2671 * @param object $discussion The discussion record.
2672 * @param object $forum The forum instance record.
2673 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2674 * they contain the record with minimal information such as 'id' and 'name'.
2675 * When the neighbour is not found the value is false.
2677 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
2678 global $CFG, $DB, $USER;
2680 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
2681 throw new coding_exception('Discussion is not part of the same forum.');
2684 $neighbours = array('prev' => false, 'next' => false);
2685 $now = round(time(), -2);
2688 $modcontext = context_module::instance($cm->id);
2689 $groupmode = groups_get_activity_groupmode($cm);
2690 $currentgroup = groups_get_activity_group($cm);
2692 // Users must fulfill timed posts.
2694 if (!empty($CFG->forum_enabletimedposts)) {
2695 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2696 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2697 $params['tltimestart'] = $now;
2698 $params['tltimeend'] = $now;
2700 $timelimit .= ' OR d.userid = :tluserid';
2701 $params['tluserid'] = $USER->id;
2707 // Limiting to posts accessible according to groups.
2710 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2711 if ($currentgroup) {
2712 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2713 $params['groupid'] = $currentgroup;
2716 if ($currentgroup) {
2717 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2718 $params['groupid'] = $currentgroup;
2720 $groupselect = 'AND d.groupid = -1';
2725 $params['forumid'] = $cm->instance;
2726 $params['discid1'] = $discussion->id;
2727 $params['discid2'] = $discussion->id;
2728 $params['discid3'] = $discussion->id;
2729 $params['discid4'] = $discussion->id;
2730 $params['disctimecompare1'] = $discussion->timemodified;
2731 $params['disctimecompare2'] = $discussion->timemodified;
2732 $params['pinnedstate1'] = (int) $discussion->pinned;
2733 $params['pinnedstate2'] = (int) $discussion->pinned;
2734 $params['pinnedstate3'] = (int) $discussion->pinned;
2735 $params['pinnedstate4'] = (int) $discussion->pinned;
2737 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2738 FROM {forum_discussions} d
2739 JOIN {forum_posts} p ON d.firstpost = p.id
2740 WHERE d.forum = :forumid
2741 AND d.id <> :discid1
2744 $comparefield = "d.timemodified";
2745 $comparevalue = ":disctimecompare1";
2746 $comparevalue2 = ":disctimecompare2";
2747 if (!empty($CFG->forum_enabletimedposts)) {
2748 // Here we need to take into account the release time (timestart)
2749 // if one is set, of the neighbouring posts and compare it to the
2750 // timestart or timemodified of *this* post depending on if the
2751 // release date of this post is in the future or not.
2752 // This stops discussions that appear later because of the
2753 // timestart value from being buried under discussions that were
2755 $comparefield = "CASE WHEN d.timemodified < d.timestart
2756 THEN d.timestart ELSE d.timemodified END";
2757 if ($discussion->timemodified < $discussion->timestart) {
2758 // Normally we would just use the timemodified for sorting
2759 // discussion posts. However, when timed discussions are enabled,
2760 // then posts need to be sorted base on the later of timemodified
2761 // or the release date of the post (timestart).
2762 $params['disctimecompare1'] = $discussion->timestart;
2763 $params['disctimecompare2'] = $discussion->timestart;
2766 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2767 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
2769 if ($forum->type === 'blog') {
2770 $subselect = "SELECT pp.created
2771 FROM {forum_discussions} dd
2772 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
2774 $subselectwhere1 = " WHERE dd.id = :discid3";
2775 $subselectwhere2 = " WHERE dd.id = :discid4";
2777 $comparefield = "p.created";
2779 $sub1 = $subselect.$subselectwhere1;
2780 $comparevalue = "($sub1)";
2782 $sub2 = $subselect.$subselectwhere2;
2783 $comparevalue2 = "($sub2)";
2785 $orderbydesc = "d.pinned, p.created DESC";
2786 $orderbyasc = "d.pinned, p.created ASC";
2789 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2790 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2791 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2792 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
2794 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2795 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2796 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2797 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
2799 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2800 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2805 * Get the sql to use in the ORDER BY clause for forum discussions.
2807 * This has the ordering take timed discussion windows into account.
2809 * @param bool $desc True for DESC, False for ASC.
2810 * @param string $compare The field in the SQL to compare to normally sort by.
2811 * @param string $prefix The prefix being used for the discussion table.
2812 * @param bool $pinned sort pinned posts to the top
2815 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
2818 if (!empty($prefix)) {
2822 $dir = $desc ? 'DESC' : 'ASC';
2824 if ($pinned == true) {
2825 $pinned = "{$prefix}pinned DESC,";
2830 $sort = "{$prefix}timemodified";
2831 if (!empty($CFG->forum_enabletimedposts)) {
2832 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2833 THEN {$prefix}timestart
2837 return "$pinned $sort $dir";
2845 * @uses CONTEXT_MODULE
2846 * @uses VISIBLEGROUPS
2850 function forum_get_discussions_unread($cm) {
2851 global $CFG, $DB, $USER;
2853 $now = round(time(), -2);
2854 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2857 $groupmode = groups_get_activity_groupmode($cm);
2858 $currentgroup = groups_get_activity_group($cm);
2861 $modcontext = context_module::instance($cm->id);
2863 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2864 if ($currentgroup) {
2865 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2866 $params['currentgroup'] = $currentgroup;
2872 //separate groups without access all
2873 if ($currentgroup) {
2874 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2875 $params['currentgroup'] = $currentgroup;
2877 $groupselect = "AND d.groupid = -1";
2884 if (!empty($CFG->forum_enabletimedposts)) {
2885 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2886 $params['now1'] = $now;
2887 $params['now2'] = $now;
2892 $sql = "SELECT d.id, COUNT(p.id) AS unread
2893 FROM {forum_discussions} d
2894 JOIN {forum_posts} p ON p.discussion = d.id
2895 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2896 WHERE d.forum = {$cm->instance}
2897 AND p.modified >= :cutoffdate AND r.id is NULL
2901 $params['cutoffdate'] = $cutoffdate;
2903 if ($unreads = $DB->get_records_sql($sql, $params)) {
2904 foreach ($unreads as $unread) {
2905 $unreads[$unread->id] = $unread->unread;
2917 * @uses CONEXT_MODULE
2918 * @uses VISIBLEGROUPS
2922 function forum_get_discussions_count($cm) {
2923 global $CFG, $DB, $USER;
2925 $now = round(time(), -2);
2926 $params = array($cm->instance);
2927 $groupmode = groups_get_activity_groupmode($cm);
2928 $currentgroup = groups_get_activity_group($cm);
2931 $modcontext = context_module::instance($cm->id);
2933 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2934 if ($currentgroup) {
2935 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2936 $params[] = $currentgroup;
2942 //seprate groups without access all
2943 if ($currentgroup) {
2944 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2945 $params[] = $currentgroup;
2947 $groupselect = "AND d.groupid = -1";
2956 if (!empty($CFG->forum_enabletimedposts)) {
2958 $modcontext = context_module::instance($cm->id);
2960 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2961 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2965 $timelimit .= " OR d.userid = ?";
2966 $params[] = $USER->id;
2972 $sql = "SELECT COUNT(d.id)
2973 FROM {forum_discussions} d
2974 JOIN {forum_posts} p ON p.discussion = d.id
2975 WHERE d.forum = ? AND p.parent = 0
2976 $groupselect $timelimit";
2978 return $DB->get_field_sql($sql, $params);
2982 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2988 * @param int $courseid
2989 * @param string $type
2991 function forum_get_course_forum($courseid, $type) {
2992 // How to set up special 1-per-course forums
2993 global $CFG, $DB, $OUTPUT, $USER;
2995 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2996 // There should always only be ONE, but with the right combination of
2997 // errors there might be more. In this case, just return the oldest one (lowest ID).
2998 foreach ($forums as $forum) {
2999 return $forum; // ie the first one
3003 // Doesn't exist, so create one now.
3004 $forum = new stdClass();
3005 $forum->course = $courseid;
3006 $forum->type = "$type";
3007 if (!empty($USER->htmleditor)) {
3008 $forum->introformat = $USER->htmleditor;
3010 switch ($forum->type) {
3012 $forum->name = get_string("namenews", "forum");
3013 $forum->intro = get_string("intronews", "forum");
3014 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
3015 $forum->assessed = 0;
3016 if ($courseid == SITEID) {
3017 $forum->name = get_string("sitenews");
3018 $forum->forcesubscribe = 0;
3022 $forum->name = get_string("namesocial", "forum");
3023 $forum->intro = get_string("introsocial", "forum");
3024 $forum->assessed = 0;
3025 $forum->forcesubscribe = 0;
3028 $forum->name = get_string('blogforum', 'forum');
3029 $forum->intro = get_string('introblog', 'forum');
3030 $forum->assessed = 0;
3031 $forum->forcesubscribe = 0;
3034 echo $OUTPUT->notification("That forum type doesn't exist!");
3039 $forum->timemodified = time();
3040 $forum->id = $DB->insert_record("forum", $forum);
3042 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
3043 echo $OUTPUT->notification("Could not find forum module!!");
3046 $mod = new stdClass();
3047 $mod->course = $courseid;
3048 $mod->module = $module->id;
3049 $mod->instance = $forum->id;
3051 include_once("$CFG->dirroot/course/lib.php");
3052 if (! $mod->coursemodule = add_course_module($mod) ) {
3053 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3056 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3057 return $DB->get_record("forum", array("id" => "$forum->id"));
3061 * Print a forum post
3065 * @uses FORUM_MODE_THREADED
3066 * @uses PORTFOLIO_FORMAT_PLAINHTML
3067 * @uses PORTFOLIO_FORMAT_FILE
3068 * @uses PORTFOLIO_FORMAT_RICHHTML
3069 * @uses PORTFOLIO_ADD_TEXT_LINK
3070 * @uses CONTEXT_MODULE
3071 * @param object $post The post to print.
3072 * @param object $discussion
3073 * @param object $forum
3075 * @param object $course
3076 * @param boolean $ownpost Whether this post belongs to the current user.
3077 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3078 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3079 * @param string $footer Extra stuff to print after the message.
3080 * @param string $highlight Space-separated list of terms to highlight.
3081 * @param int $post_read true, false or -99. If we already know whether this user
3082 * has read this post, pass that in, otherwise, pass in -99, and this
3083 * function will work it out.
3084 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3085 * the current user can't see this post, if this argument is true
3086 * (the default) then print a dummy 'you can't see this post' post.
3087 * If false, don't output anything at all.
3088 * @param bool|null $istracked
3091 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3092 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3093 global $USER, $CFG, $OUTPUT;
3095 require_once($CFG->libdir . '/filelib.php');
3099 // This is an extremely hacky way to ensure we only print the 'unread' anchor
3100 // the first time we encounter an unread post on a page. Ideally this would
3101 // be moved into the caller somehow, and be better testable. But at the time
3102 // of dealing with this bug, this static workaround was the most surgical and
3103 // it fits together with only printing th unread anchor id once on a given page.
3104 static $firstunreadanchorprinted = false;
3106 $modcontext = context_module::instance($cm->id);
3108 $post->course = $course->id;
3109 $post->forum = $forum->id;
3110 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3111 if (!empty($CFG->enableplagiarism)) {
3112 require_once($CFG->libdir.'/plagiarismlib.php');
3113 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3114 'content' => $post->message,
3116 'course' => $post->course,
3117 'forum' => $post->forum));
3121 if (!isset($cm->cache)) {
3122 $cm->cache = new stdClass;
3125 if (!isset($cm->cache->caps)) {
3126 $cm->cache->caps = array();
3127 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3128 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3129 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3130 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3131 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3132 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3133 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3134 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3135 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3138 if (!isset($cm->uservisible)) {
3139 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3142 if ($istracked && is_null($postisread)) {
3143 $postisread = forum_tp_is_post_read($USER->id, $post);
3146 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3148 if (!$dummyifcantsee) {
3155 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3156 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3158 'aria-label' => get_string('hiddenforumpost', 'forum')));
3159 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3160 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3161 if ($post->parent) {
3162 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3164 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3166 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3167 'role' => 'header')); // Subject.
3168 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3169 'role' => 'header')); // Author.
3170 $output .= html_writer::end_tag('div');
3171 $output .= html_writer::end_tag('div'); // row
3172 $output .= html_writer::start_tag('div', array('class'=>'row'));
3173 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3174 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3175 $output .= html_writer::end_tag('div'); // row
3176 $output .= html_writer::end_tag('div'); // forumpost
3186 $str = new stdClass;
3187 $str->edit = get_string('edit', 'forum');
3188 $str->delete = get_string('delete', 'forum');
3189 $str->reply = get_string('reply', 'forum');
3190 $str->parent = get_string('parent', 'forum');
3191 $str->pruneheading = get_string('pruneheading', 'forum');
3192 $str->prune = get_string('prune', 'forum');
3193 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3194 $str->markread = get_string('markread', 'forum');
3195 $str->markunread = get_string('markunread', 'forum');
3198 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3200 // Build an object that represents the posting user
3201 $postuser = new stdClass;
3202 $postuserfields = explode(',', user_picture::fields());
3203 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3204 $postuser->id = $post->userid;
3205 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3206 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3208 // Prepare the groups the posting user belongs to
3209 if (isset($cm->cache->usersgroups)) {
3211 if (isset($cm->cache->usersgroups[$post->userid])) {
3212 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3213 $groups[$gid] = $cm->cache->groups[$gid];
3217 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3220 // Prepare the attachements for the post, files then images
3221 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3223 // Determine if we need to shorten this post
3224 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3227 // Prepare an array of commands
3228 $commands = array();
3231 $permalink = new moodle_url($discussionlink);
3232 $permalink->set_anchor('p' . $post->id);
3233 $commands[] = array('url' => $permalink, 'text' => get_string('permalink', 'forum'));
3235 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3236 // Don't display the mark read / unread controls in this case.
3237 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3238 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3239 $text = $str->markunread;
3241 $url->param('mark', 'read');
3242 $text = $str->markread;
3244 if ($str->displaymode == FORUM_MODE_THREADED) {
3245 $url->param('parent', $post->parent);
3247 $url->set_anchor('p'.$post->id);
3249 $commands[] = array('url'=>$url, 'text'=>$text);
3252 // Zoom in to the parent specifically
3253 if ($post->parent) {
3254 $url = new moodle_url($discussionlink);
3255 if ($str->displaymode == FORUM_MODE_THREADED) {
3256 $url->param('parent', $post->parent);
3258 $url->set_anchor('p'.$post->parent);
3260 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3263 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3264 $age = time() - $post->created;
3265 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3269 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3270 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3271 // The first post in single simple is the forum description.
3272 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3274 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3275 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3278 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3279 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3282 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3283 // Do not allow deleting of first post in single simple type.
3284 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3285 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3289 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3292 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3293 $p = array('postid' => $post->id);
3294 require_once($CFG->libdir.'/portfoliolib.php');
3295 $button = new portfolio_add_button();
3296 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3297 if (empty($attachments)) {
3298 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3300 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3303 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3304 if (!empty($porfoliohtml)) {
3305 $commands[] = $porfoliohtml;
3308 // Finished building commands
3317 $forumpostclass = ' read';
3319 $forumpostclass = ' unread';
3320 // If this is the first unread post printed then give it an anchor and id of unread.
3321 if (!$firstunreadanchorprinted) {
3322 $output .= html_writer::tag('a', '', array('id' => 'unread'));
3323 $firstunreadanchorprinted = true;
3327 // ignore trackign status if not tracked or tracked param missing
3328 $forumpostclass = '';
3332 if (empty($post->parent)) {
3333 $topicclass = ' firstpost starter';
3336 if (!empty($post->lastpost)) {
3337 $forumpostclass .= ' lastpost';
3340 // Flag to indicate whether we should hide the author or not.
3341 $authorhidden = forum_is_author_hidden($post, $forum);
3342 $postbyuser = new stdClass;
3343 $postbyuser->post = $post->subject;
3344 $postbyuser->user = $postuser->fullname;
3345 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3346 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3347 // Begin forum post.
3348 $output .= html_writer::start_div('forumpost clearfix' . $forumpostclass . $topicclass,
3349 ['role' => 'region', 'aria-label' => $discussionbyuser]);
3350 // Begin header row.
3351 $output .= html_writer::start_div('row header clearfix');
3354 if (!$authorhidden) {
3355 $picture = $OUTPUT->user_picture($postuser, ['courseid' => $course->id]);
3356 $output .= html_writer::div($picture, 'left picture');
3357 $topicclass = 'topic' . $topicclass;
3360 // Begin topic column.
3361 $output .= html_writer::start_div($topicclass);
3362 $postsubject = $post->subject;
3363 if (empty($post->subjectnoformat)) {
3364 $postsubject = format_string($postsubject);
3366 $output .= html_writer::div($postsubject, 'subject', ['role' => 'heading', 'aria-level' => '2']);
3368 if ($authorhidden) {
3369 $bytext = userdate($post->modified);
3371 $by = new stdClass();
3372 $by->date = userdate($post->modified);
3373 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3374 $bytext = get_string('bynameondate', 'forum', $by);
3377 'role' => 'heading',
3378 'aria-level' => '2',
3380 $output .= html_writer::div($bytext, 'author', $bytextoptions);
3381 // End topic column.
3382 $output .= html_writer::end_div();
3385 $output .= html_writer::end_div();
3387 // Row with the forum post content.
3388 $output .= html_writer::start_div('row maincontent clearfix');
3389 // Show if author is not hidden or we have groups.
3390 if (!$authorhidden || $groups) {
3391 $output .= html_writer::start_div('left');
3394 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3396 if (empty($groupoutput)) {
3397 $groupoutput = ' ';
3399 $output .= html_writer::div($groupoutput, 'grouppictures');
3400 $output .= html_writer::end_div(); // Left side.
3403 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3404 $output .= html_writer::start_tag('div', array('class'=>'content'));
3406 $options = new stdClass;
3407 $options->para = false;
3408 $options->trusted = $post->messagetrust;
3409 $options->context = $modcontext;
3411 // Prepare shortened version by filtering the text then shortening it.
3412 $postclass = 'shortenedpost';
3413 $postcontent = format_text($post->message, $post->messageformat, $options);
3414 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3415 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3416 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3417 array('class'=>'post-word-count'));
3419 // Prepare whole post
3420 $postclass = 'fullpost';
3421 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3422 if (!empty($highlight)) {
3423 $postcontent = highlight($highlight, $postcontent);
3425 if (!empty($forum->displaywordcount)) {
3426 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3427 array('class'=>'post-word-count'));
3429 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3432 // Output the post content
3433 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3434 $output .= html_writer::end_tag('div'); // Content
3435 $output .= html_writer::end_tag('div'); // Content mask
3436 $output .= html_writer::end_tag('div'); // Row
3438 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3439 $output .= html_writer::tag('div',' ', array('class'=>'left'));
3440 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'