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/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') || die();
26 /** Include required files */
27 require_once($CFG->libdir.'/filelib.php');
28 require_once($CFG->libdir.'/eventslib.php');
29 require_once($CFG->dirroot.'/user/selector/lib.php');
30 require_once($CFG->dirroot.'/mod/forum/post_form.php');
32 /// CONSTANTS ///////////////////////////////////////////////////////////
34 define('FORUM_MODE_FLATOLDEST', 1);
35 define('FORUM_MODE_FLATNEWEST', -1);
36 define('FORUM_MODE_THREADED', 2);
37 define('FORUM_MODE_NESTED', 3);
39 define('FORUM_CHOOSESUBSCRIBE', 0);
40 define('FORUM_FORCESUBSCRIBE', 1);
41 define('FORUM_INITIALSUBSCRIBE', 2);
42 define('FORUM_DISALLOWSUBSCRIBE',3);
44 define('FORUM_TRACKING_OFF', 0);
45 define('FORUM_TRACKING_OPTIONAL', 1);
46 define('FORUM_TRACKING_ON', 2);
48 if (!defined('FORUM_CRON_USER_CACHE')) {
49 /** Defines how many full user records are cached in forum cron. */
50 define('FORUM_CRON_USER_CACHE', 5000);
53 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
56 * Given an object containing all the necessary data,
57 * (defined by the form in mod_form.php) this function
58 * will create a new instance and return the id number
59 * of the new instance.
61 * @param stdClass $forum add forum instance
62 * @param mod_forum_mod_form $mform
63 * @return int intance id
65 function forum_add_instance($forum, $mform = null) {
68 $forum->timemodified = time();
70 if (empty($forum->assessed)) {
74 if (empty($forum->ratingtime) or empty($forum->assessed)) {
75 $forum->assesstimestart = 0;
76 $forum->assesstimefinish = 0;
79 $forum->id = $DB->insert_record('forum', $forum);
80 $modcontext = get_context_instance(CONTEXT_MODULE, $forum->coursemodule);
82 if ($forum->type == 'single') { // Create related discussion.
83 $discussion = new stdClass();
84 $discussion->course = $forum->course;
85 $discussion->forum = $forum->id;
86 $discussion->name = $forum->name;
87 $discussion->assessed = $forum->assessed;
88 $discussion->message = $forum->intro;
89 $discussion->messageformat = $forum->introformat;
90 $discussion->messagetrust = trusttext_trusted(get_context_instance(CONTEXT_COURSE, $forum->course));
91 $discussion->mailnow = false;
92 $discussion->groupid = -1;
96 $discussion->id = forum_add_discussion($discussion, null, $message);
98 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
99 // ugly hack - we need to copy the files somehow
100 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
101 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
103 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id,
104 mod_forum_post_form::attachment_options($forum), $post->message);
105 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
109 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
110 /// all users should be subscribed initially
111 /// Note: forum_get_potential_subscribers should take the forum context,
112 /// but that does not exist yet, becuase the forum is only half build at this
113 /// stage. However, because the forum is brand new, we know that there are
114 /// no role assignments or overrides in the forum context, so using the
115 /// course context gives the same list of users.
116 $users = forum_get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
117 foreach ($users as $user) {
118 forum_subscribe($user->id, $forum->id);
122 forum_grade_item_update($forum);
129 * Given an object containing all the necessary data,
130 * (defined by the form in mod_form.php) this function
131 * will update an existing instance with new data.
134 * @param object $forum forum instance (with magic quotes)
135 * @return bool success
137 function forum_update_instance($forum, $mform) {
138 global $DB, $OUTPUT, $USER;
140 $forum->timemodified = time();
141 $forum->id = $forum->instance;
143 if (empty($forum->assessed)) {
144 $forum->assessed = 0;
147 if (empty($forum->ratingtime) or empty($forum->assessed)) {
148 $forum->assesstimestart = 0;
149 $forum->assesstimefinish = 0;
152 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
154 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
155 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
156 // 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
157 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
158 forum_update_grades($forum); // recalculate grades for the forum
161 if ($forum->type == 'single') { // Update related discussion and post.
162 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
163 if (!empty($discussions)) {
164 if (count($discussions) > 1) {
165 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
167 $discussion = array_pop($discussions);
169 // try to recover by creating initial discussion - MDL-16262
170 $discussion = new stdClass();
171 $discussion->course = $forum->course;
172 $discussion->forum = $forum->id;
173 $discussion->name = $forum->name;
174 $discussion->assessed = $forum->assessed;
175 $discussion->message = $forum->intro;
176 $discussion->messageformat = $forum->introformat;
177 $discussion->messagetrust = true;
178 $discussion->mailnow = false;
179 $discussion->groupid = -1;
183 forum_add_discussion($discussion, null, $message);
185 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
186 print_error('cannotadd', 'forum');
189 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
190 print_error('cannotfindfirstpost', 'forum');
193 $cm = get_coursemodule_from_instance('forum', $forum->id);
194 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
196 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
197 // ugly hack - we need to copy the files somehow
198 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
199 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
201 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id,
202 mod_forum_post_form::editor_options(), $post->message);
205 $post->subject = $forum->name;
206 $post->message = $forum->intro;
207 $post->messageformat = $forum->introformat;
208 $post->messagetrust = trusttext_trusted($modcontext);
209 $post->modified = $forum->timemodified;
210 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities
212 $DB->update_record('forum_posts', $post);
213 $discussion->name = $forum->name;
214 $DB->update_record('forum_discussions', $discussion);
217 $DB->update_record('forum', $forum);
219 forum_grade_item_update($forum);
226 * Given an ID of an instance of this module,
227 * this function will permanently delete the instance
228 * and any data that depends on it.
231 * @param int $id forum instance id
232 * @return bool success
234 function forum_delete_instance($id) {
237 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
240 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
243 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
247 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
249 // now get rid of all files
250 $fs = get_file_storage();
251 $fs->delete_area_files($context->id);
255 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
256 foreach ($discussions as $discussion) {
257 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
263 if (!$DB->delete_records('forum_subscriptions', array('forum'=>$forum->id))) {
267 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
269 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
273 forum_grade_item_delete($forum);
280 * Indicates API features that the forum supports.
282 * @uses FEATURE_GROUPS
283 * @uses FEATURE_GROUPINGS
284 * @uses FEATURE_GROUPMEMBERSONLY
285 * @uses FEATURE_MOD_INTRO
286 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
287 * @uses FEATURE_COMPLETION_HAS_RULES
288 * @uses FEATURE_GRADE_HAS_GRADE
289 * @uses FEATURE_GRADE_OUTCOMES
290 * @param string $feature
291 * @return mixed True if yes (some features may use other values)
293 function forum_supports($feature) {
295 case FEATURE_GROUPS: return true;
296 case FEATURE_GROUPINGS: return true;
297 case FEATURE_GROUPMEMBERSONLY: return true;
298 case FEATURE_MOD_INTRO: return true;
299 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
300 case FEATURE_COMPLETION_HAS_RULES: return true;
301 case FEATURE_GRADE_HAS_GRADE: return true;
302 case FEATURE_GRADE_OUTCOMES: return true;
303 case FEATURE_RATE: return true;
304 case FEATURE_BACKUP_MOODLE2: return true;
305 case FEATURE_SHOW_DESCRIPTION: return true;
307 default: return null;
313 * Obtains the automatic completion state for this forum based on any conditions
318 * @param object $course Course
319 * @param object $cm Course-module
320 * @param int $userid User ID
321 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
322 * @return bool True if completed, false if not. (If no conditions, then return
323 * value depends on comparison type)
325 function forum_get_completion_state($course,$cm,$userid,$type) {
329 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
330 throw new Exception("Can't find forum {$cm->instance}");
333 $result=$type; // Default return value
335 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
341 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
343 fp.userid=:userid AND fd.forum=:forumid";
345 if ($forum->completiondiscussions) {
346 $value = $forum->completiondiscussions <=
347 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
348 if ($type == COMPLETION_AND) {
349 $result = $result && $value;
351 $result = $result || $value;
354 if ($forum->completionreplies) {
355 $value = $forum->completionreplies <=
356 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
357 if ($type==COMPLETION_AND) {
358 $result = $result && $value;
360 $result = $result || $value;
363 if ($forum->completionposts) {
364 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
365 if ($type == COMPLETION_AND) {
366 $result = $result && $value;
368 $result = $result || $value;
376 * Create a message-id string to use in the custom headers of forum notification emails
378 * message-id is used by email clients to identify emails and to nest conversations
380 * @param int $postid The ID of the forum post we are notifying the user about
381 * @param int $usertoid The ID of the user being notified
382 * @param string $hostname The server's hostname
383 * @return string A unique message-id
385 function forum_get_email_message_id($postid, $usertoid, $hostname) {
386 return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
390 * Removes properties from user record that are not necessary
391 * for sending post notifications.
392 * @param stdClass $user
393 * @return void, $user parameter is modified
395 function forum_cron_minimise_user_record(stdClass $user) {
397 // We store large amount of users in one huge array,
398 // make sure we do not store info there we do not actually need
399 // in mail generation code or messaging.
401 unset($user->institution);
402 unset($user->department);
403 unset($user->address);
406 unset($user->currentlogin);
407 unset($user->description);
408 unset($user->descriptionformat);
412 * Function to be run periodically according to the moodle cron
413 * Finds all posts that have yet to be mailed out, and mails them
414 * out to all subscribers
419 * @uses CONTEXT_MODULE
420 * @uses CONTEXT_COURSE
425 function forum_cron() {
426 global $CFG, $USER, $DB;
430 // All users that are subscribed to any post that needs sending,
431 // please increase $CFG->extramemorylimit on large sites that
432 // send notifications to a large number of users.
434 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
437 $mailcount = array();
438 $errorcount = array();
441 $discussions = array();
444 $coursemodules = array();
445 $subscribedusers = array();
448 // Posts older than 2 days will not be mailed. This is to avoid the problem where
449 // cron has not been running for a long time, and then suddenly people are flooded
450 // with mail from the past few weeks or months
452 $endtime = $timenow - $CFG->maxeditingtime;
453 $starttime = $endtime - 48 * 3600; // Two days earlier
455 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
456 // Mark them all now as being mailed. It's unlikely but possible there
457 // might be an error later so that a post is NOT actually mailed out,
458 // but since mail isn't crucial, we can accept this risk. Doing it now
459 // prevents the risk of duplicated mails, which is a worse problem.
461 if (!forum_mark_old_posts_as_mailed($endtime)) {
462 mtrace('Errors occurred while trying to mark some posts as being mailed.');
463 return false; // Don't continue trying to mail them, in case we are in a cron loop
466 // checking post validity, and adding users to loop through later
467 foreach ($posts as $pid => $post) {
469 $discussionid = $post->discussion;
470 if (!isset($discussions[$discussionid])) {
471 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
472 $discussions[$discussionid] = $discussion;
474 mtrace('Could not find discussion '.$discussionid);
479 $forumid = $discussions[$discussionid]->forum;
480 if (!isset($forums[$forumid])) {
481 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
482 $forums[$forumid] = $forum;
484 mtrace('Could not find forum '.$forumid);
489 $courseid = $forums[$forumid]->course;
490 if (!isset($courses[$courseid])) {
491 if ($course = $DB->get_record('course', array('id' => $courseid))) {
492 $courses[$courseid] = $course;
494 mtrace('Could not find course '.$courseid);
499 if (!isset($coursemodules[$forumid])) {
500 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
501 $coursemodules[$forumid] = $cm;
503 mtrace('Could not find course module for forum '.$forumid);
510 // caching subscribed users of each forum
511 if (!isset($subscribedusers[$forumid])) {
512 $modcontext = get_context_instance(CONTEXT_MODULE, $coursemodules[$forumid]->id);
513 if ($subusers = forum_subscribed_users($courses[$courseid], $forums[$forumid], 0, $modcontext, "u.*")) {
514 foreach ($subusers as $postuser) {
515 // this user is subscribed to this forum
516 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
518 if ($userscount > FORUM_CRON_USER_CACHE) {
519 // Store minimal user info.
520 $minuser = new stdClass();
521 $minuser->id = $postuser->id;
522 $users[$postuser->id] = $minuser;
524 // Cache full user record.
525 forum_cron_minimise_user_record($postuser);
526 $users[$postuser->id] = $postuser;
535 $mailcount[$pid] = 0;
536 $errorcount[$pid] = 0;
540 if ($users && $posts) {
542 $urlinfo = parse_url($CFG->wwwroot);
543 $hostname = $urlinfo['host'];
545 foreach ($users as $userto) {
547 @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes
549 mtrace('Processing user '.$userto->id);
551 // Init user caches - we keep the cache for one cycle only,
552 // otherwise it could consume too much memory.
553 if (isset($userto->username)) {
554 $userto = clone($userto);
556 $userto = $DB->get_record('user', array('id' => $userto->id));
557 forum_cron_minimise_user_record($userto);
559 $userto->viewfullnames = array();
560 $userto->canpost = array();
561 $userto->markposts = array();
563 // set this so that the capabilities are cached, and environment matches receiving user
564 cron_setup_user($userto);
567 foreach ($coursemodules as $forumid=>$unused) {
568 $coursemodules[$forumid]->cache = new stdClass();
569 $coursemodules[$forumid]->cache->caps = array();
570 unset($coursemodules[$forumid]->uservisible);
573 foreach ($posts as $pid => $post) {
575 // Set up the environment for the post, discussion, forum, course
576 $discussion = $discussions[$post->discussion];
577 $forum = $forums[$discussion->forum];
578 $course = $courses[$forum->course];
579 $cm =& $coursemodules[$forum->id];
581 // Do some checks to see if we can bail out now
582 // Only active enrolled users are in the list of subscribers
583 if (!isset($subscribedusers[$forum->id][$userto->id])) {
584 continue; // user does not subscribe to this forum
587 // Don't send email if the forum is Q&A and the user has not posted
588 // Initial topics are still mailed
589 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
590 mtrace('Did not email '.$userto->id.' because user has not posted in discussion');
594 // Get info about the sending user
595 if (array_key_exists($post->userid, $users)) { // we might know him/her already
596 $userfrom = $users[$post->userid];
597 if (!isset($userfrom->idnumber)) {
598 // Minimalised user info, fetch full record.
599 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
600 forum_cron_minimise_user_record($userfrom);
603 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
604 forum_cron_minimise_user_record($userfrom);
605 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
606 if ($userscount <= FORUM_CRON_USER_CACHE) {
608 $users[$userfrom->id] = $userfrom;
612 mtrace('Could not find user '.$post->userid);
616 //if we want to check that userto and userfrom are not the same person this is probably the spot to do it
618 // setup global $COURSE properly - needed for roles and languages
619 cron_setup_user($userto, $course);
622 if (!isset($userto->viewfullnames[$forum->id])) {
623 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
624 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
626 if (!isset($userto->canpost[$discussion->id])) {
627 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
628 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
630 if (!isset($userfrom->groups[$forum->id])) {
631 if (!isset($userfrom->groups)) {
632 $userfrom->groups = array();
633 if (isset($users[$userfrom->id])) {
634 $users[$userfrom->id]->groups = array();
637 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
638 if (isset($users[$userfrom->id])) {
639 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
643 // Make sure groups allow this user to see this email
644 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
645 if (!groups_group_exists($discussion->groupid)) { // Can't find group
646 continue; // Be safe and don't send it to anyone
649 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
650 // do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
655 // Make sure we're allowed to see it...
656 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
657 mtrace('user '.$userto->id. ' can not see '.$post->id);
661 // OK so we need to send the email.
663 // Does the user want this post in a digest? If so postpone it for now.
664 if ($userto->maildigest > 0) {
665 // This user wants the mails to be in digest form
666 $queue = new stdClass();
667 $queue->userid = $userto->id;
668 $queue->discussionid = $discussion->id;
669 $queue->postid = $post->id;
670 $queue->timemodified = $post->created;
671 $DB->insert_record('forum_queue', $queue);
676 // Prepare to actually send the post now, and build up the content
678 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
680 $userfrom->customheaders = array ( // Headers to make emails easier to track
682 'List-Id: "'.$cleanforumname.'" <moodleforum'.$forum->id.'@'.$hostname.'>',
683 'List-Help: '.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id,
684 'Message-ID: '.forum_get_email_message_id($post->id, $userto->id, $hostname),
685 'X-Course-Id: '.$course->id,
686 'X-Course-Name: '.format_string($course->fullname, true)
689 if ($post->parent) { // This post is a reply, so add headers for threading (see MDL-22551)
690 $userfrom->customheaders[] = 'In-Reply-To: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
691 $userfrom->customheaders[] = 'References: '.forum_get_email_message_id($post->parent, $userto->id, $hostname);
694 $shortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
696 $postsubject = html_to_text("$shortname: ".format_string($post->subject, true));
697 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
698 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
700 // Send the post now!
702 mtrace('Sending ', '');
704 $eventdata = new stdClass();
705 $eventdata->component = 'mod_forum';
706 $eventdata->name = 'posts';
707 $eventdata->userfrom = $userfrom;
708 $eventdata->userto = $userto;
709 $eventdata->subject = $postsubject;
710 $eventdata->fullmessage = $posttext;
711 $eventdata->fullmessageformat = FORMAT_PLAIN;
712 $eventdata->fullmessagehtml = $posthtml;
713 $eventdata->notification = 1;
715 $smallmessagestrings = new stdClass();
716 $smallmessagestrings->user = fullname($userfrom);
717 $smallmessagestrings->forumname = "$shortname: ".format_string($forum->name,true).": ".$discussion->name;
718 $smallmessagestrings->message = $post->message;
719 //make sure strings are in message recipients language
720 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
722 $eventdata->contexturl = "{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}#p{$post->id}";
723 $eventdata->contexturlname = $discussion->name;
725 $mailresult = message_send($eventdata);
727 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
728 " ($userto->email) .. not trying again.");
729 add_to_log($course->id, 'forum', 'mail error', "discuss.php?d=$discussion->id#p$post->id",
730 substr(format_string($post->subject,true),0,30), $cm->id, $userto->id);
731 $errorcount[$post->id]++;
733 $mailcount[$post->id]++;
735 // Mark post as read if forum_usermarksread is set off
736 if (!$CFG->forum_usermarksread) {
737 $userto->markposts[$post->id] = $post->id;
741 mtrace('post '.$post->id. ': '.$post->subject);
744 // mark processed posts as read
745 forum_tp_mark_posts_read($userto, $userto->markposts);
751 foreach ($posts as $post) {
752 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
753 if ($errorcount[$post->id]) {
754 $DB->set_field("forum_posts", "mailed", "2", array("id" => "$post->id"));
759 // release some memory
760 unset($subscribedusers);
766 $sitetimezone = $CFG->timezone;
768 // Now see if there are any digest mails waiting to be sent, and if we should send them
770 mtrace('Starting digest processing...');
772 @set_time_limit(300); // terminate if not able to fetch all digests in 5 minutes
774 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
775 set_config('digestmailtimelast', 0);
779 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
781 // Delete any really old ones (normally there shouldn't be any)
782 $weekago = $timenow - (7 * 24 * 3600);
783 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
784 mtrace ('Cleaned old digest records');
786 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
788 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
790 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
792 if ($digestposts_rs->valid()) {
794 // We have work to do
797 //caches - reuse the those filled before too
798 $discussionposts = array();
799 $userdiscussions = array();
801 foreach ($digestposts_rs as $digestpost) {
802 if (!isset($posts[$digestpost->postid])) {
803 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
804 $posts[$digestpost->postid] = $post;
809 $discussionid = $digestpost->discussionid;
810 if (!isset($discussions[$discussionid])) {
811 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
812 $discussions[$discussionid] = $discussion;
817 $forumid = $discussions[$discussionid]->forum;
818 if (!isset($forums[$forumid])) {
819 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
820 $forums[$forumid] = $forum;
826 $courseid = $forums[$forumid]->course;
827 if (!isset($courses[$courseid])) {
828 if ($course = $DB->get_record('course', array('id' => $courseid))) {
829 $courses[$courseid] = $course;
835 if (!isset($coursemodules[$forumid])) {
836 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
837 $coursemodules[$forumid] = $cm;
842 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
843 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
845 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
847 // Data collected, start sending out emails to each user
848 foreach ($userdiscussions as $userid => $thesediscussions) {
850 @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes
854 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
856 // First of all delete all the queue entries for this user
857 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
859 // Init user caches - we keep the cache for one cycle only,
860 // otherwise it would unnecessarily consume memory.
861 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
862 $userto = clone($users[$userid]);
864 $userto = $DB->get_record('user', array('id' => $userid));
865 forum_cron_minimise_user_record($userto);
867 $userto->viewfullnames = array();
868 $userto->canpost = array();
869 $userto->markposts = array();
871 // Override the language and timezone of the "current" user, so that
872 // mail is customised for the receiver.
873 cron_setup_user($userto);
875 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
877 $headerdata = new stdClass();
878 $headerdata->sitename = format_string($site->fullname, true);
879 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&course='.$site->id;
881 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
882 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
884 $posthtml = "<head>";
885 /* foreach ($CFG->stylesheets as $stylesheet) {
887 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
889 $posthtml .= "</head>\n<body id=\"email\">\n";
890 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
892 foreach ($thesediscussions as $discussionid) {
894 @set_time_limit(120); // to be reset for each post
896 $discussion = $discussions[$discussionid];
897 $forum = $forums[$discussion->forum];
898 $course = $courses[$forum->course];
899 $cm = $coursemodules[$forum->id];
902 cron_setup_user($userto, $course);
905 if (!isset($userto->viewfullnames[$forum->id])) {
906 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
907 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
909 if (!isset($userto->canpost[$discussion->id])) {
910 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
911 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
914 $strforums = get_string('forums', 'forum');
915 $canunsubscribe = ! forum_is_forcesubscribed($forum);
916 $canreply = $userto->canpost[$discussion->id];
917 $shortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
919 $posttext .= "\n \n";
920 $posttext .= '=====================================================================';
921 $posttext .= "\n \n";
922 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
923 if ($discussion->name != $forum->name) {
924 $posttext .= " -> ".format_string($discussion->name,true);
928 $posthtml .= "<p><font face=\"sans-serif\">".
929 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
930 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
931 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
932 if ($discussion->name == $forum->name) {
933 $posthtml .= "</font></p>";
935 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
939 $postsarray = $discussionposts[$discussionid];
942 foreach ($postsarray as $postid) {
943 $post = $posts[$postid];
945 if (array_key_exists($post->userid, $users)) { // we might know him/her already
946 $userfrom = $users[$post->userid];
947 if (!isset($userfrom->idnumber)) {
948 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
949 forum_cron_minimise_user_record($userfrom);
952 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
953 forum_cron_minimise_user_record($userfrom);
954 if ($userscount <= FORUM_CRON_USER_CACHE) {
956 $users[$userfrom->id] = $userfrom;
960 mtrace('Could not find user '.$post->userid);
964 if (!isset($userfrom->groups[$forum->id])) {
965 if (!isset($userfrom->groups)) {
966 $userfrom->groups = array();
967 if (isset($users[$userfrom->id])) {
968 $users[$userfrom->id]->groups = array();
971 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
972 if (isset($users[$userfrom->id])) {
973 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
977 $userfrom->customheaders = array ("Precedence: Bulk");
979 if ($userto->maildigest == 2) {
981 $by = new stdClass();
982 $by->name = fullname($userfrom);
983 $by->date = userdate($post->modified);
984 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
985 $posttext .= "\n---------------------------------------------------------------------";
987 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&course=$course->id\">$by->name</a>";
988 $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>';
991 // The full treatment
992 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
993 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
995 // Create an array of postid's for this user to mark as read.
996 if (!$CFG->forum_usermarksread) {
997 $userto->markposts[$post->id] = $post->id;
1001 if ($canunsubscribe) {
1002 $posthtml .= "\n<div class='mdl-right'><font size=\"1\"><a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">".get_string("unsubscribe", "forum")."</a></font></div>";
1004 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">".get_string("everyoneissubscribed", "forum")."</font></div>";
1006 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1008 $posthtml .= '</body>';
1010 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1011 // This user DOESN'T want to receive HTML
1015 $attachment = $attachname='';
1016 $usetrueaddress = true;
1017 // Directly email forum digests rather than sending them via messaging, use the
1018 // site shortname as 'from name', the noreply address will be used by email_to_user.
1019 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname, $usetrueaddress, $CFG->forum_replytouser);
1023 echo "Error: mod/forum/cron.php: Could not send out digest mail to user $userto->id ($userto->email)... not trying again.\n";
1024 add_to_log($course->id, 'forum', 'mail digest error', '', '', $cm->id, $userto->id);
1029 // Mark post as read if forum_usermarksread is set off
1030 forum_tp_mark_posts_read($userto, $userto->markposts);
1034 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1035 set_config('digestmailtimelast', $timenow);
1040 if (!empty($usermailcount)) {
1041 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1044 if (!empty($CFG->forum_lastreadclean)) {
1046 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1047 set_config('forum_lastreadclean', $timenow);
1048 mtrace('Removing old forum read tracking info...');
1049 forum_tp_clean_read_records();
1052 set_config('forum_lastreadclean', time());
1060 * Builds and returns the body of the email notification in plain text.
1064 * @uses CONTEXT_MODULE
1065 * @param object $course
1067 * @param object $forum
1068 * @param object $discussion
1069 * @param object $post
1070 * @param object $userfrom
1071 * @param object $userto
1072 * @param boolean $bare
1073 * @return string The email body in plain text format.
1075 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false) {
1078 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1080 if (!isset($userto->viewfullnames[$forum->id])) {
1081 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1083 $viewfullnames = $userto->viewfullnames[$forum->id];
1086 if (!isset($userto->canpost[$discussion->id])) {
1087 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1089 $canreply = $userto->canpost[$discussion->id];
1093 $by->name = fullname($userfrom, $viewfullnames);
1094 $by->date = userdate($post->modified, "", $userto->timezone);
1096 $strbynameondate = get_string('bynameondate', 'forum', $by);
1098 $strforums = get_string('forums', 'forum');
1100 $canunsubscribe = ! forum_is_forcesubscribed($forum);
1105 $shortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
1106 $posttext = "$shortname -> $strforums -> ".format_string($forum->name,true);
1108 if ($discussion->name != $forum->name) {
1109 $posttext .= " -> ".format_string($discussion->name,true);
1113 // add absolute file links
1114 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1116 $posttext .= "\n---------------------------------------------------------------------\n";
1117 $posttext .= format_string($post->subject,true);
1119 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1121 $posttext .= "\n".$strbynameondate."\n";
1122 $posttext .= "---------------------------------------------------------------------\n";
1123 $posttext .= format_text_email($post->message, $post->messageformat);
1124 $posttext .= "\n\n";
1125 $posttext .= forum_print_attachments($post, $cm, "text");
1127 if (!$bare && $canreply) {
1128 $posttext .= "---------------------------------------------------------------------\n";
1129 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1130 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1132 if (!$bare && $canunsubscribe) {
1133 $posttext .= "\n---------------------------------------------------------------------\n";
1134 $posttext .= get_string("unsubscribe", "forum");
1135 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1142 * Builds and returns the body of the email notification in html format.
1145 * @param object $course
1147 * @param object $forum
1148 * @param object $discussion
1149 * @param object $post
1150 * @param object $userfrom
1151 * @param object $userto
1152 * @return string The email text in HTML format
1154 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto) {
1157 if ($userto->mailformat != 1) { // Needs to be HTML
1161 if (!isset($userto->canpost[$discussion->id])) {
1162 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1164 $canreply = $userto->canpost[$discussion->id];
1167 $strforums = get_string('forums', 'forum');
1168 $canunsubscribe = ! forum_is_forcesubscribed($forum);
1169 $shortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
1171 $posthtml = '<head>';
1172 /* foreach ($CFG->stylesheets as $stylesheet) {
1174 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1176 $posthtml .= '</head>';
1177 $posthtml .= "\n<body id=\"email\">\n\n";
1179 $posthtml .= '<div class="navbar">'.
1180 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$shortname.'</a> » '.
1181 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> » '.
1182 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1183 if ($discussion->name == $forum->name) {
1184 $posthtml .= '</div>';
1186 $posthtml .= ' » <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1187 format_string($discussion->name,true).'</a></div>';
1189 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1191 if ($canunsubscribe) {
1192 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">
1193 <a href="'.$CFG->wwwroot.'/mod/forum/subscribe.php?id='.$forum->id.'">'.get_string('unsubscribe', 'forum').'</a>
1194 <a href="'.$CFG->wwwroot.'/mod/forum/unsubscribeall.php">'.get_string('unsubscribeall', 'forum').'</a></div>';
1197 $posthtml .= '</body>';
1205 * @param object $course
1206 * @param object $user
1207 * @param object $mod TODO this is not used in this function, refactor
1208 * @param object $forum
1209 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1211 function forum_user_outline($course, $user, $mod, $forum) {
1213 require_once("$CFG->libdir/gradelib.php");
1214 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1215 if (empty($grades->items[0]->grades)) {
1218 $grade = reset($grades->items[0]->grades);
1221 $count = forum_count_user_posts($forum->id, $user->id);
1223 if ($count && $count->postcount > 0) {
1224 $result = new stdClass();
1225 $result->info = get_string("numposts", "forum", $count->postcount);
1226 $result->time = $count->lastpost;
1228 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1231 } else if ($grade) {
1232 $result = new stdClass();
1233 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1235 //datesubmitted == time created. dategraded == time modified or time overridden
1236 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1237 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1238 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1239 $result->time = $grade->dategraded;
1241 $result->time = $grade->datesubmitted;
1253 * @param object $coure
1254 * @param object $user
1255 * @param object $mod
1256 * @param object $forum
1258 function forum_user_complete($course, $user, $mod, $forum) {
1259 global $CFG,$USER, $OUTPUT;
1260 require_once("$CFG->libdir/gradelib.php");
1262 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1263 if (!empty($grades->items[0]->grades)) {
1264 $grade = reset($grades->items[0]->grades);
1265 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1266 if ($grade->str_feedback) {
1267 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1271 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1273 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1274 print_error('invalidcoursemodule');
1276 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1278 foreach ($posts as $post) {
1279 if (!isset($discussions[$post->discussion])) {
1282 $discussion = $discussions[$post->discussion];
1284 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1287 echo "<p>".get_string("noposts", "forum")."</p>";
1300 * @param array $courses
1301 * @param array $htmlarray
1303 function forum_print_overview($courses,&$htmlarray) {
1304 global $USER, $CFG, $DB, $SESSION;
1306 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1310 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1314 // Courses to search for new posts
1315 $coursessqls = array();
1317 foreach ($courses as $course) {
1319 // If the user has never entered into the course all posts are pending
1320 if ($course->lastaccess == 0) {
1321 $coursessqls[] = '(f.course = ?)';
1322 $params[] = $course->id;
1324 // Only posts created after the course last access
1326 $coursessqls[] = '(f.course = ? AND p.created > ?)';
1327 $params[] = $course->id;
1328 $params[] = $course->lastaccess;
1331 $params[] = $USER->id;
1332 $coursessql = implode(' OR ', $coursessqls);
1334 $sql = "SELECT f.id, COUNT(*) as count "
1336 .'JOIN {forum_discussions} d ON d.forum = f.id '
1337 .'JOIN {forum_posts} p ON p.discussion = d.id '
1338 ."WHERE ($coursessql) "
1339 .'AND p.userid != ? '
1342 if (!$new = $DB->get_records_sql($sql, $params)) {
1343 $new = array(); // avoid warnings
1346 // also get all forum tracking stuff ONCE.
1347 $trackingforums = array();
1348 foreach ($forums as $forum) {
1349 if (forum_tp_can_track_forums($forum)) {
1350 $trackingforums[$forum->id] = $forum;
1354 if (count($trackingforums) > 0) {
1355 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1356 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1357 ' FROM {forum_posts} p '.
1358 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1359 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1360 $params = array($USER->id);
1362 foreach ($trackingforums as $track) {
1363 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1364 $params[] = $track->id;
1365 if (isset($SESSION->currentgroup[$track->course])) {
1366 $groupid = $SESSION->currentgroup[$track->course];
1368 // get first groupid
1369 $groupids = groups_get_all_groups($track->course, $USER->id);
1372 $groupid = key($groupids);
1373 $SESSION->currentgroup[$track->course] = $groupid;
1379 $params[] = $groupid;
1381 $sql = substr($sql,0,-3); // take off the last OR
1382 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1383 $params[] = $cutoffdate;
1385 if (!$unread = $DB->get_records_sql($sql, $params)) {
1392 if (empty($unread) and empty($new)) {
1396 $strforum = get_string('modulename','forum');
1398 foreach ($forums as $forum) {
1402 $showunread = false;
1403 // either we have something from logs, or trackposts, or nothing.
1404 if (array_key_exists($forum->id, $new) && !empty($new[$forum->id])) {
1405 $count = $new[$forum->id]->count;
1407 if (array_key_exists($forum->id,$unread)) {
1408 $thisunread = $unread[$forum->id]->count;
1411 if ($count > 0 || $thisunread > 0) {
1412 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1413 $forum->name.'</a></div>';
1414 $str .= '<div class="info"><span class="postsincelogin">';
1415 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1416 if (!empty($showunread)) {
1417 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1419 $str .= '</div></div>';
1422 if (!array_key_exists($forum->course,$htmlarray)) {
1423 $htmlarray[$forum->course] = array();
1425 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1426 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1428 $htmlarray[$forum->course]['forum'] .= $str;
1434 * Given a course and a date, prints a summary of all the new
1435 * messages posted in the course since that date
1440 * @uses CONTEXT_MODULE
1441 * @uses VISIBLEGROUPS
1442 * @param object $course
1443 * @param bool $viewfullnames capability
1444 * @param int $timestart
1445 * @return bool success
1447 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1448 global $CFG, $USER, $DB, $OUTPUT;
1450 // do not use log table if possible, it may be huge and is expensive to join with other tables
1452 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1453 d.timestart, d.timeend, d.userid AS duserid,
1454 u.firstname, u.lastname, u.email, u.picture
1455 FROM {forum_posts} p
1456 JOIN {forum_discussions} d ON d.id = p.discussion
1457 JOIN {forum} f ON f.id = d.forum
1458 JOIN {user} u ON u.id = p.userid
1459 WHERE p.created > ? AND f.course = ?
1460 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1464 $modinfo = get_fast_modinfo($course);
1466 $groupmodes = array();
1469 $strftimerecent = get_string('strftimerecent');
1471 $printposts = array();
1472 foreach ($posts as $post) {
1473 if (!isset($modinfo->instances['forum'][$post->forum])) {
1477 $cm = $modinfo->instances['forum'][$post->forum];
1478 if (!$cm->uservisible) {
1481 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1483 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1487 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1488 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1489 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1494 $groupmode = groups_get_activity_groupmode($cm, $course);
1497 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) {
1498 // oki (Open discussions have groupid -1)
1501 if (isguestuser()) {
1506 if (is_null($modinfo->groups)) {
1507 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
1510 if (!array_key_exists($post->groupid, $modinfo->groups[0])) {
1516 $printposts[] = $post;
1524 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1525 echo "\n<ul class='unlist'>\n";
1527 foreach ($printposts as $post) {
1528 $subjectclass = empty($post->parent) ? ' bold' : '';
1530 echo '<li><div class="head">'.
1531 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1532 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1534 echo '<div class="info'.$subjectclass.'">';
1535 if (empty($post->parent)) {
1536 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1538 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&parent='.$post->parent.'#p'.$post->id.'">';
1540 $post->subject = break_up_long_words(format_string($post->subject, true));
1541 echo $post->subject;
1542 echo "</a>\"</div></li>\n";
1551 * Return grade for given user or all users.
1555 * @param object $forum
1556 * @param int $userid optional user id, 0 means all users
1557 * @return array array of grades, false if none
1559 function forum_get_user_grades($forum, $userid = 0) {
1562 require_once($CFG->dirroot.'/rating/lib.php');
1564 $ratingoptions = new stdClass;
1565 $ratingoptions->component = 'mod_forum';
1566 $ratingoptions->ratingarea = 'post';
1568 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1569 $ratingoptions->modulename = 'forum';
1570 $ratingoptions->moduleid = $forum->id;
1571 $ratingoptions->userid = $userid;
1572 $ratingoptions->aggregationmethod = $forum->assessed;
1573 $ratingoptions->scaleid = $forum->scale;
1574 $ratingoptions->itemtable = 'forum_posts';
1575 $ratingoptions->itemtableusercolumn = 'userid';
1577 $rm = new rating_manager();
1578 return $rm->get_user_grades($ratingoptions);
1582 * Update activity grades
1585 * @param object $forum
1586 * @param int $userid specific user only, 0 means all
1587 * @param boolean $nullifnone return null if grade does not exist
1590 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1592 require_once($CFG->libdir.'/gradelib.php');
1594 if (!$forum->assessed) {
1595 forum_grade_item_update($forum);
1597 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1598 forum_grade_item_update($forum, $grades);
1600 } else if ($userid and $nullifnone) {
1601 $grade = new stdClass();
1602 $grade->userid = $userid;
1603 $grade->rawgrade = NULL;
1604 forum_grade_item_update($forum, $grade);
1607 forum_grade_item_update($forum);
1612 * Update all grades in gradebook.
1615 function forum_upgrade_grades() {
1618 $sql = "SELECT COUNT('x')
1619 FROM {forum} f, {course_modules} cm, {modules} m
1620 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
1621 $count = $DB->count_records_sql($sql);
1623 $sql = "SELECT f.*, cm.idnumber AS cmidnumber, f.course AS courseid
1624 FROM {forum} f, {course_modules} cm, {modules} m
1625 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
1626 $rs = $DB->get_recordset_sql($sql);
1628 $pbar = new progress_bar('forumupgradegrades', 500, true);
1630 foreach ($rs as $forum) {
1632 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
1633 forum_update_grades($forum, 0, false);
1634 $pbar->update($i, $count, "Updating Forum grades ($i/$count).");
1641 * Create/update grade item for given forum
1644 * @uses GRADE_TYPE_NONE
1645 * @uses GRADE_TYPE_VALUE
1646 * @uses GRADE_TYPE_SCALE
1647 * @param stdClass $forum Forum object with extra cmidnumber
1648 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1649 * @return int 0 if ok
1651 function forum_grade_item_update($forum, $grades=NULL) {
1653 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1654 require_once($CFG->libdir.'/gradelib.php');
1657 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1659 if (!$forum->assessed or $forum->scale == 0) {
1660 $params['gradetype'] = GRADE_TYPE_NONE;
1662 } else if ($forum->scale > 0) {
1663 $params['gradetype'] = GRADE_TYPE_VALUE;
1664 $params['grademax'] = $forum->scale;
1665 $params['grademin'] = 0;
1667 } else if ($forum->scale < 0) {
1668 $params['gradetype'] = GRADE_TYPE_SCALE;
1669 $params['scaleid'] = -$forum->scale;
1672 if ($grades === 'reset') {
1673 $params['reset'] = true;
1677 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1681 * Delete grade item for given forum
1684 * @param stdClass $forum Forum object
1685 * @return grade_item
1687 function forum_grade_item_delete($forum) {
1689 require_once($CFG->libdir.'/gradelib.php');
1691 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1696 * This function returns if a scale is being used by one forum
1699 * @param int $forumid
1700 * @param int $scaleid negative number
1703 function forum_scale_used ($forumid,$scaleid) {
1707 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1709 if (!empty($rec) && !empty($scaleid)) {
1717 * Checks if scale is being used by any instance of forum
1719 * This is used to find out if scale used anywhere
1722 * @param $scaleid int
1723 * @return boolean True if the scale is used by any forum
1725 function forum_scale_used_anywhere($scaleid) {
1727 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1734 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1737 * Gets a post with all info ready for forum_print_post
1738 * Most of these joins are just to get the forum id
1742 * @param int $postid
1743 * @return mixed array of posts or false
1745 function forum_get_post_full($postid) {
1748 return $DB->get_record_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1749 FROM {forum_posts} p
1750 JOIN {forum_discussions} d ON p.discussion = d.id
1751 LEFT JOIN {user} u ON p.userid = u.id
1752 WHERE p.id = ?", array($postid));
1756 * Gets posts with all info ready for forum_print_post
1757 * We pass forumid in because we always know it so no need to make a
1758 * complicated join to find it out.
1762 * @return mixed array of posts or false
1764 function forum_get_discussion_posts($discussion, $sort, $forumid) {
1767 return $DB->get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1768 FROM {forum_posts} p
1769 LEFT JOIN {user} u ON p.userid = u.id
1770 WHERE p.discussion = ?
1771 AND p.parent > 0 $sort", array($discussion));
1775 * Gets all posts in discussion including top parent.
1780 * @param int $discussionid
1781 * @param string $sort
1782 * @param bool $tracking does user track the forum?
1783 * @return array of posts
1785 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1786 global $CFG, $DB, $USER;
1794 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1795 $tr_sel = ", fr.id AS postread";
1796 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1797 $params[] = $USER->id;
1800 $params[] = $discussionid;
1801 if (!$posts = $DB->get_records_sql("SELECT p.*, u.firstname, u.lastname, u.email, u.picture, u.imagealt $tr_sel
1802 FROM {forum_posts} p
1803 LEFT JOIN {user} u ON p.userid = u.id
1805 WHERE p.discussion = ?
1806 ORDER BY $sort", $params)) {
1810 foreach ($posts as $pid=>$p) {
1812 if (forum_tp_is_post_old($p)) {
1813 $posts[$pid]->postread = true;
1819 if (!isset($posts[$p->parent])) {
1820 continue; // parent does not exist??
1822 if (!isset($posts[$p->parent]->children)) {
1823 $posts[$p->parent]->children = array();
1825 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1832 * Gets posts with all info ready for forum_print_post
1833 * We pass forumid in because we always know it so no need to make a
1834 * complicated join to find it out.
1838 * @param int $parent
1839 * @param int $forumid
1842 function forum_get_child_posts($parent, $forumid) {
1845 return $DB->get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1846 FROM {forum_posts} p
1847 LEFT JOIN {user} u ON p.userid = u.id
1849 ORDER BY p.created ASC", array($parent));
1853 * An array of forum objects that the user is allowed to read/search through.
1858 * @param int $userid
1859 * @param int $courseid if 0, we look for forums throughout the whole site.
1860 * @return array of forum objects, or false if no matches
1861 * Forum objects have the following attributes:
1862 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1863 * viewhiddentimedposts
1865 function forum_get_readable_forums($userid, $courseid=0) {
1867 global $CFG, $DB, $USER;
1868 require_once($CFG->dirroot.'/course/lib.php');
1870 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1871 print_error('notinstalled', 'forum');
1875 $courses = $DB->get_records('course', array('id' => $courseid));
1877 // If no course is specified, then the user can see SITE + his courses.
1878 $courses1 = $DB->get_records('course', array('id' => SITEID));
1879 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1880 $courses = array_merge($courses1, $courses2);
1886 $readableforums = array();
1888 foreach ($courses as $course) {
1890 $modinfo = get_fast_modinfo($course);
1891 if (is_null($modinfo->groups)) {
1892 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1895 if (empty($modinfo->instances['forum'])) {
1900 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1902 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1903 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1906 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1907 $forum = $courseforums[$forumid];
1908 $forum->context = $context;
1911 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1916 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1917 if (is_null($modinfo->groups)) {
1918 $modinfo->groups = groups_get_user_groups($course->id, $USER->id);
1920 if (isset($modinfo->groups[$cm->groupingid])) {
1921 $forum->onlygroups = $modinfo->groups[$cm->groupingid];
1922 $forum->onlygroups[] = -1;
1924 $forum->onlygroups = array(-1);
1928 /// hidden timed discussions
1929 $forum->viewhiddentimedposts = true;
1930 if (!empty($CFG->forum_enabletimedposts)) {
1931 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1932 $forum->viewhiddentimedposts = false;
1937 if ($forum->type == 'qanda'
1938 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1940 // We need to check whether the user has posted in the qanda forum.
1941 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1942 // the user is allowed to see in this forum.
1943 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1944 foreach ($discussionspostedin as $d) {
1945 $forum->onlydiscussions[] = $d->id;
1950 $readableforums[$forum->id] = $forum;
1955 } // End foreach $courses
1957 return $readableforums;
1961 * Returns a list of posts found using an array of search terms.
1966 * @param array $searchterms array of search terms, e.g. word +word -word
1967 * @param int $courseid if 0, we search through the whole site
1968 * @param int $limitfrom
1969 * @param int $limitnum
1970 * @param int &$totalcount
1971 * @param string $extrasql
1972 * @return array|bool Array of posts found or false
1974 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
1975 &$totalcount, $extrasql='') {
1976 global $CFG, $DB, $USER;
1977 require_once($CFG->libdir.'/searchlib.php');
1979 $forums = forum_get_readable_forums($USER->id, $courseid);
1981 if (count($forums) == 0) {
1986 $now = round(time(), -2); // db friendly
1988 $fullaccess = array();
1992 foreach ($forums as $forumid => $forum) {
1995 if (!$forum->viewhiddentimedposts) {
1996 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1997 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2001 $context = $forum->context;
2003 if ($forum->type == 'qanda'
2004 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2005 if (!empty($forum->onlydiscussions)) {
2006 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2007 $params = array_merge($params, $discussionid_params);
2008 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2010 $select[] = "p.parent = 0";
2014 if (!empty($forum->onlygroups)) {
2015 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2016 $params = array_merge($params, $groupid_params);
2017 $select[] = "d.groupid $groupid_sql";
2021 $selects = implode(" AND ", $select);
2022 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2023 $params['forum'.$forumid] = $forumid;
2025 $fullaccess[] = $forumid;
2030 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2031 $params = array_merge($params, $fullid_params);
2032 $where[] = "(d.forum $fullid_sql)";
2035 $selectdiscussion = "(".implode(" OR ", $where).")";
2037 $messagesearch = '';
2040 // Need to concat these back together for parser to work.
2041 foreach($searchterms as $searchterm){
2042 if ($searchstring != '') {
2043 $searchstring .= ' ';
2045 $searchstring .= $searchterm;
2048 // We need to allow quoted strings for the search. The quotes *should* be stripped
2049 // by the parser, but this should be examined carefully for security implications.
2050 $searchstring = str_replace("\\\"","\"",$searchstring);
2051 $parser = new search_parser();
2052 $lexer = new search_lexer($parser);
2054 if ($lexer->parse($searchstring)) {
2055 $parsearray = $parser->get_parsed_array();
2056 // Experimental feature under 1.8! MDL-8830
2057 // Use alternative text searches if defined
2058 // This feature only works under mysql until properly implemented for other DBs
2059 // Requires manual creation of text index for forum_posts before enabling it:
2060 // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
2061 // Experimental feature under 1.8! MDL-8830
2062 if (!empty($CFG->forum_usetextsearches)) {
2063 list($messagesearch, $msparams) = search_generate_text_SQL($parsearray, 'p.message', 'p.subject',
2064 'p.userid', 'u.id', 'u.firstname',
2065 'u.lastname', 'p.modified', 'd.forum');
2067 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2068 'p.userid', 'u.id', 'u.firstname',
2069 'u.lastname', 'p.modified', 'd.forum');
2071 $params = array_merge($params, $msparams);
2074 $fromsql = "{forum_posts} p,
2075 {forum_discussions} d,
2078 $selectsql = " $messagesearch
2079 AND p.discussion = d.id
2081 AND $selectdiscussion
2084 $countsql = "SELECT COUNT(*)
2088 $searchsql = "SELECT p.*,
2097 ORDER BY p.modified DESC";
2099 $totalcount = $DB->count_records_sql($countsql, $params);
2101 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2105 * Returns a list of ratings for a particular post - sorted.
2107 * TODO: Check if this function is actually used anywhere.
2108 * Up until the fix for MDL-27471 this function wasn't even returning.
2110 * @param stdClass $context
2111 * @param int $postid
2112 * @param string $sort
2113 * @return array Array of ratings or false
2115 function forum_get_ratings($context, $postid, $sort = "u.firstname ASC") {
2116 $options = new stdClass;
2117 $options->context = $context;
2118 $options->component = 'mod_forum';
2119 $options->ratingarea = 'post';
2120 $options->itemid = $postid;
2121 $options->sort = "ORDER BY $sort";
2123 $rm = new rating_manager();
2124 return $rm->get_all_ratings_for_item($options);
2128 * Returns a list of all new posts that have not been mailed yet
2130 * @param int $starttime posts created after this time
2131 * @param int $endtime posts created before this
2132 * @param int $now used for timed discussions only
2135 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2138 $params = array($starttime, $endtime);
2139 if (!empty($CFG->forum_enabletimedposts)) {
2143 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2150 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2151 FROM {forum_posts} p
2152 JOIN {forum_discussions} d ON d.id = p.discussion
2155 AND (p.created < ? OR p.mailnow = 1)
2157 ORDER BY p.modified ASC", $params);
2161 * Marks posts before a certain time as being mailed already
2165 * @param int $endtime
2166 * @param int $now Defaults to time()
2169 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2175 if (empty($CFG->forum_enabletimedposts)) {
2176 return $DB->execute("UPDATE {forum_posts}
2178 WHERE (created < ? OR mailnow = 1)
2179 AND mailed = 0", array($endtime));
2182 return $DB->execute("UPDATE {forum_posts}
2184 WHERE discussion NOT IN (SELECT d.id
2185 FROM {forum_discussions} d
2186 WHERE d.timestart > ?)
2187 AND (created < ? OR mailnow = 1)
2188 AND mailed = 0", array($now, $endtime));
2193 * Get all the posts for a user in a forum suitable for forum_print_post
2197 * @uses CONTEXT_MODULE
2200 function forum_get_user_posts($forumid, $userid) {
2204 $params = array($forumid, $userid);
2206 if (!empty($CFG->forum_enabletimedposts)) {
2207 $cm = get_coursemodule_from_instance('forum', $forumid);
2208 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2210 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2216 return $DB->get_records_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
2218 JOIN {forum_discussions} d ON d.forum = f.id
2219 JOIN {forum_posts} p ON p.discussion = d.id
2220 JOIN {user} u ON u.id = p.userid
2224 ORDER BY p.modified ASC", $params);
2228 * Get all the discussions user participated in
2232 * @uses CONTEXT_MODULE
2233 * @param int $forumid
2234 * @param int $userid
2235 * @return array Array or false
2237 function forum_get_user_involved_discussions($forumid, $userid) {
2241 $params = array($forumid, $userid);
2242 if (!empty($CFG->forum_enabletimedposts)) {
2243 $cm = get_coursemodule_from_instance('forum', $forumid);
2244 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2246 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2252 return $DB->get_records_sql("SELECT DISTINCT d.*
2254 JOIN {forum_discussions} d ON d.forum = f.id
2255 JOIN {forum_posts} p ON p.discussion = d.id
2258 $timedsql", $params);
2262 * Get all the posts for a user in a forum suitable for forum_print_post
2266 * @param int $forumid
2267 * @param int $userid
2268 * @return array of counts or false
2270 function forum_count_user_posts($forumid, $userid) {
2274 $params = array($forumid, $userid);
2275 if (!empty($CFG->forum_enabletimedposts)) {
2276 $cm = get_coursemodule_from_instance('forum', $forumid);
2277 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2279 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2285 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2287 JOIN {forum_discussions} d ON d.forum = f.id
2288 JOIN {forum_posts} p ON p.discussion = d.id
2289 JOIN {user} u ON u.id = p.userid
2292 $timedsql", $params);
2296 * Given a log entry, return the forum post details for it.
2300 * @param object $log
2301 * @return array|null
2303 function forum_get_post_from_log($log) {
2306 if ($log->action == "add post") {
2308 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
2309 u.firstname, u.lastname, u.email, u.picture
2310 FROM {forum_discussions} d,
2315 AND d.id = p.discussion
2317 AND u.deleted <> '1'
2318 AND f.id = d.forum", array($log->info));
2321 } else if ($log->action == "add discussion") {
2323 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
2324 u.firstname, u.lastname, u.email, u.picture
2325 FROM {forum_discussions} d,
2330 AND d.firstpost = p.id
2332 AND u.deleted <> '1'
2333 AND f.id = d.forum", array($log->info));
2339 * Given a discussion id, return the first post from the discussion
2343 * @param int $dicsussionid
2346 function forum_get_firstpost_from_discussion($discussionid) {
2349 return $DB->get_record_sql("SELECT p.*
2350 FROM {forum_discussions} d,
2353 AND d.firstpost = p.id ", array($discussionid));
2357 * Returns an array of counts of replies to each discussion
2361 * @param int $forumid
2362 * @param string $forumsort
2365 * @param int $perpage
2368 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2374 } else if ($page != -1) {
2375 $limitfrom = $page*$perpage;
2376 $limitnum = $perpage;
2382 if ($forumsort == "") {
2387 $orderby = "ORDER BY $forumsort";
2388 $groupby = ", ".strtolower($forumsort);
2389 $groupby = str_replace('desc', '', $groupby);
2390 $groupby = str_replace('asc', '', $groupby);
2393 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2394 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2395 FROM {forum_posts} p
2396 JOIN {forum_discussions} d ON p.discussion = d.id
2397 WHERE p.parent > 0 AND d.forum = ?
2398 GROUP BY p.discussion";
2399 return $DB->get_records_sql($sql, array($forumid));
2402 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2403 FROM {forum_posts} p
2404 JOIN {forum_discussions} d ON p.discussion = d.id
2406 GROUP BY p.discussion $groupby
2408 return $DB->get_records_sql("SELECT * FROM ($sql) sq", array($forumid), $limitfrom, $limitnum);
2416 * @staticvar array $cache
2417 * @param object $forum
2419 * @param object $course
2422 function forum_count_discussions($forum, $cm, $course) {
2423 global $CFG, $DB, $USER;
2425 static $cache = array();
2427 $now = round(time(), -2); // db cache friendliness
2429 $params = array($course->id);
2431 if (!isset($cache[$course->id])) {
2432 if (!empty($CFG->forum_enabletimedposts)) {
2433 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2440 $sql = "SELECT f.id, COUNT(d.id) as dcount
2442 JOIN {forum_discussions} d ON d.forum = f.id
2447 if ($counts = $DB->get_records_sql($sql, $params)) {
2448 foreach ($counts as $count) {
2449 $counts[$count->id] = $count->dcount;
2451 $cache[$course->id] = $counts;
2453 $cache[$course->id] = array();
2457 if (empty($cache[$course->id][$forum->id])) {
2461 $groupmode = groups_get_activity_groupmode($cm, $course);
2463 if ($groupmode != SEPARATEGROUPS) {
2464 return $cache[$course->id][$forum->id];
2467 if (has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2468 return $cache[$course->id][$forum->id];
2471 require_once($CFG->dirroot.'/course/lib.php');
2473 $modinfo = get_fast_modinfo($course);
2474 if (is_null($modinfo->groups)) {
2475 $modinfo->groups = groups_get_user_groups($course->id, $USER->id);
2478 if (array_key_exists($cm->groupingid, $modinfo->groups)) {
2479 $mygroups = $modinfo->groups[$cm->groupingid];
2481 $mygroups = false; // Will be set below
2484 // add all groups posts
2485 if (empty($mygroups)) {
2486 $mygroups = array(-1=>-1);
2491 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2492 $params[] = $forum->id;
2494 if (!empty($CFG->forum_enabletimedposts)) {
2495 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2502 $sql = "SELECT COUNT(d.id)
2503 FROM {forum_discussions} d
2504 WHERE d.groupid $mygroups_sql AND d.forum = ?
2507 return $DB->get_field_sql($sql, $params);
2511 * How many posts by other users are unrated by a given user in the given discussion?
2513 * TODO: Is this function still used anywhere?
2515 * @param int $discussionid
2516 * @param int $userid
2519 function forum_count_unrated_posts($discussionid, $userid) {
2522 $sql = "SELECT COUNT(*) as num
2525 AND discussion = :discussionid
2526 AND userid <> :userid";
2527 $params = array('discussionid' => $discussionid, 'userid' => $userid);
2528 $posts = $DB->get_record_sql($sql, $params);
2530 $sql = "SELECT count(*) as num
2531 FROM {forum_posts} p,
2533 WHERE p.discussion = :discussionid AND
2535 r.userid = userid AND
2536 r.component = 'mod_forum' AND
2537 r.ratingarea = 'post'";
2538 $rated = $DB->get_record_sql($sql, $params);
2540 if ($posts->num > $rated->num) {
2541 return $posts->num - $rated->num;
2543 return 0; // Just in case there was a counting error
2554 * Get all discussions in a forum
2559 * @uses CONTEXT_MODULE
2560 * @uses VISIBLEGROUPS
2562 * @param string $forumsort
2563 * @param bool $fullpost
2564 * @param int $unused
2566 * @param bool $userlastmodified
2568 * @param int $perpage
2571 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2572 global $CFG, $DB, $USER;
2576 $now = round(time(), -2);
2577 $params = array($cm->instance);
2579 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2581 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2585 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2587 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2588 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2592 $timelimit .= " OR d.userid = ?";
2593 $params[] = $USER->id;
2602 } else if ($page != -1) {
2603 $limitfrom = $page*$perpage;
2604 $limitnum = $perpage;
2610 $groupmode = groups_get_activity_groupmode($cm);
2611 $currentgroup = groups_get_activity_group($cm);
2614 if (empty($modcontext)) {
2615 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2618 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2619 if ($currentgroup) {
2620 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2621 $params[] = $currentgroup;
2627 //seprate groups without access all
2628 if ($currentgroup) {
2629 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2630 $params[] = $currentgroup;
2632 $groupselect = "AND d.groupid = -1";
2640 if (empty($forumsort)) {
2641 $forumsort = "d.timemodified DESC";
2643 if (empty($fullpost)) {
2644 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2649 if (empty($userlastmodified)) { // We don't need to know this
2653 $umfields = ", um.firstname AS umfirstname, um.lastname AS umlastname";
2654 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2657 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend,
2658 u.firstname, u.lastname, u.email, u.picture, u.imagealt $umfields
2659 FROM {forum_discussions} d
2660 JOIN {forum_posts} p ON p.discussion = d.id
2661 JOIN {user} u ON p.userid = u.id
2663 WHERE d.forum = ? AND p.parent = 0
2664 $timelimit $groupselect
2665 ORDER BY $forumsort";
2666 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2674 * @uses CONTEXT_MODULE
2675 * @uses VISIBLEGROUPS
2679 function forum_get_discussions_unread($cm) {
2680 global $CFG, $DB, $USER;
2682 $now = round(time(), -2);
2683 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2686 $groupmode = groups_get_activity_groupmode($cm);
2687 $currentgroup = groups_get_activity_group($cm);
2690 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2692 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2693 if ($currentgroup) {
2694 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2695 $params['currentgroup'] = $currentgroup;
2701 //separate groups without access all
2702 if ($currentgroup) {
2703 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2704 $params['currentgroup'] = $currentgroup;
2706 $groupselect = "AND d.groupid = -1";
2713 if (!empty($CFG->forum_enabletimedposts)) {
2714 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2715 $params['now1'] = $now;
2716 $params['now2'] = $now;
2721 $sql = "SELECT d.id, COUNT(p.id) AS unread
2722 FROM {forum_discussions} d
2723 JOIN {forum_posts} p ON p.discussion = d.id
2724 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2725 WHERE d.forum = {$cm->instance}
2726 AND p.modified >= :cutoffdate AND r.id is NULL
2730 $params['cutoffdate'] = $cutoffdate;
2732 if ($unreads = $DB->get_records_sql($sql, $params)) {
2733 foreach ($unreads as $unread) {
2734 $unreads[$unread->id] = $unread->unread;
2746 * @uses CONEXT_MODULE
2747 * @uses VISIBLEGROUPS
2751 function forum_get_discussions_count($cm) {
2752 global $CFG, $DB, $USER;
2754 $now = round(time(), -2);
2755 $params = array($cm->instance);
2756 $groupmode = groups_get_activity_groupmode($cm);
2757 $currentgroup = groups_get_activity_group($cm);
2760 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2762 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2763 if ($currentgroup) {
2764 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2765 $params[] = $currentgroup;
2771 //seprate groups without access all
2772 if ($currentgroup) {
2773 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2774 $params[] = $currentgroup;
2776 $groupselect = "AND d.groupid = -1";
2783 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2787 if (!empty($CFG->forum_enabletimedposts)) {
2789 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2791 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2792 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2796 $timelimit .= " OR d.userid = ?";
2797 $params[] = $USER->id;
2803 $sql = "SELECT COUNT(d.id)
2804 FROM {forum_discussions} d
2805 JOIN {forum_posts} p ON p.discussion = d.id
2806 WHERE d.forum = ? AND p.parent = 0
2807 $groupselect $timelimit";
2809 return $DB->get_field_sql($sql, $params);
2814 * Get all discussions started by a particular user in a course (or group)
2815 * This function no longer used ...
2817 * @todo Remove this function if no longer used
2820 * @param int $courseid
2821 * @param int $userid
2822 * @param int $groupid
2825 function forum_get_user_discussions($courseid, $userid, $groupid=0) {
2827 $params = array($courseid, $userid);
2829 $groupselect = " AND d.groupid = ? ";
2830 $params[] = $groupid;
2835 return $DB->get_records_sql("SELECT p.*, d.groupid, u.firstname, u.lastname, u.email, u.picture, u.imagealt,
2836 f.type as forumtype, f.name as forumname, f.id as forumid
2837 FROM {forum_discussions} d,
2842 AND p.discussion = d.id
2846 AND d.forum = f.id $groupselect
2847 ORDER BY p.created DESC", $params);
2851 * Get the list of potential subscribers to a forum.
2853 * @param object $forumcontext the forum context.
2854 * @param integer $groupid the id of a group, or 0 for all groups.
2855 * @param string $fields the list of fields to return for each user. As for get_users_by_capability.
2856 * @param string $sort sort order. As for get_users_by_capability.
2857 * @return array list of users.
2859 function forum_get_potential_subscribers($forumcontext, $groupid, $fields, $sort) {
2862 // only active enrolled users or everybody on the frontpage
2863 list($esql, $params) = get_enrolled_sql($forumcontext, '', $groupid, true);
2865 $sql = "SELECT $fields
2867 JOIN ($esql) je ON je.id = u.id";
2869 $sql = "$sql ORDER BY $sort";
2871 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2874 return $DB->get_records_sql($sql, $params);
2878 * Returns list of user objects that are subscribed to this forum
2882 * @param object $course the course
2883 * @param forum $forum the forum
2884 * @param integer $groupid group id, or 0 for all.
2885 * @param object $context the forum context, to save re-fetching it where possible.
2886 * @param string $fields requested user fields (with "u." table prefix)
2887 * @return array list of users.
2889 function forum_subscribed_users($course, $forum, $groupid=0, $context = null, $fields = null) {
2892 if (empty($fields)) {
2915 if (empty($context)) {
2916 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
2917 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2920 if (forum_is_forcesubscribed($forum)) {
2921 $results = forum_get_potential_subscribers($context, $groupid, $fields, "u.email ASC");
2924 // only active enrolled users or everybody on the frontpage
2925 list($esql, $params) = get_enrolled_sql($context, '', $groupid, true);
2926 $params['forumid'] = $forum->id;
2927 $results = $DB->get_records_sql("SELECT $fields
2929 JOIN ($esql) je ON je.id = u.id
2930 JOIN {forum_subscriptions} s ON s.userid = u.id
2931 WHERE s.forum = :forumid
2932 ORDER BY u.email ASC", $params);
2935 // Guest user should never be subscribed to a forum.
2936 unset($results[$CFG->siteguest]);
2943 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2949 * @param int $courseid
2950 * @param string $type
2952 function forum_get_course_forum($courseid, $type) {
2953 // How to set up special 1-per-course forums
2954 global $CFG, $DB, $OUTPUT;
2956 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2957 // There should always only be ONE, but with the right combination of
2958 // errors there might be more. In this case, just return the oldest one (lowest ID).
2959 foreach ($forums as $forum) {
2960 return $forum; // ie the first one
2964 // Doesn't exist, so create one now.
2965 $forum = new stdClass();
2966 $forum->course = $courseid;
2967 $forum->type = "$type";
2968 switch ($forum->type) {
2970 $forum->name = get_string("namenews", "forum");
2971 $forum->intro = get_string("intronews", "forum");
2972 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2973 $forum->assessed = 0;
2974 if ($courseid == SITEID) {
2975 $forum->name = get_string("sitenews");
2976 $forum->forcesubscribe = 0;
2980 $forum->name = get_string("namesocial", "forum");
2981 $forum->intro = get_string("introsocial", "forum");
2982 $forum->assessed = 0;
2983 $forum->forcesubscribe = 0;
2986 $forum->name = get_string('blogforum', 'forum');
2987 $forum->intro = get_string('introblog', 'forum');
2988 $forum->assessed = 0;
2989 $forum->forcesubscribe = 0;
2992 echo $OUTPUT->notification("That forum type doesn't exist!");
2997 $forum->timemodified = time();
2998 $forum->id = $DB->insert_record("forum", $forum);
3000 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
3001 echo $OUTPUT->notification("Could not find forum module!!");
3004 $mod = new stdClass();
3005 $mod->course = $courseid;
3006 $mod->module = $module->id;
3007 $mod->instance = $forum->id;
3009 if (! $mod->coursemodule = add_course_module($mod) ) { // assumes course/lib.php is loaded
3010 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3013 if (! $sectionid = add_mod_to_section($mod) ) { // assumes course/lib.php is loaded
3014 echo $OUTPUT->notification("Could not add the new course module to that section");
3017 $DB->set_field("course_modules", "section", $sectionid, array("id" => $mod->coursemodule));
3019 include_once("$CFG->dirroot/course/lib.php");
3020 rebuild_course_cache($courseid);
3022 return $DB->get_record("forum", array("id" => "$forum->id"));
3027 * Given the data about a posting, builds up the HTML to display it and
3028 * returns the HTML in a string. This is designed for sending via HTML email.
3031 * @param object $course
3033 * @param object $forum
3034 * @param object $discussion
3035 * @param object $post
3036 * @param object $userform
3037 * @param object $userto
3038 * @param bool $ownpost
3039 * @param bool $reply
3042 * @param string $footer
3045 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
3046 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
3048 global $CFG, $OUTPUT;
3050 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
3052 if (!isset($userto->viewfullnames[$forum->id])) {
3053 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3055 $viewfullnames = $userto->viewfullnames[$forum->id];
3058 // add absolute file links
3059 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3061 // format the post body
3062 $options = new stdClass();
3063 $options->para = true;
3064 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
3066 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3068 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3069 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
3072 if ($post->parent) {
3073 $output .= '<td class="topic">';
3075 $output .= '<td class="topic starter">';
3077 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3079 $fullname = fullname($userfrom, $viewfullnames);
3080 $by = new stdClass();
3081 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&course='.$course->id.'">'.$fullname.'</a>';
3082 $by->date = userdate($post->modified, '', $userto->timezone);
3083 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3085 $output .= '</td></tr>';
3087 $output .= '<tr><td class="left side" valign="top">';
3089 if (isset($userfrom->groups)) {
3090 $groups = $userfrom->groups[$forum->id];
3092 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3096 $output .= print_group_picture($groups, $course->id, false, true, true);
3098 $output .= ' ';
3101 $output .= '</td><td class="content">';
3103 $attachments = forum_print_attachments($post, $cm, 'html');
3104 if ($attachments !== '') {
3105 $output .= '<div class="attachments">';
3106 $output .= $attachments;
3107 $output .= '</div>';
3110 $output .= $formattedtext;
3113 $commands = array();
3115 if ($post->parent) {
3116 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3117 $post->discussion.'&parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3121 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3122 get_string('reply', 'forum').'</a>';
3125 $output .= '<div class="commands">';
3126 $output .= implode(' | ', $commands);
3127 $output .= '</div>';
3129 // Context link to post if required
3131 $output .= '<div class="link">';
3132 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3133 get_string('postincontext', 'forum').'</a>';
3134 $output .= '</div>';
3138 $output .= '<div class="footer">'.$footer.'</div>';
3140 $output .= '</td></tr></table>'."\n\n";
3146 * Print a forum post
3150 * @uses FORUM_MODE_THREADED
3151 * @uses PORTFOLIO_FORMAT_PLAINHTML
3152 * @uses PORTFOLIO_FORMAT_FILE
3153 * @uses PORTFOLIO_FORMAT_RICHHTML
3154 * @uses PORTFOLIO_ADD_TEXT_LINK
3155 * @uses CONTEXT_MODULE
3156 * @param object $post The post to print.
3157 * @param object $discussion
3158 * @param object $forum
3160 * @param object $course
3161 * @param boolean $ownpost Whether this post belongs to the current user.
3162 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3163 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3164 * @param string $footer Extra stuff to print after the message.
3165 * @param string $highlight Space-separated list of terms to highlight.
3166 * @param int $post_read true, false or -99. If we already know whether this user
3167 * has read this post, pass that in, otherwise, pass in -99, and this
3168 * function will work it out.
3169 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3170 * the current user can't see this post, if this argument is true
3171 * (the default) then print a dummy 'you can't see this post' post.
3172 * If false, don't output anything at all.
3173 * @param bool|null $istracked
3176 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3177 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3178 global $USER, $CFG, $OUTPUT;
3180 require_once($CFG->libdir . '/filelib.php');
3185 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
3187 $post->course = $course->id;
3188 $post->forum = $forum->id;
3189 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3192 if (!isset($cm->cache)) {
3193 $cm->cache = new stdClass;
3196 if (!isset($cm->cache->caps)) {
3197 $cm->cache->caps = array();
3198 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3199 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3200 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3201 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3202 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3203 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3204 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3205 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3206 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3209 if (!isset($cm->uservisible)) {
3210 $cm->uservisible = coursemodule_visible_for_user($cm);
3213 if ($istracked && is_null($postisread)) {
3214 $postisread = forum_tp_is_post_read($USER->id, $post);
3217 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3219 if (!$dummyifcantsee) {
3226 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3227 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'));
3228 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3229 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3230 if ($post->parent) {
3231 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3233 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3235 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class'=>'subject')); // Subject
3236 $output .= html_writer::tag('div', get_string('forumauthorhidden','forum'), array('class'=>'author')); // author
3237 $output .= html_writer::end_tag('div');
3238 $output .= html_writer::end_tag('div'); // row
3239 $output .= html_writer::start_tag('div', array('class'=>'row'));
3240 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3241 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3242 $output .= html_writer::end_tag('div'); // row
3243 $output .= html_writer::end_tag('div'); // forumpost
3253 $str = new stdClass;
3254 $str->edit = get_string('edit', 'forum');
3255 $str->delete = get_string('delete', 'forum');
3256 $str->reply = get_string('reply', 'forum');
3257 $str->parent = get_string('parent', 'forum');
3258 $str->pruneheading = get_string('pruneheading', 'forum');
3259 $str->prune = get_string('prune', 'forum');
3260 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3261 $str->markread = get_string('markread', 'forum');
3262 $str->markunread = get_string('markunread', 'forum');
3265 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3267 // Build an object that represents the posting user
3268 $postuser = new stdClass;
3269 $postuser->id = $post->userid;
3270 $postuser->firstname = $post->firstname;
3271 $postuser->lastname = $post->lastname;
3272 $postuser->imagealt = $post->imagealt;
3273 $postuser->picture = $post->picture;
3274 $postuser->email = $post->email;
3275 // Some handy things for later on
3276 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3277 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3279 // Prepare the groups the posting user belongs to
3280 if (isset($cm->cache->usersgroups)) {
3282 if (isset($cm->cache->usersgroups[$post->userid])) {
3283 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3284 $groups[$gid] = $cm->cache->groups[$gid];
3288 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3291 // Prepare the attachements for the post, files then images
3292 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3294 // Determine if we need to shorten this post
3295 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3298 // Prepare an array of commands
3299 $commands = array();
3301 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3302 // Don't display the mark read / unread controls in this case.
3303 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3304 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3305 $text = $str->markunread;
3307 $url->param('mark', 'read');
3308 $text = $str->markread;
3310 if ($str->displaymode == FORUM_MODE_THREADED) {
3311 $url->param('parent', $post->parent);
3313 $url->set_anchor('p'.$post->id);
3315 $commands[] = array('url'=>$url, 'text'=>$text);
3318 // Zoom in to the parent specifically
3319 if ($post->parent) {
3320 $url = new moodle_url($discussionlink);
3321 if ($str->displaymode == FORUM_MODE_THREADED) {
3322 $url->param('parent', $post->parent);
3324 $url->set_anchor('p'.$post->parent);
3326 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3329 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3330 $age = time() - $post->created;
3331 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3334 if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3335 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3338 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3339 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3342 if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3343 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3347 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mform1', array('reply'=>$post->id)), 'text'=>$str->reply);
3350 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3351 $p = array('postid' => $post->id);
3352 require_once($CFG->libdir.'/portfoliolib.php');
3353 $button = new portfolio_add_button();
3354 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), '/mod/forum/locallib.php');
3355 if (empty($attachments)) {
3356 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3358 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3361 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3362 if (!empty($porfoliohtml)) {
3363 $commands[] = $porfoliohtml;
3366 // Finished building commands
3375 $forumpostclass = ' read';
3377 $forumpostclass = ' unread';
3378 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3381 // ignore trackign status if not tracked or tracked param missing
3382 $forumpostclass = '';
3386 if (empty($post->parent)) {
3387 $topicclass = ' firstpost starter';
3390 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3391 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass));
3392 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3393 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3394 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3395 $output .= html_writer::end_tag('div');
3398 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3400 $postsubject = $post->subject;
3401 if (empty($post->subjectnoformat)) {
3402 $postsubject = format_string($postsubject);
3404 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject'));
3406 $by = new stdClass();
3407 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3408 $by->date = userdate($post->modified);
3409 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author'));
3411 $output .= html_writer::end_tag('div'); //topic
3412 $output .= html_writer::end_tag('div'); //row
3414 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3415 $output .= html_writer::start_tag('div', array('class'=>'left'));
3419 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3421 if (empty($groupoutput)) {
3422 $groupoutput = ' ';
3424 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3426 $output .= html_writer::end_tag('div'); //left side
3427 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3428 $output .= html_writer::start_tag('div', array('class'=>'content'));
3429 if (!empty($attachments)) {
3430 $output .= html_writer::tag('div', $attachments, array('class'=>'attachments'));
3433 $options = new stdClass;
3434 $options->para = false;
3435 $options->trusted = $post->messagetrust;
3436 $options->context = $modcontext;
3438 // Prepare shortened version
3439 $postclass = 'shortenedpost';
3440 $postcontent = format_text(forum_shorten_post($post->message), $post->messageformat, $options, $course->id);
3441 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3442 $postcontent .= html_writer::tag('span', '('.get_string('numwords', 'moodle', count_words(strip_tags($post->message))).')...', array('class'=>'post-word-count'));
3444 // Prepare whole post
3445 $postclass = 'fullpost';
3446 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3447 if (!empty($highlight)) {
3448 $postcontent = highlight($highlight, $postcontent);
3450 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3452 // Output the post content
3453 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3454 $output .= html_writer::end_tag('div'); // Content
3455 $output .= html_writer::end_tag('div'); // Content mask
3456 $output .= html_writer::end_tag('div'); // Row
3458 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3459 $output .= html_writer::tag('div',' ', array('class'=>'left'));
3460 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3463 if (!empty($post->rating)) {
3464 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3467 // Output the commands
3468 $commandhtml = array();
3469 foreach ($commands as $command) {
3470 if (is_array($command)) {
3471 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3473 $commandhtml[] = $command;
3476 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3478 // Output link to post if required
3480 if ($post->replies == 1) {
3481 $replystring = get_string('repliesone', 'forum', $post->replies);
3483 $replystring = get_string('repliesmany', 'forum', $post->replies);
3486 $output .= html_writer::start_tag('div', array('class'=>'link'));
3487 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3488 $output .= ' ('.$replystring.')';
3489 $output .= html_writer::end_tag('div'); // link
3492 // Output footer if required