2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') || die();
25 /** Include required files */
26 require_once(__DIR__ . '/deprecatedlib.php');
27 require_once($CFG->libdir.'/filelib.php');
28 require_once($CFG->libdir.'/eventslib.php');
30 /// CONSTANTS ///////////////////////////////////////////////////////////
32 define('FORUM_MODE_FLATOLDEST', 1);
33 define('FORUM_MODE_FLATNEWEST', -1);
34 define('FORUM_MODE_THREADED', 2);
35 define('FORUM_MODE_NESTED', 3);
37 define('FORUM_CHOOSESUBSCRIBE', 0);
38 define('FORUM_FORCESUBSCRIBE', 1);
39 define('FORUM_INITIALSUBSCRIBE', 2);
40 define('FORUM_DISALLOWSUBSCRIBE',3);
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
62 if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
70 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
72 define('FORUM_DISCUSSION_PINNED', 1);
73 define('FORUM_DISCUSSION_UNPINNED', 0);
75 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
78 * Given an object containing all the necessary data,
79 * (defined by the form in mod_form.php) this function
80 * will create a new instance and return the id number
81 * of the new instance.
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
85 * @return int intance id
87 function forum_add_instance($forum, $mform = null) {
90 $forum->timemodified = time();
92 if (empty($forum->assessed)) {
96 if (empty($forum->ratingtime) or empty($forum->assessed)) {
97 $forum->assesstimestart = 0;
98 $forum->assesstimefinish = 0;
101 $forum->id = $DB->insert_record('forum', $forum);
102 $modcontext = context_module::instance($forum->coursemodule);
104 if ($forum->type == 'single') { // Create related discussion.
105 $discussion = new stdClass();
106 $discussion->course = $forum->course;
107 $discussion->forum = $forum->id;
108 $discussion->name = $forum->name;
109 $discussion->assessed = $forum->assessed;
110 $discussion->message = $forum->intro;
111 $discussion->messageformat = $forum->introformat;
112 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
113 $discussion->mailnow = false;
114 $discussion->groupid = -1;
118 $discussion->id = forum_add_discussion($discussion, null, $message);
120 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
121 // Ugly hack - we need to copy the files somehow.
122 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
123 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
125 $options = array('subdirs'=>true); // Use the same options as intro field!
126 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
127 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
131 forum_grade_item_update($forum);
137 * Handle changes following the creation of a forum instance.
138 * This function is typically called by the course_module_created observer.
140 * @param object $context the forum context
141 * @param stdClass $forum The forum object
144 function forum_instance_created($context, $forum) {
145 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
146 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
147 foreach ($users as $user) {
148 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
154 * Given an object containing all the necessary data,
155 * (defined by the form in mod_form.php) this function
156 * will update an existing instance with new data.
159 * @param object $forum forum instance (with magic quotes)
160 * @return bool success
162 function forum_update_instance($forum, $mform) {
163 global $DB, $OUTPUT, $USER;
165 $forum->timemodified = time();
166 $forum->id = $forum->instance;
168 if (empty($forum->assessed)) {
169 $forum->assessed = 0;
172 if (empty($forum->ratingtime) or empty($forum->assessed)) {
173 $forum->assesstimestart = 0;
174 $forum->assesstimefinish = 0;
177 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
179 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
180 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
181 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
182 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
183 forum_update_grades($forum); // recalculate grades for the forum
186 if ($forum->type == 'single') { // Update related discussion and post.
187 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
188 if (!empty($discussions)) {
189 if (count($discussions) > 1) {
190 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
192 $discussion = array_pop($discussions);
194 // try to recover by creating initial discussion - MDL-16262
195 $discussion = new stdClass();
196 $discussion->course = $forum->course;
197 $discussion->forum = $forum->id;
198 $discussion->name = $forum->name;
199 $discussion->assessed = $forum->assessed;
200 $discussion->message = $forum->intro;
201 $discussion->messageformat = $forum->introformat;
202 $discussion->messagetrust = true;
203 $discussion->mailnow = false;
204 $discussion->groupid = -1;
208 forum_add_discussion($discussion, null, $message);
210 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
211 print_error('cannotadd', 'forum');
214 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
215 print_error('cannotfindfirstpost', 'forum');
218 $cm = get_coursemodule_from_instance('forum', $forum->id);
219 $modcontext = context_module::instance($cm->id, MUST_EXIST);
221 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
222 $post->subject = $forum->name;
223 $post->message = $forum->intro;
224 $post->messageformat = $forum->introformat;
225 $post->messagetrust = trusttext_trusted($modcontext);
226 $post->modified = $forum->timemodified;
227 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
229 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
230 // Ugly hack - we need to copy the files somehow.
231 $options = array('subdirs'=>true); // Use the same options as intro field!
232 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
235 $DB->update_record('forum_posts', $post);
236 $discussion->name = $forum->name;
237 $DB->update_record('forum_discussions', $discussion);
240 $DB->update_record('forum', $forum);
242 $modcontext = context_module::instance($forum->coursemodule);
243 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
244 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
245 foreach ($users as $user) {
246 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
250 forum_grade_item_update($forum);
257 * Given an ID of an instance of this module,
258 * this function will permanently delete the instance
259 * and any data that depends on it.
262 * @param int $id forum instance id
263 * @return bool success
265 function forum_delete_instance($id) {
268 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
271 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
274 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
278 $context = context_module::instance($cm->id);
280 // now get rid of all files
281 $fs = get_file_storage();
282 $fs->delete_area_files($context->id);
286 // Delete digest and subscription preferences.
287 $DB->delete_records('forum_digests', array('forum' => $forum->id));
288 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
289 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
291 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
292 foreach ($discussions as $discussion) {
293 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
299 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
301 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
305 forum_grade_item_delete($forum);
312 * Indicates API features that the forum supports.
314 * @uses FEATURE_GROUPS
315 * @uses FEATURE_GROUPINGS
316 * @uses FEATURE_MOD_INTRO
317 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
318 * @uses FEATURE_COMPLETION_HAS_RULES
319 * @uses FEATURE_GRADE_HAS_GRADE
320 * @uses FEATURE_GRADE_OUTCOMES
321 * @param string $feature
322 * @return mixed True if yes (some features may use other values)
324 function forum_supports($feature) {
326 case FEATURE_GROUPS: return true;
327 case FEATURE_GROUPINGS: return true;
328 case FEATURE_MOD_INTRO: return true;
329 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
330 case FEATURE_COMPLETION_HAS_RULES: return true;
331 case FEATURE_GRADE_HAS_GRADE: return true;
332 case FEATURE_GRADE_OUTCOMES: return true;
333 case FEATURE_RATE: return true;
334 case FEATURE_BACKUP_MOODLE2: return true;
335 case FEATURE_SHOW_DESCRIPTION: return true;
336 case FEATURE_PLAGIARISM: return true;
338 default: return null;
344 * Obtains the automatic completion state for this forum based on any conditions
349 * @param object $course Course
350 * @param object $cm Course-module
351 * @param int $userid User ID
352 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
353 * @return bool True if completed, false if not. (If no conditions, then return
354 * value depends on comparison type)
356 function forum_get_completion_state($course,$cm,$userid,$type) {
360 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
361 throw new Exception("Can't find forum {$cm->instance}");
364 $result=$type; // Default return value
366 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
372 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
374 fp.userid=:userid AND fd.forum=:forumid";
376 if ($forum->completiondiscussions) {
377 $value = $forum->completiondiscussions <=
378 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
379 if ($type == COMPLETION_AND) {
380 $result = $result && $value;
382 $result = $result || $value;
385 if ($forum->completionreplies) {
386 $value = $forum->completionreplies <=
387 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
388 if ($type==COMPLETION_AND) {
389 $result = $result && $value;
391 $result = $result || $value;
394 if ($forum->completionposts) {
395 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
396 if ($type == COMPLETION_AND) {
397 $result = $result && $value;
399 $result = $result || $value;
407 * Create a message-id string to use in the custom headers of forum notification emails
409 * message-id is used by email clients to identify emails and to nest conversations
411 * @param int $postid The ID of the forum post we are notifying the user about
412 * @param int $usertoid The ID of the user being notified
413 * @param string $hostname The server's hostname
414 * @return string A unique message-id
416 function forum_get_email_message_id($postid, $usertoid, $hostname) {
417 return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
421 * Removes properties from user record that are not necessary
422 * for sending post notifications.
423 * @param stdClass $user
424 * @return void, $user parameter is modified
426 function forum_cron_minimise_user_record(stdClass $user) {
428 // We store large amount of users in one huge array,
429 // make sure we do not store info there we do not actually need
430 // in mail generation code or messaging.
432 unset($user->institution);
433 unset($user->department);
434 unset($user->address);
437 unset($user->currentlogin);
438 unset($user->description);
439 unset($user->descriptionformat);
443 * Function to be run periodically according to the scheduled task.
445 * Finds all posts that have yet to be mailed out, and mails them
446 * out to all subscribers as well as other maintance tasks.
448 * NOTE: Since 2.7.2 this function is run by scheduled task rather
449 * than standard cron.
451 * @todo MDL-44734 The function will be split up into seperate tasks.
453 function forum_cron() {
454 global $CFG, $USER, $DB, $PAGE;
458 // The main renderers.
459 $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
460 $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
461 $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
462 $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
463 $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
464 $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
466 // All users that are subscribed to any post that needs sending,
467 // please increase $CFG->extramemorylimit on large sites that
468 // send notifications to a large number of users.
470 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
473 $mailcount = array();
474 $errorcount = array();
477 $discussions = array();
480 $coursemodules = array();
481 $subscribedusers = array();
482 $messageinboundhandlers = array();
484 // Posts older than 2 days will not be mailed. This is to avoid the problem where
485 // cron has not been running for a long time, and then suddenly people are flooded
486 // with mail from the past few weeks or months
488 $endtime = $timenow - $CFG->maxeditingtime;
489 $starttime = $endtime - 48 * 3600; // Two days earlier
491 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
492 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
494 foreach ($digestsset as $thisrow) {
495 if (!isset($digests[$thisrow->forum])) {
496 $digests[$thisrow->forum] = array();
498 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
500 $digestsset->close();
502 // Create the generic messageinboundgenerator.
503 $messageinboundgenerator = new \core\message\inbound\address_manager();
504 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
506 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
507 // Mark them all now as being mailed. It's unlikely but possible there
508 // might be an error later so that a post is NOT actually mailed out,
509 // but since mail isn't crucial, we can accept this risk. Doing it now
510 // prevents the risk of duplicated mails, which is a worse problem.
512 if (!forum_mark_old_posts_as_mailed($endtime)) {
513 mtrace('Errors occurred while trying to mark some posts as being mailed.');
514 return false; // Don't continue trying to mail them, in case we are in a cron loop
517 // checking post validity, and adding users to loop through later
518 foreach ($posts as $pid => $post) {
520 $discussionid = $post->discussion;
521 if (!isset($discussions[$discussionid])) {
522 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
523 $discussions[$discussionid] = $discussion;
524 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
525 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
528 mtrace('Could not find discussion ' . $discussionid);
533 $forumid = $discussions[$discussionid]->forum;
534 if (!isset($forums[$forumid])) {
535 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
536 $forums[$forumid] = $forum;
538 mtrace('Could not find forum '.$forumid);
543 $courseid = $forums[$forumid]->course;
544 if (!isset($courses[$courseid])) {
545 if ($course = $DB->get_record('course', array('id' => $courseid))) {
546 $courses[$courseid] = $course;
548 mtrace('Could not find course '.$courseid);
553 if (!isset($coursemodules[$forumid])) {
554 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
555 $coursemodules[$forumid] = $cm;
557 mtrace('Could not find course module for forum '.$forumid);
563 // Save the Inbound Message datakey here to reduce DB queries later.
564 $messageinboundgenerator->set_data($pid);
565 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
567 // Caching subscribed users of each forum.
568 if (!isset($subscribedusers[$forumid])) {
569 $modcontext = context_module::instance($coursemodules[$forumid]->id);
570 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
572 foreach ($subusers as $postuser) {
573 // this user is subscribed to this forum
574 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
576 if ($userscount > FORUM_CRON_USER_CACHE) {
577 // Store minimal user info.
578 $minuser = new stdClass();
579 $minuser->id = $postuser->id;
580 $users[$postuser->id] = $minuser;
582 // Cache full user record.
583 forum_cron_minimise_user_record($postuser);
584 $users[$postuser->id] = $postuser;
592 $mailcount[$pid] = 0;
593 $errorcount[$pid] = 0;
597 if ($users && $posts) {
599 $urlinfo = parse_url($CFG->wwwroot);
600 $hostname = $urlinfo['host'];
602 foreach ($users as $userto) {
603 // Terminate if processing of any account takes longer than 2 minutes.
604 core_php_time_limit::raise(120);
606 mtrace('Processing user ' . $userto->id);
608 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
609 if (isset($userto->username)) {
610 $userto = clone($userto);
612 $userto = $DB->get_record('user', array('id' => $userto->id));
613 forum_cron_minimise_user_record($userto);
615 $userto->viewfullnames = array();
616 $userto->canpost = array();
617 $userto->markposts = array();
619 // Setup this user so that the capabilities are cached, and environment matches receiving user.
620 cron_setup_user($userto);
623 foreach ($coursemodules as $forumid => $unused) {
624 $coursemodules[$forumid]->cache = new stdClass();
625 $coursemodules[$forumid]->cache->caps = array();
626 unset($coursemodules[$forumid]->uservisible);
629 foreach ($posts as $pid => $post) {
630 $discussion = $discussions[$post->discussion];
631 $forum = $forums[$discussion->forum];
632 $course = $courses[$forum->course];
633 $cm =& $coursemodules[$forum->id];
635 // Do some checks to see if we can bail out now.
637 // Only active enrolled users are in the list of subscribers.
638 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
639 if (!isset($subscribedusers[$forum->id][$userto->id])) {
640 // The user does not subscribe to this forum.
644 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
645 // The user does not subscribe to this forum, or to this specific discussion.
649 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
650 // Skip posts if the user subscribed to the discussion after it was created.
651 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
656 // Don't send email if the forum is Q&A and the user has not posted.
657 // Initial topics are still mailed.
658 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
659 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
663 // Get info about the sending user.
664 if (array_key_exists($post->userid, $users)) {
665 // We might know the user already.
666 $userfrom = $users[$post->userid];
667 if (!isset($userfrom->idnumber)) {
668 // Minimalised user info, fetch full record.
669 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
670 forum_cron_minimise_user_record($userfrom);
673 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
674 forum_cron_minimise_user_record($userfrom);
675 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
676 if ($userscount <= FORUM_CRON_USER_CACHE) {
678 $users[$userfrom->id] = $userfrom;
681 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
685 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
687 // Setup global $COURSE properly - needed for roles and languages.
688 cron_setup_user($userto, $course);
691 if (!isset($userto->viewfullnames[$forum->id])) {
692 $modcontext = context_module::instance($cm->id);
693 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
695 if (!isset($userto->canpost[$discussion->id])) {
696 $modcontext = context_module::instance($cm->id);
697 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
699 if (!isset($userfrom->groups[$forum->id])) {
700 if (!isset($userfrom->groups)) {
701 $userfrom->groups = array();
702 if (isset($users[$userfrom->id])) {
703 $users[$userfrom->id]->groups = array();
706 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
707 if (isset($users[$userfrom->id])) {
708 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
712 // Make sure groups allow this user to see this email.
713 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
714 // Groups are being used.
715 if (!groups_group_exists($discussion->groupid)) {
716 // Can't find group - be safe and don't this message.
720 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
721 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
726 // Make sure we're allowed to see the post.
727 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
728 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
732 // OK so we need to send the email.
734 // Does the user want this post in a digest? If so postpone it for now.
735 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
737 if ($maildigest > 0) {
738 // This user wants the mails to be in digest form.
739 $queue = new stdClass();
740 $queue->userid = $userto->id;
741 $queue->discussionid = $discussion->id;
742 $queue->postid = $post->id;
743 $queue->timemodified = $post->created;
744 $DB->insert_record('forum_queue', $queue);
748 // Prepare to actually send the post now, and build up the content.
750 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
752 $userfrom->customheaders = array (
753 // Headers to make emails easier to track.
754 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id . '@' . $hostname.'>',
755 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
756 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id, $hostname),
757 'X-Course-Id: ' . $course->id,
758 'X-Course-Name: ' . format_string($course->fullname, true),
760 // Headers to help prevent auto-responders.
762 'X-Auto-Response-Suppress: All',
763 'Auto-Submitted: auto-generated',
767 // This post is a reply, so add headers for threading (see MDL-22551).
768 $userfrom->customheaders[] = 'In-Reply-To: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
769 $userfrom->customheaders[] = 'References: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
772 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
774 // Generate a reply-to address from using the Inbound Message handler.
775 $replyaddress = null;
776 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
777 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
778 $replyaddress = $messageinboundgenerator->generate($userto->id);
781 if (!isset($userto->canpost[$discussion->id])) {
782 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
784 $canreply = $userto->canpost[$discussion->id];
787 $data = new \mod_forum\output\forum_post_email(
798 $userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>',
799 $data->get_unsubscribediscussionlink());
801 if (!isset($userto->viewfullnames[$forum->id])) {
802 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
804 $data->viewfullnames = $userto->viewfullnames[$forum->id];
807 // Not all of these variables are used in the default language
808 // string but are made available to support custom subjects.
810 $a->subject = $data->get_subject();
811 $a->forumname = $cleanforumname;
812 $a->sitefullname = format_string($site->fullname);
813 $a->siteshortname = format_string($site->shortname);
814 $a->courseidnumber = $data->get_courseidnumber();
815 $a->coursefullname = $data->get_coursefullname();
816 $a->courseshortname = $data->get_coursename();
817 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
819 // Send the post now!
820 mtrace('Sending ', '');
822 $eventdata = new \core\message\message();
823 $eventdata->component = 'mod_forum';
824 $eventdata->name = 'posts';
825 $eventdata->userfrom = $userfrom;
826 $eventdata->userto = $userto;
827 $eventdata->subject = $postsubject;
828 $eventdata->fullmessage = $textout->render($data);
829 $eventdata->fullmessageformat = FORMAT_PLAIN;
830 $eventdata->fullmessagehtml = $htmlout->render($data);
831 $eventdata->notification = 1;
832 $eventdata->replyto = $replyaddress;
833 if (!empty($replyaddress)) {
834 // Add extra text to email messages if they can reply back.
835 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
836 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
837 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
838 'fullmessagehtml' => array('footer' => $htmlfooter));
839 $eventdata->set_additional_content('email', $additionalcontent);
842 // If forum_replytouser is not set then send mail using the noreplyaddress.
843 if (empty($CFG->forum_replytouser)) {
844 $eventdata->userfrom = core_user::get_noreply_user();
847 $smallmessagestrings = new stdClass();
848 $smallmessagestrings->user = fullname($userfrom);
849 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
850 $smallmessagestrings->message = $post->message;
852 // Make sure strings are in message recipients language.
853 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
855 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
856 $eventdata->contexturl = $contexturl->out();
857 $eventdata->contexturlname = $discussion->name;
859 $mailresult = message_send($eventdata);
861 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
862 " ($userto->email) .. not trying again.");
863 $errorcount[$post->id]++;
865 $mailcount[$post->id]++;
867 // Mark post as read if forum_usermarksread is set off.
868 if (!$CFG->forum_usermarksread) {
869 $userto->markposts[$post->id] = $post->id;
873 mtrace('post ' . $post->id . ': ' . $post->subject);
876 // Mark processed posts as read.
877 forum_tp_mark_posts_read($userto, $userto->markposts);
883 foreach ($posts as $post) {
884 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
885 if ($errorcount[$post->id]) {
886 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
891 // release some memory
892 unset($subscribedusers);
898 $sitetimezone = core_date::get_server_timezone();
900 // Now see if there are any digest mails waiting to be sent, and if we should send them
902 mtrace('Starting digest processing...');
904 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
906 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
907 set_config('digestmailtimelast', 0);
911 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
913 // Delete any really old ones (normally there shouldn't be any)
914 $weekago = $timenow - (7 * 24 * 3600);
915 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
916 mtrace ('Cleaned old digest records');
918 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
920 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
922 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
924 if ($digestposts_rs->valid()) {
926 // We have work to do
929 //caches - reuse the those filled before too
930 $discussionposts = array();
931 $userdiscussions = array();
933 foreach ($digestposts_rs as $digestpost) {
934 if (!isset($posts[$digestpost->postid])) {
935 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
936 $posts[$digestpost->postid] = $post;
941 $discussionid = $digestpost->discussionid;
942 if (!isset($discussions[$discussionid])) {
943 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
944 $discussions[$discussionid] = $discussion;
949 $forumid = $discussions[$discussionid]->forum;
950 if (!isset($forums[$forumid])) {
951 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
952 $forums[$forumid] = $forum;
958 $courseid = $forums[$forumid]->course;
959 if (!isset($courses[$courseid])) {
960 if ($course = $DB->get_record('course', array('id' => $courseid))) {
961 $courses[$courseid] = $course;
967 if (!isset($coursemodules[$forumid])) {
968 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
969 $coursemodules[$forumid] = $cm;
974 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
975 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
977 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
979 // Data collected, start sending out emails to each user
980 foreach ($userdiscussions as $userid => $thesediscussions) {
982 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
986 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
988 // First of all delete all the queue entries for this user
989 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
991 // Init user caches - we keep the cache for one cycle only,
992 // otherwise it would unnecessarily consume memory.
993 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
994 $userto = clone($users[$userid]);
996 $userto = $DB->get_record('user', array('id' => $userid));
997 forum_cron_minimise_user_record($userto);
999 $userto->viewfullnames = array();
1000 $userto->canpost = array();
1001 $userto->markposts = array();
1003 // Override the language and timezone of the "current" user, so that
1004 // mail is customised for the receiver.
1005 cron_setup_user($userto);
1007 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
1009 $headerdata = new stdClass();
1010 $headerdata->sitename = format_string($site->fullname, true);
1011 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&course='.$site->id;
1013 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
1014 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
1016 $posthtml = "<head>";
1017 /* foreach ($CFG->stylesheets as $stylesheet) {
1019 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1021 $posthtml .= "</head>\n<body id=\"email\">\n";
1022 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
1024 foreach ($thesediscussions as $discussionid) {
1026 core_php_time_limit::raise(120); // to be reset for each post
1028 $discussion = $discussions[$discussionid];
1029 $forum = $forums[$discussion->forum];
1030 $course = $courses[$forum->course];
1031 $cm = $coursemodules[$forum->id];
1034 cron_setup_user($userto, $course);
1037 if (!isset($userto->viewfullnames[$forum->id])) {
1038 $modcontext = context_module::instance($cm->id);
1039 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
1041 if (!isset($userto->canpost[$discussion->id])) {
1042 $modcontext = context_module::instance($cm->id);
1043 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1046 $strforums = get_string('forums', 'forum');
1047 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1048 $canreply = $userto->canpost[$discussion->id];
1049 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1051 $posttext .= "\n \n";
1052 $posttext .= '=====================================================================';
1053 $posttext .= "\n \n";
1054 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1055 if ($discussion->name != $forum->name) {
1056 $posttext .= " -> ".format_string($discussion->name,true);
1059 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1062 $posthtml .= "<p><font face=\"sans-serif\">".
1063 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1064 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1065 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
1066 if ($discussion->name == $forum->name) {
1067 $posthtml .= "</font></p>";
1069 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
1073 $postsarray = $discussionposts[$discussionid];
1077 foreach ($postsarray as $postid) {
1078 $post = $posts[$postid];
1080 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1081 $userfrom = $users[$post->userid];
1082 if (!isset($userfrom->idnumber)) {
1083 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1084 forum_cron_minimise_user_record($userfrom);
1087 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1088 forum_cron_minimise_user_record($userfrom);
1089 if ($userscount <= FORUM_CRON_USER_CACHE) {
1091 $users[$userfrom->id] = $userfrom;
1095 mtrace('Could not find user '.$post->userid);
1099 if (!isset($userfrom->groups[$forum->id])) {
1100 if (!isset($userfrom->groups)) {
1101 $userfrom->groups = array();
1102 if (isset($users[$userfrom->id])) {
1103 $users[$userfrom->id]->groups = array();
1106 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1107 if (isset($users[$userfrom->id])) {
1108 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1112 // Headers to help prevent auto-responders.
1113 $userfrom->customheaders = array(
1115 'X-Auto-Response-Suppress: All',
1116 'Auto-Submitted: auto-generated',
1119 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1120 if (!isset($userto->canpost[$discussion->id])) {
1121 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1123 $canreply = $userto->canpost[$discussion->id];
1126 $data = new \mod_forum\output\forum_post_email(
1137 if (!isset($userto->viewfullnames[$forum->id])) {
1138 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1140 $data->viewfullnames = $userto->viewfullnames[$forum->id];
1143 if ($maildigest == 2) {
1144 // Subjects and link only.
1145 $posttext .= $textdigestbasicout->render($data);
1146 $posthtml .= $htmldigestbasicout->render($data);
1148 // The full treatment.
1149 $posttext .= $textdigestfullout->render($data);
1150 $posthtml .= $htmldigestfullout->render($data);
1152 // Create an array of postid's for this user to mark as read.
1153 if (!$CFG->forum_usermarksread) {
1154 $userto->markposts[$post->id] = $post->id;
1159 $footerlinks = array();
1160 if ($canunsubscribe) {
1161 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1163 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1165 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1166 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1167 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1169 $posthtml .= '</body>';
1171 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1172 // This user DOESN'T want to receive HTML
1176 $eventdata = new \core\message\message();
1177 $eventdata->component = 'mod_forum';
1178 $eventdata->name = 'digests';
1179 $eventdata->userfrom = core_user::get_noreply_user();
1180 $eventdata->userto = $userto;
1181 $eventdata->subject = $postsubject;
1182 $eventdata->fullmessage = $posttext;
1183 $eventdata->fullmessageformat = FORMAT_PLAIN;
1184 $eventdata->fullmessagehtml = $posthtml;
1185 $eventdata->notification = 1;
1186 $eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $sentcount);
1187 $mailresult = message_send($eventdata);
1190 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1191 "($userto->email)... not trying again.");
1196 // Mark post as read if forum_usermarksread is set off
1197 forum_tp_mark_posts_read($userto, $userto->markposts);
1201 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1202 set_config('digestmailtimelast', $timenow);
1207 if (!empty($usermailcount)) {
1208 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1211 if (!empty($CFG->forum_lastreadclean)) {
1213 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1214 set_config('forum_lastreadclean', $timenow);
1215 mtrace('Removing old forum read tracking info...');
1216 forum_tp_clean_read_records();
1219 set_config('forum_lastreadclean', time());
1227 * @param object $course
1228 * @param object $user
1229 * @param object $mod TODO this is not used in this function, refactor
1230 * @param object $forum
1231 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1233 function forum_user_outline($course, $user, $mod, $forum) {
1235 require_once("$CFG->libdir/gradelib.php");
1236 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1237 if (empty($grades->items[0]->grades)) {
1240 $grade = reset($grades->items[0]->grades);
1243 $count = forum_count_user_posts($forum->id, $user->id);
1245 if ($count && $count->postcount > 0) {
1246 $result = new stdClass();
1247 $result->info = get_string("numposts", "forum", $count->postcount);
1248 $result->time = $count->lastpost;
1250 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1253 } else if ($grade) {
1254 $result = new stdClass();
1255 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1257 //datesubmitted == time created. dategraded == time modified or time overridden
1258 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1259 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1260 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1261 $result->time = $grade->dategraded;
1263 $result->time = $grade->datesubmitted;
1275 * @param object $coure
1276 * @param object $user
1277 * @param object $mod
1278 * @param object $forum
1280 function forum_user_complete($course, $user, $mod, $forum) {
1281 global $CFG,$USER, $OUTPUT;
1282 require_once("$CFG->libdir/gradelib.php");
1284 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1285 if (!empty($grades->items[0]->grades)) {
1286 $grade = reset($grades->items[0]->grades);
1287 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1288 if ($grade->str_feedback) {
1289 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1293 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1295 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1296 print_error('invalidcoursemodule');
1298 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1300 foreach ($posts as $post) {
1301 if (!isset($discussions[$post->discussion])) {
1304 $discussion = $discussions[$post->discussion];
1306 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1309 echo "<p>".get_string("noposts", "forum")."</p>";
1314 * Filters the forum discussions according to groups membership and config.
1316 * @since Moodle 2.8, 2.7.1, 2.6.4
1317 * @param array $discussions Discussions with new posts array
1318 * @return array Forums with the number of new posts
1320 function forum_filter_user_groups_discussions($discussions) {
1322 // Group the remaining discussions posts by their forumid.
1323 $filteredforums = array();
1325 // Discard not visible groups.
1326 foreach ($discussions as $discussion) {
1328 // Course data is already cached.
1329 $instances = get_fast_modinfo($discussion->course)->get_instances();
1330 $forum = $instances['forum'][$discussion->forum];
1332 // Continue if the user should not see this discussion.
1333 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1337 // Grouping results by forum.
1338 if (empty($filteredforums[$forum->instance])) {
1339 $filteredforums[$forum->instance] = new stdClass();
1340 $filteredforums[$forum->instance]->id = $forum->id;
1341 $filteredforums[$forum->instance]->count = 0;
1343 $filteredforums[$forum->instance]->count += $discussion->count;
1347 return $filteredforums;
1351 * Returns whether the discussion group is visible by the current user or not.
1353 * @since Moodle 2.8, 2.7.1, 2.6.4
1354 * @param cm_info $cm The discussion course module
1355 * @param int $discussiongroupid The discussion groupid
1358 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1360 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1364 if (isguestuser()) {
1368 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1369 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1380 * @param array $courses
1381 * @param array $htmlarray
1383 function forum_print_overview($courses,&$htmlarray) {
1384 global $USER, $CFG, $DB, $SESSION;
1386 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1390 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1394 // Courses to search for new posts
1395 $coursessqls = array();
1397 foreach ($courses as $course) {
1399 // If the user has never entered into the course all posts are pending
1400 if ($course->lastaccess == 0) {
1401 $coursessqls[] = '(d.course = ?)';
1402 $params[] = $course->id;
1404 // Only posts created after the course last access
1406 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1407 $params[] = $course->id;
1408 $params[] = $course->lastaccess;
1411 $params[] = $USER->id;
1412 $coursessql = implode(' OR ', $coursessqls);
1414 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1415 .'FROM {forum_discussions} d '
1416 .'JOIN {forum_posts} p ON p.discussion = d.id '
1417 ."WHERE ($coursessql) "
1418 .'AND p.userid != ? '
1419 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
1420 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1421 .'ORDER BY d.course, d.forum';
1426 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1427 $discussions = array();
1430 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1432 // also get all forum tracking stuff ONCE.
1433 $trackingforums = array();
1434 foreach ($forums as $forum) {
1435 if (forum_tp_can_track_forums($forum)) {
1436 $trackingforums[$forum->id] = $forum;
1440 if (count($trackingforums) > 0) {
1441 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1442 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1443 ' FROM {forum_posts} p '.
1444 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1445 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1446 $params = array($USER->id);
1448 foreach ($trackingforums as $track) {
1449 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1450 $params[] = $track->id;
1451 if (isset($SESSION->currentgroup[$track->course])) {
1452 $groupid = $SESSION->currentgroup[$track->course];
1454 // get first groupid
1455 $groupids = groups_get_all_groups($track->course, $USER->id);
1458 $groupid = key($groupids);
1459 $SESSION->currentgroup[$track->course] = $groupid;
1465 $params[] = $groupid;
1467 $sql = substr($sql,0,-3); // take off the last OR
1468 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1469 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1470 $sql .= 'GROUP BY d.forum,d.course';
1471 $params[] = $cutoffdate;
1475 if (!$unread = $DB->get_records_sql($sql, $params)) {
1482 if (empty($unread) and empty($forumsnewposts)) {
1486 $strforum = get_string('modulename','forum');
1488 foreach ($forums as $forum) {
1492 $showunread = false;
1493 // either we have something from logs, or trackposts, or nothing.
1494 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1495 $count = $forumsnewposts[$forum->id]->count;
1497 if (array_key_exists($forum->id,$unread)) {
1498 $thisunread = $unread[$forum->id]->count;
1501 if ($count > 0 || $thisunread > 0) {
1502 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1503 $forum->name.'</a></div>';
1504 $str .= '<div class="info"><span class="postsincelogin">';
1505 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1506 if (!empty($showunread)) {
1507 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1509 $str .= '</div></div>';
1512 if (!array_key_exists($forum->course,$htmlarray)) {
1513 $htmlarray[$forum->course] = array();
1515 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1516 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1518 $htmlarray[$forum->course]['forum'] .= $str;
1524 * Given a course and a date, prints a summary of all the new
1525 * messages posted in the course since that date
1530 * @uses CONTEXT_MODULE
1531 * @uses VISIBLEGROUPS
1532 * @param object $course
1533 * @param bool $viewfullnames capability
1534 * @param int $timestart
1535 * @return bool success
1537 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1538 global $CFG, $USER, $DB, $OUTPUT;
1540 // do not use log table if possible, it may be huge and is expensive to join with other tables
1542 $allnamefields = user_picture::fields('u', null, 'duserid');
1543 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1544 d.timestart, d.timeend, $allnamefields
1545 FROM {forum_posts} p
1546 JOIN {forum_discussions} d ON d.id = p.discussion
1547 JOIN {forum} f ON f.id = d.forum
1548 JOIN {user} u ON u.id = p.userid
1549 WHERE p.created > ? AND f.course = ?
1550 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1554 $modinfo = get_fast_modinfo($course);
1556 $groupmodes = array();
1559 $strftimerecent = get_string('strftimerecent');
1561 $printposts = array();
1562 foreach ($posts as $post) {
1563 if (!isset($modinfo->instances['forum'][$post->forum])) {
1567 $cm = $modinfo->instances['forum'][$post->forum];
1568 if (!$cm->uservisible) {
1571 $context = context_module::instance($cm->id);
1573 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1577 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1578 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1579 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1584 // Check that the user can see the discussion.
1585 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1586 $printposts[] = $post;
1596 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1597 echo "\n<ul class='unlist'>\n";
1599 foreach ($printposts as $post) {
1600 $subjectclass = empty($post->parent) ? ' bold' : '';
1602 echo '<li><div class="head">'.
1603 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1604 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1606 echo '<div class="info'.$subjectclass.'">';
1607 if (empty($post->parent)) {
1608 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1610 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&parent='.$post->parent.'#p'.$post->id.'">';
1612 $post->subject = break_up_long_words(format_string($post->subject, true));
1613 echo $post->subject;
1614 echo "</a>\"</div></li>\n";
1623 * Return grade for given user or all users.
1627 * @param object $forum
1628 * @param int $userid optional user id, 0 means all users
1629 * @return array array of grades, false if none
1631 function forum_get_user_grades($forum, $userid = 0) {
1634 require_once($CFG->dirroot.'/rating/lib.php');
1636 $ratingoptions = new stdClass;
1637 $ratingoptions->component = 'mod_forum';
1638 $ratingoptions->ratingarea = 'post';
1640 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1641 $ratingoptions->modulename = 'forum';
1642 $ratingoptions->moduleid = $forum->id;
1643 $ratingoptions->userid = $userid;
1644 $ratingoptions->aggregationmethod = $forum->assessed;
1645 $ratingoptions->scaleid = $forum->scale;
1646 $ratingoptions->itemtable = 'forum_posts';
1647 $ratingoptions->itemtableusercolumn = 'userid';
1649 $rm = new rating_manager();
1650 return $rm->get_user_grades($ratingoptions);
1654 * Update activity grades
1657 * @param object $forum
1658 * @param int $userid specific user only, 0 means all
1659 * @param boolean $nullifnone return null if grade does not exist
1662 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1664 require_once($CFG->libdir.'/gradelib.php');
1666 if (!$forum->assessed) {
1667 forum_grade_item_update($forum);
1669 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1670 forum_grade_item_update($forum, $grades);
1672 } else if ($userid and $nullifnone) {
1673 $grade = new stdClass();
1674 $grade->userid = $userid;
1675 $grade->rawgrade = NULL;
1676 forum_grade_item_update($forum, $grade);
1679 forum_grade_item_update($forum);
1684 * Create/update grade item for given forum
1687 * @uses GRADE_TYPE_NONE
1688 * @uses GRADE_TYPE_VALUE
1689 * @uses GRADE_TYPE_SCALE
1690 * @param stdClass $forum Forum object with extra cmidnumber
1691 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1692 * @return int 0 if ok
1694 function forum_grade_item_update($forum, $grades=NULL) {
1696 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1697 require_once($CFG->libdir.'/gradelib.php');
1700 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1702 if (!$forum->assessed or $forum->scale == 0) {
1703 $params['gradetype'] = GRADE_TYPE_NONE;
1705 } else if ($forum->scale > 0) {
1706 $params['gradetype'] = GRADE_TYPE_VALUE;
1707 $params['grademax'] = $forum->scale;
1708 $params['grademin'] = 0;
1710 } else if ($forum->scale < 0) {
1711 $params['gradetype'] = GRADE_TYPE_SCALE;
1712 $params['scaleid'] = -$forum->scale;
1715 if ($grades === 'reset') {
1716 $params['reset'] = true;
1720 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1724 * Delete grade item for given forum
1727 * @param stdClass $forum Forum object
1728 * @return grade_item
1730 function forum_grade_item_delete($forum) {
1732 require_once($CFG->libdir.'/gradelib.php');
1734 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1739 * This function returns if a scale is being used by one forum
1742 * @param int $forumid
1743 * @param int $scaleid negative number
1746 function forum_scale_used ($forumid,$scaleid) {
1750 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1752 if (!empty($rec) && !empty($scaleid)) {
1760 * Checks if scale is being used by any instance of forum
1762 * This is used to find out if scale used anywhere
1765 * @param $scaleid int
1766 * @return boolean True if the scale is used by any forum
1768 function forum_scale_used_anywhere($scaleid) {
1770 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1777 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1780 * Gets a post with all info ready for forum_print_post
1781 * Most of these joins are just to get the forum id
1785 * @param int $postid
1786 * @return mixed array of posts or false
1788 function forum_get_post_full($postid) {
1791 $allnames = get_all_user_name_fields(true, 'u');
1792 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1793 FROM {forum_posts} p
1794 JOIN {forum_discussions} d ON p.discussion = d.id
1795 LEFT JOIN {user} u ON p.userid = u.id
1796 WHERE p.id = ?", array($postid));
1800 * Gets all posts in discussion including top parent.
1805 * @param int $discussionid
1806 * @param string $sort
1807 * @param bool $tracking does user track the forum?
1808 * @return array of posts
1810 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1811 global $CFG, $DB, $USER;
1819 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1820 $tr_sel = ", fr.id AS postread";
1821 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1822 $params[] = $USER->id;
1825 $allnames = get_all_user_name_fields(true, 'u');
1826 $params[] = $discussionid;
1827 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1828 FROM {forum_posts} p
1829 LEFT JOIN {user} u ON p.userid = u.id
1831 WHERE p.discussion = ?
1832 ORDER BY $sort", $params)) {
1836 foreach ($posts as $pid=>$p) {
1838 if (forum_tp_is_post_old($p)) {
1839 $posts[$pid]->postread = true;
1845 if (!isset($posts[$p->parent])) {
1846 continue; // parent does not exist??
1848 if (!isset($posts[$p->parent]->children)) {
1849 $posts[$p->parent]->children = array();
1851 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1854 // Start with the last child of the first post.
1855 $post = &$posts[reset($posts)->id];
1858 while (!$lastpost) {
1859 if (!isset($post->children)) {
1860 $post->lastpost = true;
1863 // Go to the last child of this post.
1864 $post = &$posts[end($post->children)->id];
1872 * An array of forum objects that the user is allowed to read/search through.
1877 * @param int $userid
1878 * @param int $courseid if 0, we look for forums throughout the whole site.
1879 * @return array of forum objects, or false if no matches
1880 * Forum objects have the following attributes:
1881 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1882 * viewhiddentimedposts
1884 function forum_get_readable_forums($userid, $courseid=0) {
1886 global $CFG, $DB, $USER;
1887 require_once($CFG->dirroot.'/course/lib.php');
1889 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1890 print_error('notinstalled', 'forum');
1894 $courses = $DB->get_records('course', array('id' => $courseid));
1896 // If no course is specified, then the user can see SITE + his courses.
1897 $courses1 = $DB->get_records('course', array('id' => SITEID));
1898 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1899 $courses = array_merge($courses1, $courses2);
1905 $readableforums = array();
1907 foreach ($courses as $course) {
1909 $modinfo = get_fast_modinfo($course);
1911 if (empty($modinfo->instances['forum'])) {
1916 $courseforums = $DB->get_records('forum', array('course' => $course->id));
1918 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1919 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1922 $context = context_module::instance($cm->id);
1923 $forum = $courseforums[$forumid];
1924 $forum->context = $context;
1927 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1932 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
1934 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1935 $forum->onlygroups[] = -1;
1938 /// hidden timed discussions
1939 $forum->viewhiddentimedposts = true;
1940 if (!empty($CFG->forum_enabletimedposts)) {
1941 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1942 $forum->viewhiddentimedposts = false;
1947 if ($forum->type == 'qanda'
1948 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1950 // We need to check whether the user has posted in the qanda forum.
1951 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1952 // the user is allowed to see in this forum.
1953 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1954 foreach ($discussionspostedin as $d) {
1955 $forum->onlydiscussions[] = $d->id;
1960 $readableforums[$forum->id] = $forum;
1965 } // End foreach $courses
1967 return $readableforums;
1971 * Returns a list of posts found using an array of search terms.
1976 * @param array $searchterms array of search terms, e.g. word +word -word
1977 * @param int $courseid if 0, we search through the whole site
1978 * @param int $limitfrom
1979 * @param int $limitnum
1980 * @param int &$totalcount
1981 * @param string $extrasql
1982 * @return array|bool Array of posts found or false
1984 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
1985 &$totalcount, $extrasql='') {
1986 global $CFG, $DB, $USER;
1987 require_once($CFG->libdir.'/searchlib.php');
1989 $forums = forum_get_readable_forums($USER->id, $courseid);
1991 if (count($forums) == 0) {
1996 $now = round(time(), -2); // db friendly
1998 $fullaccess = array();
2002 foreach ($forums as $forumid => $forum) {
2005 if (!$forum->viewhiddentimedposts) {
2006 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2007 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2011 $context = $forum->context;
2013 if ($forum->type == 'qanda'
2014 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2015 if (!empty($forum->onlydiscussions)) {
2016 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2017 $params = array_merge($params, $discussionid_params);
2018 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2020 $select[] = "p.parent = 0";
2024 if (!empty($forum->onlygroups)) {
2025 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2026 $params = array_merge($params, $groupid_params);
2027 $select[] = "d.groupid $groupid_sql";
2031 $selects = implode(" AND ", $select);
2032 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2033 $params['forum'.$forumid] = $forumid;
2035 $fullaccess[] = $forumid;
2040 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2041 $params = array_merge($params, $fullid_params);
2042 $where[] = "(d.forum $fullid_sql)";
2045 $selectdiscussion = "(".implode(" OR ", $where).")";
2047 $messagesearch = '';
2050 // Need to concat these back together for parser to work.
2051 foreach($searchterms as $searchterm){
2052 if ($searchstring != '') {
2053 $searchstring .= ' ';
2055 $searchstring .= $searchterm;
2058 // We need to allow quoted strings for the search. The quotes *should* be stripped
2059 // by the parser, but this should be examined carefully for security implications.
2060 $searchstring = str_replace("\\\"","\"",$searchstring);
2061 $parser = new search_parser();
2062 $lexer = new search_lexer($parser);
2064 if ($lexer->parse($searchstring)) {
2065 $parsearray = $parser->get_parsed_array();
2066 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2067 'p.userid', 'u.id', 'u.firstname',
2068 'u.lastname', 'p.modified', 'd.forum');
2069 $params = array_merge($params, $msparams);
2072 $fromsql = "{forum_posts} p,
2073 {forum_discussions} d,
2076 $selectsql = " $messagesearch
2077 AND p.discussion = d.id
2079 AND $selectdiscussion
2082 $countsql = "SELECT COUNT(*)
2086 $allnames = get_all_user_name_fields(true, 'u');
2087 $searchsql = "SELECT p.*,
2095 ORDER BY p.modified DESC";
2097 $totalcount = $DB->count_records_sql($countsql, $params);
2099 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2103 * Returns a list of all new posts that have not been mailed yet
2105 * @param int $starttime posts created after this time
2106 * @param int $endtime posts created before this
2107 * @param int $now used for timed discussions only
2110 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2114 $params['mailed'] = FORUM_MAILED_PENDING;
2115 $params['ptimestart'] = $starttime;
2116 $params['ptimeend'] = $endtime;
2117 $params['mailnow'] = 1;
2119 if (!empty($CFG->forum_enabletimedposts)) {
2123 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2124 $params['pptimestart'] = $starttime;
2125 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2126 $params['dtimestart'] = $now;
2127 $params['dtimeend'] = $now;
2130 $selectsql = "AND p.created >= :ptimestart";
2133 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2134 FROM {forum_posts} p
2135 JOIN {forum_discussions} d ON d.id = p.discussion
2136 WHERE p.mailed = :mailed
2138 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2140 ORDER BY p.modified ASC", $params);
2144 * Marks posts before a certain time as being mailed already
2148 * @param int $endtime
2149 * @param int $now Defaults to time()
2152 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2160 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2161 $params['now'] = $now;
2162 $params['endtime'] = $endtime;
2163 $params['mailnow'] = 1;
2164 $params['mailedpending'] = FORUM_MAILED_PENDING;
2166 if (empty($CFG->forum_enabletimedposts)) {
2167 return $DB->execute("UPDATE {forum_posts}
2168 SET mailed = :mailedsuccess
2169 WHERE (created < :endtime OR mailnow = :mailnow)
2170 AND mailed = :mailedpending", $params);
2172 return $DB->execute("UPDATE {forum_posts}
2173 SET mailed = :mailedsuccess
2174 WHERE discussion NOT IN (SELECT d.id
2175 FROM {forum_discussions} d
2176 WHERE d.timestart > :now)
2177 AND (created < :endtime OR mailnow = :mailnow)
2178 AND mailed = :mailedpending", $params);
2183 * Get all the posts for a user in a forum suitable for forum_print_post
2187 * @uses CONTEXT_MODULE
2190 function forum_get_user_posts($forumid, $userid) {
2194 $params = array($forumid, $userid);
2196 if (!empty($CFG->forum_enabletimedposts)) {
2197 $cm = get_coursemodule_from_instance('forum', $forumid);
2198 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2200 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2206 $allnames = get_all_user_name_fields(true, 'u');
2207 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2209 JOIN {forum_discussions} d ON d.forum = f.id
2210 JOIN {forum_posts} p ON p.discussion = d.id
2211 JOIN {user} u ON u.id = p.userid
2215 ORDER BY p.modified ASC", $params);
2219 * Get all the discussions user participated in
2223 * @uses CONTEXT_MODULE
2224 * @param int $forumid
2225 * @param int $userid
2226 * @return array Array or false
2228 function forum_get_user_involved_discussions($forumid, $userid) {
2232 $params = array($forumid, $userid);
2233 if (!empty($CFG->forum_enabletimedposts)) {
2234 $cm = get_coursemodule_from_instance('forum', $forumid);
2235 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2237 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2243 return $DB->get_records_sql("SELECT DISTINCT d.*
2245 JOIN {forum_discussions} d ON d.forum = f.id
2246 JOIN {forum_posts} p ON p.discussion = d.id
2249 $timedsql", $params);
2253 * Get all the posts for a user in a forum suitable for forum_print_post
2257 * @param int $forumid
2258 * @param int $userid
2259 * @return array of counts or false
2261 function forum_count_user_posts($forumid, $userid) {
2265 $params = array($forumid, $userid);
2266 if (!empty($CFG->forum_enabletimedposts)) {
2267 $cm = get_coursemodule_from_instance('forum', $forumid);
2268 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2270 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2276 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2278 JOIN {forum_discussions} d ON d.forum = f.id
2279 JOIN {forum_posts} p ON p.discussion = d.id
2280 JOIN {user} u ON u.id = p.userid
2283 $timedsql", $params);
2287 * Given a log entry, return the forum post details for it.
2291 * @param object $log
2292 * @return array|null
2294 function forum_get_post_from_log($log) {
2297 $allnames = get_all_user_name_fields(true, 'u');
2298 if ($log->action == "add post") {
2300 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2301 FROM {forum_discussions} d,
2306 AND d.id = p.discussion
2308 AND u.deleted <> '1'
2309 AND f.id = d.forum", array($log->info));
2312 } else if ($log->action == "add discussion") {
2314 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2315 FROM {forum_discussions} d,
2320 AND d.firstpost = p.id
2322 AND u.deleted <> '1'
2323 AND f.id = d.forum", array($log->info));
2329 * Given a discussion id, return the first post from the discussion
2333 * @param int $dicsussionid
2336 function forum_get_firstpost_from_discussion($discussionid) {
2339 return $DB->get_record_sql("SELECT p.*
2340 FROM {forum_discussions} d,
2343 AND d.firstpost = p.id ", array($discussionid));
2347 * Returns an array of counts of replies to each discussion
2351 * @param int $forumid
2352 * @param string $forumsort
2355 * @param int $perpage
2358 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2364 } else if ($page != -1) {
2365 $limitfrom = $page*$perpage;
2366 $limitnum = $perpage;
2372 if ($forumsort == "") {
2377 $orderby = "ORDER BY $forumsort";
2378 $groupby = ", ".strtolower($forumsort);
2379 $groupby = str_replace('desc', '', $groupby);
2380 $groupby = str_replace('asc', '', $groupby);
2383 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2384 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2385 FROM {forum_posts} p
2386 JOIN {forum_discussions} d ON p.discussion = d.id
2387 WHERE p.parent > 0 AND d.forum = ?
2388 GROUP BY p.discussion";
2389 return $DB->get_records_sql($sql, array($forumid));
2392 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2393 FROM {forum_posts} p
2394 JOIN {forum_discussions} d ON p.discussion = d.id
2396 GROUP BY p.discussion $groupby $orderby";
2397 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2405 * @staticvar array $cache
2406 * @param object $forum
2408 * @param object $course
2411 function forum_count_discussions($forum, $cm, $course) {
2412 global $CFG, $DB, $USER;
2414 static $cache = array();
2416 $now = round(time(), -2); // db cache friendliness
2418 $params = array($course->id);
2420 if (!isset($cache[$course->id])) {
2421 if (!empty($CFG->forum_enabletimedposts)) {
2422 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2429 $sql = "SELECT f.id, COUNT(d.id) as dcount
2431 JOIN {forum_discussions} d ON d.forum = f.id
2436 if ($counts = $DB->get_records_sql($sql, $params)) {
2437 foreach ($counts as $count) {
2438 $counts[$count->id] = $count->dcount;
2440 $cache[$course->id] = $counts;
2442 $cache[$course->id] = array();
2446 if (empty($cache[$course->id][$forum->id])) {
2450 $groupmode = groups_get_activity_groupmode($cm, $course);
2452 if ($groupmode != SEPARATEGROUPS) {
2453 return $cache[$course->id][$forum->id];
2456 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2457 return $cache[$course->id][$forum->id];
2460 require_once($CFG->dirroot.'/course/lib.php');
2462 $modinfo = get_fast_modinfo($course);
2464 $mygroups = $modinfo->get_groups($cm->groupingid);
2466 // add all groups posts
2469 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2470 $params[] = $forum->id;
2472 if (!empty($CFG->forum_enabletimedposts)) {
2473 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2480 $sql = "SELECT COUNT(d.id)
2481 FROM {forum_discussions} d
2482 WHERE d.groupid $mygroups_sql AND d.forum = ?
2485 return $DB->get_field_sql($sql, $params);
2489 * Get all discussions in a forum
2494 * @uses CONTEXT_MODULE
2495 * @uses VISIBLEGROUPS
2497 * @param string $forumsort
2498 * @param bool $fullpost
2499 * @param int $unused
2501 * @param bool $userlastmodified
2503 * @param int $perpage
2504 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2505 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
2508 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
2509 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1) {
2510 global $CFG, $DB, $USER;
2514 $now = round(time(), -2);
2515 $params = array($cm->instance);
2517 $modcontext = context_module::instance($cm->id);
2519 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2523 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2525 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2526 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2530 $timelimit .= " OR d.userid = ?";
2531 $params[] = $USER->id;
2540 } else if ($page != -1) {
2541 $limitfrom = $page*$perpage;
2542 $limitnum = $perpage;
2548 $groupmode = groups_get_activity_groupmode($cm);
2552 if (empty($modcontext)) {
2553 $modcontext = context_module::instance($cm->id);
2556 // Special case, we received a groupid to override currentgroup.
2558 $course = get_course($cm->course);
2559 if (!groups_group_visible($groupid, $course, $cm)) {
2560 // User doesn't belong to this group, return nothing.
2563 $currentgroup = $groupid;
2564 } else if ($groupid === -1) {
2565 $currentgroup = groups_get_activity_group($cm);
2567 // Get discussions for all groups current user can see.
2568 $currentgroup = null;
2571 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2572 if ($currentgroup) {
2573 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2574 $params[] = $currentgroup;
2582 // Get discussions for all groups current user can see.
2583 if ($currentgroup === null) {
2584 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
2585 if (empty($mygroups)) {
2586 $groupselect = "AND d.groupid = -1";
2588 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2589 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2590 $params = array_merge($params, $inparamsgroups);
2592 } else if ($currentgroup) {
2593 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2594 $params[] = $currentgroup;
2596 $groupselect = "AND d.groupid = -1";
2602 if (empty($forumsort)) {
2603 $forumsort = forum_get_default_sort_order();
2605 if (empty($fullpost)) {
2606 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2611 if (empty($userlastmodified)) { // We don't need to know this
2615 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2616 um.imagealt AS umimagealt';
2617 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2620 $allnames = get_all_user_name_fields(true, 'u');
2621 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
2622 u.email, u.picture, u.imagealt $umfields
2623 FROM {forum_discussions} d
2624 JOIN {forum_posts} p ON p.discussion = d.id
2625 JOIN {user} u ON p.userid = u.id
2627 WHERE d.forum = ? AND p.parent = 0
2628 $timelimit $groupselect
2629 ORDER BY $forumsort, d.id DESC";
2630 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2634 * Gets the neighbours (previous and next) of a discussion.
2636 * The calculation is based on the timemodified when time modified or time created is identical
2637 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
2639 * For blog-style forums, the calculation is based on the original creation time of the
2642 * Please note that this does not check whether or not the discussion passed is accessible
2643 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2644 * the returned neighbours are checked and are accessible to the current user.
2646 * @param object $cm The CM record.
2647 * @param object $discussion The discussion record.
2648 * @param object $forum The forum instance record.
2649 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2650 * they contain the record with minimal information such as 'id' and 'name'.
2651 * When the neighbour is not found the value is false.
2653 function forum_get_discussion_neighbours($cm, $discussion, $forum) {
2654 global $CFG, $DB, $USER;
2656 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
2657 throw new coding_exception('Discussion is not part of the same forum.');
2660 $neighbours = array('prev' => false, 'next' => false);
2661 $now = round(time(), -2);
2664 $modcontext = context_module::instance($cm->id);
2665 $groupmode = groups_get_activity_groupmode($cm);
2666 $currentgroup = groups_get_activity_group($cm);
2668 // Users must fulfill timed posts.
2670 if (!empty($CFG->forum_enabletimedposts)) {
2671 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2672 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2673 $params['tltimestart'] = $now;
2674 $params['tltimeend'] = $now;
2676 $timelimit .= ' OR d.userid = :tluserid';
2677 $params['tluserid'] = $USER->id;
2683 // Limiting to posts accessible according to groups.
2686 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2687 if ($currentgroup) {
2688 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2689 $params['groupid'] = $currentgroup;
2692 if ($currentgroup) {
2693 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2694 $params['groupid'] = $currentgroup;
2696 $groupselect = 'AND d.groupid = -1';
2701 $params['forumid'] = $cm->instance;
2702 $params['discid1'] = $discussion->id;
2703 $params['discid2'] = $discussion->id;
2704 $params['discid3'] = $discussion->id;
2705 $params['discid4'] = $discussion->id;
2706 $params['disctimecompare1'] = $discussion->timemodified;
2707 $params['disctimecompare2'] = $discussion->timemodified;
2708 $params['pinnedstate1'] = (int) $discussion->pinned;
2709 $params['pinnedstate2'] = (int) $discussion->pinned;
2710 $params['pinnedstate3'] = (int) $discussion->pinned;
2711 $params['pinnedstate4'] = (int) $discussion->pinned;
2713 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2714 FROM {forum_discussions} d
2715 JOIN {forum_posts} p ON d.firstpost = p.id
2716 WHERE d.forum = :forumid
2717 AND d.id <> :discid1
2720 $comparefield = "d.timemodified";
2721 $comparevalue = ":disctimecompare1";
2722 $comparevalue2 = ":disctimecompare2";
2723 if (!empty($CFG->forum_enabletimedposts)) {
2724 // Here we need to take into account the release time (timestart)
2725 // if one is set, of the neighbouring posts and compare it to the
2726 // timestart or timemodified of *this* post depending on if the
2727 // release date of this post is in the future or not.
2728 // This stops discussions that appear later because of the
2729 // timestart value from being buried under discussions that were
2731 $comparefield = "CASE WHEN d.timemodified < d.timestart
2732 THEN d.timestart ELSE d.timemodified END";
2733 if ($discussion->timemodified < $discussion->timestart) {
2734 // Normally we would just use the timemodified for sorting
2735 // discussion posts. However, when timed discussions are enabled,
2736 // then posts need to be sorted base on the later of timemodified
2737 // or the release date of the post (timestart).
2738 $params['disctimecompare1'] = $discussion->timestart;
2739 $params['disctimecompare2'] = $discussion->timestart;
2742 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2743 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
2745 if ($forum->type === 'blog') {
2746 $subselect = "SELECT pp.created
2747 FROM {forum_discussions} dd
2748 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
2750 $subselectwhere1 = " WHERE dd.id = :discid3";
2751 $subselectwhere2 = " WHERE dd.id = :discid4";
2753 $comparefield = "p.created";
2755 $sub1 = $subselect.$subselectwhere1;
2756 $comparevalue = "($sub1)";
2758 $sub2 = $subselect.$subselectwhere2;
2759 $comparevalue2 = "($sub2)";
2761 $orderbydesc = "d.pinned, p.created DESC";
2762 $orderbyasc = "d.pinned, p.created ASC";
2765 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2766 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2767 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2768 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
2770 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2771 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2772 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2773 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
2775 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2776 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2781 * Get the sql to use in the ORDER BY clause for forum discussions.
2783 * This has the ordering take timed discussion windows into account.
2785 * @param bool $desc True for DESC, False for ASC.
2786 * @param string $compare The field in the SQL to compare to normally sort by.
2787 * @param string $prefix The prefix being used for the discussion table.
2788 * @param bool $pinned sort pinned posts to the top
2791 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
2794 if (!empty($prefix)) {
2798 $dir = $desc ? 'DESC' : 'ASC';
2800 if ($pinned == true) {
2801 $pinned = "{$prefix}pinned DESC,";
2806 $sort = "{$prefix}timemodified";
2807 if (!empty($CFG->forum_enabletimedposts)) {
2808 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2809 THEN {$prefix}timestart
2813 return "$pinned $sort $dir";
2821 * @uses CONTEXT_MODULE
2822 * @uses VISIBLEGROUPS
2826 function forum_get_discussions_unread($cm) {
2827 global $CFG, $DB, $USER;
2829 $now = round(time(), -2);
2830 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2833 $groupmode = groups_get_activity_groupmode($cm);
2834 $currentgroup = groups_get_activity_group($cm);
2837 $modcontext = context_module::instance($cm->id);
2839 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2840 if ($currentgroup) {
2841 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2842 $params['currentgroup'] = $currentgroup;
2848 //separate groups without access all
2849 if ($currentgroup) {
2850 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2851 $params['currentgroup'] = $currentgroup;
2853 $groupselect = "AND d.groupid = -1";
2860 if (!empty($CFG->forum_enabletimedposts)) {
2861 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2862 $params['now1'] = $now;
2863 $params['now2'] = $now;
2868 $sql = "SELECT d.id, COUNT(p.id) AS unread
2869 FROM {forum_discussions} d
2870 JOIN {forum_posts} p ON p.discussion = d.id
2871 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2872 WHERE d.forum = {$cm->instance}
2873 AND p.modified >= :cutoffdate AND r.id is NULL
2877 $params['cutoffdate'] = $cutoffdate;
2879 if ($unreads = $DB->get_records_sql($sql, $params)) {
2880 foreach ($unreads as $unread) {
2881 $unreads[$unread->id] = $unread->unread;
2893 * @uses CONEXT_MODULE
2894 * @uses VISIBLEGROUPS
2898 function forum_get_discussions_count($cm) {
2899 global $CFG, $DB, $USER;
2901 $now = round(time(), -2);
2902 $params = array($cm->instance);
2903 $groupmode = groups_get_activity_groupmode($cm);
2904 $currentgroup = groups_get_activity_group($cm);
2907 $modcontext = context_module::instance($cm->id);
2909 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2910 if ($currentgroup) {
2911 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2912 $params[] = $currentgroup;
2918 //seprate groups without access all
2919 if ($currentgroup) {
2920 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2921 $params[] = $currentgroup;
2923 $groupselect = "AND d.groupid = -1";
2930 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2934 if (!empty($CFG->forum_enabletimedposts)) {
2936 $modcontext = context_module::instance($cm->id);
2938 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2939 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2943 $timelimit .= " OR d.userid = ?";
2944 $params[] = $USER->id;
2950 $sql = "SELECT COUNT(d.id)
2951 FROM {forum_discussions} d
2952 JOIN {forum_posts} p ON p.discussion = d.id
2953 WHERE d.forum = ? AND p.parent = 0
2954 $groupselect $timelimit";
2956 return $DB->get_field_sql($sql, $params);
2960 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2966 * @param int $courseid
2967 * @param string $type
2969 function forum_get_course_forum($courseid, $type) {
2970 // How to set up special 1-per-course forums
2971 global $CFG, $DB, $OUTPUT, $USER;
2973 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2974 // There should always only be ONE, but with the right combination of
2975 // errors there might be more. In this case, just return the oldest one (lowest ID).
2976 foreach ($forums as $forum) {
2977 return $forum; // ie the first one
2981 // Doesn't exist, so create one now.
2982 $forum = new stdClass();
2983 $forum->course = $courseid;
2984 $forum->type = "$type";
2985 if (!empty($USER->htmleditor)) {
2986 $forum->introformat = $USER->htmleditor;
2988 switch ($forum->type) {
2990 $forum->name = get_string("namenews", "forum");
2991 $forum->intro = get_string("intronews", "forum");
2992 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2993 $forum->assessed = 0;
2994 if ($courseid == SITEID) {
2995 $forum->name = get_string("sitenews");
2996 $forum->forcesubscribe = 0;
3000 $forum->name = get_string("namesocial", "forum");
3001 $forum->intro = get_string("introsocial", "forum");
3002 $forum->assessed = 0;
3003 $forum->forcesubscribe = 0;
3006 $forum->name = get_string('blogforum', 'forum');
3007 $forum->intro = get_string('introblog', 'forum');
3008 $forum->assessed = 0;
3009 $forum->forcesubscribe = 0;
3012 echo $OUTPUT->notification("That forum type doesn't exist!");
3017 $forum->timemodified = time();
3018 $forum->id = $DB->insert_record("forum", $forum);
3020 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
3021 echo $OUTPUT->notification("Could not find forum module!!");
3024 $mod = new stdClass();
3025 $mod->course = $courseid;
3026 $mod->module = $module->id;
3027 $mod->instance = $forum->id;
3029 include_once("$CFG->dirroot/course/lib.php");
3030 if (! $mod->coursemodule = add_course_module($mod) ) {
3031 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3034 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3035 return $DB->get_record("forum", array("id" => "$forum->id"));
3039 * Print a forum post
3043 * @uses FORUM_MODE_THREADED
3044 * @uses PORTFOLIO_FORMAT_PLAINHTML
3045 * @uses PORTFOLIO_FORMAT_FILE
3046 * @uses PORTFOLIO_FORMAT_RICHHTML
3047 * @uses PORTFOLIO_ADD_TEXT_LINK
3048 * @uses CONTEXT_MODULE
3049 * @param object $post The post to print.
3050 * @param object $discussion
3051 * @param object $forum
3053 * @param object $course
3054 * @param boolean $ownpost Whether this post belongs to the current user.
3055 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3056 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3057 * @param string $footer Extra stuff to print after the message.
3058 * @param string $highlight Space-separated list of terms to highlight.
3059 * @param int $post_read true, false or -99. If we already know whether this user
3060 * has read this post, pass that in, otherwise, pass in -99, and this
3061 * function will work it out.
3062 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3063 * the current user can't see this post, if this argument is true
3064 * (the default) then print a dummy 'you can't see this post' post.
3065 * If false, don't output anything at all.
3066 * @param bool|null $istracked
3069 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3070 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3071 global $USER, $CFG, $OUTPUT;
3073 require_once($CFG->libdir . '/filelib.php');
3078 $modcontext = context_module::instance($cm->id);
3080 $post->course = $course->id;
3081 $post->forum = $forum->id;
3082 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3083 if (!empty($CFG->enableplagiarism)) {
3084 require_once($CFG->libdir.'/plagiarismlib.php');
3085 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3086 'content' => $post->message,
3088 'course' => $post->course,
3089 'forum' => $post->forum));
3093 if (!isset($cm->cache)) {
3094 $cm->cache = new stdClass;
3097 if (!isset($cm->cache->caps)) {
3098 $cm->cache->caps = array();
3099 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3100 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3101 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3102 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3103 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3104 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3105 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3106 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3107 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3110 if (!isset($cm->uservisible)) {
3111 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3114 if ($istracked && is_null($postisread)) {
3115 $postisread = forum_tp_is_post_read($USER->id, $post);
3118 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3120 if (!$dummyifcantsee) {
3127 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3128 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3130 'aria-label' => get_string('hiddenforumpost', 'forum')));
3131 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3132 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3133 if ($post->parent) {
3134 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3136 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3138 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3139 'role' => 'header')); // Subject.
3140 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3141 'role' => 'header')); // Author.
3142 $output .= html_writer::end_tag('div');
3143 $output .= html_writer::end_tag('div'); // row
3144 $output .= html_writer::start_tag('div', array('class'=>'row'));
3145 $output .= html_writer::tag('div', ' ', array('class'=>'left side')); // Groups
3146 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3147 $output .= html_writer::end_tag('div'); // row
3148 $output .= html_writer::end_tag('div'); // forumpost
3158 $str = new stdClass;
3159 $str->edit = get_string('edit', 'forum');
3160 $str->delete = get_string('delete', 'forum');
3161 $str->reply = get_string('reply', 'forum');
3162 $str->parent = get_string('parent', 'forum');
3163 $str->pruneheading = get_string('pruneheading', 'forum');
3164 $str->prune = get_string('prune', 'forum');
3165 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3166 $str->markread = get_string('markread', 'forum');
3167 $str->markunread = get_string('markunread', 'forum');
3170 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3172 // Build an object that represents the posting user
3173 $postuser = new stdClass;
3174 $postuserfields = explode(',', user_picture::fields());
3175 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3176 $postuser->id = $post->userid;
3177 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3178 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3180 // Prepare the groups the posting user belongs to
3181 if (isset($cm->cache->usersgroups)) {
3183 if (isset($cm->cache->usersgroups[$post->userid])) {
3184 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3185 $groups[$gid] = $cm->cache->groups[$gid];
3189 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3192 // Prepare the attachements for the post, files then images
3193 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3195 // Determine if we need to shorten this post
3196 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3199 // Prepare an array of commands
3200 $commands = array();
3203 $permalink = new moodle_url($discussionlink);
3204 $permalink->set_anchor('p' . $post->id);
3205 $commands[] = array('url' => $permalink, 'text' => get_string('permalink', 'forum'));
3207 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3208 // Don't display the mark read / unread controls in this case.
3209 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3210 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3211 $text = $str->markunread;
3213 $url->param('mark', 'read');
3214 $text = $str->markread;
3216 if ($str->displaymode == FORUM_MODE_THREADED) {
3217 $url->param('parent', $post->parent);
3219 $url->set_anchor('p'.$post->id);
3221 $commands[] = array('url'=>$url, 'text'=>$text);
3224 // Zoom in to the parent specifically
3225 if ($post->parent) {
3226 $url = new moodle_url($discussionlink);
3227 if ($str->displaymode == FORUM_MODE_THREADED) {
3228 $url->param('parent', $post->parent);
3230 $url->set_anchor('p'.$post->parent);
3232 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3235 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3236 $age = time() - $post->created;
3237 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3241 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3242 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3243 // The first post in single simple is the forum description.
3244 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3246 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3247 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3250 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3251 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3254 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3255 // Do not allow deleting of first post in single simple type.
3256 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3257 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3261 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3264 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3265 $p = array('postid' => $post->id);
3266 require_once($CFG->libdir.'/portfoliolib.php');
3267 $button = new portfolio_add_button();
3268 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3269 if (empty($attachments)) {
3270 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3272 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3275 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3276 if (!empty($porfoliohtml)) {
3277 $commands[] = $porfoliohtml;
3280 // Finished building commands
3289 $forumpostclass = ' read';
3291 $forumpostclass = ' unread';
3292 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3295 // ignore trackign status if not tracked or tracked param missing
3296 $forumpostclass = '';
3300 if (empty($post->parent)) {
3301 $topicclass = ' firstpost starter';
3304 if (!empty($post->lastpost)) {
3305 $forumpostclass .= ' lastpost';
3308 $postbyuser = new stdClass;
3309 $postbyuser->post = $post->subject;
3310 $postbyuser->user = $postuser->fullname;
3311 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3312 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3313 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3315 'aria-label' => $discussionbyuser));
3316 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3317 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3318 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3319 $output .= html_writer::end_tag('div');
3322 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3324 $postsubject = $post->subject;
3325 if (empty($post->subjectnoformat)) {
3326 $postsubject = format_string($postsubject);
3328 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject',
3329 'role' => 'heading',
3330 'aria-level' => '2'));
3332 $by = new stdClass();
3333 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3334 $by->date = userdate($post->modified);
3335 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3336 'role' => 'heading',
3337 'aria-level' => '2'));
3339 $output .= html_writer::end_tag('div'); //topic
3340 $output .= html_writer::end_tag('div'); //row
3342 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3343 $output .= html_writer::start_tag('div', array('class'=>'left'));
3347 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3349 if (empty($groupoutput)) {
3350 $groupoutput = ' ';
3352 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3354 $output .= html_writer::end_tag('div'); //left side
3355 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3356 $output .= html_writer::start_tag('div', array('class'=>'content'));
3358 $options = new stdClass;
3359 $options->para = false;
3360 $options->trusted = $post->messagetrust;
3361 $options->context = $modcontext;
3363 // Prepare shortened version by filtering the text then shortening it.
3364 $postclass = 'shortenedpost';
3365 $postcontent = format_text($post->message, $post->messageformat, $options);
3366 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3367 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3368 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3369 array('class'=>'post-word-count'));
3371 // Prepare whole post
3372 $postclass = 'fullpost';
3373 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3374 if (!empty($highlight)) {
3375 $postcontent = highlight($highlight, $postcontent);
3377 if (!empty($forum->displaywordcount)) {
3378 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3379 array('class'=>'post-word-count'));
3381 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3384 // Output the post content
3385 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3386 $output .= html_writer::end_tag('div'); // Content
3387 $output .= html_writer::end_tag('div'); // Content mask
3388 $output .= html_writer::end_tag('div'); // Row
3390 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3391 $output .= html_writer::tag('div',' ', array('class'=>'left'));
3392 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3394 if (!empty($attachments)) {
3395 $output .= html_writer::tag('div', $attachments, array('class' => 'attachments'));
3399 if (!empty($post->rating)) {
3400 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3403 // Output the commands
3404 $commandhtml = array();
3405 foreach ($commands as $command) {
3406 if (is_array($command)) {
3407 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3409 $commandhtml[] = $command;
3412 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3414 // Output link to post if required
3415 if ($link && forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3416 if ($post->replies == 1) {
3417 $replystring = get_string('repliesone', 'forum', $post->replies);
3419 $replystring = get_string('repliesmany', 'forum', $post->replies);
3421 if (!empty($discussion->unread) && $discussion->unread !== '-') {
3422 $replystring .= ' <span class="sep">/</span> <span class="unread">';
3423 if ($discussion->unread == 1) {
3424 $replystring .= get_string('unreadpostsone', 'forum');
3426 $replystring .= get_string('unreadpostsnumber', 'forum', $discussion->unread);
3428 $replystring .= '</span>';
3431 $output .= html_writer::start_tag('div', array('class'=>'link'));
3432 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3433 $output .= ' ('.$replystring.')';
3434 $output .= html_writer::end_tag('div'); // link