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);
67 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
70 * Given an object containing all the necessary data,
71 * (defined by the form in mod_form.php) this function
72 * will create a new instance and return the id number
73 * of the new instance.
75 * @param stdClass $forum add forum instance
76 * @param mod_forum_mod_form $mform
77 * @return int intance id
79 function forum_add_instance($forum, $mform = null) {
82 $forum->timemodified = time();
84 if (empty($forum->assessed)) {
88 if (empty($forum->ratingtime) or empty($forum->assessed)) {
89 $forum->assesstimestart = 0;
90 $forum->assesstimefinish = 0;
93 $forum->id = $DB->insert_record('forum', $forum);
94 $modcontext = context_module::instance($forum->coursemodule);
96 if ($forum->type == 'single') { // Create related discussion.
97 $discussion = new stdClass();
98 $discussion->course = $forum->course;
99 $discussion->forum = $forum->id;
100 $discussion->name = $forum->name;
101 $discussion->assessed = $forum->assessed;
102 $discussion->message = $forum->intro;
103 $discussion->messageformat = $forum->introformat;
104 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
105 $discussion->mailnow = false;
106 $discussion->groupid = -1;
110 $discussion->id = forum_add_discussion($discussion, null, $message);
112 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
113 // Ugly hack - we need to copy the files somehow.
114 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
115 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
117 $options = array('subdirs'=>true); // Use the same options as intro field!
118 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
119 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
123 forum_grade_item_update($forum);
129 * Handle changes following the creation of a forum instance.
130 * This function is typically called by the course_module_created observer.
132 * @param object $context the forum context
133 * @param stdClass $forum The forum object
136 function forum_instance_created($context, $forum) {
137 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
138 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
139 foreach ($users as $user) {
140 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
146 * Given an object containing all the necessary data,
147 * (defined by the form in mod_form.php) this function
148 * will update an existing instance with new data.
151 * @param object $forum forum instance (with magic quotes)
152 * @return bool success
154 function forum_update_instance($forum, $mform) {
155 global $DB, $OUTPUT, $USER;
157 $forum->timemodified = time();
158 $forum->id = $forum->instance;
160 if (empty($forum->assessed)) {
161 $forum->assessed = 0;
164 if (empty($forum->ratingtime) or empty($forum->assessed)) {
165 $forum->assesstimestart = 0;
166 $forum->assesstimefinish = 0;
169 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
171 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
172 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
173 // 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
174 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
175 forum_update_grades($forum); // recalculate grades for the forum
178 if ($forum->type == 'single') { // Update related discussion and post.
179 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
180 if (!empty($discussions)) {
181 if (count($discussions) > 1) {
182 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
184 $discussion = array_pop($discussions);
186 // try to recover by creating initial discussion - MDL-16262
187 $discussion = new stdClass();
188 $discussion->course = $forum->course;
189 $discussion->forum = $forum->id;
190 $discussion->name = $forum->name;
191 $discussion->assessed = $forum->assessed;
192 $discussion->message = $forum->intro;
193 $discussion->messageformat = $forum->introformat;
194 $discussion->messagetrust = true;
195 $discussion->mailnow = false;
196 $discussion->groupid = -1;
200 forum_add_discussion($discussion, null, $message);
202 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
203 print_error('cannotadd', 'forum');
206 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
207 print_error('cannotfindfirstpost', 'forum');
210 $cm = get_coursemodule_from_instance('forum', $forum->id);
211 $modcontext = context_module::instance($cm->id, MUST_EXIST);
213 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
214 $post->subject = $forum->name;
215 $post->message = $forum->intro;
216 $post->messageformat = $forum->introformat;
217 $post->messagetrust = trusttext_trusted($modcontext);
218 $post->modified = $forum->timemodified;
219 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
221 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
222 // Ugly hack - we need to copy the files somehow.
223 $options = array('subdirs'=>true); // Use the same options as intro field!
224 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
227 $DB->update_record('forum_posts', $post);
228 $discussion->name = $forum->name;
229 $DB->update_record('forum_discussions', $discussion);
232 $DB->update_record('forum', $forum);
234 $modcontext = context_module::instance($forum->coursemodule);
235 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
236 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
237 foreach ($users as $user) {
238 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
242 forum_grade_item_update($forum);
249 * Given an ID of an instance of this module,
250 * this function will permanently delete the instance
251 * and any data that depends on it.
254 * @param int $id forum instance id
255 * @return bool success
257 function forum_delete_instance($id) {
260 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
263 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
266 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
270 $context = context_module::instance($cm->id);
272 // now get rid of all files
273 $fs = get_file_storage();
274 $fs->delete_area_files($context->id);
278 // Delete digest and subscription preferences.
279 $DB->delete_records('forum_digests', array('forum' => $forum->id));
280 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
281 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
283 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
284 foreach ($discussions as $discussion) {
285 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
291 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
293 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
297 forum_grade_item_delete($forum);
304 * Indicates API features that the forum supports.
306 * @uses FEATURE_GROUPS
307 * @uses FEATURE_GROUPINGS
308 * @uses FEATURE_MOD_INTRO
309 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
310 * @uses FEATURE_COMPLETION_HAS_RULES
311 * @uses FEATURE_GRADE_HAS_GRADE
312 * @uses FEATURE_GRADE_OUTCOMES
313 * @param string $feature
314 * @return mixed True if yes (some features may use other values)
316 function forum_supports($feature) {
318 case FEATURE_GROUPS: return true;
319 case FEATURE_GROUPINGS: return true;
320 case FEATURE_MOD_INTRO: return true;
321 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
322 case FEATURE_COMPLETION_HAS_RULES: return true;
323 case FEATURE_GRADE_HAS_GRADE: return true;
324 case FEATURE_GRADE_OUTCOMES: return true;
325 case FEATURE_RATE: return true;
326 case FEATURE_BACKUP_MOODLE2: return true;
327 case FEATURE_SHOW_DESCRIPTION: return true;
328 case FEATURE_PLAGIARISM: return true;
330 default: return null;
336 * Obtains the automatic completion state for this forum based on any conditions
341 * @param object $course Course
342 * @param object $cm Course-module
343 * @param int $userid User ID
344 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
345 * @return bool True if completed, false if not. (If no conditions, then return
346 * value depends on comparison type)
348 function forum_get_completion_state($course,$cm,$userid,$type) {
352 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
353 throw new Exception("Can't find forum {$cm->instance}");
356 $result=$type; // Default return value
358 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
364 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
366 fp.userid=:userid AND fd.forum=:forumid";
368 if ($forum->completiondiscussions) {
369 $value = $forum->completiondiscussions <=
370 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
371 if ($type == COMPLETION_AND) {
372 $result = $result && $value;
374 $result = $result || $value;
377 if ($forum->completionreplies) {
378 $value = $forum->completionreplies <=
379 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
380 if ($type==COMPLETION_AND) {
381 $result = $result && $value;
383 $result = $result || $value;
386 if ($forum->completionposts) {
387 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
388 if ($type == COMPLETION_AND) {
389 $result = $result && $value;
391 $result = $result || $value;
399 * Create a message-id string to use in the custom headers of forum notification emails
401 * message-id is used by email clients to identify emails and to nest conversations
403 * @param int $postid The ID of the forum post we are notifying the user about
404 * @param int $usertoid The ID of the user being notified
405 * @param string $hostname The server's hostname
406 * @return string A unique message-id
408 function forum_get_email_message_id($postid, $usertoid, $hostname) {
409 return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
413 * Removes properties from user record that are not necessary
414 * for sending post notifications.
415 * @param stdClass $user
416 * @return void, $user parameter is modified
418 function forum_cron_minimise_user_record(stdClass $user) {
420 // We store large amount of users in one huge array,
421 // make sure we do not store info there we do not actually need
422 // in mail generation code or messaging.
424 unset($user->institution);
425 unset($user->department);
426 unset($user->address);
429 unset($user->currentlogin);
430 unset($user->description);
431 unset($user->descriptionformat);
435 * Function to be run periodically according to the scheduled task.
437 * Finds all posts that have yet to be mailed out, and mails them
438 * out to all subscribers as well as other maintance tasks.
440 * NOTE: Since 2.7.2 this function is run by scheduled task rather
441 * than standard cron.
443 * @todo MDL-44734 The function will be split up into seperate tasks.
445 function forum_cron() {
446 global $CFG, $USER, $DB;
450 // All users that are subscribed to any post that needs sending,
451 // please increase $CFG->extramemorylimit on large sites that
452 // send notifications to a large number of users.
454 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
457 $mailcount = array();
458 $errorcount = array();
461 $discussions = array();
464 $coursemodules = array();
465 $subscribedusers = array();
466 $messageinboundhandlers = array();
468 // Posts older than 2 days will not be mailed. This is to avoid the problem where
469 // cron has not been running for a long time, and then suddenly people are flooded
470 // with mail from the past few weeks or months
472 $endtime = $timenow - $CFG->maxeditingtime;
473 $starttime = $endtime - 48 * 3600; // Two days earlier
475 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
476 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
478 foreach ($digestsset as $thisrow) {
479 if (!isset($digests[$thisrow->forum])) {
480 $digests[$thisrow->forum] = array();
482 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
484 $digestsset->close();
486 // Create the generic messageinboundgenerator.
487 $messageinboundgenerator = new \core\message\inbound\address_manager();
488 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
490 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
491 // Mark them all now as being mailed. It's unlikely but possible there
492 // might be an error later so that a post is NOT actually mailed out,
493 // but since mail isn't crucial, we can accept this risk. Doing it now
494 // prevents the risk of duplicated mails, which is a worse problem.
496 if (!forum_mark_old_posts_as_mailed($endtime)) {
497 mtrace('Errors occurred while trying to mark some posts as being mailed.');
498 return false; // Don't continue trying to mail them, in case we are in a cron loop
501 // checking post validity, and adding users to loop through later
502 foreach ($posts as $pid => $post) {
504 $discussionid = $post->discussion;
505 if (!isset($discussions[$discussionid])) {
506 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
507 $discussions[$discussionid] = $discussion;
508 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
509 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
512 mtrace('Could not find discussion ' . $discussionid);
517 $forumid = $discussions[$discussionid]->forum;
518 if (!isset($forums[$forumid])) {
519 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
520 $forums[$forumid] = $forum;
522 mtrace('Could not find forum '.$forumid);
527 $courseid = $forums[$forumid]->course;
528 if (!isset($courses[$courseid])) {
529 if ($course = $DB->get_record('course', array('id' => $courseid))) {
530 $courses[$courseid] = $course;
532 mtrace('Could not find course '.$courseid);
537 if (!isset($coursemodules[$forumid])) {
538 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
539 $coursemodules[$forumid] = $cm;
541 mtrace('Could not find course module for forum '.$forumid);
547 // Save the Inbound Message datakey here to reduce DB queries later.
548 $messageinboundgenerator->set_data($pid);
549 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
551 // Caching subscribed users of each forum.
552 if (!isset($subscribedusers[$forumid])) {
553 $modcontext = context_module::instance($coursemodules[$forumid]->id);
554 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
556 foreach ($subusers as $postuser) {
557 // this user is subscribed to this forum
558 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
560 if ($userscount > FORUM_CRON_USER_CACHE) {
561 // Store minimal user info.
562 $minuser = new stdClass();
563 $minuser->id = $postuser->id;
564 $users[$postuser->id] = $minuser;
566 // Cache full user record.
567 forum_cron_minimise_user_record($postuser);
568 $users[$postuser->id] = $postuser;
576 $mailcount[$pid] = 0;
577 $errorcount[$pid] = 0;
581 if ($users && $posts) {
583 $urlinfo = parse_url($CFG->wwwroot);
584 $hostname = $urlinfo['host'];
586 foreach ($users as $userto) {
587 // Terminate if processing of any account takes longer than 2 minutes.
588 core_php_time_limit::raise(120);
590 mtrace('Processing user ' . $userto->id);
592 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
593 if (isset($userto->username)) {
594 $userto = clone($userto);
596 $userto = $DB->get_record('user', array('id' => $userto->id));
597 forum_cron_minimise_user_record($userto);
599 $userto->viewfullnames = array();
600 $userto->canpost = array();
601 $userto->markposts = array();
603 // Setup this user so that the capabilities are cached, and environment matches receiving user.
604 cron_setup_user($userto);
607 foreach ($coursemodules as $forumid => $unused) {
608 $coursemodules[$forumid]->cache = new stdClass();
609 $coursemodules[$forumid]->cache->caps = array();
610 unset($coursemodules[$forumid]->uservisible);
613 foreach ($posts as $pid => $post) {
614 $discussion = $discussions[$post->discussion];
615 $forum = $forums[$discussion->forum];
616 $course = $courses[$forum->course];
617 $cm =& $coursemodules[$forum->id];
619 // Do some checks to see if we can bail out now.
621 // Only active enrolled users are in the list of subscribers.
622 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
623 if (!isset($subscribedusers[$forum->id][$userto->id])) {
624 // The user does not subscribe to this forum.
628 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
629 // The user does not subscribe to this forum, or to this specific discussion.
633 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
634 // Skip posts if the user subscribed to the discussion after it was created.
635 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
640 // Don't send email if the forum is Q&A and the user has not posted.
641 // Initial topics are still mailed.
642 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
643 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
647 // Get info about the sending user.
648 if (array_key_exists($post->userid, $users)) {
649 // We might know the user already.
650 $userfrom = $users[$post->userid];
651 if (!isset($userfrom->idnumber)) {
652 // Minimalised user info, fetch full record.
653 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
654 forum_cron_minimise_user_record($userfrom);
657 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
658 forum_cron_minimise_user_record($userfrom);
659 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
660 if ($userscount <= FORUM_CRON_USER_CACHE) {
662 $users[$userfrom->id] = $userfrom;
665 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
669 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
671 // Setup global $COURSE properly - needed for roles and languages.
672 cron_setup_user($userto, $course);
675 if (!isset($userto->viewfullnames[$forum->id])) {
676 $modcontext = context_module::instance($cm->id);
677 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
679 if (!isset($userto->canpost[$discussion->id])) {
680 $modcontext = context_module::instance($cm->id);
681 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
683 if (!isset($userfrom->groups[$forum->id])) {
684 if (!isset($userfrom->groups)) {
685 $userfrom->groups = array();
686 if (isset($users[$userfrom->id])) {
687 $users[$userfrom->id]->groups = array();
690 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
691 if (isset($users[$userfrom->id])) {
692 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
696 // Make sure groups allow this user to see this email.
697 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
698 // Groups are being used.
699 if (!groups_group_exists($discussion->groupid)) {
700 // Can't find group - be safe and don't this message.
704 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
705 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
710 // Make sure we're allowed to see the post.
711 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
712 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
716 // OK so we need to send the email.
718 // Does the user want this post in a digest? If so postpone it for now.
719 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
721 if ($maildigest > 0) {
722 // This user wants the mails to be in digest form.
723 $queue = new stdClass();
724 $queue->userid = $userto->id;
725 $queue->discussionid = $discussion->id;
726 $queue->postid = $post->id;
727 $queue->timemodified = $post->created;
728 $DB->insert_record('forum_queue', $queue);
732 // Prepare to actually send the post now, and build up the content.
734 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
736 $userfrom->customheaders = array (
737 // Headers to make emails easier to track.
738 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id . '@' . $hostname.'>',
739 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
740 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id, $hostname),
741 'X-Course-Id: ' . $course->id,
742 'X-Course-Name: ' . format_string($course->fullname, true),
744 // Headers to help prevent auto-responders.
746 'X-Auto-Response-Suppress: All',
747 'Auto-Submitted: auto-generated',
751 // This post is a reply, so add headers for threading (see MDL-22551).
752 $userfrom->customheaders[] = 'In-Reply-To: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
753 $userfrom->customheaders[] = 'References: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
756 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
758 // Generate a reply-to address from using the Inbound Message handler.
759 $replyaddress = null;
760 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
761 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
762 $replyaddress = $messageinboundgenerator->generate($userto->id);
766 $a->courseshortname = $shortname;
767 $a->forumname = $cleanforumname;
768 $a->subject = format_string($post->subject, true);
769 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
770 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false,
772 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
775 // Send the post now!
776 mtrace('Sending ', '');
778 $eventdata = new \core\message\message();
779 $eventdata->component = 'mod_forum';
780 $eventdata->name = 'posts';
781 $eventdata->userfrom = $userfrom;
782 $eventdata->userto = $userto;
783 $eventdata->subject = $postsubject;
784 $eventdata->fullmessage = $posttext;
785 $eventdata->fullmessageformat = FORMAT_PLAIN;
786 $eventdata->fullmessagehtml = $posthtml;
787 $eventdata->notification = 1;
788 $eventdata->replyto = $replyaddress;
789 if (!empty($replyaddress)) {
790 // Add extra text to email messages if they can reply back.
791 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
792 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
793 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
794 'fullmessagehtml' => array('footer' => $htmlfooter));
795 $eventdata->set_additional_content('email', $additionalcontent);
798 // If forum_replytouser is not set then send mail using the noreplyaddress.
799 if (empty($CFG->forum_replytouser)) {
800 $eventdata->userfrom = core_user::get_noreply_user();
803 $smallmessagestrings = new stdClass();
804 $smallmessagestrings->user = fullname($userfrom);
805 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
806 $smallmessagestrings->message = $post->message;
808 // Make sure strings are in message recipients language.
809 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
811 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
812 $eventdata->contexturl = $contexturl->out();
813 $eventdata->contexturlname = $discussion->name;
815 $mailresult = message_send($eventdata);
817 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
818 " ($userto->email) .. not trying again.");
819 $errorcount[$post->id]++;
821 $mailcount[$post->id]++;
823 // Mark post as read if forum_usermarksread is set off.
824 if (!$CFG->forum_usermarksread) {
825 $userto->markposts[$post->id] = $post->id;
829 mtrace('post ' . $post->id . ': ' . $post->subject);
832 // Mark processed posts as read.
833 forum_tp_mark_posts_read($userto, $userto->markposts);
839 foreach ($posts as $post) {
840 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
841 if ($errorcount[$post->id]) {
842 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
847 // release some memory
848 unset($subscribedusers);
854 $sitetimezone = core_date::get_server_timezone();
856 // Now see if there are any digest mails waiting to be sent, and if we should send them
858 mtrace('Starting digest processing...');
860 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
862 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
863 set_config('digestmailtimelast', 0);
867 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
869 // Delete any really old ones (normally there shouldn't be any)
870 $weekago = $timenow - (7 * 24 * 3600);
871 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
872 mtrace ('Cleaned old digest records');
874 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
876 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
878 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
880 if ($digestposts_rs->valid()) {
882 // We have work to do
885 //caches - reuse the those filled before too
886 $discussionposts = array();
887 $userdiscussions = array();
889 foreach ($digestposts_rs as $digestpost) {
890 if (!isset($posts[$digestpost->postid])) {
891 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
892 $posts[$digestpost->postid] = $post;
897 $discussionid = $digestpost->discussionid;
898 if (!isset($discussions[$discussionid])) {
899 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
900 $discussions[$discussionid] = $discussion;
905 $forumid = $discussions[$discussionid]->forum;
906 if (!isset($forums[$forumid])) {
907 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
908 $forums[$forumid] = $forum;
914 $courseid = $forums[$forumid]->course;
915 if (!isset($courses[$courseid])) {
916 if ($course = $DB->get_record('course', array('id' => $courseid))) {
917 $courses[$courseid] = $course;
923 if (!isset($coursemodules[$forumid])) {
924 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
925 $coursemodules[$forumid] = $cm;
930 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
931 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
933 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
935 // Data collected, start sending out emails to each user
936 foreach ($userdiscussions as $userid => $thesediscussions) {
938 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
942 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
944 // First of all delete all the queue entries for this user
945 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
947 // Init user caches - we keep the cache for one cycle only,
948 // otherwise it would unnecessarily consume memory.
949 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
950 $userto = clone($users[$userid]);
952 $userto = $DB->get_record('user', array('id' => $userid));
953 forum_cron_minimise_user_record($userto);
955 $userto->viewfullnames = array();
956 $userto->canpost = array();
957 $userto->markposts = array();
959 // Override the language and timezone of the "current" user, so that
960 // mail is customised for the receiver.
961 cron_setup_user($userto);
963 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
965 $headerdata = new stdClass();
966 $headerdata->sitename = format_string($site->fullname, true);
967 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&course='.$site->id;
969 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
970 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
972 $posthtml = "<head>";
973 /* foreach ($CFG->stylesheets as $stylesheet) {
975 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
977 $posthtml .= "</head>\n<body id=\"email\">\n";
978 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
980 foreach ($thesediscussions as $discussionid) {
982 core_php_time_limit::raise(120); // to be reset for each post
984 $discussion = $discussions[$discussionid];
985 $forum = $forums[$discussion->forum];
986 $course = $courses[$forum->course];
987 $cm = $coursemodules[$forum->id];
990 cron_setup_user($userto, $course);
993 if (!isset($userto->viewfullnames[$forum->id])) {
994 $modcontext = context_module::instance($cm->id);
995 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
997 if (!isset($userto->canpost[$discussion->id])) {
998 $modcontext = context_module::instance($cm->id);
999 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1002 $strforums = get_string('forums', 'forum');
1003 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1004 $canreply = $userto->canpost[$discussion->id];
1005 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1007 $posttext .= "\n \n";
1008 $posttext .= '=====================================================================';
1009 $posttext .= "\n \n";
1010 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1011 if ($discussion->name != $forum->name) {
1012 $posttext .= " -> ".format_string($discussion->name,true);
1015 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1018 $posthtml .= "<p><font face=\"sans-serif\">".
1019 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1020 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1021 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
1022 if ($discussion->name == $forum->name) {
1023 $posthtml .= "</font></p>";
1025 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
1029 $postsarray = $discussionposts[$discussionid];
1032 foreach ($postsarray as $postid) {
1033 $post = $posts[$postid];
1035 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1036 $userfrom = $users[$post->userid];
1037 if (!isset($userfrom->idnumber)) {
1038 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1039 forum_cron_minimise_user_record($userfrom);
1042 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1043 forum_cron_minimise_user_record($userfrom);
1044 if ($userscount <= FORUM_CRON_USER_CACHE) {
1046 $users[$userfrom->id] = $userfrom;
1050 mtrace('Could not find user '.$post->userid);
1054 if (!isset($userfrom->groups[$forum->id])) {
1055 if (!isset($userfrom->groups)) {
1056 $userfrom->groups = array();
1057 if (isset($users[$userfrom->id])) {
1058 $users[$userfrom->id]->groups = array();
1061 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1062 if (isset($users[$userfrom->id])) {
1063 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1067 // Headers to help prevent auto-responders.
1068 $userfrom->customheaders = array(
1070 'X-Auto-Response-Suppress: All',
1071 'Auto-Submitted: auto-generated',
1074 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1075 if ($maildigest == 2) {
1076 // Subjects and link only
1078 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1079 $by = new stdClass();
1080 $by->name = fullname($userfrom);
1081 $by->date = userdate($post->modified);
1082 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
1083 $posttext .= "\n---------------------------------------------------------------------";
1085 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&course=$course->id\">$by->name</a>";
1086 $posthtml .= '<div><a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'#p'.$post->id.'">'.format_string($post->subject,true).'</a> '.get_string("bynameondate", "forum", $by).'</div>';
1089 // The full treatment
1090 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
1091 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1093 // Create an array of postid's for this user to mark as read.
1094 if (!$CFG->forum_usermarksread) {
1095 $userto->markposts[$post->id] = $post->id;
1099 $footerlinks = array();
1100 if ($canunsubscribe) {
1101 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1103 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1105 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1106 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1107 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1109 $posthtml .= '</body>';
1111 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1112 // This user DOESN'T want to receive HTML
1116 $attachment = $attachname='';
1117 // Directly email forum digests rather than sending them via messaging, use the
1118 // site shortname as 'from name', the noreply address will be used by email_to_user.
1119 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);
1122 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1123 "($userto->email)... not trying again.");
1128 // Mark post as read if forum_usermarksread is set off
1129 forum_tp_mark_posts_read($userto, $userto->markposts);
1133 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1134 set_config('digestmailtimelast', $timenow);
1139 if (!empty($usermailcount)) {
1140 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1143 if (!empty($CFG->forum_lastreadclean)) {
1145 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1146 set_config('forum_lastreadclean', $timenow);
1147 mtrace('Removing old forum read tracking info...');
1148 forum_tp_clean_read_records();
1151 set_config('forum_lastreadclean', time());
1158 * Builds and returns the body of the email notification in plain text.
1162 * @uses CONTEXT_MODULE
1163 * @param object $course
1165 * @param object $forum
1166 * @param object $discussion
1167 * @param object $post
1168 * @param object $userfrom
1169 * @param object $userto
1170 * @param boolean $bare
1171 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1172 * @return string The email body in plain text format.
1174 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false, $replyaddress = null) {
1177 $modcontext = context_module::instance($cm->id);
1179 if (!isset($userto->viewfullnames[$forum->id])) {
1180 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1182 $viewfullnames = $userto->viewfullnames[$forum->id];
1185 if (!isset($userto->canpost[$discussion->id])) {
1186 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1188 $canreply = $userto->canpost[$discussion->id];
1192 $by->name = fullname($userfrom, $viewfullnames);
1193 $by->date = userdate($post->modified, "", core_date::get_user_timezone($userto));
1195 $strbynameondate = get_string('bynameondate', 'forum', $by);
1197 $strforums = get_string('forums', 'forum');
1199 $canunsubscribe = !\mod_forum\subscriptions::is_forcesubscribed($forum);
1204 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1205 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1207 if ($discussion->name != $forum->name) {
1208 $posttext .= " -> ".format_string($discussion->name,true);
1212 // add absolute file links
1213 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1216 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1217 $posttext .= format_string($post->subject,true);
1219 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1221 $posttext .= "\n".$strbynameondate."\n";
1222 $posttext .= "---------------------------------------------------------------------\n";
1223 $posttext .= format_text_email($post->message, $post->messageformat);
1224 $posttext .= "\n\n";
1225 $posttext .= forum_print_attachments($post, $cm, "text");
1226 $posttext .= "\n---------------------------------------------------------------------\n";
1230 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1231 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1234 if ($canunsubscribe) {
1235 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1236 // If subscribed to this forum, offer the unsubscribe link.
1237 $posttext .= get_string("unsubscribe", "forum");
1238 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1240 // Always offer the unsubscribe from discussion link.
1241 $posttext .= get_string("unsubscribediscussion", "forum");
1242 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id&d=$discussion->id\n";
1246 $posttext .= get_string("digestmailpost", "forum");
1247 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1253 * Builds and returns the body of the email notification in html format.
1256 * @param object $course
1258 * @param object $forum
1259 * @param object $discussion
1260 * @param object $post
1261 * @param object $userfrom
1262 * @param object $userto
1263 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1264 * @return string The email text in HTML format
1266 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $replyaddress = null) {
1269 if ($userto->mailformat != 1) { // Needs to be HTML
1273 if (!isset($userto->canpost[$discussion->id])) {
1274 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1276 $canreply = $userto->canpost[$discussion->id];
1279 $strforums = get_string('forums', 'forum');
1280 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1281 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1283 $posthtml = '<head>';
1284 /* foreach ($CFG->stylesheets as $stylesheet) {
1286 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1288 $posthtml .= '</head>';
1289 $posthtml .= "\n<body id=\"email\">\n\n";
1291 $posthtml .= '<div class="navbar">'.
1292 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$shortname.'</a> » '.
1293 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> » '.
1294 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1295 if ($discussion->name == $forum->name) {
1296 $posthtml .= '</div>';
1298 $posthtml .= ' » <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1299 format_string($discussion->name,true).'</a></div>';
1301 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1303 $footerlinks = array();
1304 if ($canunsubscribe) {
1305 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1306 // If subscribed to this forum, offer the unsubscribe link.
1307 $unsublink = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id));
1308 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribe', 'mod_forum'));
1310 // Always offer the unsubscribe from discussion link.
1311 $unsublink = new moodle_url('/mod/forum/subscribe.php', array(
1313 'd' => $discussion->id,
1315 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribediscussion', 'mod_forum'));
1317 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
1319 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1320 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode(' ', $footerlinks) . '</div>';
1322 $posthtml .= '</body>';
1330 * @param object $course
1331 * @param object $user
1332 * @param object $mod TODO this is not used in this function, refactor
1333 * @param object $forum
1334 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1336 function forum_user_outline($course, $user, $mod, $forum) {
1338 require_once("$CFG->libdir/gradelib.php");
1339 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1340 if (empty($grades->items[0]->grades)) {
1343 $grade = reset($grades->items[0]->grades);
1346 $count = forum_count_user_posts($forum->id, $user->id);
1348 if ($count && $count->postcount > 0) {
1349 $result = new stdClass();
1350 $result->info = get_string("numposts", "forum", $count->postcount);
1351 $result->time = $count->lastpost;
1353 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1356 } else if ($grade) {
1357 $result = new stdClass();
1358 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1360 //datesubmitted == time created. dategraded == time modified or time overridden
1361 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1362 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1363 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1364 $result->time = $grade->dategraded;
1366 $result->time = $grade->datesubmitted;
1378 * @param object $coure
1379 * @param object $user
1380 * @param object $mod
1381 * @param object $forum
1383 function forum_user_complete($course, $user, $mod, $forum) {
1384 global $CFG,$USER, $OUTPUT;
1385 require_once("$CFG->libdir/gradelib.php");
1387 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1388 if (!empty($grades->items[0]->grades)) {
1389 $grade = reset($grades->items[0]->grades);
1390 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1391 if ($grade->str_feedback) {
1392 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1396 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1398 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1399 print_error('invalidcoursemodule');
1401 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1403 foreach ($posts as $post) {
1404 if (!isset($discussions[$post->discussion])) {
1407 $discussion = $discussions[$post->discussion];
1409 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1412 echo "<p>".get_string("noposts", "forum")."</p>";
1417 * Filters the forum discussions according to groups membership and config.
1419 * @since Moodle 2.8, 2.7.1, 2.6.4
1420 * @param array $discussions Discussions with new posts array
1421 * @return array Forums with the number of new posts
1423 function forum_filter_user_groups_discussions($discussions) {
1425 // Group the remaining discussions posts by their forumid.
1426 $filteredforums = array();
1428 // Discard not visible groups.
1429 foreach ($discussions as $discussion) {
1431 // Course data is already cached.
1432 $instances = get_fast_modinfo($discussion->course)->get_instances();
1433 $forum = $instances['forum'][$discussion->forum];
1435 // Continue if the user should not see this discussion.
1436 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1440 // Grouping results by forum.
1441 if (empty($filteredforums[$forum->instance])) {
1442 $filteredforums[$forum->instance] = new stdClass();
1443 $filteredforums[$forum->instance]->id = $forum->id;
1444 $filteredforums[$forum->instance]->count = 0;
1446 $filteredforums[$forum->instance]->count += $discussion->count;
1450 return $filteredforums;
1454 * Returns whether the discussion group is visible by the current user or not.
1456 * @since Moodle 2.8, 2.7.1, 2.6.4
1457 * @param cm_info $cm The discussion course module
1458 * @param int $discussiongroupid The discussion groupid
1461 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1463 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1467 if (isguestuser()) {
1471 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1472 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1483 * @param array $courses
1484 * @param array $htmlarray
1486 function forum_print_overview($courses,&$htmlarray) {
1487 global $USER, $CFG, $DB, $SESSION;
1489 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1493 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1497 // Courses to search for new posts
1498 $coursessqls = array();
1500 foreach ($courses as $course) {
1502 // If the user has never entered into the course all posts are pending
1503 if ($course->lastaccess == 0) {
1504 $coursessqls[] = '(d.course = ?)';
1505 $params[] = $course->id;
1507 // Only posts created after the course last access
1509 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1510 $params[] = $course->id;
1511 $params[] = $course->lastaccess;
1514 $params[] = $USER->id;
1515 $coursessql = implode(' OR ', $coursessqls);
1517 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1518 .'FROM {forum_discussions} d '
1519 .'JOIN {forum_posts} p ON p.discussion = d.id '
1520 ."WHERE ($coursessql) "
1521 .'AND p.userid != ? '
1522 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1523 .'ORDER BY d.course, d.forum';
1526 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1527 $discussions = array();
1530 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1532 // also get all forum tracking stuff ONCE.
1533 $trackingforums = array();
1534 foreach ($forums as $forum) {
1535 if (forum_tp_can_track_forums($forum)) {
1536 $trackingforums[$forum->id] = $forum;
1540 if (count($trackingforums) > 0) {
1541 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1542 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1543 ' FROM {forum_posts} p '.
1544 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1545 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1546 $params = array($USER->id);
1548 foreach ($trackingforums as $track) {
1549 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1550 $params[] = $track->id;
1551 if (isset($SESSION->currentgroup[$track->course])) {
1552 $groupid = $SESSION->currentgroup[$track->course];
1554 // get first groupid
1555 $groupids = groups_get_all_groups($track->course, $USER->id);
1558 $groupid = key($groupids);
1559 $SESSION->currentgroup[$track->course] = $groupid;
1565 $params[] = $groupid;
1567 $sql = substr($sql,0,-3); // take off the last OR
1568 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1569 $params[] = $cutoffdate;
1571 if (!$unread = $DB->get_records_sql($sql, $params)) {
1578 if (empty($unread) and empty($forumsnewposts)) {
1582 $strforum = get_string('modulename','forum');
1584 foreach ($forums as $forum) {
1588 $showunread = false;
1589 // either we have something from logs, or trackposts, or nothing.
1590 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1591 $count = $forumsnewposts[$forum->id]->count;
1593 if (array_key_exists($forum->id,$unread)) {
1594 $thisunread = $unread[$forum->id]->count;
1597 if ($count > 0 || $thisunread > 0) {
1598 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1599 $forum->name.'</a></div>';
1600 $str .= '<div class="info"><span class="postsincelogin">';
1601 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1602 if (!empty($showunread)) {
1603 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1605 $str .= '</div></div>';
1608 if (!array_key_exists($forum->course,$htmlarray)) {
1609 $htmlarray[$forum->course] = array();
1611 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1612 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1614 $htmlarray[$forum->course]['forum'] .= $str;
1620 * Given a course and a date, prints a summary of all the new
1621 * messages posted in the course since that date
1626 * @uses CONTEXT_MODULE
1627 * @uses VISIBLEGROUPS
1628 * @param object $course
1629 * @param bool $viewfullnames capability
1630 * @param int $timestart
1631 * @return bool success
1633 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1634 global $CFG, $USER, $DB, $OUTPUT;
1636 // do not use log table if possible, it may be huge and is expensive to join with other tables
1638 $allnamefields = user_picture::fields('u', null, 'duserid');
1639 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1640 d.timestart, d.timeend, $allnamefields
1641 FROM {forum_posts} p
1642 JOIN {forum_discussions} d ON d.id = p.discussion
1643 JOIN {forum} f ON f.id = d.forum
1644 JOIN {user} u ON u.id = p.userid
1645 WHERE p.created > ? AND f.course = ?
1646 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1650 $modinfo = get_fast_modinfo($course);
1652 $groupmodes = array();
1655 $strftimerecent = get_string('strftimerecent');
1657 $printposts = array();
1658 foreach ($posts as $post) {
1659 if (!isset($modinfo->instances['forum'][$post->forum])) {
1663 $cm = $modinfo->instances['forum'][$post->forum];
1664 if (!$cm->uservisible) {
1667 $context = context_module::instance($cm->id);
1669 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1673 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1674 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1675 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1680 // Check that the user can see the discussion.
1681 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1682 $printposts[] = $post;
1692 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1693 echo "\n<ul class='unlist'>\n";
1695 foreach ($printposts as $post) {
1696 $subjectclass = empty($post->parent) ? ' bold' : '';
1698 echo '<li><div class="head">'.
1699 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1700 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1702 echo '<div class="info'.$subjectclass.'">';
1703 if (empty($post->parent)) {
1704 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1706 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&parent='.$post->parent.'#p'.$post->id.'">';
1708 $post->subject = break_up_long_words(format_string($post->subject, true));
1709 echo $post->subject;
1710 echo "</a>\"</div></li>\n";
1719 * Return grade for given user or all users.
1723 * @param object $forum
1724 * @param int $userid optional user id, 0 means all users
1725 * @return array array of grades, false if none
1727 function forum_get_user_grades($forum, $userid = 0) {
1730 require_once($CFG->dirroot.'/rating/lib.php');
1732 $ratingoptions = new stdClass;
1733 $ratingoptions->component = 'mod_forum';
1734 $ratingoptions->ratingarea = 'post';
1736 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1737 $ratingoptions->modulename = 'forum';
1738 $ratingoptions->moduleid = $forum->id;
1739 $ratingoptions->userid = $userid;
1740 $ratingoptions->aggregationmethod = $forum->assessed;
1741 $ratingoptions->scaleid = $forum->scale;
1742 $ratingoptions->itemtable = 'forum_posts';
1743 $ratingoptions->itemtableusercolumn = 'userid';
1745 $rm = new rating_manager();
1746 return $rm->get_user_grades($ratingoptions);
1750 * Update activity grades
1753 * @param object $forum
1754 * @param int $userid specific user only, 0 means all
1755 * @param boolean $nullifnone return null if grade does not exist
1758 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1760 require_once($CFG->libdir.'/gradelib.php');
1762 if (!$forum->assessed) {
1763 forum_grade_item_update($forum);
1765 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1766 forum_grade_item_update($forum, $grades);
1768 } else if ($userid and $nullifnone) {
1769 $grade = new stdClass();
1770 $grade->userid = $userid;
1771 $grade->rawgrade = NULL;
1772 forum_grade_item_update($forum, $grade);
1775 forum_grade_item_update($forum);
1780 * Create/update grade item for given forum
1783 * @uses GRADE_TYPE_NONE
1784 * @uses GRADE_TYPE_VALUE
1785 * @uses GRADE_TYPE_SCALE
1786 * @param stdClass $forum Forum object with extra cmidnumber
1787 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1788 * @return int 0 if ok
1790 function forum_grade_item_update($forum, $grades=NULL) {
1792 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1793 require_once($CFG->libdir.'/gradelib.php');
1796 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1798 if (!$forum->assessed or $forum->scale == 0) {
1799 $params['gradetype'] = GRADE_TYPE_NONE;
1801 } else if ($forum->scale > 0) {
1802 $params['gradetype'] = GRADE_TYPE_VALUE;
1803 $params['grademax'] = $forum->scale;
1804 $params['grademin'] = 0;
1806 } else if ($forum->scale < 0) {
1807 $params['gradetype'] = GRADE_TYPE_SCALE;
1808 $params['scaleid'] = -$forum->scale;
1811 if ($grades === 'reset') {
1812 $params['reset'] = true;
1816 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1820 * Delete grade item for given forum
1823 * @param stdClass $forum Forum object
1824 * @return grade_item
1826 function forum_grade_item_delete($forum) {
1828 require_once($CFG->libdir.'/gradelib.php');
1830 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1835 * This function returns if a scale is being used by one forum
1838 * @param int $forumid
1839 * @param int $scaleid negative number
1842 function forum_scale_used ($forumid,$scaleid) {
1846 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1848 if (!empty($rec) && !empty($scaleid)) {
1856 * Checks if scale is being used by any instance of forum
1858 * This is used to find out if scale used anywhere
1861 * @param $scaleid int
1862 * @return boolean True if the scale is used by any forum
1864 function forum_scale_used_anywhere($scaleid) {
1866 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1873 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1876 * Gets a post with all info ready for forum_print_post
1877 * Most of these joins are just to get the forum id
1881 * @param int $postid
1882 * @return mixed array of posts or false
1884 function forum_get_post_full($postid) {
1887 $allnames = get_all_user_name_fields(true, 'u');
1888 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1889 FROM {forum_posts} p
1890 JOIN {forum_discussions} d ON p.discussion = d.id
1891 LEFT JOIN {user} u ON p.userid = u.id
1892 WHERE p.id = ?", array($postid));
1896 * Gets all posts in discussion including top parent.
1901 * @param int $discussionid
1902 * @param string $sort
1903 * @param bool $tracking does user track the forum?
1904 * @return array of posts
1906 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1907 global $CFG, $DB, $USER;
1915 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1916 $tr_sel = ", fr.id AS postread";
1917 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1918 $params[] = $USER->id;
1921 $allnames = get_all_user_name_fields(true, 'u');
1922 $params[] = $discussionid;
1923 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1924 FROM {forum_posts} p
1925 LEFT JOIN {user} u ON p.userid = u.id
1927 WHERE p.discussion = ?
1928 ORDER BY $sort", $params)) {
1932 foreach ($posts as $pid=>$p) {
1934 if (forum_tp_is_post_old($p)) {
1935 $posts[$pid]->postread = true;
1941 if (!isset($posts[$p->parent])) {
1942 continue; // parent does not exist??
1944 if (!isset($posts[$p->parent]->children)) {
1945 $posts[$p->parent]->children = array();
1947 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1950 // Start with the last child of the first post.
1951 $post = &$posts[reset($posts)->id];
1954 while (!$lastpost) {
1955 if (!isset($post->children)) {
1956 $post->lastpost = true;
1959 // Go to the last child of this post.
1960 $post = &$posts[end($post->children)->id];
1968 * An array of forum objects that the user is allowed to read/search through.
1973 * @param int $userid
1974 * @param int $courseid if 0, we look for forums throughout the whole site.
1975 * @return array of forum objects, or false if no matches
1976 * Forum objects have the following attributes:
1977 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1978 * viewhiddentimedposts
1980 function forum_get_readable_forums($userid, $courseid=0) {
1982 global $CFG, $DB, $USER;
1983 require_once($CFG->dirroot.'/course/lib.php');
1985 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1986 print_error('notinstalled', 'forum');
1990 $courses = $DB->get_records('course', array('id' => $courseid));
1992 // If no course is specified, then the user can see SITE + his courses.
1993 $courses1 = $DB->get_records('course', array('id' => SITEID));
1994 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1995 $courses = array_merge($courses1, $courses2);
2001 $readableforums = array();
2003 foreach ($courses as $course) {
2005 $modinfo = get_fast_modinfo($course);
2007 if (empty($modinfo->instances['forum'])) {
2012 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2014 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
2015 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
2018 $context = context_module::instance($cm->id);
2019 $forum = $courseforums[$forumid];
2020 $forum->context = $context;
2023 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2028 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2030 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
2031 $forum->onlygroups[] = -1;
2034 /// hidden timed discussions
2035 $forum->viewhiddentimedposts = true;
2036 if (!empty($CFG->forum_enabletimedposts)) {
2037 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
2038 $forum->viewhiddentimedposts = false;
2043 if ($forum->type == 'qanda'
2044 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2046 // We need to check whether the user has posted in the qanda forum.
2047 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
2048 // the user is allowed to see in this forum.
2049 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
2050 foreach ($discussionspostedin as $d) {
2051 $forum->onlydiscussions[] = $d->id;
2056 $readableforums[$forum->id] = $forum;
2061 } // End foreach $courses
2063 return $readableforums;
2067 * Returns a list of posts found using an array of search terms.
2072 * @param array $searchterms array of search terms, e.g. word +word -word
2073 * @param int $courseid if 0, we search through the whole site
2074 * @param int $limitfrom
2075 * @param int $limitnum
2076 * @param int &$totalcount
2077 * @param string $extrasql
2078 * @return array|bool Array of posts found or false
2080 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2081 &$totalcount, $extrasql='') {
2082 global $CFG, $DB, $USER;
2083 require_once($CFG->libdir.'/searchlib.php');
2085 $forums = forum_get_readable_forums($USER->id, $courseid);
2087 if (count($forums) == 0) {
2092 $now = round(time(), -2); // db friendly
2094 $fullaccess = array();
2098 foreach ($forums as $forumid => $forum) {
2101 if (!$forum->viewhiddentimedposts) {
2102 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2103 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2107 $context = $forum->context;
2109 if ($forum->type == 'qanda'
2110 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2111 if (!empty($forum->onlydiscussions)) {
2112 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2113 $params = array_merge($params, $discussionid_params);
2114 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2116 $select[] = "p.parent = 0";
2120 if (!empty($forum->onlygroups)) {
2121 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2122 $params = array_merge($params, $groupid_params);
2123 $select[] = "d.groupid $groupid_sql";
2127 $selects = implode(" AND ", $select);
2128 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2129 $params['forum'.$forumid] = $forumid;
2131 $fullaccess[] = $forumid;
2136 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2137 $params = array_merge($params, $fullid_params);
2138 $where[] = "(d.forum $fullid_sql)";
2141 $selectdiscussion = "(".implode(" OR ", $where).")";
2143 $messagesearch = '';
2146 // Need to concat these back together for parser to work.
2147 foreach($searchterms as $searchterm){
2148 if ($searchstring != '') {
2149 $searchstring .= ' ';
2151 $searchstring .= $searchterm;
2154 // We need to allow quoted strings for the search. The quotes *should* be stripped
2155 // by the parser, but this should be examined carefully for security implications.
2156 $searchstring = str_replace("\\\"","\"",$searchstring);
2157 $parser = new search_parser();
2158 $lexer = new search_lexer($parser);
2160 if ($lexer->parse($searchstring)) {
2161 $parsearray = $parser->get_parsed_array();
2162 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2163 'p.userid', 'u.id', 'u.firstname',
2164 'u.lastname', 'p.modified', 'd.forum');
2165 $params = array_merge($params, $msparams);
2168 $fromsql = "{forum_posts} p,
2169 {forum_discussions} d,
2172 $selectsql = " $messagesearch
2173 AND p.discussion = d.id
2175 AND $selectdiscussion
2178 $countsql = "SELECT COUNT(*)
2182 $allnames = get_all_user_name_fields(true, 'u');
2183 $searchsql = "SELECT p.*,
2191 ORDER BY p.modified DESC";
2193 $totalcount = $DB->count_records_sql($countsql, $params);
2195 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2199 * Returns a list of all new posts that have not been mailed yet
2201 * @param int $starttime posts created after this time
2202 * @param int $endtime posts created before this
2203 * @param int $now used for timed discussions only
2206 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2210 $params['mailed'] = FORUM_MAILED_PENDING;
2211 $params['ptimestart'] = $starttime;
2212 $params['ptimeend'] = $endtime;
2213 $params['mailnow'] = 1;
2215 if (!empty($CFG->forum_enabletimedposts)) {
2219 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2220 $params['dtimestart'] = $now;
2221 $params['dtimeend'] = $now;
2226 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2227 FROM {forum_posts} p
2228 JOIN {forum_discussions} d ON d.id = p.discussion
2229 WHERE p.mailed = :mailed
2230 AND p.created >= :ptimestart
2231 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2233 ORDER BY p.modified ASC", $params);
2237 * Marks posts before a certain time as being mailed already
2241 * @param int $endtime
2242 * @param int $now Defaults to time()
2245 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2253 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2254 $params['now'] = $now;
2255 $params['endtime'] = $endtime;
2256 $params['mailnow'] = 1;
2257 $params['mailedpending'] = FORUM_MAILED_PENDING;
2259 if (empty($CFG->forum_enabletimedposts)) {
2260 return $DB->execute("UPDATE {forum_posts}
2261 SET mailed = :mailedsuccess
2262 WHERE (created < :endtime OR mailnow = :mailnow)
2263 AND mailed = :mailedpending", $params);
2265 return $DB->execute("UPDATE {forum_posts}
2266 SET mailed = :mailedsuccess
2267 WHERE discussion NOT IN (SELECT d.id
2268 FROM {forum_discussions} d
2269 WHERE d.timestart > :now)
2270 AND (created < :endtime OR mailnow = :mailnow)
2271 AND mailed = :mailedpending", $params);
2276 * Get all the posts for a user in a forum suitable for forum_print_post
2280 * @uses CONTEXT_MODULE
2283 function forum_get_user_posts($forumid, $userid) {
2287 $params = array($forumid, $userid);
2289 if (!empty($CFG->forum_enabletimedposts)) {
2290 $cm = get_coursemodule_from_instance('forum', $forumid);
2291 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2293 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2299 $allnames = get_all_user_name_fields(true, 'u');
2300 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2302 JOIN {forum_discussions} d ON d.forum = f.id
2303 JOIN {forum_posts} p ON p.discussion = d.id
2304 JOIN {user} u ON u.id = p.userid
2308 ORDER BY p.modified ASC", $params);
2312 * Get all the discussions user participated in
2316 * @uses CONTEXT_MODULE
2317 * @param int $forumid
2318 * @param int $userid
2319 * @return array Array or false
2321 function forum_get_user_involved_discussions($forumid, $userid) {
2325 $params = array($forumid, $userid);
2326 if (!empty($CFG->forum_enabletimedposts)) {
2327 $cm = get_coursemodule_from_instance('forum', $forumid);
2328 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2330 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2336 return $DB->get_records_sql("SELECT DISTINCT d.*
2338 JOIN {forum_discussions} d ON d.forum = f.id
2339 JOIN {forum_posts} p ON p.discussion = d.id
2342 $timedsql", $params);
2346 * Get all the posts for a user in a forum suitable for forum_print_post
2350 * @param int $forumid
2351 * @param int $userid
2352 * @return array of counts or false
2354 function forum_count_user_posts($forumid, $userid) {
2358 $params = array($forumid, $userid);
2359 if (!empty($CFG->forum_enabletimedposts)) {
2360 $cm = get_coursemodule_from_instance('forum', $forumid);
2361 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2363 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2369 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2371 JOIN {forum_discussions} d ON d.forum = f.id
2372 JOIN {forum_posts} p ON p.discussion = d.id
2373 JOIN {user} u ON u.id = p.userid
2376 $timedsql", $params);
2380 * Given a log entry, return the forum post details for it.
2384 * @param object $log
2385 * @return array|null
2387 function forum_get_post_from_log($log) {
2390 $allnames = get_all_user_name_fields(true, 'u');
2391 if ($log->action == "add post") {
2393 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2394 FROM {forum_discussions} d,
2399 AND d.id = p.discussion
2401 AND u.deleted <> '1'
2402 AND f.id = d.forum", array($log->info));
2405 } else if ($log->action == "add discussion") {
2407 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2408 FROM {forum_discussions} d,
2413 AND d.firstpost = p.id
2415 AND u.deleted <> '1'
2416 AND f.id = d.forum", array($log->info));
2422 * Given a discussion id, return the first post from the discussion
2426 * @param int $dicsussionid
2429 function forum_get_firstpost_from_discussion($discussionid) {
2432 return $DB->get_record_sql("SELECT p.*
2433 FROM {forum_discussions} d,
2436 AND d.firstpost = p.id ", array($discussionid));
2440 * Returns an array of counts of replies to each discussion
2444 * @param int $forumid
2445 * @param string $forumsort
2448 * @param int $perpage
2451 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2457 } else if ($page != -1) {
2458 $limitfrom = $page*$perpage;
2459 $limitnum = $perpage;
2465 if ($forumsort == "") {
2470 $orderby = "ORDER BY $forumsort";
2471 $groupby = ", ".strtolower($forumsort);
2472 $groupby = str_replace('desc', '', $groupby);
2473 $groupby = str_replace('asc', '', $groupby);
2476 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2477 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2478 FROM {forum_posts} p
2479 JOIN {forum_discussions} d ON p.discussion = d.id
2480 WHERE p.parent > 0 AND d.forum = ?
2481 GROUP BY p.discussion";
2482 return $DB->get_records_sql($sql, array($forumid));
2485 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2486 FROM {forum_posts} p
2487 JOIN {forum_discussions} d ON p.discussion = d.id
2489 GROUP BY p.discussion $groupby $orderby";
2490 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2498 * @staticvar array $cache
2499 * @param object $forum
2501 * @param object $course
2504 function forum_count_discussions($forum, $cm, $course) {
2505 global $CFG, $DB, $USER;
2507 static $cache = array();
2509 $now = round(time(), -2); // db cache friendliness
2511 $params = array($course->id);
2513 if (!isset($cache[$course->id])) {
2514 if (!empty($CFG->forum_enabletimedposts)) {
2515 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2522 $sql = "SELECT f.id, COUNT(d.id) as dcount
2524 JOIN {forum_discussions} d ON d.forum = f.id
2529 if ($counts = $DB->get_records_sql($sql, $params)) {
2530 foreach ($counts as $count) {
2531 $counts[$count->id] = $count->dcount;
2533 $cache[$course->id] = $counts;
2535 $cache[$course->id] = array();
2539 if (empty($cache[$course->id][$forum->id])) {
2543 $groupmode = groups_get_activity_groupmode($cm, $course);
2545 if ($groupmode != SEPARATEGROUPS) {
2546 return $cache[$course->id][$forum->id];
2549 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2550 return $cache[$course->id][$forum->id];
2553 require_once($CFG->dirroot.'/course/lib.php');
2555 $modinfo = get_fast_modinfo($course);
2557 $mygroups = $modinfo->get_groups($cm->groupingid);
2559 // add all groups posts
2562 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2563 $params[] = $forum->id;
2565 if (!empty($CFG->forum_enabletimedposts)) {
2566 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2573 $sql = "SELECT COUNT(d.id)
2574 FROM {forum_discussions} d
2575 WHERE d.groupid $mygroups_sql AND d.forum = ?
2578 return $DB->get_field_sql($sql, $params);
2582 * Get all discussions in a forum
2587 * @uses CONTEXT_MODULE
2588 * @uses VISIBLEGROUPS
2590 * @param string $forumsort
2591 * @param bool $fullpost
2592 * @param int $unused
2594 * @param bool $userlastmodified
2596 * @param int $perpage
2599 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2600 global $CFG, $DB, $USER;
2604 $now = round(time(), -2);
2605 $params = array($cm->instance);
2607 $modcontext = context_module::instance($cm->id);
2609 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2613 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2615 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2616 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2620 $timelimit .= " OR d.userid = ?";
2621 $params[] = $USER->id;
2630 } else if ($page != -1) {
2631 $limitfrom = $page*$perpage;
2632 $limitnum = $perpage;
2638 $groupmode = groups_get_activity_groupmode($cm);
2639 $currentgroup = groups_get_activity_group($cm);
2642 if (empty($modcontext)) {
2643 $modcontext = context_module::instance($cm->id);
2646 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2647 if ($currentgroup) {
2648 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2649 $params[] = $currentgroup;
2655 //seprate groups without access all
2656 if ($currentgroup) {
2657 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2658 $params[] = $currentgroup;
2660 $groupselect = "AND d.groupid = -1";
2668 if (empty($forumsort)) {
2669 $forumsort = "d.timemodified DESC";
2671 if (empty($fullpost)) {
2672 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2677 if (empty($userlastmodified)) { // We don't need to know this
2681 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
2682 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2685 $allnames = get_all_user_name_fields(true, 'u');
2686 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2687 u.email, u.picture, u.imagealt $umfields
2688 FROM {forum_discussions} d
2689 JOIN {forum_posts} p ON p.discussion = d.id
2690 JOIN {user} u ON p.userid = u.id
2692 WHERE d.forum = ? AND p.parent = 0
2693 $timelimit $groupselect
2694 ORDER BY $forumsort";
2695 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2699 * Gets the neighbours (previous and next) of a discussion.
2701 * The calculation is based on the timemodified of the discussion and does not handle
2702 * the neighbours having an identical timemodified. The reason is that we do not have any
2703 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2706 * Please note that this does not check whether or not the discussion passed is accessible
2707 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2708 * the returned neighbours are checked and are accessible to the current user.
2710 * @param object $cm The CM record.
2711 * @param object $discussion The discussion record.
2712 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2713 * they contain the record with minimal information such as 'id' and 'name'.
2714 * When the neighbour is not found the value is false.
2716 function forum_get_discussion_neighbours($cm, $discussion) {
2717 global $CFG, $DB, $USER;
2719 if ($cm->instance != $discussion->forum) {
2720 throw new coding_exception('Discussion is not part of the same forum.');
2723 $neighbours = array('prev' => false, 'next' => false);
2724 $now = round(time(), -2);
2727 $modcontext = context_module::instance($cm->id);
2728 $groupmode = groups_get_activity_groupmode($cm);
2729 $currentgroup = groups_get_activity_group($cm);
2731 // Users must fulfill timed posts.
2733 if (!empty($CFG->forum_enabletimedposts)) {
2734 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2735 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2736 $params['tltimestart'] = $now;
2737 $params['tltimeend'] = $now;
2739 $timelimit .= ' OR d.userid = :tluserid';
2740 $params['tluserid'] = $USER->id;
2746 // Limiting to posts accessible according to groups.
2749 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2750 if ($currentgroup) {
2751 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2752 $params['groupid'] = $currentgroup;
2755 if ($currentgroup) {
2756 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2757 $params['groupid'] = $currentgroup;
2759 $groupselect = 'AND d.groupid = -1';
2764 $params['forumid'] = $cm->instance;
2765 $params['discid'] = $discussion->id;
2766 $params['disctimemodified'] = $discussion->timemodified;
2768 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2769 FROM {forum_discussions} d
2770 WHERE d.forum = :forumid
2775 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2776 ORDER BY d.timemodified DESC";
2778 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2779 ORDER BY d.timemodified ASC";
2781 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2782 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2792 * @uses CONTEXT_MODULE
2793 * @uses VISIBLEGROUPS
2797 function forum_get_discussions_unread($cm) {
2798 global $CFG, $DB, $USER;
2800 $now = round(time(), -2);
2801 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2804 $groupmode = groups_get_activity_groupmode($cm);
2805 $currentgroup = groups_get_activity_group($cm);
2808 $modcontext = context_module::instance($cm->id);
2810 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2811 if ($currentgroup) {
2812 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2813 $params['currentgroup'] = $currentgroup;
2819 //separate groups without access all
2820 if ($currentgroup) {
2821 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2822 $params['currentgroup'] = $currentgroup;
2824 $groupselect = "AND d.groupid = -1";
2831 if (!empty($CFG->forum_enabletimedposts)) {
2832 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2833 $params['now1'] = $now;
2834 $params['now2'] = $now;
2839 $sql = "SELECT d.id, COUNT(p.id) AS unread
2840 FROM {forum_discussions} d
2841 JOIN {forum_posts} p ON p.discussion = d.id
2842 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2843 WHERE d.forum = {$cm->instance}
2844 AND p.modified >= :cutoffdate AND r.id is NULL
2848 $params['cutoffdate'] = $cutoffdate;
2850 if ($unreads = $DB->get_records_sql($sql, $params)) {
2851 foreach ($unreads as $unread) {
2852 $unreads[$unread->id] = $unread->unread;
2864 * @uses CONEXT_MODULE
2865 * @uses VISIBLEGROUPS
2869 function forum_get_discussions_count($cm) {
2870 global $CFG, $DB, $USER;
2872 $now = round(time(), -2);
2873 $params = array($cm->instance);
2874 $groupmode = groups_get_activity_groupmode($cm);
2875 $currentgroup = groups_get_activity_group($cm);
2878 $modcontext = context_module::instance($cm->id);
2880 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2881 if ($currentgroup) {
2882 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2883 $params[] = $currentgroup;
2889 //seprate groups without access all
2890 if ($currentgroup) {
2891 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2892 $params[] = $currentgroup;
2894 $groupselect = "AND d.groupid = -1";
2901 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2905 if (!empty($CFG->forum_enabletimedposts)) {
2907 $modcontext = context_module::instance($cm->id);
2909 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2910 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2914 $timelimit .= " OR d.userid = ?";
2915 $params[] = $USER->id;
2921 $sql = "SELECT COUNT(d.id)
2922 FROM {forum_discussions} d
2923 JOIN {forum_posts} p ON p.discussion = d.id
2924 WHERE d.forum = ? AND p.parent = 0
2925 $groupselect $timelimit";
2927 return $DB->get_field_sql($sql, $params);
2931 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2937 * @param int $courseid
2938 * @param string $type
2940 function forum_get_course_forum($courseid, $type) {
2941 // How to set up special 1-per-course forums
2942 global $CFG, $DB, $OUTPUT, $USER;
2944 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2945 // There should always only be ONE, but with the right combination of
2946 // errors there might be more. In this case, just return the oldest one (lowest ID).
2947 foreach ($forums as $forum) {
2948 return $forum; // ie the first one
2952 // Doesn't exist, so create one now.
2953 $forum = new stdClass();
2954 $forum->course = $courseid;
2955 $forum->type = "$type";
2956 if (!empty($USER->htmleditor)) {
2957 $forum->introformat = $USER->htmleditor;
2959 switch ($forum->type) {
2961 $forum->name = get_string("namenews", "forum");
2962 $forum->intro = get_string("intronews", "forum");
2963 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2964 $forum->assessed = 0;
2965 if ($courseid == SITEID) {
2966 $forum->name = get_string("sitenews");
2967 $forum->forcesubscribe = 0;
2971 $forum->name = get_string("namesocial", "forum");
2972 $forum->intro = get_string("introsocial", "forum");
2973 $forum->assessed = 0;
2974 $forum->forcesubscribe = 0;
2977 $forum->name = get_string('blogforum', 'forum');
2978 $forum->intro = get_string('introblog', 'forum');
2979 $forum->assessed = 0;
2980 $forum->forcesubscribe = 0;
2983 echo $OUTPUT->notification("That forum type doesn't exist!");
2988 $forum->timemodified = time();
2989 $forum->id = $DB->insert_record("forum", $forum);
2991 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2992 echo $OUTPUT->notification("Could not find forum module!!");
2995 $mod = new stdClass();
2996 $mod->course = $courseid;
2997 $mod->module = $module->id;
2998 $mod->instance = $forum->id;
3000 include_once("$CFG->dirroot/course/lib.php");
3001 if (! $mod->coursemodule = add_course_module($mod) ) {
3002 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3005 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3006 return $DB->get_record("forum", array("id" => "$forum->id"));
3011 * Given the data about a posting, builds up the HTML to display it and
3012 * returns the HTML in a string. This is designed for sending via HTML email.
3015 * @param object $course
3017 * @param object $forum
3018 * @param object $discussion
3019 * @param object $post
3020 * @param object $userform
3021 * @param object $userto
3022 * @param bool $ownpost
3023 * @param bool $reply
3026 * @param string $footer
3029 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
3030 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
3032 global $CFG, $OUTPUT;
3034 $modcontext = context_module::instance($cm->id);
3036 if (!isset($userto->viewfullnames[$forum->id])) {
3037 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3039 $viewfullnames = $userto->viewfullnames[$forum->id];
3042 // add absolute file links
3043 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3045 // format the post body
3046 $options = new stdClass();
3047 $options->para = true;
3048 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
3050 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3052 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3053 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
3056 if ($post->parent) {
3057 $output .= '<td class="topic">';
3059 $output .= '<td class="topic starter">';
3061 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3063 $fullname = fullname($userfrom, $viewfullnames);
3064 $by = new stdClass();
3065 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&course='.$course->id.'">'.$fullname.'</a>';
3066 $by->date = userdate($post->modified, '', core_date::get_user_timezone($userto));
3067 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3069 $output .= '</td></tr>';
3071 $output .= '<tr><td class="left side" valign="top">';
3073 if (isset($userfrom->groups)) {
3074 $groups = $userfrom->groups[$forum->id];
3076 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3080 $output .= print_group_picture($groups, $course->id, false, true, true);
3082 $output .= ' ';
3085 $output .= '</td><td class="content">';
3087 $attachments = forum_print_attachments($post, $cm, 'html');
3088 if ($attachments !== '') {
3089 $output .= '<div class="attachments">';
3090 $output .= $attachments;
3091 $output .= '</div>';
3094 $output .= $formattedtext;
3097 $commands = array();
3099 if ($post->parent) {
3100 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3101 $post->discussion.'&parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3105 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3106 get_string('reply', 'forum').'</a>';
3109 $output .= '<div class="commands">';
3110 $output .= implode(' | ', $commands);
3111 $output .= '</div>';
3113 // Context link to post if required
3115 $output .= '<div class="link">';
3116 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3117 get_string('postincontext', 'forum').'</a>';
3118 $output .= '</div>';
3122 $output .= '<div class="footer">'.$footer.'</div>';
3124 $output .= '</td></tr></table>'."\n\n";
3130 * Print a forum post
3134 * @uses FORUM_MODE_THREADED
3135 * @uses PORTFOLIO_FORMAT_PLAINHTML
3136 * @uses PORTFOLIO_FORMAT_FILE
3137 * @uses PORTFOLIO_FORMAT_RICHHTML
3138 * @uses PORTFOLIO_ADD_TEXT_LINK
3139 * @uses CONTEXT_MODULE
3140 * @param object $post The post to print.
3141 * @param object $discussion
3142 * @param object $forum
3144 * @param object $course
3145 * @param boolean $ownpost Whether this post belongs to the current user.
3146 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3147 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3148 * @param string $footer Extra stuff to print after the message.
3149 * @param string $highlight Space-separated list of terms to highlight.
3150 * @param int $post_read true, false or -99. If we already know whether this user
3151 * has read this post, pass that in, otherwise, pass in -99, and this
3152 * function will work it out.
3153 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3154 * the current user can't see this post, if this argument is true
3155 * (the default) then print a dummy 'you can't see this post' post.
3156 * If false, don't output anything at all.
3157 * @param bool|null $istracked
3160 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3161 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3162 global $USER, $CFG, $OUTPUT;
3164 require_once($CFG->libdir . '/filelib.php');
3169 $modcontext = context_module::instance($cm->id);
3171 $post->course = $course->id;
3172 $post->forum = $forum->id;
3173 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3174 if (!empty($CFG->enableplagiarism)) {
3175 require_once($CFG->libdir.'/plagiarismlib.php');
3176 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3177 'content' => $post->message,
3179 'course' => $post->course,
3180 'forum' => $post->forum));
3184 if (!isset($cm->cache)) {
3185 $cm->cache = new stdClass;
3188 if (!isset($cm->cache->caps)) {
3189 $cm->cache->caps = array();
3190 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3191 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3192 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3193 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3194 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3195 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3196 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3197 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3198 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3201 if (!isset($cm->uservisible)) {
3202 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3205 if ($istracked && is_null($postisread)) {
3206 $postisread = forum_tp_is_post_read($USER->id, $post);
3209 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3211 if (!$dummyifcantsee) {
3218 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3219 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3221 'aria-label' => get_string('hiddenforumpost', 'forum')));
3222 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3223 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3224 if ($post->parent) {
3225 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3227 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3229 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3230 'role' => 'header')); // Subject.
3231 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3232 'role' => 'header')); // Author.
3233 $output .= html_writer::end_tag('div');
3234 $output .= html_writer::end_tag('div'); // row
3235 $output .= html_writer::start_tag('div', array('class'=>'row'));
3236 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3237 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3238 $output .= html_writer::end_tag('div'); // row
3239 $output .= html_writer::end_tag('div'); // forumpost
3249 $str = new stdClass;
3250 $str->edit = get_string('edit', 'forum');
3251 $str->delete = get_string('delete', 'forum');
3252 $str->reply = get_string('reply', 'forum');
3253 $str->parent = get_string('parent', 'forum');
3254 $str->pruneheading = get_string('pruneheading', 'forum');
3255 $str->prune = get_string('prune', 'forum');
3256 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3257 $str->markread = get_string('markread', 'forum');
3258 $str->markunread = get_string('markunread', 'forum');
3261 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3263 // Build an object that represents the posting user
3264 $postuser = new stdClass;
3265 $postuserfields = explode(',', user_picture::fields());
3266 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3267 $postuser->id = $post->userid;
3268 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3269 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3271 // Prepare the groups the posting user belongs to
3272 if (isset($cm->cache->usersgroups)) {
3274 if (isset($cm->cache->usersgroups[$post->userid])) {
3275 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3276 $groups[$gid] = $cm->cache->groups[$gid];
3280 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3283 // Prepare the attachements for the post, files then images
3284 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3286 // Determine if we need to shorten this post
3287 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3290 // Prepare an array of commands
3291 $commands = array();
3293 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3294 // Don't display the mark read / unread controls in this case.
3295 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3296 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3297 $text = $str->markunread;
3299 $url->param('mark', 'read');
3300 $text = $str->markread;
3302 if ($str->displaymode == FORUM_MODE_THREADED) {
3303 $url->param('parent', $post->parent);
3305 $url->set_anchor('p'.$post->id);
3307 $commands[] = array('url'=>$url, 'text'=>$text);
3310 // Zoom in to the parent specifically
3311 if ($post->parent) {
3312 $url = new moodle_url($discussionlink);
3313 if ($str->displaymode == FORUM_MODE_THREADED) {
3314 $url->param('parent', $post->parent);
3316 $url->set_anchor('p'.$post->parent);
3318 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3321 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3322 $age = time() - $post->created;
3323 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3327 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3328 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3329 // The first post in single simple is the forum description.
3330 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3332 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3333 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3336 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3337 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3340 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3341 // Do not allow deleting of first post in single simple type.
3342 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3343 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3347 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3350 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3351 $p = array('postid' => $post->id);
3352 require_once($CFG->libdir.'/portfoliolib.php');
3353 $button = new portfolio_add_button();
3354 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3355 if (empty($attachments)) {
3356 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3358 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3361 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3362 if (!empty($porfoliohtml)) {
3363 $commands[] = $porfoliohtml;
3366 // Finished building commands
3375 $forumpostclass = ' read';
3377 $forumpostclass = ' unread';
3378 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3381 // ignore trackign status if not tracked or tracked param missing
3382 $forumpostclass = '';
3386 if (empty($post->parent)) {
3387 $topicclass = ' firstpost starter';
3390 if (!empty($post->lastpost)) {
3391 $forumpostclass = ' lastpost';
3394 $postbyuser = new stdClass;
3395 $postbyuser->post = $post->subject;
3396 $postbyuser->user = $postuser->fullname;
3397 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3398 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3399 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3401 'aria-label' => $discussionbyuser));
3402 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3403 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3404 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3405 $output .= html_writer::end_tag('div');
3408 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3410 $postsubject = $post->subject;
3411 if (empty($post->subjectnoformat)) {
3412 $postsubject = format_string($postsubject);
3414 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject',
3415 'role' => 'heading',
3416 'aria-level' => '2'));
3418 $by = new stdClass();
3419 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3420 $by->date = userdate($post->modified);
3421 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3422 'role' => 'heading',
3423 'aria-level' => '2'));
3425 $output .= html_writer::end_tag('div'); //topic
3426 $output .= html_writer::end_tag('div'); //row
3428 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3429 $output .= html_writer::start_tag('div', array('class'=>'left'));
3433 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3435 if (empty($groupoutput)) {
3436 $groupoutput = ' ';
3438 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3440 $output .= html_writer::end_tag('div'); //left side
3441 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3442 $output .= html_writer::start_tag('div', array('class'=>'content'));
3444 $options = new stdClass;
3445 $options->para = false;
3446 $options->trusted = $post->messagetrust;
3447 $options->context = $modcontext;
3449 // Prepare shortened version by filtering the text then shortening it.
3450 $postclass = 'shortenedpost';
3451 $postcontent = format_text($post->message, $post->messageformat, $options);
3452 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3453 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3454 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3455 array('class'=>'post-word-count'));
3457 // Prepare whole post
3458 $postclass = 'fullpost';
3459 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3460 if (!empty($highlight)) {
3461 $postcontent = highlight($highlight, $postcontent);
3463 if (!empty($forum->displaywordcount)) {
3464 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3465 array('class'=>'post-word-count'));
3467 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));