Merge branch 'MDL-51253_forum_urls' of git://github.com/BenKelada/moodle
[moodle.git] / mod / forum / lib.php
blob42f6db39301ce65c305e86fa6ec2e01500bb6ca5
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 .= "\n";
1218 $posttext .= format_string($post->subject,true);
1219 if ($bare) {
1220 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1222 $posttext .= "\n".$strbynameondate."\n";
1223 $posttext .= "---------------------------------------------------------------------\n";
1224 $posttext .= format_text_email($post->message, $post->messageformat);
1225 $posttext .= "\n\n";
1226 $posttext .= forum_print_attachments($post, $cm, "text");
1227 $posttext .= "\n---------------------------------------------------------------------\n";
1229 if (!$bare) {
1230 if ($canreply) {
1231 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1232 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1235 if ($canunsubscribe) {
1236 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1237 // If subscribed to this forum, offer the unsubscribe link.
1238 $posttext .= get_string("unsubscribe", "forum");
1239 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1241 // Always offer the unsubscribe from discussion link.
1242 $posttext .= get_string("unsubscribediscussion", "forum");
1243 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id&d=$discussion->id\n";
1247 $posttext .= get_string("digestmailpost", "forum");
1248 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1250 return $posttext;
1254 * Builds and returns the body of the email notification in html format.
1256 * @global object
1257 * @param object $course
1258 * @param object $cm
1259 * @param object $forum
1260 * @param object $discussion
1261 * @param object $post
1262 * @param object $userfrom
1263 * @param object $userto
1264 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1265 * @return string The email text in HTML format
1267 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $replyaddress = null) {
1268 global $CFG;
1270 if ($userto->mailformat != 1) { // Needs to be HTML
1271 return '';
1274 if (!isset($userto->canpost[$discussion->id])) {
1275 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1276 } else {
1277 $canreply = $userto->canpost[$discussion->id];
1280 $strforums = get_string('forums', 'forum');
1281 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
1282 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1284 $posthtml = '<head>';
1285 /* foreach ($CFG->stylesheets as $stylesheet) {
1286 //TODO: MDL-21120
1287 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1289 $posthtml .= '</head>';
1290 $posthtml .= "\n<body id=\"email\">\n\n";
1292 $posthtml .= '<div class="navbar">'.
1293 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$shortname.'</a> &raquo; '.
1294 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> &raquo; '.
1295 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
1296 if ($discussion->name == $forum->name) {
1297 $posthtml .= '</div>';
1298 } else {
1299 $posthtml .= ' &raquo; <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
1300 format_string($discussion->name,true).'</a></div>';
1302 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1304 $footerlinks = array();
1305 if ($canunsubscribe) {
1306 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1307 // If subscribed to this forum, offer the unsubscribe link.
1308 $unsublink = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id));
1309 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribe', 'mod_forum'));
1311 // Always offer the unsubscribe from discussion link.
1312 $unsublink = new moodle_url('/mod/forum/subscribe.php', array(
1313 'id' => $forum->id,
1314 'd' => $discussion->id,
1316 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribediscussion', 'mod_forum'));
1318 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
1320 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1321 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode('&nbsp;', $footerlinks) . '</div>';
1323 $posthtml .= '</body>';
1325 return $posthtml;
1331 * @param object $course
1332 * @param object $user
1333 * @param object $mod TODO this is not used in this function, refactor
1334 * @param object $forum
1335 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1337 function forum_user_outline($course, $user, $mod, $forum) {
1338 global $CFG;
1339 require_once("$CFG->libdir/gradelib.php");
1340 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1341 if (empty($grades->items[0]->grades)) {
1342 $grade = false;
1343 } else {
1344 $grade = reset($grades->items[0]->grades);
1347 $count = forum_count_user_posts($forum->id, $user->id);
1349 if ($count && $count->postcount > 0) {
1350 $result = new stdClass();
1351 $result->info = get_string("numposts", "forum", $count->postcount);
1352 $result->time = $count->lastpost;
1353 if ($grade) {
1354 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1356 return $result;
1357 } else if ($grade) {
1358 $result = new stdClass();
1359 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1361 //datesubmitted == time created. dategraded == time modified or time overridden
1362 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1363 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1364 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1365 $result->time = $grade->dategraded;
1366 } else {
1367 $result->time = $grade->datesubmitted;
1370 return $result;
1372 return NULL;
1377 * @global object
1378 * @global object
1379 * @param object $coure
1380 * @param object $user
1381 * @param object $mod
1382 * @param object $forum
1384 function forum_user_complete($course, $user, $mod, $forum) {
1385 global $CFG,$USER, $OUTPUT;
1386 require_once("$CFG->libdir/gradelib.php");
1388 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1389 if (!empty($grades->items[0]->grades)) {
1390 $grade = reset($grades->items[0]->grades);
1391 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1392 if ($grade->str_feedback) {
1393 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1397 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
1399 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
1400 print_error('invalidcoursemodule');
1402 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
1404 foreach ($posts as $post) {
1405 if (!isset($discussions[$post->discussion])) {
1406 continue;
1408 $discussion = $discussions[$post->discussion];
1410 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1412 } else {
1413 echo "<p>".get_string("noposts", "forum")."</p>";
1418 * Filters the forum discussions according to groups membership and config.
1420 * @since Moodle 2.8, 2.7.1, 2.6.4
1421 * @param array $discussions Discussions with new posts array
1422 * @return array Forums with the number of new posts
1424 function forum_filter_user_groups_discussions($discussions) {
1426 // Group the remaining discussions posts by their forumid.
1427 $filteredforums = array();
1429 // Discard not visible groups.
1430 foreach ($discussions as $discussion) {
1432 // Course data is already cached.
1433 $instances = get_fast_modinfo($discussion->course)->get_instances();
1434 $forum = $instances['forum'][$discussion->forum];
1436 // Continue if the user should not see this discussion.
1437 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1438 continue;
1441 // Grouping results by forum.
1442 if (empty($filteredforums[$forum->instance])) {
1443 $filteredforums[$forum->instance] = new stdClass();
1444 $filteredforums[$forum->instance]->id = $forum->id;
1445 $filteredforums[$forum->instance]->count = 0;
1447 $filteredforums[$forum->instance]->count += $discussion->count;
1451 return $filteredforums;
1455 * Returns whether the discussion group is visible by the current user or not.
1457 * @since Moodle 2.8, 2.7.1, 2.6.4
1458 * @param cm_info $cm The discussion course module
1459 * @param int $discussiongroupid The discussion groupid
1460 * @return bool
1462 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1464 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1465 return true;
1468 if (isguestuser()) {
1469 return false;
1472 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1473 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1474 return true;
1477 return false;
1481 * @global object
1482 * @global object
1483 * @global object
1484 * @param array $courses
1485 * @param array $htmlarray
1487 function forum_print_overview($courses,&$htmlarray) {
1488 global $USER, $CFG, $DB, $SESSION;
1490 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1491 return array();
1494 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1495 return;
1498 // Courses to search for new posts
1499 $coursessqls = array();
1500 $params = array();
1501 foreach ($courses as $course) {
1503 // If the user has never entered into the course all posts are pending
1504 if ($course->lastaccess == 0) {
1505 $coursessqls[] = '(d.course = ?)';
1506 $params[] = $course->id;
1508 // Only posts created after the course last access
1509 } else {
1510 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1511 $params[] = $course->id;
1512 $params[] = $course->lastaccess;
1515 $params[] = $USER->id;
1516 $coursessql = implode(' OR ', $coursessqls);
1518 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1519 .'FROM {forum_discussions} d '
1520 .'JOIN {forum_posts} p ON p.discussion = d.id '
1521 ."WHERE ($coursessql) "
1522 .'AND p.userid != ? '
1523 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1524 .'ORDER BY d.course, d.forum';
1526 // Avoid warnings.
1527 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1528 $discussions = array();
1531 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1533 // also get all forum tracking stuff ONCE.
1534 $trackingforums = array();
1535 foreach ($forums as $forum) {
1536 if (forum_tp_can_track_forums($forum)) {
1537 $trackingforums[$forum->id] = $forum;
1541 if (count($trackingforums) > 0) {
1542 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1543 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1544 ' FROM {forum_posts} p '.
1545 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1546 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1547 $params = array($USER->id);
1549 foreach ($trackingforums as $track) {
1550 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1551 $params[] = $track->id;
1552 if (isset($SESSION->currentgroup[$track->course])) {
1553 $groupid = $SESSION->currentgroup[$track->course];
1554 } else {
1555 // get first groupid
1556 $groupids = groups_get_all_groups($track->course, $USER->id);
1557 if ($groupids) {
1558 reset($groupids);
1559 $groupid = key($groupids);
1560 $SESSION->currentgroup[$track->course] = $groupid;
1561 } else {
1562 $groupid = 0;
1564 unset($groupids);
1566 $params[] = $groupid;
1568 $sql = substr($sql,0,-3); // take off the last OR
1569 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1570 $params[] = $cutoffdate;
1572 if (!$unread = $DB->get_records_sql($sql, $params)) {
1573 $unread = array();
1575 } else {
1576 $unread = array();
1579 if (empty($unread) and empty($forumsnewposts)) {
1580 return;
1583 $strforum = get_string('modulename','forum');
1585 foreach ($forums as $forum) {
1586 $str = '';
1587 $count = 0;
1588 $thisunread = 0;
1589 $showunread = false;
1590 // either we have something from logs, or trackposts, or nothing.
1591 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1592 $count = $forumsnewposts[$forum->id]->count;
1594 if (array_key_exists($forum->id,$unread)) {
1595 $thisunread = $unread[$forum->id]->count;
1596 $showunread = true;
1598 if ($count > 0 || $thisunread > 0) {
1599 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1600 $forum->name.'</a></div>';
1601 $str .= '<div class="info"><span class="postsincelogin">';
1602 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1603 if (!empty($showunread)) {
1604 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1606 $str .= '</div></div>';
1608 if (!empty($str)) {
1609 if (!array_key_exists($forum->course,$htmlarray)) {
1610 $htmlarray[$forum->course] = array();
1612 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1613 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1615 $htmlarray[$forum->course]['forum'] .= $str;
1621 * Given a course and a date, prints a summary of all the new
1622 * messages posted in the course since that date
1624 * @global object
1625 * @global object
1626 * @global object
1627 * @uses CONTEXT_MODULE
1628 * @uses VISIBLEGROUPS
1629 * @param object $course
1630 * @param bool $viewfullnames capability
1631 * @param int $timestart
1632 * @return bool success
1634 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1635 global $CFG, $USER, $DB, $OUTPUT;
1637 // do not use log table if possible, it may be huge and is expensive to join with other tables
1639 $allnamefields = user_picture::fields('u', null, 'duserid');
1640 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1641 d.timestart, d.timeend, $allnamefields
1642 FROM {forum_posts} p
1643 JOIN {forum_discussions} d ON d.id = p.discussion
1644 JOIN {forum} f ON f.id = d.forum
1645 JOIN {user} u ON u.id = p.userid
1646 WHERE p.created > ? AND f.course = ?
1647 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
1648 return false;
1651 $modinfo = get_fast_modinfo($course);
1653 $groupmodes = array();
1654 $cms = array();
1656 $strftimerecent = get_string('strftimerecent');
1658 $printposts = array();
1659 foreach ($posts as $post) {
1660 if (!isset($modinfo->instances['forum'][$post->forum])) {
1661 // not visible
1662 continue;
1664 $cm = $modinfo->instances['forum'][$post->forum];
1665 if (!$cm->uservisible) {
1666 continue;
1668 $context = context_module::instance($cm->id);
1670 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1671 continue;
1674 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1675 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
1676 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1677 continue;
1681 // Check that the user can see the discussion.
1682 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1683 $printposts[] = $post;
1687 unset($posts);
1689 if (!$printposts) {
1690 return false;
1693 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1694 echo "\n<ul class='unlist'>\n";
1696 foreach ($printposts as $post) {
1697 $subjectclass = empty($post->parent) ? ' bold' : '';
1699 echo '<li><div class="head">'.
1700 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1701 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1702 '</div>';
1703 echo '<div class="info'.$subjectclass.'">';
1704 if (empty($post->parent)) {
1705 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1706 } else {
1707 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&amp;parent='.$post->parent.'#p'.$post->id.'">';
1709 $post->subject = break_up_long_words(format_string($post->subject, true));
1710 echo $post->subject;
1711 echo "</a>\"</div></li>\n";
1714 echo "</ul>\n";
1716 return true;
1720 * Return grade for given user or all users.
1722 * @global object
1723 * @global object
1724 * @param object $forum
1725 * @param int $userid optional user id, 0 means all users
1726 * @return array array of grades, false if none
1728 function forum_get_user_grades($forum, $userid = 0) {
1729 global $CFG;
1731 require_once($CFG->dirroot.'/rating/lib.php');
1733 $ratingoptions = new stdClass;
1734 $ratingoptions->component = 'mod_forum';
1735 $ratingoptions->ratingarea = 'post';
1737 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1738 $ratingoptions->modulename = 'forum';
1739 $ratingoptions->moduleid = $forum->id;
1740 $ratingoptions->userid = $userid;
1741 $ratingoptions->aggregationmethod = $forum->assessed;
1742 $ratingoptions->scaleid = $forum->scale;
1743 $ratingoptions->itemtable = 'forum_posts';
1744 $ratingoptions->itemtableusercolumn = 'userid';
1746 $rm = new rating_manager();
1747 return $rm->get_user_grades($ratingoptions);
1751 * Update activity grades
1753 * @category grade
1754 * @param object $forum
1755 * @param int $userid specific user only, 0 means all
1756 * @param boolean $nullifnone return null if grade does not exist
1757 * @return void
1759 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1760 global $CFG, $DB;
1761 require_once($CFG->libdir.'/gradelib.php');
1763 if (!$forum->assessed) {
1764 forum_grade_item_update($forum);
1766 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1767 forum_grade_item_update($forum, $grades);
1769 } else if ($userid and $nullifnone) {
1770 $grade = new stdClass();
1771 $grade->userid = $userid;
1772 $grade->rawgrade = NULL;
1773 forum_grade_item_update($forum, $grade);
1775 } else {
1776 forum_grade_item_update($forum);
1781 * Create/update grade item for given forum
1783 * @category grade
1784 * @uses GRADE_TYPE_NONE
1785 * @uses GRADE_TYPE_VALUE
1786 * @uses GRADE_TYPE_SCALE
1787 * @param stdClass $forum Forum object with extra cmidnumber
1788 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1789 * @return int 0 if ok
1791 function forum_grade_item_update($forum, $grades=NULL) {
1792 global $CFG;
1793 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1794 require_once($CFG->libdir.'/gradelib.php');
1797 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
1799 if (!$forum->assessed or $forum->scale == 0) {
1800 $params['gradetype'] = GRADE_TYPE_NONE;
1802 } else if ($forum->scale > 0) {
1803 $params['gradetype'] = GRADE_TYPE_VALUE;
1804 $params['grademax'] = $forum->scale;
1805 $params['grademin'] = 0;
1807 } else if ($forum->scale < 0) {
1808 $params['gradetype'] = GRADE_TYPE_SCALE;
1809 $params['scaleid'] = -$forum->scale;
1812 if ($grades === 'reset') {
1813 $params['reset'] = true;
1814 $grades = NULL;
1817 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
1821 * Delete grade item for given forum
1823 * @category grade
1824 * @param stdClass $forum Forum object
1825 * @return grade_item
1827 function forum_grade_item_delete($forum) {
1828 global $CFG;
1829 require_once($CFG->libdir.'/gradelib.php');
1831 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
1836 * This function returns if a scale is being used by one forum
1838 * @global object
1839 * @param int $forumid
1840 * @param int $scaleid negative number
1841 * @return bool
1843 function forum_scale_used ($forumid,$scaleid) {
1844 global $DB;
1845 $return = false;
1847 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1849 if (!empty($rec) && !empty($scaleid)) {
1850 $return = true;
1853 return $return;
1857 * Checks if scale is being used by any instance of forum
1859 * This is used to find out if scale used anywhere
1861 * @global object
1862 * @param $scaleid int
1863 * @return boolean True if the scale is used by any forum
1865 function forum_scale_used_anywhere($scaleid) {
1866 global $DB;
1867 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1868 return true;
1869 } else {
1870 return false;
1874 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1877 * Gets a post with all info ready for forum_print_post
1878 * Most of these joins are just to get the forum id
1880 * @global object
1881 * @global object
1882 * @param int $postid
1883 * @return mixed array of posts or false
1885 function forum_get_post_full($postid) {
1886 global $CFG, $DB;
1888 $allnames = get_all_user_name_fields(true, 'u');
1889 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1890 FROM {forum_posts} p
1891 JOIN {forum_discussions} d ON p.discussion = d.id
1892 LEFT JOIN {user} u ON p.userid = u.id
1893 WHERE p.id = ?", array($postid));
1897 * Gets all posts in discussion including top parent.
1899 * @global object
1900 * @global object
1901 * @global object
1902 * @param int $discussionid
1903 * @param string $sort
1904 * @param bool $tracking does user track the forum?
1905 * @return array of posts
1907 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1908 global $CFG, $DB, $USER;
1910 $tr_sel = "";
1911 $tr_join = "";
1912 $params = array();
1914 if ($tracking) {
1915 $now = time();
1916 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1917 $tr_sel = ", fr.id AS postread";
1918 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1919 $params[] = $USER->id;
1922 $allnames = get_all_user_name_fields(true, 'u');
1923 $params[] = $discussionid;
1924 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1925 FROM {forum_posts} p
1926 LEFT JOIN {user} u ON p.userid = u.id
1927 $tr_join
1928 WHERE p.discussion = ?
1929 ORDER BY $sort", $params)) {
1930 return array();
1933 foreach ($posts as $pid=>$p) {
1934 if ($tracking) {
1935 if (forum_tp_is_post_old($p)) {
1936 $posts[$pid]->postread = true;
1939 if (!$p->parent) {
1940 continue;
1942 if (!isset($posts[$p->parent])) {
1943 continue; // parent does not exist??
1945 if (!isset($posts[$p->parent]->children)) {
1946 $posts[$p->parent]->children = array();
1948 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1951 // Start with the last child of the first post.
1952 $post = &$posts[reset($posts)->id];
1954 $lastpost = false;
1955 while (!$lastpost) {
1956 if (!isset($post->children)) {
1957 $post->lastpost = true;
1958 $lastpost = true;
1959 } else {
1960 // Go to the last child of this post.
1961 $post = &$posts[end($post->children)->id];
1965 return $posts;
1969 * An array of forum objects that the user is allowed to read/search through.
1971 * @global object
1972 * @global object
1973 * @global object
1974 * @param int $userid
1975 * @param int $courseid if 0, we look for forums throughout the whole site.
1976 * @return array of forum objects, or false if no matches
1977 * Forum objects have the following attributes:
1978 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1979 * viewhiddentimedposts
1981 function forum_get_readable_forums($userid, $courseid=0) {
1983 global $CFG, $DB, $USER;
1984 require_once($CFG->dirroot.'/course/lib.php');
1986 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1987 print_error('notinstalled', 'forum');
1990 if ($courseid) {
1991 $courses = $DB->get_records('course', array('id' => $courseid));
1992 } else {
1993 // If no course is specified, then the user can see SITE + his courses.
1994 $courses1 = $DB->get_records('course', array('id' => SITEID));
1995 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1996 $courses = array_merge($courses1, $courses2);
1998 if (!$courses) {
1999 return array();
2002 $readableforums = array();
2004 foreach ($courses as $course) {
2006 $modinfo = get_fast_modinfo($course);
2008 if (empty($modinfo->instances['forum'])) {
2009 // hmm, no forums?
2010 continue;
2013 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2015 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
2016 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
2017 continue;
2019 $context = context_module::instance($cm->id);
2020 $forum = $courseforums[$forumid];
2021 $forum->context = $context;
2022 $forum->cm = $cm;
2024 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2025 continue;
2028 /// group access
2029 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2031 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
2032 $forum->onlygroups[] = -1;
2035 /// hidden timed discussions
2036 $forum->viewhiddentimedposts = true;
2037 if (!empty($CFG->forum_enabletimedposts)) {
2038 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
2039 $forum->viewhiddentimedposts = false;
2043 /// qanda access
2044 if ($forum->type == 'qanda'
2045 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2047 // We need to check whether the user has posted in the qanda forum.
2048 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
2049 // the user is allowed to see in this forum.
2050 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
2051 foreach ($discussionspostedin as $d) {
2052 $forum->onlydiscussions[] = $d->id;
2057 $readableforums[$forum->id] = $forum;
2060 unset($modinfo);
2062 } // End foreach $courses
2064 return $readableforums;
2068 * Returns a list of posts found using an array of search terms.
2070 * @global object
2071 * @global object
2072 * @global object
2073 * @param array $searchterms array of search terms, e.g. word +word -word
2074 * @param int $courseid if 0, we search through the whole site
2075 * @param int $limitfrom
2076 * @param int $limitnum
2077 * @param int &$totalcount
2078 * @param string $extrasql
2079 * @return array|bool Array of posts found or false
2081 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2082 &$totalcount, $extrasql='') {
2083 global $CFG, $DB, $USER;
2084 require_once($CFG->libdir.'/searchlib.php');
2086 $forums = forum_get_readable_forums($USER->id, $courseid);
2088 if (count($forums) == 0) {
2089 $totalcount = 0;
2090 return false;
2093 $now = round(time(), -2); // db friendly
2095 $fullaccess = array();
2096 $where = array();
2097 $params = array();
2099 foreach ($forums as $forumid => $forum) {
2100 $select = array();
2102 if (!$forum->viewhiddentimedposts) {
2103 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2104 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2107 $cm = $forum->cm;
2108 $context = $forum->context;
2110 if ($forum->type == 'qanda'
2111 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2112 if (!empty($forum->onlydiscussions)) {
2113 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
2114 $params = array_merge($params, $discussionid_params);
2115 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2116 } else {
2117 $select[] = "p.parent = 0";
2121 if (!empty($forum->onlygroups)) {
2122 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
2123 $params = array_merge($params, $groupid_params);
2124 $select[] = "d.groupid $groupid_sql";
2127 if ($select) {
2128 $selects = implode(" AND ", $select);
2129 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2130 $params['forum'.$forumid] = $forumid;
2131 } else {
2132 $fullaccess[] = $forumid;
2136 if ($fullaccess) {
2137 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
2138 $params = array_merge($params, $fullid_params);
2139 $where[] = "(d.forum $fullid_sql)";
2142 $selectdiscussion = "(".implode(" OR ", $where).")";
2144 $messagesearch = '';
2145 $searchstring = '';
2147 // Need to concat these back together for parser to work.
2148 foreach($searchterms as $searchterm){
2149 if ($searchstring != '') {
2150 $searchstring .= ' ';
2152 $searchstring .= $searchterm;
2155 // We need to allow quoted strings for the search. The quotes *should* be stripped
2156 // by the parser, but this should be examined carefully for security implications.
2157 $searchstring = str_replace("\\\"","\"",$searchstring);
2158 $parser = new search_parser();
2159 $lexer = new search_lexer($parser);
2161 if ($lexer->parse($searchstring)) {
2162 $parsearray = $parser->get_parsed_array();
2163 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2164 'p.userid', 'u.id', 'u.firstname',
2165 'u.lastname', 'p.modified', 'd.forum');
2166 $params = array_merge($params, $msparams);
2169 $fromsql = "{forum_posts} p,
2170 {forum_discussions} d,
2171 {user} u";
2173 $selectsql = " $messagesearch
2174 AND p.discussion = d.id
2175 AND p.userid = u.id
2176 AND $selectdiscussion
2177 $extrasql";
2179 $countsql = "SELECT COUNT(*)
2180 FROM $fromsql
2181 WHERE $selectsql";
2183 $allnames = get_all_user_name_fields(true, 'u');
2184 $searchsql = "SELECT p.*,
2185 d.forum,
2186 $allnames,
2187 u.email,
2188 u.picture,
2189 u.imagealt
2190 FROM $fromsql
2191 WHERE $selectsql
2192 ORDER BY p.modified DESC";
2194 $totalcount = $DB->count_records_sql($countsql, $params);
2196 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2200 * Returns a list of all new posts that have not been mailed yet
2202 * @param int $starttime posts created after this time
2203 * @param int $endtime posts created before this
2204 * @param int $now used for timed discussions only
2205 * @return array
2207 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2208 global $CFG, $DB;
2210 $params = array();
2211 $params['mailed'] = FORUM_MAILED_PENDING;
2212 $params['ptimestart'] = $starttime;
2213 $params['ptimeend'] = $endtime;
2214 $params['mailnow'] = 1;
2216 if (!empty($CFG->forum_enabletimedposts)) {
2217 if (empty($now)) {
2218 $now = time();
2220 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2221 $params['dtimestart'] = $now;
2222 $params['dtimeend'] = $now;
2223 } else {
2224 $timedsql = "";
2227 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2228 FROM {forum_posts} p
2229 JOIN {forum_discussions} d ON d.id = p.discussion
2230 WHERE p.mailed = :mailed
2231 AND p.created >= :ptimestart
2232 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2233 $timedsql
2234 ORDER BY p.modified ASC", $params);
2238 * Marks posts before a certain time as being mailed already
2240 * @global object
2241 * @global object
2242 * @param int $endtime
2243 * @param int $now Defaults to time()
2244 * @return bool
2246 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2247 global $CFG, $DB;
2249 if (empty($now)) {
2250 $now = time();
2253 $params = array();
2254 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2255 $params['now'] = $now;
2256 $params['endtime'] = $endtime;
2257 $params['mailnow'] = 1;
2258 $params['mailedpending'] = FORUM_MAILED_PENDING;
2260 if (empty($CFG->forum_enabletimedposts)) {
2261 return $DB->execute("UPDATE {forum_posts}
2262 SET mailed = :mailedsuccess
2263 WHERE (created < :endtime OR mailnow = :mailnow)
2264 AND mailed = :mailedpending", $params);
2265 } else {
2266 return $DB->execute("UPDATE {forum_posts}
2267 SET mailed = :mailedsuccess
2268 WHERE discussion NOT IN (SELECT d.id
2269 FROM {forum_discussions} d
2270 WHERE d.timestart > :now)
2271 AND (created < :endtime OR mailnow = :mailnow)
2272 AND mailed = :mailedpending", $params);
2277 * Get all the posts for a user in a forum suitable for forum_print_post
2279 * @global object
2280 * @global object
2281 * @uses CONTEXT_MODULE
2282 * @return array
2284 function forum_get_user_posts($forumid, $userid) {
2285 global $CFG, $DB;
2287 $timedsql = "";
2288 $params = array($forumid, $userid);
2290 if (!empty($CFG->forum_enabletimedposts)) {
2291 $cm = get_coursemodule_from_instance('forum', $forumid);
2292 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2293 $now = time();
2294 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2295 $params[] = $now;
2296 $params[] = $now;
2300 $allnames = get_all_user_name_fields(true, 'u');
2301 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2302 FROM {forum} f
2303 JOIN {forum_discussions} d ON d.forum = f.id
2304 JOIN {forum_posts} p ON p.discussion = d.id
2305 JOIN {user} u ON u.id = p.userid
2306 WHERE f.id = ?
2307 AND p.userid = ?
2308 $timedsql
2309 ORDER BY p.modified ASC", $params);
2313 * Get all the discussions user participated in
2315 * @global object
2316 * @global object
2317 * @uses CONTEXT_MODULE
2318 * @param int $forumid
2319 * @param int $userid
2320 * @return array Array or false
2322 function forum_get_user_involved_discussions($forumid, $userid) {
2323 global $CFG, $DB;
2325 $timedsql = "";
2326 $params = array($forumid, $userid);
2327 if (!empty($CFG->forum_enabletimedposts)) {
2328 $cm = get_coursemodule_from_instance('forum', $forumid);
2329 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2330 $now = time();
2331 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2332 $params[] = $now;
2333 $params[] = $now;
2337 return $DB->get_records_sql("SELECT DISTINCT d.*
2338 FROM {forum} f
2339 JOIN {forum_discussions} d ON d.forum = f.id
2340 JOIN {forum_posts} p ON p.discussion = d.id
2341 WHERE f.id = ?
2342 AND p.userid = ?
2343 $timedsql", $params);
2347 * Get all the posts for a user in a forum suitable for forum_print_post
2349 * @global object
2350 * @global object
2351 * @param int $forumid
2352 * @param int $userid
2353 * @return array of counts or false
2355 function forum_count_user_posts($forumid, $userid) {
2356 global $CFG, $DB;
2358 $timedsql = "";
2359 $params = array($forumid, $userid);
2360 if (!empty($CFG->forum_enabletimedposts)) {
2361 $cm = get_coursemodule_from_instance('forum', $forumid);
2362 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
2363 $now = time();
2364 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2365 $params[] = $now;
2366 $params[] = $now;
2370 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2371 FROM {forum} f
2372 JOIN {forum_discussions} d ON d.forum = f.id
2373 JOIN {forum_posts} p ON p.discussion = d.id
2374 JOIN {user} u ON u.id = p.userid
2375 WHERE f.id = ?
2376 AND p.userid = ?
2377 $timedsql", $params);
2381 * Given a log entry, return the forum post details for it.
2383 * @global object
2384 * @global object
2385 * @param object $log
2386 * @return array|null
2388 function forum_get_post_from_log($log) {
2389 global $CFG, $DB;
2391 $allnames = get_all_user_name_fields(true, 'u');
2392 if ($log->action == "add post") {
2394 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2395 FROM {forum_discussions} d,
2396 {forum_posts} p,
2397 {forum} f,
2398 {user} u
2399 WHERE p.id = ?
2400 AND d.id = p.discussion
2401 AND p.userid = u.id
2402 AND u.deleted <> '1'
2403 AND f.id = d.forum", array($log->info));
2406 } else if ($log->action == "add discussion") {
2408 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2409 FROM {forum_discussions} d,
2410 {forum_posts} p,
2411 {forum} f,
2412 {user} u
2413 WHERE d.id = ?
2414 AND d.firstpost = p.id
2415 AND p.userid = u.id
2416 AND u.deleted <> '1'
2417 AND f.id = d.forum", array($log->info));
2419 return NULL;
2423 * Given a discussion id, return the first post from the discussion
2425 * @global object
2426 * @global object
2427 * @param int $dicsussionid
2428 * @return array
2430 function forum_get_firstpost_from_discussion($discussionid) {
2431 global $CFG, $DB;
2433 return $DB->get_record_sql("SELECT p.*
2434 FROM {forum_discussions} d,
2435 {forum_posts} p
2436 WHERE d.id = ?
2437 AND d.firstpost = p.id ", array($discussionid));
2441 * Returns an array of counts of replies to each discussion
2443 * @global object
2444 * @global object
2445 * @param int $forumid
2446 * @param string $forumsort
2447 * @param int $limit
2448 * @param int $page
2449 * @param int $perpage
2450 * @return array
2452 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2453 global $CFG, $DB;
2455 if ($limit > 0) {
2456 $limitfrom = 0;
2457 $limitnum = $limit;
2458 } else if ($page != -1) {
2459 $limitfrom = $page*$perpage;
2460 $limitnum = $perpage;
2461 } else {
2462 $limitfrom = 0;
2463 $limitnum = 0;
2466 if ($forumsort == "") {
2467 $orderby = "";
2468 $groupby = "";
2470 } else {
2471 $orderby = "ORDER BY $forumsort";
2472 $groupby = ", ".strtolower($forumsort);
2473 $groupby = str_replace('desc', '', $groupby);
2474 $groupby = str_replace('asc', '', $groupby);
2477 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2478 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2479 FROM {forum_posts} p
2480 JOIN {forum_discussions} d ON p.discussion = d.id
2481 WHERE p.parent > 0 AND d.forum = ?
2482 GROUP BY p.discussion";
2483 return $DB->get_records_sql($sql, array($forumid));
2485 } else {
2486 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2487 FROM {forum_posts} p
2488 JOIN {forum_discussions} d ON p.discussion = d.id
2489 WHERE d.forum = ?
2490 GROUP BY p.discussion $groupby $orderby";
2491 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2496 * @global object
2497 * @global object
2498 * @global object
2499 * @staticvar array $cache
2500 * @param object $forum
2501 * @param object $cm
2502 * @param object $course
2503 * @return mixed
2505 function forum_count_discussions($forum, $cm, $course) {
2506 global $CFG, $DB, $USER;
2508 static $cache = array();
2510 $now = round(time(), -2); // db cache friendliness
2512 $params = array($course->id);
2514 if (!isset($cache[$course->id])) {
2515 if (!empty($CFG->forum_enabletimedposts)) {
2516 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2517 $params[] = $now;
2518 $params[] = $now;
2519 } else {
2520 $timedsql = "";
2523 $sql = "SELECT f.id, COUNT(d.id) as dcount
2524 FROM {forum} f
2525 JOIN {forum_discussions} d ON d.forum = f.id
2526 WHERE f.course = ?
2527 $timedsql
2528 GROUP BY f.id";
2530 if ($counts = $DB->get_records_sql($sql, $params)) {
2531 foreach ($counts as $count) {
2532 $counts[$count->id] = $count->dcount;
2534 $cache[$course->id] = $counts;
2535 } else {
2536 $cache[$course->id] = array();
2540 if (empty($cache[$course->id][$forum->id])) {
2541 return 0;
2544 $groupmode = groups_get_activity_groupmode($cm, $course);
2546 if ($groupmode != SEPARATEGROUPS) {
2547 return $cache[$course->id][$forum->id];
2550 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
2551 return $cache[$course->id][$forum->id];
2554 require_once($CFG->dirroot.'/course/lib.php');
2556 $modinfo = get_fast_modinfo($course);
2558 $mygroups = $modinfo->get_groups($cm->groupingid);
2560 // add all groups posts
2561 $mygroups[-1] = -1;
2563 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2564 $params[] = $forum->id;
2566 if (!empty($CFG->forum_enabletimedposts)) {
2567 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2568 $params[] = $now;
2569 $params[] = $now;
2570 } else {
2571 $timedsql = "";
2574 $sql = "SELECT COUNT(d.id)
2575 FROM {forum_discussions} d
2576 WHERE d.groupid $mygroups_sql AND d.forum = ?
2577 $timedsql";
2579 return $DB->get_field_sql($sql, $params);
2583 * Get all discussions in a forum
2585 * @global object
2586 * @global object
2587 * @global object
2588 * @uses CONTEXT_MODULE
2589 * @uses VISIBLEGROUPS
2590 * @param object $cm
2591 * @param string $forumsort
2592 * @param bool $fullpost
2593 * @param int $unused
2594 * @param int $limit
2595 * @param bool $userlastmodified
2596 * @param int $page
2597 * @param int $perpage
2598 * @return array
2600 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2601 global $CFG, $DB, $USER;
2603 $timelimit = '';
2605 $now = round(time(), -2);
2606 $params = array($cm->instance);
2608 $modcontext = context_module::instance($cm->id);
2610 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2611 return array();
2614 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2616 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2617 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2618 $params[] = $now;
2619 $params[] = $now;
2620 if (isloggedin()) {
2621 $timelimit .= " OR d.userid = ?";
2622 $params[] = $USER->id;
2624 $timelimit .= ")";
2628 if ($limit > 0) {
2629 $limitfrom = 0;
2630 $limitnum = $limit;
2631 } else if ($page != -1) {
2632 $limitfrom = $page*$perpage;
2633 $limitnum = $perpage;
2634 } else {
2635 $limitfrom = 0;
2636 $limitnum = 0;
2639 $groupmode = groups_get_activity_groupmode($cm);
2640 $currentgroup = groups_get_activity_group($cm);
2642 if ($groupmode) {
2643 if (empty($modcontext)) {
2644 $modcontext = context_module::instance($cm->id);
2647 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2648 if ($currentgroup) {
2649 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2650 $params[] = $currentgroup;
2651 } else {
2652 $groupselect = "";
2655 } else {
2656 //seprate groups without access all
2657 if ($currentgroup) {
2658 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2659 $params[] = $currentgroup;
2660 } else {
2661 $groupselect = "AND d.groupid = -1";
2664 } else {
2665 $groupselect = "";
2669 if (empty($forumsort)) {
2670 $forumsort = "d.timemodified DESC";
2672 if (empty($fullpost)) {
2673 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2674 } else {
2675 $postdata = "p.*";
2678 if (empty($userlastmodified)) { // We don't need to know this
2679 $umfields = "";
2680 $umtable = "";
2681 } else {
2682 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
2683 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2686 $allnames = get_all_user_name_fields(true, 'u');
2687 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2688 u.email, u.picture, u.imagealt $umfields
2689 FROM {forum_discussions} d
2690 JOIN {forum_posts} p ON p.discussion = d.id
2691 JOIN {user} u ON p.userid = u.id
2692 $umtable
2693 WHERE d.forum = ? AND p.parent = 0
2694 $timelimit $groupselect
2695 ORDER BY $forumsort";
2696 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2700 * Gets the neighbours (previous and next) of a discussion.
2702 * The calculation is based on the timemodified of the discussion and does not handle
2703 * the neighbours having an identical timemodified. The reason is that we do not have any
2704 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2705 * timemodified.
2707 * Please note that this does not check whether or not the discussion passed is accessible
2708 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2709 * the returned neighbours are checked and are accessible to the current user.
2711 * @param object $cm The CM record.
2712 * @param object $discussion The discussion record.
2713 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2714 * they contain the record with minimal information such as 'id' and 'name'.
2715 * When the neighbour is not found the value is false.
2717 function forum_get_discussion_neighbours($cm, $discussion) {
2718 global $CFG, $DB, $USER;
2720 if ($cm->instance != $discussion->forum) {
2721 throw new coding_exception('Discussion is not part of the same forum.');
2724 $neighbours = array('prev' => false, 'next' => false);
2725 $now = round(time(), -2);
2726 $params = array();
2728 $modcontext = context_module::instance($cm->id);
2729 $groupmode = groups_get_activity_groupmode($cm);
2730 $currentgroup = groups_get_activity_group($cm);
2732 // Users must fulfill timed posts.
2733 $timelimit = '';
2734 if (!empty($CFG->forum_enabletimedposts)) {
2735 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2736 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2737 $params['tltimestart'] = $now;
2738 $params['tltimeend'] = $now;
2739 if (isloggedin()) {
2740 $timelimit .= ' OR d.userid = :tluserid';
2741 $params['tluserid'] = $USER->id;
2743 $timelimit .= ')';
2747 // Limiting to posts accessible according to groups.
2748 $groupselect = '';
2749 if ($groupmode) {
2750 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2751 if ($currentgroup) {
2752 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2753 $params['groupid'] = $currentgroup;
2755 } else {
2756 if ($currentgroup) {
2757 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2758 $params['groupid'] = $currentgroup;
2759 } else {
2760 $groupselect = 'AND d.groupid = -1';
2765 $params['forumid'] = $cm->instance;
2766 $params['discid'] = $discussion->id;
2767 $params['disctimemodified'] = $discussion->timemodified;
2769 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2770 FROM {forum_discussions} d
2771 WHERE d.forum = :forumid
2772 AND d.id <> :discid
2773 $timelimit
2774 $groupselect";
2776 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2777 ORDER BY d.timemodified DESC";
2779 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2780 ORDER BY d.timemodified ASC";
2782 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2783 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2785 return $neighbours;
2790 * @global object
2791 * @global object
2792 * @global object
2793 * @uses CONTEXT_MODULE
2794 * @uses VISIBLEGROUPS
2795 * @param object $cm
2796 * @return array
2798 function forum_get_discussions_unread($cm) {
2799 global $CFG, $DB, $USER;
2801 $now = round(time(), -2);
2802 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2804 $params = array();
2805 $groupmode = groups_get_activity_groupmode($cm);
2806 $currentgroup = groups_get_activity_group($cm);
2808 if ($groupmode) {
2809 $modcontext = context_module::instance($cm->id);
2811 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2812 if ($currentgroup) {
2813 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2814 $params['currentgroup'] = $currentgroup;
2815 } else {
2816 $groupselect = "";
2819 } else {
2820 //separate groups without access all
2821 if ($currentgroup) {
2822 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2823 $params['currentgroup'] = $currentgroup;
2824 } else {
2825 $groupselect = "AND d.groupid = -1";
2828 } else {
2829 $groupselect = "";
2832 if (!empty($CFG->forum_enabletimedposts)) {
2833 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2834 $params['now1'] = $now;
2835 $params['now2'] = $now;
2836 } else {
2837 $timedsql = "";
2840 $sql = "SELECT d.id, COUNT(p.id) AS unread
2841 FROM {forum_discussions} d
2842 JOIN {forum_posts} p ON p.discussion = d.id
2843 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2844 WHERE d.forum = {$cm->instance}
2845 AND p.modified >= :cutoffdate AND r.id is NULL
2846 $groupselect
2847 $timedsql
2848 GROUP BY d.id";
2849 $params['cutoffdate'] = $cutoffdate;
2851 if ($unreads = $DB->get_records_sql($sql, $params)) {
2852 foreach ($unreads as $unread) {
2853 $unreads[$unread->id] = $unread->unread;
2855 return $unreads;
2856 } else {
2857 return array();
2862 * @global object
2863 * @global object
2864 * @global object
2865 * @uses CONEXT_MODULE
2866 * @uses VISIBLEGROUPS
2867 * @param object $cm
2868 * @return array
2870 function forum_get_discussions_count($cm) {
2871 global $CFG, $DB, $USER;
2873 $now = round(time(), -2);
2874 $params = array($cm->instance);
2875 $groupmode = groups_get_activity_groupmode($cm);
2876 $currentgroup = groups_get_activity_group($cm);
2878 if ($groupmode) {
2879 $modcontext = context_module::instance($cm->id);
2881 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2882 if ($currentgroup) {
2883 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2884 $params[] = $currentgroup;
2885 } else {
2886 $groupselect = "";
2889 } else {
2890 //seprate groups without access all
2891 if ($currentgroup) {
2892 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2893 $params[] = $currentgroup;
2894 } else {
2895 $groupselect = "AND d.groupid = -1";
2898 } else {
2899 $groupselect = "";
2902 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2904 $timelimit = "";
2906 if (!empty($CFG->forum_enabletimedposts)) {
2908 $modcontext = context_module::instance($cm->id);
2910 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2911 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2912 $params[] = $now;
2913 $params[] = $now;
2914 if (isloggedin()) {
2915 $timelimit .= " OR d.userid = ?";
2916 $params[] = $USER->id;
2918 $timelimit .= ")";
2922 $sql = "SELECT COUNT(d.id)
2923 FROM {forum_discussions} d
2924 JOIN {forum_posts} p ON p.discussion = d.id
2925 WHERE d.forum = ? AND p.parent = 0
2926 $groupselect $timelimit";
2928 return $DB->get_field_sql($sql, $params);
2932 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2936 * @global object
2937 * @global object
2938 * @param int $courseid
2939 * @param string $type
2941 function forum_get_course_forum($courseid, $type) {
2942 // How to set up special 1-per-course forums
2943 global $CFG, $DB, $OUTPUT, $USER;
2945 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2946 // There should always only be ONE, but with the right combination of
2947 // errors there might be more. In this case, just return the oldest one (lowest ID).
2948 foreach ($forums as $forum) {
2949 return $forum; // ie the first one
2953 // Doesn't exist, so create one now.
2954 $forum = new stdClass();
2955 $forum->course = $courseid;
2956 $forum->type = "$type";
2957 if (!empty($USER->htmleditor)) {
2958 $forum->introformat = $USER->htmleditor;
2960 switch ($forum->type) {
2961 case "news":
2962 $forum->name = get_string("namenews", "forum");
2963 $forum->intro = get_string("intronews", "forum");
2964 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
2965 $forum->assessed = 0;
2966 if ($courseid == SITEID) {
2967 $forum->name = get_string("sitenews");
2968 $forum->forcesubscribe = 0;
2970 break;
2971 case "social":
2972 $forum->name = get_string("namesocial", "forum");
2973 $forum->intro = get_string("introsocial", "forum");
2974 $forum->assessed = 0;
2975 $forum->forcesubscribe = 0;
2976 break;
2977 case "blog":
2978 $forum->name = get_string('blogforum', 'forum');
2979 $forum->intro = get_string('introblog', 'forum');
2980 $forum->assessed = 0;
2981 $forum->forcesubscribe = 0;
2982 break;
2983 default:
2984 echo $OUTPUT->notification("That forum type doesn't exist!");
2985 return false;
2986 break;
2989 $forum->timemodified = time();
2990 $forum->id = $DB->insert_record("forum", $forum);
2992 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2993 echo $OUTPUT->notification("Could not find forum module!!");
2994 return false;
2996 $mod = new stdClass();
2997 $mod->course = $courseid;
2998 $mod->module = $module->id;
2999 $mod->instance = $forum->id;
3000 $mod->section = 0;
3001 include_once("$CFG->dirroot/course/lib.php");
3002 if (! $mod->coursemodule = add_course_module($mod) ) {
3003 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3004 return false;
3006 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
3007 return $DB->get_record("forum", array("id" => "$forum->id"));
3012 * Given the data about a posting, builds up the HTML to display it and
3013 * returns the HTML in a string. This is designed for sending via HTML email.
3015 * @global object
3016 * @param object $course
3017 * @param object $cm
3018 * @param object $forum
3019 * @param object $discussion
3020 * @param object $post
3021 * @param object $userform
3022 * @param object $userto
3023 * @param bool $ownpost
3024 * @param bool $reply
3025 * @param bool $link
3026 * @param bool $rate
3027 * @param string $footer
3028 * @return string
3030 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
3031 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
3033 global $CFG, $OUTPUT;
3035 $modcontext = context_module::instance($cm->id);
3037 if (!isset($userto->viewfullnames[$forum->id])) {
3038 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3039 } else {
3040 $viewfullnames = $userto->viewfullnames[$forum->id];
3043 // add absolute file links
3044 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3046 // format the post body
3047 $options = new stdClass();
3048 $options->para = true;
3049 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
3051 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3053 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3054 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
3055 $output .= '</td>';
3057 if ($post->parent) {
3058 $output .= '<td class="topic">';
3059 } else {
3060 $output .= '<td class="topic starter">';
3062 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
3064 $fullname = fullname($userfrom, $viewfullnames);
3065 $by = new stdClass();
3066 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
3067 $by->date = userdate($post->modified, '', core_date::get_user_timezone($userto));
3068 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3070 $output .= '</td></tr>';
3072 $output .= '<tr><td class="left side" valign="top">';
3074 if (isset($userfrom->groups)) {
3075 $groups = $userfrom->groups[$forum->id];
3076 } else {
3077 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
3080 if ($groups) {
3081 $output .= print_group_picture($groups, $course->id, false, true, true);
3082 } else {
3083 $output .= '&nbsp;';
3086 $output .= '</td><td class="content">';
3088 $attachments = forum_print_attachments($post, $cm, 'html');
3089 if ($attachments !== '') {
3090 $output .= '<div class="attachments">';
3091 $output .= $attachments;
3092 $output .= '</div>';
3095 $output .= $formattedtext;
3097 // Commands
3098 $commands = array();
3100 if ($post->parent) {
3101 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
3102 $post->discussion.'&amp;parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
3105 if ($reply) {
3106 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
3107 get_string('reply', 'forum').'</a>';
3110 $output .= '<div class="commands">';
3111 $output .= implode(' | ', $commands);
3112 $output .= '</div>';
3114 // Context link to post if required
3115 if ($link) {
3116 $output .= '<div class="link">';
3117 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id.'">'.
3118 get_string('postincontext', 'forum').'</a>';
3119 $output .= '</div>';
3122 if ($footer) {
3123 $output .= '<div class="footer">'.$footer.'</div>';
3125 $output .= '</td></tr></table>'."\n\n";
3127 return $output;
3131 * Print a forum post
3133 * @global object
3134 * @global object
3135 * @uses FORUM_MODE_THREADED
3136 * @uses PORTFOLIO_FORMAT_PLAINHTML
3137 * @uses PORTFOLIO_FORMAT_FILE
3138 * @uses PORTFOLIO_FORMAT_RICHHTML
3139 * @uses PORTFOLIO_ADD_TEXT_LINK
3140 * @uses CONTEXT_MODULE
3141 * @param object $post The post to print.
3142 * @param object $discussion
3143 * @param object $forum
3144 * @param object $cm
3145 * @param object $course
3146 * @param boolean $ownpost Whether this post belongs to the current user.
3147 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3148 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3149 * @param string $footer Extra stuff to print after the message.
3150 * @param string $highlight Space-separated list of terms to highlight.
3151 * @param int $post_read true, false or -99. If we already know whether this user
3152 * has read this post, pass that in, otherwise, pass in -99, and this
3153 * function will work it out.
3154 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3155 * the current user can't see this post, if this argument is true
3156 * (the default) then print a dummy 'you can't see this post' post.
3157 * If false, don't output anything at all.
3158 * @param bool|null $istracked
3159 * @return void
3161 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3162 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3163 global $USER, $CFG, $OUTPUT;
3165 require_once($CFG->libdir . '/filelib.php');
3167 // String cache
3168 static $str;
3170 $modcontext = context_module::instance($cm->id);
3172 $post->course = $course->id;
3173 $post->forum = $forum->id;
3174 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3175 if (!empty($CFG->enableplagiarism)) {
3176 require_once($CFG->libdir.'/plagiarismlib.php');
3177 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3178 'content' => $post->message,
3179 'cmid' => $cm->id,
3180 'course' => $post->course,
3181 'forum' => $post->forum));
3184 // caching
3185 if (!isset($cm->cache)) {
3186 $cm->cache = new stdClass;
3189 if (!isset($cm->cache->caps)) {
3190 $cm->cache->caps = array();
3191 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3192 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3193 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3194 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3195 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3196 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3197 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3198 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3199 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3202 if (!isset($cm->uservisible)) {
3203 $cm->uservisible = \core_availability\info_module::is_user_visible($cm, 0, false);
3206 if ($istracked && is_null($postisread)) {
3207 $postisread = forum_tp_is_post_read($USER->id, $post);
3210 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3211 $output = '';
3212 if (!$dummyifcantsee) {
3213 if ($return) {
3214 return $output;
3216 echo $output;
3217 return;
3219 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3220 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix',
3221 'role' => 'region',
3222 'aria-label' => get_string('hiddenforumpost', 'forum')));
3223 $output .= html_writer::start_tag('div', array('class'=>'row header'));
3224 $output .= html_writer::tag('div', '', array('class'=>'left picture')); // Picture
3225 if ($post->parent) {
3226 $output .= html_writer::start_tag('div', array('class'=>'topic'));
3227 } else {
3228 $output .= html_writer::start_tag('div', array('class'=>'topic starter'));
3230 $output .= html_writer::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3231 'role' => 'header')); // Subject.
3232 $output .= html_writer::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3233 'role' => 'header')); // Author.
3234 $output .= html_writer::end_tag('div');
3235 $output .= html_writer::end_tag('div'); // row
3236 $output .= html_writer::start_tag('div', array('class'=>'row'));
3237 $output .= html_writer::tag('div', '&nbsp;', array('class'=>'left side')); // Groups
3238 $output .= html_writer::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3239 $output .= html_writer::end_tag('div'); // row
3240 $output .= html_writer::end_tag('div'); // forumpost
3242 if ($return) {
3243 return $output;
3245 echo $output;
3246 return;
3249 if (empty($str)) {
3250 $str = new stdClass;
3251 $str->edit = get_string('edit', 'forum');
3252 $str->delete = get_string('delete', 'forum');
3253 $str->reply = get_string('reply', 'forum');
3254 $str->parent = get_string('parent', 'forum');
3255 $str->pruneheading = get_string('pruneheading', 'forum');
3256 $str->prune = get_string('prune', 'forum');
3257 $str->displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
3258 $str->markread = get_string('markread', 'forum');
3259 $str->markunread = get_string('markunread', 'forum');
3262 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion));
3264 // Build an object that represents the posting user
3265 $postuser = new stdClass;
3266 $postuserfields = explode(',', user_picture::fields());
3267 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3268 $postuser->id = $post->userid;
3269 $postuser->fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
3270 $postuser->profilelink = new moodle_url('/user/view.php', array('id'=>$post->userid, 'course'=>$course->id));
3272 // Prepare the groups the posting user belongs to
3273 if (isset($cm->cache->usersgroups)) {
3274 $groups = array();
3275 if (isset($cm->cache->usersgroups[$post->userid])) {
3276 foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
3277 $groups[$gid] = $cm->cache->groups[$gid];
3280 } else {
3281 $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
3284 // Prepare the attachements for the post, files then images
3285 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3287 // Determine if we need to shorten this post
3288 $shortenpost = ($link && (strlen(strip_tags($post->message)) > $CFG->forum_longpost));
3291 // Prepare an array of commands
3292 $commands = array();
3294 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3295 // Don't display the mark read / unread controls in this case.
3296 if ($istracked && $CFG->forum_usermarksread && isloggedin()) {
3297 $url = new moodle_url($discussionlink, array('postid'=>$post->id, 'mark'=>'unread'));
3298 $text = $str->markunread;
3299 if (!$postisread) {
3300 $url->param('mark', 'read');
3301 $text = $str->markread;
3303 if ($str->displaymode == FORUM_MODE_THREADED) {
3304 $url->param('parent', $post->parent);
3305 } else {
3306 $url->set_anchor('p'.$post->id);
3308 $commands[] = array('url'=>$url, 'text'=>$text);
3311 // Zoom in to the parent specifically
3312 if ($post->parent) {
3313 $url = new moodle_url($discussionlink);
3314 if ($str->displaymode == FORUM_MODE_THREADED) {
3315 $url->param('parent', $post->parent);
3316 } else {
3317 $url->set_anchor('p'.$post->parent);
3319 $commands[] = array('url'=>$url, 'text'=>$str->parent);
3322 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3323 $age = time() - $post->created;
3324 if (!$post->parent && $forum->type == 'news' && $discussion->timestart > time()) {
3325 $age = 0;
3328 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3329 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3330 // The first post in single simple is the forum description.
3331 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit);
3333 } else if (($ownpost && $age < $CFG->maxeditingtime) || $cm->cache->caps['mod/forum:editanypost']) {
3334 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id)), 'text'=>$str->edit);
3337 if ($cm->cache->caps['mod/forum:splitdiscussions'] && $post->parent && $forum->type != 'single') {
3338 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id)), 'text'=>$str->prune, 'title'=>$str->pruneheading);
3341 if ($forum->type == 'single' and $discussion->firstpost == $post->id) {
3342 // Do not allow deleting of first post in single simple type.
3343 } else if (($ownpost && $age < $CFG->maxeditingtime && $cm->cache->caps['mod/forum:deleteownpost']) || $cm->cache->caps['mod/forum:deleteanypost']) {
3344 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id)), 'text'=>$str->delete);
3347 if ($reply) {
3348 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id)), 'text'=>$str->reply);
3351 if ($CFG->enableportfolios && ($cm->cache->caps['mod/forum:exportpost'] || ($ownpost && $cm->cache->caps['mod/forum:exportownpost']))) {
3352 $p = array('postid' => $post->id);
3353 require_once($CFG->libdir.'/portfoliolib.php');
3354 $button = new portfolio_add_button();
3355 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id), 'mod_forum');
3356 if (empty($attachments)) {
3357 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML);
3358 } else {
3359 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML);
3362 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
3363 if (!empty($porfoliohtml)) {
3364 $commands[] = $porfoliohtml;
3367 // Finished building commands
3370 // Begin output
3372 $output = '';
3374 if ($istracked) {
3375 if ($postisread) {
3376 $forumpostclass = ' read';
3377 } else {
3378 $forumpostclass = ' unread';
3379 $output .= html_writer::tag('a', '', array('name'=>'unread'));
3381 } else {
3382 // ignore trackign status if not tracked or tracked param missing
3383 $forumpostclass = '';
3386 $topicclass = '';
3387 if (empty($post->parent)) {
3388 $topicclass = ' firstpost starter';
3391 if (!empty($post->lastpost)) {
3392 $forumpostclass .= ' lastpost';
3395 $postbyuser = new stdClass;
3396 $postbyuser->post = $post->subject;
3397 $postbyuser->user = $postuser->fullname;
3398 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3399 $output .= html_writer::tag('a', '', array('id'=>'p'.$post->id));
3400 $output .= html_writer::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3401 'role' => 'region',
3402 'aria-label' => $discussionbyuser));
3403 $output .= html_writer::start_tag('div', array('class'=>'row header clearfix'));
3404 $output .= html_writer::start_tag('div', array('class'=>'left picture'));
3405 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id));
3406 $output .= html_writer::end_tag('div');
3409 $output .= html_writer::start_tag('div', array('class'=>'topic'.$topicclass));
3411 $postsubject = $post->subject;
3412 if (empty($post->subjectnoformat)) {
3413 $postsubject = format_string($postsubject);
3415 $output .= html_writer::tag('div', $postsubject, array('class'=>'subject',
3416 'role' => 'heading',
3417 'aria-level' => '2'));
3419 $by = new stdClass();
3420 $by->name = html_writer::link($postuser->profilelink, $postuser->fullname);
3421 $by->date = userdate($post->modified);
3422 $output .= html_writer::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3423 'role' => 'heading',
3424 'aria-level' => '2'));
3426 $output .= html_writer::end_tag('div'); //topic
3427 $output .= html_writer::end_tag('div'); //row
3429 $output .= html_writer::start_tag('div', array('class'=>'row maincontent clearfix'));
3430 $output .= html_writer::start_tag('div', array('class'=>'left'));
3432 $groupoutput = '';
3433 if ($groups) {
3434 $groupoutput = print_group_picture($groups, $course->id, false, true, true);
3436 if (empty($groupoutput)) {
3437 $groupoutput = '&nbsp;';
3439 $output .= html_writer::tag('div', $groupoutput, array('class'=>'grouppictures'));
3441 $output .= html_writer::end_tag('div'); //left side
3442 $output .= html_writer::start_tag('div', array('class'=>'no-overflow'));
3443 $output .= html_writer::start_tag('div', array('class'=>'content'));
3445 $options = new stdClass;
3446 $options->para = false;
3447 $options->trusted = $post->messagetrust;
3448 $options->context = $modcontext;
3449 if ($shortenpost) {
3450 // Prepare shortened version by filtering the text then shortening it.
3451 $postclass = 'shortenedpost';
3452 $postcontent = format_text($post->message, $post->messageformat, $options);
3453 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost);
3454 $postcontent .= html_writer::link($discussionlink, get_string('readtherest', 'forum'));
3455 $postcontent .= html_writer::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message)).')',
3456 array('class'=>'post-word-count'));
3457 } else {
3458 // Prepare whole post
3459 $postclass = 'fullpost';
3460 $postcontent = format_text($post->message, $post->messageformat, $options, $course->id);
3461 if (!empty($highlight)) {
3462 $postcontent = highlight($highlight, $postcontent);
3464 if (!empty($forum->displaywordcount)) {
3465 $postcontent .= html_writer::tag('div', get_string('numwords', 'moodle', count_words($post->message)),
3466 array('class'=>'post-word-count'));
3468 $postcontent .= html_writer::tag('div', $attachedimages, array('class'=>'attachedimages'));
3471 // Output the post content
3472 $output .= html_writer::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3473 $output .= html_writer::end_tag('div'); // Content
3474 $output .= html_writer::end_tag('div'); // Content mask
3475 $output .= html_writer::end_tag('div'); // Row
3477 $output .= html_writer::start_tag('div', array('class'=>'row side'));
3478 $output .= html_writer::tag('div','&nbsp;', array('class'=>'left'));
3479 $output .= html_writer::start_tag('div', array('class'=>'options clearfix'));
3481 if (!empty($attachments)) {
3482 $output .= html_writer::tag('div', $attachments, array('class' => 'attachments'));
3485 // Output ratings
3486 if (!empty($post->rating)) {
3487 $output .= html_writer::tag('div', $OUTPUT->render($post->rating), array('class'=>'forum-post-rating'));
3490 // Output the commands
3491 $commandhtml = array();
3492 foreach ($commands as $command) {
3493 if (is_array($command)) {
3494 $commandhtml[] = html_writer::link($command['url'], $command['text']);
3495 } else {
3496 $commandhtml[] = $command;
3499 $output .= html_writer::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3501 // Output link to post if required
3502 if ($link && forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3503 if ($post->replies == 1) {
3504 $replystring = get_string('repliesone', 'forum', $post->replies);
3505 } else {
3506 $replystring = get_string('repliesmany', 'forum', $post->replies);
3508 if (!empty($discussion->unread) && $discussion->unread !== '-') {
3509 $replystring .= ' <span class="sep">/</span> <span class="unread">';
3510 if ($discussion->unread == 1) {
3511 $replystring .= get_string('unreadpostsone', 'forum');
3512 } else {
3513 $replystring .= get_string('unreadpostsnumber', 'forum', $discussion->unread);
3515 $replystring .= '</span>';
3518 $output .= html_writer::start_tag('div', array('class'=>'link'));
3519 $output .= html_writer::link($discussionlink, get_string('discussthistopic', 'forum'));
3520 $output .= '&nbsp;('.$replystring.')';
3521 $output .= html_writer::end_tag('div'); // link
3524 // Output footer if required
3525 if ($footer) {
3526 $output .= html_writer::tag('div', $footer, array('class'=>'footer'));
3529 // Close remaining open divs
3530 $output .= html_writer::end_tag('div'); // content
3531 $output .= html_writer::end_tag('div'); // row
3532 $output .= html_writer::end_tag('div'); // forumpost
3534 // Mark the forum post as read if required
3535 if ($istracked && !$CFG->forum_usermarksread && !$postisread) {
3536 forum_tp_mark_post_read($USER->id, $post, $forum->id);
3539 if ($return) {
3540 return $output;
3542 echo $output;
3543 return;
3547 * Return rating related permissions
3549 * @param string $options the context id
3550 * @return array an associative array of the user's rating permissions
3552 function forum_rating_permissions($contextid, $component, $ratingarea) {
3553 $context = context::instance_by_id($contextid, MUST_EXIST);
3554 if ($component != 'mod_forum' || $ratingarea != 'post') {
3555 // We don't know about this component/ratingarea so just return null to get the
3556 // default restrictive permissions.
3557 return null;
3559 return array(
3560 'view' => has_capability('mod/forum:viewrating', $context),
3561 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3562 'viewall' => has_capability('mod/forum:viewallratings', $context),
3563 'rate' => has_capability('mod/forum:rate', $context)
3568 * Validates a submitted rating
3569 * @param array $params submitted data
3570 * context => object the context in which the rated items exists [required]
3571 * component => The component for this module - should always be mod_forum [required]
3572 * ratingarea => object the context in which the rated items exists [required]
3573 * itemid => int the ID of the object being rated [required]
3574 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3575 * rating => int the submitted rating [required]
3576 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3577 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3578 * @return boolean true if the rating is valid. Will throw rating_exception if not
3580 function forum_rating_validate($params) {
3581 global $DB, $USER;
3583 // Check the component is mod_forum
3584 if ($params['component'] != 'mod_forum') {
3585 throw new rating_exception('invalidcomponent');
3588 // Check the ratingarea is post (the only rating area in forum)
3589 if ($params['ratingarea'] != 'post') {
3590 throw new rating_exception('invalidratingarea');
3593 // Check the rateduserid is not the current user .. you can't rate your own posts
3594 if ($params['rateduserid'] == $USER->id) {
3595 throw new rating_exception('nopermissiontorate');
3598 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
3599 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
3600 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
3601 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
3602 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
3603 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
3604 $context = context_module::instance($cm->id);
3606 // Make sure the context provided is the context of the forum
3607 if ($context->id != $params['context']->id) {
3608 throw new rating_exception('invalidcontext');
3611 if ($forum->scale != $params['scaleid']) {
3612 //the scale being submitted doesnt match the one in the database
3613 throw new rating_exception('invalidscaleid');
3616 // check the item we're rating was created in the assessable time window
3617 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
3618 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
3619 throw new rating_exception('notavailable');
3623 //check that the submitted rating is valid for the scale
3625 // lower limit
3626 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
3627 throw new rating_exception('invalidnum');
3630 // upper limit
3631 if ($forum->scale < 0) {
3632 //its a custom scale
3633 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
3634 if ($scalerecord) {
3635 $scalearray = explode(',', $scalerecord->scale);
3636 if ($params['rating'] > count($scalearray)) {
3637 throw new rating_exception('invalidnum');
3639 } else {
3640 throw new rating_exception('invalidscaleid');
3642 } else if ($params['rating'] > $forum->scale) {
3643 //if its numeric and submitted rating is above maximum
3644 throw new rating_exception('invalidnum');
3647 // Make sure groups allow this user to see the item they're rating
3648 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
3649 if (!groups_group_exists($discussion->groupid)) { // Can't find group
3650 throw new rating_exception('cannotfindgroup');//something is wrong
3653 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
3654 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
3655 throw new rating_exception('notmemberofgroup');
3659 // perform some final capability checks
3660 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3661 throw new rating_exception('nopermissiontorate');
3664 return true;
3668 * Can the current user see ratings for a given itemid?
3670 * @param array $params submitted data
3671 * contextid => int contextid [required]
3672 * component => The component for this module - should always be mod_forum [required]
3673 * ratingarea => object the context in which the rated items exists [required]
3674 * itemid => int the ID of the object being rated [required]
3675 * scaleid => int scale id [optional]
3676 * @return bool
3677 * @throws coding_exception
3678 * @throws rating_exception
3680 function mod_forum_rating_can_see_item_ratings($params) {
3681 global $DB, $USER;
3683 // Check the component is mod_forum.
3684 if (!isset($params['component']) || $params['component'] != 'mod_forum') {
3685 throw new rating_exception('invalidcomponent');
3688 // Check the ratingarea is post (the only rating area in forum).
3689 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
3690 throw new rating_exception('invalidratingarea');
3693 if (!isset($params['itemid'])) {
3694 throw new rating_exception('invaliditemid');
3697 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
3698 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
3699 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
3700 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
3701 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
3703 // Perform some final capability checks.
3704 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3705 return false;
3707 return true;
3711 * This function prints the overview of a discussion in the forum listing.
3712 * It needs some discussion information and some post information, these
3713 * happen to be combined for efficiency in the $post parameter by the function
3714 * that calls this one: forum_print_latest_discussions()
3716 * @global object
3717 * @global object
3718 * @param object $post The post object (passed by reference for speed).
3719 * @param object $forum The forum object.
3720 * @param int $group Current group.
3721 * @param string $datestring Format to use for the dates.
3722 * @param boolean $cantrack Is tracking enabled for this forum.
3723 * @param boolean $forumtracked Is the user tracking this forum.
3724 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
3726 function forum_print_discussion_header(&$post, $forum, $group=-1, $datestring="",
3727 $cantrack=true, $forumtracked=true, $canviewparticipants=true, $modcontext=NULL) {
3729 global $COURSE, $USER, $CFG, $OUTPUT;
3731 static $rowcount;
3732 static $strmarkalldread;
3734 if (empty($modcontext)) {
3735 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
3736 print_error('invalidcoursemodule');
3738 $modcontext = context_module::instance($cm->id);
3741 if (!isset($rowcount)) {
3742 $rowcount = 0;
3743 $strmarkalldread = get_string('markalldread', 'forum');
3744 } else {
3745 $rowcount = ($rowcount + 1) % 2;
3748 $post->subject = format_string($post->subject,true);
3750 echo "\n\n";
3751 echo '<tr class="discussion r'.$rowcount.'">';
3753 // Topic
3754 echo '<td class="topic starter">';
3755 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
3756 echo "</td>\n";
3758 // Picture
3759 $postuser = new stdClass();
3760 $postuserfields = explode(',', user_picture::fields());
3761 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3762 $postuser->id = $post->userid;
3763 echo '<td class="picture">';
3764 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
3765 echo "</td>\n";
3767 // User name
3768 $fullname = fullname($postuser, has_capability('moodle/site:viewfullnames', $modcontext));
3769 echo '<td class="author">';
3770 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
3771 echo "</td>\n";
3773 // Group picture
3774 if ($group !== -1) { // Groups are active - group is a group data object or NULL
3775 echo '<td class="picture group">';
3776 if (!empty($group->picture) and empty($group->hidepicture)) {
3777 if ($canviewparticipants && $COURSE->groupmode) {
3778 $picturelink = true;
3779 } else {
3780 $picturelink = false;
3782 print_group_picture($group, $forum->course, false, false, $picturelink);
3783 } else if (isset($group->id)) {
3784 if ($canviewparticipants && $COURSE->groupmode) {
3785 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
3786 } else {
3787 echo $group->name;
3790 echo "</td>\n";
3793 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
3794 echo '<td class="replies">';
3795 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
3796 echo $post->replies.'</a>';
3797 echo "</td>\n";
3799 if ($cantrack) {
3800 echo '<td class="replies">';
3801 if ($forumtracked) {
3802 if ($post->unread > 0) {
3803 echo '<span class="unread">';
3804 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
3805 echo $post->unread;
3806 echo '</a>';
3807 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
3808 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;returnpage=view.php">' .
3809 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.$strmarkalldread.'" /></a>';
3810 echo '</span>';
3811 } else {
3812 echo '<span class="read">';
3813 echo $post->unread;
3814 echo '</span>';
3816 } else {
3817 echo '<span class="read">';
3818 echo '-';
3819 echo '</span>';
3821 echo "</td>\n";
3825 echo '<td class="lastpost">';
3826 $usedate = (empty($post->timemodified)) ? $post->modified : $post->timemodified; // Just in case
3827 $parenturl = '';
3828 $usermodified = new stdClass();
3829 $usermodified->id = $post->usermodified;
3830 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
3832 // In QA forums we check that the user can view participants.
3833 if ($forum->type !== 'qanda' || $canviewparticipants) {
3834 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
3835 fullname($usermodified).'</a><br />';
3836 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
3839 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
3840 userdate($usedate, $datestring).'</a>';
3841 echo "</td>\n";
3843 // is_guest should be used here as this also checks whether the user is a guest in the current course.
3844 // Guests and visitors cannot subscribe - only enrolled users.
3845 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
3846 // Discussion subscription.
3847 if (\mod_forum\subscriptions::is_subscribable($forum)) {
3848 echo '<td class="discussionsubscription">';
3849 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
3850 echo '</td>';
3854 echo "</tr>\n\n";
3859 * Return the markup for the discussion subscription toggling icon.
3861 * @param stdClass $forum The forum object.
3862 * @param int $discussionid The discussion to create an icon for.
3863 * @return string The generated markup.
3865 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
3866 global $USER, $OUTPUT, $PAGE;
3868 if ($returnurl === null && $PAGE->url) {
3869 $returnurl = $PAGE->url->out();
3872 $o = '';
3873 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
3874 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
3875 'sesskey' => sesskey(),
3876 'id' => $forum->id,
3877 'd' => $discussionid,
3878 'returnurl' => $returnurl,
3881 if ($includetext) {
3882 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
3885 if ($subscriptionstatus) {
3886 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
3887 if ($includetext) {
3888 $output .= get_string('subscribed', 'mod_forum');
3891 return html_writer::link($subscriptionlink, $output, array(
3892 'title' => get_string('clicktounsubscribe', 'forum'),
3893 'class' => 'discussiontoggle iconsmall',
3894 'data-forumid' => $forum->id,
3895 'data-discussionid' => $discussionid,
3896 'data-includetext' => $includetext,
3899 } else {
3900 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
3901 if ($includetext) {
3902 $output .= get_string('notsubscribed', 'mod_forum');
3905 return html_writer::link($subscriptionlink, $output, array(
3906 'title' => get_string('clicktosubscribe', 'forum'),
3907 'class' => 'discussiontoggle iconsmall',
3908 'data-forumid' => $forum->id,
3909 'data-discussionid' => $discussionid,
3910 'data-includetext' => $includetext,
3916 * Return a pair of spans containing classes to allow the subscribe and
3917 * unsubscribe icons to be pre-loaded by a browser.
3919 * @return string The generated markup
3921 function forum_get_discussion_subscription_icon_preloaders() {
3922 $o = '';
3923 $o .= html_writer::span('&nbsp;', 'preload-subscribe');
3924 $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
3925 return $o;
3929 * Print the drop down that allows the user to select how they want to have
3930 * the discussion displayed.
3932 * @param int $id forum id if $forumtype is 'single',
3933 * discussion id for any other forum type
3934 * @param mixed $mode forum layout mode
3935 * @param string $forumtype optional
3937 function forum_print_mode_form($id, $mode, $forumtype='') {
3938 global $OUTPUT;
3939 if ($forumtype == 'single') {
3940 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3941 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3942 $select->class = "forummode";
3943 } else {
3944 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3945 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3947 echo $OUTPUT->render($select);
3951 * @global object
3952 * @param object $course
3953 * @param string $search
3954 * @return string
3956 function forum_search_form($course, $search='') {
3957 global $CFG, $OUTPUT;
3959 $output = '<div class="forumsearch">';
3960 $output .= '<form action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">';
3961 $output .= '<fieldset class="invisiblefieldset">';
3962 $output .= $OUTPUT->help_icon('search');
3963 $output .= '<label class="accesshide" for="search" >'.get_string('search', 'forum').'</label>';
3964 $output .= '<input id="search" name="search" type="text" size="18" value="'.s($search, true).'" />';
3965 $output .= '<label class="accesshide" for="searchforums" >'.get_string('searchforums', 'forum').'</label>';
3966 $output .= '<input id="searchforums" value="'.get_string('searchforums', 'forum').'" type="submit" />';
3967 $output .= '<input name="id" type="hidden" value="'.$course->id.'" />';
3968 $output .= '</fieldset>';
3969 $output .= '</form>';
3970 $output .= '</div>';
3972 return $output;
3977 * @global object
3978 * @global object
3980 function forum_set_return() {
3981 global $CFG, $SESSION;
3983 if (! isset($SESSION->fromdiscussion)) {
3984 $referer = get_local_referer(false);
3985 // If the referer is NOT a login screen then save it.
3986 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
3987 $SESSION->fromdiscussion = $referer;
3994 * @global object
3995 * @param string|\moodle_url $default
3996 * @return string
3998 function forum_go_back_to($default) {
3999 global $SESSION;
4001 if (!empty($SESSION->fromdiscussion)) {
4002 $returnto = $SESSION->fromdiscussion;
4003 unset($SESSION->fromdiscussion);
4004 return $returnto;
4005 } else {
4006 return $default;
4011 * Given a discussion object that is being moved to $forumto,
4012 * this function checks all posts in that discussion
4013 * for attachments, and if any are found, these are
4014 * moved to the new forum directory.
4016 * @global object
4017 * @param object $discussion
4018 * @param int $forumfrom source forum id
4019 * @param int $forumto target forum id
4020 * @return bool success
4022 function forum_move_attachments($discussion, $forumfrom, $forumto) {
4023 global $DB;
4025 $fs = get_file_storage();
4027 $newcm = get_coursemodule_from_instance('forum', $forumto);
4028 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
4030 $newcontext = context_module::instance($newcm->id);
4031 $oldcontext = context_module::instance($oldcm->id);
4033 // loop through all posts, better not use attachment flag ;-)
4034 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
4035 foreach ($posts as $post) {
4036 $fs->move_area_files_to_new_context($oldcontext->id,
4037 $newcontext->id, 'mod_forum', 'post', $post->id);
4038 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
4039 $newcontext->id, 'mod_forum', 'attachment', $post->id);
4040 if ($attachmentsmoved > 0 && $post->attachment != '1') {
4041 // Weird - let's fix it
4042 $post->attachment = '1';
4043 $DB->update_record('forum_posts', $post);
4044 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
4045 // Weird - let's fix it
4046 $post->attachment = '';
4047 $DB->update_record('forum_posts', $post);
4052 return true;
4056 * Returns attachments as formated text/html optionally with separate images
4058 * @global object
4059 * @global object
4060 * @global object
4061 * @param object $post
4062 * @param object $cm
4063 * @param string $type html/text/separateimages
4064 * @return mixed string or array of (html text withouth images and image HTML)
4066 function forum_print_attachments($post, $cm, $type) {
4067 global $CFG, $DB, $USER, $OUTPUT;
4069 if (empty($post->attachment)) {
4070 return $type !== 'separateimages' ? '' : array('', '');
4073 if (!in_array($type, array('separateimages', 'html', 'text'))) {
4074 return $type !== 'separateimages' ? '' : array('', '');
4077 if (!$context = context_module::instance($cm->id)) {
4078 return $type !== 'separateimages' ? '' : array('', '');
4080 $strattachment = get_string('attachment', 'forum');
4082 $fs = get_file_storage();
4084 $imagereturn = '';
4085 $output = '';
4087 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
4089 if ($canexport) {
4090 require_once($CFG->libdir.'/portfoliolib.php');
4093 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
4094 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
4095 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
4096 if ($files) {
4097 if ($canexport) {
4098 $button = new portfolio_add_button();
4100 foreach ($files as $file) {
4101 $filename = $file->get_filename();
4102 $mimetype = $file->get_mimetype();
4103 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
4104 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
4106 if ($type == 'html') {
4107 $output .= "<a href=\"$path\">$iconimage</a> ";
4108 $output .= "<a href=\"$path\">".s($filename)."</a>";
4109 if ($canexport) {
4110 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4111 $button->set_format_by_file($file);
4112 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4114 $output .= "<br />";
4116 } else if ($type == 'text') {
4117 $output .= "$strattachment ".s($filename).":\n$path\n";
4119 } else { //'returnimages'
4120 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
4121 // Image attachments don't get printed as links
4122 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
4123 if ($canexport) {
4124 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4125 $button->set_format_by_file($file);
4126 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4128 } else {
4129 $output .= "<a href=\"$path\">$iconimage</a> ";
4130 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
4131 if ($canexport) {
4132 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
4133 $button->set_format_by_file($file);
4134 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
4136 $output .= '<br />';
4140 if (!empty($CFG->enableplagiarism)) {
4141 require_once($CFG->libdir.'/plagiarismlib.php');
4142 $output .= plagiarism_get_links(array('userid' => $post->userid,
4143 'file' => $file,
4144 'cmid' => $cm->id,
4145 'course' => $cm->course,
4146 'forum' => $cm->instance));
4147 $output .= '<br />';
4152 if ($type !== 'separateimages') {
4153 return $output;
4155 } else {
4156 return array($output, $imagereturn);
4160 ////////////////////////////////////////////////////////////////////////////////
4161 // File API //
4162 ////////////////////////////////////////////////////////////////////////////////
4165 * Lists all browsable file areas
4167 * @package mod_forum
4168 * @category files
4169 * @param stdClass $course course object
4170 * @param stdClass $cm course module object
4171 * @param stdClass $context context object
4172 * @return array
4174 function forum_get_file_areas($course, $cm, $context) {
4175 return array(
4176 'attachment' => get_string('areaattachment', 'mod_forum'),
4177 'post' => get_string('areapost', 'mod_forum'),
4182 * File browsing support for forum module.
4184 * @package mod_forum
4185 * @category files
4186 * @param stdClass $browser file browser object
4187 * @param stdClass $areas file areas
4188 * @param stdClass $course course object
4189 * @param stdClass $cm course module
4190 * @param stdClass $context context module
4191 * @param string $filearea file area
4192 * @param int $itemid item ID
4193 * @param string $filepath file path
4194 * @param string $filename file name
4195 * @return file_info instance or null if not found
4197 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4198 global $CFG, $DB, $USER;
4200 if ($context->contextlevel != CONTEXT_MODULE) {
4201 return null;
4204 // filearea must contain a real area
4205 if (!isset($areas[$filearea])) {
4206 return null;
4209 // Note that forum_user_can_see_post() additionally allows access for parent roles
4210 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
4211 // course:managefiles, we will need to extend this.
4212 if (!has_capability('mod/forum:viewdiscussion', $context)) {
4213 return null;
4216 if (is_null($itemid)) {
4217 require_once($CFG->dirroot.'/mod/forum/locallib.php');
4218 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
4221 static $cached = array();
4222 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
4223 // is cleared between unit tests we check if this is the same session
4224 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
4225 $cached = array('sesskey' => sesskey());
4228 if (isset($cached['post']) && $cached['post']->id == $itemid) {
4229 $post = $cached['post'];
4230 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
4231 $cached['post'] = $post;
4232 } else {
4233 return null;
4236 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
4237 $discussion = $cached['discussion'];
4238 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
4239 $cached['discussion'] = $discussion;
4240 } else {
4241 return null;
4244 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
4245 $forum = $cached['forum'];
4246 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
4247 $cached['forum'] = $forum;
4248 } else {
4249 return null;
4252 $fs = get_file_storage();
4253 $filepath = is_null($filepath) ? '/' : $filepath;
4254 $filename = is_null($filename) ? '.' : $filename;
4255 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
4256 return null;
4259 // Checks to see if the user can manage files or is the owner.
4260 // TODO MDL-33805 - Do not use userid here and move the capability check above.
4261 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
4262 return null;
4264 // Make sure groups allow this user to see this file
4265 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
4266 $groupmode = groups_get_activity_groupmode($cm, $course);
4267 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
4268 return null;
4272 // Make sure we're allowed to see it...
4273 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4274 return null;
4277 $urlbase = $CFG->wwwroot.'/pluginfile.php';
4278 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
4282 * Serves the forum attachments. Implements needed access control ;-)
4284 * @package mod_forum
4285 * @category files
4286 * @param stdClass $course course object
4287 * @param stdClass $cm course module object
4288 * @param stdClass $context context object
4289 * @param string $filearea file area
4290 * @param array $args extra arguments
4291 * @param bool $forcedownload whether or not force download
4292 * @param array $options additional options affecting the file serving
4293 * @return bool false if file not found, does not return if found - justsend the file
4295 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
4296 global $CFG, $DB;
4298 if ($context->contextlevel != CONTEXT_MODULE) {
4299 return false;
4302 require_course_login($course, true, $cm);
4304 $areas = forum_get_file_areas($course, $cm, $context);
4306 // filearea must contain a real area
4307 if (!isset($areas[$filearea])) {
4308 return false;
4311 $postid = (int)array_shift($args);
4313 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
4314 return false;
4317 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
4318 return false;
4321 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
4322 return false;
4325 $fs = get_file_storage();
4326 $relativepath = implode('/', $args);
4327 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
4328 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4329 return false;
4332 // Make sure groups allow this user to see this file
4333 if ($discussion->groupid > 0) {
4334 $groupmode = groups_get_activity_groupmode($cm, $course);
4335 if ($groupmode == SEPARATEGROUPS) {
4336 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
4337 return false;
4342 // Make sure we're allowed to see it...
4343 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4344 return false;
4347 // finally send the file
4348 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
4352 * If successful, this function returns the name of the file
4354 * @global object
4355 * @param object $post is a full post record, including course and forum
4356 * @param object $forum
4357 * @param object $cm
4358 * @param mixed $mform
4359 * @param string $unused
4360 * @return bool
4362 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
4363 global $DB;
4365 if (empty($mform)) {
4366 return false;
4369 if (empty($post->attachments)) {
4370 return true; // Nothing to do
4373 $context = context_module::instance($cm->id);
4375 $info = file_get_draft_area_info($post->attachments);
4376 $present = ($info['filecount']>0) ? '1' : '';
4377 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
4378 mod_forum_post_form::attachment_options($forum));
4380 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
4382 return true;
4386 * Add a new post in an existing discussion.
4388 * @global object
4389 * @global object
4390 * @global object
4391 * @param object $post
4392 * @param mixed $mform
4393 * @param string $unused formerly $message, renamed in 2.8 as it was unused.
4394 * @return int
4396 function forum_add_new_post($post, $mform, $unused = null) {
4397 global $USER, $CFG, $DB;
4399 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4400 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4401 $cm = get_coursemodule_from_instance('forum', $forum->id);
4402 $context = context_module::instance($cm->id);
4404 $post->created = $post->modified = time();
4405 $post->mailed = FORUM_MAILED_PENDING;
4406 $post->userid = $USER->id;
4407 $post->attachment = "";
4408 if (!isset($post->totalscore)) {
4409 $post->totalscore = 0;
4411 if (!isset($post->mailnow)) {
4412 $post->mailnow = 0;
4415 $post->id = $DB->insert_record("forum_posts", $post);
4416 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
4417 mod_forum_post_form::editor_options($context, null), $post->message);
4418 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
4419 forum_add_attachment($post, $forum, $cm, $mform);
4421 // Update discussion modified date
4422 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
4423 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
4425 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4426 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4429 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4430 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
4432 return $post->id;
4436 * Update a post
4438 * @global object
4439 * @global object
4440 * @global object
4441 * @param object $post
4442 * @param mixed $mform
4443 * @param string $message
4444 * @return bool
4446 function forum_update_post($post, $mform, &$message) {
4447 global $USER, $CFG, $DB;
4449 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
4450 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
4451 $cm = get_coursemodule_from_instance('forum', $forum->id);
4452 $context = context_module::instance($cm->id);
4454 $post->modified = time();
4456 $DB->update_record('forum_posts', $post);
4458 $discussion->timemodified = $post->modified; // last modified tracking
4459 $discussion->usermodified = $post->userid; // last modified tracking
4461 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
4462 $discussion->name = $post->subject;
4463 $discussion->timestart = $post->timestart;
4464 $discussion->timeend = $post->timeend;
4466 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
4467 mod_forum_post_form::editor_options($context, $post->id), $post->message);
4468 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
4470 $DB->update_record('forum_discussions', $discussion);
4472 forum_add_attachment($post, $forum, $cm, $mform, $message);
4474 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4475 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4478 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4479 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
4481 return true;
4485 * Given an object containing all the necessary data,
4486 * create a new discussion and return the id
4488 * @param object $post
4489 * @param mixed $mform
4490 * @param string $unused
4491 * @param int $userid
4492 * @return object
4494 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
4495 global $USER, $CFG, $DB;
4497 $timenow = time();
4499 if (is_null($userid)) {
4500 $userid = $USER->id;
4503 // The first post is stored as a real post, and linked
4504 // to from the discuss entry.
4506 $forum = $DB->get_record('forum', array('id'=>$discussion->forum));
4507 $cm = get_coursemodule_from_instance('forum', $forum->id);
4509 $post = new stdClass();
4510 $post->discussion = 0;
4511 $post->parent = 0;
4512 $post->userid = $userid;
4513 $post->created = $timenow;
4514 $post->modified = $timenow;
4515 $post->mailed = FORUM_MAILED_PENDING;
4516 $post->subject = $discussion->name;
4517 $post->message = $discussion->message;
4518 $post->messageformat = $discussion->messageformat;
4519 $post->messagetrust = $discussion->messagetrust;
4520 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null;
4521 $post->forum = $forum->id; // speedup
4522 $post->course = $forum->course; // speedup
4523 $post->mailnow = $discussion->mailnow;
4525 $post->id = $DB->insert_record("forum_posts", $post);
4527 // TODO: Fix the calling code so that there always is a $cm when this function is called
4528 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet
4529 $context = context_module::instance($cm->id);
4530 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id,
4531 mod_forum_post_form::editor_options($context, null), $post->message);
4532 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id));
4535 // Now do the main entry for the discussion, linking to this first post
4537 $discussion->firstpost = $post->id;
4538 $discussion->timemodified = $timenow;
4539 $discussion->usermodified = $post->userid;
4540 $discussion->userid = $userid;
4541 $discussion->assessed = 0;
4543 $post->discussion = $DB->insert_record("forum_discussions", $discussion);
4545 // Finally, set the pointer on the post.
4546 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id));
4548 if (!empty($cm->id)) {
4549 forum_add_attachment($post, $forum, $cm, $mform, $unused);
4552 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4553 forum_tp_mark_post_read($post->userid, $post, $post->forum);
4556 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4557 if (!empty($cm->id)) {
4558 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
4561 return $post->discussion;
4566 * Deletes a discussion and handles all associated cleanup.
4568 * @global object
4569 * @param object $discussion Discussion to delete
4570 * @param bool $fulldelete True when deleting entire forum
4571 * @param object $course Course
4572 * @param object $cm Course-module
4573 * @param object $forum Forum
4574 * @return bool
4576 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
4577 global $DB, $CFG;
4578 require_once($CFG->libdir.'/completionlib.php');
4580 $result = true;
4582 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) {
4583 foreach ($posts as $post) {
4584 $post->course = $discussion->course;
4585 $post->forum = $discussion->forum;
4586 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
4587 $result = false;
4592 forum_tp_delete_read_records(-1, -1, $discussion->id);
4594 // Discussion subscriptions must be removed before discussions because of key constraints.
4595 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id));
4596 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) {
4597 $result = false;
4600 // Update completion state if we are tracking completion based on number of posts
4601 // But don't bother when deleting whole thing
4602 if (!$fulldelete) {
4603 $completion = new completion_info($course);
4604 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4605 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4606 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid);
4610 return $result;
4615 * Deletes a single forum post.
4617 * @global object
4618 * @param object $post Forum post object
4619 * @param mixed $children Whether to delete children. If false, returns false
4620 * if there are any children (without deleting the post). If true,
4621 * recursively deletes all children. If set to special value 'ignore', deletes
4622 * post regardless of children (this is for use only when deleting all posts
4623 * in a disussion).
4624 * @param object $course Course
4625 * @param object $cm Course-module
4626 * @param object $forum Forum
4627 * @param bool $skipcompletion True to skip updating completion state if it
4628 * would otherwise be updated, i.e. when deleting entire forum anyway.
4629 * @return bool
4631 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
4632 global $DB, $CFG;
4633 require_once($CFG->libdir.'/completionlib.php');
4635 $context = context_module::instance($cm->id);
4637 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) {
4638 if ($children) {
4639 foreach ($childposts as $childpost) {
4640 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
4642 } else {
4643 return false;
4647 // Delete ratings.
4648 require_once($CFG->dirroot.'/rating/lib.php');
4649 $delopt = new stdClass;
4650 $delopt->contextid = $context->id;
4651 $delopt->component = 'mod_forum';
4652 $delopt->ratingarea = 'post';
4653 $delopt->itemid = $post->id;
4654 $rm = new rating_manager();
4655 $rm->delete_ratings($delopt);
4657 // Delete attachments.
4658 $fs = get_file_storage();
4659 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id);
4660 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id);
4662 // Delete cached RSS feeds.
4663 if (!empty($CFG->enablerssfeeds)) {
4664 require_once($CFG->dirroot.'/mod/forum/rsslib.php');
4665 forum_rss_delete_file($forum);
4668 if ($DB->delete_records("forum_posts", array("id" => $post->id))) {
4670 forum_tp_delete_read_records(-1, $post->id);
4672 // Just in case we are deleting the last post
4673 forum_discussion_update_last_post($post->discussion);
4675 // Update completion state if we are tracking completion based on number of posts
4676 // But don't bother when deleting whole thing
4678 if (!$skipcompletion) {
4679 $completion = new completion_info($course);
4680 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC &&
4681 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) {
4682 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid);
4686 return true;
4688 return false;
4692 * Sends post content to plagiarism plugin
4693 * @param object $post Forum post object
4694 * @param object $cm Course-module
4695 * @param string $name
4696 * @return bool
4698 function forum_trigger_content_uploaded_event($post, $cm, $name) {
4699 $context = context_module::instance($cm->id);
4700 $fs = get_file_storage();
4701 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false);
4702 $params = array(
4703 'context' => $context,
4704 'objectid' => $post->id,
4705 'other' => array(
4706 'content' => $post->message,
4707 'pathnamehashes' => array_keys($files),
4708 'discussionid' => $post->discussion,
4709 'triggeredfrom' => $name,
4712 $event = \mod_forum\event\assessable_uploaded::create($params);
4713 $event->trigger();
4714 return true;
4718 * @global object
4719 * @param object $post
4720 * @param bool $children
4721 * @return int
4723 function forum_count_replies($post, $children=true) {
4724 global $DB;
4725 $count = 0;
4727 if ($children) {
4728 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id))) {
4729 foreach ($childposts as $childpost) {
4730 $count ++; // For this child
4731 $count += forum_count_replies($childpost, true);
4734 } else {
4735 $count += $DB->count_records('forum_posts', array('parent' => $post->id));
4738 return $count;
4742 * Given a new post, subscribes or unsubscribes as appropriate.
4743 * Returns some text which describes what happened.
4745 * @param object $fromform The submitted form
4746 * @param stdClass $forum The forum record
4747 * @param stdClass $discussion The forum discussion record
4748 * @return string
4750 function forum_post_subscription($fromform, $forum, $discussion) {
4751 global $USER;
4753 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4754 return "";
4755 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) {
4756 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4757 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) {
4758 // This user should not be subscribed to the forum.
4759 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum);
4761 return "";
4764 $info = new stdClass();
4765 $info->name = fullname($USER);
4766 $info->discussion = format_string($discussion->name);
4767 $info->forum = format_string($forum->name);
4769 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) {
4770 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) {
4771 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
4773 } else {
4774 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) {
4775 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
4779 return '';
4783 * Generate and return the subscribe or unsubscribe link for a forum.
4785 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
4786 * @param object $context the context object for this forum.
4787 * @param array $messages text used for the link in its various states
4788 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
4789 * Any strings not passed in are taken from the $defaultmessages array
4790 * at the top of the function.
4791 * @param bool $cantaccessagroup
4792 * @param bool $fakelink
4793 * @param bool $backtoindex
4794 * @param array $subscribed_forums
4795 * @return string
4797 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $fakelink=true, $backtoindex=false, $subscribed_forums=null) {
4798 global $CFG, $USER, $PAGE, $OUTPUT;
4799 $defaultmessages = array(
4800 'subscribed' => get_string('unsubscribe', 'forum'),
4801 'unsubscribed' => get_string('subscribe', 'forum'),
4802 'cantaccessgroup' => get_string('no'),
4803 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
4804 'cantsubscribe' => get_string('disallowsubscribe','forum')
4806 $messages = $messages + $defaultmessages;
4808 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
4809 return $messages['forcesubscribed'];
4810 } else if (\mod_forum\subscriptions::subscription_disabled($forum) &&
4811 !has_capability('mod/forum:managesubscriptions', $context)) {
4812 return $messages['cantsubscribe'];
4813 } else if ($cantaccessagroup) {
4814 return $messages['cantaccessgroup'];
4815 } else {
4816 if (!is_enrolled($context, $USER, '', true)) {
4817 return '';
4820 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum);
4821 if ($subscribed) {
4822 $linktext = $messages['subscribed'];
4823 $linktitle = get_string('subscribestop', 'forum');
4824 } else {
4825 $linktext = $messages['unsubscribed'];
4826 $linktitle = get_string('subscribestart', 'forum');
4829 $options = array();
4830 if ($backtoindex) {
4831 $backtoindexlink = '&amp;backtoindex=1';
4832 $options['backtoindex'] = 1;
4833 } else {
4834 $backtoindexlink = '';
4836 $link = '';
4838 if ($fakelink) {
4839 $PAGE->requires->js('/mod/forum/forum.js');
4840 $PAGE->requires->js_function_call('forum_produce_subscribe_link', array($forum->id, $backtoindexlink, $linktext, $linktitle));
4841 $link = "<noscript>";
4843 $options['id'] = $forum->id;
4844 $options['sesskey'] = sesskey();
4845 $url = new moodle_url('/mod/forum/subscribe.php', $options);
4846 $link .= $OUTPUT->single_button($url, $linktext, 'get', array('title'=>$linktitle));
4847 if ($fakelink) {
4848 $link .= '</noscript>';
4851 return $link;
4856 * Returns true if user created new discussion already
4858 * @global object
4859 * @global object
4860 * @param int $forumid
4861 * @param int $userid
4862 * @return bool
4864 function forum_user_has_posted_discussion($forumid, $userid) {
4865 global $CFG, $DB;
4867 $sql = "SELECT 'x'
4868 FROM {forum_discussions} d, {forum_posts} p
4869 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 and p.userid = ?";
4871 return $DB->record_exists_sql($sql, array($forumid, $userid));
4875 * @global object
4876 * @global object
4877 * @param int $forumid
4878 * @param int $userid
4879 * @return array
4881 function forum_discussions_user_has_posted_in($forumid, $userid) {
4882 global $CFG, $DB;
4884 $haspostedsql = "SELECT d.id AS id,
4886 FROM {forum_posts} p,
4887 {forum_discussions} d
4888 WHERE p.discussion = d.id
4889 AND d.forum = ?
4890 AND p.userid = ?";
4892 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
4896 * @global object
4897 * @global object
4898 * @param int $forumid
4899 * @param int $did
4900 * @param int $userid
4901 * @return bool
4903 function forum_user_has_posted($forumid, $did, $userid) {
4904 global $DB;
4906 if (empty($did)) {
4907 // posted in any forum discussion?
4908 $sql = "SELECT 'x'
4909 FROM {forum_posts} p
4910 JOIN {forum_discussions} d ON d.id = p.discussion
4911 WHERE p.userid = :userid AND d.forum = :forumid";
4912 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
4913 } else {
4914 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
4919 * Returns creation time of the first user's post in given discussion
4920 * @global object $DB
4921 * @param int $did Discussion id
4922 * @param int $userid User id
4923 * @return int|bool post creation time stamp or return false
4925 function forum_get_user_posted_time($did, $userid) {
4926 global $DB;
4928 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
4929 if (empty($posttime)) {
4930 return false;
4932 return $posttime;
4936 * @global object
4937 * @param object $forum
4938 * @param object $currentgroup
4939 * @param int $unused
4940 * @param object $cm
4941 * @param object $context
4942 * @return bool
4944 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
4945 // $forum is an object
4946 global $USER;
4948 // shortcut - guest and not-logged-in users can not post
4949 if (isguestuser() or !isloggedin()) {
4950 return false;
4953 if (!$cm) {
4954 debugging('missing cm', DEBUG_DEVELOPER);
4955 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
4956 print_error('invalidcoursemodule');
4960 if (!$context) {
4961 $context = context_module::instance($cm->id);
4964 if ($currentgroup === null) {
4965 $currentgroup = groups_get_activity_group($cm);
4968 $groupmode = groups_get_activity_groupmode($cm);
4970 if ($forum->type == 'news') {
4971 $capname = 'mod/forum:addnews';
4972 } else if ($forum->type == 'qanda') {
4973 $capname = 'mod/forum:addquestion';
4974 } else {
4975 $capname = 'mod/forum:startdiscussion';
4978 if (!has_capability($capname, $context)) {
4979 return false;
4982 if ($forum->type == 'single') {
4983 return false;
4986 if ($forum->type == 'eachuser') {
4987 if (forum_user_has_posted_discussion($forum->id, $USER->id)) {
4988 return false;
4992 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
4993 return true;
4996 if ($currentgroup) {
4997 return groups_is_member($currentgroup);
4998 } else {
4999 // no group membership and no accessallgroups means no new discussions
5000 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
5001 return false;
5006 * This function checks whether the user can reply to posts in a forum
5007 * discussion. Use forum_user_can_post_discussion() to check whether the user
5008 * can start discussions.
5010 * @global object
5011 * @global object
5012 * @uses DEBUG_DEVELOPER
5013 * @uses CONTEXT_MODULE
5014 * @uses VISIBLEGROUPS
5015 * @param object $forum forum object
5016 * @param object $discussion
5017 * @param object $user
5018 * @param object $cm
5019 * @param object $course
5020 * @param object $context
5021 * @return bool
5023 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
5024 global $USER, $DB;
5025 if (empty($user)) {
5026 $user = $USER;
5029 // shortcut - guest and not-logged-in users can not post
5030 if (isguestuser($user) or empty($user->id)) {
5031 return false;
5034 if (!isset($discussion->groupid)) {
5035 debugging('incorrect discussion parameter', DEBUG_DEVELOPER);
5036 return false;
5039 if (!$cm) {
5040 debugging('missing cm', DEBUG_DEVELOPER);
5041 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5042 print_error('invalidcoursemodule');
5046 if (!$course) {
5047 debugging('missing course', DEBUG_DEVELOPER);
5048 if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
5049 print_error('invalidcourseid');
5053 if (!$context) {
5054 $context = context_module::instance($cm->id);
5057 // normal users with temporary guest access can not post, suspended users can not post either
5058 if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) {
5059 return false;
5062 if ($forum->type == 'news') {
5063 $capname = 'mod/forum:replynews';
5064 } else {
5065 $capname = 'mod/forum:replypost';
5068 if (!has_capability($capname, $context, $user->id)) {
5069 return false;
5072 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
5073 return true;
5076 if (has_capability('moodle/site:accessallgroups', $context)) {
5077 return true;
5080 if ($groupmode == VISIBLEGROUPS) {
5081 if ($discussion->groupid == -1) {
5082 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
5083 return true;
5085 return groups_is_member($discussion->groupid);
5087 } else {
5088 //separate groups
5089 if ($discussion->groupid == -1) {
5090 return false;
5092 return groups_is_member($discussion->groupid);
5097 * Check to ensure a user can view a timed discussion.
5099 * @param object $discussion
5100 * @param object $user
5101 * @param object $context
5102 * @return boolean returns true if they can view post, false otherwise
5104 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
5105 global $CFG;
5107 // Check that the user can view a discussion that is normally hidden due to access times.
5108 if (!empty($CFG->forum_enabletimedposts)) {
5109 $time = time();
5110 if (($discussion->timestart != 0 && $discussion->timestart > $time)
5111 || ($discussion->timeend != 0 && $discussion->timeend < $time)) {
5112 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) {
5113 return false;
5118 return true;
5122 * Check to ensure a user can view a group discussion.
5124 * @param object $discussion
5125 * @param object $cm
5126 * @param object $context
5127 * @return boolean returns true if they can view post, false otherwise
5129 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
5131 // If it's a grouped discussion, make sure the user is a member.
5132 if ($discussion->groupid > 0) {
5133 $groupmode = groups_get_activity_groupmode($cm);
5134 if ($groupmode == SEPARATEGROUPS) {
5135 return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context);
5139 return true;
5143 * @global object
5144 * @global object
5145 * @uses DEBUG_DEVELOPER
5146 * @param object $forum
5147 * @param object $discussion
5148 * @param object $context
5149 * @param object $user
5150 * @return bool
5152 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
5153 global $USER, $DB;
5155 if (empty($user) || empty($user->id)) {
5156 $user = $USER;
5159 // retrieve objects (yuk)
5160 if (is_numeric($forum)) {
5161 debugging('missing full forum', DEBUG_DEVELOPER);
5162 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5163 return false;
5166 if (is_numeric($discussion)) {
5167 debugging('missing full discussion', DEBUG_DEVELOPER);
5168 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5169 return false;
5172 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5173 print_error('invalidcoursemodule');
5176 if (!has_capability('mod/forum:viewdiscussion', $context)) {
5177 return false;
5180 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
5181 return false;
5184 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
5185 return false;
5188 return true;
5192 * @global object
5193 * @global object
5194 * @param object $forum
5195 * @param object $discussion
5196 * @param object $post
5197 * @param object $user
5198 * @param object $cm
5199 * @return bool
5201 function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NULL) {
5202 global $CFG, $USER, $DB;
5204 // Context used throughout function.
5205 $modcontext = context_module::instance($cm->id);
5207 // retrieve objects (yuk)
5208 if (is_numeric($forum)) {
5209 debugging('missing full forum', DEBUG_DEVELOPER);
5210 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5211 return false;
5215 if (is_numeric($discussion)) {
5216 debugging('missing full discussion', DEBUG_DEVELOPER);
5217 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5218 return false;
5221 if (is_numeric($post)) {
5222 debugging('missing full post', DEBUG_DEVELOPER);
5223 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
5224 return false;
5228 if (!isset($post->id) && isset($post->parent)) {
5229 $post->id = $post->parent;
5232 if (!$cm) {
5233 debugging('missing cm', DEBUG_DEVELOPER);
5234 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5235 print_error('invalidcoursemodule');
5239 if (empty($user) || empty($user->id)) {
5240 $user = $USER;
5243 $canviewdiscussion = !empty($cm->cache->caps['mod/forum:viewdiscussion']) || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id);
5244 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) {
5245 return false;
5248 if (isset($cm->uservisible)) {
5249 if (!$cm->uservisible) {
5250 return false;
5252 } else {
5253 if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) {
5254 return false;
5258 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
5259 return false;
5262 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
5263 return false;
5266 if ($forum->type == 'qanda') {
5267 $firstpost = forum_get_firstpost_from_discussion($discussion->id);
5268 $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id);
5270 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime)) ||
5271 $firstpost->id == $post->id || $post->userid == $user->id || $firstpost->userid == $user->id ||
5272 has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id));
5274 return true;
5279 * Prints the discussion view screen for a forum.
5281 * @global object
5282 * @global object
5283 * @param object $course The current course object.
5284 * @param object $forum Forum to be printed.
5285 * @param int $maxdiscussions .
5286 * @param string $displayformat The display format to use (optional).
5287 * @param string $sort Sort arguments for database query (optional).
5288 * @param int $groupmode Group mode of the forum (optional).
5289 * @param void $unused (originally current group)
5290 * @param int $page Page mode, page to display (optional).
5291 * @param int $perpage The maximum number of discussions per page(optional)
5292 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
5295 function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '',
5296 $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null) {
5297 global $CFG, $USER, $OUTPUT;
5299 if (!$cm) {
5300 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
5301 print_error('invalidcoursemodule');
5304 $context = context_module::instance($cm->id);
5306 if (empty($sort)) {
5307 $sort = "d.timemodified DESC";
5310 $olddiscussionlink = false;
5312 // Sort out some defaults
5313 if ($perpage <= 0) {
5314 $perpage = 0;
5315 $page = -1;
5318 if ($maxdiscussions == 0) {
5319 // all discussions - backwards compatibility
5320 $page = -1;
5321 $perpage = 0;
5322 if ($displayformat == 'plain') {
5323 $displayformat = 'header'; // Abbreviate display by default
5326 } else if ($maxdiscussions > 0) {
5327 $page = -1;
5328 $perpage = $maxdiscussions;
5331 $fullpost = false;
5332 if ($displayformat == 'plain') {
5333 $fullpost = true;
5337 // Decide if current user is allowed to see ALL the current discussions or not
5339 // First check the group stuff
5340 if ($currentgroup == -1 or $groupmode == -1) {
5341 $groupmode = groups_get_activity_groupmode($cm, $course);
5342 $currentgroup = groups_get_activity_group($cm);
5345 $groups = array(); //cache
5347 // If the user can post discussions, then this is a good place to put the
5348 // button for it. We do not show the button if we are showing site news
5349 // and the current user is a guest.
5351 $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
5352 if (!$canstart and $forum->type !== 'news') {
5353 if (isguestuser() or !isloggedin()) {
5354 $canstart = true;
5356 if (!is_enrolled($context) and !is_viewing($context)) {
5357 // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
5358 // normal users with temporary guest access see this button too, they are asked to enrol instead
5359 // do not show the button to users with suspended enrolments here
5360 $canstart = enrol_selfenrol_available($course->id);
5364 if ($canstart) {
5365 echo '<div class="singlebutton forumaddnew">';
5366 echo "<form id=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
5367 echo '<div>';
5368 echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
5369 switch ($forum->type) {
5370 case 'news':
5371 case 'blog':
5372 $buttonadd = get_string('addanewtopic', 'forum');
5373 break;
5374 case 'qanda':
5375 $buttonadd = get_string('addanewquestion', 'forum');
5376 break;
5377 default:
5378 $buttonadd = get_string('addanewdiscussion', 'forum');
5379 break;
5381 echo '<input type="submit" value="'.$buttonadd.'" />';
5382 echo '</div>';
5383 echo '</form>';
5384 echo "</div>\n";
5386 } else if (isguestuser() or !isloggedin() or $forum->type == 'news' or
5387 $forum->type == 'qanda' and !has_capability('mod/forum:addquestion', $context) or
5388 $forum->type != 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
5389 // no button and no info
5391 } else if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
5392 // inform users why they can not post new discussion
5393 if (!$currentgroup) {
5394 echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
5395 } else if (!groups_is_member($currentgroup)) {
5396 echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
5400 // Get all the recent discussions we're allowed to see
5402 $getuserlastmodified = ($displayformat == 'header');
5404 if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
5405 echo '<div class="forumnodiscuss">';
5406 if ($forum->type == 'news') {
5407 echo '('.get_string('nonews', 'forum').')';
5408 } else if ($forum->type == 'qanda') {
5409 echo '('.get_string('noquestions','forum').')';
5410 } else {
5411 echo '('.get_string('nodiscussions', 'forum').')';
5413 echo "</div>\n";
5414 return;
5417 // If we want paging
5418 if ($page != -1) {
5419 ///Get the number of discussions found
5420 $numdiscussions = forum_get_discussions_count($cm);
5422 ///Show the paging bar
5423 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5424 if ($numdiscussions > 1000) {
5425 // saves some memory on sites with very large forums
5426 $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
5427 } else {
5428 $replies = forum_count_discussion_replies($forum->id);
5431 } else {
5432 $replies = forum_count_discussion_replies($forum->id);
5434 if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
5435 $olddiscussionlink = true;
5439 $canviewparticipants = has_capability('moodle/course:viewparticipants',$context);
5441 $strdatestring = get_string('strftimerecentfull');
5443 // Check if the forum is tracked.
5444 if ($cantrack = forum_tp_can_track_forums($forum)) {
5445 $forumtracked = forum_tp_is_tracked($forum);
5446 } else {
5447 $forumtracked = false;
5450 if ($forumtracked) {
5451 $unreads = forum_get_discussions_unread($cm);
5452 } else {
5453 $unreads = array();
5456 if ($displayformat == 'header') {
5457 echo '<table cellspacing="0" class="forumheaderlist">';
5458 echo '<thead>';
5459 echo '<tr>';
5460 echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
5461 echo '<th class="header author" colspan="2" scope="col">'.get_string('startedby', 'forum').'</th>';
5462 if ($groupmode > 0) {
5463 echo '<th class="header group" scope="col">'.get_string('group').'</th>';
5465 if (has_capability('mod/forum:viewdiscussion', $context)) {
5466 echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
5467 // If the forum can be tracked, display the unread column.
5468 if ($cantrack) {
5469 echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
5470 if ($forumtracked) {
5471 echo '<a title="'.get_string('markallread', 'forum').
5472 '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
5473 $forum->id.'&amp;mark=read&amp;returnpage=view.php">'.
5474 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.get_string('markallread', 'forum').'" /></a>';
5476 echo '</th>';
5479 echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
5480 if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $context)) {
5481 if (\mod_forum\subscriptions::is_subscribable($forum)) {
5482 echo '<th class="header discussionsubscription" scope="col">';
5483 echo forum_get_discussion_subscription_icon_preloaders();
5484 echo '</th>';
5487 echo '</tr>';
5488 echo '</thead>';
5489 echo '<tbody>';
5492 foreach ($discussions as $discussion) {
5493 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) &&
5494 !forum_user_has_posted($forum->id, $discussion->discussion, $USER->id)) {
5495 $canviewparticipants = false;
5498 if (!empty($replies[$discussion->discussion])) {
5499 $discussion->replies = $replies[$discussion->discussion]->replies;
5500 $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
5501 } else {
5502 $discussion->replies = 0;
5505 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
5506 // All posts are read in this case.
5507 if (!$forumtracked) {
5508 $discussion->unread = '-';
5509 } else if (empty($USER)) {
5510 $discussion->unread = 0;
5511 } else {
5512 if (empty($unreads[$discussion->discussion])) {
5513 $discussion->unread = 0;
5514 } else {
5515 $discussion->unread = $unreads[$discussion->discussion];
5519 if (isloggedin()) {
5520 $ownpost = ($discussion->userid == $USER->id);
5521 } else {
5522 $ownpost=false;
5524 // Use discussion name instead of subject of first post
5525 $discussion->subject = $discussion->name;
5527 switch ($displayformat) {
5528 case 'header':
5529 if ($groupmode > 0) {
5530 if (isset($groups[$discussion->groupid])) {
5531 $group = $groups[$discussion->groupid];
5532 } else {
5533 $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
5535 } else {
5536 $group = -1;
5538 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
5539 $canviewparticipants, $context);
5540 break;
5541 default:
5542 $link = false;
5544 if ($discussion->replies) {
5545 $link = true;
5546 } else {
5547 $modcontext = context_module::instance($cm->id);
5548 $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
5551 $discussion->forum = $forum->id;
5553 forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
5554 '', null, true, $forumtracked);
5555 break;
5559 if ($displayformat == "header") {
5560 echo '</tbody>';
5561 echo '</table>';
5564 if ($olddiscussionlink) {
5565 if ($forum->type == 'news') {
5566 $strolder = get_string('oldertopics', 'forum');
5567 } else {
5568 $strolder = get_string('olderdiscussions', 'forum');
5570 echo '<div class="forumolddiscuss">';
5571 echo '<a href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'&amp;showall=1">';
5572 echo $strolder.'</a> ...</div>';
5575 if ($page != -1) { ///Show the paging bar
5576 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5582 * Prints a forum discussion
5584 * @uses CONTEXT_MODULE
5585 * @uses FORUM_MODE_FLATNEWEST
5586 * @uses FORUM_MODE_FLATOLDEST
5587 * @uses FORUM_MODE_THREADED
5588 * @uses FORUM_MODE_NESTED
5589 * @param stdClass $course
5590 * @param stdClass $cm
5591 * @param stdClass $forum
5592 * @param stdClass $discussion
5593 * @param stdClass $post
5594 * @param int $mode
5595 * @param mixed $canreply
5596 * @param bool $canrate
5598 function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
5599 global $USER, $CFG;
5601 require_once($CFG->dirroot.'/rating/lib.php');
5603 $ownpost = (isloggedin() && $USER->id == $post->userid);
5605 $modcontext = context_module::instance($cm->id);
5606 if ($canreply === NULL) {
5607 $reply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
5608 } else {
5609 $reply = $canreply;
5612 // $cm holds general cache for forum functions
5613 $cm->cache = new stdClass;
5614 $cm->cache->groups = groups_get_all_groups($course->id, 0, $cm->groupingid);
5615 $cm->cache->usersgroups = array();
5617 $posters = array();
5619 // preload all posts - TODO: improve...
5620 if ($mode == FORUM_MODE_FLATNEWEST) {
5621 $sort = "p.created DESC";
5622 } else {
5623 $sort = "p.created ASC";
5626 $forumtracked = forum_tp_is_tracked($forum);
5627 $posts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
5628 $post = $posts[$post->id];
5630 foreach ($posts as $pid=>$p) {
5631 $posters[$p->userid] = $p->userid;
5634 // preload all groups of ppl that posted in this discussion
5635 if ($postersgroups = groups_get_all_groups($course->id, $posters, $cm->groupingid, 'gm.id, gm.groupid, gm.userid')) {
5636 foreach($postersgroups as $pg) {
5637 if (!isset($cm->cache->usersgroups[$pg->userid])) {
5638 $cm->cache->usersgroups[$pg->userid] = array();
5640 $cm->cache->usersgroups[$pg->userid][$pg->groupid] = $pg->groupid;
5642 unset($postersgroups);
5645 //load ratings
5646 if ($forum->assessed != RATING_AGGREGATE_NONE) {
5647 $ratingoptions = new stdClass;
5648 $ratingoptions->context = $modcontext;
5649 $ratingoptions->component = 'mod_forum';
5650 $ratingoptions->ratingarea = 'post';
5651 $ratingoptions->items = $posts;
5652 $ratingoptions->aggregate = $forum->assessed;//the aggregation method
5653 $ratingoptions->scaleid = $forum->scale;
5654 $ratingoptions->userid = $USER->id;
5655 if ($forum->type == 'single' or !$discussion->id) {
5656 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/view.php?id=$cm->id";
5657 } else {
5658 $ratingoptions->returnurl = "$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id";
5660 $ratingoptions->assesstimestart = $forum->assesstimestart;
5661 $ratingoptions->assesstimefinish = $forum->assesstimefinish;
5663 $rm = new rating_manager();
5664 $posts = $rm->get_ratings($ratingoptions);
5668 $post->forum = $forum->id; // Add the forum id to the post object, later used by forum_print_post
5669 $post->forumtype = $forum->type;
5671 $post->subject = format_string($post->subject);
5673 $postread = !empty($post->postread);
5675 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false,
5676 '', '', $postread, true, $forumtracked);
5678 switch ($mode) {
5679 case FORUM_MODE_FLATOLDEST :
5680 case FORUM_MODE_FLATNEWEST :
5681 default:
5682 forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts);
5683 break;
5685 case FORUM_MODE_THREADED :
5686 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $reply, $forumtracked, $posts);
5687 break;
5689 case FORUM_MODE_NESTED :
5690 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5691 break;
5697 * @global object
5698 * @global object
5699 * @uses FORUM_MODE_FLATNEWEST
5700 * @param object $course
5701 * @param object $cm
5702 * @param object $forum
5703 * @param object $discussion
5704 * @param object $post
5705 * @param object $mode
5706 * @param bool $reply
5707 * @param bool $forumtracked
5708 * @param array $posts
5709 * @return void
5711 function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts) {
5712 global $USER, $CFG;
5714 $link = false;
5716 if ($mode == FORUM_MODE_FLATNEWEST) {
5717 $sort = "ORDER BY created DESC";
5718 } else {
5719 $sort = "ORDER BY created ASC";
5722 foreach ($posts as $post) {
5723 if (!$post->parent) {
5724 continue;
5726 $post->subject = format_string($post->subject);
5727 $ownpost = ($USER->id == $post->userid);
5729 $postread = !empty($post->postread);
5731 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5732 '', '', $postread, true, $forumtracked);
5737 * @todo Document this function
5739 * @global object
5740 * @global object
5741 * @uses CONTEXT_MODULE
5742 * @return void
5744 function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $reply, $forumtracked, $posts) {
5745 global $USER, $CFG;
5747 $link = false;
5749 if (!empty($posts[$parent->id]->children)) {
5750 $posts = $posts[$parent->id]->children;
5752 $modcontext = context_module::instance($cm->id);
5753 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
5755 foreach ($posts as $post) {
5757 echo '<div class="indent">';
5758 if ($depth > 0) {
5759 $ownpost = ($USER->id == $post->userid);
5760 $post->subject = format_string($post->subject);
5762 $postread = !empty($post->postread);
5764 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5765 '', '', $postread, true, $forumtracked);
5766 } else {
5767 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
5768 echo "</div>\n";
5769 continue;
5771 $by = new stdClass();
5772 $by->name = fullname($post, $canviewfullnames);
5773 $by->date = userdate($post->modified);
5775 if ($forumtracked) {
5776 if (!empty($post->postread)) {
5777 $style = '<span class="forumthread read">';
5778 } else {
5779 $style = '<span class="forumthread unread">';
5781 } else {
5782 $style = '<span class="forumthread">';
5784 echo $style."<a name=\"$post->id\"></a>".
5785 "<a href=\"discuss.php?d=$post->discussion&amp;parent=$post->id\">".format_string($post->subject,true)."</a> ";
5786 print_string("bynameondate", "forum", $by);
5787 echo "</span>";
5790 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $reply, $forumtracked, $posts);
5791 echo "</div>\n";
5797 * @todo Document this function
5798 * @global object
5799 * @global object
5800 * @return void
5802 function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $reply, $forumtracked, $posts) {
5803 global $USER, $CFG;
5805 $link = false;
5807 if (!empty($posts[$parent->id]->children)) {
5808 $posts = $posts[$parent->id]->children;
5810 foreach ($posts as $post) {
5812 echo '<div class="indent">';
5813 if (!isloggedin()) {
5814 $ownpost = false;
5815 } else {
5816 $ownpost = ($USER->id == $post->userid);
5819 $post->subject = format_string($post->subject);
5820 $postread = !empty($post->postread);
5822 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5823 '', '', $postread, true, $forumtracked);
5824 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5825 echo "</div>\n";
5831 * Returns all forum posts since a given time in specified forum.
5833 * @todo Document this functions args
5834 * @global object
5835 * @global object
5836 * @global object
5837 * @global object
5839 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
5840 global $CFG, $COURSE, $USER, $DB;
5842 if ($COURSE->id == $courseid) {
5843 $course = $COURSE;
5844 } else {
5845 $course = $DB->get_record('course', array('id' => $courseid));
5848 $modinfo = get_fast_modinfo($course);
5850 $cm = $modinfo->cms[$cmid];
5851 $params = array($timestart, $cm->instance);
5853 if ($userid) {
5854 $userselect = "AND u.id = ?";
5855 $params[] = $userid;
5856 } else {
5857 $userselect = "";
5860 if ($groupid) {
5861 $groupselect = "AND d.groupid = ?";
5862 $params[] = $groupid;
5863 } else {
5864 $groupselect = "";
5867 $allnames = get_all_user_name_fields(true, 'u');
5868 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
5869 d.timestart, d.timeend, d.userid AS duserid,
5870 $allnames, u.email, u.picture, u.imagealt, u.email
5871 FROM {forum_posts} p
5872 JOIN {forum_discussions} d ON d.id = p.discussion
5873 JOIN {forum} f ON f.id = d.forum
5874 JOIN {user} u ON u.id = p.userid
5875 WHERE p.created > ? AND f.id = ?
5876 $userselect $groupselect
5877 ORDER BY p.id ASC", $params)) { // order by initial posting date
5878 return;
5881 $groupmode = groups_get_activity_groupmode($cm, $course);
5882 $cm_context = context_module::instance($cm->id);
5883 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
5884 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
5886 $printposts = array();
5887 foreach ($posts as $post) {
5889 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
5890 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
5891 if (!$viewhiddentimed) {
5892 continue;
5896 if ($groupmode) {
5897 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
5898 // oki (Open discussions have groupid -1)
5899 } else {
5900 // separate mode
5901 if (isguestuser()) {
5902 // shortcut
5903 continue;
5906 if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
5907 continue;
5912 $printposts[] = $post;
5915 if (!$printposts) {
5916 return;
5919 $aname = format_string($cm->name,true);
5921 foreach ($printposts as $post) {
5922 $tmpactivity = new stdClass();
5924 $tmpactivity->type = 'forum';
5925 $tmpactivity->cmid = $cm->id;
5926 $tmpactivity->name = $aname;
5927 $tmpactivity->sectionnum = $cm->sectionnum;
5928 $tmpactivity->timestamp = $post->modified;
5930 $tmpactivity->content = new stdClass();
5931 $tmpactivity->content->id = $post->id;
5932 $tmpactivity->content->discussion = $post->discussion;
5933 $tmpactivity->content->subject = format_string($post->subject);
5934 $tmpactivity->content->parent = $post->parent;
5936 $tmpactivity->user = new stdClass();
5937 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
5938 $additionalfields = explode(',', user_picture::fields());
5939 $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
5940 $tmpactivity->user->id = $post->userid;
5942 $activities[$index++] = $tmpactivity;
5945 return;
5949 * @todo Document this function
5950 * @global object
5952 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
5953 global $CFG, $OUTPUT;
5955 if ($activity->content->parent) {
5956 $class = 'reply';
5957 } else {
5958 $class = 'discussion';
5961 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
5963 echo "<tr><td class=\"userpicture\" valign=\"top\">";
5964 echo $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid));
5965 echo "</td><td class=\"$class\">";
5967 if ($activity->content->parent) {
5968 $class = 'title';
5969 } else {
5970 // Bold the title of new discussions so they stand out.
5971 $class = 'title bold';
5973 echo "<div class=\"{$class}\">";
5974 if ($detail) {
5975 $aname = s($activity->name);
5976 echo "<img src=\"" . $OUTPUT->pix_url('icon', $activity->type) . "\" ".
5977 "class=\"icon\" alt=\"{$aname}\" />";
5979 echo "<a href=\"$CFG->wwwroot/mod/forum/discuss.php?d={$activity->content->discussion}"
5980 ."#p{$activity->content->id}\">{$activity->content->subject}</a>";
5981 echo '</div>';
5983 echo '<div class="user">';
5984 $fullname = fullname($activity->user, $viewfullnames);
5985 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
5986 ."{$fullname}</a> - ".userdate($activity->timestamp);
5987 echo '</div>';
5988 echo "</td></tr></table>";
5990 return;
5994 * recursively sets the discussion field to $discussionid on $postid and all its children
5995 * used when pruning a post
5997 * @global object
5998 * @param int $postid
5999 * @param int $discussionid
6000 * @return bool
6002 function forum_change_discussionid($postid, $discussionid) {
6003 global $DB;
6004 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
6005 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
6006 foreach ($posts as $post) {
6007 forum_change_discussionid($post->id, $discussionid);
6010 return true;
6014 * Prints the editing button on subscribers page
6016 * @global object
6017 * @global object
6018 * @param int $courseid
6019 * @param int $forumid
6020 * @return string
6022 function forum_update_subscriptions_button($courseid, $forumid) {
6023 global $CFG, $USER;
6025 if (!empty($USER->subscriptionsediting)) {
6026 $string = get_string('turneditingoff');
6027 $edit = "off";
6028 } else {
6029 $string = get_string('turneditingon');
6030 $edit = "on";
6033 return "<form method=\"get\" action=\"$CFG->wwwroot/mod/forum/subscribers.php\">".
6034 "<input type=\"hidden\" name=\"id\" value=\"$forumid\" />".
6035 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
6036 "<input type=\"submit\" value=\"$string\" /></form>";
6039 // Functions to do with read tracking.
6042 * Mark posts as read.
6044 * @global object
6045 * @global object
6046 * @param object $user object
6047 * @param array $postids array of post ids
6048 * @return boolean success
6050 function forum_tp_mark_posts_read($user, $postids) {
6051 global $CFG, $DB;
6053 if (!forum_tp_can_track_forums(false, $user)) {
6054 return true;
6057 $status = true;
6059 $now = time();
6060 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6062 if (empty($postids)) {
6063 return true;
6065 } else if (count($postids) > 200) {
6066 while ($part = array_splice($postids, 0, 200)) {
6067 $status = forum_tp_mark_posts_read($user, $part) && $status;
6069 return $status;
6072 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid');
6074 $insertparams = array(
6075 'userid1' => $user->id,
6076 'userid2' => $user->id,
6077 'userid3' => $user->id,
6078 'firstread' => $now,
6079 'lastread' => $now,
6080 'cutoffdate' => $cutoffdate,
6082 $params = array_merge($postidparams, $insertparams);
6084 if ($CFG->forum_allowforcedreadtracking) {
6085 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6086 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))";
6087 } else {
6088 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6089 AND tf.id IS NULL)";
6092 // First insert any new entries.
6093 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6095 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
6096 FROM {forum_posts} p
6097 JOIN {forum_discussions} d ON d.id = p.discussion
6098 JOIN {forum} f ON f.id = d.forum
6099 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
6100 LEFT JOIN {forum_read} fr ON (
6101 fr.userid = :userid3
6102 AND fr.postid = p.id
6103 AND fr.discussionid = d.id
6104 AND fr.forumid = f.id
6106 WHERE p.id $usql
6107 AND p.modified >= :cutoffdate
6108 $trackingsql
6109 AND fr.id IS NULL";
6111 $status = $DB->execute($sql, $params) && $status;
6113 // Then update all records.
6114 $updateparams = array(
6115 'userid' => $user->id,
6116 'lastread' => $now,
6118 $params = array_merge($postidparams, $updateparams);
6119 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
6120 userid = :userid
6121 AND lastread <> :lastread
6122 AND postid ' . $usql,
6123 $params) && $status;
6125 return $status;
6129 * Mark post as read.
6130 * @global object
6131 * @global object
6132 * @param int $userid
6133 * @param int $postid
6135 function forum_tp_add_read_record($userid, $postid) {
6136 global $CFG, $DB;
6138 $now = time();
6139 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
6141 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
6142 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6144 SELECT ?, p.id, p.discussion, d.forum, ?, ?
6145 FROM {forum_posts} p
6146 JOIN {forum_discussions} d ON d.id = p.discussion
6147 WHERE p.id = ? AND p.modified >= ?";
6148 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
6150 } else {
6151 $sql = "UPDATE {forum_read}
6152 SET lastread = ?
6153 WHERE userid = ? AND postid = ?";
6154 return $DB->execute($sql, array($now, $userid, $userid));
6159 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
6161 * @return bool
6163 function forum_tp_mark_post_read($userid, $post, $forumid) {
6164 if (!forum_tp_is_post_old($post)) {
6165 return forum_tp_add_read_record($userid, $post->id);
6166 } else {
6167 return true;
6172 * Marks a whole forum as read, for a given user
6174 * @global object
6175 * @global object
6176 * @param object $user
6177 * @param int $forumid
6178 * @param int|bool $groupid
6179 * @return bool
6181 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
6182 global $CFG, $DB;
6184 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6186 $groupsel = "";
6187 $params = array($user->id, $forumid, $cutoffdate);
6189 if ($groupid !== false) {
6190 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
6191 $params[] = $groupid;
6194 $sql = "SELECT p.id
6195 FROM {forum_posts} p
6196 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
6197 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6198 WHERE d.forum = ?
6199 AND p.modified >= ? AND r.id is NULL
6200 $groupsel";
6202 if ($posts = $DB->get_records_sql($sql, $params)) {
6203 $postids = array_keys($posts);
6204 return forum_tp_mark_posts_read($user, $postids);
6207 return true;
6211 * Marks a whole discussion as read, for a given user
6213 * @global object
6214 * @global object
6215 * @param object $user
6216 * @param int $discussionid
6217 * @return bool
6219 function forum_tp_mark_discussion_read($user, $discussionid) {
6220 global $CFG, $DB;
6222 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6224 $sql = "SELECT p.id
6225 FROM {forum_posts} p
6226 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6227 WHERE p.discussion = ?
6228 AND p.modified >= ? AND r.id is NULL";
6230 if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) {
6231 $postids = array_keys($posts);
6232 return forum_tp_mark_posts_read($user, $postids);
6235 return true;
6239 * @global object
6240 * @param int $userid
6241 * @param object $post
6243 function forum_tp_is_post_read($userid, $post) {
6244 global $DB;
6245 return (forum_tp_is_post_old($post) ||
6246 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id)));
6250 * @global object
6251 * @param object $post
6252 * @param int $time Defautls to time()
6254 function forum_tp_is_post_old($post, $time=null) {
6255 global $CFG;
6257 if (is_null($time)) {
6258 $time = time();
6260 return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600)));
6264 * Returns the count of records for the provided user and course.
6265 * Please note that group access is ignored!
6267 * @global object
6268 * @global object
6269 * @param int $userid
6270 * @param int $courseid
6271 * @return array
6273 function forum_tp_get_course_unread_posts($userid, $courseid) {
6274 global $CFG, $DB;
6276 $now = round(time(), -2); // DB cache friendliness.
6277 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 60 * 60);
6278 $params = array($userid, $userid, $courseid, $cutoffdate, $userid);
6280 if (!empty($CFG->forum_enabletimedposts)) {
6281 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6282 $params[] = $now;
6283 $params[] = $now;
6284 } else {
6285 $timedsql = "";
6288 if ($CFG->forum_allowforcedreadtracking) {
6289 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED."
6290 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL
6291 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))";
6292 } else {
6293 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6294 AND tf.id IS NULL
6295 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)";
6298 $sql = "SELECT f.id, COUNT(p.id) AS unread
6299 FROM {forum_posts} p
6300 JOIN {forum_discussions} d ON d.id = p.discussion
6301 JOIN {forum} f ON f.id = d.forum
6302 JOIN {course} c ON c.id = f.course
6303 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6304 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id)
6305 WHERE f.course = ?
6306 AND p.modified >= ? AND r.id is NULL
6307 $trackingsql
6308 $timedsql
6309 GROUP BY f.id";
6311 if ($return = $DB->get_records_sql($sql, $params)) {
6312 return $return;
6315 return array();
6319 * Returns the count of records for the provided user and forum and [optionally] group.
6321 * @global object
6322 * @global object
6323 * @global object
6324 * @param object $cm
6325 * @param object $course
6326 * @return int
6328 function forum_tp_count_forum_unread_posts($cm, $course) {
6329 global $CFG, $USER, $DB;
6331 static $readcache = array();
6333 $forumid = $cm->instance;
6335 if (!isset($readcache[$course->id])) {
6336 $readcache[$course->id] = array();
6337 if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) {
6338 foreach ($counts as $count) {
6339 $readcache[$course->id][$count->id] = $count->unread;
6344 if (empty($readcache[$course->id][$forumid])) {
6345 // no need to check group mode ;-)
6346 return 0;
6349 $groupmode = groups_get_activity_groupmode($cm, $course);
6351 if ($groupmode != SEPARATEGROUPS) {
6352 return $readcache[$course->id][$forumid];
6355 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
6356 return $readcache[$course->id][$forumid];
6359 require_once($CFG->dirroot.'/course/lib.php');
6361 $modinfo = get_fast_modinfo($course);
6363 $mygroups = $modinfo->get_groups($cm->groupingid);
6365 // add all groups posts
6366 $mygroups[-1] = -1;
6368 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);
6370 $now = round(time(), -2); // db cache friendliness
6371 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
6372 $params = array($USER->id, $forumid, $cutoffdate);
6374 if (!empty($CFG->forum_enabletimedposts)) {
6375 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6376 $params[] = $now;
6377 $params[] = $now;
6378 } else {
6379 $timedsql = "";
6382 $params = array_merge($params, $groups_params);
6384 $sql = "SELECT COUNT(p.id)
6385 FROM {forum_posts} p
6386 JOIN {forum_discussions} d ON p.discussion = d.id
6387 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6388 WHERE d.forum = ?
6389 AND p.modified >= ? AND r.id is NULL
6390 $timedsql
6391 AND d.groupid $groups_sql";
6393 return $DB->get_field_sql($sql, $params);
6397 * Deletes read records for the specified index. At least one parameter must be specified.
6399 * @global object
6400 * @param int $userid
6401 * @param int $postid
6402 * @param int $discussionid
6403 * @param int $forumid
6404 * @return bool
6406 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
6407 global $DB;
6408 $params = array();
6410 $select = '';
6411 if ($userid > -1) {
6412 if ($select != '') $select .= ' AND ';
6413 $select .= 'userid = ?';
6414 $params[] = $userid;
6416 if ($postid > -1) {
6417 if ($select != '') $select .= ' AND ';
6418 $select .= 'postid = ?';
6419 $params[] = $postid;
6421 if ($discussionid > -1) {
6422 if ($select != '') $select .= ' AND ';
6423 $select .= 'discussionid = ?';
6424 $params[] = $discussionid;
6426 if ($forumid > -1) {
6427 if ($select != '') $select .= ' AND ';
6428 $select .= 'forumid = ?';
6429 $params[] = $forumid;
6431 if ($select == '') {
6432 return false;
6434 else {
6435 return $DB->delete_records_select('forum_read', $select, $params);
6439 * Get a list of forums not tracked by the user.
6441 * @global object
6442 * @global object
6443 * @param int $userid The id of the user to use.
6444 * @param int $courseid The id of the course being checked.
6445 * @return mixed An array indexed by forum id, or false.
6447 function forum_tp_get_untracked_forums($userid, $courseid) {
6448 global $CFG, $DB;
6450 if ($CFG->forum_allowforcedreadtracking) {
6451 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6452 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL
6453 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6454 } else {
6455 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF."
6456 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.")
6457 AND (ft.id IS NOT NULL
6458 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6461 $sql = "SELECT f.id
6462 FROM {forum} f
6463 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
6464 WHERE f.course = ?
6465 $trackingsql";
6467 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
6468 foreach ($forums as $forum) {
6469 $forums[$forum->id] = $forum;
6471 return $forums;
6473 } else {
6474 return array();
6479 * Determine if a user can track forums and optionally a particular forum.
6480 * Checks the site settings, the user settings and the forum settings (if
6481 * requested).
6483 * @global object
6484 * @global object
6485 * @global object
6486 * @param mixed $forum The forum object to test, or the int id (optional).
6487 * @param mixed $userid The user object to check for (optional).
6488 * @return boolean
6490 function forum_tp_can_track_forums($forum=false, $user=false) {
6491 global $USER, $CFG, $DB;
6493 // if possible, avoid expensive
6494 // queries
6495 if (empty($CFG->forum_trackreadposts)) {
6496 return false;
6499 if ($user === false) {
6500 $user = $USER;
6503 if (isguestuser($user) or empty($user->id)) {
6504 return false;
6507 if ($forum === false) {
6508 if ($CFG->forum_allowforcedreadtracking) {
6509 // Since we can force tracking, assume yes without a specific forum.
6510 return true;
6511 } else {
6512 return (bool)$user->trackforums;
6516 // Work toward always passing an object...
6517 if (is_numeric($forum)) {
6518 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6519 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
6522 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6523 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6525 if ($CFG->forum_allowforcedreadtracking) {
6526 // If we allow forcing, then forced forums takes procidence over user setting.
6527 return ($forumforced || ($forumallows && (!empty($user->trackforums) && (bool)$user->trackforums)));
6528 } else {
6529 // If we don't allow forcing, user setting trumps.
6530 return ($forumforced || $forumallows) && !empty($user->trackforums);
6535 * Tells whether a specific forum is tracked by the user. A user can optionally
6536 * be specified. If not specified, the current user is assumed.
6538 * @global object
6539 * @global object
6540 * @global object
6541 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
6542 * @param int $userid The id of the user being checked (optional).
6543 * @return boolean
6545 function forum_tp_is_tracked($forum, $user=false) {
6546 global $USER, $CFG, $DB;
6548 if ($user === false) {
6549 $user = $USER;
6552 if (isguestuser($user) or empty($user->id)) {
6553 return false;
6556 // Work toward always passing an object...
6557 if (is_numeric($forum)) {
6558 debugging('Better use proper forum object.', DEBUG_DEVELOPER);
6559 $forum = $DB->get_record('forum', array('id' => $forum));
6562 if (!forum_tp_can_track_forums($forum, $user)) {
6563 return false;
6566 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL);
6567 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED);
6568 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id));
6570 if ($CFG->forum_allowforcedreadtracking) {
6571 return $forumforced || ($forumallows && $userpref === false);
6572 } else {
6573 return ($forumallows || $forumforced) && $userpref === false;
6578 * @global object
6579 * @global object
6580 * @param int $forumid
6581 * @param int $userid
6583 function forum_tp_start_tracking($forumid, $userid=false) {
6584 global $USER, $DB;
6586 if ($userid === false) {
6587 $userid = $USER->id;
6590 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
6594 * @global object
6595 * @global object
6596 * @param int $forumid
6597 * @param int $userid
6599 function forum_tp_stop_tracking($forumid, $userid=false) {
6600 global $USER, $DB;
6602 if ($userid === false) {
6603 $userid = $USER->id;
6606 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
6607 $track_prefs = new stdClass();
6608 $track_prefs->userid = $userid;
6609 $track_prefs->forumid = $forumid;
6610 $DB->insert_record('forum_track_prefs', $track_prefs);
6613 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
6618 * Clean old records from the forum_read table.
6619 * @global object
6620 * @global object
6621 * @return void
6623 function forum_tp_clean_read_records() {
6624 global $CFG, $DB;
6626 if (!isset($CFG->forum_oldpostdays)) {
6627 return;
6629 // Look for records older than the cutoffdate that are still in the forum_read table.
6630 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60);
6632 //first get the oldest tracking present - we need tis to speedup the next delete query
6633 $sql = "SELECT MIN(fp.modified) AS first
6634 FROM {forum_posts} fp
6635 JOIN {forum_read} fr ON fr.postid=fp.id";
6636 if (!$first = $DB->get_field_sql($sql)) {
6637 // nothing to delete;
6638 return;
6641 // now delete old tracking info
6642 $sql = "DELETE
6643 FROM {forum_read}
6644 WHERE postid IN (SELECT fp.id
6645 FROM {forum_posts} fp
6646 WHERE fp.modified >= ? AND fp.modified < ?)";
6647 $DB->execute($sql, array($first, $cutoffdate));
6651 * Sets the last post for a given discussion
6653 * @global object
6654 * @global object
6655 * @param into $discussionid
6656 * @return bool|int
6658 function forum_discussion_update_last_post($discussionid) {
6659 global $CFG, $DB;
6661 // Check the given discussion exists
6662 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
6663 return false;
6666 // Use SQL to find the last post for this discussion
6667 $sql = "SELECT id, userid, modified
6668 FROM {forum_posts}
6669 WHERE discussion=?
6670 ORDER BY modified DESC";
6672 // Lets go find the last post
6673 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
6674 $lastpost = reset($lastposts);
6675 $discussionobject = new stdClass();
6676 $discussionobject->id = $discussionid;
6677 $discussionobject->usermodified = $lastpost->userid;
6678 $discussionobject->timemodified = $lastpost->modified;
6679 $DB->update_record('forum_discussions', $discussionobject);
6680 return $lastpost->id;
6683 // To get here either we couldn't find a post for the discussion (weird)
6684 // or we couldn't update the discussion record (weird x2)
6685 return false;
6690 * List the actions that correspond to a view of this module.
6691 * This is used by the participation report.
6693 * Note: This is not used by new logging system. Event with
6694 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
6695 * be considered as view action.
6697 * @return array
6699 function forum_get_view_actions() {
6700 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
6704 * List the actions that correspond to a post of this module.
6705 * This is used by the participation report.
6707 * Note: This is not used by new logging system. Event with
6708 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
6709 * will be considered as post action.
6711 * @return array
6713 function forum_get_post_actions() {
6714 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
6718 * Returns a warning object if a user has reached the number of posts equal to
6719 * the warning/blocking setting, or false if there is no warning to show.
6721 * @param int|stdClass $forum the forum id or the forum object
6722 * @param stdClass $cm the course module
6723 * @return stdClass|bool returns an object with the warning information, else
6724 * returns false if no warning is required.
6726 function forum_check_throttling($forum, $cm = null) {
6727 global $CFG, $DB, $USER;
6729 if (is_numeric($forum)) {
6730 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST);
6733 if (!is_object($forum)) {
6734 return false; // This is broken.
6737 if (!$cm) {
6738 $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST);
6741 if (empty($forum->blockafter)) {
6742 return false;
6745 if (empty($forum->blockperiod)) {
6746 return false;
6749 $modcontext = context_module::instance($cm->id);
6750 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
6751 return false;
6754 // Get the number of posts in the last period we care about.
6755 $timenow = time();
6756 $timeafter = $timenow - $forum->blockperiod;
6757 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
6758 JOIN {forum_discussions} d
6759 ON p.discussion = d.id WHERE d.forum = ?
6760 AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter));
6762 $a = new stdClass();
6763 $a->blockafter = $forum->blockafter;
6764 $a->numposts = $numposts;
6765 $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
6767 if ($forum->blockafter <= $numposts) {
6768 $warning = new stdClass();
6769 $warning->canpost = false;
6770 $warning->errorcode = 'forumblockingtoomanyposts';
6771 $warning->module = 'error';
6772 $warning->additional = $a;
6773 $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id;
6775 return $warning;
6778 if ($forum->warnafter <= $numposts) {
6779 $warning = new stdClass();
6780 $warning->canpost = true;
6781 $warning->errorcode = 'forumblockingalmosttoomanyposts';
6782 $warning->module = 'forum';
6783 $warning->additional = $a;
6784 $warning->link = null;
6786 return $warning;
6791 * Throws an error if the user is no longer allowed to post due to having reached
6792 * or exceeded the number of posts specified in 'Post threshold for blocking'
6793 * setting.
6795 * @since Moodle 2.5
6796 * @param stdClass $thresholdwarning the warning information returned
6797 * from the function forum_check_throttling.
6799 function forum_check_blocking_threshold($thresholdwarning) {
6800 if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
6801 print_error($thresholdwarning->errorcode,
6802 $thresholdwarning->module,
6803 $thresholdwarning->link,
6804 $thresholdwarning->additional);
6810 * Removes all grades from gradebook
6812 * @global object
6813 * @global object
6814 * @param int $courseid
6815 * @param string $type optional
6817 function forum_reset_gradebook($courseid, $type='') {
6818 global $CFG, $DB;
6820 $wheresql = '';
6821 $params = array($courseid);
6822 if ($type) {
6823 $wheresql = "AND f.type=?";
6824 $params[] = $type;
6827 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
6828 FROM {forum} f, {course_modules} cm, {modules} m
6829 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
6831 if ($forums = $DB->get_records_sql($sql, $params)) {
6832 foreach ($forums as $forum) {
6833 forum_grade_item_update($forum, 'reset');
6839 * This function is used by the reset_course_userdata function in moodlelib.
6840 * This function will remove all posts from the specified forum
6841 * and clean up any related data.
6843 * @global object
6844 * @global object
6845 * @param $data the data submitted from the reset course.
6846 * @return array status array
6848 function forum_reset_userdata($data) {
6849 global $CFG, $DB;
6850 require_once($CFG->dirroot.'/rating/lib.php');
6852 $componentstr = get_string('modulenameplural', 'forum');
6853 $status = array();
6855 $params = array($data->courseid);
6857 $removeposts = false;
6858 $typesql = "";
6859 if (!empty($data->reset_forum_all)) {
6860 $removeposts = true;
6861 $typesstr = get_string('resetforumsall', 'forum');
6862 $types = array();
6863 } else if (!empty($data->reset_forum_types)){
6864 $removeposts = true;
6865 $types = array();
6866 $sqltypes = array();
6867 $forum_types_all = forum_get_forum_types_all();
6868 foreach ($data->reset_forum_types as $type) {
6869 if (!array_key_exists($type, $forum_types_all)) {
6870 continue;
6872 $types[] = $forum_types_all[$type];
6873 $sqltypes[] = $type;
6875 if (!empty($sqltypes)) {
6876 list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
6877 $typesql = " AND f.type " . $typesql;
6878 $params = array_merge($params, $typeparams);
6880 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
6882 $alldiscussionssql = "SELECT fd.id
6883 FROM {forum_discussions} fd, {forum} f
6884 WHERE f.course=? AND f.id=fd.forum";
6886 $allforumssql = "SELECT f.id
6887 FROM {forum} f
6888 WHERE f.course=?";
6890 $allpostssql = "SELECT fp.id
6891 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
6892 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
6894 $forumssql = $forums = $rm = null;
6896 if( $removeposts || !empty($data->reset_forum_ratings) ) {
6897 $forumssql = "$allforumssql $typesql";
6898 $forums = $forums = $DB->get_records_sql($forumssql, $params);
6899 $rm = new rating_manager();
6900 $ratingdeloptions = new stdClass;
6901 $ratingdeloptions->component = 'mod_forum';
6902 $ratingdeloptions->ratingarea = 'post';
6905 if ($removeposts) {
6906 $discussionssql = "$alldiscussionssql $typesql";
6907 $postssql = "$allpostssql $typesql";
6909 // now get rid of all attachments
6910 $fs = get_file_storage();
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);
6917 $fs->delete_area_files($context->id, 'mod_forum', 'attachment');
6918 $fs->delete_area_files($context->id, 'mod_forum', 'post');
6920 //remove ratings
6921 $ratingdeloptions->contextid = $context->id;
6922 $rm->delete_ratings($ratingdeloptions);
6926 // first delete all read flags
6927 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
6929 // remove tracking prefs
6930 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
6932 // remove posts from queue
6933 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
6935 // all posts - initial posts must be kept in single simple discussion forums
6936 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
6937 $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
6939 // finally all discussions except single simple forums
6940 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
6942 // remove all grades from gradebook
6943 if (empty($data->reset_gradebook_grades)) {
6944 if (empty($types)) {
6945 forum_reset_gradebook($data->courseid);
6946 } else {
6947 foreach ($types as $type) {
6948 forum_reset_gradebook($data->courseid, $type);
6953 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
6956 // remove all ratings in this course's forums
6957 if (!empty($data->reset_forum_ratings)) {
6958 if ($forums) {
6959 foreach ($forums as $forumid=>$unused) {
6960 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
6961 continue;
6963 $context = context_module::instance($cm->id);
6965 //remove ratings
6966 $ratingdeloptions->contextid = $context->id;
6967 $rm->delete_ratings($ratingdeloptions);
6971 // remove all grades from gradebook
6972 if (empty($data->reset_gradebook_grades)) {
6973 forum_reset_gradebook($data->courseid);
6977 // remove all digest settings unconditionally - even for users still enrolled in course.
6978 if (!empty($data->reset_forum_digests)) {
6979 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
6980 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
6983 // remove all subscriptions unconditionally - even for users still enrolled in course
6984 if (!empty($data->reset_forum_subscriptions)) {
6985 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
6986 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
6987 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
6990 // remove all tracking prefs unconditionally - even for users still enrolled in course
6991 if (!empty($data->reset_forum_track_prefs)) {
6992 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
6993 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
6996 /// updating dates - shift may be negative too
6997 if ($data->timeshift) {
6998 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid);
6999 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
7002 return $status;
7006 * Called by course/reset.php
7008 * @param $mform form passed by reference
7010 function forum_reset_course_form_definition(&$mform) {
7011 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
7013 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
7015 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
7016 $mform->setAdvanced('reset_forum_types');
7017 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
7019 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
7020 $mform->setAdvanced('reset_forum_digests');
7022 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
7023 $mform->setAdvanced('reset_forum_subscriptions');
7025 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
7026 $mform->setAdvanced('reset_forum_track_prefs');
7027 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
7029 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
7030 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
7034 * Course reset form defaults.
7035 * @return array
7037 function forum_reset_course_form_defaults($course) {
7038 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
7042 * Returns array of forum layout modes
7044 * @return array
7046 function forum_get_layout_modes() {
7047 return array (FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
7048 FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
7049 FORUM_MODE_THREADED => get_string('modethreaded', 'forum'),
7050 FORUM_MODE_NESTED => get_string('modenested', 'forum'));
7054 * Returns array of forum types chooseable on the forum editing form
7056 * @return array
7058 function forum_get_forum_types() {
7059 return array ('general' => get_string('generalforum', 'forum'),
7060 'eachuser' => get_string('eachuserforum', 'forum'),
7061 'single' => get_string('singleforum', 'forum'),
7062 'qanda' => get_string('qandaforum', 'forum'),
7063 'blog' => get_string('blogforum', 'forum'));
7067 * Returns array of all forum layout modes
7069 * @return array
7071 function forum_get_forum_types_all() {
7072 return array ('news' => get_string('namenews','forum'),
7073 'social' => get_string('namesocial','forum'),
7074 'general' => get_string('generalforum', 'forum'),
7075 'eachuser' => get_string('eachuserforum', 'forum'),
7076 'single' => get_string('singleforum', 'forum'),
7077 'qanda' => get_string('qandaforum', 'forum'),
7078 'blog' => get_string('blogforum', 'forum'));
7082 * Returns all other caps used in module
7084 * @return array
7086 function forum_get_extra_capabilities() {
7087 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate');
7091 * Adds module specific settings to the settings block
7093 * @param settings_navigation $settings The settings navigation object
7094 * @param navigation_node $forumnode The node to add module settings to
7096 function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) {
7097 global $USER, $PAGE, $CFG, $DB, $OUTPUT;
7099 $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm->instance));
7100 if (empty($PAGE->cm->context)) {
7101 $PAGE->cm->context = context_module::instance($PAGE->cm->instance);
7104 $params = $PAGE->url->params();
7105 if (!empty($params['d'])) {
7106 $discussionid = $params['d'];
7109 // for some actions you need to be enrolled, beiing admin is not enough sometimes here
7110 $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false);
7111 $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true);
7113 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context);
7114 $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject);
7115 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) &&
7116 (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage);
7118 if ($canmanage) {
7119 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER);
7121 $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);
7122 $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);
7123 $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);
7124 $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);
7126 switch ($subscriptionmode) {
7127 case FORUM_CHOOSESUBSCRIBE : // 0
7128 $allowchoice->action = null;
7129 $allowchoice->add_class('activesetting');
7130 break;
7131 case FORUM_FORCESUBSCRIBE : // 1
7132 $forceforever->action = null;
7133 $forceforever->add_class('activesetting');
7134 break;
7135 case FORUM_INITIALSUBSCRIBE : // 2
7136 $forceinitially->action = null;
7137 $forceinitially->add_class('activesetting');
7138 break;
7139 case FORUM_DISALLOWSUBSCRIBE : // 3
7140 $disallowchoice->action = null;
7141 $disallowchoice->add_class('activesetting');
7142 break;
7145 } else if ($activeenrolled) {
7147 switch ($subscriptionmode) {
7148 case FORUM_CHOOSESUBSCRIBE : // 0
7149 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
7150 break;
7151 case FORUM_FORCESUBSCRIBE : // 1
7152 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
7153 break;
7154 case FORUM_INITIALSUBSCRIBE : // 2
7155 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
7156 break;
7157 case FORUM_DISALLOWSUBSCRIBE : // 3
7158 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
7159 break;
7163 if ($cansubscribe) {
7164 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, null, $PAGE->cm)) {
7165 $linktext = get_string('unsubscribe', 'forum');
7166 } else {
7167 $linktext = get_string('subscribe', 'forum');
7169 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey()));
7170 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7172 if (isset($discussionid)) {
7173 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, $discussionid, $PAGE->cm)) {
7174 $linktext = get_string('unsubscribediscussion', 'forum');
7175 } else {
7176 $linktext = get_string('subscribediscussion', 'forum');
7178 $url = new moodle_url('/mod/forum/subscribe.php', array(
7179 'id' => $forumobject->id,
7180 'sesskey' => sesskey(),
7181 'd' => $discussionid,
7182 'returnurl' => $PAGE->url->out(),
7184 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7188 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){
7189 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id));
7190 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING);
7193 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
7194 if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL
7195 || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) {
7196 if (forum_tp_is_tracked($forumobject)) {
7197 $linktext = get_string('notrackforum', 'forum');
7198 } else {
7199 $linktext = get_string('trackforum', 'forum');
7201 $url = new moodle_url('/mod/forum/settracking.php', array(
7202 'id' => $forumobject->id,
7203 'sesskey' => sesskey(),
7205 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING);
7209 if (!isloggedin() && $PAGE->course->id == SITEID) {
7210 $userid = guest_user()->id;
7211 } else {
7212 $userid = $USER->id;
7215 $hascourseaccess = ($PAGE->course->id == SITEID) || can_access_course($PAGE->course, $userid);
7216 $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds);
7218 if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) {
7220 if (!function_exists('rss_get_url')) {
7221 require_once("$CFG->libdir/rsslib.php");
7224 if ($forumobject->rsstype == 1) {
7225 $string = get_string('rsssubscriberssdiscussions','forum');
7226 } else {
7227 $string = get_string('rsssubscriberssposts','forum');
7230 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id));
7231 $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
7236 * Adds information about unread messages, that is only required for the course view page (and
7237 * similar), to the course-module object.
7238 * @param cm_info $cm Course-module object
7240 function forum_cm_info_view(cm_info $cm) {
7241 global $CFG;
7243 if (forum_tp_can_track_forums()) {
7244 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
7245 $out = '<span class="unread"> <a href="' . $cm->url . '">';
7246 if ($unread == 1) {
7247 $out .= get_string('unreadpostsone', 'forum');
7248 } else {
7249 $out .= get_string('unreadpostsnumber', 'forum', $unread);
7251 $out .= '</a></span>';
7252 $cm->set_after_link($out);
7258 * Return a list of page types
7259 * @param string $pagetype current page type
7260 * @param stdClass $parentcontext Block's parent context
7261 * @param stdClass $currentcontext Current context of block
7263 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
7264 $forum_pagetype = array(
7265 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
7266 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
7267 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
7269 return $forum_pagetype;
7273 * Gets all of the courses where the provided user has posted in a forum.
7275 * @global moodle_database $DB The database connection
7276 * @param stdClass $user The user who's posts we are looking for
7277 * @param bool $discussionsonly If true only look for discussions started by the user
7278 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
7279 * @param int $limitfrom The offset of records to return
7280 * @param int $limitnum The number of records to return
7281 * @return array An array of courses
7283 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
7284 global $DB;
7286 // If we are only after discussions we need only look at the forum_discussions
7287 // table and join to the userid there. If we are looking for posts then we need
7288 // to join to the forum_posts table.
7289 if (!$discussionsonly) {
7290 $subquery = "(SELECT DISTINCT fd.course
7291 FROM {forum_discussions} fd
7292 JOIN {forum_posts} fp ON fp.discussion = fd.id
7293 WHERE fp.userid = :userid )";
7294 } else {
7295 $subquery= "(SELECT DISTINCT fd.course
7296 FROM {forum_discussions} fd
7297 WHERE fd.userid = :userid )";
7300 $params = array('userid' => $user->id);
7302 // Join to the context table so that we can preload contexts if required.
7303 if ($includecontexts) {
7304 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
7305 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
7306 $params['contextlevel'] = CONTEXT_COURSE;
7307 } else {
7308 $ctxselect = '';
7309 $ctxjoin = '';
7312 // Now we need to get all of the courses to search.
7313 // All courses where the user has posted within a forum will be returned.
7314 $sql = "SELECT c.* $ctxselect
7315 FROM {course} c
7316 $ctxjoin
7317 WHERE c.id IN ($subquery)";
7318 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7319 if ($includecontexts) {
7320 array_map('context_helper::preload_from_record', $courses);
7322 return $courses;
7326 * Gets all of the forums a user has posted in for one or more courses.
7328 * @global moodle_database $DB
7329 * @param stdClass $user
7330 * @param array $courseids An array of courseids to search or if not provided
7331 * all courses the user has posted within
7332 * @param bool $discussionsonly If true then only forums where the user has started
7333 * a discussion will be returned.
7334 * @param int $limitfrom The offset of records to return
7335 * @param int $limitnum The number of records to return
7336 * @return array An array of forums the user has posted within in the provided courses
7338 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
7339 global $DB;
7341 if (!is_null($courseids)) {
7342 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid');
7343 $coursewhere = ' AND f.course '.$coursewhere;
7344 } else {
7345 $coursewhere = '';
7346 $params = array();
7348 $params['userid'] = $user->id;
7349 $params['forum'] = 'forum';
7351 if ($discussionsonly) {
7352 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
7353 } else {
7354 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
7355 JOIN {forum_posts} ff ON ff.discussion = fd.id';
7358 $sql = "SELECT f.*, cm.id AS cmid
7359 FROM {forum} f
7360 JOIN {course_modules} cm ON cm.instance = f.id
7361 JOIN {modules} m ON m.id = cm.module
7362 JOIN (
7363 SELECT f.id
7364 FROM {forum} f
7365 {$join}
7366 WHERE ff.userid = :userid
7367 GROUP BY f.id
7368 ) j ON j.id = f.id
7369 WHERE m.name = :forum
7370 {$coursewhere}";
7372 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7373 return $courseforums;
7377 * Returns posts made by the selected user in the requested courses.
7379 * This method can be used to return all of the posts made by the requested user
7380 * within the given courses.
7381 * For each course the access of the current user and requested user is checked
7382 * and then for each post access to the post and forum is checked as well.
7384 * This function is safe to use with usercapabilities.
7386 * @global moodle_database $DB
7387 * @param stdClass $user The user whose posts we want to get
7388 * @param array $courses The courses to search
7389 * @param bool $musthaveaccess If set to true errors will be thrown if the user
7390 * cannot access one or more of the courses to search
7391 * @param bool $discussionsonly If set to true only discussion starting posts
7392 * will be returned.
7393 * @param int $limitfrom The offset of records to return
7394 * @param int $limitnum The number of records to return
7395 * @return stdClass An object the following properties
7396 * ->totalcount: the total number of posts made by the requested user
7397 * that the current user can see.
7398 * ->courses: An array of courses the current user can see that the
7399 * requested user has posted in.
7400 * ->forums: An array of forums relating to the posts returned in the
7401 * property below.
7402 * ->posts: An array containing the posts to show for this request.
7404 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
7405 global $DB, $USER, $CFG;
7407 $return = new stdClass;
7408 $return->totalcount = 0; // The total number of posts that the current user is able to view
7409 $return->courses = array(); // The courses the current user can access
7410 $return->forums = array(); // The forums that the current user can access that contain posts
7411 $return->posts = array(); // The posts to display
7413 // First up a small sanity check. If there are no courses to check we can
7414 // return immediately, there is obviously nothing to search.
7415 if (empty($courses)) {
7416 return $return;
7419 // A couple of quick setups
7420 $isloggedin = isloggedin();
7421 $isguestuser = $isloggedin && isguestuser();
7422 $iscurrentuser = $isloggedin && $USER->id == $user->id;
7424 // Checkout whether or not the current user has capabilities over the requested
7425 // user and if so they have the capabilities required to view the requested
7426 // users content.
7427 $usercontext = context_user::instance($user->id, MUST_EXIST);
7428 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
7429 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
7431 // Before we actually search each course we need to check the user's access to the
7432 // course. If the user doesn't have the appropraite access then we either throw an
7433 // error if a particular course was requested or we just skip over the course.
7434 foreach ($courses as $course) {
7435 $coursecontext = context_course::instance($course->id, MUST_EXIST);
7436 if ($iscurrentuser || $hascapsonuser) {
7437 // If it is the current user, or the current user has capabilities to the
7438 // requested user then all we need to do is check the requested users
7439 // current access to the course.
7440 // Note: There is no need to check group access or anything of the like
7441 // as either the current user is the requested user, or has granted
7442 // capabilities on the requested user. Either way they can see what the
7443 // requested user posted, although its VERY unlikely in the `parent` situation
7444 // that the current user will be able to view the posts in context.
7445 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
7446 // Need to have full access to a course to see the rest of own info
7447 if ($musthaveaccess) {
7448 print_error('errorenrolmentrequired', 'forum');
7450 continue;
7452 } else {
7453 // Check whether the current user is enrolled or has access to view the course
7454 // if they don't we immediately have a problem.
7455 if (!can_access_course($course)) {
7456 if ($musthaveaccess) {
7457 print_error('errorenrolmentrequired', 'forum');
7459 continue;
7462 // Check whether the requested user is enrolled or has access to view the course
7463 // if they don't we immediately have a problem.
7464 if (!can_access_course($course, $user) && !is_enrolled($coursecontext, $user)) {
7465 if ($musthaveaccess) {
7466 print_error('notenrolled', 'forum');
7468 continue;
7471 // If groups are in use and enforced throughout the course then make sure
7472 // we can meet in at least one course level group.
7473 // Note that we check if either the current user or the requested user have
7474 // the capability to access all groups. This is because with that capability
7475 // a user in group A could post in the group B forum. Grrrr.
7476 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
7477 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
7478 // If its the guest user to bad... the guest user cannot access groups
7479 if (!$isloggedin or $isguestuser) {
7480 // do not use require_login() here because we might have already used require_login($course)
7481 if ($musthaveaccess) {
7482 redirect(get_login_url());
7484 continue;
7486 // Get the groups of the current user
7487 $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
7488 // Get the groups the requested user is a member of
7489 $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
7490 // Check whether they are members of the same group. If they are great.
7491 $intersect = array_intersect($mygroups, $usergroups);
7492 if (empty($intersect)) {
7493 // But they're not... if it was a specific course throw an error otherwise
7494 // just skip this course so that it is not searched.
7495 if ($musthaveaccess) {
7496 print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
7498 continue;
7502 // Woo hoo we got this far which means the current user can search this
7503 // this course for the requested user. Although this is only the course accessibility
7504 // handling that is complete, the forum accessibility tests are yet to come.
7505 $return->courses[$course->id] = $course;
7507 // No longer beed $courses array - lose it not it may be big
7508 unset($courses);
7510 // Make sure that we have some courses to search
7511 if (empty($return->courses)) {
7512 // If we don't have any courses to search then the reality is that the current
7513 // user doesn't have access to any courses is which the requested user has posted.
7514 // Although we do know at this point that the requested user has posts.
7515 if ($musthaveaccess) {
7516 print_error('permissiondenied');
7517 } else {
7518 return $return;
7522 // Next step: Collect all of the forums that we will want to search.
7523 // It is important to note that this step isn't actually about searching, it is
7524 // about determining which forums we can search by testing accessibility.
7525 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);
7527 // Will be used to build the where conditions for the search
7528 $forumsearchwhere = array();
7529 // Will be used to store the where condition params for the search
7530 $forumsearchparams = array();
7531 // Will record forums where the user can freely access everything
7532 $forumsearchfullaccess = array();
7533 // DB caching friendly
7534 $now = round(time(), -2);
7535 // For each course to search we want to find the forums the user has posted in
7536 // and providing the current user can access the forum create a search condition
7537 // for the forum to get the requested users posts.
7538 foreach ($return->courses as $course) {
7539 // Now we need to get the forums
7540 $modinfo = get_fast_modinfo($course);
7541 if (empty($modinfo->instances['forum'])) {
7542 // hmmm, no forums? well at least its easy... skip!
7543 continue;
7545 // Iterate
7546 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
7547 if (!$cm->uservisible or !isset($forums[$forumid])) {
7548 continue;
7550 // Get the forum in question
7551 $forum = $forums[$forumid];
7553 // This is needed for functionality later on in the forum code. It is converted to an object
7554 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
7555 // code were expecting an writeable object. See {@link forum_print_post()}.
7556 $forum->cm = new stdClass();
7557 foreach ($cm as $key => $value) {
7558 $forum->cm->$key = $value;
7561 // Check that either the current user can view the forum, or that the
7562 // current user has capabilities over the requested user and the requested
7563 // user can view the discussion
7564 if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
7565 continue;
7568 // This will contain forum specific where clauses
7569 $forumsearchselect = array();
7570 if (!$iscurrentuser && !$hascapsonuser) {
7571 // Make sure we check group access
7572 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
7573 $groups = $modinfo->get_groups($cm->groupingid);
7574 $groups[] = -1;
7575 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
7576 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
7577 $forumsearchselect[] = "d.groupid $groupid_sql";
7580 // hidden timed discussions
7581 if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
7582 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
7583 $forumsearchparams['userid'.$forumid] = $user->id;
7584 $forumsearchparams['timestart'.$forumid] = $now;
7585 $forumsearchparams['timeend'.$forumid] = $now;
7588 // qanda access
7589 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
7590 // We need to check whether the user has posted in the qanda forum.
7591 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
7592 if (!empty($discussionspostedin)) {
7593 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
7594 foreach ($discussionspostedin as $d) {
7595 $forumonlydiscussions[] = $d->id;
7597 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
7598 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
7599 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
7600 } else {
7601 $forumsearchselect[] = "p.parent = 0";
7606 if (count($forumsearchselect) > 0) {
7607 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
7608 $forumsearchparams['forum'.$forumid] = $forumid;
7609 } else {
7610 $forumsearchfullaccess[] = $forumid;
7612 } else {
7613 // The current user/parent can see all of their own posts
7614 $forumsearchfullaccess[] = $forumid;
7619 // If we dont have any search conditions, and we don't have any forums where
7620 // the user has full access then we just return the default.
7621 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
7622 return $return;
7625 // Prepare a where condition for the full access forums.
7626 if (count($forumsearchfullaccess) > 0) {
7627 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
7628 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
7629 $forumsearchwhere[] = "(d.forum $fullidsql)";
7632 // Prepare SQL to both count and search.
7633 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
7634 // oracle and mssql.
7635 $userfields = user_picture::fields('u', null, 'useridx');
7636 $countsql = 'SELECT COUNT(*) ';
7637 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
7638 $wheresql = implode(" OR ", $forumsearchwhere);
7640 if ($discussionsonly) {
7641 if ($wheresql == '') {
7642 $wheresql = 'p.parent = 0';
7643 } else {
7644 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
7648 $sql = "FROM {forum_posts} p
7649 JOIN {forum_discussions} d ON d.id = p.discussion
7650 JOIN {user} u ON u.id = p.userid
7651 WHERE ($wheresql)
7652 AND p.userid = :userid ";
7653 $orderby = "ORDER BY p.modified DESC";
7654 $forumsearchparams['userid'] = $user->id;
7656 // Set the total number posts made by the requested user that the current user can see
7657 $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
7658 // Set the collection of posts that has been requested
7659 $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
7661 // We need to build an array of forums for which posts will be displayed.
7662 // We do this here to save the caller needing to retrieve them themselves before
7663 // printing these forums posts. Given we have the forums already there is
7664 // practically no overhead here.
7665 foreach ($return->posts as $post) {
7666 if (!array_key_exists($post->forum, $return->forums)) {
7667 $return->forums[$post->forum] = $forums[$post->forum];
7671 return $return;
7675 * Set the per-forum maildigest option for the specified user.
7677 * @param stdClass $forum The forum to set the option for.
7678 * @param int $maildigest The maildigest option.
7679 * @param stdClass $user The user object. This defaults to the global $USER object.
7680 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
7682 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
7683 global $DB, $USER;
7685 if (is_number($forum)) {
7686 $forum = $DB->get_record('forum', array('id' => $forum));
7689 if ($user === null) {
7690 $user = $USER;
7693 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
7694 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
7695 $context = context_module::instance($cm->id);
7697 // User must be allowed to see this forum.
7698 require_capability('mod/forum:viewdiscussion', $context, $user->id);
7700 // Validate the maildigest setting.
7701 $digestoptions = forum_get_user_digest_options($user);
7703 if (!isset($digestoptions[$maildigest])) {
7704 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
7707 // Attempt to retrieve any existing forum digest record.
7708 $subscription = $DB->get_record('forum_digests', array(
7709 'userid' => $user->id,
7710 'forum' => $forum->id,
7713 // Create or Update the existing maildigest setting.
7714 if ($subscription) {
7715 if ($maildigest == -1) {
7716 $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id));
7717 } else if ($maildigest !== $subscription->maildigest) {
7718 // Only update the maildigest setting if it's changed.
7720 $subscription->maildigest = $maildigest;
7721 $DB->update_record('forum_digests', $subscription);
7723 } else {
7724 if ($maildigest != -1) {
7725 // Only insert the maildigest setting if it's non-default.
7727 $subscription = new stdClass();
7728 $subscription->forum = $forum->id;
7729 $subscription->userid = $user->id;
7730 $subscription->maildigest = $maildigest;
7731 $subscription->id = $DB->insert_record('forum_digests', $subscription);
7737 * Determine the maildigest setting for the specified user against the
7738 * specified forum.
7740 * @param Array $digests An array of forums and user digest settings.
7741 * @param stdClass $user The user object containing the id and maildigest default.
7742 * @param int $forumid The ID of the forum to check.
7743 * @return int The calculated maildigest setting for this user and forum.
7745 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
7746 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) {
7747 $maildigest = $digests[$forumid][$user->id];
7748 if ($maildigest === -1) {
7749 $maildigest = $user->maildigest;
7751 } else {
7752 $maildigest = $user->maildigest;
7754 return $maildigest;
7758 * Retrieve the list of available user digest options.
7760 * @param stdClass $user The user object. This defaults to the global $USER object.
7761 * @return array The mapping of values to digest options.
7763 function forum_get_user_digest_options($user = null) {
7764 global $USER;
7766 // Revert to the global user object.
7767 if ($user === null) {
7768 $user = $USER;
7771 $digestoptions = array();
7772 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
7773 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
7774 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
7776 // We need to add the default digest option at the end - it relies on
7777 // the contents of the existing values.
7778 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
7779 $digestoptions[$user->maildigest]);
7781 // Resort the options to be in a sensible order.
7782 ksort($digestoptions);
7784 return $digestoptions;
7788 * Determine the current context if one was not already specified.
7790 * If a context of type context_module is specified, it is immediately
7791 * returned and not checked.
7793 * @param int $forumid The ID of the forum
7794 * @param context_module $context The current context.
7795 * @return context_module The context determined
7797 function forum_get_context($forumid, $context = null) {
7798 global $PAGE;
7800 if (!$context || !($context instanceof context_module)) {
7801 // Find out forum context. First try to take current page context to save on DB query.
7802 if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid
7803 && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) {
7804 $context = $PAGE->context;
7805 } else {
7806 $cm = get_coursemodule_from_instance('forum', $forumid);
7807 $context = \context_module::instance($cm->id);
7811 return $context;
7815 * Mark the activity completed (if required) and trigger the course_module_viewed event.
7817 * @param stdClass $forum forum object
7818 * @param stdClass $course course object
7819 * @param stdClass $cm course module object
7820 * @param stdClass $context context object
7821 * @since Moodle 2.9
7823 function forum_view($forum, $course, $cm, $context) {
7825 // Completion.
7826 $completion = new completion_info($course);
7827 $completion->set_module_viewed($cm);
7829 // Trigger course_module_viewed event.
7831 $params = array(
7832 'context' => $context,
7833 'objectid' => $forum->id
7836 $event = \mod_forum\event\course_module_viewed::create($params);
7837 $event->add_record_snapshot('course_modules', $cm);
7838 $event->add_record_snapshot('course', $course);
7839 $event->add_record_snapshot('forum', $forum);
7840 $event->trigger();
7844 * Trigger the discussion viewed event
7846 * @param stdClass $modcontext module context object
7847 * @param stdClass $forum forum object
7848 * @param stdClass $discussion discussion object
7849 * @since Moodle 2.9
7851 function forum_discussion_view($modcontext, $forum, $discussion) {
7852 $params = array(
7853 'context' => $modcontext,
7854 'objectid' => $discussion->id,
7857 $event = \mod_forum\event\discussion_viewed::create($params);
7858 $event->add_record_snapshot('forum_discussions', $discussion);
7859 $event->add_record_snapshot('forum', $forum);
7860 $event->trigger();
7864 * Add nodes to myprofile page.
7866 * @param \core_user\output\myprofile\tree $tree Tree object
7867 * @param stdClass $user user object
7868 * @param bool $iscurrentuser
7869 * @param stdClass $course Course object
7871 * @return bool
7873 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
7874 if (isguestuser($user)) {
7875 // The guest user cannot post, so it is not possible to view any posts.
7876 // May as well just bail aggressively here.
7877 return false;
7879 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id));
7880 if (!empty($course)) {
7881 $postsurl->param('course', $course->id);
7883 $string = get_string('forumposts', 'mod_forum');
7884 $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl);
7885 $tree->add_node($node);
7887 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions'));
7888 if (!empty($course)) {
7889 $discussionssurl->param('course', $course->id);
7891 $string = get_string('myprofileotherdis', 'mod_forum');
7892 $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null,
7893 $discussionssurl);
7894 $tree->add_node($node);
7896 return true;