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();
467 // Posts older than 2 days will not be mailed. This is to avoid the problem where
468 // cron has not been running for a long time, and then suddenly people are flooded
469 // with mail from the past few weeks or months
471 $endtime = $timenow - $CFG->maxeditingtime;
472 $starttime = $endtime - 48 * 3600; // Two days earlier
474 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
475 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
477 foreach ($digestsset as $thisrow) {
478 if (!isset($digests[$thisrow->forum])) {
479 $digests[$thisrow->forum] = array();
481 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
483 $digestsset->close();
485 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
486 // Mark them all now as being mailed. It's unlikely but possible there
487 // might be an error later so that a post is NOT actually mailed out,
488 // but since mail isn't crucial, we can accept this risk. Doing it now
489 // prevents the risk of duplicated mails, which is a worse problem.
491 if (!forum_mark_old_posts_as_mailed($endtime)) {
492 mtrace('Errors occurred while trying to mark some posts as being mailed.');
493 return false; // Don't continue trying to mail them, in case we are in a cron loop
496 // checking post validity, and adding users to loop through later
497 foreach ($posts as $pid => $post) {
499 $discussionid = $post->discussion;
500 if (!isset($discussions[$discussionid])) {
501 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
502 $discussions[$discussionid] = $discussion;
503 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
504 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
507 mtrace('Could not find discussion ' . $discussionid);
512 $forumid = $discussions[$discussionid]->forum;
513 if (!isset($forums[$forumid])) {
514 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
515 $forums[$forumid] = $forum;
517 mtrace('Could not find forum '.$forumid);
522 $courseid = $forums[$forumid]->course;
523 if (!isset($courses[$courseid])) {
524 if ($course = $DB->get_record('course', array('id' => $courseid))) {
525 $courses[$courseid] = $course;
527 mtrace('Could not find course '.$courseid);
532 if (!isset($coursemodules[$forumid])) {
533 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
534 $coursemodules[$forumid] = $cm;
536 mtrace('Could not find course module for forum '.$forumid);
542 // Caching subscribed users of each forum.
543 if (!isset($subscribedusers[$forumid])) {
544 $modcontext = context_module::instance($coursemodules[$forumid]->id);
545 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
546 foreach ($subusers as $postuser) {
547 // this user is subscribed to this forum
548 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
550 if ($userscount > FORUM_CRON_USER_CACHE) {
551 // Store minimal user info.
552 $minuser = new stdClass();
553 $minuser->id = $postuser->id;
554 $users[$postuser->id] = $minuser;
556 // Cache full user record.
557 forum_cron_minimise_user_record($postuser);
558 $users[$postuser->id] = $postuser;
566 $mailcount[$pid] = 0;
567 $errorcount[$pid] = 0;
571 if ($users && $posts) {
573 $urlinfo = parse_url($CFG->wwwroot);
574 $hostname = $urlinfo['host'];
576 foreach ($users as $userto) {
577 // Terminate if processing of any account takes longer than 2 minutes.
578 core_php_time_limit::raise(120);
580 mtrace('Processing user ' . $userto->id);
582 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
583 if (isset($userto->username)) {
584 $userto = clone($userto);
586 $userto = $DB->get_record('user', array('id' => $userto->id));
587 forum_cron_minimise_user_record($userto);
589 $userto->viewfullnames = array();
590 $userto->canpost = array();
591 $userto->markposts = array();
593 // Setup this user so that the capabilities are cached, and environment matches receiving user.
594 cron_setup_user($userto);
597 foreach ($coursemodules as $forumid => $unused) {
598 $coursemodules[$forumid]->cache = new stdClass();
599 $coursemodules[$forumid]->cache->caps = array();
600 unset($coursemodules[$forumid]->uservisible);
603 foreach ($posts as $pid => $post) {
604 $discussion = $discussions[$post->discussion];
605 $forum = $forums[$discussion->forum];
606 $course = $courses[$forum->course];
607 $cm =& $coursemodules[$forum->id];
609 // Do some checks to see if we can bail out now.
611 // Only active enrolled users are in the list of subscribers.
612 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
613 if (!isset($subscribedusers[$forum->id][$userto->id])) {
614 // The user does not subscribe to this forum.
618 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
619 // The user does not subscribe to this forum, or to this specific discussion.
623 // Don't send email if the forum is Q&A and the user has not posted.
624 // Initial topics are still mailed.
625 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
626 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
630 // Get info about the sending user.
631 if (array_key_exists($post->userid, $users)) {
632 // We might know the user already.
633 $userfrom = $users[$post->userid];
634 if (!isset($userfrom->idnumber)) {
635 // Minimalised user info, fetch full record.
636 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
637 forum_cron_minimise_user_record($userfrom);
640 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
641 forum_cron_minimise_user_record($userfrom);
642 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
643 if ($userscount <= FORUM_CRON_USER_CACHE) {
645 $users[$userfrom->id] = $userfrom;
648 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
652 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
654 // Setup global $COURSE properly - needed for roles and languages.
655 cron_setup_user($userto, $course);
658 if (!isset($userto->viewfullnames[$forum->id])) {
659 $modcontext = context_module::instance($cm->id);
660 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
662 if (!isset($userto->canpost[$discussion->id])) {
663 $modcontext = context_module::instance($cm->id);
664 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
666 if (!isset($userfrom->groups[$forum->id])) {
667 if (!isset($userfrom->groups)) {
668 $userfrom->groups = array();
669 if (isset($users[$userfrom->id])) {
670 $users[$userfrom->id]->groups = array();
673 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
674 if (isset($users[$userfrom->id])) {
675 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
679 // Make sure groups allow this user to see this email.
680 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
681 // Groups are being used.
682 if (!groups_group_exists($discussion->groupid)) {
683 // Can't find group - be safe and don't this message.
687 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
688 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
693 // Make sure we're allowed to see the post.
694 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
695 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
699 // OK so we need to send the email.
701 // Does the user want this post in a digest? If so postpone it for now.
702 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
704 if ($maildigest > 0) {
705 // This user wants the mails to be in digest form.
706 $queue = new stdClass();
707 $queue->userid = $userto->id;
708 $queue->discussionid = $discussion->id;
709 $queue->postid = $post->id;
710 $queue->timemodified = $post->created;
711 $DB->insert_record('forum_queue', $queue);
715 // Prepare to actually send the post now, and build up the content.
717 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
719 $userfrom->customheaders = array (
720 // Headers to make emails easier to track.
722 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id . '@' . $hostname.'>',
723 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
724 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id, $hostname),
725 'X-Course-Id: ' . $course->id,
726 'X-Course-Name: ' . format_string($course->fullname, true)
730 // This post is a reply, so add headers for threading (see MDL-22551).
731 $userfrom->customheaders[] = 'In-Reply-To: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
732 $userfrom->customheaders[] = 'References: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
735 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
738 $a->courseshortname = $shortname;
739 $a->forumname = $cleanforumname;
740 $a->subject = format_string($post->subject, true);
741 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a));
742 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
743 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
745 // Send the post now!
746 mtrace('Sending ', '');
748 $eventdata = new stdClass();
749 $eventdata->component = 'mod_forum';
750 $eventdata->name = 'posts';
751 $eventdata->userfrom = $userfrom;
752 $eventdata->userto = $userto;
753 $eventdata->subject = $postsubject;
754 $eventdata->fullmessage = $posttext;
755 $eventdata->fullmessageformat = FORMAT_PLAIN;
756 $eventdata->fullmessagehtml = $posthtml;
757 $eventdata->notification = 1;
759 // If forum_replytouser is not set then send mail using the noreplyaddress.
760 if (empty($CFG->forum_replytouser)) {
761 // Clone userfrom as it is referenced by $users.
762 $cloneduserfrom = clone($userfrom);
763 $cloneduserfrom->email = $CFG->noreplyaddress;
764 $eventdata->userfrom = $cloneduserfrom;
767 $smallmessagestrings = new stdClass();
768 $smallmessagestrings->user = fullname($userfrom);
769 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
770 $smallmessagestrings->message = $post->message;
772 // Make sure strings are in message recipients language.
773 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
775 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
776 $eventdata->contexturl = $contexturl->out();
777 $eventdata->contexturlname = $discussion->name;
779 $mailresult = message_send($eventdata);
781 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
782 " ($userto->email) .. not trying again.");
783 $errorcount[$post->id]++;
785 $mailcount[$post->id]++;
787 // Mark post as read if forum_usermarksread is set off.
788 if (!$CFG->forum_usermarksread) {
789 $userto->markposts[$post->id] = $post->id;
793 mtrace('post ' . $post->id . ': ' . $post->subject);
796 // Mark processed posts as read.
797 forum_tp_mark_posts_read($userto, $userto->markposts);
803 foreach ($posts as $post) {
804 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
805 if ($errorcount[$post->id]) {
806 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
811 // release some memory
812 unset($subscribedusers);
818 $sitetimezone = $CFG->timezone;
820 // Now see if there are any digest mails waiting to be sent, and if we should send them
822 mtrace('Starting digest processing...');
824 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
826 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
827 set_config('digestmailtimelast', 0);
831 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
833 // Delete any really old ones (normally there shouldn't be any)
834 $weekago = $timenow - (7 * 24 * 3600);
835 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
836 mtrace ('Cleaned old digest records');
838 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
840 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
842 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
844 if ($digestposts_rs->valid()) {
846 // We have work to do
849 //caches - reuse the those filled before too
850 $discussionposts = array();
851 $userdiscussions = array();
853 foreach ($digestposts_rs as $digestpost) {
854 if (!isset($posts[$digestpost->postid])) {
855 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
856 $posts[$digestpost->postid] = $post;
861 $discussionid = $digestpost->discussionid;
862 if (!isset($discussions[$discussionid])) {
863 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
864 $discussions[$discussionid] = $discussion;
869 $forumid = $discussions[$discussionid]->forum;
870 if (!isset($forums[$forumid])) {
871 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
872 $forums[$forumid] = $forum;
878 $courseid = $forums[$forumid]->course;
879 if (!isset($courses[$courseid])) {
880 if ($course = $DB->get_record('course', array('id' => $courseid))) {
881 $courses[$courseid] = $course;
887 if (!isset($coursemodules[$forumid])) {
888 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
889 $coursemodules[$forumid] = $cm;
894 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
895 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
897 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
899 // Data collected, start sending out emails to each user
900 foreach ($userdiscussions as $userid => $thesediscussions) {
902 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
906 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
908 // First of all delete all the queue entries for this user
909 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
911 // Init user caches - we keep the cache for one cycle only,
912 // otherwise it would unnecessarily consume memory.
913 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
914 $userto = clone($users[$userid]);
916 $userto = $DB->get_record('user', array('id' => $userid));
917 forum_cron_minimise_user_record($userto);
919 $userto->viewfullnames = array();
920 $userto->canpost = array();
921 $userto->markposts = array();
923 // Override the language and timezone of the "current" user, so that
924 // mail is customised for the receiver.
925 cron_setup_user($userto);
927 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
929 $headerdata = new stdClass();
930 $headerdata->sitename = format_string($site->fullname, true);
931 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&course='.$site->id;
933 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
934 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
936 $posthtml = "<head>";
937 /* foreach ($CFG->stylesheets as $stylesheet) {
939 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
941 $posthtml .= "</head>\n<body id=\"email\">\n";
942 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
944 foreach ($thesediscussions as $discussionid) {
946 core_php_time_limit::raise(120); // to be reset for each post
948 $discussion = $discussions[$discussionid];
949 $forum = $forums[$discussion->forum];
950 $course = $courses[$forum->course];
951 $cm = $coursemodules[$forum->id];
954 cron_setup_user($userto, $course);
957 if (!isset($userto->viewfullnames[$forum->id])) {
958 $modcontext = context_module::instance($cm->id);
959 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
961 if (!isset($userto->canpost[$discussion->id])) {
962 $modcontext = context_module::instance($cm->id);
963 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
966 $strforums = get_string('forums', 'forum');
967 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
968 $canreply = $userto->canpost[$discussion->id];
969 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
971 $posttext .= "\n \n";
972 $posttext .= '=====================================================================';
973 $posttext .= "\n \n";
974 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
975 if ($discussion->name != $forum->name) {
976 $posttext .= " -> ".format_string($discussion->name,true);
979 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
982 $posthtml .= "<p><font face=\"sans-serif\">".
983 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
984 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
985 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
986 if ($discussion->name == $forum->name) {
987 $posthtml .= "</font></p>";
989 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
993 $postsarray = $discussionposts[$discussionid];
996 foreach ($postsarray as $postid) {
997 $post = $posts[$postid];
999 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1000 $userfrom = $users[$post->userid];
1001 if (!isset($userfrom->idnumber)) {
1002 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1003 forum_cron_minimise_user_record($userfrom);
1006 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1007 forum_cron_minimise_user_record($userfrom);
1008 if ($userscount <= FORUM_CRON_USER_CACHE) {
1010 $users[$userfrom->id] = $userfrom;
1014 mtrace('Could not find user '.$post->userid);
1018 if (!isset($userfrom->groups[$forum->id])) {
1019 if (!isset($userfrom->groups)) {
1020 $userfrom->groups = array();
1021 if (isset($users[$userfrom->id])) {
1022 $users[$userfrom->id]->groups = array();
1025 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1026 if (isset($users[$userfrom->id])) {
1027 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1031 $userfrom->customheaders = array ("Precedence: Bulk");
1033 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1034 if ($maildigest == 2) {
1035 // Subjects and link only
1037 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1038 $by = new stdClass();
1039 $by->name = fullname($userfrom);
1040 $by->date = userdate($post->modified);
1041 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
1042 $posttext .= "\n---------------------------------------------------------------------";
1044 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&course=$course->id\">$by->name</a>";
1045 $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>';
1048 // The full treatment
1049 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
1050 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1052 // Create an array of postid's for this user to mark as read.
1053 if (!$CFG->forum_usermarksread) {
1054 $userto->markposts[$post->id] = $post->id;
1058 $footerlinks = array();
1059 if ($canunsubscribe) {
1060 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1062 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1064 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1065 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1066 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1068 $posthtml .= '</body>';
1070 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1071 // This user DOESN'T want to receive HTML
1075 $attachment = $attachname='';
1076 // Directly email forum digests rather than sending them via messaging, use the
1077 // site shortname as 'from name', the noreply address will be used by email_to_user.
1078 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);
1081 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1082 "($userto->email)... not trying again.");
1087 // Mark post as read if forum_usermarksread is set off
1088 forum_tp_mark_posts_read($userto, $userto->markposts);
1092 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1093 set_config('digestmailtimelast', $timenow);
1098 if (!empty($usermailcount)) {
1099 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1102 if (!empty($CFG->forum_lastreadclean)) {
1104 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1105 set_config('forum_lastreadclean', $timenow);
1106 mtrace('Removing old forum read tracking info...');
1107 forum_tp_clean_read_records();
1110 set_config('forum_lastreadclean', time());
1117 * Builds and returns the body of the email notification in plain text.
1121 * @uses CONTEXT_MODULE
1122 * @param object $course
1124 * @param object $forum
1125 * @param object $discussion
1126 * @param object $post
1127 * @param object $userfrom
1128 * @param object $userto
1129 * @param boolean $bare
1130 * @return string The email body in plain text format.
1132 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false) {
1135 $modcontext = context_module::instance($cm->id);
1137 if (!isset($userto->viewfullnames[$forum->id])) {
1138 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1140 $viewfullnames = $userto->viewfullnames[$forum->id];
1143 if (!isset($userto->canpost[$discussion->id])) {
1144 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1146 $canreply = $userto->canpost[$discussion->id];
1150 $by->name = fullname($userfrom, $viewfullnames);
1151 $by->date = userdate($post->modified, "", $userto->timezone);
1153 $strbynameondate = get_string('bynameondate', 'forum', $by);
1155 $strforums = get_string('forums', 'forum');
1157 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1162 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1163 $posttext = "$shortname -> $strforums -> ".format_string($forum->name,true);
1165 if ($discussion->name != $forum->name) {
1166 $posttext .= " -> ".format_string($discussion->name,true);
1170 // add absolute file links
1171 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1174 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1175 $posttext .= "\n---------------------------------------------------------------------\n";
1176 $posttext .= format_string($post->subject,true);
1178 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1180 $posttext .= "\n".$strbynameondate."\n";
1181 $posttext .= "---------------------------------------------------------------------\n";
1182 $posttext .= format_text_email($post->message, $post->messageformat);
1183 $posttext .= "\n\n";
1184 $posttext .= forum_print_attachments($post, $cm, "text");
1186 if (!$bare && $canreply) {
1187 $posttext .= "---------------------------------------------------------------------\n";
1188 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1189 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1191 if (!$bare && $canunsubscribe) {
1192 $posttext .= "\n---------------------------------------------------------------------\n";
1193 $posttext .= get_string("unsubscribe", "forum");
1194 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1197 $posttext .= "\n---------------------------------------------------------------------\n";
1198 $posttext .= get_string("digestmailpost", "forum");
1199 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1205 * Builds and returns the body of the email notification in html format.
1208 * @param object $course
1210 * @param object $forum
1211 * @param object $discussion
1212 * @param object $post
1213 * @param object $userfrom
1214 * @param object $userto
1215 * @return string The email text in HTML format
1217 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto) {
1220 if ($userto->mailformat != 1) { // Needs to be HTML
1224 if (!isset($userto->canpost[$discussion->id])) {
1225 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1227 $canreply = $userto->canpost[$discussion->id];
1230 $strforums = get_string('forums', 'forum');
1231 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1232 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1234 $posthtml = '<head>';
1235 /* foreach ($CFG->stylesheets as $stylesheet) {
1237 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1239 $posthtml .= '</head>';
1240 $posthtml .= "\n<body id=\"email\">\n\n";
1242 $posthtml .= '<div class="navbar">'.
1243 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$shortname.'</a> » '.
1244 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> » '.
1245 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1246 if ($discussion->name == $forum->name) {
1247 $posthtml .= '</div>';
1249 $posthtml .= ' » <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1250 format_string($discussion->name,true).'</a></div>';
1252 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1254 $footerlinks = array();
1255 if ($canunsubscribe) {
1256 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/subscribe.php?id=' . $forum->id . '">' . get_string('unsubscribe', 'forum') . '</a>';
1257 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
1259 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1260 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode(' ', $footerlinks) . '</div>';
1262 $posthtml .= '</body>';
1270 * @param object $course
1271 * @param object $user
1272 * @param object $mod TODO this is not used in this function, refactor
1273 * @param object $forum
1274 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1276 function forum_user_outline($course, $user, $mod, $forum) {
1278 require_once("$CFG->libdir/gradelib.php");
1279 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1280 if (empty($grades->items[0]->grades)) {
1283 $grade = reset($grades->items[0]->grades);
1286 $count = forum_count_user_posts($forum->id, $user->id);
1288 if ($count && $count->postcount > 0) {
1289 $result = new stdClass();
1290 $result->info = get_string("numposts", "forum", $count->postcount);
1291 $result->time = $count->lastpost;
1293 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1296 } else if ($grade) {
1297 $result = new stdClass();
1298 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1300 //datesubmitted == time created. dategraded == time modified or time overridden
1301 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1302 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1303 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1304 $result->time = $grade->dategraded;
1306 $result->time = $grade->datesubmitted;
1318 * @param object $coure
1319 * @param object $user
1320 * @param object $mod
1321 * @param object $forum
1323 function forum_user_complete($course, $user, $mod, $forum) {
1324 global $CFG,$USER, $OUTPUT;
1325 require_once("$CFG->libdir/gradelib.php");
1327 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1328 if (!empty($grades->items[0]->grades)) {
1329 $grade = reset($grades->items[0]->grades);
1330 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1331 if ($grade->str_feedback) {
1332 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1336 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1338 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1339 print_error('invalidcoursemodule');
1341 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1343 foreach ($posts as $post) {
1344 if (!isset($discussions[$post->discussion])) {
1347 $discussion = $discussions[$post->discussion];
1349 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1352 echo "<p>".get_string("noposts", "forum")."</p>";
1357 * Filters the forum discussions according to groups membership and config.
1359 * @since Moodle 2.8, 2.7.1, 2.6.4
1360 * @param array $discussions Discussions with new posts array
1361 * @return array Forums with the number of new posts
1363 function forum_filter_user_groups_discussions($discussions) {
1365 // Group the remaining discussions posts by their forumid.
1366 $filteredforums = array();
1368 // Discard not visible groups.
1369 foreach ($discussions as $discussion) {
1371 // Course data is already cached.
1372 $instances = get_fast_modinfo($discussion->course)->get_instances();
1373 $forum = $instances['forum'][$discussion->forum];
1375 // Continue if the user should not see this discussion.
1376 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1380 // Grouping results by forum.
1381 if (empty($filteredforums[$forum->instance])) {
1382 $filteredforums[$forum->instance] = new stdClass();
1383 $filteredforums[$forum->instance]->id = $forum->id;
1384 $filteredforums[$forum->instance]->count = 0;
1386 $filteredforums[$forum->instance]->count += $discussion->count;
1390 return $filteredforums;
1394 * Returns whether the discussion group is visible by the current user or not.
1396 * @since Moodle 2.8, 2.7.1, 2.6.4
1397 * @param cm_info $cm The discussion course module
1398 * @param int $discussiongroupid The discussion groupid
1401 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1403 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1407 if (isguestuser()) {
1411 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1412 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1423 * @param array $courses
1424 * @param array $htmlarray
1426 function forum_print_overview($courses,&$htmlarray) {
1427 global $USER, $CFG, $DB, $SESSION;
1429 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1433 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1437 // Courses to search for new posts
1438 $coursessqls = array();
1440 foreach ($courses as $course) {
1442 // If the user has never entered into the course all posts are pending
1443 if ($course->lastaccess == 0) {
1444 $coursessqls[] = '(d.course = ?)';
1445 $params[] = $course->id;
1447 // Only posts created after the course last access
1449 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1450 $params[] = $course->id;
1451 $params[] = $course->lastaccess;
1454 $params[] = $USER->id;
1455 $coursessql = implode(' OR ', $coursessqls);
1457 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1458 .'FROM {forum_discussions} d '
1459 .'JOIN {forum_posts} p ON p.discussion = d.id '
1460 ."WHERE ($coursessql) "
1461 .'AND p.userid != ? '
1462 .'GROUP BY d.id, d.forum, d.course, d.groupid';
1465 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1466 $discussions = array();
1469 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1471 // also get all forum tracking stuff ONCE.
1472 $trackingforums = array();
1473 foreach ($forums as $forum) {
1474 if (forum_tp_can_track_forums($forum)) {
1475 $trackingforums[$forum->id] = $forum;
1479 if (count($trackingforums) > 0) {
1480 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1481 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1482 ' FROM {forum_posts} p '.
1483 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1484 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1485 $params = array($USER->id);
1487 foreach ($trackingforums as $track) {
1488 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1489 $params[] = $track->id;
1490 if (isset($SESSION->currentgroup[$track->course])) {
1491 $groupid = $SESSION->currentgroup[$track->course];
1493 // get first groupid
1494 $groupids = groups_get_all_groups($track->course, $USER->id);
1497 $groupid = key($groupids);
1498 $SESSION->currentgroup[$track->course] = $groupid;
1504 $params[] = $groupid;
1506 $sql = substr($sql,0,-3); // take off the last OR
1507 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1508 $params[] = $cutoffdate;
1510 if (!$unread = $DB->get_records_sql($sql, $params)) {
1517 if (empty($unread) and empty($forumsnewposts)) {
1521 $strforum = get_string('modulename','forum');
1523 foreach ($forums as $forum) {
1527 $showunread = false;
1528 // either we have something from logs, or trackposts, or nothing.
1529 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1530 $count = $forumsnewposts[$forum->id]->count;
1532 if (array_key_exists($forum->id,$unread)) {
1533 $thisunread = $unread[$forum->id]->count;
1536 if ($count > 0 || $thisunread > 0) {
1537 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1538 $forum->name.'</a></div>';
1539 $str .= '<div class="info"><span class="postsincelogin">';
1540 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1541 if (!empty($showunread)) {
1542 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1544 $str .= '</div></div>';
1547 if (!array_key_exists($forum->course,$htmlarray)) {
1548 $htmlarray[$forum->course] = array();
1550 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1551 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1553 $htmlarray[$forum->course]['forum'] .= $str;
1559 * Given a course and a date, prints a summary of all the new
1560 * messages posted in the course since that date
1565 * @uses CONTEXT_MODULE
1566 * @uses VISIBLEGROUPS
1567 * @param object $course
1568 * @param bool $viewfullnames capability
1569 * @param int $timestart
1570 * @return bool success
1572 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1573 global $CFG, $USER, $DB, $OUTPUT;
1575 // do not use log table if possible, it may be huge and is expensive to join with other tables
1577 $allnamefields = user_picture::fields('u', null, 'duserid');
1578 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1579 d.timestart, d.timeend, $allnamefields
1580 FROM {forum_posts} p
1581 JOIN {forum_discussions} d ON d.id = p.discussion
1582 JOIN {forum} f ON f.id = d.forum
1583 JOIN {user} u ON u.id = p.userid
1584 WHERE p.created > ? AND f.course = ?
1585 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1589 $modinfo = get_fast_modinfo($course);
1591 $groupmodes = array();
1594 $strftimerecent = get_string('strftimerecent');
1596 $printposts = array();
1597 foreach ($posts as $post) {
1598 if (!isset($modinfo->instances['forum'][$post->forum])) {
1602 $cm = $modinfo->instances['forum'][$post->forum];
1603 if (!$cm->uservisible) {
1606 $context = context_module::instance($cm->id);
1608 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1612 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1613 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1614 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1619 // Check that the user can see the discussion.
1620 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1621 $printposts[] = $post;
1631 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1632 echo "\n<ul class='unlist'>\n";
1634 foreach ($printposts as $post) {
1635 $subjectclass = empty($post->parent) ? ' bold' : '';
1637 echo '<li><div class="head">'.
1638 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1639 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1641 echo '<div class="info'.$subjectclass.'">';
1642 if (empty($post->parent)) {
1643 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1645 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&parent='.$post->parent.'#p'.$post->id.'">';
1647 $post->subject = break_up_long_words(format_string($post->subject, true));
1648 echo $post->subject;
1649 echo "</a>\"</div></li>\n";
1658 * Return grade for given user or all users.
1662 * @param object $forum
1663 * @param int $userid optional user id, 0 means all users
1664 * @return array array of grades, false if none
1666 function forum_get_user_grades($forum, $userid = 0) {
1669 require_once($CFG->dirroot.'/rating/lib.php');
1671 $ratingoptions = new stdClass;
1672 $ratingoptions->component = 'mod_forum';
1673 $ratingoptions->ratingarea = 'post';
1675 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1676 $ratingoptions->modulename = 'forum';
1677 $ratingoptions->moduleid = $forum->id;
1678 $ratingoptions->userid = $userid;
1679 $ratingoptions->aggregationmethod = $forum->assessed;
1680 $ratingoptions->scaleid = $forum->scale;
1681 $ratingoptions->itemtable = 'forum_posts';
1682 $ratingoptions->itemtableusercolumn = 'userid';
1684 $rm = new rating_manager();
1685 return $rm->get_user_grades($ratingoptions);
1689 * Update activity grades
1692 * @param object $forum
1693 * @param int $userid specific user only, 0 means all
1694 * @param boolean $nullifnone return null if grade does not exist
1697 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1699 require_once($CFG->libdir.'/gradelib.php');
1701 if (!$forum->assessed) {
1702 forum_grade_item_update($forum);
1704 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1705 forum_grade_item_update($forum, $grades);
1707 } else if ($userid and $nullifnone) {
1708 $grade = new stdClass();
1709 $grade->userid = $userid;
1710 $grade->rawgrade = NULL;
1711 forum_grade_item_update($forum, $grade);
1714 forum_grade_item_update($forum);
1719 * Create/update grade item for given forum
1722 * @uses GRADE_TYPE_NONE
1723 * @uses GRADE_TYPE_VALUE
1724 * @uses GRADE_TYPE_SCALE
1725 * @param stdClass $forum Forum object with extra cmidnumber
1726 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1727 * @return int 0 if ok
1729 function forum_grade_item_update($forum, $grades=NULL) {
1731 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1732 require_once($CFG->libdir.'/gradelib.php');
1735 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1737 if (!$forum->assessed or $forum->scale == 0) {
1738 $params['gradetype'] = GRADE_TYPE_NONE;
1740 } else if ($forum->scale > 0) {
1741 $params['gradetype'] = GRADE_TYPE_VALUE;
1742 $params['grademax'] = $forum->scale;
1743 $params['grademin'] = 0;
1745 } else if ($forum->scale < 0) {
1746 $params['gradetype'] = GRADE_TYPE_SCALE;
1747 $params['scaleid'] = -$forum->scale;
1750 if ($grades === 'reset') {
1751 $params['reset'] = true;
1755 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1759 * Delete grade item for given forum
1762 * @param stdClass $forum Forum object
1763 * @return grade_item
1765 function forum_grade_item_delete($forum) {
1767 require_once($CFG->libdir.'/gradelib.php');
1769 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1774 * This function returns if a scale is being used by one forum
1777 * @param int $forumid
1778 * @param int $scaleid negative number
1781 function forum_scale_used ($forumid,$scaleid) {
1785 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1787 if (!empty($rec) && !empty($scaleid)) {
1795 * Checks if scale is being used by any instance of forum
1797 * This is used to find out if scale used anywhere
1800 * @param $scaleid int
1801 * @return boolean True if the scale is used by any forum
1803 function forum_scale_used_anywhere($scaleid) {
1805 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1812 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1815 * Gets a post with all info ready for forum_print_post
1816 * Most of these joins are just to get the forum id
1820 * @param int $postid
1821 * @return mixed array of posts or false
1823 function forum_get_post_full($postid) {
1826 $allnames = get_all_user_name_fields(true, 'u');
1827 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1828 FROM {forum_posts} p
1829 JOIN {forum_discussions} d ON p.discussion = d.id
1830 LEFT JOIN {user} u ON p.userid = u.id
1831 WHERE p.id = ?", array($postid));
1835 * Gets all posts in discussion including top parent.
1840 * @param int $discussionid
1841 * @param string $sort
1842 * @param bool $tracking does user track the forum?
1843 * @return array of posts
1845 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1846 global $CFG, $DB, $USER;
1854 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1855 $tr_sel = ", fr.id AS postread";
1856 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1857 $params[] = $USER->id;
1860 $allnames = get_all_user_name_fields(true, 'u');
1861 $params[] = $discussionid;
1862 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1863 FROM {forum_posts} p
1864 LEFT JOIN {user} u ON p.userid = u.id
1866 WHERE p.discussion = ?
1867 ORDER BY $sort", $params)) {
1871 foreach ($posts as $pid=>$p) {
1873 if (forum_tp_is_post_old($p)) {
1874 $posts[$pid]->postread = true;
1880 if (!isset($posts[$p->parent])) {
1881 continue; // parent does not exist??
1883 if (!isset($posts[$p->parent]->children)) {
1884 $posts[$p->parent]->children = array();
1886 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1893 * An array of forum objects that the user is allowed to read/search through.
1898 * @param int $userid
1899 * @param int $courseid if 0, we look for forums throughout the whole site.
1900 * @return array of forum objects, or false if no matches
1901 * Forum objects have the following attributes:
1902 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1903 * viewhiddentimedposts
1905 function forum_get_readable_forums($userid, $courseid=0) {
1907 global $CFG, $DB, $USER;
1908 require_once($CFG->dirroot.'/course/lib.php');
1910 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1911 print_error('notinstalled', 'forum');
1915 $courses = $DB->get_records('course', array('id' => $courseid));
1917 // If no course is specified, then the user can see SITE + his courses.
1918 $courses1 = $DB->get_records('course', array('id' => SITEID));
1919 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1920 $courses = array_merge($courses1, $courses2);
1926 $readableforums = array();
1928 foreach ($courses as $course) {
1930 $modinfo = get_fast_modinfo($course);
1932 if (empty($modinfo->instances['forum'])) {
1937 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1939 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1940 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1943 $context = context_module::instance($cm->id);
1944 $forum = $courseforums[$forumid];
1945 $forum->context = $context;
1948 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1953 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1955 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1956 $forum->onlygroups[] = -1;
1959 /// hidden timed discussions
1960 $forum->viewhiddentimedposts = true;
1961 if (!empty($CFG->forum_enabletimedposts)) {
1962 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1963 $forum->viewhiddentimedposts = false;
1968 if ($forum->type == 'qanda'
1969 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1971 // We need to check whether the user has posted in the qanda forum.
1972 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1973 // the user is allowed to see in this forum.
1974 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1975 foreach ($discussionspostedin as $d) {
1976 $forum->onlydiscussions[] = $d->id;
1981 $readableforums[$forum->id] = $forum;
1986 } // End foreach $courses
1988 return $readableforums;
1992 * Returns a list of posts found using an array of search terms.
1997 * @param array $searchterms array of search terms, e.g. word +word -word
1998 * @param int $courseid if 0, we search through the whole site
1999 * @param int $limitfrom
2000 * @param int $limitnum
2001 * @param int &$totalcount
2002 * @param string $extrasql
2003 * @return array|bool Array of posts found or false
2005 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2006 &$totalcount, $extrasql='') {
2007 global $CFG, $DB, $USER;
2008 require_once($CFG->libdir.'/searchlib.php');
2010 $forums = forum_get_readable_forums($USER->id, $courseid);
2012 if (count($forums) == 0) {
2017 $now = round(time(), -2); // db friendly
2019 $fullaccess = array();
2023 foreach ($forums as $forumid => $forum) {
2026 if (!$forum->viewhiddentimedposts) {
2027 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2028 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2032 $context = $forum->context;
2034 if ($forum->type == 'qanda'
2035 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2036 if (!empty($forum->onlydiscussions)) {
2037 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2038 $params = array_merge($params, $discussionid_params);
2039 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2041 $select[] = "p.parent = 0";
2045 if (!empty($forum->onlygroups)) {
2046 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2047 $params = array_merge($params, $groupid_params);
2048 $select[] = "d.groupid $groupid_sql";
2052 $selects = implode(" AND ", $select);
2053 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2054 $params['forum'.$forumid] = $forumid;
2056 $fullaccess[] = $forumid;
2061 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2062 $params = array_merge($params, $fullid_params);
2063 $where[] = "(d.forum $fullid_sql)";
2066 $selectdiscussion = "(".implode(" OR ", $where).")";
2068 $messagesearch = '';
2071 // Need to concat these back together for parser to work.
2072 foreach($searchterms as $searchterm){
2073 if ($searchstring != '') {
2074 $searchstring .= ' ';
2076 $searchstring .= $searchterm;
2079 // We need to allow quoted strings for the search. The quotes *should* be stripped
2080 // by the parser, but this should be examined carefully for security implications.
2081 $searchstring = str_replace("\\\"","\"",$searchstring);
2082 $parser = new search_parser();
2083 $lexer = new search_lexer($parser);
2085 if ($lexer->parse($searchstring)) {
2086 $parsearray = $parser->get_parsed_array();
2087 // Experimental feature under 1.8! MDL-8830
2088 // Use alternative text searches if defined
2089 // This feature only works under mysql until properly implemented for other DBs
2090 // Requires manual creation of text index for forum_posts before enabling it:
2091 // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
2092 // Experimental feature under 1.8! MDL-8830
2093 if (!empty($CFG->forum_usetextsearches)) {
2094 list($messagesearch, $msparams) = search_generate_text_SQL($parsearray, 'p.message', 'p.subject',
2095 'p.userid', 'u.id', 'u.firstname',
2096 'u.lastname', 'p.modified', 'd.forum');
2098 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2099 'p.userid', 'u.id', 'u.firstname',
2100 'u.lastname', 'p.modified', 'd.forum');
2102 $params = array_merge($params, $msparams);
2105 $fromsql = "{forum_posts} p,
2106 {forum_discussions} d,
2109 $selectsql = " $messagesearch
2110 AND p.discussion = d.id
2112 AND $selectdiscussion
2115 $countsql = "SELECT COUNT(*)
2119 $allnames = get_all_user_name_fields(true, 'u');
2120 $searchsql = "SELECT p.*,
2128 ORDER BY p.modified DESC";
2130 $totalcount = $DB->count_records_sql($countsql, $params);
2132 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2136 * Returns a list of all new posts that have not been mailed yet
2138 * @param int $starttime posts created after this time
2139 * @param int $endtime posts created before this
2140 * @param int $now used for timed discussions only
2143 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2147 $params['mailed'] = FORUM_MAILED_PENDING;
2148 $params['ptimestart'] = $starttime;
2149 $params['ptimeend'] = $endtime;
2150 $params['mailnow'] = 1;
2152 if (!empty($CFG->forum_enabletimedposts)) {
2156 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2157 $params['dtimestart'] = $now;
2158 $params['dtimeend'] = $now;
2163 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2164 FROM {forum_posts} p
2165 JOIN {forum_discussions} d ON d.id = p.discussion
2166 WHERE p.mailed = :mailed
2167 AND p.created >= :ptimestart
2168 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2170 ORDER BY p.modified ASC", $params);
2174 * Marks posts before a certain time as being mailed already
2178 * @param int $endtime
2179 * @param int $now Defaults to time()
2182 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2190 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2191 $params['now'] = $now;
2192 $params['endtime'] = $endtime;
2193 $params['mailnow'] = 1;
2194 $params['mailedpending'] = FORUM_MAILED_PENDING;
2196 if (empty($CFG->forum_enabletimedposts)) {
2197 return $DB->execute("UPDATE {forum_posts}
2198 SET mailed = :mailedsuccess
2199 WHERE (created < :endtime OR mailnow = :mailnow)
2200 AND mailed = :mailedpending", $params);
2202 return $DB->execute("UPDATE {forum_posts}
2203 SET mailed = :mailedsuccess
2204 WHERE discussion NOT IN (SELECT d.id
2205 FROM {forum_discussions} d
2206 WHERE d.timestart > :now)
2207 AND (created < :endtime OR mailnow = :mailnow)
2208 AND mailed = :mailedpending", $params);
2213 * Get all the posts for a user in a forum suitable for forum_print_post
2217 * @uses CONTEXT_MODULE
2220 function forum_get_user_posts($forumid, $userid) {
2224 $params = array($forumid, $userid);
2226 if (!empty($CFG->forum_enabletimedposts)) {
2227 $cm = get_coursemodule_from_instance('forum', $forumid);
2228 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2230 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2236 $allnames = get_all_user_name_fields(true, 'u');
2237 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2239 JOIN {forum_discussions} d ON d.forum = f.id
2240 JOIN {forum_posts} p ON p.discussion = d.id
2241 JOIN {user} u ON u.id = p.userid
2245 ORDER BY p.modified ASC", $params);
2249 * Get all the discussions user participated in
2253 * @uses CONTEXT_MODULE
2254 * @param int $forumid
2255 * @param int $userid
2256 * @return array Array or false
2258 function forum_get_user_involved_discussions($forumid, $userid) {
2262 $params = array($forumid, $userid);
2263 if (!empty($CFG->forum_enabletimedposts)) {
2264 $cm = get_coursemodule_from_instance('forum', $forumid);
2265 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2267 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2273 return $DB->get_records_sql("SELECT DISTINCT d.*
2275 JOIN {forum_discussions} d ON d.forum = f.id
2276 JOIN {forum_posts} p ON p.discussion = d.id
2279 $timedsql", $params);
2283 * Get all the posts for a user in a forum suitable for forum_print_post
2287 * @param int $forumid
2288 * @param int $userid
2289 * @return array of counts or false
2291 function forum_count_user_posts($forumid, $userid) {
2295 $params = array($forumid, $userid);
2296 if (!empty($CFG->forum_enabletimedposts)) {
2297 $cm = get_coursemodule_from_instance('forum', $forumid);
2298 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2300 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2306 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2308 JOIN {forum_discussions} d ON d.forum = f.id
2309 JOIN {forum_posts} p ON p.discussion = d.id
2310 JOIN {user} u ON u.id = p.userid
2313 $timedsql", $params);
2317 * Given a log entry, return the forum post details for it.
2321 * @param object $log
2322 * @return array|null
2324 function forum_get_post_from_log($log) {
2327 $allnames = get_all_user_name_fields(true, 'u');
2328 if ($log->action == "add post") {
2330 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2331 FROM {forum_discussions} d,
2336 AND d.id = p.discussion
2338 AND u.deleted <> '1'
2339 AND f.id = d.forum", array($log->info));
2342 } else if ($log->action == "add discussion") {
2344 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2345 FROM {forum_discussions} d,
2350 AND d.firstpost = p.id
2352 AND u.deleted <> '1'
2353 AND f.id = d.forum", array($log->info));
2359 * Given a discussion id, return the first post from the discussion
2363 * @param int $dicsussionid
2366 function forum_get_firstpost_from_discussion($discussionid) {
2369 return $DB->get_record_sql("SELECT p.*
2370 FROM {forum_discussions} d,
2373 AND d.firstpost = p.id ", array($discussionid));
2377 * Returns an array of counts of replies to each discussion
2381 * @param int $forumid
2382 * @param string $forumsort
2385 * @param int $perpage
2388 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2394 } else if ($page != -1) {
2395 $limitfrom = $page*$perpage;
2396 $limitnum = $perpage;
2402 if ($forumsort == "") {
2407 $orderby = "ORDER BY $forumsort";
2408 $groupby = ", ".strtolower($forumsort);
2409 $groupby = str_replace('desc', '', $groupby);
2410 $groupby = str_replace('asc', '', $groupby);
2413 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2414 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2415 FROM {forum_posts} p
2416 JOIN {forum_discussions} d ON p.discussion = d.id
2417 WHERE p.parent > 0 AND d.forum = ?
2418 GROUP BY p.discussion";
2419 return $DB->get_records_sql($sql, array($forumid));
2422 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2423 FROM {forum_posts} p
2424 JOIN {forum_discussions} d ON p.discussion = d.id
2426 GROUP BY p.discussion $groupby
2428 return $DB->get_records_sql("SELECT * FROM ($sql) sq", array($forumid), $limitfrom, $limitnum);
2436 * @staticvar array $cache
2437 * @param object $forum
2439 * @param object $course
2442 function forum_count_discussions($forum, $cm, $course) {
2443 global $CFG, $DB, $USER;
2445 static $cache = array();
2447 $now = round(time(), -2); // db cache friendliness
2449 $params = array($course->id);
2451 if (!isset($cache[$course->id])) {
2452 if (!empty($CFG->forum_enabletimedposts)) {
2453 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2460 $sql = "SELECT f.id, COUNT(d.id) as dcount
2462 JOIN {forum_discussions} d ON d.forum = f.id
2467 if ($counts = $DB->get_records_sql($sql, $params)) {
2468 foreach ($counts as $count) {
2469 $counts[$count->id] = $count->dcount;
2471 $cache[$course->id] = $counts;
2473 $cache[$course->id] = array();
2477 if (empty($cache[$course->id][$forum->id])) {
2481 $groupmode = groups_get_activity_groupmode($cm, $course);
2483 if ($groupmode != SEPARATEGROUPS) {
2484 return $cache[$course->id][$forum->id];
2487 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2488 return $cache[$course->id][$forum->id];
2491 require_once($CFG->dirroot.'/course/lib.php');
2493 $modinfo = get_fast_modinfo($course);
2495 $mygroups = $modinfo->get_groups($cm->groupingid);
2497 // add all groups posts
2500 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2501 $params[] = $forum->id;
2503 if (!empty($CFG->forum_enabletimedposts)) {
2504 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2511 $sql = "SELECT COUNT(d.id)
2512 FROM {forum_discussions} d
2513 WHERE d.groupid $mygroups_sql AND d.forum = ?
2516 return $DB->get_field_sql($sql, $params);
2520 * Get all discussions in a forum
2525 * @uses CONTEXT_MODULE
2526 * @uses VISIBLEGROUPS
2528 * @param string $forumsort
2529 * @param bool $fullpost
2530 * @param int $unused
2532 * @param bool $userlastmodified
2534 * @param int $perpage
2537 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2538 global $CFG, $DB, $USER;
2542 $now = round(time(), -2);
2543 $params = array($cm->instance);
2545 $modcontext = context_module::instance($cm->id);
2547 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2551 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2553 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2554 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2558 $timelimit .= " OR d.userid = ?";
2559 $params[] = $USER->id;
2568 } else if ($page != -1) {
2569 $limitfrom = $page*$perpage;
2570 $limitnum = $perpage;
2576 $groupmode = groups_get_activity_groupmode($cm);
2577 $currentgroup = groups_get_activity_group($cm);
2580 if (empty($modcontext)) {
2581 $modcontext = context_module::instance($cm->id);
2584 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2585 if ($currentgroup) {
2586 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2587 $params[] = $currentgroup;
2593 //seprate groups without access all
2594 if ($currentgroup) {
2595 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2596 $params[] = $currentgroup;
2598 $groupselect = "AND d.groupid = -1";
2606 if (empty($forumsort)) {
2607 $forumsort = "d.timemodified DESC";
2609 if (empty($fullpost)) {
2610 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2615 if (empty($userlastmodified)) { // We don't need to know this
2619 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
2620 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2623 $allnames = get_all_user_name_fields(true, 'u');
2624 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2625 u.email, u.picture, u.imagealt $umfields
2626 FROM {forum_discussions} d
2627 JOIN {forum_posts} p ON p.discussion = d.id
2628 JOIN {user} u ON p.userid = u.id
2630 WHERE d.forum = ? AND p.parent = 0
2631 $timelimit $groupselect
2632 ORDER BY $forumsort";
2633 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2637 * Gets the neighbours (previous and next) of a discussion.
2639 * The calculation is based on the timemodified of the discussion and does not handle
2640 * the neighbours having an identical timemodified. The reason is that we do not have any
2641 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2644 * Please note that this does not check whether or not the discussion passed is accessible
2645 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2646 * the returned neighbours are checked and are accessible to the current user.
2648 * @param object $cm The CM record.
2649 * @param object $discussion The discussion record.
2650 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2651 * they contain the record with minimal information such as 'id' and 'name'.
2652 * When the neighbour is not found the value is false.
2654 function forum_get_discussion_neighbours($cm, $discussion) {
2655 global $CFG, $DB, $USER;
2657 if ($cm->instance != $discussion->forum) {
2658 throw new coding_exception('Discussion is not part of the same forum.');
2661 $neighbours = array('prev' => false, 'next' => false);
2662 $now = round(time(), -2);
2665 $modcontext = context_module::instance($cm->id);
2666 $groupmode = groups_get_activity_groupmode($cm);
2667 $currentgroup = groups_get_activity_group($cm);
2669 // Users must fulfill timed posts.
2671 if (!empty($CFG->forum_enabletimedposts)) {
2672 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2673 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2674 $params['tltimestart'] = $now;
2675 $params['tltimeend'] = $now;
2677 $timelimit .= ' OR d.userid = :tluserid';
2678 $params['tluserid'] = $USER->id;
2684 // Limiting to posts accessible according to groups.
2687 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2688 if ($currentgroup) {
2689 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2690 $params['groupid'] = $currentgroup;
2693 if ($currentgroup) {
2694 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2695 $params['groupid'] = $currentgroup;
2697 $groupselect = 'AND d.groupid = -1';
2702 $params['forumid'] = $cm->instance;
2703 $params['discid'] = $discussion->id;
2704 $params['disctimemodified'] = $discussion->timemodified;
2706 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2707 FROM {forum_discussions} d
2708 WHERE d.forum = :forumid
2713 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2714 ORDER BY d.timemodified DESC";
2716 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2717 ORDER BY d.timemodified ASC";
2719 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2720 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2730 * @uses CONTEXT_MODULE
2731 * @uses VISIBLEGROUPS
2735 function forum_get_discussions_unread($cm) {
2736 global $CFG, $DB, $USER;
2738 $now = round(time(), -2);
2739 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2742 $groupmode = groups_get_activity_groupmode($cm);
2743 $currentgroup = groups_get_activity_group($cm);
2746 $modcontext = context_module::instance($cm->id);
2748 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2749 if ($currentgroup) {
2750 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2751 $params['currentgroup'] = $currentgroup;
2757 //separate groups without access all
2758 if ($currentgroup) {
2759 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2760 $params['currentgroup'] = $currentgroup;
2762 $groupselect = "AND d.groupid = -1";
2769 if (!empty($CFG->forum_enabletimedposts)) {
2770 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2771 $params['now1'] = $now;
2772 $params['now2'] = $now;
2777 $sql = "SELECT d.id, COUNT(p.id) AS unread
2778 FROM {forum_discussions} d
2779 JOIN {forum_posts} p ON p.discussion = d.id
2780 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2781 WHERE d.forum = {$cm->instance}
2782 AND p.modified >= :cutoffdate AND r.id is NULL
2786 $params['cutoffdate'] = $cutoffdate;
2788 if ($unreads = $DB->get_records_sql($sql, $params)) {
2789 foreach ($unreads as $unread) {
2790 $unreads[$unread->id] = $unread->unread;
2802 * @uses CONEXT_MODULE
2803 * @uses VISIBLEGROUPS
2807 function forum_get_discussions_count($cm) {
2808 global $CFG, $DB, $USER;
2810 $now = round(time(), -2);
2811 $params = array($cm->instance);
2812 $groupmode = groups_get_activity_groupmode($cm);
2813 $currentgroup = groups_get_activity_group($cm);
2816 $modcontext = context_module::instance($cm->id);
2818 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2819 if ($currentgroup) {
2820 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2821 $params[] = $currentgroup;
2827 //seprate groups without access all
2828 if ($currentgroup) {
2829 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2830 $params[] = $currentgroup;
2832 $groupselect = "AND d.groupid = -1";
2839 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2843 if (!empty($CFG->forum_enabletimedposts)) {
2845 $modcontext = context_module::instance($cm->id);
2847 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2848 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2852 $timelimit .= " OR d.userid = ?";
2853 $params[] = $USER->id;
2859 $sql = "SELECT COUNT(d.id)
2860 FROM {forum_discussions} d
2861 JOIN {forum_posts} p ON p.discussion = d.id
2862 WHERE d.forum = ? AND p.parent = 0
2863 $groupselect $timelimit";
2865 return $DB->get_field_sql($sql, $params);
2869 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2875 * @param int $courseid
2876 * @param string $type
2878 function forum_get_course_forum($courseid, $type) {
2879 // How to set up special 1-per-course forums
2880 global $CFG, $DB, $OUTPUT, $USER;
2882 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2883 // There should always only be ONE, but with the right combination of
2884 // errors there might be more. In this case, just return the oldest one (lowest ID).
2885 foreach ($forums as $forum) {
2886 return $forum; // ie the first one
2890 // Doesn't exist, so create one now.
2891 $forum = new stdClass();
2892 $forum->course = $courseid;
2893 $forum->type = "$type";
2894 if (!empty($USER->htmleditor)) {
2895 $forum->introformat = $USER->htmleditor;
2897 switch ($forum->type) {
2899 $forum->name = get_string("namenews", "forum");
2900 $forum->intro = get_string("intronews", "forum");
2901 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2902 $forum->assessed = 0;
2903 if ($courseid == SITEID) {
2904 $forum->name = get_string("sitenews");
2905 $forum->forcesubscribe = 0;
2909 $forum->name = get_string("namesocial", "forum");
2910 $forum->intro = get_string("introsocial", "forum");
2911 $forum->assessed = 0;
2912 $forum->forcesubscribe = 0;
2915 $forum->name = get_string('blogforum', 'forum');
2916 $forum->intro = get_string('introblog', 'forum');
2917 $forum->assessed = 0;
2918 $forum->forcesubscribe = 0;
2921 echo $OUTPUT->notification("That forum type doesn't exist!");
2926 $forum->timemodified = time();
2927 $forum->id = $DB->insert_record("forum", $forum);
2929 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2930 echo $OUTPUT->notification("Could not find forum module!!");
2933 $mod = new stdClass();
2934 $mod->course = $courseid;
2935 $mod->module = $module->id;
2936 $mod->instance = $forum->id;
2938 include_once("$CFG->dirroot/course/lib.php");
2939 if (! $mod->coursemodule = add_course_module($mod) ) {
2940 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2943 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
2944 return $DB->get_record("forum", array("id" => "$forum->id"));
2949 * Given the data about a posting, builds up the HTML to display it and
2950 * returns the HTML in a string. This is designed for sending via HTML email.
2953 * @param object $course
2955 * @param object $forum
2956 * @param object $discussion
2957 * @param object $post
2958 * @param object $userform
2959 * @param object $userto
2960 * @param bool $ownpost
2961 * @param bool $reply
2964 * @param string $footer
2967 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
2968 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
2970 global $CFG, $OUTPUT;
2972 $modcontext = context_module::instance($cm->id);
2974 if (!isset($userto->viewfullnames[$forum->id])) {
2975 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
2977 $viewfullnames = $userto->viewfullnames[$forum->id];
2980 // add absolute file links
2981 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
2983 // format the post body
2984 $options = new stdClass();
2985 $options->para = true;
2986 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
2988 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
2990 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
2991 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
2994 if ($post->parent) {
2995 $output .= '<td class="topic">';
2997 $output .= '<td class="topic starter">';
2999 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3001 $fullname = fullname($userfrom, $viewfullnames);
3002 $by = new stdClass();
3003 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&course='.$course->id.'">'.$fullname.'</a>';
3004 $by->date = userdate($post->modified, '', $userto->timezone);
3005 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3007 $output .= '</td></tr>';
3009 $output .= '<tr><td class="left side" valign="top">';
3011 if (isset($userfrom->groups)) {
3012 $groups = $userfrom->groups[$forum->id];
3014 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3018 $output .= print_group_picture($groups, $course->id, false, true, true);
3020 $output .= ' ';
3023 $output .= '</td><td class="content">';
3025 $attachments = forum_print_attachments($post, $cm, 'html');
3026 if ($attachments !== '') {
3027 $output .= '<div class="attachments">';
3028 $output .= $attachments;
3029 $output .= '</div>';
3032 $output .= $formattedtext;
3035 $commands = array();
3037 if ($post->parent) {
3038 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3039 $post->discussion.'&parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3043 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3044 get_string('reply', 'forum').'</a>';
3047 $output .= '<div class="commands">';
3048 $output .= implode(' | ', $commands);
3049 $output .= '</div>';
3051 // Context link to post if required
3053 $output .= '<div class="link">';
3054 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3055 get_string('postincontext', 'forum').'</a>';
3056 $output .= '</div>';
3060 $output .= '<div class="footer">'.$footer.'</div>';
3062 $output .= '</td></tr></table>'."\n\n";
3068 * Print a forum post
3072 * @uses FORUM_MODE_THREADED
3073 * @uses PORTFOLIO_FORMAT_PLAINHTML
3074 * @uses PORTFOLIO_FORMAT_FILE
3075 * @uses PORTFOLIO_FORMAT_RICHHTML
3076 * @uses PORTFOLIO_ADD_TEXT_LINK
3077 * @uses CONTEXT_MODULE
3078 * @param object $post The post to print.
3079 * @param object $discussion
3080 * @param object $forum
3082 * @param object $course
3083 * @param boolean $ownpost Whether this post belongs to the current user.
3084 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3085 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3086 * @param string $footer Extra stuff to print after the message.
3087 * @param string $highlight Space-separated list of terms to highlight.
3088 * @param int $post_read true, false or -99. If we already know whether this user
3089 * has read this post, pass that in, otherwise, pass in -99, and this
3090 * function will work it out.
3091 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3092 * the current user can't see this post, if this argument is true
3093 * (the default) then print a dummy 'you can't see this post' post.
3094 * If false, don't output anything at all.
3095 * @param bool|null $istracked
3098 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3099 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3100 global $USER, $CFG, $OUTPUT;
3102 require_once($CFG->libdir . '/filelib.php');
3107 $modcontext = context_module::instance($cm->id);
3109 $post->course = $course->id;
3110 $post->forum = $forum->id;
3111 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3112 if (!empty($CFG->enableplagiarism)) {
3113 require_once($CFG->libdir.'/plagiarismlib.php');
3114 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3115 'content' => $post->message,
3117 'course' => $post->course,
3118 'forum' => $post->forum));
3122 if (!isset($cm->cache)) {
3123 $cm->cache = new stdClass;
3126 if (!isset($cm->cache->caps)) {
3127 $cm->cache->caps = array();
3128 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3129 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3130 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3131 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3132 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3133 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3134 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3135 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3136 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3139 if (!isset($cm->uservisible)) {
3140 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3143 if ($istracked && is_null($postisread)) {
3144 $postisread = forum_tp_is_post_read($USER->id, $post);
3147 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3149 if (!$dummyifcantsee) {
3156 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3157 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3159 'aria-label' => get_string('hiddenforumpost', 'forum')));
3160 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3161 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3162 if ($post->parent) {
3163 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3165 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3167 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3168 'role' => 'header')); // Subject.
3169 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3170 'role' => 'header')); // Author.
3171 $output .= html_writer::end_tag('div');
3172 $output .= html_writer::end_tag('div'); // row
3173 $output .= html_writer::start_tag('div', array('class'=>'row'));
3174 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3175 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3176 $output .= html_writer::end_tag('div'); // row
3177 $output .= html_writer::end_tag('div'); // forumpost
3187 $str = new stdClass;
3188 $str->edit = get_string('edit', 'forum');
3189 $str->delete = get_string('delete', 'forum');
3190 $str->reply = get_string('reply', 'forum');
3191 $str->parent = get_string('parent', 'forum');
3192 $str->pruneheading = get_string('pruneheading', 'forum');
3193 $str->prune = get_string('prune', 'forum');
3194 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3195 $str->markread = get_string('markread', 'forum');
3196 $str->markunread = get_string('markunread', 'forum');
3199 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3201 // Build an object that represents the posting user
3202 $postuser = new stdClass;
3203 $postuserfields = explode(',', user_picture::fields());
3204 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3205 $postuser->id = $post->userid;
3206 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3207 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3209 // Prepare the groups the posting user belongs to
3210 if (isset($cm->cache->usersgroups)) {
3212 if (isset($cm->cache->usersgroups[$post->userid])) {
3213 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3214 $groups[$gid] = $cm->cache->groups[$gid];
3218 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3221 // Prepare the attachements for the post, files then images
3222 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3224 // Determine if we need to shorten this post
3225 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3228 // Prepare an array of commands
3229 $commands = array();
3231 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3232 // Don't display the mark read / unread controls in this case.
3233 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3234 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3235 $text = $str->markunread;
3237 $url->param('mark', 'read');
3238 $text = $str->markread;
3240 if ($str->displaymode == FORUM_MODE_THREADED) {
3241 $url->param('parent', $post->parent);
3243 $url->set_anchor('p'.$post->id);
3245 $commands[] = array('url'=>$url, 'text'=>$text);
3248 // Zoom in to the parent specifically
3249 if ($post->parent) {
3250 $url = new moodle_url($discussionlink);
3251 if ($str->displaymode == FORUM_MODE_THREADED) {
3252 $url->param('parent', $post->parent);
3254 $url->set_anchor('p'.$post->parent);
3256 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3259 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3260 $age = time() - $post->created;
3261 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3265 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3266 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3267 // The first post in single simple is the forum description.
3268 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3270 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3271 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3274 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3275 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3278 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3279 // Do not allow deleting of first post in single simple type.
3280 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3281 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3285 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3288 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3289 $p = array('postid' => $post->id);
3290 require_once($CFG->libdir.'/portfoliolib.php');
3291 $button = new portfolio_add_button();
3292 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3293 if (empty($attachments)) {
3294 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3296 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3299 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3300 if (!empty($porfoliohtml)) {
3301 $commands[] = $porfoliohtml;
3304 // Finished building commands
3313 $forumpostclass = ' read';
3315 $forumpostclass = ' unread';
3316 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3319 // ignore trackign status if not tracked or tracked param missing
3320 $forumpostclass = '';
3324 if (empty($post->parent)) {
3325 $topicclass = ' firstpost starter';
3328 $postbyuser = new stdClass;
3329 $postbyuser->post = $post->subject;
3330 $postbyuser->user = $postuser->fullname;
3331 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3332 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3333 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3335 'aria-label' => $discussionbyuser));
3336 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3337 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3338 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3339 $output .= html_writer::end_tag('div');
3342 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3344 $postsubject = $post->subject;
3345 if (empty($post->subjectnoformat)) {
3346 $postsubject = format_string($postsubject);
3348 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject',
3349 'role' => 'heading',
3350 'aria-level' => '2'));
3352 $by = new stdClass();
3353 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3354 $by->date = userdate($post->modified);
3355 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3356 'role' => 'heading',
3357 'aria-level' => '2'));
3359 $output .= html_writer::end_tag('div'); //topic
3360 $output .= html_writer::end_tag('div'); //row
3362 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3363 $output .= html_writer::start_tag('div', array('class'=>'left'));
3367 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3369 if (empty($groupoutput)) {
3370 $groupoutput = ' ';
3372 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3374 $output .= html_writer::end_tag('div'); //left side
3375 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3376 $output .= html_writer::start_tag('div', array('class'=>'content'));
3378 $options = new stdClass;
3379 $options->para = false;
3380 $options->trusted = $post->messagetrust;
3381 $options->context = $modcontext;
3383 // Prepare shortened version by filtering the text then shortening it.
3384 $postclass = 'shortenedpost';
3385 $postcontent = format_text($post->message, $post->messageformat, $options);
3386 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3387 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3388 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3389 array('class'=>'post-word-count'));
3391 // Prepare whole post
3392 $postclass = 'fullpost';
3393 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3394 if (!empty($highlight)) {
3395 $postcontent = highlight($highlight, $postcontent);
3397 if (!empty($forum->displaywordcount)) {
3398 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3399 array('class'=>'post-word-count'));
3401 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3404 // Output the post content
3405 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3406 $output .= html_writer::end_tag('div'); // Content
3407 $output .= html_writer::end_tag('div'); // Content mask
3408 $output .= html_writer::end_tag('div'); // Row
3410 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3411 $output .= html_writer::tag('div',' ', array('class'=>'left'));
3412 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3414 if (!empty($attachments)) {
3415 $output .= html_writer::tag('div', $attachments, array('class' => 'attachments'));
3419 if (!empty($post->rating)) {
3420 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3423 // Output the commands
3424 $commandhtml = array();
3425 foreach ($commands as $command) {
3426 if (is_array($command)) {
3427 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3429 $commandhtml[] = $command;
3432 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3434 // Output link to post if required
3435 if ($link && forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3436 if ($post->replies == 1) {
3437 $replystring = get_string('repliesone', 'forum', $post->replies);
3439 $replystring = get_string('repliesmany', 'forum', $post->replies);
3442 $output .= html_writer::start_tag('div', array('class'=>'link'));
3443 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3444 $output .= ' ('.$replystring.')';
3445 $output .= html_writer::end_tag('div'); // link
3448 // Output footer if required
3450 $output .= html_writer::tag('div', $footer, array('class'=>'footer'));
3453 // Close remaining open divs
3454 $output .= html_writer::end_tag('div'); // content
3455 $output .= html_writer::end_tag('div'); // row
3456 $output .= html_writer::end_tag('div'); // forumpost
3458 // Mark the forum post as read if required
3459 if ($istracked && !$CFG->forum_usermarksread && !$postisread) {
3460 forum_tp_mark_post_read($USER->id, $post, $forum->id);
3471 * Return rating related permissions
3473 * @param string $options the context id
3474 * @return array an associative array of the user's rating permissions
3476 function forum_rating_permissions($contextid, $component, $ratingarea) {
3477 $context = context::instance_by_id($contextid, MUST_EXIST);
3478 if ($component != 'mod_forum' || $ratingarea != 'post') {
3479 // We don't know about this component/ratingarea so just return null to get the