3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // 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 /** Include required files */
25 require_once($CFG->libdir.'/filelib.php');
26 require_once($CFG->libdir.'/eventslib.php');
27 require_once($CFG->dirroot.'/user/selector/lib.php');
29 /// CONSTANTS ///////////////////////////////////////////////////////////
31 define('FORUM_MODE_FLATOLDEST', 1);
32 define('FORUM_MODE_FLATNEWEST', -1);
33 define('FORUM_MODE_THREADED', 2);
34 define('FORUM_MODE_NESTED', 3);
36 define('FORUM_CHOOSESUBSCRIBE', 0);
37 define('FORUM_FORCESUBSCRIBE', 1);
38 define('FORUM_INITIALSUBSCRIBE', 2);
39 define('FORUM_DISALLOWSUBSCRIBE',3);
41 define('FORUM_TRACKING_OFF', 0);
42 define('FORUM_TRACKING_OPTIONAL', 1);
43 define('FORUM_TRACKING_ON', 2);
45 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
48 * Given an object containing all the necessary data,
49 * (defined by the form in mod_form.php) this function
50 * will create a new instance and return the id number
51 * of the new instance.
55 * @param object $forum add forum instance (with magic quotes)
56 * @return int intance id
58 function forum_add_instance($forum, $mform) {
61 $forum->timemodified = time();
63 if (empty($forum->assessed)) {
67 if (empty($forum->ratingtime) or empty($forum->assessed)) {
68 $forum->assesstimestart = 0;
69 $forum->assesstimefinish = 0;
72 $forum->id = $DB->insert_record('forum', $forum);
73 $modcontext = get_context_instance(CONTEXT_MODULE, $forum->coursemodule);
75 if ($forum->type == 'single') { // Create related discussion.
76 $discussion = new stdClass();
77 $discussion->course = $forum->course;
78 $discussion->forum = $forum->id;
79 $discussion->name = $forum->name;
80 $discussion->assessed = $forum->assessed;
81 $discussion->message = $forum->intro;
82 $discussion->messageformat = $forum->introformat;
83 $discussion->messagetrust = trusttext_trusted(get_context_instance(CONTEXT_COURSE, $forum->course));
84 $discussion->mailnow = false;
85 $discussion->groupid = -1;
89 $discussion->id = forum_add_discussion($discussion, null, $message);
91 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
92 // ugly hack - we need to copy the files somehow
93 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
94 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
96 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, array('subdirs'=>true), $post->message);
97 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
101 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
102 /// all users should be subscribed initially
103 /// Note: forum_get_potential_subscribers should take the forum context,
104 /// but that does not exist yet, becuase the forum is only half build at this
105 /// stage. However, because the forum is brand new, we know that there are
106 /// no role assignments or overrides in the forum context, so using the
107 /// course context gives the same list of users.
108 $users = forum_get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
109 foreach ($users as $user) {
110 forum_subscribe($user->id, $forum->id);
114 forum_grade_item_update($forum);
121 * Given an object containing all the necessary data,
122 * (defined by the form in mod_form.php) this function
123 * will update an existing instance with new data.
126 * @param object $forum forum instance (with magic quotes)
127 * @return bool success
129 function forum_update_instance($forum, $mform) {
130 global $DB, $OUTPUT, $USER;
132 $forum->timemodified = time();
133 $forum->id = $forum->instance;
135 if (empty($forum->assessed)) {
136 $forum->assessed = 0;
139 if (empty($forum->ratingtime) or empty($forum->assessed)) {
140 $forum->assesstimestart = 0;
141 $forum->assesstimefinish = 0;
144 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
146 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
147 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
148 // 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
149 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
150 forum_update_grades($forum); // recalculate grades for the forum
153 if ($forum->type == 'single') { // Update related discussion and post.
154 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
155 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC')) {
156 echo $OUTPUT->notification('Warning! There is more than one discussion in this forum - using the most recent');
157 $discussion = array_pop($discussions);
159 // try to recover by creating initial discussion - MDL-16262
160 $discussion = new stdClass();
161 $discussion->course = $forum->course;
162 $discussion->forum = $forum->id;
163 $discussion->name = $forum->name;
164 $discussion->assessed = $forum->assessed;
165 $discussion->message = $forum->intro;
166 $discussion->messageformat = $forum->introformat;
167 $discussion->messagetrust = true;
168 $discussion->mailnow = false;
169 $discussion->groupid = -1;
173 forum_add_discussion($discussion, null, $message);
175 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
176 print_error('cannotadd', 'forum');
180 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
181 print_error('cannotfindfirstpost', 'forum');
184 $cm = get_coursemodule_from_instance('forum', $forum->id);
185 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
187 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
188 // ugly hack - we need to copy the files somehow
189 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
190 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
192 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, array('subdirs'=>true), $post->message);
195 $post->subject = $forum->name;
196 $post->message = $forum->intro;
197 $post->messageformat = $forum->introformat;
198 $post->messagetrust = trusttext_trusted($modcontext);
199 $post->modified = $forum->timemodified;
200 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities
202 $DB->update_record('forum_posts', $post);
203 $discussion->name = $forum->name;
204 $DB->update_record('forum_discussions', $discussion);
207 $DB->update_record('forum', $forum);
209 forum_grade_item_update($forum);
216 * Given an ID of an instance of this module,
217 * this function will permanently delete the instance
218 * and any data that depends on it.
221 * @param int $id forum instance id
222 * @return bool success
224 function forum_delete_instance($id) {
227 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
230 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
233 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
237 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
239 // now get rid of all files
240 $fs = get_file_storage();
241 $fs->delete_area_files($context->id);
245 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
246 foreach ($discussions as $discussion) {
247 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
253 if (!$DB->delete_records('forum_subscriptions', array('forum'=>$forum->id))) {
257 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
259 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
263 forum_grade_item_delete($forum);
270 * Indicates API features that the forum supports.
272 * @uses FEATURE_GROUPS
273 * @uses FEATURE_GROUPINGS
274 * @uses FEATURE_GROUPMEMBERSONLY
275 * @uses FEATURE_MOD_INTRO
276 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
277 * @uses FEATURE_COMPLETION_HAS_RULES
278 * @uses FEATURE_GRADE_HAS_GRADE
279 * @uses FEATURE_GRADE_OUTCOMES
280 * @param string $feature
281 * @return mixed True if yes (some features may use other values)
283 function forum_supports($feature) {
285 case FEATURE_GROUPS: return true;
286 case FEATURE_GROUPINGS: return true;
287 case FEATURE_GROUPMEMBERSONLY: return true;
288 case FEATURE_MOD_INTRO: return true;
289 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
290 case FEATURE_COMPLETION_HAS_RULES: return true;
291 case FEATURE_GRADE_HAS_GRADE: return true;
292 case FEATURE_GRADE_OUTCOMES: return true;
293 case FEATURE_RATE: return true;
294 case FEATURE_BACKUP_MOODLE2: return true;
296 default: return null;
302 * Obtains the automatic completion state for this forum based on any conditions
307 * @param object $course Course
308 * @param object $cm Course-module
309 * @param int $userid User ID
310 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
311 * @return bool True if completed, false if not. (If no conditions, then return
312 * value depends on comparison type)
314 function forum_get_completion_state($course,$cm,$userid,$type) {
318 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
319 throw new Exception("Can't find forum {$cm->instance}");
322 $result=$type; // Default return value
324 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
330 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
332 fp.userid=:userid AND fd.forum=:forumid";
334 if ($forum->completiondiscussions) {
335 $value = $forum->completiondiscussions <=
336 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
337 if ($type == COMPLETION_AND) {
338 $result = $result && $value;
340 $result = $result || $value;
343 if ($forum->completionreplies) {
344 $value = $forum->completionreplies <=
345 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
346 if ($type==COMPLETION_AND) {
347 $result = $result && $value;
349 $result = $result || $value;
352 if ($forum->completionposts) {
353 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
354 if ($type == COMPLETION_AND) {
355 $result = $result && $value;
357 $result = $result || $value;
366 * Function to be run periodically according to the moodle cron
367 * Finds all posts that have yet to be mailed out, and mails them
368 * out to all subscribers
373 * @uses CONTEXT_MODULE
374 * @uses CONTEXT_COURSE
379 function forum_cron() {
380 global $CFG, $USER, $DB;
384 // all users that are subscribed to any post that needs sending
388 $mailcount = array();
389 $errorcount = array();
392 $discussions = array();
395 $coursemodules = array();
396 $subscribedusers = array();
399 // Posts older than 2 days will not be mailed. This is to avoid the problem where
400 // cron has not been running for a long time, and then suddenly people are flooded
401 // with mail from the past few weeks or months
403 $endtime = $timenow - $CFG->maxeditingtime;
404 $starttime = $endtime - 48 * 3600; // Two days earlier
406 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
407 // Mark them all now as being mailed. It's unlikely but possible there
408 // might be an error later so that a post is NOT actually mailed out,
409 // but since mail isn't crucial, we can accept this risk. Doing it now
410 // prevents the risk of duplicated mails, which is a worse problem.
412 if (!forum_mark_old_posts_as_mailed($endtime)) {
413 mtrace('Errors occurred while trying to mark some posts as being mailed.');
414 return false; // Don't continue trying to mail them, in case we are in a cron loop
417 // checking post validity, and adding users to loop through later
418 foreach ($posts as $pid => $post) {
420 $discussionid = $post->discussion;
421 if (!isset($discussions[$discussionid])) {
422 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
423 $discussions[$discussionid] = $discussion;
425 mtrace('Could not find discussion '.$discussionid);
430 $forumid = $discussions[$discussionid]->forum;
431 if (!isset($forums[$forumid])) {
432 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
433 $forums[$forumid] = $forum;
435 mtrace('Could not find forum '.$forumid);
440 $courseid = $forums[$forumid]->course;
441 if (!isset($courses[$courseid])) {
442 if ($course = $DB->get_record('course', array('id' => $courseid))) {
443 $courses[$courseid] = $course;
445 mtrace('Could not find course '.$courseid);
450 if (!isset($coursemodules[$forumid])) {
451 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
452 $coursemodules[$forumid] = $cm;
454 mtrace('Could not find course module for forum '.$forumid);
461 // caching subscribed users of each forum
462 if (!isset($subscribedusers[$forumid])) {
463 $modcontext = get_context_instance(CONTEXT_MODULE, $coursemodules[$forumid]->id);
464 if ($subusers = forum_subscribed_users($courses[$courseid], $forums[$forumid], 0, $modcontext, "u.*")) {
465 foreach ($subusers as $postuser) {
466 unset($postuser->description); // not necessary
467 // this user is subscribed to this forum
468 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
469 // this user is a user we have to process later
470 $users[$postuser->id] = $postuser;
472 unset($subusers); // release memory
476 $mailcount[$pid] = 0;
477 $errorcount[$pid] = 0;
481 if ($users && $posts) {
483 $urlinfo = parse_url($CFG->wwwroot);
484 $hostname = $urlinfo['host'];
486 foreach ($users as $userto) {
488 @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes
490 // set this so that the capabilities are cached, and environment matches receiving user
491 cron_setup_user($userto);
493 mtrace('Processing user '.$userto->id);
496 $userto->viewfullnames = array();
497 $userto->canpost = array();
498 $userto->markposts = array();
501 foreach ($coursemodules as $forumid=>$unused) {
502 $coursemodules[$forumid]->cache = new stdClass();
503 $coursemodules[$forumid]->cache->caps = array();
504 unset($coursemodules[$forumid]->uservisible);
507 foreach ($posts as $pid => $post) {
509 // Set up the environment for the post, discussion, forum, course
510 $discussion = $discussions[$post->discussion];
511 $forum = $forums[$discussion->forum];
512 $course = $courses[$forum->course];
513 $cm =& $coursemodules[$forum->id];
515 // Do some checks to see if we can bail out now
516 // Only active enrolled users are in the list of subscribers
517 if (!isset($subscribedusers[$forum->id][$userto->id])) {
518 continue; // user does not subscribe to this forum
521 // Don't send email if the forum is Q&A and the user has not posted
522 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id)) {
523 mtrace('Did not email '.$userto->id.' because user has not posted in discussion');
527 // Get info about the sending user
528 if (array_key_exists($post->userid, $users)) { // we might know him/her already
529 $userfrom = $users[$post->userid];
530 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
531 unset($userfrom->description); // not necessary
532 $users[$userfrom->id] = $userfrom; // fetch only once, we can add it to user list, it will be skipped anyway
534 mtrace('Could not find user '.$post->userid);
538 //if we want to check that userto and userfrom are not the same person this is probably the spot to do it
540 // setup global $COURSE properly - needed for roles and languages
541 cron_setup_user($userto, $course);
544 if (!isset($userto->viewfullnames[$forum->id])) {
545 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
546 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
548 if (!isset($userto->canpost[$discussion->id])) {
549 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
550 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
552 if (!isset($userfrom->groups[$forum->id])) {
553 if (!isset($userfrom->groups)) {
554 $userfrom->groups = array();
555 $users[$userfrom->id]->groups = array();
557 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
558 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
561 // Make sure groups allow this user to see this email
562 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
563 if (!groups_group_exists($discussion->groupid)) { // Can't find group
564 continue; // Be safe and don't send it to anyone
567 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
568 // do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
573 // Make sure we're allowed to see it...
574 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
575 mtrace('user '.$userto->id. ' can not see '.$post->id);
579 // OK so we need to send the email.
581 // Does the user want this post in a digest? If so postpone it for now.
582 if ($userto->maildigest > 0) {
583 // This user wants the mails to be in digest form
584 $queue = new stdClass();
585 $queue->userid = $userto->id;
586 $queue->discussionid = $discussion->id;
587 $queue->postid = $post->id;
588 $queue->timemodified = $post->created;
589 $DB->insert_record('forum_queue', $queue);
594 // Prepare to actually send the post now, and build up the content
596 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
598 $userfrom->customheaders = array ( // Headers to make emails easier to track
600 'List-Id: "'.$cleanforumname.'" <moodleforum'.$forum->id.'@'.$hostname.'>',
601 'List-Help: '.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id,
602 'Message-ID: <moodlepost'.$post->id.'@'.$hostname.'>',
603 'X-Course-Id: '.$course->id,
604 'X-Course-Name: '.format_string($course->fullname, true)
607 if ($post->parent) { // This post is a reply, so add headers for threading (see MDL-22551)
608 $userfrom->customheaders[] = 'In-Reply-To: <moodlepost'.$post->parent.'@'.$hostname.'>';
609 $userfrom->customheaders[] = 'References: <moodlepost'.$post->parent.'@'.$hostname.'>';
612 $postsubject = "$course->shortname: ".format_string($post->subject,true);
613 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
614 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto);
616 // Send the post now!
618 mtrace('Sending ', '');
620 $eventdata = new stdClass();
621 $eventdata->component = 'mod_forum';
622 $eventdata->name = 'posts';
623 $eventdata->userfrom = $userfrom;
624 $eventdata->userto = $userto;
625 $eventdata->subject = $postsubject;
626 $eventdata->fullmessage = $posttext;
627 $eventdata->fullmessageformat = FORMAT_PLAIN;
628 $eventdata->fullmessagehtml = $posthtml;
629 $eventdata->notification = 1;
631 $smallmessagestrings = new stdClass();
632 $smallmessagestrings->user = fullname($userfrom);
633 $smallmessagestrings->forumname = "{$course->shortname}: ".format_string($forum->name,true).": ".$discussion->name;
634 $smallmessagestrings->message = $post->message;
635 //make sure strings are in message recipients language
636 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
638 $eventdata->contexturl = "{$CFG->wwwroot}/mod/forum/discuss.php?d={$discussion->id}#p{$post->id}";
639 $eventdata->contexturlname = $discussion->name;
641 $mailresult = message_send($eventdata);
643 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
644 " ($userto->email) .. not trying again.");
645 add_to_log($course->id, 'forum', 'mail error', "discuss.php?d=$discussion->id#p$post->id",
646 substr(format_string($post->subject,true),0,30), $cm->id, $userto->id);
647 $errorcount[$post->id]++;
649 $mailcount[$post->id]++;
651 // Mark post as read if forum_usermarksread is set off
652 if (!$CFG->forum_usermarksread) {
653 $userto->markposts[$post->id] = $post->id;
657 mtrace('post '.$post->id. ': '.$post->subject);
660 // mark processed posts as read
661 forum_tp_mark_posts_read($userto, $userto->markposts);
666 foreach ($posts as $post) {
667 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
668 if ($errorcount[$post->id]) {
669 $DB->set_field("forum_posts", "mailed", "2", array("id" => "$post->id"));
674 // release some memory
675 unset($subscribedusers);
681 $sitetimezone = $CFG->timezone;
683 // Now see if there are any digest mails waiting to be sent, and if we should send them
685 mtrace('Starting digest processing...');
687 @set_time_limit(300); // terminate if not able to fetch all digests in 5 minutes
689 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
690 set_config('digestmailtimelast', 0);
694 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
696 // Delete any really old ones (normally there shouldn't be any)
697 $weekago = $timenow - (7 * 24 * 3600);
698 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
699 mtrace ('Cleaned old digest records');
701 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
703 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
705 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
707 if ($digestposts_rs->valid()) {
709 // We have work to do
712 //caches - reuse the those filled before too
713 $discussionposts = array();
714 $userdiscussions = array();
716 foreach ($digestposts_rs as $digestpost) {
717 if (!isset($users[$digestpost->userid])) {
718 if ($user = $DB->get_record('user', array('id' => $digestpost->userid))) {
719 $users[$digestpost->userid] = $user;
724 $postuser = $users[$digestpost->userid];
726 if (!isset($posts[$digestpost->postid])) {
727 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
728 $posts[$digestpost->postid] = $post;
733 $discussionid = $digestpost->discussionid;
734 if (!isset($discussions[$discussionid])) {
735 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
736 $discussions[$discussionid] = $discussion;
741 $forumid = $discussions[$discussionid]->forum;
742 if (!isset($forums[$forumid])) {
743 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
744 $forums[$forumid] = $forum;
750 $courseid = $forums[$forumid]->course;
751 if (!isset($courses[$courseid])) {
752 if ($course = $DB->get_record('course', array('id' => $courseid))) {
753 $courses[$courseid] = $course;
759 if (!isset($coursemodules[$forumid])) {
760 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
761 $coursemodules[$forumid] = $cm;
766 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
767 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
769 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
771 // Data collected, start sending out emails to each user
772 foreach ($userdiscussions as $userid => $thesediscussions) {
774 @set_time_limit(120); // terminate if processing of any account takes longer than 2 minutes
778 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
780 // First of all delete all the queue entries for this user
781 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
782 $userto = $users[$userid];
784 // Override the language and timezone of the "current" user, so that
785 // mail is customised for the receiver.
786 cron_setup_user($userto);
789 $userto->viewfullnames = array();
790 $userto->canpost = array();
791 $userto->markposts = array();
793 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
795 $headerdata = new stdClass();
796 $headerdata->sitename = format_string($site->fullname, true);
797 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&course='.$site->id;
799 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
800 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
802 $posthtml = "<head>";
803 /* foreach ($CFG->stylesheets as $stylesheet) {
805 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
807 $posthtml .= "</head>\n<body id=\"email\">\n";
808 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
810 foreach ($thesediscussions as $discussionid) {
812 @set_time_limit(120); // to be reset for each post
814 $discussion = $discussions[$discussionid];
815 $forum = $forums[$discussion->forum];
816 $course = $courses[$forum->course];
817 $cm = $coursemodules[$forum->id];
820 cron_setup_user($userto, $course);
823 if (!isset($userto->viewfullnames[$forum->id])) {
824 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
825 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
827 if (!isset($userto->canpost[$discussion->id])) {
828 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
829 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
832 $strforums = get_string('forums', 'forum');
833 $canunsubscribe = ! forum_is_forcesubscribed($forum);
834 $canreply = $userto->canpost[$discussion->id];
836 $posttext .= "\n \n";
837 $posttext .= '=====================================================================';
838 $posttext .= "\n \n";
839 $posttext .= "$course->shortname -> $strforums -> ".format_string($forum->name,true);
840 if ($discussion->name != $forum->name) {
841 $posttext .= " -> ".format_string($discussion->name,true);
845 $posthtml .= "<p><font face=\"sans-serif\">".
846 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> -> ".
847 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
848 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
849 if ($discussion->name == $forum->name) {
850 $posthtml .= "</font></p>";
852 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
856 $postsarray = $discussionposts[$discussionid];
859 foreach ($postsarray as $postid) {
860 $post = $posts[$postid];
862 if (array_key_exists($post->userid, $users)) { // we might know him/her already
863 $userfrom = $users[$post->userid];
864 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
865 $users[$userfrom->id] = $userfrom; // fetch only once, we can add it to user list, it will be skipped anyway
867 mtrace('Could not find user '.$post->userid);
871 if (!isset($userfrom->groups[$forum->id])) {
872 if (!isset($userfrom->groups)) {
873 $userfrom->groups = array();
874 $users[$userfrom->id]->groups = array();
876 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
877 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
880 $userfrom->customheaders = array ("Precedence: Bulk");
882 if ($userto->maildigest == 2) {
884 $by = new stdClass();
885 $by->name = fullname($userfrom);
886 $by->date = userdate($post->modified);
887 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
888 $posttext .= "\n---------------------------------------------------------------------";
890 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&course=$course->id\">$by->name</a>";
891 $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>';
894 // The full treatment
895 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
896 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
898 // Create an array of postid's for this user to mark as read.
899 if (!$CFG->forum_usermarksread) {
900 $userto->markposts[$post->id] = $post->id;
904 if ($canunsubscribe) {
905 $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>";
907 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">".get_string("everyoneissubscribed", "forum")."</font></div>";
909 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
911 $posthtml .= '</body>';
913 if (empty($userto->mailformat) || $userto->mailformat != 1) {
914 // This user DOESN'T want to receive HTML
918 $attachment = $attachname='';
919 $usetrueaddress = true;
920 //directly email forum digests rather than sending them via messaging
921 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname, $usetrueaddress, $CFG->forum_replytouser);
925 echo "Error: mod/forum/cron.php: Could not send out digest mail to user $userto->id ($userto->email)... not trying again.\n";
926 add_to_log($course->id, 'forum', 'mail digest error', '', '', $cm->id, $userto->id);
931 // Mark post as read if forum_usermarksread is set off
932 forum_tp_mark_posts_read($userto, $userto->markposts);
936 /// We have finishied all digest emails, update $CFG->digestmailtimelast
937 set_config('digestmailtimelast', $timenow);
942 if (!empty($usermailcount)) {
943 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
946 if (!empty($CFG->forum_lastreadclean)) {
948 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
949 set_config('forum_lastreadclean', $timenow);
950 mtrace('Removing old forum read tracking info...');
951 forum_tp_clean_read_records();
954 set_config('forum_lastreadclean', time());
962 * Builds and returns the body of the email notification in plain text.
966 * @uses CONTEXT_MODULE
967 * @param object $course
969 * @param object $forum
970 * @param object $discussion
971 * @param object $post
972 * @param object $userfrom
973 * @param object $userto
974 * @param boolean $bare
975 * @return string The email body in plain text format.
977 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false) {
980 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
982 if (!isset($userto->viewfullnames[$forum->id])) {
983 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
985 $viewfullnames = $userto->viewfullnames[$forum->id];
988 if (!isset($userto->canpost[$discussion->id])) {
989 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
991 $canreply = $userto->canpost[$discussion->id];
995 $by->name = fullname($userfrom, $viewfullnames);
996 $by->date = userdate($post->modified, "", $userto->timezone);
998 $strbynameondate = get_string('bynameondate', 'forum', $by);
1000 $strforums = get_string('forums', 'forum');
1002 $canunsubscribe = ! forum_is_forcesubscribed($forum);
1007 $posttext = "$course->shortname -> $strforums -> ".format_string($forum->name,true);
1009 if ($discussion->name != $forum->name) {
1010 $posttext .= " -> ".format_string($discussion->name,true);
1014 // add absolute file links
1015 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1017 $posttext .= "\n---------------------------------------------------------------------\n";
1018 $posttext .= format_string($post->subject,true);
1020 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1022 $posttext .= "\n".$strbynameondate."\n";
1023 $posttext .= "---------------------------------------------------------------------\n";
1024 $posttext .= format_text_email($post->message, $post->messageformat);
1025 $posttext .= "\n\n";
1026 $posttext .= forum_print_attachments($post, $cm, "text");
1028 if (!$bare && $canreply) {
1029 $posttext .= "---------------------------------------------------------------------\n";
1030 $posttext .= get_string("postmailinfo", "forum", $course->shortname)."\n";
1031 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1033 if (!$bare && $canunsubscribe) {
1034 $posttext .= "\n---------------------------------------------------------------------\n";
1035 $posttext .= get_string("unsubscribe", "forum");
1036 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1043 * Builds and returns the body of the email notification in html format.
1046 * @param object $course
1048 * @param object $forum
1049 * @param object $discussion
1050 * @param object $post
1051 * @param object $userfrom
1052 * @param object $userto
1053 * @return string The email text in HTML format
1055 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto) {
1058 if ($userto->mailformat != 1) { // Needs to be HTML
1062 if (!isset($userto->canpost[$discussion->id])) {
1063 $canreply = forum_user_can_post($forum, $discussion, $userto);
1065 $canreply = $userto->canpost[$discussion->id];
1068 $strforums = get_string('forums', 'forum');
1069 $canunsubscribe = ! forum_is_forcesubscribed($forum);
1071 $posthtml = '<head>';
1072 /* foreach ($CFG->stylesheets as $stylesheet) {
1074 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1076 $posthtml .= '</head>';
1077 $posthtml .= "\n<body id=\"email\">\n\n";
1079 $posthtml .= '<div class="navbar">'.
1080 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->shortname.'</a> » '.
1081 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> » '.
1082 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1083 if ($discussion->name == $forum->name) {
1084 $posthtml .= '</div>';
1086 $posthtml .= ' » <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1087 format_string($discussion->name,true).'</a></div>';
1089 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1091 if ($canunsubscribe) {
1092 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">
1093 <a href="'.$CFG->wwwroot.'/mod/forum/subscribe.php?id='.$forum->id.'">'.get_string('unsubscribe', 'forum').'</a>
1094 <a href="'.$CFG->wwwroot.'/mod/forum/unsubscribeall.php">'.get_string('unsubscribeall', 'forum').'</a></div>';
1097 $posthtml .= '</body>';
1105 * @param object $course
1106 * @param object $user
1107 * @param object $mod TODO this is not used in this function, refactor
1108 * @param object $forum
1109 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1111 function forum_user_outline($course, $user, $mod, $forum) {
1113 require_once("$CFG->libdir/gradelib.php");
1114 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1115 if (empty($grades->items[0]->grades)) {
1118 $grade = reset($grades->items[0]->grades);
1121 $count = forum_count_user_posts($forum->id, $user->id);
1123 if ($count && $count->postcount > 0) {
1124 $result = new stdClass();
1125 $result->info = get_string("numposts", "forum", $count->postcount);
1126 $result->time = $count->lastpost;
1128 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1131 } else if ($grade) {
1132 $result = new stdClass();
1133 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1135 //datesubmitted == time created. dategraded == time modified or time overridden
1136 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1137 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1138 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1139 $result->time = $grade->dategraded;
1141 $result->time = $grade->datesubmitted;
1153 * @param object $coure
1154 * @param object $user
1155 * @param object $mod
1156 * @param object $forum
1158 function forum_user_complete($course, $user, $mod, $forum) {
1159 global $CFG,$USER, $OUTPUT;
1160 require_once("$CFG->libdir/gradelib.php");
1162 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1163 if (!empty($grades->items[0]->grades)) {
1164 $grade = reset($grades->items[0]->grades);
1165 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1166 if ($grade->str_feedback) {
1167 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1171 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1173 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1174 print_error('invalidcoursemodule');
1176 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1178 foreach ($posts as $post) {
1179 if (!isset($discussions[$post->discussion])) {
1182 $discussion = $discussions[$post->discussion];
1184 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1187 echo "<p>".get_string("noposts", "forum")."</p>";
1200 * @param array $courses
1201 * @param array $htmlarray
1203 function forum_print_overview($courses,&$htmlarray) {
1204 global $USER, $CFG, $DB, $SESSION;
1206 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1210 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1215 // get all forum logs in ONE query (much better!)
1217 $sql = "SELECT instance,cmid,l.course,COUNT(l.id) as count FROM {log} l "
1218 ." JOIN {course_modules} cm ON cm.id = cmid "
1220 foreach ($courses as $course) {
1221 $sql .= '(l.course = ? AND l.time > ?) OR ';
1222 $params[] = $course->id;
1223 $params[] = $course->lastaccess;
1225 $sql = substr($sql,0,-3); // take off the last OR
1227 $sql .= ") AND l.module = 'forum' AND action = 'add post' "
1228 ." AND userid != ? GROUP BY cmid,l.course,instance";
1230 $params[] = $USER->id;
1232 if (!$new = $DB->get_records_sql($sql, $params)) {
1233 $new = array(); // avoid warnings
1236 // also get all forum tracking stuff ONCE.
1237 $trackingforums = array();
1238 foreach ($forums as $forum) {
1239 if (forum_tp_can_track_forums($forum)) {
1240 $trackingforums[$forum->id] = $forum;
1244 if (count($trackingforums) > 0) {
1245 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1246 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1247 ' FROM {forum_posts} p '.
1248 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1249 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1250 $params = array($USER->id);
1252 foreach ($trackingforums as $track) {
1253 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1254 $params[] = $track->id;
1255 if (isset($SESSION->currentgroup[$track->course])) {
1256 $groupid = $SESSION->currentgroup[$track->course];
1258 $groupid = groups_get_all_groups($track->course, $USER->id);
1259 if (is_array($groupid)) {
1260 $groupid = array_shift(array_keys($groupid));
1261 $SESSION->currentgroup[$track->course] = $groupid;
1266 $params[] = $groupid;
1268 $sql = substr($sql,0,-3); // take off the last OR
1269 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1270 $params[] = $cutoffdate;
1272 if (!$unread = $DB->get_records_sql($sql, $params)) {
1279 if (empty($unread) and empty($new)) {
1283 $strforum = get_string('modulename','forum');
1284 $strnumunread = get_string('overviewnumunread','forum');
1285 $strnumpostssince = get_string('overviewnumpostssince','forum');
1287 foreach ($forums as $forum) {
1291 $showunread = false;
1292 // either we have something from logs, or trackposts, or nothing.
1293 if (array_key_exists($forum->id, $new) && !empty($new[$forum->id])) {
1294 $count = $new[$forum->id]->count;
1296 if (array_key_exists($forum->id,$unread)) {
1297 $thisunread = $unread[$forum->id]->count;
1300 if ($count > 0 || $thisunread > 0) {
1301 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1302 $forum->name.'</a></div>';
1303 $str .= '<div class="info"><span class="postsincelogin">';
1304 $str .= $count.' '.$strnumpostssince."</span>";
1305 if (!empty($showunread)) {
1306 $str .= '<div class="unreadposts">'.$thisunread .' '.$strnumunread.'</div>';
1308 $str .= '</div></div>';
1311 if (!array_key_exists($forum->course,$htmlarray)) {
1312 $htmlarray[$forum->course] = array();
1314 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1315 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1317 $htmlarray[$forum->course]['forum'] .= $str;
1323 * Given a course and a date, prints a summary of all the new
1324 * messages posted in the course since that date
1329 * @uses CONTEXT_MODULE
1330 * @uses VISIBLEGROUPS
1331 * @param object $course
1332 * @param bool $viewfullnames capability
1333 * @param int $timestart
1334 * @return bool success
1336 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1337 global $CFG, $USER, $DB, $OUTPUT;
1339 // do not use log table if possible, it may be huge and is expensive to join with other tables
1341 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1342 d.timestart, d.timeend, d.userid AS duserid,
1343 u.firstname, u.lastname, u.email, u.picture
1344 FROM {forum_posts} p
1345 JOIN {forum_discussions} d ON d.id = p.discussion
1346 JOIN {forum} f ON f.id = d.forum
1347 JOIN {user} u ON u.id = p.userid
1348 WHERE p.created > ? AND f.course = ?
1349 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1353 $modinfo =& get_fast_modinfo($course);
1355 $groupmodes = array();
1358 $strftimerecent = get_string('strftimerecent');
1360 $printposts = array();
1361 foreach ($posts as $post) {
1362 if (!isset($modinfo->instances['forum'][$post->forum])) {
1366 $cm = $modinfo->instances['forum'][$post->forum];
1367 if (!$cm->uservisible) {
1370 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1372 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1376 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1377 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1378 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1383 $groupmode = groups_get_activity_groupmode($cm, $course);
1386 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $context)) {
1387 // oki (Open discussions have groupid -1)
1390 if (isguestuser()) {
1395 if (is_null($modinfo->groups)) {
1396 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
1399 if (!array_key_exists($post->groupid, $modinfo->groups[0])) {
1405 $printposts[] = $post;
1413 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1414 echo "\n<ul class='unlist'>\n";
1416 foreach ($printposts as $post) {
1417 $subjectclass = empty($post->parent) ? ' bold' : '';
1419 echo '<li><div class="head">'.
1420 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1421 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1423 echo '<div class="info'.$subjectclass.'">';
1424 if (empty($post->parent)) {
1425 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1427 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&parent='.$post->parent.'#p'.$post->id.'">';
1429 $post->subject = break_up_long_words(format_string($post->subject, true));
1430 echo $post->subject;
1431 echo "</a>\"</div></li>\n";
1440 * Return grade for given user or all users.
1444 * @param object $forum
1445 * @param int $userid optional user id, 0 means all users
1446 * @return array array of grades, false if none
1448 function forum_get_user_grades($forum, $userid = 0) {
1451 require_once($CFG->dirroot.'/rating/lib.php');
1453 $ratingoptions = new stdClass;
1454 $ratingoptions->component = 'mod_forum';
1455 $ratingoptions->ratingarea = 'post';
1457 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1458 $ratingoptions->modulename = 'forum';
1459 $ratingoptions->moduleid = $forum->id;
1460 $ratingoptions->userid = $userid;
1461 $ratingoptions->aggregationmethod = $forum->assessed;
1462 $ratingoptions->scaleid = $forum->scale;
1463 $ratingoptions->itemtable = 'forum_posts';
1464 $ratingoptions->itemtableusercolumn = 'userid';
1466 $rm = new rating_manager();
1467 return $rm->get_user_grades($ratingoptions);
1471 * Update activity grades
1475 * @param object $forum
1476 * @param int $userid specific user only, 0 means all
1477 * @param boolean $nullifnone return null if grade does not exist
1480 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1482 require_once($CFG->libdir.'/gradelib.php');
1484 if (!$forum->assessed) {
1485 forum_grade_item_update($forum);
1487 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1488 forum_grade_item_update($forum, $grades);
1490 } else if ($userid and $nullifnone) {
1491 $grade = new stdClass();
1492 $grade->userid = $userid;
1493 $grade->rawgrade = NULL;
1494 forum_grade_item_update($forum, $grade);
1497 forum_grade_item_update($forum);
1502 * Update all grades in gradebook.
1505 function forum_upgrade_grades() {
1508 $sql = "SELECT COUNT('x')
1509 FROM {forum} f, {course_modules} cm, {modules} m
1510 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
1511 $count = $DB->count_records_sql($sql);
1513 $sql = "SELECT f.*, cm.idnumber AS cmidnumber, f.course AS courseid
1514 FROM {forum} f, {course_modules} cm, {modules} m
1515 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id";
1516 $rs = $DB->get_recordset_sql($sql);
1518 $pbar = new progress_bar('forumupgradegrades', 500, true);
1520 foreach ($rs as $forum) {
1522 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
1523 forum_update_grades($forum, 0, false);
1524 $pbar->update($i, $count, "Updating Forum grades ($i/$count).");
1531 * Create/update grade item for given forum
1534 * @uses GRADE_TYPE_NONE
1535 * @uses GRADE_TYPE_VALUE
1536 * @uses GRADE_TYPE_SCALE
1537 * @param object $forum object with extra cmidnumber
1538 * @param mixed $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1539 * @return int 0 if ok
1541 function forum_grade_item_update($forum, $grades=NULL) {
1543 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1544 require_once($CFG->libdir.'/gradelib.php');
1547 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1549 if (!$forum->assessed or $forum->scale == 0) {
1550 $params['gradetype'] = GRADE_TYPE_NONE;
1552 } else if ($forum->scale > 0) {
1553 $params['gradetype'] = GRADE_TYPE_VALUE;
1554 $params['grademax'] = $forum->scale;
1555 $params['grademin'] = 0;
1557 } else if ($forum->scale < 0) {
1558 $params['gradetype'] = GRADE_TYPE_SCALE;
1559 $params['scaleid'] = -$forum->scale;
1562 if ($grades === 'reset') {
1563 $params['reset'] = true;
1567 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1571 * Delete grade item for given forum
1574 * @param object $forum object
1575 * @return object grade_item
1577 function forum_grade_item_delete($forum) {
1579 require_once($CFG->libdir.'/gradelib.php');
1581 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1586 * Returns the users with data in one forum
1587 * (users with records in forum_subscriptions, forum_posts, students)
1589 * @todo: deprecated - to be deleted in 2.2
1591 * @param int $forumid
1592 * @return mixed array or false if none
1594 function forum_get_participants($forumid) {
1598 $params = array('forumid' => $forumid);
1600 //Get students from forum_subscriptions
1601 $sql = "SELECT DISTINCT u.id, u.id
1603 {forum_subscriptions} s
1604 WHERE s.forum = :forumid AND
1606 $st_subscriptions = $DB->get_records_sql($sql, $params);
1608 //Get students from forum_posts
1609 $sql = "SELECT DISTINCT u.id, u.id
1611 {forum_discussions} d,
1613 WHERE d.forum = :forumid AND
1614 p.discussion = d.id AND
1616 $st_posts = $DB->get_records_sql($sql, $params);
1618 //Get students from the ratings table
1619 $sql = "SELECT DISTINCT r.userid, r.userid AS id
1620 FROM {forum_discussions} d
1621 JOIN {forum_posts} p ON p.discussion = d.id
1622 JOIN {rating} r on r.itemid = p.id
1623 WHERE d.forum = :forumid AND
1624 r.component = 'mod_forum' AND
1625 r.ratingarea = 'post'";
1626 $st_ratings = $DB->get_records_sql($sql, $params);
1628 //Add st_posts to st_subscriptions
1630 foreach ($st_posts as $st_post) {
1631 $st_subscriptions[$st_post->id] = $st_post;
1634 //Add st_ratings to st_subscriptions
1636 foreach ($st_ratings as $st_rating) {
1637 $st_subscriptions[$st_rating->id] = $st_rating;
1640 //Return st_subscriptions array (it contains an array of unique users)
1641 return ($st_subscriptions);
1645 * This function returns if a scale is being used by one forum
1648 * @param int $forumid
1649 * @param int $scaleid negative number
1652 function forum_scale_used ($forumid,$scaleid) {
1656 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1658 if (!empty($rec) && !empty($scaleid)) {
1666 * Checks if scale is being used by any instance of forum
1668 * This is used to find out if scale used anywhere
1671 * @param $scaleid int
1672 * @return boolean True if the scale is used by any forum
1674 function forum_scale_used_anywhere($scaleid) {
1676 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1683 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1686 * Gets a post with all info ready for forum_print_post
1687 * Most of these joins are just to get the forum id
1691 * @param int $postid
1692 * @return mixed array of posts or false
1694 function forum_get_post_full($postid) {
1697 return $DB->get_record_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1698 FROM {forum_posts} p
1699 JOIN {forum_discussions} d ON p.discussion = d.id
1700 LEFT JOIN {user} u ON p.userid = u.id
1701 WHERE p.id = ?", array($postid));
1705 * Gets posts with all info ready for forum_print_post
1706 * We pass forumid in because we always know it so no need to make a
1707 * complicated join to find it out.
1711 * @return mixed array of posts or false
1713 function forum_get_discussion_posts($discussion, $sort, $forumid) {
1716 return $DB->get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1717 FROM {forum_posts} p
1718 LEFT JOIN {user} u ON p.userid = u.id
1719 WHERE p.discussion = ?
1720 AND p.parent > 0 $sort", array($discussion));
1724 * Gets all posts in discussion including top parent.
1729 * @param int $discussionid
1730 * @param string $sort
1731 * @param bool $tracking does user track the forum?
1732 * @return array of posts
1734 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1735 global $CFG, $DB, $USER;
1743 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1744 $tr_sel = ", fr.id AS postread";
1745 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1746 $params[] = $USER->id;
1749 $params[] = $discussionid;
1750 if (!$posts = $DB->get_records_sql("SELECT p.*, u.firstname, u.lastname, u.email, u.picture, u.imagealt $tr_sel
1751 FROM {forum_posts} p
1752 LEFT JOIN {user} u ON p.userid = u.id
1754 WHERE p.discussion = ?
1755 ORDER BY $sort", $params)) {
1759 foreach ($posts as $pid=>$p) {
1761 if (forum_tp_is_post_old($p)) {
1762 $posts[$pid]->postread = true;
1768 if (!isset($posts[$p->parent])) {
1769 continue; // parent does not exist??
1771 if (!isset($posts[$p->parent]->children)) {
1772 $posts[$p->parent]->children = array();
1774 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1781 * Gets posts with all info ready for forum_print_post
1782 * We pass forumid in because we always know it so no need to make a
1783 * complicated join to find it out.
1787 * @param int $parent
1788 * @param int $forumid
1791 function forum_get_child_posts($parent, $forumid) {
1794 return $DB->get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
1795 FROM {forum_posts} p
1796 LEFT JOIN {user} u ON p.userid = u.id
1798 ORDER BY p.created ASC", array($parent));
1802 * An array of forum objects that the user is allowed to read/search through.
1807 * @param int $userid
1808 * @param int $courseid if 0, we look for forums throughout the whole site.
1809 * @return array of forum objects, or false if no matches
1810 * Forum objects have the following attributes:
1811 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1812 * viewhiddentimedposts
1814 function forum_get_readable_forums($userid, $courseid=0) {
1816 global $CFG, $DB, $USER;
1817 require_once($CFG->dirroot.'/course/lib.php');
1819 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1820 print_error('notinstalled', 'forum');
1824 $courses = $DB->get_records('course', array('id' => $courseid));
1826 // If no course is specified, then the user can see SITE + his courses.
1827 $courses1 = $DB->get_records('course', array('id' => SITEID));
1828 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1829 $courses = array_merge($courses1, $courses2);
1835 $readableforums = array();
1837 foreach ($courses as $course) {
1839 $modinfo =& get_fast_modinfo($course);
1840 if (is_null($modinfo->groups)) {
1841 $modinfo->groups = groups_get_user_groups($course->id, $userid);
1844 if (empty($modinfo->instances['forum'])) {
1849 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1851 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1852 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1855 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1856 $forum = $courseforums[$forumid];
1857 $forum->context = $context;
1860 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1865 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1866 if (is_null($modinfo->groups)) {
1867 $modinfo->groups = groups_get_user_groups($course->id, $USER->id);
1869 if (isset($modinfo->groups[$cm->groupingid])) {
1870 $forum->onlygroups = $modinfo->groups[$cm->groupingid];
1871 $forum->onlygroups[] = -1;
1873 $forum->onlygroups = array(-1);
1877 /// hidden timed discussions
1878 $forum->viewhiddentimedposts = true;
1879 if (!empty($CFG->forum_enabletimedposts)) {
1880 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1881 $forum->viewhiddentimedposts = false;
1886 if ($forum->type == 'qanda'
1887 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1889 // We need to check whether the user has posted in the qanda forum.
1890 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1891 // the user is allowed to see in this forum.
1892 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1893 foreach ($discussionspostedin as $d) {
1894 $forum->onlydiscussions[] = $d->id;
1899 $readableforums[$forum->id] = $forum;
1904 } // End foreach $courses
1906 return $readableforums;
1910 * Returns a list of posts found using an array of search terms.
1915 * @param array $searchterms array of search terms, e.g. word +word -word
1916 * @param int $courseid if 0, we search through the whole site
1917 * @param int $limitfrom
1918 * @param int $limitnum
1919 * @param int &$totalcount
1920 * @param string $extrasql
1921 * @return array|bool Array of posts found or false
1923 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
1924 &$totalcount, $extrasql='') {
1925 global $CFG, $DB, $USER;
1926 require_once($CFG->libdir.'/searchlib.php');
1928 $forums = forum_get_readable_forums($USER->id, $courseid);
1930 if (count($forums) == 0) {
1935 $now = round(time(), -2); // db friendly
1937 $fullaccess = array();
1941 foreach ($forums as $forumid => $forum) {
1944 if (!$forum->viewhiddentimedposts) {
1945 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1946 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
1950 $context = $forum->context;
1952 if ($forum->type == 'qanda'
1953 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1954 if (!empty($forum->onlydiscussions)) {
1955 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
1956 $params = array_merge($params, $discussionid_params);
1957 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
1959 $select[] = "p.parent = 0";
1963 if (!empty($forum->onlygroups)) {
1964 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
1965 $params = array_merge($params, $groupid_params);
1966 $select[] = "d.groupid $groupid_sql";
1970 $selects = implode(" AND ", $select);
1971 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1972 $params['forum'.$forumid] = $forumid;
1974 $fullaccess[] = $forumid;
1979 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
1980 $params = array_merge($params, $fullid_params);
1981 $where[] = "(d.forum $fullid_sql)";
1984 $selectdiscussion = "(".implode(" OR ", $where).")";
1986 $messagesearch = '';
1989 // Need to concat these back together for parser to work.
1990 foreach($searchterms as $searchterm){
1991 if ($searchstring != '') {
1992 $searchstring .= ' ';
1994 $searchstring .= $searchterm;
1997 // We need to allow quoted strings for the search. The quotes *should* be stripped
1998 // by the parser, but this should be examined carefully for security implications.
1999 $searchstring = str_replace("\\\"","\"",$searchstring);
2000 $parser = new search_parser();
2001 $lexer = new search_lexer($parser);
2003 if ($lexer->parse($searchstring)) {
2004 $parsearray = $parser->get_parsed_array();
2005 // Experimental feature under 1.8! MDL-8830
2006 // Use alternative text searches if defined
2007 // This feature only works under mysql until properly implemented for other DBs
2008 // Requires manual creation of text index for forum_posts before enabling it:
2009 // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
2010 // Experimental feature under 1.8! MDL-8830
2011 if (!empty($CFG->forum_usetextsearches)) {
2012 list($messagesearch, $msparams) = search_generate_text_SQL($parsearray, 'p.message', 'p.subject',
2013 'p.userid', 'u.id', 'u.firstname',
2014 'u.lastname', 'p.modified', 'd.forum');
2016 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2017 'p.userid', 'u.id', 'u.firstname',
2018 'u.lastname', 'p.modified', 'd.forum');
2020 $params = array_merge($params, $msparams);
2023 $fromsql = "{forum_posts} p,
2024 {forum_discussions} d,
2027 $selectsql = " $messagesearch
2028 AND p.discussion = d.id
2030 AND $selectdiscussion
2033 $countsql = "SELECT COUNT(*)
2037 $searchsql = "SELECT p.*,
2047 ORDER BY p.modified DESC";
2049 $totalcount = $DB->count_records_sql($countsql, $params);
2051 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2055 * Returns a list of ratings for a particular post - sorted.
2057 * TODO: Check if this function is actually used anywhere.
2058 * Up until the fix for MDL-27471 this function wasn't even returning.
2060 * @param stdClass $context
2061 * @param int $postid
2062 * @param string $sort
2063 * @return array Array of ratings or false
2065 function forum_get_ratings($context, $postid, $sort = "u.firstname ASC") {
2066 $options = new stdClass;
2067 $options->context = $context;
2068 $options->component = 'mod_forum';
2069 $options->ratingarea = 'post';
2070 $options->itemid = $postid;
2071 $options->sort = "ORDER BY $sort";
2073 $rm = new rating_manager();
2074 return $rm->get_all_ratings_for_item($options);
2078 * Returns a list of all new posts that have not been mailed yet
2080 * @param int $starttime posts created after this time
2081 * @param int $endtime posts created before this
2082 * @param int $now used for timed discussions only
2085 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2088 $params = array($starttime, $endtime);
2089 if (!empty($CFG->forum_enabletimedposts)) {
2093 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2100 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2101 FROM {forum_posts} p
2102 JOIN {forum_discussions} d ON d.id = p.discussion
2105 AND (p.created < ? OR p.mailnow = 1)
2107 ORDER BY p.modified ASC", $params);
2111 * Marks posts before a certain time as being mailed already
2115 * @param int $endtime
2116 * @param int $now Defaults to time()
2119 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2125 if (empty($CFG->forum_enabletimedposts)) {
2126 return $DB->execute("UPDATE {forum_posts}
2128 WHERE (created < ? OR mailnow = 1)
2129 AND mailed = 0", array($endtime));
2132 return $DB->execute("UPDATE {forum_posts}
2134 WHERE discussion NOT IN (SELECT d.id
2135 FROM {forum_discussions} d
2136 WHERE d.timestart > ?)
2137 AND (created < ? OR mailnow = 1)
2138 AND mailed = 0", array($now, $endtime));
2143 * Get all the posts for a user in a forum suitable for forum_print_post
2147 * @uses CONTEXT_MODULE
2150 function forum_get_user_posts($forumid, $userid) {
2154 $params = array($forumid, $userid);
2156 if (!empty($CFG->forum_enabletimedposts)) {
2157 $cm = get_coursemodule_from_instance('forum', $forumid);
2158 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2160 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2166 return $DB->get_records_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture, u.imagealt
2168 JOIN {forum_discussions} d ON d.forum = f.id
2169 JOIN {forum_posts} p ON p.discussion = d.id
2170 JOIN {user} u ON u.id = p.userid
2174 ORDER BY p.modified ASC", $params);
2178 * Get all the discussions user participated in
2182 * @uses CONTEXT_MODULE
2183 * @param int $forumid
2184 * @param int $userid
2185 * @return array Array or false
2187 function forum_get_user_involved_discussions($forumid, $userid) {
2191 $params = array($forumid, $userid);
2192 if (!empty($CFG->forum_enabletimedposts)) {
2193 $cm = get_coursemodule_from_instance('forum', $forumid);
2194 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2196 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2202 return $DB->get_records_sql("SELECT DISTINCT d.*
2204 JOIN {forum_discussions} d ON d.forum = f.id
2205 JOIN {forum_posts} p ON p.discussion = d.id
2208 $timedsql", $params);
2212 * Get all the posts for a user in a forum suitable for forum_print_post
2216 * @param int $forumid
2217 * @param int $userid
2218 * @return array of counts or false
2220 function forum_count_user_posts($forumid, $userid) {
2224 $params = array($forumid, $userid);
2225 if (!empty($CFG->forum_enabletimedposts)) {
2226 $cm = get_coursemodule_from_instance('forum', $forumid);
2227 if (!has_capability('mod/forum:viewhiddentimedposts' , get_context_instance(CONTEXT_MODULE, $cm->id))) {
2229 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2235 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2237 JOIN {forum_discussions} d ON d.forum = f.id
2238 JOIN {forum_posts} p ON p.discussion = d.id
2239 JOIN {user} u ON u.id = p.userid
2242 $timedsql", $params);
2246 * Given a log entry, return the forum post details for it.
2250 * @param object $log
2251 * @return array|null
2253 function forum_get_post_from_log($log) {
2256 if ($log->action == "add post") {
2258 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
2259 u.firstname, u.lastname, u.email, u.picture
2260 FROM {forum_discussions} d,
2265 AND d.id = p.discussion
2267 AND u.deleted <> '1'
2268 AND f.id = d.forum", array($log->info));
2271 } else if ($log->action == "add discussion") {
2273 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
2274 u.firstname, u.lastname, u.email, u.picture
2275 FROM {forum_discussions} d,
2280 AND d.firstpost = p.id
2282 AND u.deleted <> '1'
2283 AND f.id = d.forum", array($log->info));
2289 * Given a discussion id, return the first post from the discussion
2293 * @param int $dicsussionid
2296 function forum_get_firstpost_from_discussion($discussionid) {
2299 return $DB->get_record_sql("SELECT p.*
2300 FROM {forum_discussions} d,
2303 AND d.firstpost = p.id ", array($discussionid));
2307 * Returns an array of counts of replies to each discussion
2311 * @param int $forumid
2312 * @param string $forumsort
2315 * @param int $perpage
2318 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2324 } else if ($page != -1) {
2325 $limitfrom = $page*$perpage;
2326 $limitnum = $perpage;
2332 if ($forumsort == "") {
2337 $orderby = "ORDER BY $forumsort";
2338 $groupby = ", ".strtolower($forumsort);
2339 $groupby = str_replace('desc', '', $groupby);
2340 $groupby = str_replace('asc', '', $groupby);
2343 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2344 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2345 FROM {forum_posts} p
2346 JOIN {forum_discussions} d ON p.discussion = d.id
2347 WHERE p.parent > 0 AND d.forum = ?
2348 GROUP BY p.discussion";
2349 return $DB->get_records_sql($sql, array($forumid));
2352 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2353 FROM {forum_posts} p
2354 JOIN {forum_discussions} d ON p.discussion = d.id
2356 GROUP BY p.discussion $groupby
2358 return $DB->get_records_sql("SELECT * FROM ($sql) sq", array($forumid), $limitfrom, $limitnum);
2366 * @staticvar array $cache
2367 * @param object $forum
2369 * @param object $course
2372 function forum_count_discussions($forum, $cm, $course) {
2373 global $CFG, $DB, $USER;
2375 static $cache = array();
2377 $now = round(time(), -2); // db cache friendliness
2379 $params = array($course->id);
2381 if (!isset($cache[$course->id])) {
2382 if (!empty($CFG->forum_enabletimedposts)) {
2383 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2390 $sql = "SELECT f.id, COUNT(d.id) as dcount
2392 JOIN {forum_discussions} d ON d.forum = f.id
2397 if ($counts = $DB->get_records_sql($sql, $params)) {
2398 foreach ($counts as $count) {
2399 $counts[$count->id] = $count->dcount;
2401 $cache[$course->id] = $counts;
2403 $cache[$course->id] = array();
2407 if (empty($cache[$course->id][$forum->id])) {
2411 $groupmode = groups_get_activity_groupmode($cm, $course);
2413 if ($groupmode != SEPARATEGROUPS) {
2414 return $cache[$course->id][$forum->id];
2417 if (has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2418 return $cache[$course->id][$forum->id];
2421 require_once($CFG->dirroot.'/course/lib.php');
2423 $modinfo =& get_fast_modinfo($course);
2424 if (is_null($modinfo->groups)) {
2425 $modinfo->groups = groups_get_user_groups($course->id, $USER->id);
2428 if (array_key_exists($cm->groupingid, $modinfo->groups)) {
2429 $mygroups = $modinfo->groups[$cm->groupingid];
2431 $mygroups = false; // Will be set below
2434 // add all groups posts
2435 if (empty($mygroups)) {
2436 $mygroups = array(-1=>-1);
2441 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2442 $params[] = $forum->id;
2444 if (!empty($CFG->forum_enabletimedposts)) {
2445 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2452 $sql = "SELECT COUNT(d.id)
2453 FROM {forum_discussions} d
2454 WHERE d.groupid $mygroups_sql AND d.forum = ?
2457 return $DB->get_field_sql($sql, $params);
2461 * How many posts by other users are unrated by a given user in the given discussion?
2463 * TODO: Is this function still used anywhere?
2465 * @param int $discussionid
2466 * @param int $userid
2469 function forum_count_unrated_posts($discussionid, $userid) {
2472 $sql = "SELECT COUNT(*) as num
2475 AND discussion = :discussionid
2476 AND userid <> :userid";
2477 $params = array('discussionid' => $discussionid, 'userid' => $userid);
2478 $posts = $DB->get_record_sql($sql, $params);
2480 $sql = "SELECT count(*) as num
2481 FROM {forum_posts} p,
2483 WHERE p.discussion = :discussionid AND
2485 r.userid = userid AND
2486 r.component = 'mod_forum' AND
2487 r.ratingarea = 'post'";
2488 $rated = $DB->get_record_sql($sql, $params);
2490 if ($posts->num > $rated->num) {
2491 return $posts->num - $rated->num;
2493 return 0; // Just in case there was a counting error
2504 * Get all discussions in a forum
2509 * @uses CONTEXT_MODULE
2510 * @uses VISIBLEGROUPS
2512 * @param string $forumsort
2513 * @param bool $fullpost
2514 * @param int $unused
2516 * @param bool $userlastmodified
2518 * @param int $perpage
2521 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2522 global $CFG, $DB, $USER;
2526 $now = round(time(), -2);
2527 $params = array($cm->instance);
2529 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2531 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2535 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2537 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2538 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2542 $timelimit .= " OR d.userid = ?";
2543 $params[] = $USER->id;
2552 } else if ($page != -1) {
2553 $limitfrom = $page*$perpage;
2554 $limitnum = $perpage;
2560 $groupmode = groups_get_activity_groupmode($cm);
2561 $currentgroup = groups_get_activity_group($cm);
2564 if (empty($modcontext)) {
2565 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2568 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2569 if ($currentgroup) {
2570 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2571 $params[] = $currentgroup;
2577 //seprate groups without access all
2578 if ($currentgroup) {
2579 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2580 $params[] = $currentgroup;
2582 $groupselect = "AND d.groupid = -1";
2590 if (empty($forumsort)) {
2591 $forumsort = "d.timemodified DESC";
2593 if (empty($fullpost)) {
2594 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2599 if (empty($userlastmodified)) { // We don't need to know this
2603 $umfields = ", um.firstname AS umfirstname, um.lastname AS umlastname";
2604 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2607 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend,
2608 u.firstname, u.lastname, u.email, u.picture, u.imagealt $umfields
2609 FROM {forum_discussions} d
2610 JOIN {forum_posts} p ON p.discussion = d.id
2611 JOIN {user} u ON p.userid = u.id
2613 WHERE d.forum = ? AND p.parent = 0
2614 $timelimit $groupselect
2615 ORDER BY $forumsort";
2616 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2624 * @uses CONTEXT_MODULE
2625 * @uses VISIBLEGROUPS
2629 function forum_get_discussions_unread($cm) {
2630 global $CFG, $DB, $USER;
2632 $now = round(time(), -2);
2633 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2636 $groupmode = groups_get_activity_groupmode($cm);
2637 $currentgroup = groups_get_activity_group($cm);
2640 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2642 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2643 if ($currentgroup) {
2644 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2645 $params['currentgroup'] = $currentgroup;
2651 //separate groups without access all
2652 if ($currentgroup) {
2653 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2654 $params['currentgroup'] = $currentgroup;
2656 $groupselect = "AND d.groupid = -1";
2663 if (!empty($CFG->forum_enabletimedposts)) {
2664 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2665 $params['now1'] = $now;
2666 $params['now2'] = $now;
2671 $sql = "SELECT d.id, COUNT(p.id) AS unread
2672 FROM {forum_discussions} d
2673 JOIN {forum_posts} p ON p.discussion = d.id
2674 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2675 WHERE d.forum = {$cm->instance}
2676 AND p.modified >= :cutoffdate AND r.id is NULL
2680 $params['cutoffdate'] = $cutoffdate;
2682 if ($unreads = $DB->get_records_sql($sql, $params)) {
2683 foreach ($unreads as $unread) {
2684 $unreads[$unread->id] = $unread->unread;
2696 * @uses CONEXT_MODULE
2697 * @uses VISIBLEGROUPS
2701 function forum_get_discussions_count($cm) {
2702 global $CFG, $DB, $USER;
2704 $now = round(time(), -2);
2705 $params = array($cm->instance);
2706 $groupmode = groups_get_activity_groupmode($cm);
2707 $currentgroup = groups_get_activity_group($cm);
2710 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2712 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2713 if ($currentgroup) {
2714 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2715 $params[] = $currentgroup;
2721 //seprate groups without access all
2722 if ($currentgroup) {
2723 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2724 $params[] = $currentgroup;
2726 $groupselect = "AND d.groupid = -1";
2733 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2737 if (!empty($CFG->forum_enabletimedposts)) {
2739 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2741 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2742 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2746 $timelimit .= " OR d.userid = ?";
2747 $params[] = $USER->id;
2753 $sql = "SELECT COUNT(d.id)
2754 FROM {forum_discussions} d
2755 JOIN {forum_posts} p ON p.discussion = d.id
2756 WHERE d.forum = ? AND p.parent = 0
2757 $groupselect $timelimit";
2759 return $DB->get_field_sql($sql, $params);
2764 * Get all discussions started by a particular user in a course (or group)
2765 * This function no longer used ...
2767 * @todo Remove this function if no longer used
2770 * @param int $courseid
2771 * @param int $userid
2772 * @param int $groupid
2775 function forum_get_user_discussions($courseid, $userid, $groupid=0) {
2777 $params = array($courseid, $userid);
2779 $groupselect = " AND d.groupid = ? ";
2780 $params[] = $groupid;
2785 return $DB->get_records_sql("SELECT p.*, d.groupid, u.firstname, u.lastname, u.email, u.picture, u.imagealt,
2786 f.type as forumtype, f.name as forumname, f.id as forumid
2787 FROM {forum_discussions} d,
2792 AND p.discussion = d.id
2796 AND d.forum = f.id $groupselect
2797 ORDER BY p.created DESC", $params);
2801 * Get the list of potential subscribers to a forum.
2803 * @param object $forumcontext the forum context.
2804 * @param integer $groupid the id of a group, or 0 for all groups.
2805 * @param string $fields the list of fields to return for each user. As for get_users_by_capability.
2806 * @param string $sort sort order. As for get_users_by_capability.
2807 * @return array list of users.
2809 function forum_get_potential_subscribers($forumcontext, $groupid, $fields, $sort) {
2812 // only active enrolled users or everybody on the frontpage with this capability
2813 list($esql, $params) = get_enrolled_sql($forumcontext, 'mod/forum:initialsubscriptions', $groupid, true);
2815 $sql = "SELECT $fields
2817 JOIN ($esql) je ON je.id = u.id";
2819 $sql = "$sql ORDER BY $sort";
2821 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2824 return $DB->get_records_sql($sql, $params);
2828 * Returns list of user objects that are subscribed to this forum
2832 * @param object $course the course
2833 * @param forum $forum the forum
2834 * @param integer $groupid group id, or 0 for all.
2835 * @param object $context the forum context, to save re-fetching it where possible.
2836 * @param string $fields requested user fields (with "u." table prefix)
2837 * @return array list of users.
2839 function forum_subscribed_users($course, $forum, $groupid=0, $context = null, $fields = null) {
2842 if (empty($fields)) {
2864 if (empty($context)) {
2865 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
2866 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2869 if (forum_is_forcesubscribed($forum)) {
2870 $results = forum_get_potential_subscribers($context, $groupid, $fields, "u.email ASC");
2873 // only active enrolled users or everybody on the frontpage
2874 list($esql, $params) = get_enrolled_sql($context, '', $groupid, true);
2875 $params['forumid'] = $forum->id;
2876 $results = $DB->get_records_sql("SELECT $fields
2878 JOIN ($esql) je ON je.id = u.id
2879 JOIN {forum_subscriptions} s ON s.userid = u.id
2880 WHERE s.forum = :forumid
2881 ORDER BY u.email ASC", $params);
2884 // Guest user should never be subscribed to a forum.
2885 unset($results[$CFG->siteguest]);
2892 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2898 * @param int $courseid
2899 * @param string $type
2901 function forum_get_course_forum($courseid, $type) {
2902 // How to set up special 1-per-course forums
2903 global $CFG, $DB, $OUTPUT;
2905 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2906 // There should always only be ONE, but with the right combination of
2907 // errors there might be more. In this case, just return the oldest one (lowest ID).
2908 foreach ($forums as $forum) {
2909 return $forum; // ie the first one
2913 // Doesn't exist, so create one now.
2914 $forum->course = $courseid;
2915 $forum->type = "$type";
2916 switch ($forum->type) {
2918 $forum->name = get_string("namenews", "forum");
2919 $forum->intro = get_string("intronews", "forum");
2920 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2921 $forum->assessed = 0;
2922 if ($courseid == SITEID) {
2923 $forum->name = get_string("sitenews");
2924 $forum->forcesubscribe = 0;
2928 $forum->name = get_string("namesocial", "forum");
2929 $forum->intro = get_string("introsocial", "forum");
2930 $forum->assessed = 0;
2931 $forum->forcesubscribe = 0;
2934 $forum->name = get_string('blogforum', 'forum');
2935 $forum->intro = get_string('introblog', 'forum');
2936 $forum->assessed = 0;
2937 $forum->forcesubscribe = 0;
2940 echo $OUTPUT->notification("That forum type doesn't exist!");
2945 $forum->timemodified = time();
2946 $forum->id = $DB->insert_record("forum", $forum);
2948 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2949 echo $OUTPUT->notification("Could not find forum module!!");
2952 $mod = new stdClass();
2953 $mod->course = $courseid;
2954 $mod->module = $module->id;
2955 $mod->instance = $forum->id;
2957 if (! $mod->coursemodule = add_course_module($mod) ) { // assumes course/lib.php is loaded
2958 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
2961 if (! $sectionid = add_mod_to_section($mod) ) { // assumes course/lib.php is loaded
2962 echo $OUTPUT->notification("Could not add the new course module to that section");
2965 $DB->set_field("course_modules", "section", $sectionid, array("id" => $mod->coursemodule));
2967 include_once("$CFG->dirroot/course/lib.php");
2968 rebuild_course_cache($courseid);
2970 return $DB->get_record("forum", array("id" => "$forum->id"));
2975 * Given the data about a posting, builds up the HTML to display it and
2976 * returns the HTML in a string. This is designed for sending via HTML email.
2979 * @param object $course
2981 * @param object $forum
2982 * @param object $discussion
2983 * @param object $post
2984 * @param object $userform
2985 * @param object $userto
2986 * @param bool $ownpost
2987 * @param bool $reply
2990 * @param string $footer
2993 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
2994 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
2996 global $CFG, $OUTPUT;
2998 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
3000 if (!isset($userto->viewfullnames[$forum->id])) {
3001 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3003 $viewfullnames = $userto->viewfullnames[$forum->id];
3006 // add absolute file links
3007 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3009 // format the post body
3010 $options = new stdClass();
3011 $options->para = true;
3012 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
3014 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3016 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3017 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
3020 if ($post->parent) {
3021 $output .= '<td class="topic">';
3023 $output .= '<td class="topic starter">';
3025 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3027 $fullname = fullname($userfrom, $viewfullnames);
3028 $by = new stdClass();
3029 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&course='.$course->id.'">'.$fullname.'</a>';
3030 $by->date = userdate($post->modified, '', $userto->timezone);
3031 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3033 $output .= '</td></tr>';
3035 $output .= '<tr><td class="left side" valign="top">';
3037 if (isset($userfrom->groups)) {
3038 $groups = $userfrom->groups[$forum->id];
3040 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3044 $output .= print_group_picture($groups, $course->id, false, true, true);
3046 $output .= ' ';
3049 $output .= '</td><td class="content">';
3051 $attachments = forum_print_attachments($post, $cm, 'html');
3052 if ($attachments !== '') {
3053 $output .= '<div class="attachments">';
3054 $output .= $attachments;
3055 $output .= '</div>';
3058 $output .= $formattedtext;
3061 $commands = array();
3063 if ($post->parent) {
3064 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3065 $post->discussion.'&parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3069 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3070 get_string('reply', 'forum').'</a>';
3073 $output .= '<div class="commands">';
3074 $output .= implode(' | ', $commands);
3075 $output .= '</div>';
3077 // Context link to post if required
3079 $output .= '<div class="link">';
3080 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3081 get_string('postincontext', 'forum').'</a>';
3082 $output .= '</div>';
3086 $output .= '<div class="footer">'.$footer.'</div>';
3088 $output .= '</td></tr></table>'."\n\n";
3094 * Print a forum post
3098 * @uses FORUM_MODE_THREADED
3099 * @uses PORTFOLIO_FORMAT_PLAINHTML
3100 * @uses PORTFOLIO_FORMAT_FILE
3101 * @uses PORTFOLIO_FORMAT_RICHHTML
3102 * @uses PORTFOLIO_ADD_TEXT_LINK
3103 * @uses CONTEXT_MODULE
3104 * @param object $post The post to print.
3105 * @param object $discussion
3106 * @param object $forum
3108 * @param object $course
3109 * @param boolean $ownpost Whether this post belongs to the current user.
3110 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3111 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3112 * @param string $footer Extra stuff to print after the message.
3113 * @param string $highlight Space-separated list of terms to highlight.
3114 * @param int $post_read true, false or -99. If we already know whether this user
3115 * has read this post, pass that in, otherwise, pass in -99, and this
3116 * function will work it out.
3117 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3118 * the current user can't see this post, if this argument is true
3119 * (the default) then print a dummy 'you can't see this post' post.
3120 * If false, don't output anything at all.
3121 * @param bool|null $istracked
3124 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3125 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3126 global $USER, $CFG, $OUTPUT;
3128 require_once($CFG->libdir . '/filelib.php');
3133 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
3135 $post->course = $course->id;
3136 $post->forum = $forum->id;
3137 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3140 if (!isset($cm->cache)) {
3141 $cm->cache = new stdClass;
3144 if (!isset($cm->cache->caps)) {
3145 $cm->cache->caps = array();
3146 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3147 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3148 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3149 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3150 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3151 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3152 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3153 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3154 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3157 if (!isset($cm->uservisible)) {
3158 $cm->uservisible = coursemodule_visible_for_user($cm);
3161 if ($istracked && is_null($postisread)) {
3162 $postisread = forum_tp_is_post_read($USER->id, $post);
3165 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3167 if (!$dummyifcantsee) {
3174 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3175 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'));
3176 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3177 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3178 if ($post->parent) {
3179 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3181 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3183 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class'=>'subject')); // Subject
3184 $output .= html_writer::tag('div', get_string('forumauthorhidden','forum'), array('class'=>'author')); // author
3185 $output .= html_writer::end_tag('div');
3186 $output .= html_writer::end_tag('div'); // row
3187 $output .= html_writer::start_tag('div', array('class'=>'row'));
3188 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3189 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3190 $output .= html_writer::end_tag('div'); // row
3191 $output .= html_writer::end_tag('div'); // forumpost
3201 $str = new stdClass;
3202 $str->edit = get_string('edit', 'forum');
3203 $str->delete = get_string('delete', 'forum');
3204 $str->reply = get_string('reply', 'forum');
3205 $str->parent = get_string('parent', 'forum');
3206 $str->pruneheading = get_string('pruneheading', 'forum');
3207 $str->prune = get_string('prune', 'forum');
3208 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3209 $str->markread = get_string('markread', 'forum');
3210 $str->markunread = get_string('markunread', 'forum');
3213 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3215 // Build an object that represents the posting user
3216 $postuser = new stdClass;
3217 $postuser->id = $post->userid;
3218 $postuser->firstname = $post->firstname;
3219 $postuser->lastname = $post->lastname;
3220 $postuser->imagealt = $post->imagealt;
3221 $postuser->picture = $post->picture;
3222 $postuser->email = $post->email;
3223 // Some handy things for later on
3224 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3225 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3227 // Prepare the groups the posting user belongs to
3228 if (isset($cm->cache->usersgroups)) {
3230 if (isset($cm->cache->usersgroups[$post->userid])) {
3231 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3232 $groups[$gid] = $cm->cache->groups[$gid];
3236 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3239 // Prepare the attachements for the post, files then images
3240 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3242 // Determine if we need to shorten this post
3243 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3246 // Prepare an array of commands
3247 $commands = array();
3249 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3250 // Don't display the mark read / unread controls in this case.
3251 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3252 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3253 $text = $str->markunread;
3255 $url->param('mark', 'read');
3256 $text = $str->markread;
3258 if ($str->displaymode == FORUM_MODE_THREADED) {
3259 $url->param('parent', $post->parent);
3261 $url->set_anchor('p'.$post->id);
3263 $commands[] = array('url'=>$url, 'text'=>$text);
3266 // Zoom in to the parent specifically
3267 if ($post->parent) {
3268 $url = new moodle_url($discussionlink);
3269 if ($str->displaymode == FORUM_MODE_THREADED) {
3270 $url->param('parent', $post->parent);
3272 $url->set_anchor('p'.$post->parent);
3274 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3277 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3278 $age = time() - $post->created;
3279 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3282 if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3283 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3286 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3287 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3290 if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3291 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3295 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('reply'=>$post->id)), 'text'=>$str->reply);
3298 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3299 $p = array('postid' => $post->id);
3300 require_once($CFG->libdir.'/portfoliolib.php');
3301 $button = new portfolio_add_button();
3302 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), '/mod/forum/locallib.php');
3303 if (empty($attachments)) {
3304 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3306 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3309 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3310 if (!empty($porfoliohtml)) {
3311 $commands[] = $porfoliohtml;
3314 // Finished building commands
3323 $forumpostclass = ' read';
3325 $forumpostclass = ' unread';
3326 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3329 // ignore trackign status if not tracked or tracked param missing
3330 $forumpostclass = '';
3334 if (empty($post->parent)) {
3335 $topicclass = ' firstpost starter';
3338 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3339 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass));
3340 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3341 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3342 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3343 $output .= html_writer::end_tag('div');
3346 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3348 $postsubject = $post->subject;
3349 if (empty($post->subjectnoformat)) {
3350 $postsubject = format_string($postsubject);
3352 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject'));
3354 $by = new stdClass();
3355 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3356 $by->date = userdate($post->modified);
3357 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author'));
3359 $output .= html_writer::end_tag('div'); //topic
3360 $output .= html_writer::end_tag('div'); //row
3362 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3363 $output .= html_writer::start_tag('div', array('class'=>'left'));
3367 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3369 if (empty($groupoutput)) {
3370 $groupoutput = ' ';
3372 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3374 $output .= html_writer::end_tag('div'); //left side
3375 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3376 $output .= html_writer::start_tag('div', array('class'=>'content'));
3377 if (!empty($attachments)) {
3378 $output .= html_writer::tag('div', $attachments, array('class'=>'attachments'));
3381 $options = new stdClass;
3382 $options->para = false;
3383 $options->trusted = $post->messagetrust;
3384 $options->context = $modcontext;
3386 // Prepare shortened version
3387 $postclass = 'shortenedpost';
3388 $postcontent = format_text(forum_shorten_post($post->message), $post->messageformat, $options, $course->id);
3389 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3390 $postcontent .= html_writer::tag('span', '('.get_string('numwords', 'moodle', count_words(strip_tags($post->message))).')...', array('class'=>'post-word-count'));
3392 // Prepare whole post
3393 $postclass = 'fullpost';
3394 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3395 if (!empty($highlight)) {
3396 $postcontent = highlight($highlight, $postcontent);
3398 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3400 // Output the post content
3401 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3402 $output .= html_writer::end_tag('div'); // Content
3403 $output .= html_writer::end_tag('div'); // Content mask
3404 $output .= html_writer::end_tag('div'); // Row
3406 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3407 $output .= html_writer::tag('div',' ', array('class'=>'left'));
3408 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3411 if (!empty($post->rating)) {
3412 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3415 // Output the commands
3416 $commandhtml = array();
3417 foreach ($commands as $command) {
3418 if (is_array($command)) {
3419 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3421 $commandhtml[] = $command;
3424 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3426 // Output link to post if required
3428 if ($post->replies == 1) {
3429 $replystring = get_string('repliesone', 'forum', $post->replies);
3431 $replystring = get_string('repliesmany', 'forum', $post->replies);
3434 $output .= html_writer::start_tag('div', array('class'=>'link'));
3435 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3436 $output .= ' ('.$replystring.')';
3437 $output .= html_writer::end_tag('div'); // link
3440 // Output footer if required
3442 $output .= html_writer::tag('div', $footer, array('class'=>'footer'));
3445 // Close remaining open divs
3446 $output .= html_writer::end_tag('div'); // content
3447 $output .= html_writer::end_tag('div'); // row
3448 $output .= html_writer::end_tag('div'); // forumpost
3450 // Mark the forum post as read if required
3451 if ($istracked && !$CFG->forum_usermarksread && !$postisread) {
3452 forum_tp_mark_post_read($USER->id, $post, $forum->id);
3463 * Return rating related permissions
3465 * @param string $options the context id
3466 * @return array an associative array of the user's rating permissions
3468 function forum_rating_permissions($contextid, $component, $ratingarea) {
3469 $context = get_context_instance_by_id($contextid, MUST_EXIST);
3470 if ($component != 'mod_forum' || $ratingarea != 'post') {
3471 // We don't know about this component/ratingarea so just return null to get the
3472 // default restrictive permissions.
3476 'view' => has_capability('mod/forum:viewrating', $context),
3477 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3478 'viewall' => has_capability('mod/forum:viewallratings', $context),
3479 'rate' => has_capability('mod/forum:rate', $context)
3484 * Validates a submitted rating
3485 * @param array $params submitted data
3486 * context => object the context in which the rated items exists [required]
3487 * component => The component for this module - should always be mod_forum [required]
3488 * ratingarea => object the context in which the rated items exists [required]
3489 * itemid => int the ID of the object being rated [required]
3490 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3491 * rating => int the submitted rating [required]
3492 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3493 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3494 * @return boolean true if the rating is valid. Will throw rating_exception if not
3496 function forum_rating_validate($params) {
3499 // Check the component is mod_forum
3500 if ($params['component'] != 'mod_forum') {
3501 throw new rating_exception('invalidcomponent');
3504 // Check the ratingarea is post (the only rating area in forum)
3505 if ($params['ratingarea'] != 'post') {