MDL-45898 myprofile: Redesign my profile page
[moodle.git] / mod / forum / lib.php
blob78f843d12aab6d95a4cc4dd6f75ae7dcf060f82c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * @package mod_forum
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);
42 /**
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
47 /**
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
52 /**
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
62 if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
67 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
69 /**
70 * Given an object containing all the necessary data,
71 * (defined by the form in mod_form.php) this function
72 * will create a new instance and return the id number
73 * of the new instance.
75 * @param stdClass $forum add forum instance
76 * @param mod_forum_mod_form $mform
77 * @return int intance id
79 function forum_add_instance($forum, $mform = null) {
80 global $CFG, $DB;
82 $forum->timemodified = time();
84 if (empty($forum->assessed)) {
85 $forum->assessed = 0;
88 if (empty($forum->ratingtime) or empty($forum->assessed)) {
89 $forum->assesstimestart = 0;
90 $forum->assesstimefinish = 0;
93 $forum->id = $DB->insert_record('forum', $forum);
94 $modcontext = context_module::instance($forum->coursemodule);
96 if ($forum->type == 'single') { // Create related discussion.
97 $discussion = new stdClass();
98 $discussion->course = $forum->course;
99 $discussion->forum = $forum->id;
100 $discussion->name = $forum->name;
101 $discussion->assessed = $forum->assessed;
102 $discussion->message = $forum->intro;
103 $discussion->messageformat = $forum->introformat;
104 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
105 $discussion->mailnow = false;
106 $discussion->groupid = -1;
108 $message = '';
110 $discussion->id = forum_add_discussion($discussion, null, $message);
112 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
113 // Ugly hack - we need to copy the files somehow.
114 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
115 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
117 $options = array('subdirs'=>true); // Use the same options as intro field!
118 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
119 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
123 forum_grade_item_update($forum);
125 return $forum->id;
129 * Handle changes following the creation of a forum instance.
130 * This function is typically called by the course_module_created observer.
132 * @param object $context the forum context
133 * @param stdClass $forum The forum object
134 * @return void
136 function forum_instance_created($context, $forum) {
137 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
138 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
139 foreach ($users as $user) {
140 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
146 * Given an object containing all the necessary data,
147 * (defined by the form in mod_form.php) this function
148 * will update an existing instance with new data.
150 * @global object
151 * @param object $forum forum instance (with magic quotes)
152 * @return bool success
154 function forum_update_instance($forum, $mform) {
155 global $DB, $OUTPUT, $USER;
157 $forum->timemodified = time();
158 $forum->id = $forum->instance;
160 if (empty($forum->assessed)) {
161 $forum->assessed = 0;
164 if (empty($forum->ratingtime) or empty($forum->assessed)) {
165 $forum->assesstimestart = 0;
166 $forum->assesstimefinish = 0;
169 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
171 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
172 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
173 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
174 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
175 forum_update_grades($forum); // recalculate grades for the forum
178 if ($forum->type == 'single') { // Update related discussion and post.
179 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
180 if (!empty($discussions)) {
181 if (count($discussions) > 1) {
182 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
184 $discussion = array_pop($discussions);
185 } else {
186 // try to recover by creating initial discussion - MDL-16262
187 $discussion = new stdClass();
188 $discussion->course = $forum->course;
189 $discussion->forum = $forum->id;
190 $discussion->name = $forum->name;
191 $discussion->assessed = $forum->assessed;
192 $discussion->message = $forum->intro;
193 $discussion->messageformat = $forum->introformat;
194 $discussion->messagetrust = true;
195 $discussion->mailnow = false;
196 $discussion->groupid = -1;
198 $message = '';
200 forum_add_discussion($discussion, null, $message);
202 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
203 print_error('cannotadd', 'forum');
206 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
207 print_error('cannotfindfirstpost', 'forum');
210 $cm = get_coursemodule_from_instance('forum', $forum->id);
211 $modcontext = context_module::instance($cm->id, MUST_EXIST);
213 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
214 $post->subject = $forum->name;
215 $post->message = $forum->intro;
216 $post->messageformat = $forum->introformat;
217 $post->messagetrust = trusttext_trusted($modcontext);
218 $post->modified = $forum->timemodified;
219 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
221 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
222 // Ugly hack - we need to copy the files somehow.
223 $options = array('subdirs'=>true); // Use the same options as intro field!
224 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
227 $DB->update_record('forum_posts', $post);
228 $discussion->name = $forum->name;
229 $DB->update_record('forum_discussions', $discussion);
232 $DB->update_record('forum', $forum);
234 $modcontext = context_module::instance($forum->coursemodule);
235 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
236 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
237 foreach ($users as $user) {
238 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
242 forum_grade_item_update($forum);
244 return true;
249 * Given an ID of an instance of this module,
250 * this function will permanently delete the instance
251 * and any data that depends on it.
253 * @global object
254 * @param int $id forum instance id
255 * @return bool success
257 function forum_delete_instance($id) {
258 global $DB;
260 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
261 return false;
263 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
264 return false;
266 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
267 return false;
270 $context = context_module::instance($cm->id);
272 // now get rid of all files
273 $fs = get_file_storage();
274 $fs->delete_area_files($context->id);
276 $result = true;
278 // Delete digest and subscription preferences.
279 $DB->delete_records('forum_digests', array('forum' => $forum->id));
280 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
281 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
283 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
284 foreach ($discussions as $discussion) {
285 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
286 $result = false;
291 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
293 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
294 $result = false;
297 forum_grade_item_delete($forum);
299 return $result;
304 * Indicates API features that the forum supports.
306 * @uses FEATURE_GROUPS
307 * @uses FEATURE_GROUPINGS
308 * @uses FEATURE_MOD_INTRO
309 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
310 * @uses FEATURE_COMPLETION_HAS_RULES
311 * @uses FEATURE_GRADE_HAS_GRADE
312 * @uses FEATURE_GRADE_OUTCOMES
313 * @param string $feature
314 * @return mixed True if yes (some features may use other values)
316 function forum_supports($feature) {
317 switch($feature) {
318 case FEATURE_GROUPS: return true;
319 case FEATURE_GROUPINGS: return true;
320 case FEATURE_MOD_INTRO: return true;
321 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
322 case FEATURE_COMPLETION_HAS_RULES: return true;
323 case FEATURE_GRADE_HAS_GRADE: return true;
324 case FEATURE_GRADE_OUTCOMES: return true;
325 case FEATURE_RATE: return true;
326 case FEATURE_BACKUP_MOODLE2: return true;
327 case FEATURE_SHOW_DESCRIPTION: return true;
328 case FEATURE_PLAGIARISM: return true;
330 default: return null;
336 * Obtains the automatic completion state for this forum based on any conditions
337 * in forum settings.
339 * @global object
340 * @global object
341 * @param object $course Course
342 * @param object $cm Course-module
343 * @param int $userid User ID
344 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
345 * @return bool True if completed, false if not. (If no conditions, then return
346 * value depends on comparison type)
348 function forum_get_completion_state($course,$cm,$userid,$type) {
349 global $CFG,$DB;
351 // Get forum details
352 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
353 throw new Exception("Can't find forum {$cm->instance}");
356 $result=$type; // Default return value
358 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
359 $postcountsql="
360 SELECT
361 COUNT(1)
362 FROM
363 {forum_posts} fp
364 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
365 WHERE
366 fp.userid=:userid AND fd.forum=:forumid";
368 if ($forum->completiondiscussions) {
369 $value = $forum->completiondiscussions <=
370 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
371 if ($type == COMPLETION_AND) {
372 $result = $result && $value;
373 } else {
374 $result = $result || $value;
377 if ($forum->completionreplies) {
378 $value = $forum->completionreplies <=
379 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
380 if ($type==COMPLETION_AND) {
381 $result = $result && $value;
382 } else {
383 $result = $result || $value;
386 if ($forum->completionposts) {
387 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
388 if ($type == COMPLETION_AND) {
389 $result = $result && $value;
390 } else {
391 $result = $result || $value;
395 return $result;
399 * Create a message-id string to use in the custom headers of forum notification emails
401 * message-id is used by email clients to identify emails and to nest conversations
403 * @param int $postid The ID of the forum post we are notifying the user about
404 * @param int $usertoid The ID of the user being notified
405 * @param string $hostname The server's hostname
406 * @return string A unique message-id
408 function forum_get_email_message_id($postid, $usertoid, $hostname) {
409 return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
413 * Removes properties from user record that are not necessary
414 * for sending post notifications.
415 * @param stdClass $user
416 * @return void, $user parameter is modified
418 function forum_cron_minimise_user_record(stdClass $user) {
420 // We store large amount of users in one huge array,
421 // make sure we do not store info there we do not actually need
422 // in mail generation code or messaging.
424 unset($user->institution);
425 unset($user->department);
426 unset($user->address);
427 unset($user->city);
428 unset($user->url);
429 unset($user->currentlogin);
430 unset($user->description);
431 unset($user->descriptionformat);
435 * Function to be run periodically according to the scheduled task.
437 * Finds all posts that have yet to be mailed out, and mails them
438 * out to all subscribers as well as other maintance tasks.
440 * NOTE: Since 2.7.2 this function is run by scheduled task rather
441 * than standard cron.
443 * @todo MDL-44734 The function will be split up into seperate tasks.
445 function forum_cron() {
446 global $CFG, $USER, $DB;
448 $site = get_site();
450 // All users that are subscribed to any post that needs sending,
451 // please increase $CFG->extramemorylimit on large sites that
452 // send notifications to a large number of users.
453 $users = array();
454 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
456 // Status arrays.
457 $mailcount = array();
458 $errorcount = array();
460 // caches
461 $discussions = array();
462 $forums = array();
463 $courses = array();
464 $coursemodules = array();
465 $subscribedusers = array();
466 $messageinboundhandlers = array();
468 // Posts older than 2 days will not be mailed. This is to avoid the problem where
469 // cron has not been running for a long time, and then suddenly people are flooded
470 // with mail from the past few weeks or months
471 $timenow = time();
472 $endtime = $timenow - $CFG->maxeditingtime;
473 $starttime = $endtime - 48 * 3600; // Two days earlier
475 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
476 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
477 $digests = array();
478 foreach ($digestsset as $thisrow) {
479 if (!isset($digests[$thisrow->forum])) {
480 $digests[$thisrow->forum] = array();
482 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
484 $digestsset->close();
486 // Create the generic messageinboundgenerator.
487 $messageinboundgenerator = new \core\message\inbound\address_manager();
488 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
490 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
491 // Mark them all now as being mailed. It's unlikely but possible there
492 // might be an error later so that a post is NOT actually mailed out,
493 // but since mail isn't crucial, we can accept this risk. Doing it now
494 // prevents the risk of duplicated mails, which is a worse problem.
496 if (!forum_mark_old_posts_as_mailed($endtime)) {
497 mtrace('Errors occurred while trying to mark some posts as being mailed.');
498 return false; // Don't continue trying to mail them, in case we are in a cron loop
501 // checking post validity, and adding users to loop through later
502 foreach ($posts as $pid => $post) {
504 $discussionid = $post->discussion;
505 if (!isset($discussions[$discussionid])) {
506 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
507 $discussions[$discussionid] = $discussion;
508 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
509 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
511 } else {
512 mtrace('Could not find discussion ' . $discussionid);
513 unset($posts[$pid]);
514 continue;
517 $forumid = $discussions[$discussionid]->forum;
518 if (!isset($forums[$forumid])) {
519 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
520 $forums[$forumid] = $forum;
521 } else {
522 mtrace('Could not find forum '.$forumid);
523 unset($posts[$pid]);
524 continue;
527 $courseid = $forums[$forumid]->course;
528 if (!isset($courses[$courseid])) {
529 if ($course = $DB->get_record('course', array('id' => $courseid))) {
530 $courses[$courseid] = $course;
531 } else {
532 mtrace('Could not find course '.$courseid);
533 unset($posts[$pid]);
534 continue;
537 if (!isset($coursemodules[$forumid])) {
538 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
539 $coursemodules[$forumid] = $cm;
540 } else {
541 mtrace('Could not find course module for forum '.$forumid);
542 unset($posts[$pid]);
543 continue;
547 // Save the Inbound Message datakey here to reduce DB queries later.
548 $messageinboundgenerator->set_data($pid);
549 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
551 // Caching subscribed users of each forum.
552 if (!isset($subscribedusers[$forumid])) {
553 $modcontext = context_module::instance($coursemodules[$forumid]->id);
554 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
556 foreach ($subusers as $postuser) {
557 // this user is subscribed to this forum
558 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
559 $userscount++;
560 if ($userscount > FORUM_CRON_USER_CACHE) {
561 // Store minimal user info.
562 $minuser = new stdClass();
563 $minuser->id = $postuser->id;
564 $users[$postuser->id] = $minuser;
565 } else {
566 // Cache full user record.
567 forum_cron_minimise_user_record($postuser);
568 $users[$postuser->id] = $postuser;
571 // Release memory.
572 unset($subusers);
573 unset($postuser);
576 $mailcount[$pid] = 0;
577 $errorcount[$pid] = 0;
581 if ($users && $posts) {
583 $urlinfo = parse_url($CFG->wwwroot);
584 $hostname = $urlinfo['host'];
586 foreach ($users as $userto) {
587 // Terminate if processing of any account takes longer than 2 minutes.
588 core_php_time_limit::raise(120);
590 mtrace('Processing user ' . $userto->id);
592 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
593 if (isset($userto->username)) {
594 $userto = clone($userto);
595 } else {
596 $userto = $DB->get_record('user', array('id' => $userto->id));
597 forum_cron_minimise_user_record($userto);
599 $userto->viewfullnames = array();
600 $userto->canpost = array();
601 $userto->markposts = array();
603 // Setup this user so that the capabilities are cached, and environment matches receiving user.
604 cron_setup_user($userto);
606 // Reset the caches.
607 foreach ($coursemodules as $forumid => $unused) {
608 $coursemodules[$forumid]->cache = new stdClass();
609 $coursemodules[$forumid]->cache->caps = array();
610 unset($coursemodules[$forumid]->uservisible);
613 foreach ($posts as $pid => $post) {
614 $discussion = $discussions[$post->discussion];
615 $forum = $forums[$discussion->forum];
616 $course = $courses[$forum->course];
617 $cm =& $coursemodules[$forum->id];
619 // Do some checks to see if we can bail out now.
621 // Only active enrolled users are in the list of subscribers.
622 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
623 if (!isset($subscribedusers[$forum->id][$userto->id])) {
624 // The user does not subscribe to this forum.
625 continue;
628 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
629 // The user does not subscribe to this forum, or to this specific discussion.
630 continue;
633 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
634 // Skip posts if the user subscribed to the discussion after it was created.
635 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
636 continue;
640 // Don't send email if the forum is Q&A and the user has not posted.
641 // Initial topics are still mailed.
642 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
643 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
644 continue;
647 // Get info about the sending user.
648 if (array_key_exists($post->userid, $users)) {
649 // We might know the user already.
650 $userfrom = $users[$post->userid];
651 if (!isset($userfrom->idnumber)) {
652 // Minimalised user info, fetch full record.
653 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
654 forum_cron_minimise_user_record($userfrom);
657 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
658 forum_cron_minimise_user_record($userfrom);
659 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
660 if ($userscount <= FORUM_CRON_USER_CACHE) {
661 $userscount++;
662 $users[$userfrom->id] = $userfrom;
664 } else {
665 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
666 continue;
669 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
671 // Setup global $COURSE properly - needed for roles and languages.
672 cron_setup_user($userto, $course);
674 // Fill caches.
675 if (!isset($userto->viewfullnames[$forum->id])) {
676 $modcontext = context_module::instance($cm->id);
677 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
679 if (!isset($userto->canpost[$discussion->id])) {
680 $modcontext = context_module::instance($cm->id);
681 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
683 if (!isset($userfrom->groups[$forum->id])) {
684 if (!isset($userfrom->groups)) {
685 $userfrom->groups = array();
686 if (isset($users[$userfrom->id])) {
687 $users[$userfrom->id]->groups = array();
690 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
691 if (isset($users[$userfrom->id])) {
692 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
696 // Make sure groups allow this user to see this email.
697 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
698 // Groups are being used.
699 if (!groups_group_exists($discussion->groupid)) {
700 // Can't find group - be safe and don't this message.
701 continue;
704 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
705 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
706 continue;
710 // Make sure we're allowed to see the post.
711 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
712 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
713 continue;
716 // OK so we need to send the email.
718 // Does the user want this post in a digest? If so postpone it for now.
719 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
721 if ($maildigest > 0) {
722 // This user wants the mails to be in digest form.
723 $queue = new stdClass();
724 $queue->userid = $userto->id;
725 $queue->discussionid = $discussion->id;
726 $queue->postid = $post->id;
727 $queue->timemodified = $post->created;
728 $DB->insert_record('forum_queue', $queue);
729 continue;
732 // Prepare to actually send the post now, and build up the content.
734 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
736 $userfrom->customheaders = array (
737 // Headers to make emails easier to track.
738 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id . '@' . $hostname.'>',
739 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
740 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id, $hostname),
741 'X-Course-Id: ' . $course->id,
742 'X-Course-Name: ' . format_string($course->fullname, true),
744 // Headers to help prevent auto-responders.
745 'Precedence: Bulk',
746 'X-Auto-Response-Suppress: All',
747 'Auto-Submitted: auto-generated',
750 if ($post->parent) {
751 // This post is a reply, so add headers for threading (see MDL-22551).
752 $userfrom->customheaders[] = 'In-Reply-To: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
753 $userfrom->customheaders[] = 'References: ' . forum_get_email_message_id($post->parent, $userto->id, $hostname);
756 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
758 // Generate a reply-to address from using the Inbound Message handler.
759 $replyaddress = null;
760 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
761 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
762 $replyaddress = $messageinboundgenerator->generate($userto->id);
765 $a = new stdClass();
766 $a->courseshortname = $shortname;
767 $a->forumname = $cleanforumname;
768 $a->subject = format_string($post->subject, true);
769 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
770 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false,
771 $replyaddress);
772 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
773 $replyaddress);
775 // Send the post now!
776 mtrace('Sending ', '');
778 $eventdata = new \core\message\message();
779 $eventdata->component = 'mod_forum';
780 $eventdata->name = 'posts';
781 $eventdata->userfrom = $userfrom;
782 $eventdata->userto = $userto;
783 $eventdata->subject = $postsubject;
784 $eventdata->fullmessage = $posttext;
785 $eventdata->fullmessageformat = FORMAT_PLAIN;
786 $eventdata->fullmessagehtml = $posthtml;
787 $eventdata->notification = 1;
788 $eventdata->replyto = $replyaddress;
789 if (!empty($replyaddress)) {
790 // Add extra text to email messages if they can reply back.
791 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
792 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
793 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
794 'fullmessagehtml' => array('footer' => $htmlfooter));
795 $eventdata->set_additional_content('email', $additionalcontent);
798 // If forum_replytouser is not set then send mail using the noreplyaddress.
799 if (empty($CFG->forum_replytouser)) {
800 $eventdata->userfrom = core_user::get_noreply_user();
803 $smallmessagestrings = new stdClass();
804 $smallmessagestrings->user = fullname($userfrom);
805 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
806 $smallmessagestrings->message = $post->message;
808 // Make sure strings are in message recipients language.
809 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
811 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
812 $eventdata->contexturl = $contexturl->out();
813 $eventdata->contexturlname = $discussion->name;
815 $mailresult = message_send($eventdata);
816 if (!$mailresult) {
817 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
818 " ($userto->email) .. not trying again.");
819 $errorcount[$post->id]++;
820 } else {
821 $mailcount[$post->id]++;
823 // Mark post as read if forum_usermarksread is set off.
824 if (!$CFG->forum_usermarksread) {
825 $userto->markposts[$post->id] = $post->id;
829 mtrace('post ' . $post->id . ': ' . $post->subject);
832 // Mark processed posts as read.
833 forum_tp_mark_posts_read($userto, $userto->markposts);
834 unset($userto);
838 if ($posts) {
839 foreach ($posts as $post) {
840 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
841 if ($errorcount[$post->id]) {
842 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
847 // release some memory
848 unset($subscribedusers);
849 unset($mailcount);
850 unset($errorcount);
852 cron_setup_user();
854 $sitetimezone = core_date::get_server_timezone();
856 // Now see if there are any digest mails waiting to be sent, and if we should send them
858 mtrace('Starting digest processing...');
860 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
862 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
863 set_config('digestmailtimelast', 0);
866 $timenow = time();
867 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
869 // Delete any really old ones (normally there shouldn't be any)
870 $weekago = $timenow - (7 * 24 * 3600);
871 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
872 mtrace ('Cleaned old digest records');
874 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
876 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
878 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
880 if ($digestposts_rs->valid()) {
882 // We have work to do
883 $usermailcount = 0;
885 //caches - reuse the those filled before too
886 $discussionposts = array();
887 $userdiscussions = array();
889 foreach ($digestposts_rs as $digestpost) {
890 if (!isset($posts[$digestpost->postid])) {
891 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
892 $posts[$digestpost->postid] = $post;
893 } else {
894 continue;
897 $discussionid = $digestpost->discussionid;
898 if (!isset($discussions[$discussionid])) {
899 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
900 $discussions[$discussionid] = $discussion;
901 } else {
902 continue;
905 $forumid = $discussions[$discussionid]->forum;
906 if (!isset($forums[$forumid])) {
907 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
908 $forums[$forumid] = $forum;
909 } else {
910 continue;
914 $courseid = $forums[$forumid]->course;
915 if (!isset($courses[$courseid])) {
916 if ($course = $DB->get_record('course', array('id' => $courseid))) {
917 $courses[$courseid] = $course;
918 } else {
919 continue;
923 if (!isset($coursemodules[$forumid])) {
924 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
925 $coursemodules[$forumid] = $cm;
926 } else {
927 continue;
930 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
931 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
933 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
935 // Data collected, start sending out emails to each user
936 foreach ($userdiscussions as $userid => $thesediscussions) {
938 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
940 cron_setup_user();
942 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
944 // First of all delete all the queue entries for this user
945 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
947 // Init user caches - we keep the cache for one cycle only,
948 // otherwise it would unnecessarily consume memory.
949 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
950 $userto = clone($users[$userid]);
951 } else {
952 $userto = $DB->get_record('user', array('id' => $userid));
953 forum_cron_minimise_user_record($userto);
955 $userto->viewfullnames = array();
956 $userto->canpost = array();
957 $userto->markposts = array();
959 // Override the language and timezone of the "current" user, so that
960 // mail is customised for the receiver.
961 cron_setup_user($userto);
963 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
965 $headerdata = new stdClass();
966 $headerdata->sitename = format_string($site->fullname, true);
967 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&amp;course='.$site->id;
969 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
970 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
972 $posthtml = "<head>";
973 /* foreach ($CFG->stylesheets as $stylesheet) {
974 //TODO: MDL-21120
975 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
977 $posthtml .= "</head>\n<body id=\"email\">\n";
978 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
980 foreach ($thesediscussions as $discussionid) {
982 core_php_time_limit::raise(120); // to be reset for each post
984 $discussion = $discussions[$discussionid];
985 $forum = $forums[$discussion->forum];
986 $course = $courses[$forum->course];
987 $cm = $coursemodules[$forum->id];
989 //override language
990 cron_setup_user($userto, $course);
992 // Fill caches
993 if (!isset($userto->viewfullnames[$forum->id])) {
994 $modcontext = context_module::instance($cm->id);
995 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
997 if (!isset($userto->canpost[$discussion->id])) {
998 $modcontext = context_module::instance($cm->id);
999 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1002 $strforums = get_string('forums', 'forum');
1003 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1004 $canreply = $userto->canpost[$discussion->id];
1005 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1007 $posttext .= "\n \n";
1008 $posttext .= '=====================================================================';
1009 $posttext .= "\n \n";
1010 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1011 if ($discussion->name != $forum->name) {
1012 $posttext .= " -> ".format_string($discussion->name,true);
1014 $posttext .= "\n";
1015 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1016 $posttext .= "\n";
1018 $posthtml .= "<p><font face=\"sans-serif\">".
1019 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1020 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1021 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
1022 if ($discussion->name == $forum->name) {
1023 $posthtml .= "</font></p>";
1024 } else {
1025 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
1027 $posthtml .= '<p>';
1029 $postsarray = $discussionposts[$discussionid];
1030 sort($postsarray);
1032 foreach ($postsarray as $postid) {
1033 $post = $posts[$postid];
1035 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1036 $userfrom = $users[$post->userid];
1037 if (!isset($userfrom->idnumber)) {
1038 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1039 forum_cron_minimise_user_record($userfrom);
1042 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
1043 forum_cron_minimise_user_record($userfrom);
1044 if ($userscount <= FORUM_CRON_USER_CACHE) {
1045 $userscount++;
1046 $users[$userfrom->id] = $userfrom;
1049 } else {
1050 mtrace('Could not find user '.$post->userid);
1051 continue;
1054 if (!isset($userfrom->groups[$forum->id])) {
1055 if (!isset($userfrom->groups)) {
1056 $userfrom->groups = array();
1057 if (isset($users[$userfrom->id])) {
1058 $users[$userfrom->id]->groups = array();
1061 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
1062 if (isset($users[$userfrom->id])) {
1063 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1067 // Headers to help prevent auto-responders.
1068 $userfrom->customheaders = array(
1069 "Precedence: Bulk",
1070 'X-Auto-Response-Suppress: All',
1071 'Auto-Submitted: auto-generated',
1074 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1075 if ($maildigest == 2) {
1076 // Subjects and link only
1077 $posttext .= "\n";
1078 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1079 $by = new stdClass();
1080 $by->name = fullname($userfrom);
1081 $by->date = userdate($post->modified);
1082 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
1083 $posttext .= "\n---------------------------------------------------------------------";
1085 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&amp;course=$course->id\">$by->name</a>";
1086 $posthtml .= '<div><a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'#p'.$post->id.'">'.format_string($post->subject,true).'</a> '.get_string("bynameondate", "forum", $by).'</div>';
1088 } else {
1089 // The full treatment
1090 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
1091 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1093 // Create an array of postid's for this user to mark as read.
1094 if (!$CFG->forum_usermarksread) {
1095 $userto->markposts[$post->id] = $post->id;
1099 $footerlinks = array();
1100 if ($canunsubscribe) {
1101 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1102 } else {
1103 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1105 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1106 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode('&nbsp;', $footerlinks) . '</font></div>';
1107 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1109 $posthtml .= '</body>';
1111 if (empty($userto->mailformat) || $userto->mailformat != 1) {
1112 // This user DOESN'T want to receive HTML
1113 $posthtml = '';
1116 $attachment = $attachname='';
1117 // Directly email forum digests rather than sending them via messaging, use the
1118 // site shortname as 'from name', the noreply address will be used by email_to_user.
1119 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);
1121 if (!$mailresult) {
1122 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1123 "($userto->email)... not trying again.");
1124 } else {
1125 mtrace("success.");
1126 $usermailcount++;
1128 // Mark post as read if forum_usermarksread is set off
1129 forum_tp_mark_posts_read($userto, $userto->markposts);
1133 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1134 set_config('digestmailtimelast', $timenow);
1137 cron_setup_user();
1139 if (!empty($usermailcount)) {
1140 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1143 if (!empty($CFG->forum_lastreadclean)) {
1144 $timenow = time();
1145 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1146 set_config('forum_lastreadclean', $timenow);
1147 mtrace('Removing old forum read tracking info...');
1148 forum_tp_clean_read_records();
1150 } else {
1151 set_config('forum_lastreadclean', time());
1154 return true;
1158 * Builds and returns the body of the email notification in plain text.
1160 * @global object
1161 * @global object
1162 * @uses CONTEXT_MODULE
1163 * @param object $course
1164 * @param object $cm
1165 * @param object $forum
1166 * @param object $discussion
1167 * @param object $post
1168 * @param object $userfrom
1169 * @param object $userto
1170 * @param boolean $bare
1171 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1172 * @return string The email body in plain text format.
1174 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false, $replyaddress = null) {
1175 global $CFG, $USER;
1177 $modcontext = context_module::instance($cm->id);
1179 if (!isset($userto->viewfullnames[$forum->id])) {
1180 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1181 } else {
1182 $viewfullnames = $userto->viewfullnames[$forum->id];
1185 if (!isset($userto->canpost[$discussion->id])) {
1186 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1187 } else {
1188 $canreply = $userto->canpost[$discussion->id];
1191 $by = New stdClass;
1192 $by->name = fullname($userfrom, $viewfullnames);
1193 $by->date = userdate($post->modified, "", core_date::get_user_timezone($userto));
1195 $strbynameondate = get_string('bynameondate', 'forum', $by);
1197 $strforums = get_string('forums', 'forum');
1199 $canunsubscribe = !\mod_forum\subscriptions::is_forcesubscribed($forum);
1201 $posttext = '';
1203 if (!$bare) {
1204 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1205 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
1207 if ($discussion->name != $forum->name) {
1208 $posttext .= " -> ".format_string($discussion->name,true);
1212 // add absolute file links
1213 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1215 $posttext .= "\n";
1216 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1217 $posttext .= format_string($post->subject,true);
1218 if ($bare) {
1219 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1221 $posttext .= "\n".$strbynameondate."\n";
1222 $posttext .= "---------------------------------------------------------------------\n";
1223 $posttext .= format_text_email($post->message, $post->messageformat);
1224 $posttext .= "\n\n";
1225 $posttext .= forum_print_attachments($post, $cm, "text");
1226 $posttext .= "\n---------------------------------------------------------------------\n";
1228 if (!$bare) {
1229 if ($canreply) {
1230 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1231 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1234 if ($canunsubscribe) {
1235 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1236 // If subscribed to this forum, offer the unsubscribe link.
1237 $posttext .= get_string("unsubscribe", "forum");
1238 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1240 // Always offer the unsubscribe from discussion link.
1241 $posttext .= get_string("unsubscribediscussion", "forum");
1242 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id&d=$discussion->id\n";
1246 $posttext .= get_string("digestmailpost", "forum");
1247 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1249 return $posttext;
1253 * Builds and returns the body of the email notification in html format.
1255 * @global object
1256 * @param object $course
1257 * @param object $cm
1258 * @param object $forum
1259 * @param object $discussion
1260 * @param object $post
1261 * @param object $userfrom
1262 * @param object $userto
1263 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1264 * @return string The email text in HTML format
1266 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $replyaddress = null) {
1267 global $CFG;
1269 if ($userto->mailformat != 1) { // Needs to be HTML
1270 return '';
1273 if (!isset($userto->canpost[$discussion->id])) {
1274 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1275 } else {
1276 $canreply = $userto->canpost[$discussion->id];
1279 $strforums = get_string('forums', 'forum');
1280 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1281 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1283 $posthtml = '<head>';
1284 /* foreach ($CFG->stylesheets as $stylesheet) {
1285 //TODO: MDL-21120
1286 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1288 $posthtml .= '</head>';
1289 $posthtml .= "\n<body id=\"email\">\n\n";
1291 $posthtml .= '<div class="navbar">'.
1292 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$shortname.'</a> &raquo; '.
1293 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> &raquo; '.
1294 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1295 if ($discussion->name == $forum->name) {
1296 $posthtml .= '</div>';
1297 } else {
1298 $posthtml .= ' &raquo; <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1299 format_string($discussion->name,true).'</a></div>';
1301 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1303 $footerlinks = array();
1304 if ($canunsubscribe) {
1305 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1306 // If subscribed to this forum, offer the unsubscribe link.
1307 $unsublink = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id));
1308 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribe', 'mod_forum'));
1310 // Always offer the unsubscribe from discussion link.
1311 $unsublink = new moodle_url('/mod/forum/subscribe.php', array(
1312 'id' => $forum->id,
1313 'd' => $discussion->id,
1315 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribediscussion', 'mod_forum'));
1317 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
1319 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1320 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode('&nbsp;', $footerlinks) . '</div>';
1322 $posthtml .= '</body>';
1324 return $posthtml;
1330 * @param object $course
1331 * @param object $user
1332 * @param object $mod TODO this is not used in this function, refactor
1333 * @param object $forum
1334 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1336 function forum_user_outline($course, $user, $mod, $forum) {
1337 global $CFG;
1338 require_once("$CFG->libdir/gradelib.php");
1339 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1340 if (empty($grades->items[0]->grades)) {
1341 $grade = false;
1342 } else {
1343 $grade = reset($grades->items[0]->grades);
1346 $count = forum_count_user_posts($forum->id, $user->id);
1348 if ($count && $count->postcount > 0) {
1349 $result = new stdClass();
1350 $result->info = get_string("numposts", "forum", $count->postcount);
1351 $result->time = $count->lastpost;
1352 if ($grade) {
1353 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1355 return $result;
1356 } else if ($grade) {
1357 $result = new stdClass();
1358 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1360 //datesubmitted == time created. dategraded == time modified or time overridden
1361 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1362 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1363 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1364 $result->time = $grade->dategraded;
1365 } else {
1366 $result->time = $grade->datesubmitted;
1369 return $result;
1371 return NULL;
1376 * @global object
1377 * @global object
1378 * @param object $coure
1379 * @param object $user
1380 * @param object $mod
1381 * @param object $forum
1383 function forum_user_complete($course, $user, $mod, $forum) {
1384 global $CFG,$USER, $OUTPUT;
1385 require_once("$CFG->libdir/gradelib.php");
1387 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1388 if (!empty($grades->items[0]->grades)) {
1389 $grade = reset($grades->items[0]->grades);
1390 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1391 if ($grade->str_feedback) {
1392 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1396 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1398 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1399 print_error('invalidcoursemodule');
1401 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1403 foreach ($posts as $post) {
1404 if (!isset($discussions[$post->discussion])) {
1405 continue;
1407 $discussion = $discussions[$post->discussion];
1409 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1411 } else {
1412 echo "<p>".get_string("noposts", "forum")."</p>";
1417 * Filters the forum discussions according to groups membership and config.
1419 * @since Moodle 2.8, 2.7.1, 2.6.4
1420 * @param array $discussions Discussions with new posts array
1421 * @return array Forums with the number of new posts
1423 function forum_filter_user_groups_discussions($discussions) {
1425 // Group the remaining discussions posts by their forumid.
1426 $filteredforums = array();
1428 // Discard not visible groups.
1429 foreach ($discussions as $discussion) {
1431 // Course data is already cached.
1432 $instances = get_fast_modinfo($discussion->course)->get_instances();
1433 $forum = $instances['forum'][$discussion->forum];
1435 // Continue if the user should not see this discussion.
1436 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1437 continue;
1440 // Grouping results by forum.
1441 if (empty($filteredforums[$forum->instance])) {
1442 $filteredforums[$forum->instance] = new stdClass();
1443 $filteredforums[$forum->instance]->id = $forum->id;
1444 $filteredforums[$forum->instance]->count = 0;
1446 $filteredforums[$forum->instance]->count += $discussion->count;
1450 return $filteredforums;
1454 * Returns whether the discussion group is visible by the current user or not.
1456 * @since Moodle 2.8, 2.7.1, 2.6.4
1457 * @param cm_info $cm The discussion course module
1458 * @param int $discussiongroupid The discussion groupid
1459 * @return bool
1461 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1463 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1464 return true;
1467 if (isguestuser()) {
1468 return false;
1471 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1472 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1473 return true;
1476 return false;
1480 * @global object
1481 * @global object
1482 * @global object
1483 * @param array $courses
1484 * @param array $htmlarray
1486 function forum_print_overview($courses,&$htmlarray) {
1487 global $USER, $CFG, $DB, $SESSION;
1489 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1490 return array();
1493 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1494 return;
1497 // Courses to search for new posts
1498 $coursessqls = array();
1499 $params = array();
1500 foreach ($courses as $course) {
1502 // If the user has never entered into the course all posts are pending
1503 if ($course->lastaccess == 0) {
1504 $coursessqls[] = '(d.course = ?)';
1505 $params[] = $course->id;
1507 // Only posts created after the course last access
1508 } else {
1509 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1510 $params[] = $course->id;
1511 $params[] = $course->lastaccess;
1514 $params[] = $USER->id;
1515 $coursessql = implode(' OR ', $coursessqls);
1517 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1518 .'FROM {forum_discussions} d '
1519 .'JOIN {forum_posts} p ON p.discussion = d.id '
1520 ."WHERE ($coursessql) "
1521 .'AND p.userid != ? '
1522 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1523 .'ORDER BY d.course, d.forum';
1525 // Avoid warnings.
1526 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1527 $discussions = array();
1530 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1532 // also get all forum tracking stuff ONCE.
1533 $trackingforums = array();
1534 foreach ($forums as $forum) {
1535 if (forum_tp_can_track_forums($forum)) {
1536 $trackingforums[$forum->id] = $forum;
1540 if (count($trackingforums) > 0) {
1541 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1542 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1543 ' FROM {forum_posts} p '.
1544 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1545 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1546 $params = array($USER->id);
1548 foreach ($trackingforums as $track) {
1549 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1550 $params[] = $track->id;
1551 if (isset($SESSION->currentgroup[$track->course])) {
1552 $groupid = $SESSION->currentgroup[$track->course];
1553 } else {
1554 // get first groupid
1555 $groupids = groups_get_all_groups($track->course, $USER->id);
1556 if ($groupids) {
1557 reset($groupids);
1558 $groupid = key($groupids);
1559 $SESSION->currentgroup[$track->course] = $groupid;
1560 } else {
1561 $groupid = 0;
1563 unset($groupids);
1565 $params[] = $groupid;
1567 $sql = substr($sql,0,-3); // take off the last OR
1568 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1569 $params[] = $cutoffdate;
1571 if (!$unread = $DB->get_records_sql($sql, $params)) {
1572 $unread = array();
1574 } else {
1575 $unread = array();
1578 if (empty($unread) and empty($forumsnewposts)) {
1579 return;
1582 $strforum = get_string('modulename','forum');
1584 foreach ($forums as $forum) {
1585 $str = '';
1586 $count = 0;
1587 $thisunread = 0;
1588 $showunread = false;
1589 // either we have something from logs, or trackposts, or nothing.
1590 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1591 $count = $forumsnewposts[$forum->id]->count;
1593 if (array_key_exists($forum->id,$unread)) {
1594 $thisunread = $unread[$forum->id]->count;
1595 $showunread = true;
1597 if ($count > 0 || $thisunread > 0) {
1598 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1599 $forum->name.'</a></div>';
1600 $str .= '<div class="info"><span class="postsincelogin">';
1601 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1602 if (!empty($showunread)) {
1603 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1605 $str .= '</div></div>';
1607 if (!empty($str)) {
1608 if (!array_key_exists($forum->course,$htmlarray)) {
1609 $htmlarray[$forum->course] = array();
1611 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1612 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1614 $htmlarray[$forum->course]['forum'] .= $str;
1620 * Given a course and a date, prints a summary of all the new
1621 * messages posted in the course since that date
1623 * @global object
1624 * @global object
1625 * @global object
1626 * @uses CONTEXT_MODULE
1627 * @uses VISIBLEGROUPS
1628 * @param object $course
1629 * @param bool $viewfullnames capability
1630 * @param int $timestart
1631 * @return bool success
1633 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1634 global $CFG, $USER, $DB, $OUTPUT;
1636 // do not use log table if possible, it may be huge and is expensive to join with other tables
1638 $allnamefields = user_picture::fields('u', null, 'duserid');
1639 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1640 d.timestart, d.timeend, $allnamefields
1641 FROM {forum_posts} p
1642 JOIN {forum_discussions} d ON d.id = p.discussion
1643 JOIN {forum} f ON f.id = d.forum
1644 JOIN {user} u ON u.id = p.userid
1645 WHERE p.created > ? AND f.course = ?
1646 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1647 return false;
1650 $modinfo = get_fast_modinfo($course);
1652 $groupmodes = array();
1653 $cms = array();
1655 $strftimerecent = get_string('strftimerecent');
1657 $printposts = array();
1658 foreach ($posts as $post) {
1659 if (!isset($modinfo->instances['forum'][$post->forum])) {
1660 // not visible
1661 continue;
1663 $cm = $modinfo->instances['forum'][$post->forum];
1664 if (!$cm->uservisible) {
1665 continue;
1667 $context = context_module::instance($cm->id);
1669 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1670 continue;
1673 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1674 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1675 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1676 continue;
1680 // Check that the user can see the discussion.
1681 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1682 $printposts[] = $post;
1686 unset($posts);
1688 if (!$printposts) {
1689 return false;
1692 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1693 echo "\n<ul class='unlist'>\n";
1695 foreach ($printposts as $post) {
1696 $subjectclass = empty($post->parent) ? ' bold' : '';
1698 echo '<li><div class="head">'.
1699 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1700 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1701 '</div>';
1702 echo '<div class="info'.$subjectclass.'">';
1703 if (empty($post->parent)) {
1704 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1705 } else {
1706 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&amp;parent='.$post->parent.'#p'.$post->id.'">';
1708 $post->subject = break_up_long_words(format_string($post->subject, true));
1709 echo $post->subject;
1710 echo "</a>\"</div></li>\n";
1713 echo "</ul>\n";
1715 return true;
1719 * Return grade for given user or all users.
1721 * @global object
1722 * @global object
1723 * @param object $forum
1724 * @param int $userid optional user id, 0 means all users
1725 * @return array array of grades, false if none
1727 function forum_get_user_grades($forum, $userid = 0) {
1728 global $CFG;
1730 require_once($CFG->dirroot.'/rating/lib.php');
1732 $ratingoptions = new stdClass;
1733 $ratingoptions->component = 'mod_forum';
1734 $ratingoptions->ratingarea = 'post';
1736 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1737 $ratingoptions->modulename = 'forum';
1738 $ratingoptions->moduleid = $forum->id;
1739 $ratingoptions->userid = $userid;
1740 $ratingoptions->aggregationmethod = $forum->assessed;
1741 $ratingoptions->scaleid = $forum->scale;
1742 $ratingoptions->itemtable = 'forum_posts';
1743 $ratingoptions->itemtableusercolumn = 'userid';
1745 $rm = new rating_manager();
1746 return $rm->get_user_grades($ratingoptions);
1750 * Update activity grades
1752 * @category grade
1753 * @param object $forum
1754 * @param int $userid specific user only, 0 means all
1755 * @param boolean $nullifnone return null if grade does not exist
1756 * @return void
1758 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1759 global $CFG, $DB;
1760 require_once($CFG->libdir.'/gradelib.php');
1762 if (!$forum->assessed) {
1763 forum_grade_item_update($forum);
1765 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1766 forum_grade_item_update($forum, $grades);
1768 } else if ($userid and $nullifnone) {
1769 $grade = new stdClass();
1770 $grade->userid = $userid;
1771 $grade->rawgrade = NULL;
1772 forum_grade_item_update($forum, $grade);
1774 } else {
1775 forum_grade_item_update($forum);
1780 * Create/update grade item for given forum
1782 * @category grade
1783 * @uses GRADE_TYPE_NONE
1784 * @uses GRADE_TYPE_VALUE
1785 * @uses GRADE_TYPE_SCALE
1786 * @param stdClass $forum Forum object with extra cmidnumber
1787 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1788 * @return int 0 if ok
1790 function forum_grade_item_update($forum, $grades=NULL) {
1791 global $CFG;
1792 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1793 require_once($CFG->libdir.'/gradelib.php');
1796 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1798 if (!$forum->assessed or $forum->scale == 0) {
1799 $params['gradetype'] = GRADE_TYPE_NONE;
1801 } else if ($forum->scale > 0) {
1802 $params['gradetype'] = GRADE_TYPE_VALUE;
1803 $params['grademax'] = $forum->scale;
1804 $params['grademin'] = 0;
1806 } else if ($forum->scale < 0) {
1807 $params['gradetype'] = GRADE_TYPE_SCALE;
1808 $params['scaleid'] = -$forum->scale;
1811 if ($grades === 'reset') {
1812 $params['reset'] = true;
1813 $grades = NULL;
1816 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1820 * Delete grade item for given forum
1822 * @category grade
1823 * @param stdClass $forum Forum object
1824 * @return grade_item
1826 function forum_grade_item_delete($forum) {
1827 global $CFG;
1828 require_once($CFG->libdir.'/gradelib.php');
1830 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1835 * This function returns if a scale is being used by one forum
1837 * @global object
1838 * @param int $forumid
1839 * @param int $scaleid negative number
1840 * @return bool
1842 function forum_scale_used ($forumid,$scaleid) {
1843 global $DB;
1844 $return = false;
1846 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1848 if (!empty($rec) && !empty($scaleid)) {
1849 $return = true;
1852 return $return;
1856 * Checks if scale is being used by any instance of forum
1858 * This is used to find out if scale used anywhere
1860 * @global object
1861 * @param $scaleid int
1862 * @return boolean True if the scale is used by any forum
1864 function forum_scale_used_anywhere($scaleid) {
1865 global $DB;
1866 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1867 return true;
1868 } else {
1869 return false;
1873 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1876 * Gets a post with all info ready for forum_print_post
1877 * Most of these joins are just to get the forum id
1879 * @global object
1880 * @global object
1881 * @param int $postid
1882 * @return mixed array of posts or false
1884 function forum_get_post_full($postid) {
1885 global $CFG, $DB;
1887 $allnames = get_all_user_name_fields(true, 'u');
1888 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1889 FROM {forum_posts} p
1890 JOIN {forum_discussions} d ON p.discussion = d.id
1891 LEFT JOIN {user} u ON p.userid = u.id
1892 WHERE p.id = ?", array($postid));
1896 * Gets all posts in discussion including top parent.
1898 * @global object
1899 * @global object
1900 * @global object
1901 * @param int $discussionid
1902 * @param string $sort
1903 * @param bool $tracking does user track the forum?
1904 * @return array of posts
1906 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1907 global $CFG, $DB, $USER;
1909 $tr_sel = "";
1910 $tr_join = "";
1911 $params = array();
1913 if ($tracking) {
1914 $now = time();
1915 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1916 $tr_sel = ", fr.id AS postread";
1917 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1918 $params[] = $USER->id;
1921 $allnames = get_all_user_name_fields(true, 'u');
1922 $params[] = $discussionid;
1923 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1924 FROM {forum_posts} p
1925 LEFT JOIN {user} u ON p.userid = u.id
1926 $tr_join
1927 WHERE p.discussion = ?
1928 ORDER BY $sort", $params)) {
1929 return array();
1932 foreach ($posts as $pid=>$p) {
1933 if ($tracking) {
1934 if (forum_tp_is_post_old($p)) {
1935 $posts[$pid]->postread = true;
1938 if (!$p->parent) {
1939 continue;
1941 if (!isset($posts[$p->parent])) {
1942 continue; // parent does not exist??
1944 if (!isset($posts[$p->parent]->children)) {
1945 $posts[$p->parent]->children = array();
1947 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1950 // Start with the last child of the first post.
1951 $post = &$posts[reset($posts)->id];
1953 $lastpost = false;
1954 while (!$lastpost) {
1955 if (!isset($post->children)) {
1956 $post->lastpost = true;
1957 $lastpost = true;
1958 } else {
1959 // Go to the last child of this post.
1960 $post = &$posts[end($post->children)->id];
1964 return $posts;
1968 * An array of forum objects that the user is allowed to read/search through.
1970 * @global object
1971 * @global object
1972 * @global object
1973 * @param int $userid
1974 * @param int $courseid if 0, we look for forums throughout the whole site.
1975 * @return array of forum objects, or false if no matches
1976 * Forum objects have the following attributes:
1977 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1978 * viewhiddentimedposts
1980 function forum_get_readable_forums($userid, $courseid=0) {
1982 global $CFG, $DB, $USER;
1983 require_once($CFG->dirroot.'/course/lib.php');
1985 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1986 print_error('notinstalled', 'forum');
1989 if ($courseid) {
1990 $courses = $DB->get_records('course', array('id' => $courseid));
1991 } else {
1992 // If no course is specified, then the user can see SITE + his courses.
1993 $courses1 = $DB->get_records('course', array('id' => SITEID));
1994 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1995 $courses = array_merge($courses1, $courses2);
1997 if (!$courses) {
1998 return array();
2001 $readableforums = array();
2003 foreach ($courses as $course) {
2005 $modinfo = get_fast_modinfo($course);
2007 if (empty($modinfo->instances['forum'])) {
2008 // hmm, no forums?
2009 continue;
2012 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2014 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
2015 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
2016 continue;
2018 $context = context_module::instance($cm->id);
2019 $forum = $courseforums[$forumid];
2020 $forum->context = $context;
2021 $forum->cm = $cm;
2023 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2024 continue;
2027 /// group access
2028 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2030 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
2031 $forum->onlygroups[] = -1;
2034 /// hidden timed discussions
2035 $forum->viewhiddentimedposts = true;
2036 if (!empty($CFG->forum_enabletimedposts)) {
2037 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
2038 $forum->viewhiddentimedposts = false;
2042 /// qanda access
2043 if ($forum->type == 'qanda'
2044 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2046 // We need to check whether the user has posted in the qanda forum.
2047 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
2048 // the user is allowed to see in this forum.
2049 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
2050 foreach ($discussionspostedin as $d) {
2051 $forum->onlydiscussions[] = $d->id;
2056 $readableforums[$forum->id] = $forum;
2059 unset($modinfo);
2061 } // End foreach $courses
2063 return $readableforums;
2067 * Returns a list of posts found using an array of search terms.
2069 * @global object
2070 * @global object
2071 * @global object
2072 * @param array $searchterms array of search terms, e.g. word +word -word
2073 * @param int $courseid if 0, we search through the whole site
2074 * @param int $limitfrom
2075 * @param int $limitnum
2076 * @param int &$totalcount
2077 * @param string $extrasql
2078 * @return array|bool Array of posts found or false
2080 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2081 &$totalcount, $extrasql='') {
2082 global $CFG, $DB, $USER;
2083 require_once($CFG->libdir.'/searchlib.php');
2085 $forums = forum_get_readable_forums($USER->id, $courseid);
2087 if (count($forums) == 0) {
2088 $totalcount = 0;
2089 return false;
2092 $now = round(time(), -2); // db friendly
2094 $fullaccess = array();
2095 $where = array();
2096 $params = array();
2098 foreach ($forums as $forumid => $forum) {
2099 $select = array();
2101 if (!$forum->viewhiddentimedposts) {
2102 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2103 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2106 $cm = $forum->cm;
2107 $context = $forum->context;
2109 if ($forum->type == 'qanda'
2110 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2111 if (!empty($forum->onlydiscussions)) {
2112 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2113 $params = array_merge($params, $discussionid_params);
2114 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2115 } else {
2116 $select[] = "p.parent = 0";
2120 if (!empty($forum->onlygroups)) {
2121 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2122 $params = array_merge($params, $groupid_params);
2123 $select[] = "d.groupid $groupid_sql";
2126 if ($select) {
2127 $selects = implode(" AND ", $select);
2128 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2129 $params['forum'.$forumid] = $forumid;
2130 } else {
2131 $fullaccess[] = $forumid;
2135 if ($fullaccess) {
2136 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2137 $params = array_merge($params, $fullid_params);
2138 $where[] = "(d.forum $fullid_sql)";
2141 $selectdiscussion = "(".implode(" OR ", $where).")";
2143 $messagesearch = '';
2144 $searchstring = '';
2146 // Need to concat these back together for parser to work.
2147 foreach($searchterms as $searchterm){
2148 if ($searchstring != '') {
2149 $searchstring .= ' ';
2151 $searchstring .= $searchterm;
2154 // We need to allow quoted strings for the search. The quotes *should* be stripped
2155 // by the parser, but this should be examined carefully for security implications.
2156 $searchstring = str_replace("\\\"","\"",$searchstring);
2157 $parser = new search_parser();
2158 $lexer = new search_lexer($parser);
2160 if ($lexer->parse($searchstring)) {
2161 $parsearray = $parser->get_parsed_array();
2162 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2163 'p.userid', 'u.id', 'u.firstname',
2164 'u.lastname', 'p.modified', 'd.forum');
2165 $params = array_merge($params, $msparams);
2168 $fromsql = "{forum_posts} p,
2169 {forum_discussions} d,
2170 {user} u";
2172 $selectsql = " $messagesearch
2173 AND p.discussion = d.id
2174 AND p.userid = u.id
2175 AND $selectdiscussion
2176 $extrasql";
2178 $countsql = "SELECT COUNT(*)
2179 FROM $fromsql
2180 WHERE $selectsql";
2182 $allnames = get_all_user_name_fields(true, 'u');
2183 $searchsql = "SELECT p.*,
2184 d.forum,
2185 $allnames,
2186 u.email,
2187 u.picture,
2188 u.imagealt
2189 FROM $fromsql
2190 WHERE $selectsql
2191 ORDER BY p.modified DESC";
2193 $totalcount = $DB->count_records_sql($countsql, $params);
2195 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2199 * Returns a list of all new posts that have not been mailed yet
2201 * @param int $starttime posts created after this time
2202 * @param int $endtime posts created before this
2203 * @param int $now used for timed discussions only
2204 * @return array
2206 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2207 global $CFG, $DB;
2209 $params = array();
2210 $params['mailed'] = FORUM_MAILED_PENDING;
2211 $params['ptimestart'] = $starttime;
2212 $params['ptimeend'] = $endtime;
2213 $params['mailnow'] = 1;
2215 if (!empty($CFG->forum_enabletimedposts)) {
2216 if (empty($now)) {
2217 $now = time();
2219 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2220 $params['dtimestart'] = $now;
2221 $params['dtimeend'] = $now;
2222 } else {
2223 $timedsql = "";
2226 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2227 FROM {forum_posts} p
2228 JOIN {forum_discussions} d ON d.id = p.discussion
2229 WHERE p.mailed = :mailed
2230 AND p.created >= :ptimestart
2231 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2232 $timedsql
2233 ORDER BY p.modified ASC", $params);
2237 * Marks posts before a certain time as being mailed already
2239 * @global object
2240 * @global object
2241 * @param int $endtime
2242 * @param int $now Defaults to time()
2243 * @return bool
2245 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2246 global $CFG, $DB;
2248 if (empty($now)) {
2249 $now = time();
2252 $params = array();
2253 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2254 $params['now'] = $now;
2255 $params['endtime'] = $endtime;
2256 $params['mailnow'] = 1;
2257 $params['mailedpending'] = FORUM_MAILED_PENDING;
2259 if (empty($CFG->forum_enabletimedposts)) {
2260 return $DB->execute("UPDATE {forum_posts}
2261 SET mailed = :mailedsuccess
2262 WHERE (created < :endtime OR mailnow = :mailnow)
2263 AND mailed = :mailedpending", $params);
2264 } else {
2265 return $DB->execute("UPDATE {forum_posts}
2266 SET mailed = :mailedsuccess
2267 WHERE discussion NOT IN (SELECT d.id
2268 FROM {forum_discussions} d
2269 WHERE d.timestart > :now)
2270 AND (created < :endtime OR mailnow = :mailnow)
2271 AND mailed = :mailedpending", $params);
2276 * Get all the posts for a user in a forum suitable for forum_print_post
2278 * @global object
2279 * @global object
2280 * @uses CONTEXT_MODULE
2281 * @return array
2283 function forum_get_user_posts($forumid, $userid) {
2284 global $CFG, $DB;
2286 $timedsql = "";
2287 $params = array($forumid, $userid);
2289 if (!empty($CFG->forum_enabletimedposts)) {
2290 $cm = get_coursemodule_from_instance('forum', $forumid);
2291 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2292 $now = time();
2293 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2294 $params[] = $now;
2295 $params[] = $now;
2299 $allnames = get_all_user_name_fields(true, 'u');
2300 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2301 FROM {forum} f
2302 JOIN {forum_discussions} d ON d.forum = f.id
2303 JOIN {forum_posts} p ON p.discussion = d.id
2304 JOIN {user} u ON u.id = p.userid
2305 WHERE f.id = ?
2306 AND p.userid = ?
2307 $timedsql
2308 ORDER BY p.modified ASC", $params);
2312 * Get all the discussions user participated in
2314 * @global object
2315 * @global object
2316 * @uses CONTEXT_MODULE
2317 * @param int $forumid
2318 * @param int $userid
2319 * @return array Array or false
2321 function forum_get_user_involved_discussions($forumid, $userid) {
2322 global $CFG, $DB;
2324 $timedsql = "";
2325 $params = array($forumid, $userid);
2326 if (!empty($CFG->forum_enabletimedposts)) {
2327 $cm = get_coursemodule_from_instance('forum', $forumid);
2328 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2329 $now = time();
2330 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2331 $params[] = $now;
2332 $params[] = $now;
2336 return $DB->get_records_sql("SELECT DISTINCT d.*
2337 FROM {forum} f
2338 JOIN {forum_discussions} d ON d.forum = f.id
2339 JOIN {forum_posts} p ON p.discussion = d.id
2340 WHERE f.id = ?
2341 AND p.userid = ?
2342 $timedsql", $params);
2346 * Get all the posts for a user in a forum suitable for forum_print_post
2348 * @global object
2349 * @global object
2350 * @param int $forumid
2351 * @param int $userid
2352 * @return array of counts or false
2354 function forum_count_user_posts($forumid, $userid) {
2355 global $CFG, $DB;
2357 $timedsql = "";
2358 $params = array($forumid, $userid);
2359 if (!empty($CFG->forum_enabletimedposts)) {
2360 $cm = get_coursemodule_from_instance('forum', $forumid);
2361 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2362 $now = time();
2363 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2364 $params[] = $now;
2365 $params[] = $now;
2369 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2370 FROM {forum} f
2371 JOIN {forum_discussions} d ON d.forum = f.id
2372 JOIN {forum_posts} p ON p.discussion = d.id
2373 JOIN {user} u ON u.id = p.userid
2374 WHERE f.id = ?
2375 AND p.userid = ?
2376 $timedsql", $params);
2380 * Given a log entry, return the forum post details for it.
2382 * @global object
2383 * @global object
2384 * @param object $log
2385 * @return array|null
2387 function forum_get_post_from_log($log) {
2388 global $CFG, $DB;
2390 $allnames = get_all_user_name_fields(true, 'u');
2391 if ($log->action == "add post") {
2393 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2394 FROM {forum_discussions} d,
2395 {forum_posts} p,
2396 {forum} f,
2397 {user} u
2398 WHERE p.id = ?
2399 AND d.id = p.discussion
2400 AND p.userid = u.id
2401 AND u.deleted <> '1'
2402 AND f.id = d.forum", array($log->info));
2405 } else if ($log->action == "add discussion") {
2407 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2408 FROM {forum_discussions} d,
2409 {forum_posts} p,
2410 {forum} f,
2411 {user} u
2412 WHERE d.id = ?
2413 AND d.firstpost = p.id
2414 AND p.userid = u.id
2415 AND u.deleted <> '1'
2416 AND f.id = d.forum", array($log->info));
2418 return NULL;
2422 * Given a discussion id, return the first post from the discussion
2424 * @global object
2425 * @global object
2426 * @param int $dicsussionid
2427 * @return array
2429 function forum_get_firstpost_from_discussion($discussionid) {
2430 global $CFG, $DB;
2432 return $DB->get_record_sql("SELECT p.*
2433 FROM {forum_discussions} d,
2434 {forum_posts} p
2435 WHERE d.id = ?
2436 AND d.firstpost = p.id ", array($discussionid));
2440 * Returns an array of counts of replies to each discussion
2442 * @global object
2443 * @global object
2444 * @param int $forumid
2445 * @param string $forumsort
2446 * @param int $limit
2447 * @param int $page
2448 * @param int $perpage
2449 * @return array
2451 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2452 global $CFG, $DB;
2454 if ($limit > 0) {
2455 $limitfrom = 0;
2456 $limitnum = $limit;
2457 } else if ($page != -1) {
2458 $limitfrom = $page*$perpage;
2459 $limitnum = $perpage;
2460 } else {
2461 $limitfrom = 0;
2462 $limitnum = 0;
2465 if ($forumsort == "") {
2466 $orderby = "";
2467 $groupby = "";
2469 } else {
2470 $orderby = "ORDER BY $forumsort";
2471 $groupby = ", ".strtolower($forumsort);
2472 $groupby = str_replace('desc', '', $groupby);
2473 $groupby = str_replace('asc', '', $groupby);
2476 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2477 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2478 FROM {forum_posts} p
2479 JOIN {forum_discussions} d ON p.discussion = d.id
2480 WHERE p.parent > 0 AND d.forum = ?
2481 GROUP BY p.discussion";
2482 return $DB->get_records_sql($sql, array($forumid));
2484 } else {
2485 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2486 FROM {forum_posts} p
2487 JOIN {forum_discussions} d ON p.discussion = d.id
2488 WHERE d.forum = ?
2489 GROUP BY p.discussion $groupby $orderby";
2490 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2495 * @global object
2496 * @global object
2497 * @global object
2498 * @staticvar array $cache
2499 * @param object $forum
2500 * @param object $cm
2501 * @param object $course
2502 * @return mixed
2504 function forum_count_discussions($forum, $cm, $course) {
2505 global $CFG, $DB, $USER;
2507 static $cache = array();
2509 $now = round(time(), -2); // db cache friendliness
2511 $params = array($course->id);
2513 if (!isset($cache[$course->id])) {
2514 if (!empty($CFG->forum_enabletimedposts)) {
2515 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2516 $params[] = $now;
2517 $params[] = $now;
2518 } else {
2519 $timedsql = "";
2522 $sql = "SELECT f.id, COUNT(d.id) as dcount
2523 FROM {forum} f
2524 JOIN {forum_discussions} d ON d.forum = f.id
2525 WHERE f.course = ?
2526 $timedsql
2527 GROUP BY f.id";
2529 if ($counts = $DB->get_records_sql($sql, $params)) {
2530 foreach ($counts as $count) {
2531 $counts[$count->id] = $count->dcount;
2533 $cache[$course->id] = $counts;
2534 } else {
2535 $cache[$course->id] = array();
2539 if (empty($cache[$course->id][$forum->id])) {
2540 return 0;
2543 $groupmode = groups_get_activity_groupmode($cm, $course);
2545 if ($groupmode != SEPARATEGROUPS) {
2546 return $cache[$course->id][$forum->id];
2549 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2550 return $cache[$course->id][$forum->id];
2553 require_once($CFG->dirroot.'/course/lib.php');
2555 $modinfo = get_fast_modinfo($course);
2557 $mygroups = $modinfo->get_groups($cm->groupingid);
2559 // add all groups posts
2560 $mygroups[-1] = -1;
2562 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2563 $params[] = $forum->id;
2565 if (!empty($CFG->forum_enabletimedposts)) {
2566 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2567 $params[] = $now;
2568 $params[] = $now;
2569 } else {
2570 $timedsql = "";
2573 $sql = "SELECT COUNT(d.id)
2574 FROM {forum_discussions} d
2575 WHERE d.groupid $mygroups_sql AND d.forum = ?
2576 $timedsql";
2578 return $DB->get_field_sql($sql, $params);
2582 * Get all discussions in a forum
2584 * @global object
2585 * @global object
2586 * @global object
2587 * @uses CONTEXT_MODULE
2588 * @uses VISIBLEGROUPS
2589 * @param object $cm
2590 * @param string $forumsort
2591 * @param bool $fullpost
2592 * @param int $unused
2593 * @param int $limit
2594 * @param bool $userlastmodified
2595 * @param int $page
2596 * @param int $perpage
2597 * @return array
2599 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2600 global $CFG, $DB, $USER;
2602 $timelimit = '';
2604 $now = round(time(), -2);
2605 $params = array($cm->instance);
2607 $modcontext = context_module::instance($cm->id);
2609 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2610 return array();
2613 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2615 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2616 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2617 $params[] = $now;
2618 $params[] = $now;
2619 if (isloggedin()) {
2620 $timelimit .= " OR d.userid = ?";
2621 $params[] = $USER->id;
2623 $timelimit .= ")";
2627 if ($limit > 0) {
2628 $limitfrom = 0;
2629 $limitnum = $limit;
2630 } else if ($page != -1) {
2631 $limitfrom = $page*$perpage;
2632 $limitnum = $perpage;
2633 } else {
2634 $limitfrom = 0;
2635 $limitnum = 0;
2638 $groupmode = groups_get_activity_groupmode($cm);
2639 $currentgroup = groups_get_activity_group($cm);
2641 if ($groupmode) {
2642 if (empty($modcontext)) {
2643 $modcontext = context_module::instance($cm->id);
2646 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2647 if ($currentgroup) {
2648 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2649 $params[] = $currentgroup;
2650 } else {
2651 $groupselect = "";
2654 } else {
2655 //seprate groups without access all
2656 if ($currentgroup) {
2657 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2658 $params[] = $currentgroup;
2659 } else {
2660 $groupselect = "AND d.groupid = -1";
2663 } else {
2664 $groupselect = "";
2668 if (empty($forumsort)) {
2669 $forumsort = "d.timemodified DESC";
2671 if (empty($fullpost)) {
2672 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2673 } else {
2674 $postdata = "p.*";
2677 if (empty($userlastmodified)) { // We don't need to know this
2678 $umfields = "";
2679 $umtable = "";
2680 } else {
2681 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
2682 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2685 $allnames = get_all_user_name_fields(true, 'u');
2686 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2687 u.email, u.picture, u.imagealt $umfields
2688 FROM {forum_discussions} d
2689 JOIN {forum_posts} p ON p.discussion = d.id
2690 JOIN {user} u ON p.userid = u.id
2691 $umtable
2692 WHERE d.forum = ? AND p.parent = 0
2693 $timelimit $groupselect
2694 ORDER BY $forumsort";
2695 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2699 * Gets the neighbours (previous and next) of a discussion.
2701 * The calculation is based on the timemodified of the discussion and does not handle
2702 * the neighbours having an identical timemodified. The reason is that we do not have any
2703 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2704 * timemodified.
2706 * Please note that this does not check whether or not the discussion passed is accessible
2707 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2708 * the returned neighbours are checked and are accessible to the current user.
2710 * @param object $cm The CM record.
2711 * @param object $discussion The discussion record.
2712 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2713 * they contain the record with minimal information such as 'id' and 'name'.
2714 * When the neighbour is not found the value is false.
2716 function forum_get_discussion_neighbours($cm, $discussion) {
2717 global $CFG, $DB, $USER;
2719 if ($cm->instance != $discussion->forum) {
2720 throw new coding_exception('Discussion is not part of the same forum.');
2723 $neighbours = array('prev' => false, 'next' => false);
2724 $now = round(time(), -2);
2725 $params = array();
2727 $modcontext = context_module::instance($cm->id);
2728 $groupmode = groups_get_activity_groupmode($cm);
2729 $currentgroup = groups_get_activity_group($cm);
2731 // Users must fulfill timed posts.
2732 $timelimit = '';
2733 if (!empty($CFG->forum_enabletimedposts)) {
2734 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2735 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2736 $params['tltimestart'] = $now;
2737 $params['tltimeend'] = $now;
2738 if (isloggedin()) {
2739 $timelimit .= ' OR d.userid = :tluserid';
2740 $params['tluserid'] = $USER->id;
2742 $timelimit .= ')';
2746 // Limiting to posts accessible according to groups.
2747 $groupselect = '';
2748 if ($groupmode) {
2749 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2750 if ($currentgroup) {
2751 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2752 $params['groupid'] = $currentgroup;
2754 } else {
2755 if ($currentgroup) {
2756 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2757 $params['groupid'] = $currentgroup;
2758 } else {
2759 $groupselect = 'AND d.groupid = -1';
2764 $params['forumid'] = $cm->instance;
2765 $params['discid'] = $discussion->id;
2766 $params['disctimemodified'] = $discussion->timemodified;
2768 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2769 FROM {forum_discussions} d
2770 WHERE d.forum = :forumid
2771 AND d.id <> :discid
2772 $timelimit
2773 $groupselect";
2775 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2776 ORDER BY d.timemodified DESC";
2778 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2779 ORDER BY d.timemodified ASC";
2781 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2782 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2784 return $neighbours;
2789 * @global object
2790 * @global object
2791 * @global object
2792 * @uses CONTEXT_MODULE
2793 * @uses VISIBLEGROUPS
2794 * @param object $cm
2795 * @return array
2797 function forum_get_discussions_unread($cm) {
2798 global $CFG, $DB, $USER;
2800 $now = round(time(), -2);
2801 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2803 $params = array();
2804 $groupmode = groups_get_activity_groupmode($cm);
2805 $currentgroup = groups_get_activity_group($cm);
2807 if ($groupmode) {
2808 $modcontext = context_module::instance($cm->id);
2810 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2811 if ($currentgroup) {
2812 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2813 $params['currentgroup'] = $currentgroup;
2814 } else {
2815 $groupselect = "";
2818 } else {
2819 //separate groups without access all
2820 if ($currentgroup) {
2821 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2822 $params['currentgroup'] = $currentgroup;
2823 } else {
2824 $groupselect = "AND d.groupid = -1";
2827 } else {
2828 $groupselect = "";
2831 if (!empty($CFG->forum_enabletimedposts)) {
2832 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2833 $params['now1'] = $now;
2834 $params['now2'] = $now;
2835 } else {
2836 $timedsql = "";
2839 $sql = "SELECT d.id, COUNT(p.id) AS unread
2840 FROM {forum_discussions} d
2841 JOIN {forum_posts} p ON p.discussion = d.id
2842 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2843 WHERE d.forum = {$cm->instance}
2844 AND p.modified >= :cutoffdate AND r.id is NULL
2845 $groupselect
2846 $timedsql
2847 GROUP BY d.id";
2848 $params['cutoffdate'] = $cutoffdate;
2850 if ($unreads = $DB->get_records_sql($sql, $params)) {
2851 foreach ($unreads as $unread) {
2852 $unreads[$unread->id] = $unread->unread;
2854 return $unreads;
2855 } else {
2856 return array();
2861 * @global object
2862 * @global object
2863 * @global object
2864 * @uses CONEXT_MODULE
2865 * @uses VISIBLEGROUPS
2866 * @param object $cm
2867 * @return array
2869 function forum_get_discussions_count($cm) {
2870 global $CFG, $DB, $USER;
2872 $now = round(time(), -2);
2873 $params = array($cm->instance);
2874 $groupmode = groups_get_activity_groupmode($cm);
2875 $currentgroup = groups_get_activity_group($cm);
2877 if ($groupmode) {
2878 $modcontext = context_module::instance($cm->id);
2880 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2881 if ($currentgroup) {
2882 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2883 $params[] = $currentgroup;
2884 } else {
2885 $groupselect = "";
2888 } else {
2889 //seprate groups without access all
2890 if ($currentgroup) {
2891 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2892 $params[] = $currentgroup;
2893 } else {
2894 $groupselect = "AND d.groupid = -1";
2897 } else {
2898 $groupselect = "";
2901 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2903 $timelimit = "";
2905 if (!empty($CFG->forum_enabletimedposts)) {
2907 $modcontext = context_module::instance($cm->id);
2909 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2910 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2911 $params[] = $now;
2912 $params[] = $now;
2913 if (isloggedin()) {
2914 $timelimit .= " OR d.userid = ?";
2915 $params[] = $USER->id;
2917 $timelimit .= ")";
2921 $sql = "SELECT COUNT(d.id)
2922 FROM {forum_discussions} d
2923 JOIN {forum_posts} p ON p.discussion = d.id
2924 WHERE d.forum = ? AND p.parent = 0
2925 $groupselect $timelimit";
2927 return $DB->get_field_sql($sql, $params);
2931 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2935 * @global object
2936 * @global object
2937 * @param int $courseid
2938 * @param string $type
2940 function forum_get_course_forum($courseid, $type) {
2941 // How to set up special 1-per-course forums
2942 global $CFG, $DB, $OUTPUT, $USER;
2944 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2945 // There should always only be ONE, but with the right combination of
2946 // errors there might be more. In this case, just return the oldest one (lowest ID).
2947 foreach ($forums as $forum) {
2948 return $forum; // ie the first one
2952 // Doesn't exist, so create one now.
2953 $forum = new stdClass();
2954 $forum->course = $courseid;
2955 $forum->type = "$type";
2956 if (!empty($USER->htmleditor)) {
2957 $forum->introformat = $USER->htmleditor;
2959 switch ($forum->type) {
2960 case "news":
2961 $forum->name = get_string("namenews", "forum");
2962 $forum->intro = get_string("intronews", "forum");
2963 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2964 $forum->assessed = 0;
2965 if ($courseid == SITEID) {
2966 $forum->name = get_string("sitenews");
2967 $forum->forcesubscribe = 0;
2969 break;
2970 case "social":
2971 $forum->name = get_string("namesocial", "forum");
2972 $forum->intro = get_string("introsocial", "forum");
2973 $forum->assessed = 0;
2974 $forum->forcesubscribe = 0;
2975 break;
2976 case "blog":
2977 $forum->name = get_string('blogforum', 'forum');
2978 $forum->intro = get_string('introblog', 'forum');
2979 $forum->assessed = 0;
2980 $forum->forcesubscribe = 0;
2981 break;
2982 default:
2983 echo $OUTPUT->notification("That forum type doesn't exist!");
2984 return false;
2985 break;
2988 $forum->timemodified = time();
2989 $forum->id = $DB->insert_record("forum", $forum);
2991 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2992 echo $OUTPUT->notification("Could not find forum module!!");
2993 return false;
2995 $mod = new stdClass();
2996 $mod->course = $courseid;
2997 $mod->module = $module->id;
2998 $mod->instance = $forum->id;
2999 $mod->section = 0;
3000 include_once("$CFG->dirroot/course/lib.php");
3001 if (! $mod->coursemodule = add_course_module($mod) ) {
3002 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3003 return false;
3005 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3006 return $DB->get_record("forum", array("id" => "$forum->id"));
3011 * Given the data about a posting, builds up the HTML to display it and
3012 * returns the HTML in a string. This is designed for sending via HTML email.
3014 * @global object
3015 * @param object $course
3016 * @param object $cm
3017 * @param object $forum
3018 * @param object $discussion
3019 * @param object $post
3020 * @param object $userform
3021 * @param object $userto
3022 * @param bool $ownpost
3023 * @param bool $reply
3024 * @param bool $link
3025 * @param bool $rate
3026 * @param string $footer
3027 * @return string
3029 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
3030 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
3032 global $CFG, $OUTPUT;
3034 $modcontext = context_module::instance($cm->id);
3036 if (!isset($userto->viewfullnames[$forum->id])) {
3037 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3038 } else {
3039 $viewfullnames = $userto->viewfullnames[$forum->id];
3042 // add absolute file links
3043 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3045 // format the post body
3046 $options = new stdClass();
3047 $options->para = true;
3048 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
3050 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3052 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3053 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
3054 $output .= '</td>';
3056 if ($post->parent) {
3057 $output .= '<td class="topic">';
3058 } else {
3059 $output .= '<td class="topic starter">';
3061 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3063 $fullname = fullname($userfrom, $viewfullnames);
3064 $by = new stdClass();
3065 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
3066 $by->date = userdate($post->modified, '', core_date::get_user_timezone($userto));
3067 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3069 $output .= '</td></tr>';
3071 $output .= '<tr><td class="left side" valign="top">';
3073 if (isset($userfrom->groups)) {
3074 $groups = $userfrom->groups[$forum->id];
3075 } else {
3076 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3079 if ($groups) {
3080 $output .= print_group_picture($groups, $course->id, false, true, true);
3081 } else {
3082 $output .= '&nbsp;';
3085 $output .= '</td><td class="content">';
3087 $attachments = forum_print_attachments($post, $cm, 'html');
3088 if ($attachments !== '') {
3089 $output .= '<div class="attachments">';
3090 $output .= $attachments;
3091 $output .= '</div>';
3094 $output .= $formattedtext;
3096 // Commands
3097 $commands = array();
3099 if ($post->parent) {
3100 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3101 $post->discussion.'&amp;parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3104 if ($reply) {
3105 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3106 get_string('reply', 'forum').'</a>';
3109 $output .= '<div class="commands">';
3110 $output .= implode(' | ', $commands);
3111 $output .= '</div>';
3113 // Context link to post if required
3114 if ($link) {
3115 $output .= '<div class="link">';
3116 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3117 get_string('postincontext', 'forum').'</a>';
3118 $output .= '</div>';
3121 if ($footer) {
3122 $output .= '<div class="footer">'.$footer.'</div>';
3124 $output .= '</td></tr></table>'."\n\n";
3126 return $output;
3130 * Print a forum post
3132 * @global object
3133 * @global object
3134 * @uses FORUM_MODE_THREADED
3135 * @uses PORTFOLIO_FORMAT_PLAINHTML
3136 * @uses PORTFOLIO_FORMAT_FILE
3137 * @uses PORTFOLIO_FORMAT_RICHHTML
3138 * @uses PORTFOLIO_ADD_TEXT_LINK
3139 * @uses CONTEXT_MODULE
3140 * @param object $post The post to print.
3141 * @param object $discussion
3142 * @param object $forum
3143 * @param object $cm
3144 * @param object $course
3145 * @param boolean $ownpost Whether this post belongs to the current user.
3146 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3147 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3148 * @param string $footer Extra stuff to print after the message.
3149 * @param string $highlight Space-separated list of terms to highlight.
3150 * @param int $post_read true, false or -99. If we already know whether this user
3151 * has read this post, pass that in, otherwise, pass in -99, and this
3152 * function will work it out.
3153 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3154 * the current user can't see this post, if this argument is true
3155 * (the default) then print a dummy 'you can't see this post' post.
3156 * If false, don't output anything at all.
3157 * @param bool|null $istracked
3158 * @return void
3160 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3161 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3162 global $USER, $CFG, $OUTPUT;
3164 require_once($CFG->libdir . '/filelib.php');
3166 // String cache
3167 static $str;
3169 $modcontext = context_module::instance($cm->id);
3171 $post->course = $course->id;
3172 $post->forum = $forum->id;
3173 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3174 if (!empty($CFG->enableplagiarism)) {
3175 require_once($CFG->libdir.'/plagiarismlib.php');
3176 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3177 'content' => $post->message,
3178 'cmid' => $cm->id,
3179 'course' => $post->course,
3180 'forum' => $post->forum));
3183 // caching
3184 if (!isset($cm->cache)) {
3185 $cm->cache = new stdClass;
3188 if (!isset($cm->cache->caps)) {
3189 $cm->cache->caps = array();
3190 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3191 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3192 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3193 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3194 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3195 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3196 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3197 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3198 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3201 if (!isset($cm->uservisible)) {
3202 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3205 if ($istracked && is_null($postisread)) {
3206 $postisread = forum_tp_is_post_read($USER->id, $post);
3209 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3210 $output = '';
3211 if (!$dummyifcantsee) {
3212 if ($return) {
3213 return $output;
3215 echo $output;
3216 return;
3218 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3219 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3220 'role' => 'region',
3221 'aria-label' => get_string('hiddenforumpost', 'forum')));
3222 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3223 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3224 if ($post->parent) {
3225 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3226 } else {
3227 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3229 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3230 'role' => 'header')); // Subject.
3231 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3232 'role' => 'header')); // Author.
3233 $output .= html_writer::end_tag('div');
3234 $output .= html_writer::end_tag('div'); // row
3235 $output .= html_writer::start_tag('div', array('class'=>'row'));
3236 $output .= html_writer::tag('div', '&nbsp;', array('class'=>'left side')); // Groups
3237 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3238 $output .= html_writer::end_tag('div'); // row
3239 $output .= html_writer::end_tag('div'); // forumpost
3241 if ($return) {
3242 return $output;
3244 echo $output;
3245 return;
3248 if (empty($str)) {
3249 $str = new stdClass;
3250 $str->edit = get_string('edit', 'forum');
3251 $str->delete = get_string('delete', 'forum');
3252 $str->reply = get_string('reply', 'forum');
3253 $str->parent = get_string('parent', 'forum');
3254 $str->pruneheading = get_string('pruneheading', 'forum');
3255 $str->prune = get_string('prune', 'forum');
3256 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3257 $str->markread = get_string('markread', 'forum');
3258 $str->markunread = get_string('markunread', 'forum');
3261 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3263 // Build an object that represents the posting user
3264 $postuser = new stdClass;
3265 $postuserfields = explode(',', user_picture::fields());
3266 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3267 $postuser->id = $post->userid;
3268 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3269 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3271 // Prepare the groups the posting user belongs to
3272 if (isset($cm->cache->usersgroups)) {
3273 $groups = array();
3274 if (isset($cm->cache->usersgroups[$post->userid])) {
3275 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3276 $groups[$gid] = $cm->cache->groups[$gid];
3279 } else {
3280 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3283 // Prepare the attachements for the post, files then images
3284 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3286 // Determine if we need to shorten this post
3287 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3290 // Prepare an array of commands
3291 $commands = array();
3293 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3294 // Don't display the mark read / unread controls in this case.
3295 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3296 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3297 $text = $str->markunread;
3298 if (!$postisread) {
3299 $url->param('mark', 'read');
3300 $text = $str->markread;
3302 if ($str->displaymode == FORUM_MODE_THREADED) {
3303 $url->param('parent', $post->parent);
3304 } else {
3305 $url->set_anchor('p'.$post->id);
3307 $commands[] = array('url'=>$url, 'text'=>$text);
3310 // Zoom in to the parent specifically
3311 if ($post->parent) {
3312 $url = new moodle_url($discussionlink);
3313 if ($str->displaymode == FORUM_MODE_THREADED) {
3314 $url->param('parent', $post->parent);
3315 } else {
3316 $url->set_anchor('p'.$post->parent);
3318 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3321 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3322 $age = time() - $post->created;
3323 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3324 $age = 0;
3327 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3328 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3329 // The first post in single simple is the forum description.
3330 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3332 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3333 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3336 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3337 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3340 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3341 // Do not allow deleting of first post in single simple type.
3342 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3343 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3346 if ($reply) {
3347 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3350 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3351 $p = array('postid' => $post->id);
3352 require_once($CFG->libdir.'/portfoliolib.php');
3353 $button = new portfolio_add_button();
3354 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3355 if (empty($attachments)) {
3356 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3357 } else {
3358 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3361 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3362 if (!empty($porfoliohtml)) {
3363 $commands[] = $porfoliohtml;
3366 // Finished building commands
3369 // Begin output
3371 $output = '';
3373 if ($istracked) {
3374 if ($postisread) {
3375 $forumpostclass = ' read';
3376 } else {
3377 $forumpostclass = ' unread';
3378 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3380 } else {
3381 // ignore trackign status if not tracked or tracked param missing
3382 $forumpostclass = '';
3385 $topicclass = '';
3386 if (empty($post->parent)) {
3387 $topicclass = ' firstpost starter';
3390 if (!empty($post->lastpost)) {
3391 $forumpostclass = ' lastpost';
3394 $postbyuser = new stdClass;
3395 $postbyuser->post = $post->subject;
3396 $postbyuser->user = $postuser->fullname;
3397 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3398 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3399 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3400 'role' => 'region',
3401 'aria-label' => $discussionbyuser));
3402 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3403 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3404 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3405 $output .= html_writer::end_tag('div');
3408 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3410 $postsubject = $post->subject;
3411 if (empty($post->subjectnoformat)) {
3412 $postsubject = format_string($postsubject);
3414 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject',
3415 'role' => 'heading',
3416 'aria-level' => '2'));
3418 $by = new stdClass();
3419 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3420 $by->date = userdate($post->modified);
3421 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3422 'role' => 'heading',
3423 'aria-level' => '2'));
3425 $output .= html_writer::end_tag('div'); //topic
3426 $output .= html_writer::end_tag('div'); //row
3428 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3429 $output .= html_writer::start_tag('div', array('class'=>'left'));
3431 $groupoutput = '';
3432 if ($groups) {
3433 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3435 if (empty($groupoutput)) {
3436 $groupoutput = '&nbsp;';
3438 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3440 $output .= html_writer::end_tag('div'); //left side
3441 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3442 $output .= html_writer::start_tag('div', array('class'=>'content'));
3444 $options = new stdClass;
3445 $options->para = false;
3446 $options->trusted = $post->messagetrust;
3447 $options->context = $modcontext;
3448 if ($shortenpost) {
3449 // Prepare shortened version by filtering the text then shortening it.
3450 $postclass = 'shortenedpost';
3451 $postcontent = format_text($post->message, $post->messageformat, $options);
3452 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3453 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3454 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3455 array('class'=>'post-word-count'));
3456 } else {
3457 // Prepare whole post
3458 $postclass = 'fullpost';
3459 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3460 if (!empty($highlight)) {
3461 $postcontent = highlight($highlight, $postcontent);
3463 if (!empty($forum->displaywordcount)) {
3464 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3465 array('class'=>'post-word-count'));
3467 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3470 // Output the post content
3471 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3472 $output .= html_writer::end_tag('div'); // Content
3473 $output .= html_writer::end_tag('div'); // Content mask
3474 $output .= html_writer::end_tag('div'); // Row
3476 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3477 $output .= html_writer::tag('div','&nbsp;', array('class'=>'left'));
3478 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3480 if (!empty($attachments)) {
3481 $output .= html_writer::tag('div', $attachments, array('class' => 'attachments'));
3484 // Output ratings
3485 if (!empty($post->rating)) {
3486 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3489 // Output the commands
3490 $commandhtml = array();
3491 foreach ($commands as $command) {
3492 if (is_array($command)) {
3493 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3494 } else {
3495 $commandhtml[] = $command;
3498 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3500 // Output link to post if required
3501 if ($link && forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3502 if ($post->replies == 1) {
3503 $replystring = get_string('repliesone', 'forum', $post->replies);
3504 } else {
3505 $replystring = get_string('repliesmany', 'forum', $post->replies);
3508 $output .= html_writer::start_tag('div', array('class'=>'link'));
3509 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3510 $output .= '&nbsp;('.$replystring.')';
3511 $output .= html_writer::end_tag('div'); // link
3514 // Output footer if required
3515 if ($footer) {
3516 $output .= html_writer::tag('div', $footer, array('class'=>'footer'));
3519 // Close remaining open divs
3520 $output .= html_writer::end_tag('div'); // content
3521 $output .= html_writer::end_tag('div'); // row
3522 $output .= html_writer::end_tag('div'); // forumpost
3524 // Mark the forum post as read if required
3525 if ($istracked && !$CFG->forum_usermarksread && !$postisread) {
3526 forum_tp_mark_post_read($USER->id, $post, $forum->id);
3529 if ($return) {
3530 return $output;
3532 echo $output;
3533 return;
3537 * Return rating related permissions
3539 * @param string $options the context id
3540 * @return array an associative array of the user's rating permissions
3542 function forum_rating_permissions($contextid, $component, $ratingarea) {
3543 $context = context::instance_by_id($contextid, MUST_EXIST);
3544 if ($component != 'mod_forum' || $ratingarea != 'post') {
3545 // We don't know about this component/ratingarea so just return null to get the
3546 // default restrictive permissions.
3547 return null;
3549 return array(
3550 'view' => has_capability('mod/forum:viewrating', $context),
3551 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3552 'viewall' => has_capability('mod/forum:viewallratings', $context),
3553 'rate' => has_capability('mod/forum:rate', $context)
3558 * Validates a submitted rating
3559 * @param array $params submitted data
3560 * context => object the context in which the rated items exists [required]
3561 * component => The component for this module - should always be mod_forum [required]
3562 * ratingarea => object the context in which the rated items exists [required]
3563 * itemid => int the ID of the object being rated [required]
3564 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3565 * rating => int the submitted rating [required]
3566 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3567 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3568 * @return boolean true if the rating is valid. Will throw rating_exception if not
3570 function forum_rating_validate($params) {
3571 global $DB, $USER;
3573 // Check the component is mod_forum
3574 if ($params['component'] != 'mod_forum') {
3575 throw new rating_exception('invalidcomponent');
3578 // Check the ratingarea is post (the only rating area in forum)
3579 if ($params['ratingarea'] != 'post') {
3580 throw new rating_exception('invalidratingarea');
3583 // Check the rateduserid is not the current user .. you can't rate your own posts
3584 if ($params['rateduserid'] == $USER->id) {
3585 throw new rating_exception('nopermissiontorate');
3588 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
3589 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
3590 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
3591 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
3592 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
3593 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
3594 $context = context_module::instance($cm->id);
3596 // Make sure the context provided is the context of the forum
3597 if ($context->id != $params['context']->id) {
3598 throw new rating_exception('invalidcontext');
3601 if ($forum->scale != $params['scaleid']) {
3602 //the scale being submitted doesnt match the one in the database
3603 throw new rating_exception('invalidscaleid');
3606 // check the item we're rating was created in the assessable time window
3607 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
3608 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
3609 throw new rating_exception('notavailable');
3613 //check that the submitted rating is valid for the scale
3615 // lower limit
3616 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
3617 throw new rating_exception('invalidnum');
3620 // upper limit
3621 if ($forum->scale < 0) {
3622 //its a custom scale
3623 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
3624 if ($scalerecord) {
3625 $scalearray = explode(',', $scalerecord->scale);
3626 if ($params['rating'] > count($scalearray)) {
3627 throw new rating_exception('invalidnum');
3629 } else {
3630 throw new rating_exception('invalidscaleid');
3632 } else if ($params['rating'] > $forum->scale) {
3633 //if its numeric and submitted rating is above maximum
3634 throw new rating_exception('invalidnum');
3637 // Make sure groups allow this user to see the item they're rating
3638 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
3639 if (!groups_group_exists($discussion->groupid)) { // Can't find group
3640 throw new rating_exception('cannotfindgroup');//something is wrong
3643 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
3644 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
3645 throw new rating_exception('notmemberofgroup');
3649 // perform some final capability checks
3650 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3651 throw new rating_exception('nopermissiontorate');
3654 return true;
3659 * This function prints the overview of a discussion in the forum listing.
3660 * It needs some discussion information and some post information, these
3661 * happen to be combined for efficiency in the $post parameter by the function
3662 * that calls this one: forum_print_latest_discussions()
3664 * @global object
3665 * @global object
3666 * @param object $post The post object (passed by reference for speed).
3667 * @param object $forum The forum object.
3668 * @param int $group Current group.
3669 * @param string $datestring Format to use for the dates.
3670 * @param boolean $cantrack Is tracking enabled for this forum.
3671 * @param boolean $forumtracked Is the user tracking this forum.
3672 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
3674 function forum_print_discussion_header(&$post, $forum, $group=-1, $datestring="",
3675 $cantrack=true, $forumtracked=true, $canviewparticipants=true, $modcontext=NULL) {
3677 global $COURSE, $USER, $CFG, $OUTPUT;
3679 static $rowcount;
3680 static $strmarkalldread;
3682 if (empty($modcontext)) {
3683 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3684 print_error('invalidcoursemodule');
3686 $modcontext = context_module::instance($cm->id);
3689 if (!isset($rowcount)) {
3690 $rowcount = 0;
3691 $strmarkalldread = get_string('markalldread', 'forum');
3692 } else {
3693 $rowcount = ($rowcount + 1) % 2;
3696 $post->subject = format_string($post->subject,true);
3698 echo "\n\n";
3699 echo '<tr class="discussion r'.$rowcount.'">';
3701 // Topic
3702 echo '<td class="topic starter">';
3703 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
3704 echo "</td>\n";
3706 // Picture
3707 $postuser = new stdClass();
3708 $postuserfields = explode(',', user_picture::fields());
3709 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3710 $postuser->id = $post->userid;
3711 echo '<td class="picture">';
3712 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
3713 echo "</td>\n";
3715 // User name
3716 $fullname = fullname($postuser, has_capability('moodle/site:viewfullnames', $modcontext));
3717 echo '<td class="author">';
3718 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
3719 echo "</td>\n";
3721 // Group picture
3722 if ($group !== -1) { // Groups are active - group is a group data object or NULL
3723 echo '<td class="picture group">';
3724 if (!empty($group->picture) and empty($group->hidepicture)) {
3725 if ($canviewparticipants && $COURSE->groupmode) {
3726 $picturelink = true;
3727 } else {
3728 $picturelink = false;
3730 print_group_picture($group, $forum->course, false, false, $picturelink);
3731 } else if (isset($group->id)) {
3732 if ($canviewparticipants && $COURSE->groupmode) {
3733 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
3734 } else {
3735 echo $group->name;
3738 echo "</td>\n";
3741 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
3742 echo '<td class="replies">';
3743 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
3744 echo $post->replies.'</a>';
3745 echo "</td>\n";
3747 if ($cantrack) {
3748 echo '<td class="replies">';
3749 if ($forumtracked) {
3750 if ($post->unread > 0) {
3751 echo '<span class="unread">';
3752 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
3753 echo $post->unread;
3754 echo '</a>';
3755 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
3756 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;returnpage=view.php">' .
3757 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.$strmarkalldread.'" /></a>';
3758 echo '</span>';
3759 } else {
3760 echo '<span class="read">';
3761 echo $post->unread;
3762 echo '</span>';
3764 } else {
3765 echo '<span class="read">';
3766 echo '-';
3767 echo '</span>';
3769 echo "</td>\n";
3773 echo '<td class="lastpost">';
3774 $usedate = (empty($post->timemodified)) ? $post->modified : $post->timemodified; // Just in case
3775 $parenturl = '';
3776 $usermodified = new stdClass();
3777 $usermodified->id = $post->usermodified;
3778 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
3780 // In QA forums we check that the user can view participants.
3781 if ($forum->type !== 'qanda' || $canviewparticipants) {
3782 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
3783 fullname($usermodified).'</a><br />';
3784 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
3787 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
3788 userdate($usedate, $datestring).'</a>';
3789 echo "</td>\n";
3791 // is_guest should be used here as this also checks whether the user is a guest in the current course.
3792 // Guests and visitors cannot subscribe - only enrolled users.
3793 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
3794 // Discussion subscription.
3795 if (\mod_forum\subscriptions::is_subscribable($forum)) {
3796 echo '<td class="discussionsubscription">';
3797 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
3798 echo '</td>';
3802 echo "</tr>\n\n";
3807 * Return the markup for the discussion subscription toggling icon.
3809 * @param stdClass $forum The forum object.
3810 * @param int $discussionid The discussion to create an icon for.
3811 * @return string The generated markup.
3813 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
3814 global $USER, $OUTPUT, $PAGE;
3816 if ($returnurl === null && $PAGE->url) {
3817 $returnurl = $PAGE->url->out();
3820 $o = '';
3821 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
3822 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
3823 'sesskey' => sesskey(),
3824 'id' => $forum->id,
3825 'd' => $discussionid,
3826 'returnurl' => $returnurl,
3829 if ($includetext) {
3830 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
3833 if ($subscriptionstatus) {
3834 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
3835 if ($includetext) {
3836 $output .= get_string('subscribed', 'mod_forum');
3839 return html_writer::link($subscriptionlink, $output, array(
3840 'title' => get_string('clicktounsubscribe', 'forum'),
3841 'class' => 'discussiontoggle iconsmall',
3842 'data-forumid' => $forum->id,
3843 'data-discussionid' => $discussionid,
3844 'data-includetext' => $includetext,
3847 } else {
3848 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
3849 if ($includetext) {
3850 $output .= get_string('notsubscribed', 'mod_forum');
3853 return html_writer::link($subscriptionlink, $output, array(
3854 'title' => get_string('clicktosubscribe', 'forum'),
3855 'class' => 'discussiontoggle iconsmall',
3856 'data-forumid' => $forum->id,
3857 'data-discussionid' => $discussionid,
3858 'data-includetext' => $includetext,
3864 * Return a pair of spans containing classes to allow the subscribe and
3865 * unsubscribe icons to be pre-loaded by a browser.
3867 * @return string The generated markup
3869 function forum_get_discussion_subscription_icon_preloaders() {
3870 $o = '';
3871 $o .= html_writer::span('&nbsp;', 'preload-subscribe');
3872 $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
3873 return $o;
3877 * Print the drop down that allows the user to select how they want to have
3878 * the discussion displayed.
3880 * @param int $id forum id if $forumtype is 'single',
3881 * discussion id for any other forum type
3882 * @param mixed $mode forum layout mode
3883 * @param string $forumtype optional
3885 function forum_print_mode_form($id, $mode, $forumtype='') {
3886 global $OUTPUT;
3887 if ($forumtype == 'single') {
3888 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3889 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3890 $select->class = "forummode";
3891 } else {
3892 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3893 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3895 echo $OUTPUT->render($select);
3899 * @global object
3900 * @param object $course
3901 * @param string $search
3902 * @return string
3904 function forum_search_form($course, $search='') {
3905 global $CFG, $OUTPUT;
3907 $output = '<div class="forumsearch">';
3908 $output .= '<form action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">';
3909 $output .= '<fieldset class="invisiblefieldset">';
3910 $output .= $OUTPUT->help_icon('search');
3911 $output .= '<label class="accesshide" for="search" >'.get_string('search', 'forum').'</label>';
3912 $output .= '<input id="search" name="search" type="text" size="18" value="'.s($search, true).'" />';
3913 $output .= '<label class="accesshide" for="searchforums" >'.get_string('searchforums', 'forum').'</label>';
3914 $output .= '<input id="searchforums" value="'.get_string('searchforums', 'forum').'" type="submit" />';
3915 $output .= '<input name="id" type="hidden" value="'.$course->id.'" />';
3916 $output .= '</fieldset>';
3917 $output .= '</form>';
3918 $output .= '</div>';
3920 return $output;
3925 * @global object
3926 * @global object
3928 function forum_set_return() {
3929 global $CFG, $SESSION;
3931 if (! isset($SESSION->fromdiscussion)) {
3932 if (!empty($_SERVER['HTTP_REFERER'])) {
3933 $referer = $_SERVER['HTTP_REFERER'];
3934 } else {
3935 $referer = "";
3937 // If the referer is NOT a login screen then save it.
3938 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
3939 $SESSION->fromdiscussion = $_SERVER["HTTP_REFERER"];
3946 * @global object
3947 * @param string $default
3948 * @return string
3950 function forum_go_back_to($default) {
3951 global $SESSION;
3953 if (!empty($SESSION->fromdiscussion)) {
3954 $returnto = $SESSION->fromdiscussion;
3955 unset($SESSION->fromdiscussion);
3956 return $returnto;
3957 } else {
3958 return $default;
3963 * Given a discussion object that is being moved to $forumto,
3964 * this function checks all posts in that discussion
3965 * for attachments, and if any are found, these are
3966 * moved to the new forum directory.
3968 * @global object
3969 * @param object $discussion
3970 * @param int $forumfrom source forum id
3971 * @param int $forumto target forum id
3972 * @return bool success
3974 function forum_move_attachments($discussion, $forumfrom, $forumto) {
3975 global $DB;
3977 $fs = get_file_storage();
3979 $newcm = get_coursemodule_from_instance('forum', $forumto);
3980 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
3982 $newcontext = context_module::instance($newcm->id);
3983 $oldcontext = context_module::instance($oldcm->id);
3985 // loop through all posts, better not use attachment flag ;-)
3986 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
3987 foreach ($posts as $post) {
3988 $fs->move_area_files_to_new_context($oldcontext->id,
3989 $newcontext->id, 'mod_forum', 'post', $post->id);
3990 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
3991 $newcontext->id, 'mod_forum', 'attachment', $post->id);
3992 if ($attachmentsmoved > 0 && $post->attachment != '1') {
3993 // Weird - let's fix it
3994 $post->attachment = '1';
3995 $DB->update_record('forum_posts', $post);
3996 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
3997 // Weird - let's fix it
3998 $post->attachment = '';
3999 $DB->update_record('forum_posts', $post);
4004 return true;
4008 * Returns attachments as formated text/html optionally with separate images
4010 * @global object
4011 * @global object
4012 * @global object
4013 * @param object $post
4014 * @param object $cm
4015 * @param string $type html/text/separateimages
4016 * @return mixed string or array of (html text withouth images and image HTML)
4018 function forum_print_attachments($post, $cm, $type) {
4019 global $CFG, $DB, $USER, $OUTPUT;
4021 if (empty($post->attachment)) {
4022 return $type !== 'separateimages' ? '' : array('', '');
4025 if (!in_array($type, array('separateimages', 'html', 'text'))) {
4026 return $type !== 'separateimages' ? '' : array('', '');
4029 if (!$context = context_module::instance($cm->id)) {
4030 return $type !== 'separateimages' ? '' : array('', '');
4032 $strattachment = get_string('attachment', 'forum');
4034 $fs = get_file_storage();
4036 $imagereturn = '';
4037 $output = '';
4039 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
4041 if ($canexport) {
4042 require_once($CFG->libdir.'/portfoliolib.php');
4045 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
4046 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
4047 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
4048 if ($files) {
4049 if ($canexport) {
4050 $button = new portfolio_add_button();
4052 foreach ($files as $file) {
4053 $filename = $file->get_filename();
4054 $mimetype = $file->get_mimetype();
4055 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
4056 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
4058 if ($type == 'html') {
4059 $output .= "<a href=\"$path\">$iconimage</a> ";
4060 $output .= "<a href=\"$path\">".s($filename)."</a>";
4061 if ($canexport) {
4062 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4063 $button->set_format_by_file($file);
4064 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4066 $output .= "<br />";
4068 } else if ($type == 'text') {
4069 $output .= "$strattachment ".s($filename).":\n$path\n";
4071 } else { //'returnimages'
4072 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
4073 // Image attachments don't get printed as links
4074 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
4075 if ($canexport) {
4076 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4077 $button->set_format_by_file($file);
4078 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4080 } else {
4081 $output .= "<a href=\"$path\">$iconimage</a> ";
4082 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
4083 if ($canexport) {
4084 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4085 $button->set_format_by_file($file);
4086 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4088 $output .= '<br />';
4092 if (!empty($CFG->enableplagiarism)) {
4093 require_once($CFG->libdir.'/plagiarismlib.php');
4094 $output .= plagiarism_get_links(array('userid' => $post->userid,
4095 'file' => $file,
4096 'cmid' => $cm->id,
4097 'course' => $post->course,
4098 'forum' => $post->forum));
4099 $output .= '<br />';
4104 if ($type !== 'separateimages') {
4105 return $output;
4107 } else {
4108 return array($output, $imagereturn);
4112 ////////////////////////////////////////////////////////////////////////////////
4113 // File API //
4114 ////////////////////////////////////////////////////////////////////////////////
4117 * Lists all browsable file areas
4119 * @package mod_forum
4120 * @category files
4121 * @param stdClass $course course object
4122 * @param stdClass $cm course module object
4123 * @param stdClass $context context object
4124 * @return array
4126 function forum_get_file_areas($course, $cm, $context) {
4127 return array(
4128 'attachment' => get_string('areaattachment', 'mod_forum'),
4129 'post' => get_string('areapost', 'mod_forum'),
4134 * File browsing support for forum module.
4136 * @package mod_forum
4137 * @category files
4138 * @param stdClass $browser file browser object
4139 * @param stdClass $areas file areas
4140 * @param stdClass $course course object
4141 * @param stdClass $cm course module
4142 * @param stdClass $context context module
4143 * @param string $filearea file area
4144 * @param int $itemid item ID
4145 * @param string $filepath file path
4146 * @param string $filename file name
4147 * @return file_info instance or null if not found
4149 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4150 global $CFG, $DB, $USER;
4152 if ($context->contextlevel != CONTEXT_MODULE) {
4153 return null;
4156 // filearea must contain a real area
4157 if (!isset($areas[$filearea])) {
4158 return null;
4161 // Note that forum_user_can_see_post() additionally allows access for parent roles
4162 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
4163 // course:managefiles, we will need to extend this.
4164 if (!has_capability('mod/forum:viewdiscussion', $context)) {
4165 return null;
4168 if (is_null($itemid)) {
4169 require_once($CFG->dirroot.'/mod/forum/locallib.php');
4170 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
4173 static $cached = array();
4174 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
4175 // is cleared between unit tests we check if this is the same session
4176 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
4177 $cached = array('sesskey' => sesskey());
4180 if (isset($cached['post']) && $cached['post']->id == $itemid) {
4181 $post = $cached['post'];
4182 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
4183 $cached['post'] = $post;
4184 } else {
4185 return null;
4188 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
4189 $discussion = $cached['discussion'];
4190 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
4191 $cached['discussion'] = $discussion;
4192 } else {
4193 return null;
4196 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
4197 $forum = $cached['forum'];
4198 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
4199 $cached['forum'] = $forum;
4200 } else {
4201 return null;
4204 $fs = get_file_storage();
4205 $filepath = is_null($filepath) ? '/' : $filepath;
4206 $filename = is_null($filename) ? '.' : $filename;
4207 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
4208 return null;
4211 // Checks to see if the user can manage files or is the owner.
4212 // TODO MDL-33805 - Do not use userid here and move the capability check above.
4213 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
4214 return null;
4216 // Make sure groups allow this user to see this file
4217 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
4218 $groupmode = groups_get_activity_groupmode($cm, $course);
4219 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
4220 return null;
4224 // Make sure we're allowed to see it...
4225 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4226 return null;
4229 $urlbase = $CFG->wwwroot.'/pluginfile.php';
4230 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
4234 * Serves the forum attachments. Implements needed access control ;-)
4236 * @package mod_forum
4237 * @category files
4238 * @param stdClass $course course object
4239 * @param stdClass $cm course module object
4240 * @param stdClass $context context object
4241 * @param string $filearea file area
4242 * @param array $args extra arguments
4243 * @param bool $forcedownload whether or not force download
4244 * @param array $options additional options affecting the file serving
4245 * @return bool false if file not found, does not return if found - justsend the file
4247 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
4248 global $CFG, $DB;
4250 if ($context->contextlevel != CONTEXT_MODULE) {
4251 return false;
4254 require_course_login($course, true, $cm);
4256 $areas = forum_get_file_areas($course, $cm, $context);
4258 // filearea must contain a real area
4259 if (!isset($areas[$filearea])) {
4260 return false;
4263 $postid = (int)array_shift($args);
4265 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
4266 return false;
4269 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
4270 return false;
4273 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
4274 return false;
4277 $fs = get_file_storage();
4278 $relativepath = implode('/', $args);
4279 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
4280 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4281 return false;
4284 // Make sure groups allow this user to see this file
4285 if ($discussion->groupid > 0) {
4286 $groupmode = groups_get_activity_groupmode($cm, $course);
4287 if ($groupmode == SEPARATEGROUPS) {
4288 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
4289 return false;
4294 // Make sure we're allowed to see it...
4295 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4296 return false;
4299 // finally send the file
4300 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
4304 * If successful, this function returns the name of the file
4306 * @global object
4307 * @param object $post is a full post record, including course and forum
4308 * @param object $forum
4309 * @param object $cm
4310 * @param mixed $mform
4311 * @param string $unused
4312 * @return bool
4314 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
4315 global $DB;
4317 if (empty($mform)) {
4318 return false;
4321 if (empty($post->attachments)) {
4322 return true; // Nothing to do
4325 $context = context_module::instance($cm->id);
4327 $info = file_get_draft_area_info($post->attachments);
4328 $present = ($info['filecount']>0) ? '1' : '';
4329 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
4330 mod_forum_post_form::attachment_options($forum));
4332 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
4334 return true;
4338 * Add a new post in an existing discussion.
4340 * @global object
4341 * @global object
4342 * @global object
4343 * @param object $post
4344 * @param mixed $mform
4345 * @param string $unused formerly $message, renamed in 2.8 as it was unused.
4346 * @return int
4348 function forum_add_new_post($post, $mform, $unused = null) {
4349 global $USER, $CFG, $DB;
4351 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4352 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4353 $cm = get_coursemodule_from_instance('forum', $forum->id);
4354 $context = context_module::instance($cm->id);
4356 $post->created = $post->modified = time();
4357 $post->mailed = FORUM_MAILED_PENDING;
4358 $post->userid = $USER->id;
4359 $post->attachment = "";
4360 if (!isset($post->totalscore)) {
4361 $post->totalscore = 0;
4363 if (!isset($post->mailnow)) {
4364 $post->mailnow = 0;
4367 $post->id = $DB->insert_record("forum_posts", $post);
4368 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
4369 mod_forum_post_form::editor_options($context, null), $post->message);
4370 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
4371 forum_add_attachment($post, $forum, $cm, $mform);
4373 // Update discussion modified date
4374 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
4375 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
4377 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4378 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4381 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4382 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
4384 return $post->id;
4388 * Update a post
4390 * @global object
4391 * @global object
4392 * @global object
4393 * @param object $post
4394 * @param mixed $mform
4395 * @param string $message
4396 * @return bool
4398 function forum_update_post($post, $mform, &$message) {
4399 global $USER, $CFG, $DB;
4401 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4402 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4403 $cm = get_coursemodule_from_instance('forum', $forum->id);
4404 $context = context_module::instance($cm->id);
4406 $post->modified = time();
4408 $DB->update_record('forum_posts', $post);
4410 $discussion->timemodified = $post->modified; // last modified tracking
4411 $discussion->usermodified = $post->userid; // last modified tracking
4413 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
4414 $discussion->name = $post->subject;
4415 $discussion->timestart = $post->timestart;
4416 $discussion->timeend = $post->timeend;
4418 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
4419 mod_forum_post_form::editor_options($context, $post->id), $post->message);
4420 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
4422 $DB->update_record('forum_discussions', $discussion);
4424 forum_add_attachment($post, $forum, $cm, $mform, $message);
4426 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4427 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4430 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4431 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
4433 return true;
4437 * Given an object containing all the necessary data,
4438 * create a new discussion and return the id
4440 * @param object $post
4441 * @param mixed $mform
4442 * @param string $unused
4443 * @param int $userid
4444 * @return object
4446 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
4447 global $USER, $CFG, $DB;
4449 $timenow = time();
4451 if (is_null($userid)) {
4452 $userid = $USER->id;
4455 // The first post is stored as a real post, and linked
4456 // to from the discuss entry.
4458 $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
4459 $cm = get_coursemodule_from_instance('forum', $forum->id);
4461 $post = new stdClass();
4462 $post->discussion = 0;
4463 $post->parent = 0;
4464 $post->userid = $userid;
4465 $post->created = $timenow;
4466 $post->modified = $timenow;
4467 $post->mailed = FORUM_MAILED_PENDING;
4468 $post->subject = $discussion->name;
4469 $post->message = $discussion->message;
4470 $post->messageformat = $discussion->messageformat;
4471 $post->messagetrust = $discussion->messagetrust;
4472 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null;
4473 $post->forum = $forum->id; // speedup
4474 $post->course = $forum->course; // speedup
4475 $post->mailnow = $discussion->mailnow;
4477 $post->id = $DB->insert_record("forum_posts", $post);
4479 // TODO: Fix the calling code so that there always is a $cm when this function is called
4480 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet
4481 $context = context_module::instance($cm->id);
4482 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
4483 mod_forum_post_form::editor_options($context, null), $post->message);
4484 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
4487 // Now do the main entry for the discussion, linking to this first post
4489 $discussion->firstpost = $post->id;
4490 $discussion->timemodified = $timenow;
4491 $discussion->usermodified = $post->userid;
4492 $discussion->userid = $userid;
4493 $discussion->assessed = 0;
4495 $post->discussion = $DB->insert_record("forum_discussions", $discussion);
4497 // Finally, set the pointer on the post.
4498 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
4500 if (!empty($cm->id)) {
4501 forum_add_attachment($post, $forum, $cm, $mform, $unused);
4504 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4505 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4508 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4509 if (!empty($cm->id)) {
4510 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
4513 return $post->discussion;
4518 * Deletes a discussion and handles all associated cleanup.
4520 * @global object
4521 * @param object $discussion Discussion to delete
4522 * @param bool $fulldelete True when deleting entire forum
4523 * @param object $course Course
4524 * @param object $cm Course-module
4525 * @param object $forum Forum
4526 * @return bool
4528 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
4529 global $DB, $CFG;
4530 require_once($CFG->libdir.'/completionlib.php');
4532 $result = true;
4534 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
4535 foreach ($posts as $post) {
4536 $post->course = $discussion->course;
4537 $post->forum = $discussion->forum;
4538 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
4539 $result = false;
4544 forum_tp_delete_read_records(-1, -1, $discussion->id);
4546 // Discussion subscriptions must be removed before discussions because of key constraints.
4547 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
4548 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
4549 $result = false;
4552 // Update completion state if we are tracking completion based on number of posts
4553 // But don't bother when deleting whole thing
4554 if (!$fulldelete) {
4555 $completion = new completion_info($course);
4556 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4557 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4558 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
4562 return $result;
4567 * Deletes a single forum post.
4569 * @global object
4570 * @param object $post Forum post object
4571 * @param mixed $children Whether to delete children. If false, returns false
4572 * if there are any children (without deleting the post). If true,
4573 * recursively deletes all children. If set to special value 'ignore', deletes
4574 * post regardless of children (this is for use only when deleting all posts
4575 * in a disussion).
4576 * @param object $course Course
4577 * @param object $cm Course-module
4578 * @param object $forum Forum
4579 * @param bool $skipcompletion True to skip updating completion state if it
4580 * would otherwise be updated, i.e. when deleting entire forum anyway.
4581 * @return bool
4583 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
4584 global $DB, $CFG;
4585 require_once($CFG->libdir.'/completionlib.php');
4587 $context = context_module::instance($cm->id);
4589 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
4590 if ($children) {
4591 foreach ($childposts as $childpost) {
4592 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
4594 } else {
4595 return false;
4599 // Delete ratings.
4600 require_once($CFG->dirroot.'/rating/lib.php');
4601 $delopt = new stdClass;
4602 $delopt->contextid = $context->id;
4603 $delopt->component = 'mod_forum';
4604 $delopt->ratingarea = 'post';
4605 $delopt->itemid = $post->id;
4606 $rm = new rating_manager();
4607 $rm->delete_ratings($delopt);
4609 // Delete attachments.
4610 $fs = get_file_storage();
4611 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
4612 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
4614 // Delete cached RSS feeds.
4615 if (!empty($CFG->enablerssfeeds)) {
4616 require_once($CFG->dirroot.'/mod/forum/rsslib.php');
4617 forum_rss_delete_file($forum);
4620 if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
4622 forum_tp_delete_read_records(-1, $post->id);
4624 // Just in case we are deleting the last post
4625 forum_discussion_update_last_post($post->discussion);
4627 // Update completion state if we are tracking completion based on number of posts
4628 // But don't bother when deleting whole thing
4630 if (!$skipcompletion) {
4631 $completion = new completion_info($course);
4632 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4633 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4634 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
4638 return true;
4640 return false;
4644 * Sends post content to plagiarism plugin
4645 * @param object $post Forum post object
4646 * @param object $cm Course-module
4647 * @param string $name
4648 * @return bool
4650 function forum_trigger_content_uploaded_event($post, $cm, $name) {
4651 $context = context_module::instance($cm->id);
4652 $fs = get_file_storage();
4653 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
4654 $params = array(
4655 'context' => $context,
4656 'objectid' => $post->id,
4657 'other' => array(
4658 'content' => $post->message,
4659 'pathnamehashes' => array_keys($files),
4660 'discussionid' => $post->discussion,
4661 'triggeredfrom' => $name,
4664 $event = \mod_forum\event\assessable_uploaded::create($params);
4665 $event->trigger();
4666 return true;
4670 * @global object
4671 * @param object $post
4672 * @param bool $children
4673 * @return int
4675 function forum_count_replies($post, $children=true) {
4676 global $DB;
4677 $count = 0;
4679 if ($children) {
4680 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id))) {
4681 foreach ($childposts as $childpost) {
4682 $count ++; // For this child
4683 $count += forum_count_replies($childpost, true);
4686 } else {
4687 $count += $DB->count_records('forum_posts', array('parent' => $post->id));
4690 return $count;
4694 * Given a new post, subscribes or unsubscribes as appropriate.
4695 * Returns some text which describes what happened.
4697 * @param object $fromform The submitted form
4698 * @param stdClass $forum The forum record
4699 * @param stdClass $discussion The forum discussion record
4700 * @return string
4702 function forum_post_subscription($fromform, $forum, $discussion) {
4703 global $USER;
4705 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4706 return "";
4707 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
4708 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4709 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
4710 // This user should not be subscribed to the forum.
4711 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
4713 return "";
4716 $info = new stdClass();
4717 $info->name = fullname($USER);
4718 $info->discussion = format_string($discussion->name);
4719 $info->forum = format_string($forum->name);
4721 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
4722 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
4723 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
4725 } else {
4726 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
4727 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
4731 return '';
4735 * Generate and return the subscribe or unsubscribe link for a forum.
4737 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
4738 * @param object $context the context object for this forum.
4739 * @param array $messages text used for the link in its various states
4740 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
4741 * Any strings not passed in are taken from the $defaultmessages array
4742 * at the top of the function.
4743 * @param bool $cantaccessagroup
4744 * @param bool $fakelink
4745 * @param bool $backtoindex
4746 * @param array $subscribed_forums
4747 * @return string
4749 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $fakelink=true, $backtoindex=false, $subscribed_forums=null) {
4750 global $CFG, $USER, $PAGE, $OUTPUT;
4751 $defaultmessages = array(
4752 'subscribed' => get_string('unsubscribe', 'forum'),
4753 'unsubscribed' => get_string('subscribe', 'forum'),
4754 'cantaccessgroup' => get_string('no'),
4755 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
4756 'cantsubscribe' => get_string('disallowsubscribe','forum')
4758 $messages = $messages + $defaultmessages;
4760 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4761 return $messages['forcesubscribed'];
4762 } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
4763 !has_capability('mod/forum:managesubscriptions', $context)) {
4764 return $messages['cantsubscribe'];
4765 } else if ($cantaccessagroup) {
4766 return $messages['cantaccessgroup'];
4767 } else {
4768 if (!is_enrolled($context, $USER, '', true)) {
4769 return '';
4772 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4773 if ($subscribed) {
4774 $linktext = $messages['subscribed'];
4775 $linktitle = get_string('subscribestop', 'forum');
4776 } else {
4777 $linktext = $messages['unsubscribed'];
4778 $linktitle = get_string('subscribestart', 'forum');
4781 $options = array();
4782 if ($backtoindex) {
4783 $backtoindexlink = '&amp;backtoindex=1';
4784 $options['backtoindex'] = 1;
4785 } else {
4786 $backtoindexlink = '';
4788 $link = '';
4790 if ($fakelink) {
4791 $PAGE->requires->js('/mod/forum/forum.js');
4792 $PAGE->requires->js_function_call('forum_produce_subscribe_link', array($forum->id, $backtoindexlink, $linktext, $linktitle));
4793 $link = "<noscript>";
4795 $options['id'] = $forum->id;
4796 $options['sesskey'] = sesskey();
4797 $url = new moodle_url('/mod/forum/subscribe.php', $options);
4798 $link .= $OUTPUT->single_button($url, $linktext, 'get', array('title'=>$linktitle));
4799 if ($fakelink) {
4800 $link .= '</noscript>';
4803 return $link;
4808 * Returns true if user created new discussion already
4810 * @global object
4811 * @global object
4812 * @param int $forumid
4813 * @param int $userid
4814 * @return bool
4816 function forum_user_has_posted_discussion($forumid, $userid) {
4817 global $CFG, $DB;
4819 $sql = "SELECT 'x'
4820 FROM {forum_discussions} d, {forum_posts} p
4821 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 and p.userid = ?";
4823 return $DB->record_exists_sql($sql, array($forumid, $userid));
4827 * @global object
4828 * @global object
4829 * @param int $forumid
4830 * @param int $userid
4831 * @return array
4833 function forum_discussions_user_has_posted_in($forumid, $userid) {
4834 global $CFG, $DB;
4836 $haspostedsql = "SELECT d.id AS id,
4838 FROM {forum_posts} p,
4839 {forum_discussions} d
4840 WHERE p.discussion = d.id
4841 AND d.forum = ?
4842 AND p.userid = ?";
4844 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
4848 * @global object
4849 * @global object
4850 * @param int $forumid
4851 * @param int $did
4852 * @param int $userid
4853 * @return bool
4855 function forum_user_has_posted($forumid, $did, $userid) {
4856 global $DB;
4858 if (empty($did)) {
4859 // posted in any forum discussion?
4860 $sql = "SELECT 'x'
4861 FROM {forum_posts} p
4862 JOIN {forum_discussions} d ON d.id = p.discussion
4863 WHERE p.userid = :userid AND d.forum = :forumid";
4864 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
4865 } else {
4866 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
4871 * Returns creation time of the first user's post in given discussion
4872 * @global object $DB
4873 * @param int $did Discussion id
4874 * @param int $userid User id
4875 * @return int|bool post creation time stamp or return false
4877 function forum_get_user_posted_time($did, $userid) {
4878 global $DB;
4880 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
4881 if (empty($posttime)) {
4882 return false;
4884 return $posttime;
4888 * @global object
4889 * @param object $forum
4890 * @param object $currentgroup
4891 * @param int $unused
4892 * @param object $cm
4893 * @param object $context
4894 * @return bool
4896 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
4897 // $forum is an object
4898 global $USER;
4900 // shortcut - guest and not-logged-in users can not post
4901 if (isguestuser() or !isloggedin()) {
4902 return false;
4905 if (!$cm) {
4906 debugging('missing cm', DEBUG_DEVELOPER);
4907 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
4908 print_error('invalidcoursemodule');
4912 if (!$context) {
4913 $context = context_module::instance($cm->id);
4916 if ($currentgroup === null) {
4917 $currentgroup = groups_get_activity_group($cm);
4920 $groupmode = groups_get_activity_groupmode($cm);
4922 if ($forum->type == 'news') {
4923 $capname = 'mod/forum:addnews';
4924 } else if ($forum->type == 'qanda') {
4925 $capname = 'mod/forum:addquestion';
4926 } else {
4927 $capname = 'mod/forum:startdiscussion';
4930 if (!has_capability($capname, $context)) {
4931 return false;
4934 if ($forum->type == 'single') {
4935 return false;
4938 if ($forum->type == 'eachuser') {
4939 if (forum_user_has_posted_discussion($forum->id, $USER->id)) {
4940 return false;
4944 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
4945 return true;
4948 if ($currentgroup) {
4949 return groups_is_member($currentgroup);
4950 } else {
4951 // no group membership and no accessallgroups means no new discussions
4952 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
4953 return false;
4958 * This function checks whether the user can reply to posts in a forum
4959 * discussion. Use forum_user_can_post_discussion() to check whether the user
4960 * can start discussions.
4962 * @global object
4963 * @global object
4964 * @uses DEBUG_DEVELOPER
4965 * @uses CONTEXT_MODULE
4966 * @uses VISIBLEGROUPS
4967 * @param object $forum forum object
4968 * @param object $discussion
4969 * @param object $user
4970 * @param object $cm
4971 * @param object $course
4972 * @param object $context
4973 * @return bool
4975 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
4976 global $USER, $DB;
4977 if (empty($user)) {
4978 $user = $USER;
4981 // shortcut - guest and not-logged-in users can not post
4982 if (isguestuser($user) or empty($user->id)) {
4983 return false;
4986 if (!isset($discussion->groupid)) {
4987 debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
4988 return false;
4991 if (!$cm) {
4992 debugging('missing cm', DEBUG_DEVELOPER);
4993 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
4994 print_error('invalidcoursemodule');
4998 if (!$course) {
4999 debugging('missing course', DEBUG_DEVELOPER);
5000 if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
5001 print_error('invalidcourseid');
5005 if (!$context) {
5006 $context = context_module::instance($cm->id);
5009 // normal users with temporary guest access can not post, suspended users can not post either
5010 if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
5011 return false;
5014 if ($forum->type == 'news') {
5015 $capname = 'mod/forum:replynews';
5016 } else {
5017 $capname = 'mod/forum:replypost';
5020 if (!has_capability($capname, $context, $user->id)) {
5021 return false;
5024 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
5025 return true;
5028 if (has_capability('moodle/site:accessallgroups', $context)) {
5029 return true;
5032 if ($groupmode == VISIBLEGROUPS) {
5033 if ($discussion->groupid == -1) {
5034 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
5035 return true;
5037 return groups_is_member($discussion->groupid);
5039 } else {
5040 //separate groups
5041 if ($discussion->groupid == -1) {
5042 return false;
5044 return groups_is_member($discussion->groupid);
5049 * Check to ensure a user can view a timed discussion.
5051 * @param object $discussion
5052 * @param object $user
5053 * @param object $context
5054 * @return boolean returns true if they can view post, false otherwise
5056 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
5057 global $CFG;
5059 // Check that the user can view a discussion that is normally hidden due to access times.
5060 if (!empty($CFG->forum_enabletimedposts)) {
5061 $time = time();
5062 if (($discussion->timestart != 0 && $discussion->timestart > $time)
5063 || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
5064 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
5065 return false;
5070 return true;
5074 * Check to ensure a user can view a group discussion.
5076 * @param object $discussion
5077 * @param object $cm
5078 * @param object $context
5079 * @return boolean returns true if they can view post, false otherwise
5081 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
5083 // If it's a grouped discussion, make sure the user is a member.
5084 if ($discussion->groupid > 0) {
5085 $groupmode = groups_get_activity_groupmode($cm);
5086 if ($groupmode == SEPARATEGROUPS) {
5087 return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
5091 return true;
5095 * @global object
5096 * @global object
5097 * @uses DEBUG_DEVELOPER
5098 * @param object $forum
5099 * @param object $discussion
5100 * @param object $context
5101 * @param object $user
5102 * @return bool
5104 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
5105 global $USER, $DB;
5107 if (empty($user) || empty($user->id)) {
5108 $user = $USER;
5111 // retrieve objects (yuk)
5112 if (is_numeric($forum)) {
5113 debugging('missing full forum', DEBUG_DEVELOPER);
5114 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5115 return false;
5118 if (is_numeric($discussion)) {
5119 debugging('missing full discussion', DEBUG_DEVELOPER);
5120 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5121 return false;
5124 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5125 print_error('invalidcoursemodule');
5128 if (!has_capability('mod/forum:viewdiscussion', $context)) {
5129 return false;
5132 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
5133 return false;
5136 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
5137 return false;
5140 if ($forum->type == 'qanda' &&
5141 !forum_user_has_posted($forum->id, $discussion->id, $user->id) &&
5142 !has_capability('mod/forum:viewqandawithoutposting', $context)) {
5143 return false;
5145 return true;
5149 * @global object
5150 * @global object
5151 * @param object $forum
5152 * @param object $discussion
5153 * @param object $post
5154 * @param object $user
5155 * @param object $cm
5156 * @return bool
5158 function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NULL) {
5159 global $CFG, $USER, $DB;
5161 // Context used throughout function.
5162 $modcontext = context_module::instance($cm->id);
5164 // retrieve objects (yuk)
5165 if (is_numeric($forum)) {
5166 debugging('missing full forum', DEBUG_DEVELOPER);
5167 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5168 return false;
5172 if (is_numeric($discussion)) {
5173 debugging('missing full discussion', DEBUG_DEVELOPER);
5174 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5175 return false;
5178 if (is_numeric($post)) {
5179 debugging('missing full post', DEBUG_DEVELOPER);
5180 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
5181 return false;
5185 if (!isset($post->id) && isset($post->parent)) {
5186 $post->id = $post->parent;
5189 if (!$cm) {
5190 debugging('missing cm', DEBUG_DEVELOPER);
5191 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5192 print_error('invalidcoursemodule');
5196 if (empty($user) || empty($user->id)) {
5197 $user = $USER;
5200 $canviewdiscussion = !empty($cm->cache->caps['mod/forum:viewdiscussion']) || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
5201 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
5202 return false;
5205 if (isset($cm->uservisible)) {
5206 if (!$cm->uservisible) {
5207 return false;
5209 } else {
5210 if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
5211 return false;
5215 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
5216 return false;
5219 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
5220 return false;
5223 if ($forum->type == 'qanda') {
5224 $firstpost = forum_get_firstpost_from_discussion($discussion->id);
5225 $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
5227 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)) ||
5228 $firstpost->id == $post->id || $post->userid == $user->id || $firstpost->userid == $user->id ||
5229 has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id));
5231 return true;
5236 * Prints the discussion view screen for a forum.
5238 * @global object
5239 * @global object
5240 * @param object $course The current course object.
5241 * @param object $forum Forum to be printed.
5242 * @param int $maxdiscussions .
5243 * @param string $displayformat The display format to use (optional).
5244 * @param string $sort Sort arguments for database query (optional).
5245 * @param int $groupmode Group mode of the forum (optional).
5246 * @param void $unused (originally current group)
5247 * @param int $page Page mode, page to display (optional).
5248 * @param int $perpage The maximum number of discussions per page(optional)
5249 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
5252 function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '',
5253 $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null) {
5254 global $CFG, $USER, $OUTPUT;
5256 if (!$cm) {
5257 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5258 print_error('invalidcoursemodule');
5261 $context = context_module::instance($cm->id);
5263 if (empty($sort)) {
5264 $sort = "d.timemodified DESC";
5267 $olddiscussionlink = false;
5269 // Sort out some defaults
5270 if ($perpage <= 0) {
5271 $perpage = 0;
5272 $page = -1;
5275 if ($maxdiscussions == 0) {
5276 // all discussions - backwards compatibility
5277 $page = -1;
5278 $perpage = 0;
5279 if ($displayformat == 'plain') {
5280 $displayformat = 'header'; // Abbreviate display by default
5283 } else if ($maxdiscussions > 0) {
5284 $page = -1;
5285 $perpage = $maxdiscussions;
5288 $fullpost = false;
5289 if ($displayformat == 'plain') {
5290 $fullpost = true;
5294 // Decide if current user is allowed to see ALL the current discussions or not
5296 // First check the group stuff
5297 if ($currentgroup == -1 or $groupmode == -1) {
5298 $groupmode = groups_get_activity_groupmode($cm, $course);
5299 $currentgroup = groups_get_activity_group($cm);
5302 $groups = array(); //cache
5304 // If the user can post discussions, then this is a good place to put the
5305 // button for it. We do not show the button if we are showing site news
5306 // and the current user is a guest.
5308 $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
5309 if (!$canstart and $forum->type !== 'news') {
5310 if (isguestuser() or !isloggedin()) {
5311 $canstart = true;
5313 if (!is_enrolled($context) and !is_viewing($context)) {
5314 // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
5315 // normal users with temporary guest access see this button too, they are asked to enrol instead
5316 // do not show the button to users with suspended enrolments here
5317 $canstart = enrol_selfenrol_available($course->id);
5321 if ($canstart) {
5322 echo '<div class="singlebutton forumaddnew">';
5323 echo "<form id=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
5324 echo '<div>';
5325 echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
5326 switch ($forum->type) {
5327 case 'news':
5328 case 'blog':
5329 $buttonadd = get_string('addanewtopic', 'forum');
5330 break;
5331 case 'qanda':
5332 $buttonadd = get_string('addanewquestion', 'forum');
5333 break;
5334 default:
5335 $buttonadd = get_string('addanewdiscussion', 'forum');
5336 break;
5338 echo '<input type="submit" value="'.$buttonadd.'" />';
5339 echo '</div>';
5340 echo '</form>';
5341 echo "</div>\n";
5343 } else if (isguestuser() or !isloggedin() or $forum->type == 'news' or
5344 $forum->type == 'qanda' and !has_capability('mod/forum:addquestion', $context) or
5345 $forum->type != 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
5346 // no button and no info
5348 } else if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
5349 // inform users why they can not post new discussion
5350 if (!$currentgroup) {
5351 echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
5352 } else if (!groups_is_member($currentgroup)) {
5353 echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
5357 // Get all the recent discussions we're allowed to see
5359 $getuserlastmodified = ($displayformat == 'header');
5361 if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
5362 echo '<div class="forumnodiscuss">';
5363 if ($forum->type == 'news') {
5364 echo '('.get_string('nonews', 'forum').')';
5365 } else if ($forum->type == 'qanda') {
5366 echo '('.get_string('noquestions','forum').')';
5367 } else {
5368 echo '('.get_string('nodiscussions', 'forum').')';
5370 echo "</div>\n";
5371 return;
5374 // If we want paging
5375 if ($page != -1) {
5376 ///Get the number of discussions found
5377 $numdiscussions = forum_get_discussions_count($cm);
5379 ///Show the paging bar
5380 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5381 if ($numdiscussions > 1000) {
5382 // saves some memory on sites with very large forums
5383 $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
5384 } else {
5385 $replies = forum_count_discussion_replies($forum->id);
5388 } else {
5389 $replies = forum_count_discussion_replies($forum->id);
5391 if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
5392 $olddiscussionlink = true;
5396 $canviewparticipants = has_capability('moodle/course:viewparticipants',$context);
5398 $strdatestring = get_string('strftimerecentfull');
5400 // Check if the forum is tracked.
5401 if ($cantrack = forum_tp_can_track_forums($forum)) {
5402 $forumtracked = forum_tp_is_tracked($forum);
5403 } else {
5404 $forumtracked = false;
5407 if ($forumtracked) {
5408 $unreads = forum_get_discussions_unread($cm);
5409 } else {
5410 $unreads = array();
5413 if ($displayformat == 'header') {
5414 echo '<table cellspacing="0" class="forumheaderlist">';
5415 echo '<thead>';
5416 echo '<tr>';
5417 echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
5418 echo '<th class="header author" colspan="2" scope="col">'.get_string('startedby', 'forum').'</th>';
5419 if ($groupmode > 0) {
5420 echo '<th class="header group" scope="col">'.get_string('group').'</th>';
5422 if (has_capability('mod/forum:viewdiscussion', $context)) {
5423 echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
5424 // If the forum can be tracked, display the unread column.
5425 if ($cantrack) {
5426 echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
5427 if ($forumtracked) {
5428 echo '<a title="'.get_string('markallread', 'forum').
5429 '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
5430 $forum->id.'&amp;mark=read&amp;returnpage=view.php">'.
5431 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.get_string('markallread', 'forum').'" /></a>';
5433 echo '</th>';
5436 echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
5437 if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $context)) {
5438 if (\mod_forum\subscriptions::is_subscribable($forum)) {
5439 echo '<th class="header discussionsubscription" scope="col">';
5440 echo forum_get_discussion_subscription_icon_preloaders();
5441 echo '</th>';
5444 echo '</tr>';
5445 echo '</thead>';
5446 echo '<tbody>';
5449 foreach ($discussions as $discussion) {
5450 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) &&
5451 !forum_user_has_posted($forum->id, $discussion->discussion, $USER->id)) {
5452 $canviewparticipants = false;
5455 if (!empty($replies[$discussion->discussion])) {
5456 $discussion->replies = $replies[$discussion->discussion]->replies;
5457 $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
5458 } else {
5459 $discussion->replies = 0;
5462 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
5463 // All posts are read in this case.
5464 if (!$forumtracked) {
5465 $discussion->unread = '-';
5466 } else if (empty($USER)) {
5467 $discussion->unread = 0;
5468 } else {
5469 if (empty($unreads[$discussion->discussion])) {
5470 $discussion->unread = 0;
5471 } else {
5472 $discussion->unread = $unreads[$discussion->discussion];
5476 if (isloggedin()) {
5477 $ownpost = ($discussion->userid == $USER->id);
5478 } else {
5479 $ownpost=false;
5481 // Use discussion name instead of subject of first post
5482 $discussion->subject = $discussion->name;
5484 switch ($displayformat) {
5485 case 'header':
5486 if ($groupmode > 0) {
5487 if (isset($groups[$discussion->groupid])) {
5488 $group = $groups[$discussion->groupid];
5489 } else {
5490 $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
5492 } else {
5493 $group = -1;
5495 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
5496 $canviewparticipants, $context);
5497 break;
5498 default:
5499 $link = false;
5501 if ($discussion->replies) {
5502 $link = true;
5503 } else {
5504 $modcontext = context_module::instance($cm->id);
5505 $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
5508 $discussion->forum = $forum->id;
5510 forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
5511 '', null, true, $forumtracked);
5512 break;
5516 if ($displayformat == "header") {
5517 echo '</tbody>';
5518 echo '</table>';
5521 if ($olddiscussionlink) {
5522 if ($forum->type == 'news') {
5523 $strolder = get_string('oldertopics', 'forum');
5524 } else {
5525 $strolder = get_string('olderdiscussions', 'forum');
5527 echo '<div class="forumolddiscuss">';
5528 echo '<a href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'&amp;showall=1">';
5529 echo $strolder.'</a> ...</div>';
5532 if ($page != -1) { ///Show the paging bar
5533 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5539 * Prints a forum discussion
5541 * @uses CONTEXT_MODULE
5542 * @uses FORUM_MODE_FLATNEWEST
5543 * @uses FORUM_MODE_FLATOLDEST
5544 * @uses FORUM_MODE_THREADED
5545 * @uses FORUM_MODE_NESTED
5546 * @param stdClass $course
5547 * @param stdClass $cm
5548 * @param stdClass $forum
5549 * @param stdClass $discussion
5550 * @param stdClass $post
5551 * @param int $mode
5552 * @param mixed $canreply
5553 * @param bool $canrate
5555 function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
5556 global $USER, $CFG;
5558 require_once($CFG->dirroot.'/rating/lib.php');
5560 $ownpost = (isloggedin() && $USER->id == $post->userid);
5562 $modcontext = context_module::instance($cm->id);
5563 if ($canreply === NULL) {
5564 $reply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
5565 } else {
5566 $reply = $canreply;
5569 // $cm holds general cache for forum functions
5570 $cm->cache = new stdClass;
5571 $cm->cache->groups = groups_get_all_groups($course->id, 0, $cm->groupingid);
5572 $cm->cache->usersgroups = array();
5574 $posters = array();
5576 // preload all posts - TODO: improve...
5577 if ($mode == FORUM_MODE_FLATNEWEST) {
5578 $sort = "p.created DESC";
5579 } else {
5580 $sort = "p.created ASC";
5583 $forumtracked = forum_tp_is_tracked($forum);
5584 $posts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
5585 $post = $posts[$post->id];
5587 foreach ($posts as $pid=>$p) {
5588 $posters[$p->userid] = $p->userid;
5591 // preload all groups of ppl that posted in this discussion
5592 if ($postersgroups = groups_get_all_groups($course->id, $posters, $cm->groupingid, 'gm.id, gm.groupid, gm.userid')) {
5593 foreach($postersgroups as $pg) {
5594 if (!isset($cm->cache->usersgroups[$pg->userid])) {
5595 $cm->cache->usersgroups[$pg->userid] = array();
5597 $cm->cache->usersgroups[$pg->userid][$pg->groupid] = $pg->groupid;
5599 unset($postersgroups);
5602 //load ratings
5603 if ($forum->assessed != RATING_AGGREGATE_NONE) {
5604 $ratingoptions = new stdClass;
5605 $ratingoptions->context = $modcontext;
5606 $ratingoptions->component = 'mod_forum';
5607 $ratingoptions->ratingarea = 'post';
5608 $ratingoptions->items = $posts;
5609 $ratingoptions->aggregate = $forum->assessed;//the aggregation method
5610 $ratingoptions->scaleid = $forum->scale;
5611 $ratingoptions->userid = $USER->id;
5612 if ($forum->type == 'single' or !$discussion->id) {
5613 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/view.php?id=$cm->id";
5614 } else {
5615 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id";
5617 $ratingoptions->assesstimestart = $forum->assesstimestart;
5618 $ratingoptions->assesstimefinish = $forum->assesstimefinish;
5620 $rm = new rating_manager();
5621 $posts = $rm->get_ratings($ratingoptions);
5625 $post->forum = $forum->id; // Add the forum id to the post object, later used by forum_print_post
5626 $post->forumtype = $forum->type;
5628 $post->subject = format_string($post->subject);
5630 $postread = !empty($post->postread);
5632 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false,
5633 '', '', $postread, true, $forumtracked);
5635 switch ($mode) {
5636 case FORUM_MODE_FLATOLDEST :
5637 case FORUM_MODE_FLATNEWEST :
5638 default:
5639 forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts);
5640 break;
5642 case FORUM_MODE_THREADED :
5643 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $reply, $forumtracked, $posts);
5644 break;
5646 case FORUM_MODE_NESTED :
5647 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5648 break;
5654 * @global object
5655 * @global object
5656 * @uses FORUM_MODE_FLATNEWEST
5657 * @param object $course
5658 * @param object $cm
5659 * @param object $forum
5660 * @param object $discussion
5661 * @param object $post
5662 * @param object $mode
5663 * @param bool $reply
5664 * @param bool $forumtracked
5665 * @param array $posts
5666 * @return void
5668 function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts) {
5669 global $USER, $CFG;
5671 $link = false;
5673 if ($mode == FORUM_MODE_FLATNEWEST) {
5674 $sort = "ORDER BY created DESC";
5675 } else {
5676 $sort = "ORDER BY created ASC";
5679 foreach ($posts as $post) {
5680 if (!$post->parent) {
5681 continue;
5683 $post->subject = format_string($post->subject);
5684 $ownpost = ($USER->id == $post->userid);
5686 $postread = !empty($post->postread);
5688 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5689 '', '', $postread, true, $forumtracked);
5694 * @todo Document this function
5696 * @global object
5697 * @global object
5698 * @uses CONTEXT_MODULE
5699 * @return void
5701 function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $reply, $forumtracked, $posts) {
5702 global $USER, $CFG;
5704 $link = false;
5706 if (!empty($posts[$parent->id]->children)) {
5707 $posts = $posts[$parent->id]->children;
5709 $modcontext = context_module::instance($cm->id);
5710 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
5712 foreach ($posts as $post) {
5714 echo '<div class="indent">';
5715 if ($depth > 0) {
5716 $ownpost = ($USER->id == $post->userid);
5717 $post->subject = format_string($post->subject);
5719 $postread = !empty($post->postread);
5721 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5722 '', '', $postread, true, $forumtracked);
5723 } else {
5724 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
5725 echo "</div>\n";
5726 continue;
5728 $by = new stdClass();
5729 $by->name = fullname($post, $canviewfullnames);
5730 $by->date = userdate($post->modified);
5732 if ($forumtracked) {
5733 if (!empty($post->postread)) {
5734 $style = '<span class="forumthread read">';
5735 } else {
5736 $style = '<span class="forumthread unread">';
5738 } else {
5739 $style = '<span class="forumthread">';
5741 echo $style."<a name=\"$post->id\"></a>".
5742 "<a href=\"discuss.php?d=$post->discussion&amp;parent=$post->id\">".format_string($post->subject,true)."</a> ";
5743 print_string("bynameondate", "forum", $by);
5744 echo "</span>";
5747 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $reply, $forumtracked, $posts);
5748 echo "</div>\n";
5754 * @todo Document this function
5755 * @global object
5756 * @global object
5757 * @return void
5759 function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $reply, $forumtracked, $posts) {
5760 global $USER, $CFG;
5762 $link = false;
5764 if (!empty($posts[$parent->id]->children)) {
5765 $posts = $posts[$parent->id]->children;
5767 foreach ($posts as $post) {
5769 echo '<div class="indent">';
5770 if (!isloggedin()) {
5771 $ownpost = false;
5772 } else {
5773 $ownpost = ($USER->id == $post->userid);
5776 $post->subject = format_string($post->subject);
5777 $postread = !empty($post->postread);
5779 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5780 '', '', $postread, true, $forumtracked);
5781 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5782 echo "</div>\n";
5788 * Returns all forum posts since a given time in specified forum.
5790 * @todo Document this functions args
5791 * @global object
5792 * @global object
5793 * @global object
5794 * @global object
5796 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
5797 global $CFG, $COURSE, $USER, $DB;
5799 if ($COURSE->id == $courseid) {
5800 $course = $COURSE;
5801 } else {
5802 $course = $DB->get_record('course', array('id' => $courseid));
5805 $modinfo = get_fast_modinfo($course);
5807 $cm = $modinfo->cms[$cmid];
5808 $params = array($timestart, $cm->instance);
5810 if ($userid) {
5811 $userselect = "AND u.id = ?";
5812 $params[] = $userid;
5813 } else {
5814 $userselect = "";
5817 if ($groupid) {
5818 $groupselect = "AND d.groupid = ?";
5819 $params[] = $groupid;
5820 } else {
5821 $groupselect = "";
5824 $allnames = get_all_user_name_fields(true, 'u');
5825 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
5826 d.timestart, d.timeend, d.userid AS duserid,
5827 $allnames, u.email, u.picture, u.imagealt, u.email
5828 FROM {forum_posts} p
5829 JOIN {forum_discussions} d ON d.id = p.discussion
5830 JOIN {forum} f ON f.id = d.forum
5831 JOIN {user} u ON u.id = p.userid
5832 WHERE p.created > ? AND f.id = ?
5833 $userselect $groupselect
5834 ORDER BY p.id ASC", $params)) { // order by initial posting date
5835 return;
5838 $groupmode = groups_get_activity_groupmode($cm, $course);
5839 $cm_context = context_module::instance($cm->id);
5840 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
5841 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
5843 $printposts = array();
5844 foreach ($posts as $post) {
5846 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
5847 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
5848 if (!$viewhiddentimed) {
5849 continue;
5853 if ($groupmode) {
5854 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
5855 // oki (Open discussions have groupid -1)
5856 } else {
5857 // separate mode
5858 if (isguestuser()) {
5859 // shortcut
5860 continue;
5863 if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
5864 continue;
5869 $printposts[] = $post;
5872 if (!$printposts) {
5873 return;
5876 $aname = format_string($cm->name,true);
5878 foreach ($printposts as $post) {
5879 $tmpactivity = new stdClass();
5881 $tmpactivity->type = 'forum';
5882 $tmpactivity->cmid = $cm->id;
5883 $tmpactivity->name = $aname;
5884 $tmpactivity->sectionnum = $cm->sectionnum;
5885 $tmpactivity->timestamp = $post->modified;
5887 $tmpactivity->content = new stdClass();
5888 $tmpactivity->content->id = $post->id;
5889 $tmpactivity->content->discussion = $post->discussion;
5890 $tmpactivity->content->subject = format_string($post->subject);
5891 $tmpactivity->content->parent = $post->parent;
5893 $tmpactivity->user = new stdClass();
5894 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
5895 $additionalfields = explode(',', user_picture::fields());
5896 $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
5897 $tmpactivity->user->id = $post->userid;
5899 $activities[$index++] = $tmpactivity;
5902 return;
5906 * @todo Document this function
5907 * @global object
5909 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
5910 global $CFG, $OUTPUT;
5912 if ($activity->content->parent) {
5913 $class = 'reply';
5914 } else {
5915 $class = 'discussion';
5918 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
5920 echo "<tr><td class=\"userpicture\" valign=\"top\">";
5921 echo $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid));
5922 echo "</td><td class=\"$class\">";
5924 if ($activity->content->parent) {
5925 $class = 'title';
5926 } else {
5927 // Bold the title of new discussions so they stand out.
5928 $class = 'title bold';
5930 echo "<div class=\"{$class}\">";
5931 if ($detail) {
5932 $aname = s($activity->name);
5933 echo "<img src=\"" . $OUTPUT->pix_url('icon', $activity->type) . "\" ".
5934 "class=\"icon\" alt=\"{$aname}\" />";
5936 echo "<a href=\"$CFG->wwwroot/mod/forum/discuss.php?d={$activity->content->discussion}"
5937 ."#p{$activity->content->id}\">{$activity->content->subject}</a>";
5938 echo '</div>';
5940 echo '<div class="user">';
5941 $fullname = fullname($activity->user, $viewfullnames);
5942 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
5943 ."{$fullname}</a> - ".userdate($activity->timestamp);
5944 echo '</div>';
5945 echo "</td></tr></table>";
5947 return;
5951 * recursively sets the discussion field to $discussionid on $postid and all its children
5952 * used when pruning a post
5954 * @global object
5955 * @param int $postid
5956 * @param int $discussionid
5957 * @return bool
5959 function forum_change_discussionid($postid, $discussionid) {
5960 global $DB;
5961 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
5962 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
5963 foreach ($posts as $post) {
5964 forum_change_discussionid($post->id, $discussionid);
5967 return true;
5971 * Prints the editing button on subscribers page
5973 * @global object
5974 * @global object
5975 * @param int $courseid
5976 * @param int $forumid
5977 * @return string
5979 function forum_update_subscriptions_button($courseid, $forumid) {
5980 global $CFG, $USER;
5982 if (!empty($USER->subscriptionsediting)) {
5983 $string = get_string('turneditingoff');
5984 $edit = "off";
5985 } else {
5986 $string = get_string('turneditingon');
5987 $edit = "on";
5990 return "<form method=\"get\" action=\"$CFG->wwwroot/mod/forum/subscribers.php\">".
5991 "<input type=\"hidden\" name=\"id\" value=\"$forumid\" />".
5992 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5993 "<input type=\"submit\" value=\"$string\" /></form>";
5996 // Functions to do with read tracking.
5999 * Mark posts as read.
6001 * @global object
6002 * @global object
6003 * @param object $user object
6004 * @param array $postids array of post ids
6005 * @return boolean success
6007 function forum_tp_mark_posts_read($user, $postids) {
6008 global $CFG, $DB;
6010 if (!forum_tp_can_track_forums(false, $user)) {
6011 return true;
6014 $status = true;
6016 $now = time();
6017 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6019 if (empty($postids)) {
6020 return true;
6022 } else if (count($postids) > 200) {
6023 while ($part = array_splice($postids, 0, 200)) {
6024 $status = forum_tp_mark_posts_read($user, $part) && $status;
6026 return $status;
6029 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid');
6031 $insertparams = array(
6032 'userid1' => $user->id,
6033 'userid2' => $user->id,
6034 'userid3' => $user->id,
6035 'firstread' => $now,
6036 'lastread' => $now,
6037 'cutoffdate' => $cutoffdate,
6039 $params = array_merge($postidparams, $insertparams);
6041 if ($CFG->forum_allowforcedreadtracking) {
6042 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6043 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))";
6044 } else {
6045 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6046 AND tf.id IS NULL)";
6049 // First insert any new entries.
6050 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6052 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
6053 FROM {forum_posts} p
6054 JOIN {forum_discussions} d ON d.id = p.discussion
6055 JOIN {forum} f ON f.id = d.forum
6056 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
6057 LEFT JOIN {forum_read} fr ON (
6058 fr.userid = :userid3
6059 AND fr.postid = p.id
6060 AND fr.discussionid = d.id
6061 AND fr.forumid = f.id
6063 WHERE p.id $usql
6064 AND p.modified >= :cutoffdate
6065 $trackingsql
6066 AND fr.id IS NULL";
6068 $status = $DB->execute($sql, $params) && $status;
6070 // Then update all records.
6071 $updateparams = array(
6072 'userid' => $user->id,
6073 'lastread' => $now,
6075 $params = array_merge($postidparams, $updateparams);
6076 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
6077 userid = :userid
6078 AND lastread <> :lastread
6079 AND postid ' . $usql,
6080 $params) && $status;
6082 return $status;
6086 * Mark post as read.
6087 * @global object
6088 * @global object
6089 * @param int $userid
6090 * @param int $postid
6092 function forum_tp_add_read_record($userid, $postid) {
6093 global $CFG, $DB;
6095 $now = time();
6096 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6098 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
6099 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6101 SELECT ?, p.id, p.discussion, d.forum, ?, ?
6102 FROM {forum_posts} p
6103 JOIN {forum_discussions} d ON d.id = p.discussion
6104 WHERE p.id = ? AND p.modified >= ?";
6105 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
6107 } else {
6108 $sql = "UPDATE {forum_read}
6109 SET lastread = ?
6110 WHERE userid = ? AND postid = ?";
6111 return $DB->execute($sql, array($now, $userid, $userid));
6116 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
6118 * @return bool
6120 function forum_tp_mark_post_read($userid, $post, $forumid) {
6121 if (!forum_tp_is_post_old($post)) {
6122 return forum_tp_add_read_record($userid, $post->id);
6123 } else {
6124 return true;
6129 * Marks a whole forum as read, for a given user
6131 * @global object
6132 * @global object
6133 * @param object $user
6134 * @param int $forumid
6135 * @param int|bool $groupid
6136 * @return bool
6138 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
6139 global $CFG, $DB;
6141 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6143 $groupsel = "";
6144 $params = array($user->id, $forumid, $cutoffdate);
6146 if ($groupid !== false) {
6147 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
6148 $params[] = $groupid;
6151 $sql = "SELECT p.id
6152 FROM {forum_posts} p
6153 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
6154 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6155 WHERE d.forum = ?
6156 AND p.modified >= ? AND r.id is NULL
6157 $groupsel";
6159 if ($posts = $DB->get_records_sql($sql, $params)) {
6160 $postids = array_keys($posts);
6161 return forum_tp_mark_posts_read($user, $postids);
6164 return true;
6168 * Marks a whole discussion as read, for a given user
6170 * @global object
6171 * @global object
6172 * @param object $user
6173 * @param int $discussionid
6174 * @return bool
6176 function forum_tp_mark_discussion_read($user, $discussionid) {
6177 global $CFG, $DB;
6179 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6181 $sql = "SELECT p.id
6182 FROM {forum_posts} p
6183 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6184 WHERE p.discussion = ?
6185 AND p.modified >= ? AND r.id is NULL";
6187 if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) {
6188 $postids = array_keys($posts);
6189 return forum_tp_mark_posts_read($user, $postids);
6192 return true;
6196 * @global object
6197 * @param int $userid
6198 * @param object $post
6200 function forum_tp_is_post_read($userid, $post) {
6201 global $DB;
6202 return (forum_tp_is_post_old($post) ||
6203 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id)));
6207 * @global object
6208 * @param object $post
6209 * @param int $time Defautls to time()
6211 function forum_tp_is_post_old($post, $time=null) {
6212 global $CFG;
6214 if (is_null($time)) {
6215 $time = time();
6217 return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600)));
6221 * Returns the count of records for the provided user and course.
6222 * Please note that group access is ignored!
6224 * @global object
6225 * @global object
6226 * @param int $userid
6227 * @param int $courseid
6228 * @return array
6230 function forum_tp_get_course_unread_posts($userid, $courseid) {
6231 global $CFG, $DB;
6233 $now = round(time(), -2); // DB cache friendliness.
6234 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 60 * 60);
6235 $params = array($userid, $userid, $courseid, $cutoffdate, $userid);
6237 if (!empty($CFG->forum_enabletimedposts)) {
6238 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6239 $params[] = $now;
6240 $params[] = $now;
6241 } else {
6242 $timedsql = "";
6245 if ($CFG->forum_allowforcedreadtracking) {
6246 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6247 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL
6248 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))";
6249 } else {
6250 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6251 AND tf.id IS NULL
6252 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)";
6255 $sql = "SELECT f.id, COUNT(p.id) AS unread
6256 FROM {forum_posts} p
6257 JOIN {forum_discussions} d ON d.id = p.discussion
6258 JOIN {forum} f ON f.id = d.forum
6259 JOIN {course} c ON c.id = f.course
6260 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6261 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id)
6262 WHERE f.course = ?
6263 AND p.modified >= ? AND r.id is NULL
6264 $trackingsql
6265 $timedsql
6266 GROUP BY f.id";
6268 if ($return = $DB->get_records_sql($sql, $params)) {
6269 return $return;
6272 return array();
6276 * Returns the count of records for the provided user and forum and [optionally] group.
6278 * @global object
6279 * @global object
6280 * @global object
6281 * @param object $cm
6282 * @param object $course
6283 * @return int
6285 function forum_tp_count_forum_unread_posts($cm, $course) {
6286 global $CFG, $USER, $DB;
6288 static $readcache = array();
6290 $forumid = $cm->instance;
6292 if (!isset($readcache[$course->id])) {
6293 $readcache[$course->id] = array();
6294 if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
6295 foreach ($counts as $count) {
6296 $readcache[$course->id][$count->id] = $count->unread;
6301 if (empty($readcache[$course->id][$forumid])) {
6302 // no need to check group mode ;-)
6303 return 0;
6306 $groupmode = groups_get_activity_groupmode($cm, $course);
6308 if ($groupmode != SEPARATEGROUPS) {
6309 return $readcache[$course->id][$forumid];
6312 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
6313 return $readcache[$course->id][$forumid];
6316 require_once($CFG->dirroot.'/course/lib.php');
6318 $modinfo = get_fast_modinfo($course);
6320 $mygroups = $modinfo->get_groups($cm->groupingid);
6322 // add all groups posts
6323 $mygroups[-1] = -1;
6325 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);
6327 $now = round(time(), -2); // db cache friendliness
6328 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
6329 $params = array($USER->id, $forumid, $cutoffdate);
6331 if (!empty($CFG->forum_enabletimedposts)) {
6332 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6333 $params[] = $now;
6334 $params[] = $now;
6335 } else {
6336 $timedsql = "";
6339 $params = array_merge($params, $groups_params);
6341 $sql = "SELECT COUNT(p.id)
6342 FROM {forum_posts} p
6343 JOIN {forum_discussions} d ON p.discussion = d.id
6344 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6345 WHERE d.forum = ?
6346 AND p.modified >= ? AND r.id is NULL
6347 $timedsql
6348 AND d.groupid $groups_sql";
6350 return $DB->get_field_sql($sql, $params);
6354 * Deletes read records for the specified index. At least one parameter must be specified.
6356 * @global object
6357 * @param int $userid
6358 * @param int $postid
6359 * @param int $discussionid
6360 * @param int $forumid
6361 * @return bool
6363 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
6364 global $DB;
6365 $params = array();
6367 $select = '';
6368 if ($userid > -1) {
6369 if ($select != '') $select .= ' AND ';
6370 $select .= 'userid = ?';
6371 $params[] = $userid;
6373 if ($postid > -1) {
6374 if ($select != '') $select .= ' AND ';
6375 $select .= 'postid = ?';
6376 $params[] = $postid;
6378 if ($discussionid > -1) {
6379 if ($select != '') $select .= ' AND ';
6380 $select .= 'discussionid = ?';
6381 $params[] = $discussionid;
6383 if ($forumid > -1) {
6384 if ($select != '') $select .= ' AND ';
6385 $select .= 'forumid = ?';
6386 $params[] = $forumid;
6388 if ($select == '') {
6389 return false;
6391 else {
6392 return $DB->delete_records_select('forum_read', $select, $params);
6396 * Get a list of forums not tracked by the user.
6398 * @global object
6399 * @global object
6400 * @param int $userid The id of the user to use.
6401 * @param int $courseid The id of the course being checked.
6402 * @return mixed An array indexed by forum id, or false.
6404 function forum_tp_get_untracked_forums($userid, $courseid) {
6405 global $CFG, $DB;
6407 if ($CFG->forum_allowforcedreadtracking) {
6408 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6409 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL
6410 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6411 } else {
6412 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6413 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6414 AND (ft.id IS NOT NULL
6415 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6418 $sql = "SELECT f.id
6419 FROM {forum} f
6420 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
6421 WHERE f.course = ?
6422 $trackingsql";
6424 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
6425 foreach ($forums as $forum) {
6426 $forums[$forum->id] = $forum;
6428 return $forums;
6430 } else {
6431 return array();
6436 * Determine if a user can track forums and optionally a particular forum.
6437 * Checks the site settings, the user settings and the forum settings (if
6438 * requested).
6440 * @global object
6441 * @global object
6442 * @global object
6443 * @param mixed $forum The forum object to test, or the int id (optional).
6444 * @param mixed $userid The user object to check for (optional).
6445 * @return boolean
6447 function forum_tp_can_track_forums($forum=false, $user=false) {
6448 global $USER, $CFG, $DB;
6450 // if possible, avoid expensive
6451 // queries
6452 if (empty($CFG->forum_trackreadposts)) {
6453 return false;
6456 if ($user === false) {
6457 $user = $USER;
6460 if (isguestuser($user) or empty($user->id)) {
6461 return false;
6464 if ($forum === false) {
6465 if ($CFG->forum_allowforcedreadtracking) {
6466 // Since we can force tracking, assume yes without a specific forum.
6467 return true;
6468 } else {
6469 return (bool)$user->trackforums;
6473 // Work toward always passing an object...
6474 if (is_numeric($forum)) {
6475 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6476 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
6479 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6480 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6482 if ($CFG->forum_allowforcedreadtracking) {
6483 // If we allow forcing, then forced forums takes procidence over user setting.
6484 return ($forumforced || ($forumallows && (!empty($user->trackforums) && (bool)$user->trackforums)));
6485 } else {
6486 // If we don't allow forcing, user setting trumps.
6487 return ($forumforced || $forumallows) && !empty($user->trackforums);
6492 * Tells whether a specific forum is tracked by the user. A user can optionally
6493 * be specified. If not specified, the current user is assumed.
6495 * @global object
6496 * @global object
6497 * @global object
6498 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
6499 * @param int $userid The id of the user being checked (optional).
6500 * @return boolean
6502 function forum_tp_is_tracked($forum, $user=false) {
6503 global $USER, $CFG, $DB;
6505 if ($user === false) {
6506 $user = $USER;
6509 if (isguestuser($user) or empty($user->id)) {
6510 return false;
6513 // Work toward always passing an object...
6514 if (is_numeric($forum)) {
6515 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6516 $forum = $DB->get_record('forum', array('id' => $forum));
6519 if (!forum_tp_can_track_forums($forum, $user)) {
6520 return false;
6523 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6524 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6525 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id));
6527 if ($CFG->forum_allowforcedreadtracking) {
6528 return $forumforced || ($forumallows && $userpref === false);
6529 } else {
6530 return ($forumallows || $forumforced) && $userpref === false;
6535 * @global object
6536 * @global object
6537 * @param int $forumid
6538 * @param int $userid
6540 function forum_tp_start_tracking($forumid, $userid=false) {
6541 global $USER, $DB;
6543 if ($userid === false) {
6544 $userid = $USER->id;
6547 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
6551 * @global object
6552 * @global object
6553 * @param int $forumid
6554 * @param int $userid
6556 function forum_tp_stop_tracking($forumid, $userid=false) {
6557 global $USER, $DB;
6559 if ($userid === false) {
6560 $userid = $USER->id;
6563 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
6564 $track_prefs = new stdClass();
6565 $track_prefs->userid = $userid;
6566 $track_prefs->forumid = $forumid;
6567 $DB->insert_record('forum_track_prefs', $track_prefs);
6570 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
6575 * Clean old records from the forum_read table.
6576 * @global object
6577 * @global object
6578 * @return void
6580 function forum_tp_clean_read_records() {
6581 global $CFG, $DB;
6583 if (!isset($CFG->forum_oldpostdays)) {
6584 return;
6586 // Look for records older than the cutoffdate that are still in the forum_read table.
6587 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6589 //first get the oldest tracking present - we need tis to speedup the next delete query
6590 $sql = "SELECT MIN(fp.modified) AS first
6591 FROM {forum_posts} fp
6592 JOIN {forum_read} fr ON fr.postid=fp.id";
6593 if (!$first = $DB->get_field_sql($sql)) {
6594 // nothing to delete;
6595 return;
6598 // now delete old tracking info
6599 $sql = "DELETE
6600 FROM {forum_read}
6601 WHERE postid IN (SELECT fp.id
6602 FROM {forum_posts} fp
6603 WHERE fp.modified >= ? AND fp.modified < ?)";
6604 $DB->execute($sql, array($first, $cutoffdate));
6608 * Sets the last post for a given discussion
6610 * @global object
6611 * @global object
6612 * @param into $discussionid
6613 * @return bool|int
6615 function forum_discussion_update_last_post($discussionid) {
6616 global $CFG, $DB;
6618 // Check the given discussion exists
6619 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
6620 return false;
6623 // Use SQL to find the last post for this discussion
6624 $sql = "SELECT id, userid, modified
6625 FROM {forum_posts}
6626 WHERE discussion=?
6627 ORDER BY modified DESC";
6629 // Lets go find the last post
6630 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
6631 $lastpost = reset($lastposts);
6632 $discussionobject = new stdClass();
6633 $discussionobject->id = $discussionid;
6634 $discussionobject->usermodified = $lastpost->userid;
6635 $discussionobject->timemodified = $lastpost->modified;
6636 $DB->update_record('forum_discussions', $discussionobject);
6637 return $lastpost->id;
6640 // To get here either we couldn't find a post for the discussion (weird)
6641 // or we couldn't update the discussion record (weird x2)
6642 return false;
6647 * List the actions that correspond to a view of this module.
6648 * This is used by the participation report.
6650 * Note: This is not used by new logging system. Event with
6651 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
6652 * be considered as view action.
6654 * @return array
6656 function forum_get_view_actions() {
6657 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
6661 * List the actions that correspond to a post of this module.
6662 * This is used by the participation report.
6664 * Note: This is not used by new logging system. Event with
6665 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
6666 * will be considered as post action.
6668 * @return array
6670 function forum_get_post_actions() {
6671 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
6675 * Returns a warning object if a user has reached the number of posts equal to
6676 * the warning/blocking setting, or false if there is no warning to show.
6678 * @param int|stdClass $forum the forum id or the forum object
6679 * @param stdClass $cm the course module
6680 * @return stdClass|bool returns an object with the warning information, else
6681 * returns false if no warning is required.
6683 function forum_check_throttling($forum, $cm = null) {
6684 global $CFG, $DB, $USER;
6686 if (is_numeric($forum)) {
6687 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST);
6690 if (!is_object($forum)) {
6691 return false; // This is broken.
6694 if (!$cm) {
6695 $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST);
6698 if (empty($forum->blockafter)) {
6699 return false;
6702 if (empty($forum->blockperiod)) {
6703 return false;
6706 $modcontext = context_module::instance($cm->id);
6707 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
6708 return false;
6711 // Get the number of posts in the last period we care about.
6712 $timenow = time();
6713 $timeafter = $timenow - $forum->blockperiod;
6714 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
6715 JOIN {forum_discussions} d
6716 ON p.discussion = d.id WHERE d.forum = ?
6717 AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter));
6719 $a = new stdClass();
6720 $a->blockafter = $forum->blockafter;
6721 $a->numposts = $numposts;
6722 $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
6724 if ($forum->blockafter <= $numposts) {
6725 $warning = new stdClass();
6726 $warning->canpost = false;
6727 $warning->errorcode = 'forumblockingtoomanyposts';
6728 $warning->module = 'error';
6729 $warning->additional = $a;
6730 $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id;
6732 return $warning;
6735 if ($forum->warnafter <= $numposts) {
6736 $warning = new stdClass();
6737 $warning->canpost = true;
6738 $warning->errorcode = 'forumblockingalmosttoomanyposts';
6739 $warning->module = 'forum';
6740 $warning->additional = $a;
6741 $warning->link = null;
6743 return $warning;
6748 * Throws an error if the user is no longer allowed to post due to having reached
6749 * or exceeded the number of posts specified in 'Post threshold for blocking'
6750 * setting.
6752 * @since Moodle 2.5
6753 * @param stdClass $thresholdwarning the warning information returned
6754 * from the function forum_check_throttling.
6756 function forum_check_blocking_threshold($thresholdwarning) {
6757 if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
6758 print_error($thresholdwarning->errorcode,
6759 $thresholdwarning->module,
6760 $thresholdwarning->link,
6761 $thresholdwarning->additional);
6767 * Removes all grades from gradebook
6769 * @global object
6770 * @global object
6771 * @param int $courseid
6772 * @param string $type optional
6774 function forum_reset_gradebook($courseid, $type='') {
6775 global $CFG, $DB;
6777 $wheresql = '';
6778 $params = array($courseid);
6779 if ($type) {
6780 $wheresql = "AND f.type=?";
6781 $params[] = $type;
6784 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
6785 FROM {forum} f, {course_modules} cm, {modules} m
6786 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
6788 if ($forums = $DB->get_records_sql($sql, $params)) {
6789 foreach ($forums as $forum) {
6790 forum_grade_item_update($forum, 'reset');
6796 * This function is used by the reset_course_userdata function in moodlelib.
6797 * This function will remove all posts from the specified forum
6798 * and clean up any related data.
6800 * @global object
6801 * @global object
6802 * @param $data the data submitted from the reset course.
6803 * @return array status array
6805 function forum_reset_userdata($data) {
6806 global $CFG, $DB;
6807 require_once($CFG->dirroot.'/rating/lib.php');
6809 $componentstr = get_string('modulenameplural', 'forum');
6810 $status = array();
6812 $params = array($data->courseid);
6814 $removeposts = false;
6815 $typesql = "";
6816 if (!empty($data->reset_forum_all)) {
6817 $removeposts = true;
6818 $typesstr = get_string('resetforumsall', 'forum');
6819 $types = array();
6820 } else if (!empty($data->reset_forum_types)){
6821 $removeposts = true;
6822 $typesql = "";
6823 $types = array();
6824 $forum_types_all = forum_get_forum_types_all();
6825 foreach ($data->reset_forum_types as $type) {
6826 if (!array_key_exists($type, $forum_types_all)) {
6827 continue;
6829 $typesql .= " AND f.type=?";
6830 $types[] = $forum_types_all[$type];
6831 $params[] = $type;
6833 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
6835 $alldiscussionssql = "SELECT fd.id
6836 FROM {forum_discussions} fd, {forum} f
6837 WHERE f.course=? AND f.id=fd.forum";
6839 $allforumssql = "SELECT f.id
6840 FROM {forum} f
6841 WHERE f.course=?";
6843 $allpostssql = "SELECT fp.id
6844 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
6845 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
6847 $forumssql = $forums = $rm = null;
6849 if( $removeposts || !empty($data->reset_forum_ratings) ) {
6850 $forumssql = "$allforumssql $typesql";
6851 $forums = $forums = $DB->get_records_sql($forumssql, $params);
6852 $rm = new rating_manager();
6853 $ratingdeloptions = new stdClass;
6854 $ratingdeloptions->component = 'mod_forum';
6855 $ratingdeloptions->ratingarea = 'post';
6858 if ($removeposts) {
6859 $discussionssql = "$alldiscussionssql $typesql";
6860 $postssql = "$allpostssql $typesql";
6862 // now get rid of all attachments
6863 $fs = get_file_storage();
6864 if ($forums) {
6865 foreach ($forums as $forumid=>$unused) {
6866 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
6867 continue;
6869 $context = context_module::instance($cm->id);
6870 $fs->delete_area_files($context->id, 'mod_forum', 'attachment');
6871 $fs->delete_area_files($context->id, 'mod_forum', 'post');
6873 //remove ratings
6874 $ratingdeloptions->contextid = $context->id;
6875 $rm->delete_ratings($ratingdeloptions);
6879 // first delete all read flags
6880 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
6882 // remove tracking prefs
6883 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
6885 // remove posts from queue
6886 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
6888 // all posts - initial posts must be kept in single simple discussion forums
6889 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
6890 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql AND f.type <> 'single') AND parent = 0", $params); // now the initial posts for non single simple
6892 // finally all discussions except single simple forums
6893 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
6895 // remove all grades from gradebook
6896 if (empty($data->reset_gradebook_grades)) {
6897 if (empty($types)) {
6898 forum_reset_gradebook($data->courseid);
6899 } else {
6900 foreach ($types as $type) {
6901 forum_reset_gradebook($data->courseid, $type);
6906 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
6909 // remove all ratings in this course's forums
6910 if (!empty($data->reset_forum_ratings)) {
6911 if ($forums) {
6912 foreach ($forums as $forumid=>$unused) {
6913 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
6914 continue;
6916 $context = context_module::instance($cm->id);
6918 //remove ratings
6919 $ratingdeloptions->contextid = $context->id;
6920 $rm->delete_ratings($ratingdeloptions);
6924 // remove all grades from gradebook
6925 if (empty($data->reset_gradebook_grades)) {
6926 forum_reset_gradebook($data->courseid);
6930 // remove all digest settings unconditionally - even for users still enrolled in course.
6931 if (!empty($data->reset_forum_digests)) {
6932 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
6933 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
6936 // remove all subscriptions unconditionally - even for users still enrolled in course
6937 if (!empty($data->reset_forum_subscriptions)) {
6938 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
6939 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
6940 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
6943 // remove all tracking prefs unconditionally - even for users still enrolled in course
6944 if (!empty($data->reset_forum_track_prefs)) {
6945 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
6946 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
6949 /// updating dates - shift may be negative too
6950 if ($data->timeshift) {
6951 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
6952 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
6955 return $status;
6959 * Called by course/reset.php
6961 * @param $mform form passed by reference
6963 function forum_reset_course_form_definition(&$mform) {
6964 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
6966 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
6968 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
6969 $mform->setAdvanced('reset_forum_types');
6970 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
6972 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
6973 $mform->setAdvanced('reset_forum_digests');
6975 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
6976 $mform->setAdvanced('reset_forum_subscriptions');
6978 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
6979 $mform->setAdvanced('reset_forum_track_prefs');
6980 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
6982 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
6983 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
6987 * Course reset form defaults.
6988 * @return array
6990 function forum_reset_course_form_defaults($course) {
6991 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
6995 * Returns array of forum layout modes
6997 * @return array
6999 function forum_get_layout_modes() {
7000 return array (FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
7001 FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
7002 FORUM_MODE_THREADED => get_string('modethreaded', 'forum'),
7003 FORUM_MODE_NESTED => get_string('modenested', 'forum'));
7007 * Returns array of forum types chooseable on the forum editing form
7009 * @return array
7011 function forum_get_forum_types() {
7012 return array ('general' => get_string('generalforum', 'forum'),
7013 'eachuser' => get_string('eachuserforum', 'forum'),
7014 'single' => get_string('singleforum', 'forum'),
7015 'qanda' => get_string('qandaforum', 'forum'),
7016 'blog' => get_string('blogforum', 'forum'));
7020 * Returns array of all forum layout modes
7022 * @return array
7024 function forum_get_forum_types_all() {
7025 return array ('news' => get_string('namenews','forum'),
7026 'social' => get_string('namesocial','forum'),
7027 'general' => get_string('generalforum', 'forum'),
7028 'eachuser' => get_string('eachuserforum', 'forum'),
7029 'single' => get_string('singleforum', 'forum'),
7030 'qanda' => get_string('qandaforum', 'forum'),
7031 'blog' => get_string('blogforum', 'forum'));
7035 * Returns all other caps used in module
7037 * @return array
7039 function forum_get_extra_capabilities() {
7040 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate');
7044 * Adds module specific settings to the settings block
7046 * @param settings_navigation $settings The settings navigation object
7047 * @param navigation_node $forumnode The node to add module settings to
7049 function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
7050 global $USER, $PAGE, $CFG, $DB, $OUTPUT;
7052 $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm->instance));
7053 if (empty($PAGE->cm->context)) {
7054 $PAGE->cm->context = context_module::instance($PAGE->cm->instance);
7057 $params = $PAGE->url->params();
7058 if (!empty($params['d'])) {
7059 $discussionid = $params['d'];
7062 // for some actions you need to be enrolled, beiing admin is not enough sometimes here
7063 $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
7064 $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);
7066 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context);
7067 $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject);
7068 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) &&
7069 (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage);
7071 if ($canmanage) {
7072 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);
7074 $allowchoice = $mode->add(get_string('subscriptionoptional', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_CHOOSESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7075 $forceforever = $mode->add(get_string("subscriptionforced", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_FORCESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7076 $forceinitially = $mode->add(get_string("subscriptionauto", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_INITIALSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7077 $disallowchoice = $mode->add(get_string('subscriptiondisabled', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_DISALLOWSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING);
7079 switch ($subscriptionmode) {
7080 case FORUM_CHOOSESUBSCRIBE : // 0
7081 $allowchoice->action = null;
7082 $allowchoice->add_class('activesetting');
7083 break;
7084 case FORUM_FORCESUBSCRIBE : // 1
7085 $forceforever->action = null;
7086 $forceforever->add_class('activesetting');
7087 break;
7088 case FORUM_INITIALSUBSCRIBE : // 2
7089 $forceinitially->action = null;
7090 $forceinitially->add_class('activesetting');
7091 break;
7092 case FORUM_DISALLOWSUBSCRIBE : // 3
7093 $disallowchoice->action = null;
7094 $disallowchoice->add_class('activesetting');
7095 break;
7098 } else if ($activeenrolled) {
7100 switch ($subscriptionmode) {
7101 case FORUM_CHOOSESUBSCRIBE : // 0
7102 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
7103 break;
7104 case FORUM_FORCESUBSCRIBE : // 1
7105 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
7106 break;
7107 case FORUM_INITIALSUBSCRIBE : // 2
7108 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
7109 break;
7110 case FORUM_DISALLOWSUBSCRIBE : // 3
7111 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
7112 break;
7116 if ($cansubscribe) {
7117 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, null, $PAGE->cm)) {
7118 $linktext = get_string('unsubscribe', 'forum');
7119 } else {
7120 $linktext = get_string('subscribe', 'forum');
7122 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey()));
7123 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7125 if (isset($discussionid)) {
7126 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, $discussionid, $PAGE->cm)) {
7127 $linktext = get_string('unsubscribediscussion', 'forum');
7128 } else {
7129 $linktext = get_string('subscribediscussion', 'forum');
7131 $url = new moodle_url('/mod/forum/subscribe.php', array(
7132 'id' => $forumobject->id,
7133 'sesskey' => sesskey(),
7134 'd' => $discussionid,
7135 'returnurl' => $PAGE->url->out(),
7137 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7141 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){
7142 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id));
7143 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING);
7146 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
7147 if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL
7148 || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) {
7149 if (forum_tp_is_tracked($forumobject)) {
7150 $linktext = get_string('notrackforum', 'forum');
7151 } else {
7152 $linktext = get_string('trackforum', 'forum');
7154 $url = new moodle_url('/mod/forum/settracking.php', array(
7155 'id' => $forumobject->id,
7156 'sesskey' => sesskey(),
7158 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7162 if (!isloggedin() && $PAGE->course->id == SITEID) {
7163 $userid = guest_user()->id;
7164 } else {
7165 $userid = $USER->id;
7168 $hascourseaccess = ($PAGE->course->id == SITEID) || can_access_course($PAGE->course, $userid);
7169 $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds);
7171 if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) {
7173 if (!function_exists('rss_get_url')) {
7174 require_once("$CFG->libdir/rsslib.php");
7177 if ($forumobject->rsstype == 1) {
7178 $string = get_string('rsssubscriberssdiscussions','forum');
7179 } else {
7180 $string = get_string('rsssubscriberssposts','forum');
7183 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id));
7184 $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
7189 * Adds information about unread messages, that is only required for the course view page (and
7190 * similar), to the course-module object.
7191 * @param cm_info $cm Course-module object
7193 function forum_cm_info_view(cm_info $cm) {
7194 global $CFG;
7196 if (forum_tp_can_track_forums()) {
7197 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
7198 $out = '<span class="unread"> <a href="' . $cm->url . '">';
7199 if ($unread == 1) {
7200 $out .= get_string('unreadpostsone', 'forum');
7201 } else {
7202 $out .= get_string('unreadpostsnumber', 'forum', $unread);
7204 $out .= '</a></span>';
7205 $cm->set_after_link($out);
7211 * Return a list of page types
7212 * @param string $pagetype current page type
7213 * @param stdClass $parentcontext Block's parent context
7214 * @param stdClass $currentcontext Current context of block
7216 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
7217 $forum_pagetype = array(
7218 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
7219 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
7220 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
7222 return $forum_pagetype;
7226 * Gets all of the courses where the provided user has posted in a forum.
7228 * @global moodle_database $DB The database connection
7229 * @param stdClass $user The user who's posts we are looking for
7230 * @param bool $discussionsonly If true only look for discussions started by the user
7231 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
7232 * @param int $limitfrom The offset of records to return
7233 * @param int $limitnum The number of records to return
7234 * @return array An array of courses
7236 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
7237 global $DB;
7239 // If we are only after discussions we need only look at the forum_discussions
7240 // table and join to the userid there. If we are looking for posts then we need
7241 // to join to the forum_posts table.
7242 if (!$discussionsonly) {
7243 $subquery = "(SELECT DISTINCT fd.course
7244 FROM {forum_discussions} fd
7245 JOIN {forum_posts} fp ON fp.discussion = fd.id
7246 WHERE fp.userid = :userid )";
7247 } else {
7248 $subquery= "(SELECT DISTINCT fd.course
7249 FROM {forum_discussions} fd
7250 WHERE fd.userid = :userid )";
7253 $params = array('userid' => $user->id);
7255 // Join to the context table so that we can preload contexts if required.
7256 if ($includecontexts) {
7257 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
7258 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
7259 $params['contextlevel'] = CONTEXT_COURSE;
7260 } else {
7261 $ctxselect = '';
7262 $ctxjoin = '';
7265 // Now we need to get all of the courses to search.
7266 // All courses where the user has posted within a forum will be returned.
7267 $sql = "SELECT c.* $ctxselect
7268 FROM {course} c
7269 $ctxjoin
7270 WHERE c.id IN ($subquery)";
7271 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7272 if ($includecontexts) {
7273 array_map('context_helper::preload_from_record', $courses);
7275 return $courses;
7279 * Gets all of the forums a user has posted in for one or more courses.
7281 * @global moodle_database $DB
7282 * @param stdClass $user
7283 * @param array $courseids An array of courseids to search or if not provided
7284 * all courses the user has posted within
7285 * @param bool $discussionsonly If true then only forums where the user has started
7286 * a discussion will be returned.
7287 * @param int $limitfrom The offset of records to return
7288 * @param int $limitnum The number of records to return
7289 * @return array An array of forums the user has posted within in the provided courses
7291 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
7292 global $DB;
7294 if (!is_null($courseids)) {
7295 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid');
7296 $coursewhere = ' AND f.course '.$coursewhere;
7297 } else {
7298 $coursewhere = '';
7299 $params = array();
7301 $params['userid'] = $user->id;
7302 $params['forum'] = 'forum';
7304 if ($discussionsonly) {
7305 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
7306 } else {
7307 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
7308 JOIN {forum_posts} ff ON ff.discussion = fd.id';
7311 $sql = "SELECT f.*, cm.id AS cmid
7312 FROM {forum} f
7313 JOIN {course_modules} cm ON cm.instance = f.id
7314 JOIN {modules} m ON m.id = cm.module
7315 JOIN (
7316 SELECT f.id
7317 FROM {forum} f
7318 {$join}
7319 WHERE ff.userid = :userid
7320 GROUP BY f.id
7321 ) j ON j.id = f.id
7322 WHERE m.name = :forum
7323 {$coursewhere}";
7325 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7326 return $courseforums;
7330 * Returns posts made by the selected user in the requested courses.
7332 * This method can be used to return all of the posts made by the requested user
7333 * within the given courses.
7334 * For each course the access of the current user and requested user is checked
7335 * and then for each post access to the post and forum is checked as well.
7337 * This function is safe to use with usercapabilities.
7339 * @global moodle_database $DB
7340 * @param stdClass $user The user whose posts we want to get
7341 * @param array $courses The courses to search
7342 * @param bool $musthaveaccess If set to true errors will be thrown if the user
7343 * cannot access one or more of the courses to search
7344 * @param bool $discussionsonly If set to true only discussion starting posts
7345 * will be returned.
7346 * @param int $limitfrom The offset of records to return
7347 * @param int $limitnum The number of records to return
7348 * @return stdClass An object the following properties
7349 * ->totalcount: the total number of posts made by the requested user
7350 * that the current user can see.
7351 * ->courses: An array of courses the current user can see that the
7352 * requested user has posted in.
7353 * ->forums: An array of forums relating to the posts returned in the
7354 * property below.
7355 * ->posts: An array containing the posts to show for this request.
7357 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
7358 global $DB, $USER, $CFG;
7360 $return = new stdClass;
7361 $return->totalcount = 0; // The total number of posts that the current user is able to view
7362 $return->courses = array(); // The courses the current user can access
7363 $return->forums = array(); // The forums that the current user can access that contain posts
7364 $return->posts = array(); // The posts to display
7366 // First up a small sanity check. If there are no courses to check we can
7367 // return immediately, there is obviously nothing to search.
7368 if (empty($courses)) {
7369 return $return;
7372 // A couple of quick setups
7373 $isloggedin = isloggedin();
7374 $isguestuser = $isloggedin && isguestuser();
7375 $iscurrentuser = $isloggedin && $USER->id == $user->id;
7377 // Checkout whether or not the current user has capabilities over the requested
7378 // user and if so they have the capabilities required to view the requested
7379 // users content.
7380 $usercontext = context_user::instance($user->id, MUST_EXIST);
7381 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
7382 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
7384 // Before we actually search each course we need to check the user's access to the
7385 // course. If the user doesn't have the appropraite access then we either throw an
7386 // error if a particular course was requested or we just skip over the course.
7387 foreach ($courses as $course) {
7388 $coursecontext = context_course::instance($course->id, MUST_EXIST);
7389 if ($iscurrentuser || $hascapsonuser) {
7390 // If it is the current user, or the current user has capabilities to the
7391 // requested user then all we need to do is check the requested users
7392 // current access to the course.
7393 // Note: There is no need to check group access or anything of the like
7394 // as either the current user is the requested user, or has granted
7395 // capabilities on the requested user. Either way they can see what the
7396 // requested user posted, although its VERY unlikely in the `parent` situation
7397 // that the current user will be able to view the posts in context.
7398 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
7399 // Need to have full access to a course to see the rest of own info
7400 if ($musthaveaccess) {
7401 print_error('errorenrolmentrequired', 'forum');
7403 continue;
7405 } else {
7406 // Check whether the current user is enrolled or has access to view the course
7407 // if they don't we immediately have a problem.
7408 if (!can_access_course($course)) {
7409 if ($musthaveaccess) {
7410 print_error('errorenrolmentrequired', 'forum');
7412 continue;
7415 // Check whether the requested user is enrolled or has access to view the course
7416 // if they don't we immediately have a problem.
7417 if (!can_access_course($course, $user) && !is_enrolled($coursecontext, $user)) {
7418 if ($musthaveaccess) {
7419 print_error('notenrolled', 'forum');
7421 continue;
7424 // If groups are in use and enforced throughout the course then make sure
7425 // we can meet in at least one course level group.
7426 // Note that we check if either the current user or the requested user have
7427 // the capability to access all groups. This is because with that capability
7428 // a user in group A could post in the group B forum. Grrrr.
7429 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
7430 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
7431 // If its the guest user to bad... the guest user cannot access groups
7432 if (!$isloggedin or $isguestuser) {
7433 // do not use require_login() here because we might have already used require_login($course)
7434 if ($musthaveaccess) {
7435 redirect(get_login_url());
7437 continue;
7439 // Get the groups of the current user
7440 $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
7441 // Get the groups the requested user is a member of
7442 $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
7443 // Check whether they are members of the same group. If they are great.
7444 $intersect = array_intersect($mygroups, $usergroups);
7445 if (empty($intersect)) {
7446 // But they're not... if it was a specific course throw an error otherwise
7447 // just skip this course so that it is not searched.
7448 if ($musthaveaccess) {
7449 print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
7451 continue;
7455 // Woo hoo we got this far which means the current user can search this
7456 // this course for the requested user. Although this is only the course accessibility
7457 // handling that is complete, the forum accessibility tests are yet to come.
7458 $return->courses[$course->id] = $course;
7460 // No longer beed $courses array - lose it not it may be big
7461 unset($courses);
7463 // Make sure that we have some courses to search
7464 if (empty($return->courses)) {
7465 // If we don't have any courses to search then the reality is that the current
7466 // user doesn't have access to any courses is which the requested user has posted.
7467 // Although we do know at this point that the requested user has posts.
7468 if ($musthaveaccess) {
7469 print_error('permissiondenied');
7470 } else {
7471 return $return;
7475 // Next step: Collect all of the forums that we will want to search.
7476 // It is important to note that this step isn't actually about searching, it is
7477 // about determining which forums we can search by testing accessibility.
7478 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);
7480 // Will be used to build the where conditions for the search
7481 $forumsearchwhere = array();
7482 // Will be used to store the where condition params for the search
7483 $forumsearchparams = array();
7484 // Will record forums where the user can freely access everything
7485 $forumsearchfullaccess = array();
7486 // DB caching friendly
7487 $now = round(time(), -2);
7488 // For each course to search we want to find the forums the user has posted in
7489 // and providing the current user can access the forum create a search condition
7490 // for the forum to get the requested users posts.
7491 foreach ($return->courses as $course) {
7492 // Now we need to get the forums
7493 $modinfo = get_fast_modinfo($course);
7494 if (empty($modinfo->instances['forum'])) {
7495 // hmmm, no forums? well at least its easy... skip!
7496 continue;
7498 // Iterate
7499 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
7500 if (!$cm->uservisible or !isset($forums[$forumid])) {
7501 continue;
7503 // Get the forum in question
7504 $forum = $forums[$forumid];
7506 // This is needed for functionality later on in the forum code. It is converted to an object
7507 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
7508 // code were expecting an writeable object. See {@link forum_print_post()}.
7509 $forum->cm = new stdClass();
7510 foreach ($cm as $key => $value) {
7511 $forum->cm->$key = $value;
7514 // Check that either the current user can view the forum, or that the
7515 // current user has capabilities over the requested user and the requested
7516 // user can view the discussion
7517 if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
7518 continue;
7521 // This will contain forum specific where clauses
7522 $forumsearchselect = array();
7523 if (!$iscurrentuser && !$hascapsonuser) {
7524 // Make sure we check group access
7525 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
7526 $groups = $modinfo->get_groups($cm->groupingid);
7527 $groups[] = -1;
7528 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
7529 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
7530 $forumsearchselect[] = "d.groupid $groupid_sql";
7533 // hidden timed discussions
7534 if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
7535 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
7536 $forumsearchparams['userid'.$forumid] = $user->id;
7537 $forumsearchparams['timestart'.$forumid] = $now;
7538 $forumsearchparams['timeend'.$forumid] = $now;
7541 // qanda access
7542 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
7543 // We need to check whether the user has posted in the qanda forum.
7544 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
7545 if (!empty($discussionspostedin)) {
7546 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
7547 foreach ($discussionspostedin as $d) {
7548 $forumonlydiscussions[] = $d->id;
7550 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
7551 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
7552 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
7553 } else {
7554 $forumsearchselect[] = "p.parent = 0";
7559 if (count($forumsearchselect) > 0) {
7560 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
7561 $forumsearchparams['forum'.$forumid] = $forumid;
7562 } else {
7563 $forumsearchfullaccess[] = $forumid;
7565 } else {
7566 // The current user/parent can see all of their own posts
7567 $forumsearchfullaccess[] = $forumid;
7572 // If we dont have any search conditions, and we don't have any forums where
7573 // the user has full access then we just return the default.
7574 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
7575 return $return;
7578 // Prepare a where condition for the full access forums.
7579 if (count($forumsearchfullaccess) > 0) {
7580 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
7581 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
7582 $forumsearchwhere[] = "(d.forum $fullidsql)";
7585 // Prepare SQL to both count and search.
7586 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
7587 // oracle and mssql.
7588 $userfields = user_picture::fields('u', null, 'useridx');
7589 $countsql = 'SELECT COUNT(*) ';
7590 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
7591 $wheresql = implode(" OR ", $forumsearchwhere);
7593 if ($discussionsonly) {
7594 if ($wheresql == '') {
7595 $wheresql = 'p.parent = 0';
7596 } else {
7597 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
7601 $sql = "FROM {forum_posts} p
7602 JOIN {forum_discussions} d ON d.id = p.discussion
7603 JOIN {user} u ON u.id = p.userid
7604 WHERE ($wheresql)
7605 AND p.userid = :userid ";
7606 $orderby = "ORDER BY p.modified DESC";
7607 $forumsearchparams['userid'] = $user->id;
7609 // Set the total number posts made by the requested user that the current user can see
7610 $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
7611 // Set the collection of posts that has been requested
7612 $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
7614 // We need to build an array of forums for which posts will be displayed.
7615 // We do this here to save the caller needing to retrieve them themselves before
7616 // printing these forums posts. Given we have the forums already there is
7617 // practically no overhead here.
7618 foreach ($return->posts as $post) {
7619 if (!array_key_exists($post->forum, $return->forums)) {
7620 $return->forums[$post->forum] = $forums[$post->forum];
7624 return $return;
7628 * Set the per-forum maildigest option for the specified user.
7630 * @param stdClass $forum The forum to set the option for.
7631 * @param int $maildigest The maildigest option.
7632 * @param stdClass $user The user object. This defaults to the global $USER object.
7633 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
7635 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
7636 global $DB, $USER;
7638 if (is_number($forum)) {
7639 $forum = $DB->get_record('forum', array('id' => $forum));
7642 if ($user === null) {
7643 $user = $USER;
7646 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
7647 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
7648 $context = context_module::instance($cm->id);
7650 // User must be allowed to see this forum.
7651 require_capability('mod/forum:viewdiscussion', $context, $user->id);
7653 // Validate the maildigest setting.
7654 $digestoptions = forum_get_user_digest_options($user);
7656 if (!isset($digestoptions[$maildigest])) {
7657 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
7660 // Attempt to retrieve any existing forum digest record.
7661 $subscription = $DB->get_record('forum_digests', array(
7662 'userid' => $user->id,
7663 'forum' => $forum->id,
7666 // Create or Update the existing maildigest setting.
7667 if ($subscription) {
7668 if ($maildigest == -1) {
7669 $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id));
7670 } else if ($maildigest !== $subscription->maildigest) {
7671 // Only update the maildigest setting if it's changed.
7673 $subscription->maildigest = $maildigest;
7674 $DB->update_record('forum_digests', $subscription);
7676 } else {
7677 if ($maildigest != -1) {
7678 // Only insert the maildigest setting if it's non-default.
7680 $subscription = new stdClass();
7681 $subscription->forum = $forum->id;
7682 $subscription->userid = $user->id;
7683 $subscription->maildigest = $maildigest;
7684 $subscription->id = $DB->insert_record('forum_digests', $subscription);
7690 * Determine the maildigest setting for the specified user against the
7691 * specified forum.
7693 * @param Array $digests An array of forums and user digest settings.
7694 * @param stdClass $user The user object containing the id and maildigest default.
7695 * @param int $forumid The ID of the forum to check.
7696 * @return int The calculated maildigest setting for this user and forum.
7698 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
7699 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) {
7700 $maildigest = $digests[$forumid][$user->id];
7701 if ($maildigest === -1) {
7702 $maildigest = $user->maildigest;
7704 } else {
7705 $maildigest = $user->maildigest;
7707 return $maildigest;
7711 * Retrieve the list of available user digest options.
7713 * @param stdClass $user The user object. This defaults to the global $USER object.
7714 * @return array The mapping of values to digest options.
7716 function forum_get_user_digest_options($user = null) {
7717 global $USER;
7719 // Revert to the global user object.
7720 if ($user === null) {
7721 $user = $USER;
7724 $digestoptions = array();
7725 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
7726 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
7727 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
7729 // We need to add the default digest option at the end - it relies on
7730 // the contents of the existing values.
7731 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
7732 $digestoptions[$user->maildigest]);
7734 // Resort the options to be in a sensible order.
7735 ksort($digestoptions);
7737 return $digestoptions;
7741 * Determine the current context if one was not already specified.
7743 * If a context of type context_module is specified, it is immediately
7744 * returned and not checked.
7746 * @param int $forumid The ID of the forum
7747 * @param context_module $context The current context.
7748 * @return context_module The context determined
7750 function forum_get_context($forumid, $context = null) {
7751 global $PAGE;
7753 if (!$context || !($context instanceof context_module)) {
7754 // Find out forum context. First try to take current page context to save on DB query.
7755 if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid
7756 && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) {
7757 $context = $PAGE->context;
7758 } else {
7759 $cm = get_coursemodule_from_instance('forum', $forumid);
7760 $context = \context_module::instance($cm->id);
7764 return $context;
7768 * Mark the activity completed (if required) and trigger the course_module_viewed event.
7770 * @param stdClass $forum forum object
7771 * @param stdClass $course course object
7772 * @param stdClass $cm course module object
7773 * @param stdClass $context context object
7774 * @since Moodle 2.9
7776 function forum_view($forum, $course, $cm, $context) {
7778 // Completion.
7779 $completion = new completion_info($course);
7780 $completion->set_module_viewed($cm);
7782 // Trigger course_module_viewed event.
7784 $params = array(
7785 'context' => $context,
7786 'objectid' => $forum->id
7789 $event = \mod_forum\event\course_module_viewed::create($params);
7790 $event->add_record_snapshot('course_modules', $cm);
7791 $event->add_record_snapshot('course', $course);
7792 $event->add_record_snapshot('forum', $forum);
7793 $event->trigger();
7797 * Trigger the discussion viewed event
7799 * @param stdClass $modcontext module context object
7800 * @param stdClass $forum forum object
7801 * @param stdClass $discussion discussion object
7802 * @since Moodle 2.9
7804 function forum_discussion_view($modcontext, $forum, $discussion) {
7805 $params = array(
7806 'context' => $modcontext,
7807 'objectid' => $discussion->id,
7810 $event = \mod_forum\event\discussion_viewed::create($params);
7811 $event->add_record_snapshot('forum_discussions', $discussion);
7812 $event->add_record_snapshot('forum', $forum);
7813 $event->trigger();
7817 * Add nodes to myprofile page.
7819 * @param \core_user\output\myprofile\tree $tree Tree object
7820 * @param stdClass $user user object
7821 * @param bool $iscurrentuser
7822 * @param stdClass $course Course object
7824 * @return bool
7826 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
7827 if (isguestuser($user)) {
7828 // The guest user cannot post, so it is not possible to view any posts.
7829 // May as well just bail aggressively here.
7830 return false;
7832 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id));
7833 if (!empty($course)) {
7834 $postsurl->param('coursre', $course->id);
7836 $string = $iscurrentuser ? get_string('myprofileownpost', 'mod_forum') :
7837 get_string('myprofileotherpost', 'mod_forum', fullname($user));
7838 $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl);
7839 $tree->add_node($node);
7841 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions'));
7842 if (!empty($course)) {
7843 $postsurl->param('coursre', $course->id);
7845 $string = $iscurrentuser ? get_string('myprofileowndis', 'mod_forum') :
7846 get_string('myprofileotherdis', 'mod_forum', fullname($user));
7847 $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null,
7848 $discussionssurl);
7849 $tree->add_node($node);
7851 return true;