2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 defined('MOODLE_INTERNAL') ||
die();
25 /** Include required files */
26 require_once(__DIR__
. '/deprecatedlib.php');
27 require_once($CFG->libdir
.'/filelib.php');
28 require_once($CFG->libdir
.'/eventslib.php');
30 /// CONSTANTS ///////////////////////////////////////////////////////////
32 define('FORUM_MODE_FLATOLDEST', 1);
33 define('FORUM_MODE_FLATNEWEST', -1);
34 define('FORUM_MODE_THREADED', 2);
35 define('FORUM_MODE_NESTED', 3);
37 define('FORUM_CHOOSESUBSCRIBE', 0);
38 define('FORUM_FORCESUBSCRIBE', 1);
39 define('FORUM_INITIALSUBSCRIBE', 2);
40 define('FORUM_DISALLOWSUBSCRIBE',3);
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
45 define('FORUM_TRACKING_OFF', 0);
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
50 define('FORUM_TRACKING_OPTIONAL', 1);
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
56 define('FORUM_TRACKING_FORCED', 2);
58 define('FORUM_MAILED_PENDING', 0);
59 define('FORUM_MAILED_SUCCESS', 1);
60 define('FORUM_MAILED_ERROR', 2);
62 if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
70 define('FORUM_POSTS_ALL_USER_GROUPS', -2);
72 define('FORUM_DISCUSSION_PINNED', 1);
73 define('FORUM_DISCUSSION_UNPINNED', 0);
75 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
78 * Given an object containing all the necessary data,
79 * (defined by the form in mod_form.php) this function
80 * will create a new instance and return the id number
81 * of the new instance.
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
85 * @return int intance id
87 function forum_add_instance($forum, $mform = null) {
90 $forum->timemodified
= time();
92 if (empty($forum->assessed
)) {
96 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
97 $forum->assesstimestart
= 0;
98 $forum->assesstimefinish
= 0;
101 $forum->id
= $DB->insert_record('forum', $forum);
102 $modcontext = context_module
::instance($forum->coursemodule
);
104 if ($forum->type
== 'single') { // Create related discussion.
105 $discussion = new stdClass();
106 $discussion->course
= $forum->course
;
107 $discussion->forum
= $forum->id
;
108 $discussion->name
= $forum->name
;
109 $discussion->assessed
= $forum->assessed
;
110 $discussion->message
= $forum->intro
;
111 $discussion->messageformat
= $forum->introformat
;
112 $discussion->messagetrust
= trusttext_trusted(context_course
::instance($forum->course
));
113 $discussion->mailnow
= false;
114 $discussion->groupid
= -1;
118 $discussion->id
= forum_add_discussion($discussion, null, $message);
120 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
121 // Ugly hack - we need to copy the files somehow.
122 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id
), '*', MUST_EXIST
);
123 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
125 $options = array('subdirs'=>true); // Use the same options as intro field!
126 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
127 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
131 forum_grade_item_update($forum);
133 $completiontimeexpected = !empty($forum->completionexpected
) ?
$forum->completionexpected
: null;
134 \core_completion\api
::update_completion_date_event($forum->coursemodule
, 'forum', $forum->id
, $completiontimeexpected);
140 * Handle changes following the creation of a forum instance.
141 * This function is typically called by the course_module_created observer.
143 * @param object $context the forum context
144 * @param stdClass $forum The forum object
147 function forum_instance_created($context, $forum) {
148 if ($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) {
149 $users = \mod_forum\subscriptions
::get_potential_subscribers($context, 0, 'u.id, u.email');
150 foreach ($users as $user) {
151 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $context);
157 * Given an object containing all the necessary data,
158 * (defined by the form in mod_form.php) this function
159 * will update an existing instance with new data.
162 * @param object $forum forum instance (with magic quotes)
163 * @return bool success
165 function forum_update_instance($forum, $mform) {
166 global $DB, $OUTPUT, $USER;
168 $forum->timemodified
= time();
169 $forum->id
= $forum->instance
;
171 if (empty($forum->assessed
)) {
172 $forum->assessed
= 0;
175 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
176 $forum->assesstimestart
= 0;
177 $forum->assesstimefinish
= 0;
180 $oldforum = $DB->get_record('forum', array('id'=>$forum->id
));
182 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
183 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
184 // 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
185 if (($oldforum->assessed
<>$forum->assessed
) or ($oldforum->scale
<>$forum->scale
)) {
186 forum_update_grades($forum); // recalculate grades for the forum
189 if ($forum->type
== 'single') { // Update related discussion and post.
190 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
), 'timemodified ASC');
191 if (!empty($discussions)) {
192 if (count($discussions) > 1) {
193 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
195 $discussion = array_pop($discussions);
197 // try to recover by creating initial discussion - MDL-16262
198 $discussion = new stdClass();
199 $discussion->course
= $forum->course
;
200 $discussion->forum
= $forum->id
;
201 $discussion->name
= $forum->name
;
202 $discussion->assessed
= $forum->assessed
;
203 $discussion->message
= $forum->intro
;
204 $discussion->messageformat
= $forum->introformat
;
205 $discussion->messagetrust
= true;
206 $discussion->mailnow
= false;
207 $discussion->groupid
= -1;
211 forum_add_discussion($discussion, null, $message);
213 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id
))) {
214 print_error('cannotadd', 'forum');
217 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
))) {
218 print_error('cannotfindfirstpost', 'forum');
221 $cm = get_coursemodule_from_instance('forum', $forum->id
);
222 $modcontext = context_module
::instance($cm->id
, MUST_EXIST
);
224 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
225 $post->subject
= $forum->name
;
226 $post->message
= $forum->intro
;
227 $post->messageformat
= $forum->introformat
;
228 $post->messagetrust
= trusttext_trusted($modcontext);
229 $post->modified
= $forum->timemodified
;
230 $post->userid
= $USER->id
; // MDL-18599, so that current teacher can take ownership of activities.
232 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
233 // Ugly hack - we need to copy the files somehow.
234 $options = array('subdirs'=>true); // Use the same options as intro field!
235 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
238 $DB->update_record('forum_posts', $post);
239 $discussion->name
= $forum->name
;
240 $DB->update_record('forum_discussions', $discussion);
243 $DB->update_record('forum', $forum);
245 $modcontext = context_module
::instance($forum->coursemodule
);
246 if (($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) && ($oldforum->forcesubscribe
<> $forum->forcesubscribe
)) {
247 $users = \mod_forum\subscriptions
::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
248 foreach ($users as $user) {
249 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $modcontext);
253 forum_grade_item_update($forum);
255 $completiontimeexpected = !empty($forum->completionexpected
) ?
$forum->completionexpected
: null;
256 \core_completion\api
::update_completion_date_event($forum->coursemodule
, 'forum', $forum->id
, $completiontimeexpected);
263 * Given an ID of an instance of this module,
264 * this function will permanently delete the instance
265 * and any data that depends on it.
268 * @param int $id forum instance id
269 * @return bool success
271 function forum_delete_instance($id) {
274 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
277 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
)) {
280 if (!$course = $DB->get_record('course', array('id'=>$cm->course
))) {
284 $context = context_module
::instance($cm->id
);
286 // now get rid of all files
287 $fs = get_file_storage();
288 $fs->delete_area_files($context->id
);
292 \core_completion\api
::update_completion_date_event($cm->id
, 'forum', $forum->id
, null);
294 // Delete digest and subscription preferences.
295 $DB->delete_records('forum_digests', array('forum' => $forum->id
));
296 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id
));
297 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id
));
299 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
))) {
300 foreach ($discussions as $discussion) {
301 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
307 forum_tp_delete_read_records(-1, -1, -1, $forum->id
);
309 if (!$DB->delete_records('forum', array('id'=>$forum->id
))) {
313 forum_grade_item_delete($forum);
320 * Indicates API features that the forum supports.
322 * @uses FEATURE_GROUPS
323 * @uses FEATURE_GROUPINGS
324 * @uses FEATURE_MOD_INTRO
325 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
326 * @uses FEATURE_COMPLETION_HAS_RULES
327 * @uses FEATURE_GRADE_HAS_GRADE
328 * @uses FEATURE_GRADE_OUTCOMES
329 * @param string $feature
330 * @return mixed True if yes (some features may use other values)
332 function forum_supports($feature) {
334 case FEATURE_GROUPS
: return true;
335 case FEATURE_GROUPINGS
: return true;
336 case FEATURE_MOD_INTRO
: return true;
337 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
338 case FEATURE_COMPLETION_HAS_RULES
: return true;
339 case FEATURE_GRADE_HAS_GRADE
: return true;
340 case FEATURE_GRADE_OUTCOMES
: return true;
341 case FEATURE_RATE
: return true;
342 case FEATURE_BACKUP_MOODLE2
: return true;
343 case FEATURE_SHOW_DESCRIPTION
: return true;
344 case FEATURE_PLAGIARISM
: return true;
346 default: return null;
352 * Obtains the automatic completion state for this forum based on any conditions
357 * @param object $course Course
358 * @param object $cm Course-module
359 * @param int $userid User ID
360 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
361 * @return bool True if completed, false if not. (If no conditions, then return
362 * value depends on comparison type)
364 function forum_get_completion_state($course,$cm,$userid,$type) {
368 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance
)))) {
369 throw new Exception("Can't find forum {$cm->instance}");
372 $result=$type; // Default return value
374 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id
);
380 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
382 fp.userid=:userid AND fd.forum=:forumid";
384 if ($forum->completiondiscussions
) {
385 $value = $forum->completiondiscussions
<=
386 $DB->count_records('forum_discussions',array('forum'=>$forum->id
,'userid'=>$userid));
387 if ($type == COMPLETION_AND
) {
388 $result = $result && $value;
390 $result = $result ||
$value;
393 if ($forum->completionreplies
) {
394 $value = $forum->completionreplies
<=
395 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
396 if ($type==COMPLETION_AND
) {
397 $result = $result && $value;
399 $result = $result ||
$value;
402 if ($forum->completionposts
) {
403 $value = $forum->completionposts
<= $DB->get_field_sql($postcountsql,$postcountparams);
404 if ($type == COMPLETION_AND
) {
405 $result = $result && $value;
407 $result = $result ||
$value;
415 * Create a message-id string to use in the custom headers of forum notification emails
417 * message-id is used by email clients to identify emails and to nest conversations
419 * @param int $postid The ID of the forum post we are notifying the user about
420 * @param int $usertoid The ID of the user being notified
421 * @return string A unique message-id
423 function forum_get_email_message_id($postid, $usertoid) {
424 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
428 * Removes properties from user record that are not necessary
429 * for sending post notifications.
430 * @param stdClass $user
431 * @return void, $user parameter is modified
433 function forum_cron_minimise_user_record(stdClass
$user) {
435 // We store large amount of users in one huge array,
436 // make sure we do not store info there we do not actually need
437 // in mail generation code or messaging.
439 unset($user->institution
);
440 unset($user->department
);
441 unset($user->address
);
444 unset($user->currentlogin
);
445 unset($user->description
);
446 unset($user->descriptionformat
);
450 * Function to be run periodically according to the scheduled task.
452 * Finds all posts that have yet to be mailed out, and mails them
453 * out to all subscribers as well as other maintance tasks.
455 * NOTE: Since 2.7.2 this function is run by scheduled task rather
456 * than standard cron.
458 * @todo MDL-44734 The function will be split up into seperate tasks.
460 function forum_cron() {
461 global $CFG, $USER, $DB, $PAGE;
465 // The main renderers.
466 $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
467 $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
468 $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
469 $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
470 $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
471 $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
473 // All users that are subscribed to any post that needs sending,
474 // please increase $CFG->extramemorylimit on large sites that
475 // send notifications to a large number of users.
477 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
480 $mailcount = array();
481 $errorcount = array();
484 $discussions = array();
487 $coursemodules = array();
488 $subscribedusers = array();
489 $messageinboundhandlers = array();
491 // Posts older than 2 days will not be mailed. This is to avoid the problem where
492 // cron has not been running for a long time, and then suddenly people are flooded
493 // with mail from the past few weeks or months
495 $endtime = $timenow - $CFG->maxeditingtime
;
496 $starttime = $endtime - 48 * 3600; // Two days earlier
498 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
499 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
501 foreach ($digestsset as $thisrow) {
502 if (!isset($digests[$thisrow->forum
])) {
503 $digests[$thisrow->forum
] = array();
505 $digests[$thisrow->forum
][$thisrow->userid
] = $thisrow->maildigest
;
507 $digestsset->close();
509 // Create the generic messageinboundgenerator.
510 $messageinboundgenerator = new \core\message\inbound\address_manager
();
511 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
513 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
514 // Mark them all now as being mailed. It's unlikely but possible there
515 // might be an error later so that a post is NOT actually mailed out,
516 // but since mail isn't crucial, we can accept this risk. Doing it now
517 // prevents the risk of duplicated mails, which is a worse problem.
519 if (!forum_mark_old_posts_as_mailed($endtime)) {
520 mtrace('Errors occurred while trying to mark some posts as being mailed.');
521 return false; // Don't continue trying to mail them, in case we are in a cron loop
524 // checking post validity, and adding users to loop through later
525 foreach ($posts as $pid => $post) {
527 $discussionid = $post->discussion
;
528 if (!isset($discussions[$discussionid])) {
529 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion
))) {
530 $discussions[$discussionid] = $discussion;
531 \mod_forum\subscriptions
::fill_subscription_cache($discussion->forum
);
532 \mod_forum\subscriptions
::fill_discussion_subscription_cache($discussion->forum
);
535 mtrace('Could not find discussion ' . $discussionid);
540 $forumid = $discussions[$discussionid]->forum
;
541 if (!isset($forums[$forumid])) {
542 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
543 $forums[$forumid] = $forum;
545 mtrace('Could not find forum '.$forumid);
550 $courseid = $forums[$forumid]->course
;
551 if (!isset($courses[$courseid])) {
552 if ($course = $DB->get_record('course', array('id' => $courseid))) {
553 $courses[$courseid] = $course;
555 mtrace('Could not find course '.$courseid);
560 if (!isset($coursemodules[$forumid])) {
561 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
562 $coursemodules[$forumid] = $cm;
564 mtrace('Could not find course module for forum '.$forumid);
570 $modcontext = context_module
::instance($coursemodules[$forumid]->id
);
572 // Save the Inbound Message datakey here to reduce DB queries later.
573 $messageinboundgenerator->set_data($pid);
574 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
576 // Caching subscribed users of each forum.
577 if (!isset($subscribedusers[$forumid])) {
578 if ($subusers = \mod_forum\subscriptions
::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
580 foreach ($subusers as $postuser) {
581 // this user is subscribed to this forum
582 $subscribedusers[$forumid][$postuser->id
] = $postuser->id
;
584 if ($userscount > FORUM_CRON_USER_CACHE
) {
585 // Store minimal user info.
586 $minuser = new stdClass();
587 $minuser->id
= $postuser->id
;
588 $users[$postuser->id
] = $minuser;
590 // Cache full user record.
591 forum_cron_minimise_user_record($postuser);
592 $users[$postuser->id
] = $postuser;
600 $mailcount[$pid] = 0;
601 $errorcount[$pid] = 0;
605 if ($users && $posts) {
607 foreach ($users as $userto) {
608 // Terminate if processing of any account takes longer than 2 minutes.
609 core_php_time_limit
::raise(120);
611 mtrace('Processing user ' . $userto->id
);
613 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
614 if (isset($userto->username
)) {
615 $userto = clone($userto);
617 $userto = $DB->get_record('user', array('id' => $userto->id
));
618 forum_cron_minimise_user_record($userto);
620 $userto->viewfullnames
= array();
621 $userto->canpost
= array();
622 $userto->markposts
= array();
624 // Setup this user so that the capabilities are cached, and environment matches receiving user.
625 cron_setup_user($userto);
628 foreach ($coursemodules as $forumid => $unused) {
629 $coursemodules[$forumid]->cache
= new stdClass();
630 $coursemodules[$forumid]->cache
->caps
= array();
631 unset($coursemodules[$forumid]->uservisible
);
634 foreach ($posts as $pid => $post) {
635 $discussion = $discussions[$post->discussion
];
636 $forum = $forums[$discussion->forum
];
637 $course = $courses[$forum->course
];
638 $cm =& $coursemodules[$forum->id
];
640 // Do some checks to see if we can bail out now.
642 // Only active enrolled users are in the list of subscribers.
643 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
644 if (!isset($subscribedusers[$forum->id
][$userto->id
])) {
645 // The user does not subscribe to this forum.
649 if (!\mod_forum\subscriptions
::is_subscribed($userto->id
, $forum, $post->discussion
, $coursemodules[$forum->id
])) {
650 // The user does not subscribe to this forum, or to this specific discussion.
654 if ($subscriptiontime = \mod_forum\subscriptions
::fetch_discussion_subscription($forum->id
, $userto->id
)) {
655 // Skip posts if the user subscribed to the discussion after it was created.
656 if (isset($subscriptiontime[$post->discussion
]) && ($subscriptiontime[$post->discussion
] > $post->created
)) {
661 // Don't send email if the forum is Q&A and the user has not posted.
662 // Initial topics are still mailed.
663 if ($forum->type
== 'qanda' && !forum_get_user_posted_time($discussion->id
, $userto->id
) && $pid != $discussion->firstpost
) {
664 mtrace('Did not email ' . $userto->id
.' because user has not posted in discussion');
668 // Get info about the sending user.
669 if (array_key_exists($post->userid
, $users)) {
670 // We might know the user already.
671 $userfrom = $users[$post->userid
];
672 if (!isset($userfrom->idnumber
)) {
673 // Minimalised user info, fetch full record.
674 $userfrom = $DB->get_record('user', array('id' => $userfrom->id
));
675 forum_cron_minimise_user_record($userfrom);
678 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid
))) {
679 forum_cron_minimise_user_record($userfrom);
680 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
681 if ($userscount <= FORUM_CRON_USER_CACHE
) {
683 $users[$userfrom->id
] = $userfrom;
686 mtrace('Could not find user ' . $post->userid
. ', author of post ' . $post->id
. '. Unable to send message.');
690 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
692 // Setup global $COURSE properly - needed for roles and languages.
693 cron_setup_user($userto, $course);
696 if (!isset($userto->viewfullnames
[$forum->id
])) {
697 $modcontext = context_module
::instance($cm->id
);
698 $userto->viewfullnames
[$forum->id
] = has_capability('moodle/site:viewfullnames', $modcontext);
700 if (!isset($userto->canpost
[$discussion->id
])) {
701 $modcontext = context_module
::instance($cm->id
);
702 $userto->canpost
[$discussion->id
] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
704 if (!isset($userfrom->groups
[$forum->id
])) {
705 if (!isset($userfrom->groups
)) {
706 $userfrom->groups
= array();
707 if (isset($users[$userfrom->id
])) {
708 $users[$userfrom->id
]->groups
= array();
711 $userfrom->groups
[$forum->id
] = groups_get_all_groups($course->id
, $userfrom->id
, $cm->groupingid
);
712 if (isset($users[$userfrom->id
])) {
713 $users[$userfrom->id
]->groups
[$forum->id
] = $userfrom->groups
[$forum->id
];
717 // Make sure groups allow this user to see this email.
718 if ($discussion->groupid
> 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
719 // Groups are being used.
720 if (!groups_group_exists($discussion->groupid
)) {
721 // Can't find group - be safe and don't this message.
725 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
726 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
731 // Make sure we're allowed to see the post.
732 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
733 mtrace('User ' . $userto->id
.' can not see ' . $post->id
. '. Not sending message.');
737 // OK so we need to send the email.
739 // Does the user want this post in a digest? If so postpone it for now.
740 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id
);
742 if ($maildigest > 0) {
743 // This user wants the mails to be in digest form.
744 $queue = new stdClass();
745 $queue->userid
= $userto->id
;
746 $queue->discussionid
= $discussion->id
;
747 $queue->postid
= $post->id
;
748 $queue->timemodified
= $post->created
;
749 $DB->insert_record('forum_queue', $queue);
753 // Prepare to actually send the post now, and build up the content.
755 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name
)));
757 $userfrom->customheaders
= array (
758 // Headers to make emails easier to track.
759 'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id
),
760 'List-Help: ' . $CFG->wwwroot
. '/mod/forum/view.php?f=' . $forum->id
,
761 'Message-ID: ' . forum_get_email_message_id($post->id
, $userto->id
),
762 'X-Course-Id: ' . $course->id
,
763 'X-Course-Name: ' . format_string($course->fullname
, true),
765 // Headers to help prevent auto-responders.
767 'X-Auto-Response-Suppress: All',
768 'Auto-Submitted: auto-generated',
771 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
773 // Generate a reply-to address from using the Inbound Message handler.
774 $replyaddress = null;
775 if ($userto->canpost
[$discussion->id
] && array_key_exists($post->id
, $messageinboundhandlers)) {
776 $messageinboundgenerator->set_data($post->id
, $messageinboundhandlers[$post->id
]);
777 $replyaddress = $messageinboundgenerator->generate($userto->id
);
780 if (!isset($userto->canpost
[$discussion->id
])) {
781 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
783 $canreply = $userto->canpost
[$discussion->id
];
786 $data = new \mod_forum\output\forum_post_email
(
797 $userfrom->customheaders
[] = sprintf('List-Unsubscribe: <%s>',
798 $data->get_unsubscribediscussionlink());
800 if (!isset($userto->viewfullnames
[$forum->id
])) {
801 $data->viewfullnames
= has_capability('moodle/site:viewfullnames', $modcontext, $userto->id
);
803 $data->viewfullnames
= $userto->viewfullnames
[$forum->id
];
806 // Not all of these variables are used in the default language
807 // string but are made available to support custom subjects.
809 $a->subject
= $data->get_subject();
810 $a->forumname
= $cleanforumname;
811 $a->sitefullname
= format_string($site->fullname
);
812 $a->siteshortname
= format_string($site->shortname
);
813 $a->courseidnumber
= $data->get_courseidnumber();
814 $a->coursefullname
= $data->get_coursefullname();
815 $a->courseshortname
= $data->get_coursename();
816 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
818 $rootid = forum_get_email_message_id($discussion->firstpost
, $userto->id
);
821 // This post is a reply, so add reply header (RFC 2822).
822 $parentid = forum_get_email_message_id($post->parent
, $userto->id
);
823 $userfrom->customheaders
[] = "In-Reply-To: $parentid";
825 // If the post is deeply nested we also reference the parent message id and
826 // the root message id (if different) to aid threading when parts of the email
827 // conversation have been deleted (RFC1036).
828 if ($post->parent
!= $discussion->firstpost
) {
829 $userfrom->customheaders
[] = "References: $rootid $parentid";
831 $userfrom->customheaders
[] = "References: $parentid";
835 // MS Outlook / Office uses poorly documented and non standard headers, including
836 // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
837 $a->subject
= $discussion->name
;
838 $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
839 $userfrom->customheaders
[] = "Thread-Topic: $threadtopic";
840 $userfrom->customheaders
[] = "Thread-Index: " . substr($rootid, 1, 28);
842 // Send the post now!
843 mtrace('Sending ', '');
845 $eventdata = new \core\message\
message();
846 $eventdata->courseid
= $course->id
;
847 $eventdata->component
= 'mod_forum';
848 $eventdata->name
= 'posts';
849 $eventdata->userfrom
= $userfrom;
850 $eventdata->userto
= $userto;
851 $eventdata->subject
= $postsubject;
852 $eventdata->fullmessage
= $textout->render($data);
853 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
854 $eventdata->fullmessagehtml
= $htmlout->render($data);
855 $eventdata->notification
= 1;
856 $eventdata->replyto
= $replyaddress;
857 if (!empty($replyaddress)) {
858 // Add extra text to email messages if they can reply back.
859 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
860 $htmlfooter = html_writer
::tag('p', get_string('replytopostbyemail', 'mod_forum'));
861 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
862 'fullmessagehtml' => array('footer' => $htmlfooter));
863 $eventdata->set_additional_content('email', $additionalcontent);
866 $smallmessagestrings = new stdClass();
867 $smallmessagestrings->user
= fullname($userfrom);
868 $smallmessagestrings->forumname
= "$shortname: " . format_string($forum->name
, true) . ": " . $discussion->name
;
869 $smallmessagestrings->message
= $post->message
;
871 // Make sure strings are in message recipients language.
872 $eventdata->smallmessage
= get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang
);
874 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id
), 'p' . $post->id
);
875 $eventdata->contexturl
= $contexturl->out();
876 $eventdata->contexturlname
= $discussion->name
;
878 $mailresult = message_send($eventdata);
880 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
881 " ($userto->email) .. not trying again.");
882 $errorcount[$post->id
]++
;
884 $mailcount[$post->id
]++
;
886 // Mark post as read if forum_usermarksread is set off.
887 if (!$CFG->forum_usermarksread
) {
888 $userto->markposts
[$post->id
] = $post->id
;
892 mtrace('post ' . $post->id
. ': ' . $post->subject
);
895 // Mark processed posts as read.
896 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id
) == 1) {
897 forum_tp_mark_posts_read($userto, $userto->markposts
);
905 foreach ($posts as $post) {
906 mtrace($mailcount[$post->id
]." users were sent post $post->id, '$post->subject'");
907 if ($errorcount[$post->id
]) {
908 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR
, array('id' => $post->id
));
913 // release some memory
914 unset($subscribedusers);
920 $sitetimezone = core_date
::get_server_timezone();
922 // Now see if there are any digest mails waiting to be sent, and if we should send them
924 mtrace('Starting digest processing...');
926 core_php_time_limit
::raise(300); // terminate if not able to fetch all digests in 5 minutes
928 if (!isset($CFG->digestmailtimelast
)) { // To catch the first time
929 set_config('digestmailtimelast', 0);
933 $digesttime = usergetmidnight($timenow, $sitetimezone) +
($CFG->digestmailtime
* 3600);
935 // Delete any really old ones (normally there shouldn't be any)
936 $weekago = $timenow - (7 * 24 * 3600);
937 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
938 mtrace ('Cleaned old digest records');
940 if ($CFG->digestmailtimelast
< $digesttime and $timenow > $digesttime) {
942 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
944 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
946 if ($digestposts_rs->valid()) {
948 // We have work to do
951 //caches - reuse the those filled before too
952 $discussionposts = array();
953 $userdiscussions = array();
955 foreach ($digestposts_rs as $digestpost) {
956 if (!isset($posts[$digestpost->postid
])) {
957 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid
))) {
958 $posts[$digestpost->postid
] = $post;
963 $discussionid = $digestpost->discussionid
;
964 if (!isset($discussions[$discussionid])) {
965 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
966 $discussions[$discussionid] = $discussion;
971 $forumid = $discussions[$discussionid]->forum
;
972 if (!isset($forums[$forumid])) {
973 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
974 $forums[$forumid] = $forum;
980 $courseid = $forums[$forumid]->course
;
981 if (!isset($courses[$courseid])) {
982 if ($course = $DB->get_record('course', array('id' => $courseid))) {
983 $courses[$courseid] = $course;
989 if (!isset($coursemodules[$forumid])) {
990 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
991 $coursemodules[$forumid] = $cm;
996 $userdiscussions[$digestpost->userid
][$digestpost->discussionid
] = $digestpost->discussionid
;
997 $discussionposts[$digestpost->discussionid
][$digestpost->postid
] = $digestpost->postid
;
999 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
1001 // Data collected, start sending out emails to each user
1002 foreach ($userdiscussions as $userid => $thesediscussions) {
1004 core_php_time_limit
::raise(120); // terminate if processing of any account takes longer than 2 minutes
1008 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
1010 // First of all delete all the queue entries for this user
1011 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
1013 // Init user caches - we keep the cache for one cycle only,
1014 // otherwise it would unnecessarily consume memory.
1015 if (array_key_exists($userid, $users) and isset($users[$userid]->username
)) {
1016 $userto = clone($users[$userid]);
1018 $userto = $DB->get_record('user', array('id' => $userid));
1019 forum_cron_minimise_user_record($userto);
1021 $userto->viewfullnames
= array();
1022 $userto->canpost
= array();
1023 $userto->markposts
= array();
1025 // Override the language and timezone of the "current" user, so that
1026 // mail is customised for the receiver.
1027 cron_setup_user($userto);
1029 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname
, true));
1031 $headerdata = new stdClass();
1032 $headerdata->sitename
= format_string($site->fullname
, true);
1033 $headerdata->userprefs
= $CFG->wwwroot
.'/user/forum.php?id='.$userid.'&course='.$site->id
;
1035 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
1036 $headerdata->userprefs
= '<a target="_blank" href="'.$headerdata->userprefs
.'">'.get_string('digestmailprefs', 'forum').'</a>';
1038 $posthtml = '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p>'
1039 . '<br /><hr size="1" noshade="noshade" />';
1041 foreach ($thesediscussions as $discussionid) {
1043 core_php_time_limit
::raise(120); // to be reset for each post
1045 $discussion = $discussions[$discussionid];
1046 $forum = $forums[$discussion->forum
];
1047 $course = $courses[$forum->course
];
1048 $cm = $coursemodules[$forum->id
];
1051 cron_setup_user($userto, $course);
1054 if (!isset($userto->viewfullnames
[$forum->id
])) {
1055 $modcontext = context_module
::instance($cm->id
);
1056 $userto->viewfullnames
[$forum->id
] = has_capability('moodle/site:viewfullnames', $modcontext);
1058 if (!isset($userto->canpost
[$discussion->id
])) {
1059 $modcontext = context_module
::instance($cm->id
);
1060 $userto->canpost
[$discussion->id
] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1063 $strforums = get_string('forums', 'forum');
1064 $canunsubscribe = ! \mod_forum\subscriptions
::is_forcesubscribed($forum);
1065 $canreply = $userto->canpost
[$discussion->id
];
1066 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
1068 $posttext .= "\n \n";
1069 $posttext .= '=====================================================================';
1070 $posttext .= "\n \n";
1071 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name
,true);
1072 if ($discussion->name
!= $forum->name
) {
1073 $posttext .= " -> ".format_string($discussion->name
,true);
1076 $posttext .= $CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
;
1079 $posthtml .= "<p><font face=\"sans-serif\">".
1080 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1081 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1082 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name
,true)."</a>";
1083 if ($discussion->name
== $forum->name
) {
1084 $posthtml .= "</font></p>";
1086 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name
,true)."</a></font></p>";
1090 $postsarray = $discussionposts[$discussionid];
1094 foreach ($postsarray as $postid) {
1095 $post = $posts[$postid];
1097 if (array_key_exists($post->userid
, $users)) { // we might know him/her already
1098 $userfrom = $users[$post->userid
];
1099 if (!isset($userfrom->idnumber
)) {
1100 $userfrom = $DB->get_record('user', array('id' => $userfrom->id
));
1101 forum_cron_minimise_user_record($userfrom);
1104 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid
))) {
1105 forum_cron_minimise_user_record($userfrom);
1106 if ($userscount <= FORUM_CRON_USER_CACHE
) {
1108 $users[$userfrom->id
] = $userfrom;
1112 mtrace('Could not find user '.$post->userid
);
1116 if (!isset($userfrom->groups
[$forum->id
])) {
1117 if (!isset($userfrom->groups
)) {
1118 $userfrom->groups
= array();
1119 if (isset($users[$userfrom->id
])) {
1120 $users[$userfrom->id
]->groups
= array();
1123 $userfrom->groups
[$forum->id
] = groups_get_all_groups($course->id
, $userfrom->id
, $cm->groupingid
);
1124 if (isset($users[$userfrom->id
])) {
1125 $users[$userfrom->id
]->groups
[$forum->id
] = $userfrom->groups
[$forum->id
];
1129 // Headers to help prevent auto-responders.
1130 $userfrom->customheaders
= array(
1132 'X-Auto-Response-Suppress: All',
1133 'Auto-Submitted: auto-generated',
1136 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id
);
1137 if (!isset($userto->canpost
[$discussion->id
])) {
1138 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1140 $canreply = $userto->canpost
[$discussion->id
];
1143 $data = new \mod_forum\output\forum_post_email
(
1154 if (!isset($userto->viewfullnames
[$forum->id
])) {
1155 $data->viewfullnames
= has_capability('moodle/site:viewfullnames', $modcontext, $userto->id
);
1157 $data->viewfullnames
= $userto->viewfullnames
[$forum->id
];
1160 if ($maildigest == 2) {
1161 // Subjects and link only.
1162 $posttext .= $textdigestbasicout->render($data);
1163 $posthtml .= $htmldigestbasicout->render($data);
1165 // The full treatment.
1166 $posttext .= $textdigestfullout->render($data);
1167 $posthtml .= $htmldigestfullout->render($data);
1169 // Create an array of postid's for this user to mark as read.
1170 if (!$CFG->forum_usermarksread
) {
1171 $userto->markposts
[$post->id
] = $post->id
;
1176 $footerlinks = array();
1177 if ($canunsubscribe) {
1178 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1180 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1182 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1183 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1184 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1187 if (empty($userto->mailformat
) ||
$userto->mailformat
!= 1) {
1188 // This user DOESN'T want to receive HTML
1192 $eventdata = new \core\message\
message();
1193 $eventdata->courseid
= SITEID
;
1194 $eventdata->component
= 'mod_forum';
1195 $eventdata->name
= 'digests';
1196 $eventdata->userfrom
= core_user
::get_noreply_user();
1197 $eventdata->userto
= $userto;
1198 $eventdata->subject
= $postsubject;
1199 $eventdata->fullmessage
= $posttext;
1200 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1201 $eventdata->fullmessagehtml
= $posthtml;
1202 $eventdata->notification
= 1;
1203 $eventdata->smallmessage
= get_string('smallmessagedigest', 'forum', $sentcount);
1204 $mailresult = message_send($eventdata);
1207 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1208 "($userto->email)... not trying again.");
1213 // Mark post as read if forum_usermarksread is set off
1214 if (get_user_preferences('forum_markasreadonnotification', 1, $userto->id
) == 1) {
1215 forum_tp_mark_posts_read($userto, $userto->markposts
);
1220 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1221 set_config('digestmailtimelast', $timenow);
1226 if (!empty($usermailcount)) {
1227 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1230 if (!empty($CFG->forum_lastreadclean
)) {
1232 if ($CFG->forum_lastreadclean +
(24*3600) < $timenow) {
1233 set_config('forum_lastreadclean', $timenow);
1234 mtrace('Removing old forum read tracking info...');
1235 forum_tp_clean_read_records();
1238 set_config('forum_lastreadclean', time());
1246 * @param object $course
1247 * @param object $user
1248 * @param object $mod TODO this is not used in this function, refactor
1249 * @param object $forum
1250 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1252 function forum_user_outline($course, $user, $mod, $forum) {
1254 require_once("$CFG->libdir/gradelib.php");
1255 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
1256 if (empty($grades->items
[0]->grades
)) {
1259 $grade = reset($grades->items
[0]->grades
);
1262 $count = forum_count_user_posts($forum->id
, $user->id
);
1264 if ($count && $count->postcount
> 0) {
1265 $result = new stdClass();
1266 $result->info
= get_string("numposts", "forum", $count->postcount
);
1267 $result->time
= $count->lastpost
;
1269 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
1272 } else if ($grade) {
1273 $result = new stdClass();
1274 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
1276 //datesubmitted == time created. dategraded == time modified or time overridden
1277 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1278 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1279 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
1280 $result->time
= $grade->dategraded
;
1282 $result->time
= $grade->datesubmitted
;
1294 * @param object $coure
1295 * @param object $user
1296 * @param object $mod
1297 * @param object $forum
1299 function forum_user_complete($course, $user, $mod, $forum) {
1300 global $CFG,$USER, $OUTPUT;
1301 require_once("$CFG->libdir/gradelib.php");
1303 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
1304 if (!empty($grades->items
[0]->grades
)) {
1305 $grade = reset($grades->items
[0]->grades
);
1306 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
1307 if ($grade->str_feedback
) {
1308 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
1312 if ($posts = forum_get_user_posts($forum->id
, $user->id
)) {
1314 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
)) {
1315 print_error('invalidcoursemodule');
1317 $discussions = forum_get_user_involved_discussions($forum->id
, $user->id
);
1319 foreach ($posts as $post) {
1320 if (!isset($discussions[$post->discussion
])) {
1323 $discussion = $discussions[$post->discussion
];
1325 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1328 echo "<p>".get_string("noposts", "forum")."</p>";
1333 * Filters the forum discussions according to groups membership and config.
1335 * @deprecated since 3.3
1336 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1337 * @since Moodle 2.8, 2.7.1, 2.6.4
1338 * @param array $discussions Discussions with new posts array
1339 * @return array Forums with the number of new posts
1341 function forum_filter_user_groups_discussions($discussions) {
1343 debugging('The function forum_filter_user_groups_discussions() is now deprecated.', DEBUG_DEVELOPER
);
1345 // Group the remaining discussions posts by their forumid.
1346 $filteredforums = array();
1348 // Discard not visible groups.
1349 foreach ($discussions as $discussion) {
1351 // Course data is already cached.
1352 $instances = get_fast_modinfo($discussion->course
)->get_instances();
1353 $forum = $instances['forum'][$discussion->forum
];
1355 // Continue if the user should not see this discussion.
1356 if (!forum_is_user_group_discussion($forum, $discussion->groupid
)) {
1360 // Grouping results by forum.
1361 if (empty($filteredforums[$forum->instance
])) {
1362 $filteredforums[$forum->instance
] = new stdClass();
1363 $filteredforums[$forum->instance
]->id
= $forum->id
;
1364 $filteredforums[$forum->instance
]->count
= 0;
1366 $filteredforums[$forum->instance
]->count +
= $discussion->count
;
1370 return $filteredforums;
1374 * Returns whether the discussion group is visible by the current user or not.
1376 * @since Moodle 2.8, 2.7.1, 2.6.4
1377 * @param cm_info $cm The discussion course module
1378 * @param int $discussiongroupid The discussion groupid
1381 function forum_is_user_group_discussion(cm_info
$cm, $discussiongroupid) {
1383 if ($discussiongroupid == -1 ||
$cm->effectivegroupmode
!= SEPARATEGROUPS
) {
1387 if (isguestuser()) {
1391 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
)) ||
1392 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid
))) {
1400 * @deprecated since 3.3
1401 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
1405 * @param array $courses
1406 * @param array $htmlarray
1408 function forum_print_overview($courses,&$htmlarray) {
1409 global $USER, $CFG, $DB, $SESSION;
1411 debugging('The function forum_print_overview() is now deprecated.', DEBUG_DEVELOPER
);
1413 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1417 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1421 // Courses to search for new posts
1422 $coursessqls = array();
1424 foreach ($courses as $course) {
1426 // If the user has never entered into the course all posts are pending
1427 if ($course->lastaccess
== 0) {
1428 $coursessqls[] = '(d.course = ?)';
1429 $params[] = $course->id
;
1431 // Only posts created after the course last access
1433 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1434 $params[] = $course->id
;
1435 $params[] = $course->lastaccess
;
1438 $params[] = $USER->id
;
1439 $coursessql = implode(' OR ', $coursessqls);
1441 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1442 .'FROM {forum_discussions} d '
1443 .'JOIN {forum_posts} p ON p.discussion = d.id '
1444 ."WHERE ($coursessql) "
1445 .'AND p.deleted <> 1 '
1446 .'AND p.userid != ? '
1447 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
1448 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1449 .'ORDER BY d.course, d.forum';
1454 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1455 $discussions = array();
1458 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1460 // also get all forum tracking stuff ONCE.
1461 $trackingforums = array();
1462 foreach ($forums as $forum) {
1463 if (forum_tp_can_track_forums($forum)) {
1464 $trackingforums[$forum->id
] = $forum;
1468 if (count($trackingforums) > 0) {
1469 $cutoffdate = isset($CFG->forum_oldpostdays
) ?
(time() - ($CFG->forum_oldpostdays
*24*60*60)) : 0;
1470 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1471 ' FROM {forum_posts} p '.
1472 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1473 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE p.deleted <> 1 AND (';
1474 $params = array($USER->id
);
1476 foreach ($trackingforums as $track) {
1477 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1478 $params[] = $track->id
;
1479 if (isset($SESSION->currentgroup
[$track->course
])) {
1480 $groupid = $SESSION->currentgroup
[$track->course
];
1482 // get first groupid
1483 $groupids = groups_get_all_groups($track->course
, $USER->id
);
1486 $groupid = key($groupids);
1487 $SESSION->currentgroup
[$track->course
] = $groupid;
1493 $params[] = $groupid;
1495 $sql = substr($sql,0,-3); // take off the last OR
1496 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1497 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1498 $sql .= 'GROUP BY d.forum,d.course';
1499 $params[] = $cutoffdate;
1503 if (!$unread = $DB->get_records_sql($sql, $params)) {
1510 if (empty($unread) and empty($forumsnewposts)) {
1514 $strforum = get_string('modulename','forum');
1516 foreach ($forums as $forum) {
1520 $showunread = false;
1521 // either we have something from logs, or trackposts, or nothing.
1522 if (array_key_exists($forum->id
, $forumsnewposts) && !empty($forumsnewposts[$forum->id
])) {
1523 $count = $forumsnewposts[$forum->id
]->count
;
1525 if (array_key_exists($forum->id
,$unread)) {
1526 $thisunread = $unread[$forum->id
]->count
;
1529 if ($count > 0 ||
$thisunread > 0) {
1530 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot
.'/mod/forum/view.php?f='.$forum->id
.'">'.
1531 $forum->name
.'</a></div>';
1532 $str .= '<div class="info"><span class="postsincelogin">';
1533 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1534 if (!empty($showunread)) {
1535 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1537 $str .= '</div></div>';
1540 if (!array_key_exists($forum->course
,$htmlarray)) {
1541 $htmlarray[$forum->course
] = array();
1543 if (!array_key_exists('forum',$htmlarray[$forum->course
])) {
1544 $htmlarray[$forum->course
]['forum'] = ''; // initialize, avoid warnings
1546 $htmlarray[$forum->course
]['forum'] .= $str;
1552 * Given a course and a date, prints a summary of all the new
1553 * messages posted in the course since that date
1558 * @uses CONTEXT_MODULE
1559 * @uses VISIBLEGROUPS
1560 * @param object $course
1561 * @param bool $viewfullnames capability
1562 * @param int $timestart
1563 * @return bool success
1565 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1566 global $CFG, $USER, $DB, $OUTPUT;
1568 // do not use log table if possible, it may be huge and is expensive to join with other tables
1570 $allnamefields = user_picture
::fields('u', null, 'duserid');
1571 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1572 d.timestart, d.timeend, $allnamefields
1573 FROM {forum_posts} p
1574 JOIN {forum_discussions} d ON d.id = p.discussion
1575 JOIN {forum} f ON f.id = d.forum
1576 JOIN {user} u ON u.id = p.userid
1577 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
1578 ORDER BY p.id ASC", array($timestart, $course->id
))) { // order by initial posting date
1582 $modinfo = get_fast_modinfo($course);
1584 $groupmodes = array();
1587 $strftimerecent = get_string('strftimerecent');
1589 $printposts = array();
1590 foreach ($posts as $post) {
1591 if (!isset($modinfo->instances
['forum'][$post->forum
])) {
1595 $cm = $modinfo->instances
['forum'][$post->forum
];
1596 if (!$cm->uservisible
) {
1599 $context = context_module
::instance($cm->id
);
1601 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1605 if (!empty($CFG->forum_enabletimedposts
) and $USER->id
!= $post->duserid
1606 and (($post->timestart
> 0 and $post->timestart
> time()) or ($post->timeend
> 0 and $post->timeend
< time()))) {
1607 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1612 // Check that the user can see the discussion.
1613 if (forum_is_user_group_discussion($cm, $post->groupid
)) {
1614 $printposts[] = $post;
1624 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1625 $list = html_writer
::start_tag('ul', ['class' => 'unlist']);
1627 foreach ($printposts as $post) {
1628 $subjectclass = empty($post->parent
) ?
' bold' : '';
1629 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype
]);
1631 $list .= html_writer
::start_tag('li');
1632 $list .= html_writer
::start_div('head');
1633 $list .= html_writer
::div(userdate($post->modified
, $strftimerecent), 'date');
1634 if (!$authorhidden) {
1635 $list .= html_writer
::div(fullname($post, $viewfullnames), 'name');
1637 $list .= html_writer
::end_div(); // Head.
1639 $list .= html_writer
::start_div('info' . $subjectclass);
1640 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion
]);
1641 if (!empty($post->parent
)) {
1642 $discussionurl->param('parent', $post->parent
);
1643 $discussionurl->set_anchor('p'. $post->id
);
1645 $post->subject
= break_up_long_words(format_string($post->subject
, true));
1646 $list .= html_writer
::link($discussionurl, $post->subject
);
1647 $list .= html_writer
::end_div(); // Info.
1648 $list .= html_writer
::end_tag('li');
1651 $list .= html_writer
::end_tag('ul');
1658 * Return grade for given user or all users.
1662 * @param object $forum
1663 * @param int $userid optional user id, 0 means all users
1664 * @return array array of grades, false if none
1666 function forum_get_user_grades($forum, $userid = 0) {
1669 require_once($CFG->dirroot
.'/rating/lib.php');
1671 $ratingoptions = new stdClass
;
1672 $ratingoptions->component
= 'mod_forum';
1673 $ratingoptions->ratingarea
= 'post';
1675 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1676 $ratingoptions->modulename
= 'forum';
1677 $ratingoptions->moduleid
= $forum->id
;
1678 $ratingoptions->userid
= $userid;
1679 $ratingoptions->aggregationmethod
= $forum->assessed
;
1680 $ratingoptions->scaleid
= $forum->scale
;
1681 $ratingoptions->itemtable
= 'forum_posts';
1682 $ratingoptions->itemtableusercolumn
= 'userid';
1684 $rm = new rating_manager();
1685 return $rm->get_user_grades($ratingoptions);
1689 * Update activity grades
1692 * @param object $forum
1693 * @param int $userid specific user only, 0 means all
1694 * @param boolean $nullifnone return null if grade does not exist
1697 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1699 require_once($CFG->libdir
.'/gradelib.php');
1701 if (!$forum->assessed
) {
1702 forum_grade_item_update($forum);
1704 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1705 forum_grade_item_update($forum, $grades);
1707 } else if ($userid and $nullifnone) {
1708 $grade = new stdClass();
1709 $grade->userid
= $userid;
1710 $grade->rawgrade
= NULL;
1711 forum_grade_item_update($forum, $grade);
1714 forum_grade_item_update($forum);
1719 * Create/update grade item for given forum
1722 * @uses GRADE_TYPE_NONE
1723 * @uses GRADE_TYPE_VALUE
1724 * @uses GRADE_TYPE_SCALE
1725 * @param stdClass $forum Forum object with extra cmidnumber
1726 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1727 * @return int 0 if ok
1729 function forum_grade_item_update($forum, $grades=NULL) {
1731 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1732 require_once($CFG->libdir
.'/gradelib.php');
1735 $params = array('itemname'=>$forum->name
, 'idnumber'=>$forum->cmidnumber
);
1737 if (!$forum->assessed
or $forum->scale
== 0) {
1738 $params['gradetype'] = GRADE_TYPE_NONE
;
1740 } else if ($forum->scale
> 0) {
1741 $params['gradetype'] = GRADE_TYPE_VALUE
;
1742 $params['grademax'] = $forum->scale
;
1743 $params['grademin'] = 0;
1745 } else if ($forum->scale
< 0) {
1746 $params['gradetype'] = GRADE_TYPE_SCALE
;
1747 $params['scaleid'] = -$forum->scale
;
1750 if ($grades === 'reset') {
1751 $params['reset'] = true;
1755 return grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, $grades, $params);
1759 * Delete grade item for given forum
1762 * @param stdClass $forum Forum object
1763 * @return grade_item
1765 function forum_grade_item_delete($forum) {
1767 require_once($CFG->libdir
.'/gradelib.php');
1769 return grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, NULL, array('deleted'=>1));
1774 * This function returns if a scale is being used by one forum
1777 * @param int $forumid
1778 * @param int $scaleid negative number
1781 function forum_scale_used ($forumid,$scaleid) {
1785 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1787 if (!empty($rec) && !empty($scaleid)) {
1795 * Checks if scale is being used by any instance of forum
1797 * This is used to find out if scale used anywhere
1800 * @param $scaleid int
1801 * @return boolean True if the scale is used by any forum
1803 function forum_scale_used_anywhere($scaleid) {
1805 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1812 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1815 * Gets a post with all info ready for forum_print_post
1816 * Most of these joins are just to get the forum id
1820 * @param int $postid
1821 * @return mixed array of posts or false
1823 function forum_get_post_full($postid) {
1826 $allnames = get_all_user_name_fields(true, 'u');
1827 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1828 FROM {forum_posts} p
1829 JOIN {forum_discussions} d ON p.discussion = d.id
1830 LEFT JOIN {user} u ON p.userid = u.id
1831 WHERE p.id = ?", array($postid));
1835 * Gets all posts in discussion including top parent.
1840 * @param int $discussionid
1841 * @param string $sort
1842 * @param bool $tracking does user track the forum?
1843 * @return array of posts
1845 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1846 global $CFG, $DB, $USER;
1853 $tr_sel = ", fr.id AS postread";
1854 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1855 $params[] = $USER->id
;
1858 $allnames = get_all_user_name_fields(true, 'u');
1859 $params[] = $discussionid;
1860 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1861 FROM {forum_posts} p
1862 LEFT JOIN {user} u ON p.userid = u.id
1864 WHERE p.discussion = ?
1865 ORDER BY $sort", $params)) {
1869 foreach ($posts as $pid=>$p) {
1871 if (forum_tp_is_post_old($p)) {
1872 $posts[$pid]->postread
= true;
1878 if (!isset($posts[$p->parent
])) {
1879 continue; // parent does not exist??
1881 if (!isset($posts[$p->parent
]->children
)) {
1882 $posts[$p->parent
]->children
= array();
1884 $posts[$p->parent
]->children
[$pid] =& $posts[$pid];
1887 // Start with the last child of the first post.
1888 $post = &$posts[reset($posts)->id
];
1891 while (!$lastpost) {
1892 if (!isset($post->children
)) {
1893 $post->lastpost
= true;
1896 // Go to the last child of this post.
1897 $post = &$posts[end($post->children
)->id
];
1905 * An array of forum objects that the user is allowed to read/search through.
1910 * @param int $userid
1911 * @param int $courseid if 0, we look for forums throughout the whole site.
1912 * @return array of forum objects, or false if no matches
1913 * Forum objects have the following attributes:
1914 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1915 * viewhiddentimedposts
1917 function forum_get_readable_forums($userid, $courseid=0) {
1919 global $CFG, $DB, $USER;
1920 require_once($CFG->dirroot
.'/course/lib.php');
1922 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1923 print_error('notinstalled', 'forum');
1927 $courses = $DB->get_records('course', array('id' => $courseid));
1929 // If no course is specified, then the user can see SITE + his courses.
1930 $courses1 = $DB->get_records('course', array('id' => SITEID
));
1931 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1932 $courses = array_merge($courses1, $courses2);
1938 $readableforums = array();
1940 foreach ($courses as $course) {
1942 $modinfo = get_fast_modinfo($course);
1944 if (empty($modinfo->instances
['forum'])) {
1949 $courseforums = $DB->get_records('forum', array('course' => $course->id
));
1951 foreach ($modinfo->instances
['forum'] as $forumid => $cm) {
1952 if (!$cm->uservisible
or !isset($courseforums[$forumid])) {
1955 $context = context_module
::instance($cm->id
);
1956 $forum = $courseforums[$forumid];
1957 $forum->context
= $context;
1960 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1965 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
1967 $forum->onlygroups
= $modinfo->get_groups($cm->groupingid
);
1968 $forum->onlygroups
[] = -1;
1971 /// hidden timed discussions
1972 $forum->viewhiddentimedposts
= true;
1973 if (!empty($CFG->forum_enabletimedposts
)) {
1974 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1975 $forum->viewhiddentimedposts
= false;
1980 if ($forum->type
== 'qanda'
1981 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
1983 // We need to check whether the user has posted in the qanda forum.
1984 $forum->onlydiscussions
= array(); // Holds discussion ids for the discussions
1985 // the user is allowed to see in this forum.
1986 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $USER->id
)) {
1987 foreach ($discussionspostedin as $d) {
1988 $forum->onlydiscussions
[] = $d->id
;
1993 $readableforums[$forum->id
] = $forum;
1998 } // End foreach $courses
2000 return $readableforums;
2004 * Returns a list of posts found using an array of search terms.
2009 * @param array $searchterms array of search terms, e.g. word +word -word
2010 * @param int $courseid if 0, we search through the whole site
2011 * @param int $limitfrom
2012 * @param int $limitnum
2013 * @param int &$totalcount
2014 * @param string $extrasql
2015 * @return array|bool Array of posts found or false
2017 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2018 &$totalcount, $extrasql='') {
2019 global $CFG, $DB, $USER;
2020 require_once($CFG->libdir
.'/searchlib.php');
2022 $forums = forum_get_readable_forums($USER->id
, $courseid);
2024 if (count($forums) == 0) {
2029 $now = floor(time() / 60) * 60; // DB Cache Friendly.
2031 $fullaccess = array();
2035 foreach ($forums as $forumid => $forum) {
2038 if (!$forum->viewhiddentimedposts
) {
2039 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2040 $params = array_merge($params, array('userid'.$forumid=>$USER->id
, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2044 $context = $forum->context
;
2046 if ($forum->type
== 'qanda'
2047 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2048 if (!empty($forum->onlydiscussions
)) {
2049 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions
, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
2050 $params = array_merge($params, $discussionid_params);
2051 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2053 $select[] = "p.parent = 0";
2057 if (!empty($forum->onlygroups
)) {
2058 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups
, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
2059 $params = array_merge($params, $groupid_params);
2060 $select[] = "d.groupid $groupid_sql";
2064 $selects = implode(" AND ", $select);
2065 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2066 $params['forum'.$forumid] = $forumid;
2068 $fullaccess[] = $forumid;
2073 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED
, 'fula');
2074 $params = array_merge($params, $fullid_params);
2075 $where[] = "(d.forum $fullid_sql)";
2078 $selectdiscussion = "(".implode(" OR ", $where).")";
2080 $messagesearch = '';
2083 // Need to concat these back together for parser to work.
2084 foreach($searchterms as $searchterm){
2085 if ($searchstring != '') {
2086 $searchstring .= ' ';
2088 $searchstring .= $searchterm;
2091 // We need to allow quoted strings for the search. The quotes *should* be stripped
2092 // by the parser, but this should be examined carefully for security implications.
2093 $searchstring = str_replace("\\\"","\"",$searchstring);
2094 $parser = new search_parser();
2095 $lexer = new search_lexer($parser);
2097 if ($lexer->parse($searchstring)) {
2098 $parsearray = $parser->get_parsed_array();
2103 foreach ($parsearray as $token) {
2104 if ($token->getType() == TOKEN_TAGS
) {
2105 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++
) {
2106 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
2107 if ($tagfieldcount > 10) {
2110 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
2111 ON p.id = ti_$tagfieldcount.itemid
2112 AND ti_$tagfieldcount.component = 'mod_forum'
2113 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
2114 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
2115 $tagfields[] = "t_$tagfieldcount.rawname";
2120 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2121 'p.userid', 'u.id', 'u.firstname',
2122 'u.lastname', 'p.modified', 'd.forum',
2124 $params = array_merge($params, $msparams);
2127 $fromsql = "{forum_posts} p
2128 INNER JOIN {forum_discussions} d ON d.id = p.discussion
2129 INNER JOIN {user} u ON u.id = p.userid $tagjoins";
2131 $selectsql = " $messagesearch
2132 AND p.discussion = d.id
2134 AND $selectdiscussion
2137 $countsql = "SELECT COUNT(*)
2141 $allnames = get_all_user_name_fields(true, 'u');
2142 $searchsql = "SELECT p.*,
2150 ORDER BY p.modified DESC";
2152 $totalcount = $DB->count_records_sql($countsql, $params);
2154 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2158 * Returns a list of all new posts that have not been mailed yet
2160 * @param int $starttime posts created after this time
2161 * @param int $endtime posts created before this
2162 * @param int $now used for timed discussions only
2165 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2169 $params['mailed'] = FORUM_MAILED_PENDING
;
2170 $params['ptimestart'] = $starttime;
2171 $params['ptimeend'] = $endtime;
2172 $params['mailnow'] = 1;
2174 if (!empty($CFG->forum_enabletimedposts
)) {
2178 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2179 $params['pptimestart'] = $starttime;
2180 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2181 $params['dtimestart'] = $now;
2182 $params['dtimeend'] = $now;
2185 $selectsql = "AND p.created >= :ptimestart";
2188 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2189 FROM {forum_posts} p
2190 JOIN {forum_discussions} d ON d.id = p.discussion
2191 WHERE p.mailed = :mailed
2193 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2195 ORDER BY p.modified ASC", $params);
2199 * Marks posts before a certain time as being mailed already
2203 * @param int $endtime
2204 * @param int $now Defaults to time()
2207 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2215 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS
;
2216 $params['now'] = $now;
2217 $params['endtime'] = $endtime;
2218 $params['mailnow'] = 1;
2219 $params['mailedpending'] = FORUM_MAILED_PENDING
;
2221 if (empty($CFG->forum_enabletimedposts
)) {
2222 return $DB->execute("UPDATE {forum_posts}
2223 SET mailed = :mailedsuccess
2224 WHERE (created < :endtime OR mailnow = :mailnow)
2225 AND mailed = :mailedpending", $params);
2227 return $DB->execute("UPDATE {forum_posts}
2228 SET mailed = :mailedsuccess
2229 WHERE discussion NOT IN (SELECT d.id
2230 FROM {forum_discussions} d
2231 WHERE d.timestart > :now)
2232 AND (created < :endtime OR mailnow = :mailnow)
2233 AND mailed = :mailedpending", $params);
2238 * Get all the posts for a user in a forum suitable for forum_print_post
2242 * @uses CONTEXT_MODULE
2245 function forum_get_user_posts($forumid, $userid) {
2249 $params = array($forumid, $userid);
2251 if (!empty($CFG->forum_enabletimedposts
)) {
2252 $cm = get_coursemodule_from_instance('forum', $forumid);
2253 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2255 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2261 $allnames = get_all_user_name_fields(true, 'u');
2262 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2264 JOIN {forum_discussions} d ON d.forum = f.id
2265 JOIN {forum_posts} p ON p.discussion = d.id
2266 JOIN {user} u ON u.id = p.userid
2270 ORDER BY p.modified ASC", $params);
2274 * Get all the discussions user participated in
2278 * @uses CONTEXT_MODULE
2279 * @param int $forumid
2280 * @param int $userid
2281 * @return array Array or false
2283 function forum_get_user_involved_discussions($forumid, $userid) {
2287 $params = array($forumid, $userid);
2288 if (!empty($CFG->forum_enabletimedposts
)) {
2289 $cm = get_coursemodule_from_instance('forum', $forumid);
2290 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2292 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2298 return $DB->get_records_sql("SELECT DISTINCT d.*
2300 JOIN {forum_discussions} d ON d.forum = f.id
2301 JOIN {forum_posts} p ON p.discussion = d.id
2304 $timedsql", $params);
2308 * Get all the posts for a user in a forum suitable for forum_print_post
2312 * @param int $forumid
2313 * @param int $userid
2314 * @return array of counts or false
2316 function forum_count_user_posts($forumid, $userid) {
2320 $params = array($forumid, $userid);
2321 if (!empty($CFG->forum_enabletimedposts
)) {
2322 $cm = get_coursemodule_from_instance('forum', $forumid);
2323 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2325 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2331 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2333 JOIN {forum_discussions} d ON d.forum = f.id
2334 JOIN {forum_posts} p ON p.discussion = d.id
2335 JOIN {user} u ON u.id = p.userid
2338 $timedsql", $params);
2342 * Given a log entry, return the forum post details for it.
2346 * @param object $log
2347 * @return array|null
2349 function forum_get_post_from_log($log) {
2352 $allnames = get_all_user_name_fields(true, 'u');
2353 if ($log->action
== "add post") {
2355 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2356 FROM {forum_discussions} d,
2361 AND d.id = p.discussion
2363 AND u.deleted <> '1'
2364 AND f.id = d.forum", array($log->info
));
2367 } else if ($log->action
== "add discussion") {
2369 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2370 FROM {forum_discussions} d,
2375 AND d.firstpost = p.id
2377 AND u.deleted <> '1'
2378 AND f.id = d.forum", array($log->info
));
2384 * Given a discussion id, return the first post from the discussion
2388 * @param int $dicsussionid
2391 function forum_get_firstpost_from_discussion($discussionid) {
2394 return $DB->get_record_sql("SELECT p.*
2395 FROM {forum_discussions} d,
2398 AND d.firstpost = p.id ", array($discussionid));
2402 * Returns an array of counts of replies to each discussion
2406 * @param int $forumid
2407 * @param string $forumsort
2410 * @param int $perpage
2413 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2419 } else if ($page != -1) {
2420 $limitfrom = $page*$perpage;
2421 $limitnum = $perpage;
2427 if ($forumsort == "") {
2432 $orderby = "ORDER BY $forumsort";
2433 $groupby = ", ".strtolower($forumsort);
2434 $groupby = str_replace('desc', '', $groupby);
2435 $groupby = str_replace('asc', '', $groupby);
2438 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2439 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2440 FROM {forum_posts} p
2441 JOIN {forum_discussions} d ON p.discussion = d.id
2442 WHERE p.parent > 0 AND d.forum = ?
2443 GROUP BY p.discussion";
2444 return $DB->get_records_sql($sql, array($forumid));
2447 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2448 FROM {forum_posts} p
2449 JOIN {forum_discussions} d ON p.discussion = d.id
2451 GROUP BY p.discussion $groupby $orderby";
2452 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
2460 * @staticvar array $cache
2461 * @param object $forum
2463 * @param object $course
2466 function forum_count_discussions($forum, $cm, $course) {
2467 global $CFG, $DB, $USER;
2469 static $cache = array();
2471 $now = floor(time() / 60) * 60; // DB Cache Friendly.
2473 $params = array($course->id
);
2475 if (!isset($cache[$course->id
])) {
2476 if (!empty($CFG->forum_enabletimedposts
)) {
2477 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2484 $sql = "SELECT f.id, COUNT(d.id) as dcount
2486 JOIN {forum_discussions} d ON d.forum = f.id
2491 if ($counts = $DB->get_records_sql($sql, $params)) {
2492 foreach ($counts as $count) {
2493 $counts[$count->id
] = $count->dcount
;
2495 $cache[$course->id
] = $counts;
2497 $cache[$course->id
] = array();
2501 if (empty($cache[$course->id
][$forum->id
])) {
2505 $groupmode = groups_get_activity_groupmode($cm, $course);
2507 if ($groupmode != SEPARATEGROUPS
) {
2508 return $cache[$course->id
][$forum->id
];
2511 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
2512 return $cache[$course->id
][$forum->id
];
2515 require_once($CFG->dirroot
.'/course/lib.php');
2517 $modinfo = get_fast_modinfo($course);
2519 $mygroups = $modinfo->get_groups($cm->groupingid
);
2521 // add all groups posts
2524 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2525 $params[] = $forum->id
;
2527 if (!empty($CFG->forum_enabletimedposts
)) {
2528 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2535 $sql = "SELECT COUNT(d.id)
2536 FROM {forum_discussions} d
2537 WHERE d.groupid $mygroups_sql AND d.forum = ?
2540 return $DB->get_field_sql($sql, $params);
2544 * Get all discussions in a forum
2549 * @uses CONTEXT_MODULE
2550 * @uses VISIBLEGROUPS
2552 * @param string $forumsort
2553 * @param bool $fullpost
2554 * @param int $unused
2556 * @param bool $userlastmodified
2558 * @param int $perpage
2559 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2560 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
2561 * @param int $updatedsince retrieve only discussions updated since the given time
2564 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
2565 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
2566 $updatedsince = 0) {
2567 global $CFG, $DB, $USER;
2571 $now = floor(time() / 60) * 60;
2572 $params = array($cm->instance
);
2574 $modcontext = context_module
::instance($cm->id
);
2576 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2580 if (!empty($CFG->forum_enabletimedposts
)) { /// Users must fulfill timed posts
2582 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2583 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2587 $timelimit .= " OR d.userid = ?";
2588 $params[] = $USER->id
;
2597 } else if ($page != -1) {
2598 $limitfrom = $page*$perpage;
2599 $limitnum = $perpage;
2605 $groupmode = groups_get_activity_groupmode($cm);
2609 if (empty($modcontext)) {
2610 $modcontext = context_module
::instance($cm->id
);
2613 // Special case, we received a groupid to override currentgroup.
2615 $course = get_course($cm->course
);
2616 if (!groups_group_visible($groupid, $course, $cm)) {
2617 // User doesn't belong to this group, return nothing.
2620 $currentgroup = $groupid;
2621 } else if ($groupid === -1) {
2622 $currentgroup = groups_get_activity_group($cm);
2624 // Get discussions for all groups current user can see.
2625 $currentgroup = null;
2628 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2629 if ($currentgroup) {
2630 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2631 $params[] = $currentgroup;
2639 // Get discussions for all groups current user can see.
2640 if ($currentgroup === null) {
2641 $mygroups = array_keys(groups_get_all_groups($cm->course
, $USER->id
, $cm->groupingid
, 'g.id'));
2642 if (empty($mygroups)) {
2643 $groupselect = "AND d.groupid = -1";
2645 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2646 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2647 $params = array_merge($params, $inparamsgroups);
2649 } else if ($currentgroup) {
2650 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2651 $params[] = $currentgroup;
2653 $groupselect = "AND d.groupid = -1";
2659 if (empty($forumsort)) {
2660 $forumsort = forum_get_default_sort_order();
2662 if (empty($fullpost)) {
2663 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2668 if (empty($userlastmodified)) { // We don't need to know this
2672 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2673 um.imagealt AS umimagealt';
2674 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2677 $updatedsincesql = '';
2678 if (!empty($updatedsince)) {
2679 $updatedsincesql = 'AND d.timemodified > ?';
2680 $params[] = $updatedsince;
2683 $allnames = get_all_user_name_fields(true, 'u');
2684 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
2685 u.email, u.picture, u.imagealt $umfields
2686 FROM {forum_discussions} d
2687 JOIN {forum_posts} p ON p.discussion = d.id
2688 JOIN {user} u ON p.userid = u.id
2690 WHERE d.forum = ? AND p.parent = 0
2691 $timelimit $groupselect $updatedsincesql
2692 ORDER BY $forumsort, d.id DESC";
2694 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2698 * Gets the neighbours (previous and next) of a discussion.
2700 * The calculation is based on the timemodified when time modified or time created is identical
2701 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
2703 * For blog-style forums, the calculation is based on the original creation time of the
2706 * Please note that this does not check whether or not the discussion passed is accessible
2707 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2708 * the returned neighbours are checked and are accessible to the current user.
2710 * @param object $cm The CM record.
2711 * @param object $discussion The discussion record.
2712 * @param object $forum The forum instance 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, $forum) {
2718 global $CFG, $DB, $USER;
2720 if ($cm->instance
!= $discussion->forum
or $discussion->forum
!= $forum->id
or $forum->id
!= $cm->instance
) {
2721 throw new coding_exception('Discussion is not part of the same forum.');
2724 $neighbours = array('prev' => false, 'next' => false);
2725 $now = floor(time() / 60) * 60;
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.
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;
2740 $timelimit .= ' OR d.userid = :tluserid';
2741 $params['tluserid'] = $USER->id
;
2747 // Limiting to posts accessible according to groups.
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;
2756 if ($currentgroup) {
2757 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2758 $params['groupid'] = $currentgroup;
2760 $groupselect = 'AND d.groupid = -1';
2765 $params['forumid'] = $cm->instance
;
2766 $params['discid1'] = $discussion->id
;
2767 $params['discid2'] = $discussion->id
;
2768 $params['discid3'] = $discussion->id
;
2769 $params['discid4'] = $discussion->id
;
2770 $params['disctimecompare1'] = $discussion->timemodified
;
2771 $params['disctimecompare2'] = $discussion->timemodified
;
2772 $params['pinnedstate1'] = (int) $discussion->pinned
;
2773 $params['pinnedstate2'] = (int) $discussion->pinned
;
2774 $params['pinnedstate3'] = (int) $discussion->pinned
;
2775 $params['pinnedstate4'] = (int) $discussion->pinned
;
2777 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2778 FROM {forum_discussions} d
2779 JOIN {forum_posts} p ON d.firstpost = p.id
2780 WHERE d.forum = :forumid
2781 AND d.id <> :discid1
2784 $comparefield = "d.timemodified";
2785 $comparevalue = ":disctimecompare1";
2786 $comparevalue2 = ":disctimecompare2";
2787 if (!empty($CFG->forum_enabletimedposts
)) {
2788 // Here we need to take into account the release time (timestart)
2789 // if one is set, of the neighbouring posts and compare it to the
2790 // timestart or timemodified of *this* post depending on if the
2791 // release date of this post is in the future or not.
2792 // This stops discussions that appear later because of the
2793 // timestart value from being buried under discussions that were
2795 $comparefield = "CASE WHEN d.timemodified < d.timestart
2796 THEN d.timestart ELSE d.timemodified END";
2797 if ($discussion->timemodified
< $discussion->timestart
) {
2798 // Normally we would just use the timemodified for sorting
2799 // discussion posts. However, when timed discussions are enabled,
2800 // then posts need to be sorted base on the later of timemodified
2801 // or the release date of the post (timestart).
2802 $params['disctimecompare1'] = $discussion->timestart
;
2803 $params['disctimecompare2'] = $discussion->timestart
;
2806 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2807 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
2809 if ($forum->type
=== 'blog') {
2810 $subselect = "SELECT pp.created
2811 FROM {forum_discussions} dd
2812 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
2814 $subselectwhere1 = " WHERE dd.id = :discid3";
2815 $subselectwhere2 = " WHERE dd.id = :discid4";
2817 $comparefield = "p.created";
2819 $sub1 = $subselect.$subselectwhere1;
2820 $comparevalue = "($sub1)";
2822 $sub2 = $subselect.$subselectwhere2;
2823 $comparevalue2 = "($sub2)";
2825 $orderbydesc = "d.pinned, p.created DESC";
2826 $orderbyasc = "d.pinned, p.created ASC";
2829 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2830 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2831 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2832 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
2834 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2835 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2836 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2837 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
2839 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE
);
2840 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE
);
2845 * Get the sql to use in the ORDER BY clause for forum discussions.
2847 * This has the ordering take timed discussion windows into account.
2849 * @param bool $desc True for DESC, False for ASC.
2850 * @param string $compare The field in the SQL to compare to normally sort by.
2851 * @param string $prefix The prefix being used for the discussion table.
2852 * @param bool $pinned sort pinned posts to the top
2855 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
2858 if (!empty($prefix)) {
2862 $dir = $desc ?
'DESC' : 'ASC';
2864 if ($pinned == true) {
2865 $pinned = "{$prefix}pinned DESC,";
2870 $sort = "{$prefix}timemodified";
2871 if (!empty($CFG->forum_enabletimedposts
)) {
2872 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2873 THEN {$prefix}timestart
2877 return "$pinned $sort $dir";
2885 * @uses CONTEXT_MODULE
2886 * @uses VISIBLEGROUPS
2890 function forum_get_discussions_unread($cm) {
2891 global $CFG, $DB, $USER;
2893 $now = floor(time() / 60) * 60;
2894 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
2897 $groupmode = groups_get_activity_groupmode($cm);
2898 $currentgroup = groups_get_activity_group($cm);
2901 $modcontext = context_module
::instance($cm->id
);
2903 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2904 if ($currentgroup) {
2905 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2906 $params['currentgroup'] = $currentgroup;
2912 //separate groups without access all
2913 if ($currentgroup) {
2914 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2915 $params['currentgroup'] = $currentgroup;
2917 $groupselect = "AND d.groupid = -1";
2924 if (!empty($CFG->forum_enabletimedposts
)) {
2925 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2926 $params['now1'] = $now;
2927 $params['now2'] = $now;
2932 $sql = "SELECT d.id, COUNT(p.id) AS unread
2933 FROM {forum_discussions} d
2934 JOIN {forum_posts} p ON p.discussion = d.id
2935 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2936 WHERE d.forum = {$cm->instance}
2937 AND p.modified >= :cutoffdate AND r.id is NULL
2941 $params['cutoffdate'] = $cutoffdate;
2943 if ($unreads = $DB->get_records_sql($sql, $params)) {
2944 foreach ($unreads as $unread) {
2945 $unreads[$unread->id
] = $unread->unread
;
2957 * @uses CONEXT_MODULE
2958 * @uses VISIBLEGROUPS
2962 function forum_get_discussions_count($cm) {
2963 global $CFG, $DB, $USER;
2965 $now = floor(time() / 60) * 60;
2966 $params = array($cm->instance
);
2967 $groupmode = groups_get_activity_groupmode($cm);
2968 $currentgroup = groups_get_activity_group($cm);
2971 $modcontext = context_module
::instance($cm->id
);
2973 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2974 if ($currentgroup) {
2975 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2976 $params[] = $currentgroup;
2982 //seprate groups without access all
2983 if ($currentgroup) {
2984 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2985 $params[] = $currentgroup;
2987 $groupselect = "AND d.groupid = -1";
2996 if (!empty($CFG->forum_enabletimedposts
)) {
2998 $modcontext = context_module
::instance($cm->id
);
3000 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
3001 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
3005 $timelimit .= " OR d.userid = ?";
3006 $params[] = $USER->id
;
3012 $sql = "SELECT COUNT(d.id)
3013 FROM {forum_discussions} d
3014 JOIN {forum_posts} p ON p.discussion = d.id
3015 WHERE d.forum = ? AND p.parent = 0
3016 $groupselect $timelimit";
3018 return $DB->get_field_sql($sql, $params);
3022 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
3028 * @param int $courseid
3029 * @param string $type
3031 function forum_get_course_forum($courseid, $type) {
3032 // How to set up special 1-per-course forums
3033 global $CFG, $DB, $OUTPUT, $USER;
3035 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
3036 // There should always only be ONE, but with the right combination of
3037 // errors there might be more. In this case, just return the oldest one (lowest ID).
3038 foreach ($forums as $forum) {
3039 return $forum; // ie the first one
3043 // Doesn't exist, so create one now.
3044 $forum = new stdClass();
3045 $forum->course
= $courseid;
3046 $forum->type
= "$type";
3047 if (!empty($USER->htmleditor
)) {
3048 $forum->introformat
= $USER->htmleditor
;
3050 switch ($forum->type
) {
3052 $forum->name
= get_string("namenews", "forum");
3053 $forum->intro
= get_string("intronews", "forum");
3054 $forum->forcesubscribe
= FORUM_FORCESUBSCRIBE
;
3055 $forum->assessed
= 0;
3056 if ($courseid == SITEID
) {
3057 $forum->name
= get_string("sitenews");
3058 $forum->forcesubscribe
= 0;
3062 $forum->name
= get_string("namesocial", "forum");
3063 $forum->intro
= get_string("introsocial", "forum");
3064 $forum->assessed
= 0;
3065 $forum->forcesubscribe
= 0;
3068 $forum->name
= get_string('blogforum', 'forum');
3069 $forum->intro
= get_string('introblog', 'forum');
3070 $forum->assessed
= 0;
3071 $forum->forcesubscribe
= 0;
3074 echo $OUTPUT->notification("That forum type doesn't exist!");
3079 $forum->timemodified
= time();
3080 $forum->id
= $DB->insert_record("forum", $forum);
3082 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
3083 echo $OUTPUT->notification("Could not find forum module!!");
3086 $mod = new stdClass();
3087 $mod->course
= $courseid;
3088 $mod->module
= $module->id
;
3089 $mod->instance
= $forum->id
;
3091 include_once("$CFG->dirroot/course/lib.php");
3092 if (! $mod->coursemodule
= add_course_module($mod) ) {
3093 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3096 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule
, 0);
3097 return $DB->get_record("forum", array("id" => "$forum->id"));
3101 * Print a forum post
3105 * @uses FORUM_MODE_THREADED
3106 * @uses PORTFOLIO_FORMAT_PLAINHTML
3107 * @uses PORTFOLIO_FORMAT_FILE
3108 * @uses PORTFOLIO_FORMAT_RICHHTML
3109 * @uses PORTFOLIO_ADD_TEXT_LINK
3110 * @uses CONTEXT_MODULE
3111 * @param object $post The post to print.
3112 * @param object $discussion
3113 * @param object $forum
3115 * @param object $course
3116 * @param boolean $ownpost Whether this post belongs to the current user.
3117 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3118 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3119 * @param string $footer Extra stuff to print after the message.
3120 * @param string $highlight Space-separated list of terms to highlight.
3121 * @param int $post_read true, false or -99. If we already know whether this user
3122 * has read this post, pass that in, otherwise, pass in -99, and this
3123 * function will work it out.
3124 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3125 * the current user can't see this post, if this argument is true
3126 * (the default) then print a dummy 'you can't see this post' post.
3127 * If false, don't output anything at all.
3128 * @param bool|null $istracked
3131 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3132 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3133 global $USER, $CFG, $OUTPUT;
3135 require_once($CFG->libdir
. '/filelib.php');
3139 // This is an extremely hacky way to ensure we only print the 'unread' anchor
3140 // the first time we encounter an unread post on a page. Ideally this would
3141 // be moved into the caller somehow, and be better testable. But at the time
3142 // of dealing with this bug, this static workaround was the most surgical and
3143 // it fits together with only printing th unread anchor id once on a given page.
3144 static $firstunreadanchorprinted = false;
3146 $modcontext = context_module
::instance($cm->id
);
3148 $post->course
= $course->id
;
3149 $post->forum
= $forum->id
;
3150 $post->message
= file_rewrite_pluginfile_urls($post->message
, 'pluginfile.php', $modcontext->id
, 'mod_forum', 'post', $post->id
);
3151 if (!empty($CFG->enableplagiarism
)) {
3152 require_once($CFG->libdir
.'/plagiarismlib.php');
3153 $post->message
.= plagiarism_get_links(array('userid' => $post->userid
,
3154 'content' => $post->message
,
3156 'course' => $post->course
,
3157 'forum' => $post->forum
));
3161 if (!isset($cm->cache
)) {
3162 $cm->cache
= new stdClass
;
3165 if (!isset($cm->cache
->caps
)) {
3166 $cm->cache
->caps
= array();
3167 $cm->cache
->caps
['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3168 $cm->cache
->caps
['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3169 $cm->cache
->caps
['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3170 $cm->cache
->caps
['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3171 $cm->cache
->caps
['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3172 $cm->cache
->caps
['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3173 $cm->cache
->caps
['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3174 $cm->cache
->caps
['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3175 $cm->cache
->caps
['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3178 if (!isset($cm->uservisible
)) {
3179 $cm->uservisible
= \core_availability\info_module
::is_user_visible($cm, 0, false);
3182 if ($istracked && is_null($postisread)) {
3183 $postisread = forum_tp_is_post_read($USER->id
, $post);
3186 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm, false)) {
3187 // Do _not_ check the deleted flag - we need to display a different UI.
3189 if (!$dummyifcantsee) {
3196 $output .= html_writer
::tag('a', '', array('id'=>'p'.$post->id
));
3197 $output .= html_writer
::start_tag('div', array('class'=>'forumpost clearfix',
3199 'aria-label' => get_string('hiddenforumpost', 'forum')));
3200 $output .= html_writer
::start_tag('div', array('class'=>'row header'));
3201 $output .= html_writer
::tag('div', '', array('class'=>'left picture')); // Picture
3202 if ($post->parent
) {
3203 $output .= html_writer
::start_tag('div', array('class'=>'topic'));
3205 $output .= html_writer
::start_tag('div', array('class'=>'topic starter'));
3207 $output .= html_writer
::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3208 'role' => 'header')); // Subject.
3209 $output .= html_writer
::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3210 'role' => 'header')); // Author.
3211 $output .= html_writer
::end_tag('div');
3212 $output .= html_writer
::end_tag('div'); // row
3213 $output .= html_writer
::start_tag('div', array('class'=>'row'));
3214 $output .= html_writer
::tag('div', ' ', array('class'=>'left side')); // Groups
3215 $output .= html_writer
::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3216 $output .= html_writer
::end_tag('div'); // row
3217 $output .= html_writer
::end_tag('div'); // forumpost
3226 if (!empty($post->deleted
)) {
3227 // Note: Posts marked as deleted are still returned by the above forum_user_can_post because it is required for
3228 // nesting of posts.
3230 if (!$dummyifcantsee) {
3237 $output .= html_writer
::tag('a', '', [
3238 'id' => "p{$post->id}",
3240 $output .= html_writer
::start_tag('div', [
3241 'class' => 'forumpost clearfix',
3243 'aria-label' => get_string('forumbodydeleted', 'forum'),
3246 $output .= html_writer
::start_tag('div', array('class' => 'row header'));
3247 $output .= html_writer
::tag('div', '', array('class' => 'left picture'));
3249 $classes = ['topic'];
3250 if (!empty($post->parent
)) {
3251 $classes[] = 'starter';
3253 $output .= html_writer
::start_tag('div', ['class' => implode(' ', $classes)]);
3256 $output .= html_writer
::tag('div', get_string('forumsubjectdeleted', 'forum'), [
3257 'class' => 'subject',
3262 $output .= html_writer
::tag('div', '', [
3263 'class' => 'author',
3267 $output .= html_writer
::end_tag('div');
3268 $output .= html_writer
::end_tag('div'); // End row.
3269 $output .= html_writer
::start_tag('div', ['class' => 'row']);
3270 $output .= html_writer
::tag('div', ' ', ['class' => 'left side']); // Groups.
3271 $output .= html_writer
::tag('div', get_string('forumbodydeleted', 'forum'), ['class' => 'content']); // Content.
3272 $output .= html_writer
::end_tag('div'); // End row.
3273 $output .= html_writer
::end_tag('div'); // End forumpost.
3283 $str = new stdClass
;
3284 $str->edit
= get_string('edit', 'forum');
3285 $str->delete
= get_string('delete', 'forum');
3286 $str->reply
= get_string('reply', 'forum');
3287 $str->parent
= get_string('parent', 'forum');
3288 $str->pruneheading
= get_string('pruneheading', 'forum');
3289 $str->prune
= get_string('prune', 'forum');
3290 $str->displaymode
= get_user_preferences('forum_displaymode', $CFG->forum_displaymode
);
3291 $str->markread
= get_string('markread', 'forum');
3292 $str->markunread
= get_string('markunread', 'forum');
3295 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion
));
3297 // Build an object that represents the posting user
3298 $postuser = new stdClass
;
3299 $postuserfields = explode(',', user_picture
::fields());
3300 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3301 $postuser->id
= $post->userid
;
3302 $postuser->fullname
= fullname($postuser, $cm->cache
->caps
['moodle/site:viewfullnames']);
3303 $postuser->profilelink
= new moodle_url('/user/view.php', array('id'=>$post->userid
, 'course'=>$course->id
));
3305 // Prepare the groups the posting user belongs to
3306 if (isset($cm->cache
->usersgroups
)) {
3308 if (isset($cm->cache
->usersgroups
[$post->userid
])) {
3309 foreach ($cm->cache
->usersgroups
[$post->userid
] as $gid) {
3310 $groups[$gid] = $cm->cache
->groups
[$gid];
3314 $groups = groups_get_all_groups($course->id
, $post->userid
, $cm->groupingid
);
3317 // Prepare the attachements for the post, files then images
3318 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3320 // Determine if we need to shorten this post
3321 $shortenpost = ($link && (strlen(strip_tags($post->message
)) > $CFG->forum_longpost
));
3324 // Prepare an array of commands
3325 $commands = array();
3328 $permalink = new moodle_url($discussionlink);
3329 $permalink->set_anchor('p' . $post->id
);
3330 $commands[] = array('url' => $permalink, 'text' => get_string('permalink', 'forum'));
3332 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3333 // Don't display the mark read / unread controls in this case.
3334 if ($istracked && $CFG->forum_usermarksread
&& isloggedin()) {
3335 $url = new moodle_url($discussionlink, array('postid'=>$post->id
, 'mark'=>'unread'));
3336 $text = $str->markunread
;
3338 $url->param('mark', 'read');
3339 $text = $str->markread
;
3341 if ($str->displaymode
== FORUM_MODE_THREADED
) {
3342 $url->param('parent', $post->parent
);
3344 $url->set_anchor('p'.$post->id
);
3346 $commands[] = array('url'=>$url, 'text'=>$text);
3349 // Zoom in to the parent specifically
3350 if ($post->parent
) {
3351 $url = new moodle_url($discussionlink);
3352 if ($str->displaymode
== FORUM_MODE_THREADED
) {
3353 $url->param('parent', $post->parent
);
3355 $url->set_anchor('p'.$post->parent
);
3357 $commands[] = array('url'=>$url, 'text'=>$str->parent
);
3360 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3361 $age = time() - $post->created
;
3362 if (!$post->parent
&& $forum->type
== 'news' && $discussion->timestart
> time()) {
3366 if ($forum->type
== 'single' and $discussion->firstpost
== $post->id
) {
3367 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3368 // The first post in single simple is the forum description.
3369 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id
, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit
);
3371 } else if (($ownpost && $age < $CFG->maxeditingtime
) ||
$cm->cache
->caps
['mod/forum:editanypost']) {
3372 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id
)), 'text'=>$str->edit
);
3375 if ($cm->cache
->caps
['mod/forum:splitdiscussions'] && $post->parent
&& $forum->type
!= 'single') {
3376 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id
)), 'text'=>$str->prune
, 'title'=>$str->pruneheading
);
3379 if ($forum->type
== 'single' and $discussion->firstpost
== $post->id
) {
3380 // Do not allow deleting of first post in single simple type.
3381 } else if (($ownpost && $age < $CFG->maxeditingtime
&& $cm->cache
->caps
['mod/forum:deleteownpost']) ||
$cm->cache
->caps
['mod/forum:deleteanypost']) {
3382 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id
)), 'text'=>$str->delete
);
3386 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id
)), 'text'=>$str->reply
);
3389 if ($CFG->enableportfolios
&& ($cm->cache
->caps
['mod/forum:exportpost'] ||
($ownpost && $cm->cache
->caps
['mod/forum:exportownpost']))) {
3390 $p = array('postid' => $post->id
);
3391 require_once($CFG->libdir
.'/portfoliolib.php');
3392 $button = new portfolio_add_button();
3393 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
), 'mod_forum');
3394 if (empty($attachments)) {
3395 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
3397 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
3400 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK
);
3401 if (!empty($porfoliohtml)) {
3402 $commands[] = $porfoliohtml;
3405 // Finished building commands
3414 $forumpostclass = ' read';
3416 $forumpostclass = ' unread';
3417 // If this is the first unread post printed then give it an anchor and id of unread.
3418 if (!$firstunreadanchorprinted) {
3419 $output .= html_writer
::tag('a', '', array('id' => 'unread'));
3420 $firstunreadanchorprinted = true;
3424 // ignore trackign status if not tracked or tracked param missing
3425 $forumpostclass = '';
3429 if (empty($post->parent
)) {
3430 $topicclass = ' firstpost starter';
3433 if (!empty($post->lastpost
)) {
3434 $forumpostclass .= ' lastpost';
3437 // Flag to indicate whether we should hide the author or not.
3438 $authorhidden = forum_is_author_hidden($post, $forum);
3439 $postbyuser = new stdClass
;
3440 $postbyuser->post
= $post->subject
;
3441 $postbyuser->user
= $postuser->fullname
;
3442 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3443 $output .= html_writer
::tag('a', '', array('id'=>'p'.$post->id
));
3444 // Begin forum post.
3445 $output .= html_writer
::start_div('forumpost clearfix' . $forumpostclass . $topicclass,
3446 ['role' => 'region', 'aria-label' => $discussionbyuser]);
3447 // Begin header row.
3448 $output .= html_writer
::start_div('row header clearfix');
3451 if (!$authorhidden) {
3452 $picture = $OUTPUT->user_picture($postuser, ['courseid' => $course->id
]);
3453 $output .= html_writer
::div($picture, 'left picture');
3454 $topicclass = 'topic' . $topicclass;
3457 // Begin topic column.
3458 $output .= html_writer
::start_div($topicclass);
3459 $postsubject = $post->subject
;
3460 if (empty($post->subjectnoformat
)) {
3461 $postsubject = format_string($postsubject);
3463 $output .= html_writer
::div($postsubject, 'subject', ['role' => 'heading', 'aria-level' => '2']);
3465 if ($authorhidden) {
3466 $bytext = userdate($post->modified
);
3468 $by = new stdClass();
3469 $by->date
= userdate($post->modified
);
3470 $by->name
= html_writer
::link($postuser->profilelink
, $postuser->fullname
);
3471 $bytext = get_string('bynameondate', 'forum', $by);
3474 'role' => 'heading',
3475 'aria-level' => '2',
3477 $output .= html_writer
::div($bytext, 'author', $bytextoptions);
3478 // End topic column.
3479 $output .= html_writer
::end_div();
3482 $output .= html_writer
::end_div();
3484 // Row with the forum post content.
3485 $output .= html_writer
::start_div('row maincontent clearfix');
3486 // Show if author is not hidden or we have groups.
3487 if (!$authorhidden ||
$groups) {
3488 $output .= html_writer
::start_div('left');
3491 $groupoutput = print_group_picture($groups, $course->id
, false, true, true);
3493 if (empty($groupoutput)) {
3494 $groupoutput = ' ';
3496 $output .= html_writer
::div($groupoutput, 'grouppictures');
3497 $output .= html_writer
::end_div(); // Left side.
3500 $output .= html_writer
::start_tag('div', array('class'=>'no-overflow'));
3501 $output .= html_writer
::start_tag('div', array('class'=>'content'));
3503 $options = new stdClass
;
3504 $options->para
= false;
3505 $options->trusted
= $post->messagetrust
;
3506 $options->context
= $modcontext;
3508 // Prepare shortened version by filtering the text then shortening it.
3509 $postclass = 'shortenedpost';
3510 $postcontent = format_text($post->message
, $post->messageformat
, $options);
3511 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost
);
3512 $postcontent .= html_writer
::link($discussionlink, get_string('readtherest', 'forum'));
3513 $postcontent .= html_writer
::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message
)).')',
3514 array('class'=>'post-word-count'));
3516 // Prepare whole post
3517 $postclass = 'fullpost';
3518 $postcontent = format_text($post->message
, $post->messageformat
, $options, $course->id
);
3519 if (!empty($highlight)) {
3520 $postcontent = highlight($highlight, $postcontent);
3522 if (!empty($forum->displaywordcount
)) {
3523 $postcontent .= html_writer
::tag('div', get_string('numwords', 'moodle', count_words($post->message
)),
3524 array('class'=>'post-word-count'));
3526 $postcontent .= html_writer
::tag('div', $attachedimages, array('class'=>'attachedimages'));
3529 if (\core_tag_tag
::is_enabled('mod_forum', 'forum_posts')) {
3530 $postcontent .= $OUTPUT->tag_list(core_tag_tag
::get_item_tags('mod_forum', 'forum_posts', $post->id
), null, 'forum-tags');
3533 // Output the post content
3534 $output .= html_writer
::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3535 $output .= html_writer
::end_tag('div'); // Content
3536 $output .= html_writer
::end_tag('div'); // Content mask
3537 $output .= html_writer
::end_tag('div'); // Row
3539 $output .= html_writer
::start_tag('div', array('class'=>'row side'));
3540 $output .= html_writer
::tag('div',' ', array('class'=>'left'));
3541 $output .= html_writer
::start_tag('div', array('class'=>'options clearfix'));
3543 if (!empty($attachments)) {
3544 $output .= html_writer
::tag('div', $attachments, array('class' => 'attachments'));
3548 if (!empty($post->rating
)) {
3549 $output .= html_writer
::tag('div', $OUTPUT->render($post->rating
), array('class'=>'forum-post-rating'));
3552 // Output the commands
3553 $commandhtml = array();
3554 foreach ($commands as $command) {
3555 if (is_array($command)) {
3556 $commandhtml[] = html_writer
::link($command['url'], $command['text']);
3558 $commandhtml[] = $command;
3561 $output .= html_writer
::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3563 // Output link to post if required
3565 if (forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3566 $langstring = 'discussthistopic';
3568 $langstring = 'viewthediscussion';
3570 if ($post->replies
== 1) {
3571 $replystring = get_string('repliesone', 'forum', $post->replies
);
3573 $replystring = get_string('repliesmany', 'forum', $post->replies
);
3575 if (!empty($discussion->unread
) && $discussion->unread
!== '-') {
3576 $replystring .= ' <span class="sep">/</span> <span class="unread">';
3577 $unreadlink = new moodle_url($discussionlink, null, 'unread');
3578 if ($discussion->unread
== 1) {
3579 $replystring .= html_writer
::link($unreadlink, get_string('unreadpostsone', 'forum'));
3581 $replystring .= html_writer
::link($unreadlink, get_string('unreadpostsnumber', 'forum', $discussion->unread
));
3583 $replystring .= '</span>';
3586 $output .= html_writer
::start_tag('div', array('class'=>'link'));
3587 $output .= html_writer
::link($discussionlink, get_string($langstring, 'forum'));
3588 $output .= ' ('.$replystring.')';
3589 $output .= html_writer
::end_tag('div'); // link
3592 // Output footer if required
3594 $output .= html_writer
::tag('div', $footer, array('class'=>'footer'));
3597 // Close remaining open divs
3598 $output .= html_writer
::end_tag('div'); // content
3599 $output .= html_writer
::end_tag('div'); // row
3600 $output .= html_writer
::end_tag('div'); // forumpost
3602 // Mark the forum post as read if required
3603 if ($istracked && !$CFG->forum_usermarksread
&& !$postisread) {
3604 forum_tp_mark_post_read($USER->id
, $post);
3615 * Return rating related permissions
3617 * @param string $options the context id
3618 * @return array an associative array of the user's rating permissions
3620 function forum_rating_permissions($contextid, $component, $ratingarea) {
3621 $context = context
::instance_by_id($contextid, MUST_EXIST
);
3622 if ($component != 'mod_forum' ||
$ratingarea != 'post') {
3623 // We don't know about this component/ratingarea so just return null to get the
3624 // default restrictive permissions.
3628 'view' => has_capability('mod/forum:viewrating', $context),
3629 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3630 'viewall' => has_capability('mod/forum:viewallratings', $context),
3631 'rate' => has_capability('mod/forum:rate', $context)
3636 * Validates a submitted rating
3637 * @param array $params submitted data
3638 * context => object the context in which the rated items exists [required]
3639 * component => The component for this module - should always be mod_forum [required]
3640 * ratingarea => object the context in which the rated items exists [required]
3642 * itemid => int the ID of the object being rated [required]
3643 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3644 * rating => int the submitted rating [required]
3645 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3646 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3647 * @return boolean true if the rating is valid. Will throw rating_exception if not
3649 function forum_rating_validate($params) {
3652 // Check the component is mod_forum
3653 if ($params['component'] != 'mod_forum') {
3654 throw new rating_exception('invalidcomponent');
3657 // Check the ratingarea is post (the only rating area in forum)
3658 if ($params['ratingarea'] != 'post') {
3659 throw new rating_exception('invalidratingarea');
3662 // Check the rateduserid is not the current user .. you can't rate your own posts
3663 if ($params['rateduserid'] == $USER->id
) {
3664 throw new rating_exception('nopermissiontorate');
3667 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
3668 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST
);
3669 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
), '*', MUST_EXIST
);
3670 $forum = $DB->get_record('forum', array('id' => $discussion->forum
), '*', MUST_EXIST
);
3671 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
3672 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
3673 $context = context_module
::instance($cm->id
);
3675 // Make sure the context provided is the context of the forum
3676 if ($context->id
!= $params['context']->id
) {
3677 throw new rating_exception('invalidcontext');
3680 if ($forum->scale
!= $params['scaleid']) {
3681 //the scale being submitted doesnt match the one in the database
3682 throw new rating_exception('invalidscaleid');
3685 // check the item we're rating was created in the assessable time window
3686 if (!empty($forum->assesstimestart
) && !empty($forum->assesstimefinish
)) {
3687 if ($post->created
< $forum->assesstimestart ||
$post->created
> $forum->assesstimefinish
) {
3688 throw new rating_exception('notavailable');
3692 //check that the submitted rating is valid for the scale
3695 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
3696 throw new rating_exception('invalidnum');
3700 if ($forum->scale
< 0) {
3701 //its a custom scale
3702 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale
));
3704 $scalearray = explode(',', $scalerecord->scale
);
3705 if ($params['rating'] > count($scalearray)) {
3706 throw new rating_exception('invalidnum');
3709 throw new rating_exception('invalidscaleid');
3711 } else if ($params['rating'] > $forum->scale
) {
3712 //if its numeric and submitted rating is above maximum
3713 throw new rating_exception('invalidnum');
3716 // Make sure groups allow this user to see the item they're rating
3717 if ($discussion->groupid
> 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
3718 if (!groups_group_exists($discussion->groupid
)) { // Can't find group
3719 throw new rating_exception('cannotfindgroup');//something is wrong
3722 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
3723 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
3724 throw new rating_exception('notmemberofgroup');
3728 // perform some final capability checks
3729 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3730 throw new rating_exception('nopermissiontorate');
3737 * Can the current user see ratings for a given itemid?
3739 * @param array $params submitted data
3740 * contextid => int contextid [required]
3741 * component => The component for this module - should always be mod_forum [required]
3742 * ratingarea => object the context in which the rated items exists [required]
3743 * itemid => int the ID of the object being rated [required]
3744 * scaleid => int scale id [optional]
3746 * @throws coding_exception
3747 * @throws rating_exception
3749 function mod_forum_rating_can_see_item_ratings($params) {
3752 // Check the component is mod_forum.
3753 if (!isset($params['component']) ||
$params['component'] != 'mod_forum') {
3754 throw new rating_exception('invalidcomponent');
3757 // Check the ratingarea is post (the only rating area in forum).
3758 if (!isset($params['ratingarea']) ||
$params['ratingarea'] != 'post') {
3759 throw new rating_exception('invalidratingarea');
3762 if (!isset($params['itemid'])) {
3763 throw new rating_exception('invaliditemid');
3766 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST
);
3767 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
), '*', MUST_EXIST
);
3768 $forum = $DB->get_record('forum', array('id' => $discussion->forum
), '*', MUST_EXIST
);
3769 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
3770 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
3772 // Perform some final capability checks.
3773 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3781 * This function prints the overview of a discussion in the forum listing.
3782 * It needs some discussion information and some post information, these
3783 * happen to be combined for efficiency in the $post parameter by the function
3784 * that calls this one: forum_print_latest_discussions()
3788 * @param object $post The post object (passed by reference for speed).
3789 * @param object $forum The forum object.
3790 * @param int $group Current group.
3791 * @param string $datestring Format to use for the dates.
3792 * @param boolean $cantrack Is tracking enabled for this forum.
3793 * @param boolean $forumtracked Is the user tracking this forum.
3794 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
3795 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
3797 function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
3798 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
3799 $canviewhiddentimedposts = false) {
3801 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
3804 static $strmarkalldread;
3806 if (empty($modcontext)) {
3807 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3808 print_error('invalidcoursemodule');
3810 $modcontext = context_module
::instance($cm->id
);
3813 if (!isset($rowcount)) {
3815 $strmarkalldread = get_string('markalldread', 'forum');
3817 $rowcount = ($rowcount +
1) %
2;
3820 $post->subject
= format_string($post->subject
,true);
3822 $timeddiscussion = !empty($CFG->forum_enabletimedposts
) && ($post->timestart ||
$post->timeend
);
3823 $timedoutsidewindow = '';
3824 if ($timeddiscussion && ($post->timestart
> time() ||
($post->timeend
!= 0 && $post->timeend
< time()))) {
3825 $timedoutsidewindow = ' dimmed_text';
3829 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
3831 $topicclass = 'topic starter';
3832 if (FORUM_DISCUSSION_PINNED
== $post->pinned
) {
3833 $topicclass .= ' pinned';
3835 echo '<td class="'.$topicclass.'">';
3836 if (FORUM_DISCUSSION_PINNED
== $post->pinned
) {
3837 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
3839 $canalwaysseetimedpost = $USER->id
== $post->userid ||
$canviewhiddentimedposts;
3840 if ($timeddiscussion && $canalwaysseetimedpost) {
3841 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
3844 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'">'.$post->subject
.'</a>';
3848 $postuser = new stdClass();
3849 $postuserfields = explode(',', user_picture
::fields());
3850 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3851 $postuser->id
= $post->userid
;
3852 echo '<td class="author">';
3853 echo '<div class="media">';
3854 echo '<span class="pull-left">';
3855 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course
));
3858 echo '<div class="media-body">';
3859 $fullname = fullname($postuser, has_capability('moodle/site:viewfullnames', $modcontext));
3860 echo '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$post->userid
.'&course='.$forum->course
.'">'.$fullname.'</a>';
3866 if ($group !== -1) { // Groups are active - group is a group data object or NULL
3867 echo '<td class="picture group">';
3868 if (!empty($group->picture
) and empty($group->hidepicture
)) {
3869 if ($canviewparticipants && $COURSE->groupmode
) {
3870 $picturelink = true;
3872 $picturelink = false;
3874 print_group_picture($group, $forum->course
, false, false, $picturelink);
3875 } else if (isset($group->id
)) {
3876 if ($canviewparticipants && $COURSE->groupmode
) {
3877 echo '<a href="'.$CFG->wwwroot
.'/user/index.php?id='.$forum->course
.'&group='.$group->id
.'">'.$group->name
.'</a>';
3885 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
3886 echo '<td class="replies">';
3887 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'">';
3888 echo $post->replies
.'</a>';
3892 echo '<td class="replies">';
3893 if ($forumtracked) {
3894 if ($post->unread
> 0) {
3895 echo '<span class="unread">';
3896 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'#unread">';
3899 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot
.'/mod/forum/markposts.php?f='.
3900 $forum->id
.'&d='.$post->discussion
.'&mark=read&returnpage=view.php&sesskey=' . sesskey() . '">' .
3901 $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
3904 echo '<span class="read">';
3909 echo '<span class="read">';
3917 echo '<td class="lastpost">';
3918 $usedate = (empty($post->timemodified
)) ?
$post->modified
: $post->timemodified
; // Just in case
3920 $usermodified = new stdClass();
3921 $usermodified->id
= $post->usermodified
;
3922 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
3924 // In QA forums we check that the user can view participants.
3925 if ($forum->type
!== 'qanda' ||
$canviewparticipants) {
3926 echo '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$post->usermodified
.'&course='.$forum->course
.'">'.
3927 fullname($usermodified).'</a><br />';
3928 $parenturl = (empty($post->lastpostid
)) ?
'' : '&parent='.$post->lastpostid
;
3931 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.$parenturl.'">'.
3932 userdate($usedate, $datestring).'</a>';
3935 // is_guest should be used here as this also checks whether the user is a guest in the current course.
3936 // Guests and visitors cannot subscribe - only enrolled users.
3937 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
3938 // Discussion subscription.
3939 if (\mod_forum\subscriptions
::is_subscribable($forum)) {
3940 echo '<td class="discussionsubscription">';
3941 echo forum_get_discussion_subscription_icon($forum, $post->discussion
);
3951 * Return the markup for the discussion subscription toggling icon.
3953 * @param stdClass $forum The forum object.
3954 * @param int $discussionid The discussion to create an icon for.
3955 * @return string The generated markup.
3957 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
3958 global $USER, $OUTPUT, $PAGE;
3960 if ($returnurl === null && $PAGE->url
) {
3961 $returnurl = $PAGE->url
->out();
3965 $subscriptionstatus = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum, $discussionid);
3966 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
3967 'sesskey' => sesskey(),
3969 'd' => $discussionid,
3970 'returnurl' => $returnurl,
3974 $o .= $subscriptionstatus ?
get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
3977 if ($subscriptionstatus) {
3978 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
3980 $output .= get_string('subscribed', 'mod_forum');
3983 return html_writer
::link($subscriptionlink, $output, array(
3984 'title' => get_string('clicktounsubscribe', 'forum'),
3985 'class' => 'discussiontoggle iconsmall',
3986 'data-forumid' => $forum->id
,
3987 'data-discussionid' => $discussionid,
3988 'data-includetext' => $includetext,
3992 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
3994 $output .= get_string('notsubscribed', 'mod_forum');
3997 return html_writer
::link($subscriptionlink, $output, array(
3998 'title' => get_string('clicktosubscribe', 'forum'),
3999 'class' => 'discussiontoggle iconsmall',
4000 'data-forumid' => $forum->id
,
4001 'data-discussionid' => $discussionid,
4002 'data-includetext' => $includetext,
4008 * Return a pair of spans containing classes to allow the subscribe and
4009 * unsubscribe icons to be pre-loaded by a browser.
4011 * @return string The generated markup
4013 function forum_get_discussion_subscription_icon_preloaders() {
4015 $o .= html_writer
::span(' ', 'preload-subscribe');
4016 $o .= html_writer
::span(' ', 'preload-unsubscribe');
4021 * Print the drop down that allows the user to select how they want to have
4022 * the discussion displayed.
4024 * @param int $id forum id if $forumtype is 'single',
4025 * discussion id for any other forum type
4026 * @param mixed $mode forum layout mode
4027 * @param string $forumtype optional
4029 function forum_print_mode_form($id, $mode, $forumtype='') {
4031 if ($forumtype == 'single') {
4032 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
4033 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
4034 $select->class = "forummode";
4036 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
4037 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
4039 echo $OUTPUT->render($select);
4044 * @param object $course
4045 * @param string $search
4048 function forum_search_form($course, $search='') {
4050 $forumsearch = new \mod_forum\output\
quick_search_form($course->id
, $search);
4051 $output = $PAGE->get_renderer('mod_forum');
4052 return $output->render($forumsearch);
4060 function forum_set_return() {
4061 global $CFG, $SESSION;
4063 if (! isset($SESSION->fromdiscussion
)) {
4064 $referer = get_local_referer(false);
4065 // If the referer is NOT a login screen then save it.
4066 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
4067 $SESSION->fromdiscussion
= $referer;
4075 * @param string|\moodle_url $default
4078 function forum_go_back_to($default) {
4081 if (!empty($SESSION->fromdiscussion
)) {
4082 $returnto = $SESSION->fromdiscussion
;
4083 unset($SESSION->fromdiscussion
);
4091 * Given a discussion object that is being moved to $forumto,
4092 * this function checks all posts in that discussion
4093 * for attachments, and if any are found, these are
4094 * moved to the new forum directory.
4097 * @param object $discussion
4098 * @param int $forumfrom source forum id
4099 * @param int $forumto target forum id
4100 * @return bool success
4102 function forum_move_attachments($discussion, $forumfrom, $forumto) {
4105 $fs = get_file_storage();
4107 $newcm = get_coursemodule_from_instance('forum', $forumto);
4108 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
4110 $newcontext = context_module
::instance($newcm->id
);
4111 $oldcontext = context_module
::instance($oldcm->id
);
4113 // loop through all posts, better not use attachment flag ;-)
4114 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id
), '', 'id, attachment')) {
4115 foreach ($posts as $post) {
4116 $fs->move_area_files_to_new_context($oldcontext->id
,
4117 $newcontext->id
, 'mod_forum', 'post', $post->id
);
4118 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id
,
4119 $newcontext->id
, 'mod_forum', 'attachment', $post->id
);
4120 if ($attachmentsmoved > 0 && $post->attachment
!= '1') {
4121 // Weird - let's fix it
4122 $post->attachment
= '1';
4123 $DB->update_record('forum_posts', $post);
4124 } else if ($attachmentsmoved == 0 && $post->attachment
!= '') {
4125 // Weird - let's fix it
4126 $post->attachment
= '';
4127 $DB->update_record('forum_posts', $post);
4136 * Returns attachments as formated text/html optionally with separate images
4141 * @param object $post
4143 * @param string $type html/text/separateimages
4144 * @return mixed string or array of (html text withouth images and image HTML)
4146 function forum_print_attachments($post, $cm, $type) {
4147 global $CFG, $DB, $USER, $OUTPUT;
4149 if (empty($post->attachment
)) {
4150 return $type !== 'separateimages' ?
'' : array('', '');
4153 if (!in_array($type, array('separateimages', 'html', 'text'))) {
4154 return $type !== 'separateimages' ?
'' : array('', '');
4157 if (!$context = context_module
::instance($cm->id
)) {
4158 return $type !== 'separateimages' ?
'' : array('', '');
4160 $strattachment = get_string('attachment', 'forum');
4162 $fs = get_file_storage();
4167 $canexport = !empty($CFG->enableportfolios
) && (has_capability('mod/forum:exportpost', $context) ||
($post->userid
== $USER->id
&& has_capability('mod/forum:exportownpost', $context)));
4170 require_once($CFG->libdir
.'/portfoliolib.php');
4173 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
4174 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
4175 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "filename", false);
4178 $button = new portfolio_add_button();
4180 foreach ($files as $file) {
4181 $filename = $file->get_filename();
4182 $mimetype = $file->get_mimetype();
4183 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
4184 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_forum/attachment/'.$post->id
.'/'.$filename);
4186 if ($type == 'html') {
4187 $output .= "<a href=\"$path\">$iconimage</a> ";
4188 $output .= "<a href=\"$path\">".s($filename)."</a>";
4190 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4191 $button->set_format_by_file($file);
4192 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4194 $output .= "<br />";
4196 } else if ($type == 'text') {
4197 $output .= "$strattachment ".s($filename).":\n$path\n";
4199 } else { //'returnimages'
4200 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
4201 // Image attachments don't get printed as links
4202 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
4204 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4205 $button->set_format_by_file($file);
4206 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4209 $output .= "<a href=\"$path\">$iconimage</a> ";
4210 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
4212 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4213 $button->set_format_by_file($file);
4214 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4216 $output .= '<br />';
4220 if (!empty($CFG->enableplagiarism
)) {
4221 require_once($CFG->libdir
.'/plagiarismlib.php');
4222 $output .= plagiarism_get_links(array('userid' => $post->userid
,
4225 'course' => $cm->course
,
4226 'forum' => $cm->instance
));
4227 $output .= '<br />';
4232 if ($type !== 'separateimages') {
4236 return array($output, $imagereturn);
4240 ////////////////////////////////////////////////////////////////////////////////
4242 ////////////////////////////////////////////////////////////////////////////////
4245 * Lists all browsable file areas
4247 * @package mod_forum
4249 * @param stdClass $course course object
4250 * @param stdClass $cm course module object
4251 * @param stdClass $context context object
4254 function forum_get_file_areas($course, $cm, $context) {
4256 'attachment' => get_string('areaattachment', 'mod_forum'),
4257 'post' => get_string('areapost', 'mod_forum'),
4262 * File browsing support for forum module.
4264 * @package mod_forum
4266 * @param stdClass $browser file browser object
4267 * @param stdClass $areas file areas
4268 * @param stdClass $course course object
4269 * @param stdClass $cm course module
4270 * @param stdClass $context context module
4271 * @param string $filearea file area
4272 * @param int $itemid item ID
4273 * @param string $filepath file path
4274 * @param string $filename file name
4275 * @return file_info instance or null if not found
4277 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4278 global $CFG, $DB, $USER;
4280 if ($context->contextlevel
!= CONTEXT_MODULE
) {
4284 // filearea must contain a real area
4285 if (!isset($areas[$filearea])) {
4289 // Note that forum_user_can_see_post() additionally allows access for parent roles
4290 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
4291 // course:managefiles, we will need to extend this.
4292 if (!has_capability('mod/forum:viewdiscussion', $context)) {
4296 if (is_null($itemid)) {
4297 require_once($CFG->dirroot
.'/mod/forum/locallib.php');
4298 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
4301 static $cached = array();
4302 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
4303 // is cleared between unit tests we check if this is the same session
4304 if (!isset($cached['sesskey']) ||
$cached['sesskey'] != sesskey()) {
4305 $cached = array('sesskey' => sesskey());
4308 if (isset($cached['post']) && $cached['post']->id
== $itemid) {
4309 $post = $cached['post'];
4310 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
4311 $cached['post'] = $post;
4316 if (isset($cached['discussion']) && $cached['discussion']->id
== $post->discussion
) {
4317 $discussion = $cached['discussion'];
4318 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
))) {
4319 $cached['discussion'] = $discussion;
4324 if (isset($cached['forum']) && $cached['forum']->id
== $cm->instance
) {
4325 $forum = $cached['forum'];
4326 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance
))) {
4327 $cached['forum'] = $forum;
4332 $fs = get_file_storage();
4333 $filepath = is_null($filepath) ?
'/' : $filepath;
4334 $filename = is_null($filename) ?
'.' : $filename;
4335 if (!($storedfile = $fs->get_file($context->id
, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
4339 // Checks to see if the user can manage files or is the owner.
4340 // TODO MDL-33805 - Do not use userid here and move the capability check above.
4341 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
4344 // Make sure groups allow this user to see this file
4345 if ($discussion->groupid
> 0 && !has_capability('moodle/site:accessallgroups', $context)) {
4346 $groupmode = groups_get_activity_groupmode($cm, $course);
4347 if ($groupmode == SEPARATEGROUPS
&& !groups_is_member($discussion->groupid
)) {
4352 // Make sure we're allowed to see it...
4353 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4357 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
4358 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
4362 * Serves the forum attachments. Implements needed access control ;-)
4364 * @package mod_forum
4366 * @param stdClass $course course object
4367 * @param stdClass $cm course module object
4368 * @param stdClass $context context object
4369 * @param string $filearea file area
4370 * @param array $args extra arguments
4371 * @param bool $forcedownload whether or not force download
4372 * @param array $options additional options affecting the file serving
4373 * @return bool false if file not found, does not return if found - justsend the file
4375 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
4378 if ($context->contextlevel
!= CONTEXT_MODULE
) {
4382 require_course_login($course, true, $cm);
4384 $areas = forum_get_file_areas($course, $cm, $context);
4386 // filearea must contain a real area
4387 if (!isset($areas[$filearea])) {
4391 $postid = (int)array_shift($args);
4393 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
4397 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion
))) {
4401 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance
))) {
4405 $fs = get_file_storage();
4406 $relativepath = implode('/', $args);
4407 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
4408 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4412 // Make sure groups allow this user to see this file
4413 if ($discussion->groupid
> 0) {
4414 $groupmode = groups_get_activity_groupmode($cm, $course);
4415 if ($groupmode == SEPARATEGROUPS
) {
4416 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
4422 // Make sure we're allowed to see it...
4423 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4427 // finally send the file
4428 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
4432 * If successful, this function returns the name of the file
4435 * @param object $post is a full post record, including course and forum
4436 * @param object $forum
4438 * @param mixed $mform
4439 * @param string $unused
4442 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
4445 if (empty($mform)) {
4449 if (empty($post->attachments
)) {
4450 return true; // Nothing to do
4453 $context = context_module
::instance($cm->id
);
4455 $info = file_get_draft_area_info($post->attachments
);
4456 $present = ($info['filecount']>0) ?
'1' : '';
4457 file_save_draft_area_files($post->attachments
, $context->id
, 'mod_forum', 'attachment', $post->id
,
4458 mod_forum_post_form
::attachment_options($forum));
4460 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id
));
4466 * Add a new post in an existing discussion.
4468 * @param stdClass $post The post data
4469 * @param mixed $mform The submitted form
4470 * @param string $unused
4473 function forum_add_new_post($post, $mform, $unused = null) {
4476 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
4477 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
4478 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4479 $context = context_module
::instance($cm->id
);
4481 $post->created
= $post->modified
= time();
4482 $post->mailed
= FORUM_MAILED_PENDING
;
4483 $post->userid
= $USER->id
;
4484 $post->attachment
= "";
4485 if (!isset($post->totalscore
)) {
4486 $post->totalscore
= 0;
4488 if (!isset($post->mailnow
)) {
4492 $post->id
= $DB->insert_record("forum_posts", $post);
4493 $post->message
= file_save_draft_area_files($post->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4494 mod_forum_post_form
::editor_options($context, null), $post->message
);
4495 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
4496 forum_add_attachment($post, $forum, $cm, $mform);
4498 // Update discussion modified date
4499 $DB->set_field("forum_discussions", "timemodified", $post->modified
, array("id" => $post->discussion
));
4500 $DB->set_field("forum_discussions", "usermodified", $post->userid
, array("id" => $post->discussion
));
4502 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4503 forum_tp_mark_post_read($post->userid
, $post);
4506 if (isset($post->tags
)) {
4507 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, $context, $post->tags
);
4510 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4511 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
4519 * @param stdClass $newpost The post to update
4520 * @param mixed $mform The submitted form
4521 * @param string $unused
4524 function forum_update_post($newpost, $mform, $unused = null) {
4527 $post = $DB->get_record('forum_posts', array('id' => $newpost->id
));
4528 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
4529 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
4530 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4531 $context = context_module
::instance($cm->id
);
4533 // Allowed modifiable fields.
4534 $modifiablefields = [
4544 foreach ($modifiablefields as $field) {
4545 if (isset($newpost->{$field})) {
4546 $post->{$field} = $newpost->{$field};
4549 $post->modified
= time();
4551 // Last post modified tracking.
4552 $discussion->timemodified
= $post->modified
;
4553 $discussion->usermodified
= $post->userid
;
4555 if (!$post->parent
) { // Post is a discussion starter - update discussion title and times too
4556 $discussion->name
= $post->subject
;
4557 $discussion->timestart
= $post->timestart
;
4558 $discussion->timeend
= $post->timeend
;
4560 if (isset($post->pinned
)) {
4561 $discussion->pinned
= $post->pinned
;
4564 $post->message
= file_save_draft_area_files($newpost->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4565 mod_forum_post_form
::editor_options($context, $post->id
), $post->message
);
4566 $DB->update_record('forum_posts', $post);
4567 $DB->update_record('forum_discussions', $discussion);
4569 forum_add_attachment($post, $forum, $cm, $mform);
4571 if (isset($newpost->tags
)) {
4572 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, $context, $newpost->tags
);
4575 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4576 forum_tp_mark_post_read($USER->id
, $post);
4579 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4580 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
4586 * Given an object containing all the necessary data,
4587 * create a new discussion and return the id
4589 * @param object $post
4590 * @param mixed $mform
4591 * @param string $unused
4592 * @param int $userid
4595 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
4596 global $USER, $CFG, $DB;
4598 $timenow = isset($discussion->timenow
) ?
$discussion->timenow
: time();
4600 if (is_null($userid)) {
4601 $userid = $USER->id
;
4604 // The first post is stored as a real post, and linked
4605 // to from the discuss entry.
4607 $forum = $DB->get_record('forum', array('id'=>$discussion->forum
));
4608 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4610 $post = new stdClass();
4611 $post->discussion
= 0;
4613 $post->userid
= $userid;
4614 $post->created
= $timenow;
4615 $post->modified
= $timenow;
4616 $post->mailed
= FORUM_MAILED_PENDING
;
4617 $post->subject
= $discussion->name
;
4618 $post->message
= $discussion->message
;
4619 $post->messageformat
= $discussion->messageformat
;
4620 $post->messagetrust
= $discussion->messagetrust
;
4621 $post->attachments
= isset($discussion->attachments
) ?
$discussion->attachments
: null;
4622 $post->forum
= $forum->id
; // speedup
4623 $post->course
= $forum->course
; // speedup
4624 $post->mailnow
= $discussion->mailnow
;
4626 $post->id
= $DB->insert_record("forum_posts", $post);
4628 // TODO: Fix the calling code so that there always is a $cm when this function is called
4629 if (!empty($cm->id
) && !empty($discussion->itemid
)) { // In "single simple discussions" this may not exist yet
4630 $context = context_module
::instance($cm->id
);
4631 $text = file_save_draft_area_files($discussion->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4632 mod_forum_post_form
::editor_options($context, null), $post->message
);
4633 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id
));
4636 // Now do the main entry for the discussion, linking to this first post
4638 $discussion->firstpost
= $post->id
;
4639 $discussion->timemodified
= $timenow;
4640 $discussion->usermodified
= $post->userid
;
4641 $discussion->userid
= $userid;
4642 $discussion->assessed
= 0;
4644 $post->discussion
= $DB->insert_record("forum_discussions", $discussion);
4646 // Finally, set the pointer on the post.
4647 $DB->set_field("forum_posts", "discussion", $post->discussion
, array("id"=>$post->id
));
4649 if (!empty($cm->id
)) {
4650 forum_add_attachment($post, $forum, $cm, $mform, $unused);
4653 if (isset($discussion->tags
)) {
4654 core_tag_tag
::set_item_tags('mod_forum', 'forum_posts', $post->id
, context_module
::instance($cm->id
), $discussion->tags
);
4657 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4658 forum_tp_mark_post_read($post->userid
, $post);
4661 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4662 if (!empty($cm->id
)) {
4663 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
4666 return $post->discussion
;
4671 * Deletes a discussion and handles all associated cleanup.
4674 * @param object $discussion Discussion to delete
4675 * @param bool $fulldelete True when deleting entire forum
4676 * @param object $course Course
4677 * @param object $cm Course-module
4678 * @param object $forum Forum
4681 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
4683 require_once($CFG->libdir
.'/completionlib.php');
4687 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id
))) {
4688 foreach ($posts as $post) {
4689 $post->course
= $discussion->course
;
4690 $post->forum
= $discussion->forum
;
4691 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
4697 forum_tp_delete_read_records(-1, -1, $discussion->id
);
4699 // Discussion subscriptions must be removed before discussions because of key constraints.
4700 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id
));
4701 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id
))) {
4705 // Update completion state if we are tracking completion based on number of posts
4706 // But don't bother when deleting whole thing
4708 $completion = new completion_info($course);
4709 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
4710 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
4711 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $discussion->userid
);
4720 * Deletes a single forum post.
4723 * @param object $post Forum post object
4724 * @param mixed $children Whether to delete children. If false, returns false
4725 * if there are any children (without deleting the post). If true,
4726 * recursively deletes all children. If set to special value 'ignore', deletes
4727 * post regardless of children (this is for use only when deleting all posts
4729 * @param object $course Course
4730 * @param object $cm Course-module
4731 * @param object $forum Forum
4732 * @param bool $skipcompletion True to skip updating completion state if it
4733 * would otherwise be updated, i.e. when deleting entire forum anyway.
4736 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
4737 global $DB, $CFG, $USER;
4738 require_once($CFG->libdir
.'/completionlib.php');
4740 $context = context_module
::instance($cm->id
);
4742 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id
)))) {
4744 foreach ($childposts as $childpost) {
4745 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
4753 require_once($CFG->dirroot
.'/rating/lib.php');
4754 $delopt = new stdClass
;
4755 $delopt->contextid
= $context->id
;
4756 $delopt->component
= 'mod_forum';
4757 $delopt->ratingarea
= 'post';
4758 $delopt->itemid
= $post->id
;
4759 $rm = new rating_manager();
4760 $rm->delete_ratings($delopt);
4762 // Delete attachments.
4763 $fs = get_file_storage();
4764 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment', $post->id
);
4765 $fs->delete_area_files($context->id
, 'mod_forum', 'post', $post->id
);
4767 // Delete cached RSS feeds.
4768 if (!empty($CFG->enablerssfeeds
)) {
4769 require_once($CFG->dirroot
.'/mod/forum/rsslib.php');
4770 forum_rss_delete_file($forum);
4773 if ($DB->delete_records("forum_posts", array("id" => $post->id
))) {
4775 forum_tp_delete_read_records(-1, $post->id
);
4777 // Just in case we are deleting the last post
4778 forum_discussion_update_last_post($post->discussion
);
4780 // Update completion state if we are tracking completion based on number of posts
4781 // But don't bother when deleting whole thing
4783 if (!$skipcompletion) {
4784 $completion = new completion_info($course);
4785 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
4786 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
4787 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $post->userid
);
4792 'context' => $context,
4793 'objectid' => $post->id
,
4795 'discussionid' => $post->discussion
,
4796 'forumid' => $forum->id
,
4797 'forumtype' => $forum->type
,
4801 if ($post->userid
!== $USER->id
) {
4802 $params['relateduserid'] = $post->userid
;
4804 $event = \mod_forum\event\post_deleted
::create($params);
4805 $event->add_record_snapshot('forum_posts', $post);
4814 * Sends post content to plagiarism plugin
4815 * @param object $post Forum post object
4816 * @param object $cm Course-module
4817 * @param string $name
4820 function forum_trigger_content_uploaded_event($post, $cm, $name) {
4821 $context = context_module
::instance($cm->id
);
4822 $fs = get_file_storage();
4823 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "timemodified", false);
4825 'context' => $context,
4826 'objectid' => $post->id
,
4828 'content' => $post->message
,
4829 'pathnamehashes' => array_keys($files),
4830 'discussionid' => $post->discussion
,
4831 'triggeredfrom' => $name,
4834 $event = \mod_forum\event\assessable_uploaded
::create($params);
4841 * @param object $post
4842 * @param bool $children
4845 function forum_count_replies($post, $children=true) {
4850 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id
))) {
4851 foreach ($childposts as $childpost) {
4852 $count ++
; // For this child
4853 $count +
= forum_count_replies($childpost, true);
4857 $count +
= $DB->count_records('forum_posts', array('parent' => $post->id
));
4864 * Given a new post, subscribes or unsubscribes as appropriate.
4865 * Returns some text which describes what happened.
4867 * @param object $fromform The submitted form
4868 * @param stdClass $forum The forum record
4869 * @param stdClass $discussion The forum discussion record
4872 function forum_post_subscription($fromform, $forum, $discussion) {
4875 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
4877 } else if (\mod_forum\subscriptions
::subscription_disabled($forum)) {
4878 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
4879 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course
::instance($forum->course
), $USER->id
)) {
4880 // This user should not be subscribed to the forum.
4881 \mod_forum\subscriptions
::unsubscribe_user($USER->id
, $forum);
4886 $info = new stdClass();
4887 $info->name
= fullname($USER);
4888 $info->discussion
= format_string($discussion->name
);
4889 $info->forum
= format_string($forum->name
);
4891 if (isset($fromform->discussionsubscribe
) && $fromform->discussionsubscribe
) {
4892 if ($result = \mod_forum\subscriptions
::subscribe_user_to_discussion($USER->id
, $discussion)) {
4893 return html_writer
::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
4896 if ($result = \mod_forum\subscriptions
::unsubscribe_user_from_discussion($USER->id
, $discussion)) {
4897 return html_writer
::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
4905 * Generate and return the subscribe or unsubscribe link for a forum.
4907 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
4908 * @param object $context the context object for this forum.
4909 * @param array $messages text used for the link in its various states
4910 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
4911 * Any strings not passed in are taken from the $defaultmessages array
4912 * at the top of the function.
4913 * @param bool $cantaccessagroup
4914 * @param bool $unused1
4915 * @param bool $backtoindex
4916 * @param array $unused2
4919 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true,
4920 $backtoindex = false, $unused2 = null) {
4921 global $CFG, $USER, $PAGE, $OUTPUT;
4922 $defaultmessages = array(
4923 'subscribed' => get_string('unsubscribe', 'forum'),
4924 'unsubscribed' => get_string('subscribe', 'forum'),
4925 'cantaccessgroup' => get_string('no'),
4926 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
4927 'cantsubscribe' => get_string('disallowsubscribe','forum')
4929 $messages = $messages +
$defaultmessages;
4931 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
4932 return $messages['forcesubscribed'];
4933 } else if (\mod_forum\subscriptions
::subscription_disabled($forum) &&
4934 !has_capability('mod/forum:managesubscriptions', $context)) {
4935 return $messages['cantsubscribe'];
4936 } else if ($cantaccessagroup) {
4937 return $messages['cantaccessgroup'];
4939 if (!is_enrolled($context, $USER, '', true)) {
4943 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
4945 $linktext = $messages['subscribed'];
4946 $linktitle = get_string('subscribestop', 'forum');
4948 $linktext = $messages['unsubscribed'];
4949 $linktitle = get_string('subscribestart', 'forum');
4954 $backtoindexlink = '&backtoindex=1';
4955 $options['backtoindex'] = 1;
4957 $backtoindexlink = '';
4960 $options['id'] = $forum->id
;
4961 $options['sesskey'] = sesskey();
4962 $url = new moodle_url('/mod/forum/subscribe.php', $options);
4963 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle));
4968 * Returns true if user created new discussion already.
4970 * @param int $forumid The forum to check for postings
4971 * @param int $userid The user to check for postings
4972 * @param int $groupid The group to restrict the check to
4975 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) {
4979 FROM {forum_discussions} d, {forum_posts} p
4980 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?";
4982 $params = [$forumid, $userid];
4985 $sql .= " AND d.groupid = ?";
4986 $params[] = $groupid;
4989 return $DB->record_exists_sql($sql, $params);
4995 * @param int $forumid
4996 * @param int $userid
4999 function forum_discussions_user_has_posted_in($forumid, $userid) {
5002 $haspostedsql = "SELECT d.id AS id,
5004 FROM {forum_posts} p,
5005 {forum_discussions} d
5006 WHERE p.discussion = d.id
5010 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
5016 * @param int $forumid
5018 * @param int $userid
5021 function forum_user_has_posted($forumid, $did, $userid) {
5025 // posted in any forum discussion?
5027 FROM {forum_posts} p
5028 JOIN {forum_discussions} d ON d.id = p.discussion
5029 WHERE p.userid = :userid AND d.forum = :forumid";
5030 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
5032 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
5037 * Returns creation time of the first user's post in given discussion
5038 * @global object $DB
5039 * @param int $did Discussion id
5040 * @param int $userid User id
5041 * @return int|bool post creation time stamp or return false
5043 function forum_get_user_posted_time($did, $userid) {
5046 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
5047 if (empty($posttime)) {
5055 * @param object $forum
5056 * @param object $currentgroup
5057 * @param int $unused
5059 * @param object $context
5062 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
5063 // $forum is an object
5066 // shortcut - guest and not-logged-in users can not post
5067 if (isguestuser() or !isloggedin()) {
5072 debugging('missing cm', DEBUG_DEVELOPER
);
5073 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5074 print_error('invalidcoursemodule');
5079 $context = context_module
::instance($cm->id
);
5082 if ($currentgroup === null) {
5083 $currentgroup = groups_get_activity_group($cm);
5086 $groupmode = groups_get_activity_groupmode($cm);
5088 if ($forum->type
== 'news') {
5089 $capname = 'mod/forum:addnews';
5090 } else if ($forum->type
== 'qanda') {
5091 $capname = 'mod/forum:addquestion';
5093 $capname = 'mod/forum:startdiscussion';
5096 if (!has_capability($capname, $context)) {
5100 if ($forum->type
== 'single') {
5104 if ($forum->type
== 'eachuser') {
5105 if (forum_user_has_posted_discussion($forum->id
, $USER->id
, $currentgroup)) {
5110 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
5114 if ($currentgroup) {
5115 return groups_is_member($currentgroup);
5117 // no group membership and no accessallgroups means no new discussions
5118 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
5124 * This function checks whether the user can reply to posts in a forum
5125 * discussion. Use forum_user_can_post_discussion() to check whether the user
5126 * can start discussions.
5130 * @uses DEBUG_DEVELOPER
5131 * @uses CONTEXT_MODULE
5132 * @uses VISIBLEGROUPS
5133 * @param object $forum forum object
5134 * @param object $discussion
5135 * @param object $user
5137 * @param object $course
5138 * @param object $context
5141 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
5147 // shortcut - guest and not-logged-in users can not post
5148 if (isguestuser($user) or empty($user->id
)) {
5152 if (!isset($discussion->groupid
)) {
5153 debugging('incorrect discussion parameter', DEBUG_DEVELOPER
);
5158 debugging('missing cm', DEBUG_DEVELOPER
);
5159 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5160 print_error('invalidcoursemodule');
5165 debugging('missing course', DEBUG_DEVELOPER
);
5166 if (!$course = $DB->get_record('course', array('id' => $forum->course
))) {
5167 print_error('invalidcourseid');
5172 $context = context_module
::instance($cm->id
);
5175 // Check whether the discussion is locked.
5176 if (forum_discussion_is_locked($forum, $discussion)) {
5177 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) {
5182 // normal users with temporary guest access can not post, suspended users can not post either
5183 if (!is_viewing($context, $user->id
) and !is_enrolled($context, $user->id
, '', true)) {
5187 if ($forum->type
== 'news') {
5188 $capname = 'mod/forum:replynews';
5190 $capname = 'mod/forum:replypost';
5193 if (!has_capability($capname, $context, $user->id
)) {
5197 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
5201 if (has_capability('moodle/site:accessallgroups', $context)) {
5205 if ($groupmode == VISIBLEGROUPS
) {
5206 if ($discussion->groupid
== -1) {
5207 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
5210 return groups_is_member($discussion->groupid
);
5214 if ($discussion->groupid
== -1) {
5217 return groups_is_member($discussion->groupid
);
5222 * Check to ensure a user can view a timed discussion.
5224 * @param object $discussion
5225 * @param object $user
5226 * @param object $context
5227 * @return boolean returns true if they can view post, false otherwise
5229 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
5232 // Check that the user can view a discussion that is normally hidden due to access times.
5233 if (!empty($CFG->forum_enabletimedposts
)) {
5235 if (($discussion->timestart
!= 0 && $discussion->timestart
> $time)
5236 ||
($discussion->timeend
!= 0 && $discussion->timeend
< $time)) {
5237 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id
)) {
5247 * Check to ensure a user can view a group discussion.
5249 * @param object $discussion
5251 * @param object $context
5252 * @return boolean returns true if they can view post, false otherwise
5254 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
5256 // If it's a grouped discussion, make sure the user is a member.
5257 if ($discussion->groupid
> 0) {
5258 $groupmode = groups_get_activity_groupmode($cm);
5259 if ($groupmode == SEPARATEGROUPS
) {
5260 return groups_is_member($discussion->groupid
) ||
has_capability('moodle/site:accessallgroups', $context);
5270 * @uses DEBUG_DEVELOPER
5271 * @param object $forum
5272 * @param object $discussion
5273 * @param object $context
5274 * @param object $user
5277 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
5280 if (empty($user) ||
empty($user->id
)) {
5284 // retrieve objects (yuk)
5285 if (is_numeric($forum)) {
5286 debugging('missing full forum', DEBUG_DEVELOPER
);
5287 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5291 if (is_numeric($discussion)) {
5292 debugging('missing full discussion', DEBUG_DEVELOPER
);
5293 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5297 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5298 print_error('invalidcoursemodule');
5301 if (!has_capability('mod/forum:viewdiscussion', $context)) {
5305 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
5309 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
5317 * Check whether a user can see the specified post.
5319 * @param \stdClass $forum The forum to chcek
5320 * @param \stdClass $discussion The discussion the post is in
5321 * @param \stdClass $post The post in question
5322 * @param \stdClass $user The user to test - if not specified, the current user is checked.
5323 * @param \stdClass $cm The Course Module that the forum is in (required).
5324 * @param bool $checkdeleted Whether to check the deleted flag on the post.
5327 function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) {
5328 global $CFG, $USER, $DB;
5330 // retrieve objects (yuk)
5331 if (is_numeric($forum)) {
5332 debugging('missing full forum', DEBUG_DEVELOPER
);
5333 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5338 if (is_numeric($discussion)) {
5339 debugging('missing full discussion', DEBUG_DEVELOPER
);
5340 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5344 if (is_numeric($post)) {
5345 debugging('missing full post', DEBUG_DEVELOPER
);
5346 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
5351 if (!isset($post->id
) && isset($post->parent
)) {
5352 $post->id
= $post->parent
;
5355 if ($checkdeleted && !empty($post->deleted
)) {
5360 debugging('missing cm', DEBUG_DEVELOPER
);
5361 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5362 print_error('invalidcoursemodule');
5366 // Context used throughout function.
5367 $modcontext = context_module
::instance($cm->id
);
5369 if (empty($user) ||
empty($user->id
)) {
5373 $canviewdiscussion = (isset($cm->cache
) && !empty($cm->cache
->caps
['mod/forum:viewdiscussion']))
5374 ||
has_capability('mod/forum:viewdiscussion', $modcontext, $user->id
);
5375 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user
::instance($post->userid
))) {
5379 if (isset($cm->uservisible
)) {
5380 if (!$cm->uservisible
) {
5384 if (!\core_availability\info_module
::is_user_visible($cm, $user->id
, false)) {
5389 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
5393 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
5397 if ($forum->type
== 'qanda') {
5398 if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id
) ||
$post->userid
== $user->id
5399 ||
(isset($discussion->firstpost
) && $discussion->firstpost
== $post->id
)) {
5402 $firstpost = forum_get_firstpost_from_discussion($discussion->id
);
5403 if ($firstpost->userid
== $user->id
) {
5406 $userfirstpost = forum_get_user_posted_time($discussion->id
, $user->id
);
5407 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime
)));
5414 * Prints the discussion view screen for a forum.
5418 * @param object $course The current course object.
5419 * @param object $forum Forum to be printed.
5420 * @param int $maxdiscussions .
5421 * @param string $displayformat The display format to use (optional).
5422 * @param string $sort Sort arguments for database query (optional).
5423 * @param int $groupmode Group mode of the forum (optional).
5424 * @param void $unused (originally current group)
5425 * @param int $page Page mode, page to display (optional).
5426 * @param int $perpage The maximum number of discussions per page(optional)
5427 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
5430 function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '',
5431 $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null) {
5432 global $CFG, $USER, $OUTPUT;
5434 require_once($CFG->dirroot
. '/course/lib.php');
5437 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5438 print_error('invalidcoursemodule');
5441 $context = context_module
::instance($cm->id
);
5444 $sort = forum_get_default_sort_order();
5447 $olddiscussionlink = false;
5449 // Sort out some defaults
5450 if ($perpage <= 0) {
5455 if ($maxdiscussions == 0) {
5456 // all discussions - backwards compatibility
5459 if ($displayformat == 'plain') {
5460 $displayformat = 'header'; // Abbreviate display by default
5463 } else if ($maxdiscussions > 0) {
5465 $perpage = $maxdiscussions;
5469 if ($displayformat == 'plain') {
5474 // Decide if current user is allowed to see ALL the current discussions or not
5476 // First check the group stuff
5477 if ($currentgroup == -1 or $groupmode == -1) {
5478 $groupmode = groups_get_activity_groupmode($cm, $course);
5479 $currentgroup = groups_get_activity_group($cm);
5482 $groups = array(); //cache
5484 // If the user can post discussions, then this is a good place to put the
5485 // button for it. We do not show the button if we are showing site news
5486 // and the current user is a guest.
5488 $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
5489 if (!$canstart and $forum->type
!== 'news') {
5490 if (isguestuser() or !isloggedin()) {
5493 if (!is_enrolled($context) and !is_viewing($context)) {
5494 // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
5495 // normal users with temporary guest access see this button too, they are asked to enrol instead
5496 // do not show the button to users with suspended enrolments here
5497 $canstart = enrol_selfenrol_available($course->id
);
5502 switch ($forum->type
) {
5505 $buttonadd = get_string('addanewtopic', 'forum');
5508 $buttonadd = get_string('addanewquestion', 'forum');
5511 $buttonadd = get_string('addanewdiscussion', 'forum');
5514 $button = new single_button(new moodle_url('/mod/forum/post.php', ['forum' => $forum->id
]), $buttonadd, 'get');
5515 $button->class = 'singlebutton forumaddnew';
5516 $button->formid
= 'newdiscussionform';
5517 echo $OUTPUT->render($button);
5519 } else if (isguestuser() or !isloggedin() or $forum->type
== 'news' or
5520 $forum->type
== 'qanda' and !has_capability('mod/forum:addquestion', $context) or
5521 $forum->type
!= 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
5522 // no button and no info
5524 } else if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
5525 // inform users why they can not post new discussion
5526 if (!$currentgroup) {
5527 echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
5528 } else if (!groups_is_member($currentgroup)) {
5529 echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
5533 // Get all the recent discussions we're allowed to see
5535 $getuserlastmodified = ($displayformat == 'header');
5537 if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
5538 echo '<div class="forumnodiscuss">';
5539 if ($forum->type
== 'news') {
5540 echo '('.get_string('nonews', 'forum').')';
5541 } else if ($forum->type
== 'qanda') {
5542 echo '('.get_string('noquestions','forum').')';
5544 echo '('.get_string('nodiscussions', 'forum').')';
5550 // If we want paging
5552 ///Get the number of discussions found
5553 $numdiscussions = forum_get_discussions_count($cm);
5555 ///Show the paging bar
5556 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5557 if ($numdiscussions > 1000) {
5558 // saves some memory on sites with very large forums
5559 $replies = forum_count_discussion_replies($forum->id
, $sort, $maxdiscussions, $page, $perpage);
5561 $replies = forum_count_discussion_replies($forum->id
);
5565 $replies = forum_count_discussion_replies($forum->id
);
5567 if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
5568 $olddiscussionlink = true;
5572 $canviewparticipants = course_can_view_participants($context);
5573 $canviewhiddentimedposts = has_capability('mod/forum:viewhiddentimedposts', $context);
5575 $strdatestring = get_string('strftimerecentfull');
5577 // Check if the forum is tracked.
5578 if ($cantrack = forum_tp_can_track_forums($forum)) {
5579 $forumtracked = forum_tp_is_tracked($forum);
5581 $forumtracked = false;
5584 if ($forumtracked) {
5585 $unreads = forum_get_discussions_unread($cm);
5590 if ($displayformat == 'header') {
5591 echo '<table cellspacing="0" class="forumheaderlist">';
5594 echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
5595 echo '<th class="header author" scope="col">'.get_string('startedby', 'forum').'</th>';
5596 if ($groupmode > 0) {
5597 echo '<th class="header group" scope="col">'.get_string('group').'</th>';
5599 if (has_capability('mod/forum:viewdiscussion', $context)) {
5600 echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
5601 // If the forum can be tracked, display the unread column.
5603 echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
5604 if ($forumtracked) {
5605 echo '<a title="'.get_string('markallread', 'forum').
5606 '" href="'.$CFG->wwwroot
.'/mod/forum/markposts.php?f='.
5607 $forum->id
.'&mark=read&returnpage=view.php&sesskey=' . sesskey() . '">'.
5608 $OUTPUT->pix_icon('t/markasread', get_string('markallread', 'forum')) . '</a>';
5613 echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
5614 if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $context)) {
5615 if (\mod_forum\subscriptions
::is_subscribable($forum)) {
5616 echo '<th class="header discussionsubscription" scope="col">';
5617 echo forum_get_discussion_subscription_icon_preloaders();
5626 foreach ($discussions as $discussion) {
5627 if ($forum->type
== 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) &&
5628 !forum_user_has_posted($forum->id
, $discussion->discussion
, $USER->id
)) {
5629 $canviewparticipants = false;
5632 if (!empty($replies[$discussion->discussion
])) {
5633 $discussion->replies
= $replies[$discussion->discussion
]->replies
;
5634 $discussion->lastpostid
= $replies[$discussion->discussion
]->lastpostid
;
5636 $discussion->replies
= 0;
5639 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
5640 // All posts are read in this case.
5641 if (!$forumtracked) {
5642 $discussion->unread
= '-';
5643 } else if (empty($USER)) {
5644 $discussion->unread
= 0;
5646 if (empty($unreads[$discussion->discussion
])) {
5647 $discussion->unread
= 0;
5649 $discussion->unread
= $unreads[$discussion->discussion
];
5654 $ownpost = ($discussion->userid
== $USER->id
);
5658 // Use discussion name instead of subject of first post.
5659 $discussion->subject
= $discussion->name
;
5661 switch ($displayformat) {
5663 if ($groupmode > 0) {
5664 if (isset($groups[$discussion->groupid
])) {
5665 $group = $groups[$discussion->groupid
];
5667 $group = $groups[$discussion->groupid
] = groups_get_group($discussion->groupid
);
5672 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
5673 $canviewparticipants, $context, $canviewhiddentimedposts);
5678 if ($discussion->replies
) {
5681 $modcontext = context_module
::instance($cm->id
);
5682 $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
5685 $discussion->forum
= $forum->id
;
5687 forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
5688 '', null, true, $forumtracked);
5693 if ($displayformat == "header") {
5698 if ($olddiscussionlink) {
5699 if ($forum->type
== 'news') {
5700 $strolder = get_string('oldertopics', 'forum');
5702 $strolder = get_string('olderdiscussions', 'forum');
5704 echo '<div class="forumolddiscuss">';
5705 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/view.php?f='.$forum->id
.'&showall=1">';
5706 echo $strolder.'</a> ...</div>';
5709 if ($page != -1) { ///Show the paging bar
5710 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5716 * Prints a forum discussion
5718 * @uses CONTEXT_MODULE
5719 * @uses FORUM_MODE_FLATNEWEST
5720 * @uses FORUM_MODE_FLATOLDEST
5721 * @uses FORUM_MODE_THREADED
5722 * @uses FORUM_MODE_NESTED
5723 * @param stdClass $course
5724 * @param stdClass $cm
5725 * @param stdClass $forum
5726 * @param stdClass $discussion
5727 * @param stdClass $post
5729 * @param mixed $canreply
5730 * @param bool $canrate
5732 function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
5735 require_once($CFG->dirroot
.'/rating/lib.php');
5737 $ownpost = (isloggedin() && $USER->id
== $post->userid
);
5739 $modcontext = context_module
::instance($cm->id
);
5740 if ($canreply === NULL) {
5741 $reply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
5746 // $cm holds general cache for forum functions
5747 $cm->cache
= new stdClass
;
5748 $cm->cache
->groups
= groups_get_all_groups($course->id
, 0, $cm->groupingid
);
5749 $cm->cache
->usersgroups
= array();
5753 // preload all posts - TODO: improve...
5754 if ($mode == FORUM_MODE_FLATNEWEST
) {
5755 $sort = "p.created DESC";
5757 $sort = "p.created ASC";
5760 $forumtracked = forum_tp_is_tracked($forum);
5761 $posts = forum_get_all_discussion_posts($discussion->id
, $sort, $forumtracked);
5762 $post = $posts[$post->id
];
5764 foreach ($posts as $pid=>$p) {
5765 $posters[$p->userid
] = $p->userid
;
5768 // preload all groups of ppl that posted in this discussion
5769 if ($postersgroups = groups_get_all_groups($course->id
, $posters, $cm->groupingid
, 'gm.id, gm.groupid, gm.userid')) {
5770 foreach($postersgroups as $pg) {
5771 if (!isset($cm->cache
->usersgroups
[$pg->userid
])) {
5772 $cm->cache
->usersgroups
[$pg->userid
] = array();
5774 $cm->cache
->usersgroups
[$pg->userid
][$pg->groupid
] = $pg->groupid
;
5776 unset($postersgroups);
5780 if ($forum->assessed
!= RATING_AGGREGATE_NONE
) {
5781 $ratingoptions = new stdClass
;
5782 $ratingoptions->context
= $modcontext;
5783 $ratingoptions->component
= 'mod_forum';
5784 $ratingoptions->ratingarea
= 'post';
5785 $ratingoptions->items
= $posts;
5786 $ratingoptions->aggregate
= $forum->assessed
;//the aggregation method
5787 $ratingoptions->scaleid
= $forum->scale
;
5788 $ratingoptions->userid
= $USER->id
;
5789 if ($forum->type
== 'single' or !$discussion->id
) {
5790 $ratingoptions->returnurl
= "$CFG->wwwroot/mod/forum/view.php?id=$cm->id";
5792 $ratingoptions->returnurl
= "$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id";
5794 $ratingoptions->assesstimestart
= $forum->assesstimestart
;
5795 $ratingoptions->assesstimefinish
= $forum->assesstimefinish
;
5797 $rm = new rating_manager();
5798 $posts = $rm->get_ratings($ratingoptions);
5802 $post->forum
= $forum->id
; // Add the forum id to the post object, later used by forum_print_post
5803 $post->forumtype
= $forum->type
;
5805 $post->subject
= format_string($post->subject
);
5807 $postread = !empty($post->postread
);
5809 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false,
5810 '', '', $postread, true, $forumtracked);
5813 case FORUM_MODE_FLATOLDEST
:
5814 case FORUM_MODE_FLATNEWEST
:
5816 forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts);
5819 case FORUM_MODE_THREADED
:
5820 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $reply, $forumtracked, $posts);
5823 case FORUM_MODE_NESTED
:
5824 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5833 * @uses FORUM_MODE_FLATNEWEST
5834 * @param object $course
5836 * @param object $forum
5837 * @param object $discussion
5838 * @param object $post
5839 * @param object $mode
5840 * @param bool $reply
5841 * @param bool $forumtracked
5842 * @param array $posts
5845 function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts) {
5850 foreach ($posts as $post) {
5851 if (!$post->parent
) {
5854 $post->subject
= format_string($post->subject
);
5855 $ownpost = ($USER->id
== $post->userid
);
5857 $postread = !empty($post->postread
);
5859 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5860 '', '', $postread, true, $forumtracked);
5865 * @todo Document this function
5869 * @uses CONTEXT_MODULE
5872 function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $reply, $forumtracked, $posts) {
5877 if (!empty($posts[$parent->id
]->children
)) {
5878 $posts = $posts[$parent->id
]->children
;
5880 $modcontext = context_module
::instance($cm->id
);
5881 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
5883 foreach ($posts as $post) {
5885 echo '<div class="indent">';
5887 $ownpost = ($USER->id
== $post->userid
);
5888 $post->subject
= format_string($post->subject
);
5890 $postread = !empty($post->postread
);
5892 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5893 '', '', $postread, true, $forumtracked);
5895 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm, true)) {
5896 if (forum_user_can_see_post($forum, $discussion, $post, null, $cm, false)) {
5897 // This post has been deleted but still exists and may have children.
5898 $subject = get_string('privacy:request:delete:post:subject', 'mod_forum');
5901 // The user can't see this post at all.
5906 $by = new stdClass();
5907 $by->name
= fullname($post, $canviewfullnames);
5908 $by->date
= userdate($post->modified
);
5909 $byline = ' ' . get_string("bynameondate", "forum", $by);
5910 $subject = format_string($post->subject
, true);
5913 if ($forumtracked) {
5914 if (!empty($post->postread
)) {
5915 $style = '<span class="forumthread read">';
5917 $style = '<span class="forumthread unread">';
5920 $style = '<span class="forumthread">';
5924 echo "<a name='{$post->id}'></a>";
5925 echo html_writer
::link(new moodle_url('/mod/forum/discuss.php', [
5926 'd' => $post->discussion
,
5927 'parent' => $post->id
,
5933 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $reply, $forumtracked, $posts);
5940 * @todo Document this function
5945 function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $reply, $forumtracked, $posts) {
5950 if (!empty($posts[$parent->id
]->children
)) {
5951 $posts = $posts[$parent->id
]->children
;
5953 foreach ($posts as $post) {
5955 echo '<div class="indent">';
5956 if (!isloggedin()) {
5959 $ownpost = ($USER->id
== $post->userid
);
5962 $post->subject
= format_string($post->subject
);
5963 $postread = !empty($post->postread
);
5965 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5966 '', '', $postread, true, $forumtracked);
5967 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5974 * Returns all forum posts since a given time in specified forum.
5976 * @todo Document this functions args
5982 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
5983 global $CFG, $COURSE, $USER, $DB;
5985 if ($COURSE->id
== $courseid) {
5988 $course = $DB->get_record('course', array('id' => $courseid));
5991 $modinfo = get_fast_modinfo($course);
5993 $cm = $modinfo->cms
[$cmid];
5994 $params = array($timestart, $cm->instance
);
5997 $userselect = "AND u.id = ?";
5998 $params[] = $userid;
6004 $groupselect = "AND d.groupid = ?";
6005 $params[] = $groupid;
6010 $allnames = get_all_user_name_fields(true, 'u');
6011 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
6012 d.timestart, d.timeend, d.userid AS duserid,
6013 $allnames, u.email, u.picture, u.imagealt, u.email
6014 FROM {forum_posts} p
6015 JOIN {forum_discussions} d ON d.id = p.discussion
6016 JOIN {forum} f ON f.id = d.forum
6017 JOIN {user} u ON u.id = p.userid
6018 WHERE p.created > ? AND f.id = ?
6019 $userselect $groupselect
6020 ORDER BY p.id ASC", $params)) { // order by initial posting date
6024 $groupmode = groups_get_activity_groupmode($cm, $course);
6025 $cm_context = context_module
::instance($cm->id
);
6026 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
6027 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
6029 $printposts = array();
6030 foreach ($posts as $post) {
6032 if (!empty($CFG->forum_enabletimedposts
) and $USER->id
!= $post->duserid
6033 and (($post->timestart
> 0 and $post->timestart
> time()) or ($post->timeend
> 0 and $post->timeend
< time()))) {
6034 if (!$viewhiddentimed) {
6040 if ($post->groupid
== -1 or $groupmode == VISIBLEGROUPS
or $accessallgroups) {
6041 // oki (Open discussions have groupid -1)
6044 if (isguestuser()) {
6049 if (!in_array($post->groupid
, $modinfo->get_groups($cm->groupingid
))) {
6055 $printposts[] = $post;
6062 $aname = format_string($cm->name
,true);
6064 foreach ($printposts as $post) {
6065 $tmpactivity = new stdClass();
6067 $tmpactivity->type
= 'forum';
6068 $tmpactivity->cmid
= $cm->id
;
6069 $tmpactivity->name
= $aname;
6070 $tmpactivity->sectionnum
= $cm->sectionnum
;
6071 $tmpactivity->timestamp
= $post->modified
;
6073 $tmpactivity->content
= new stdClass();
6074 $tmpactivity->content
->id
= $post->id
;
6075 $tmpactivity->content
->discussion
= $post->discussion
;
6076 $tmpactivity->content
->subject
= format_string($post->subject
);
6077 $tmpactivity->content
->parent
= $post->parent
;
6078 $tmpactivity->content
->forumtype
= $post->forumtype
;
6080 $tmpactivity->user
= new stdClass();
6081 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
6082 $additionalfields = explode(',', user_picture
::fields());
6083 $tmpactivity->user
= username_load_fields_from_object($tmpactivity->user
, $post, null, $additionalfields);
6084 $tmpactivity->user
->id
= $post->userid
;
6086 $activities[$index++
] = $tmpactivity;
6093 * Outputs the forum post indicated by $activity.
6095 * @param object $activity the activity object the forum resides in
6096 * @param int $courseid the id of the course the forum resides in
6097 * @param bool $detail not used, but required for compatibilty with other modules
6098 * @param int $modnames not used, but required for compatibilty with other modules
6099 * @param bool $viewfullnames not used, but required for compatibilty with other modules
6101 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
6104 $content = $activity->content
;
6105 if ($content->parent
) {
6108 $class = 'discussion';
6113 'cellpadding' => '3',
6114 'cellspacing' => '0',
6115 'class' => 'forum-recent'
6117 $output = html_writer
::start_tag('table', $tableoptions);
6118 $output .= html_writer
::start_tag('tr');
6120 $post = (object) ['parent' => $content->parent
];
6121 $forum = (object) ['type' => $content->forumtype
];
6122 $authorhidden = forum_is_author_hidden($post, $forum);
6124 // Show user picture if author should not be hidden.
6125 if (!$authorhidden) {
6127 'courseid' => $courseid,
6128 'link' => $authorhidden,
6129 'alttext' => $authorhidden,
6131 $picture = $OUTPUT->user_picture($activity->user
, $pictureoptions);
6132 $output .= html_writer
::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']);
6135 // Discussion title and author.
6136 $output .= html_writer
::start_tag('td', ['class' => $class]);
6137 if ($content->parent
) {
6140 // Bold the title of new discussions so they stand out.
6141 $class = 'title bold';
6144 $output .= html_writer
::start_div($class);
6146 $aname = s($activity->name
);
6147 $output .= $OUTPUT->image_icon('icon', $aname, $activity->type
);
6149 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion
]);
6150 $discussionurl->set_anchor('p' . $activity->content
->id
);
6151 $output .= html_writer
::link($discussionurl, $content->subject
);
6152 $output .= html_writer
::end_div();
6154 $timestamp = userdate($activity->timestamp
);
6155 if ($authorhidden) {
6156 $authornamedate = $timestamp;
6158 $fullname = fullname($activity->user
, $viewfullnames);
6159 $userurl = new moodle_url('/user/view.php');
6160 $userurl->params(['id' => $activity->user
->id
, 'course' => $courseid]);
6161 $by = new stdClass();
6162 $by->name
= html_writer
::link($userurl, $fullname);
6163 $by->date
= $timestamp;
6164 $authornamedate = get_string('bynameondate', 'forum', $by);
6166 $output .= html_writer
::div($authornamedate, 'user');
6167 $output .= html_writer
::end_tag('td');
6168 $output .= html_writer
::end_tag('tr');
6169 $output .= html_writer
::end_tag('table');
6175 * recursively sets the discussion field to $discussionid on $postid and all its children
6176 * used when pruning a post
6179 * @param int $postid
6180 * @param int $discussionid
6183 function forum_change_discussionid($postid, $discussionid) {
6185 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
6186 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
6187 foreach ($posts as $post) {
6188 forum_change_discussionid($post->id
, $discussionid);
6195 * Prints the editing button on subscribers page
6199 * @param int $courseid
6200 * @param int $forumid
6203 function forum_update_subscriptions_button($courseid, $forumid) {
6206 if (!empty($USER->subscriptionsediting
)) {
6207 $string = get_string('managesubscriptionsoff', 'forum');
6210 $string = get_string('managesubscriptionson', 'forum');
6214 $subscribers = html_writer
::start_tag('form', array('action' => $CFG->wwwroot
. '/mod/forum/subscribers.php',
6215 'method' => 'get', 'class' => 'form-inline'));
6216 $subscribers .= html_writer
::empty_tag('input', array('type' => 'submit', 'value' => $string,
6217 'class' => 'btn btn-secondary'));
6218 $subscribers .= html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $forumid));
6219 $subscribers .= html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'edit', 'value' => $edit));
6220 $subscribers .= html_writer
::end_tag('form');
6222 return $subscribers;
6225 // Functions to do with read tracking.
6228 * Mark posts as read.
6232 * @param object $user object
6233 * @param array $postids array of post ids
6234 * @return boolean success
6236 function forum_tp_mark_posts_read($user, $postids) {
6239 if (!forum_tp_can_track_forums(false, $user)) {
6246 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
6248 if (empty($postids)) {
6251 } else if (count($postids) > 200) {
6252 while ($part = array_splice($postids, 0, 200)) {
6253 $status = forum_tp_mark_posts_read($user, $part) && $status;
6258 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED
, 'postid');
6260 $insertparams = array(
6261 'userid1' => $user->id
,
6262 'userid2' => $user->id
,
6263 'userid3' => $user->id
,
6264 'firstread' => $now,
6266 'cutoffdate' => $cutoffdate,
6268 $params = array_merge($postidparams, $insertparams);
6270 if ($CFG->forum_allowforcedreadtracking
) {
6271 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
6272 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL))";
6274 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6275 AND tf.id IS NULL)";
6278 // First insert any new entries.
6279 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6281 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
6282 FROM {forum_posts} p
6283 JOIN {forum_discussions} d ON d.id = p.discussion
6284 JOIN {forum} f ON f.id = d.forum
6285 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
6286 LEFT JOIN {forum_read} fr ON (
6287 fr.userid = :userid3
6288 AND fr.postid = p.id
6289 AND fr.discussionid = d.id
6290 AND fr.forumid = f.id
6293 AND p.modified >= :cutoffdate
6297 $status = $DB->execute($sql, $params) && $status;
6299 // Then update all records.
6300 $updateparams = array(
6301 'userid' => $user->id
,
6304 $params = array_merge($postidparams, $updateparams);
6305 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
6307 AND lastread <> :lastread
6308 AND postid ' . $usql,
6309 $params) && $status;
6315 * Mark post as read.
6318 * @param int $userid
6319 * @param int $postid
6321 function forum_tp_add_read_record($userid, $postid) {
6325 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
6327 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
6328 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6330 SELECT ?, p.id, p.discussion, d.forum, ?, ?
6331 FROM {forum_posts} p
6332 JOIN {forum_discussions} d ON d.id = p.discussion
6333 WHERE p.id = ? AND p.modified >= ?";
6334 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
6337 $sql = "UPDATE {forum_read}
6339 WHERE userid = ? AND postid = ?";
6340 return $DB->execute($sql, array($now, $userid, $userid));
6345 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
6347 * @param int $userid The ID of the user to mark posts read for.
6348 * @param object $post The post record for the post to mark as read.
6349 * @param mixed $unused
6352 function forum_tp_mark_post_read($userid, $post, $unused = null) {
6353 if (!forum_tp_is_post_old($post)) {
6354 return forum_tp_add_read_record($userid, $post->id
);
6361 * Marks a whole forum as read, for a given user
6365 * @param object $user
6366 * @param int $forumid
6367 * @param int|bool $groupid
6370 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
6373 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6376 $params = array($user->id
, $forumid, $cutoffdate);
6378 if ($groupid !== false) {
6379 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
6380 $params[] = $groupid;
6384 FROM {forum_posts} p
6385 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
6386 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6388 AND p.modified >= ? AND r.id is NULL
6391 if ($posts = $DB->get_records_sql($sql, $params)) {
6392 $postids = array_keys($posts);
6393 return forum_tp_mark_posts_read($user, $postids);
6400 * Marks a whole discussion as read, for a given user
6404 * @param object $user
6405 * @param int $discussionid
6408 function forum_tp_mark_discussion_read($user, $discussionid) {
6411 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6414 FROM {forum_posts} p
6415 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6416 WHERE p.discussion = ?
6417 AND p.modified >= ? AND r.id is NULL";
6419 if ($posts = $DB->get_records_sql($sql, array($user->id
, $discussionid, $cutoffdate))) {
6420 $postids = array_keys($posts);
6421 return forum_tp_mark_posts_read($user, $postids);
6429 * @param int $userid
6430 * @param object $post
6432 function forum_tp_is_post_read($userid, $post) {
6434 return (forum_tp_is_post_old($post) ||
6435 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id
)));
6440 * @param object $post
6441 * @param int $time Defautls to time()
6443 function forum_tp_is_post_old($post, $time=null) {
6446 if (is_null($time)) {
6449 return ($post->modified
< ($time - ($CFG->forum_oldpostdays
* 24 * 3600)));
6453 * Returns the count of records for the provided user and course.
6454 * Please note that group access is ignored!
6458 * @param int $userid
6459 * @param int $courseid
6462 function forum_tp_get_course_unread_posts($userid, $courseid) {
6465 $now = floor(time() / 60) * 60; // DB cache friendliness.
6466 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 60 * 60);
6467 $params = array($userid, $userid, $courseid, $cutoffdate, $userid);
6469 if (!empty($CFG->forum_enabletimedposts
)) {
6470 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6477 if ($CFG->forum_allowforcedreadtracking
) {
6478 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
6479 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL
6480 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))";
6482 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6484 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)";
6487 $sql = "SELECT f.id, COUNT(p.id) AS unread
6488 FROM {forum_posts} p
6489 JOIN {forum_discussions} d ON d.id = p.discussion
6490 JOIN {forum} f ON f.id = d.forum
6491 JOIN {course} c ON c.id = f.course
6492 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6493 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id)
6495 AND p.modified >= ? AND r.id is NULL
6500 if ($return = $DB->get_records_sql($sql, $params)) {
6508 * Returns the count of records for the provided user and forum and [optionally] group.
6514 * @param object $course
6515 * @param bool $resetreadcache optional, true to reset the function static $readcache var
6518 function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) {
6519 global $CFG, $USER, $DB;
6521 static $readcache = array();
6523 if ($resetreadcache) {
6524 $readcache = array();
6527 $forumid = $cm->instance
;
6529 if (!isset($readcache[$course->id
])) {
6530 $readcache[$course->id
] = array();
6531 if ($counts = forum_tp_get_course_unread_posts($USER->id
, $course->id
)) {
6532 foreach ($counts as $count) {
6533 $readcache[$course->id
][$count->id
] = $count->unread
;
6538 if (empty($readcache[$course->id
][$forumid])) {
6539 // no need to check group mode ;-)
6543 $groupmode = groups_get_activity_groupmode($cm, $course);
6545 if ($groupmode != SEPARATEGROUPS
) {
6546 return $readcache[$course->id
][$forumid];
6549 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
6550 return $readcache[$course->id
][$forumid];
6553 require_once($CFG->dirroot
.'/course/lib.php');
6555 $modinfo = get_fast_modinfo($course);
6557 $mygroups = $modinfo->get_groups($cm->groupingid
);
6559 // add all groups posts
6562 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);
6564 $now = floor(time() / 60) * 60; // DB Cache friendliness.
6565 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
6566 $params = array($USER->id
, $forumid, $cutoffdate);
6568 if (!empty($CFG->forum_enabletimedposts
)) {
6569 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6576 $params = array_merge($params, $groups_params);
6578 $sql = "SELECT COUNT(p.id)
6579 FROM {forum_posts} p
6580 JOIN {forum_discussions} d ON p.discussion = d.id
6581 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6583 AND p.modified >= ? AND r.id is NULL
6585 AND d.groupid $groups_sql";
6587 return $DB->get_field_sql($sql, $params);
6591 * Deletes read records for the specified index. At least one parameter must be specified.
6594 * @param int $userid
6595 * @param int $postid
6596 * @param int $discussionid
6597 * @param int $forumid
6600 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
6606 if ($select != '') $select .= ' AND ';
6607 $select .= 'userid = ?';
6608 $params[] = $userid;
6611 if ($select != '') $select .= ' AND ';
6612 $select .= 'postid = ?';
6613 $params[] = $postid;
6615 if ($discussionid > -1) {
6616 if ($select != '') $select .= ' AND ';
6617 $select .= 'discussionid = ?';
6618 $params[] = $discussionid;
6620 if ($forumid > -1) {
6621 if ($select != '') $select .= ' AND ';
6622 $select .= 'forumid = ?';
6623 $params[] = $forumid;
6625 if ($select == '') {
6629 return $DB->delete_records_select('forum_read', $select, $params);
6633 * Get a list of forums not tracked by the user.
6637 * @param int $userid The id of the user to use.
6638 * @param int $courseid The id of the course being checked.
6639 * @return mixed An array indexed by forum id, or false.
6641 function forum_tp_get_untracked_forums($userid, $courseid) {
6644 if ($CFG->forum_allowforcedreadtracking
) {
6645 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
6646 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND (ft.id IS NOT NULL
6647 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6649 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
6650 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6651 AND (ft.id IS NOT NULL
6652 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6657 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
6661 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
6662 foreach ($forums as $forum) {
6663 $forums[$forum->id
] = $forum;
6673 * Determine if a user can track forums and optionally a particular forum.
6674 * Checks the site settings, the user settings and the forum settings (if
6680 * @param mixed $forum The forum object to test, or the int id (optional).
6681 * @param mixed $userid The user object to check for (optional).
6684 function forum_tp_can_track_forums($forum=false, $user=false) {
6685 global $USER, $CFG, $DB;
6687 // if possible, avoid expensive
6689 if (empty($CFG->forum_trackreadposts
)) {
6693 if ($user === false) {
6697 if (isguestuser($user) or empty($user->id
)) {
6701 if ($forum === false) {
6702 if ($CFG->forum_allowforcedreadtracking
) {
6703 // Since we can force tracking, assume yes without a specific forum.
6706 return (bool)$user->trackforums
;
6710 // Work toward always passing an object...
6711 if (is_numeric($forum)) {
6712 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
6713 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
6716 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
6717 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
6719 if ($CFG->forum_allowforcedreadtracking
) {
6720 // If we allow forcing, then forced forums takes procidence over user setting.
6721 return ($forumforced ||
($forumallows && (!empty($user->trackforums
) && (bool)$user->trackforums
)));
6723 // If we don't allow forcing, user setting trumps.
6724 return ($forumforced ||
$forumallows) && !empty($user->trackforums
);
6729 * Tells whether a specific forum is tracked by the user. A user can optionally
6730 * be specified. If not specified, the current user is assumed.
6735 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
6736 * @param int $userid The id of the user being checked (optional).
6739 function forum_tp_is_tracked($forum, $user=false) {
6740 global $USER, $CFG, $DB;
6742 if ($user === false) {
6746 if (isguestuser($user) or empty($user->id
)) {
6750 // Work toward always passing an object...
6751 if (is_numeric($forum)) {
6752 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
6753 $forum = $DB->get_record('forum', array('id' => $forum));
6756 if (!forum_tp_can_track_forums($forum, $user)) {
6760 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
6761 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
6762 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id
, 'forumid' => $forum->id
));
6764 if ($CFG->forum_allowforcedreadtracking
) {
6765 return $forumforced ||
($forumallows && $userpref === false);
6767 return ($forumallows ||
$forumforced) && $userpref === false;
6774 * @param int $forumid
6775 * @param int $userid
6777 function forum_tp_start_tracking($forumid, $userid=false) {
6780 if ($userid === false) {
6781 $userid = $USER->id
;
6784 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
6790 * @param int $forumid
6791 * @param int $userid
6793 function forum_tp_stop_tracking($forumid, $userid=false) {
6796 if ($userid === false) {
6797 $userid = $USER->id
;
6800 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
6801 $track_prefs = new stdClass();
6802 $track_prefs->userid
= $userid;
6803 $track_prefs->forumid
= $forumid;
6804 $DB->insert_record('forum_track_prefs', $track_prefs);
6807 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
6812 * Clean old records from the forum_read table.
6817 function forum_tp_clean_read_records() {
6820 if (!isset($CFG->forum_oldpostdays
)) {
6823 // Look for records older than the cutoffdate that are still in the forum_read table.
6824 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6826 //first get the oldest tracking present - we need tis to speedup the next delete query
6827 $sql = "SELECT MIN(fp.modified) AS first
6828 FROM {forum_posts} fp
6829 JOIN {forum_read} fr ON fr.postid=fp.id";
6830 if (!$first = $DB->get_field_sql($sql)) {
6831 // nothing to delete;
6835 // now delete old tracking info
6838 WHERE postid IN (SELECT fp.id
6839 FROM {forum_posts} fp
6840 WHERE fp.modified >= ? AND fp.modified < ?)";
6841 $DB->execute($sql, array($first, $cutoffdate));
6845 * Sets the last post for a given discussion
6849 * @param into $discussionid
6852 function forum_discussion_update_last_post($discussionid) {
6855 // Check the given discussion exists
6856 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
6860 // Use SQL to find the last post for this discussion
6861 $sql = "SELECT id, userid, modified
6864 ORDER BY modified DESC";
6866 // Lets go find the last post
6867 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
6868 $lastpost = reset($lastposts);
6869 $discussionobject = new stdClass();
6870 $discussionobject->id
= $discussionid;
6871 $discussionobject->usermodified
= $lastpost->userid
;
6872 $discussionobject->timemodified
= $lastpost->modified
;
6873 $DB->update_record('forum_discussions', $discussionobject);
6874 return $lastpost->id
;
6877 // To get here either we couldn't find a post for the discussion (weird)
6878 // or we couldn't update the discussion record (weird x2)
6884 * List the actions that correspond to a view of this module.
6885 * This is used by the participation report.
6887 * Note: This is not used by new logging system. Event with
6888 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
6889 * be considered as view action.
6893 function forum_get_view_actions() {
6894 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
6898 * List the options for forum subscription modes.
6899 * This is used by the settings page and by the mod_form page.
6903 function forum_get_subscriptionmode_options() {
6905 $options[FORUM_CHOOSESUBSCRIBE
] = get_string('subscriptionoptional', 'forum');
6906 $options[FORUM_FORCESUBSCRIBE
] = get_string('subscriptionforced', 'forum');
6907 $options[FORUM_INITIALSUBSCRIBE
] = get_string('subscriptionauto', 'forum');
6908 $options[FORUM_DISALLOWSUBSCRIBE
] = get_string('subscriptiondisabled', 'forum');
6913 * List the actions that correspond to a post of this module.
6914 * This is used by the participation report.
6916 * Note: This is not used by new logging system. Event with
6917 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
6918 * will be considered as post action.
6922 function forum_get_post_actions() {
6923 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
6927 * Returns a warning object if a user has reached the number of posts equal to
6928 * the warning/blocking setting, or false if there is no warning to show.
6930 * @param int|stdClass $forum the forum id or the forum object
6931 * @param stdClass $cm the course module
6932 * @return stdClass|bool returns an object with the warning information, else
6933 * returns false if no warning is required.
6935 function forum_check_throttling($forum, $cm = null) {
6936 global $CFG, $DB, $USER;
6938 if (is_numeric($forum)) {
6939 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST
);
6942 if (!is_object($forum)) {
6943 return false; // This is broken.
6947 $cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
, false, MUST_EXIST
);
6950 if (empty($forum->blockafter
)) {
6954 if (empty($forum->blockperiod
)) {
6958 $modcontext = context_module
::instance($cm->id
);
6959 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
6963 // Get the number of posts in the last period we care about.
6965 $timeafter = $timenow - $forum->blockperiod
;
6966 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
6967 JOIN {forum_discussions} d
6968 ON p.discussion = d.id WHERE d.forum = ?
6969 AND p.userid = ? AND p.created > ?', array($forum->id
, $USER->id
, $timeafter));
6971 $a = new stdClass();
6972 $a->blockafter
= $forum->blockafter
;
6973 $a->numposts
= $numposts;
6974 $a->blockperiod
= get_string('secondstotime'.$forum->blockperiod
);
6976 if ($forum->blockafter
<= $numposts) {
6977 $warning = new stdClass();
6978 $warning->canpost
= false;
6979 $warning->errorcode
= 'forumblockingtoomanyposts';
6980 $warning->module
= 'error';
6981 $warning->additional
= $a;
6982 $warning->link
= $CFG->wwwroot
. '/mod/forum/view.php?f=' . $forum->id
;
6987 if ($forum->warnafter
<= $numposts) {
6988 $warning = new stdClass();
6989 $warning->canpost
= true;
6990 $warning->errorcode
= 'forumblockingalmosttoomanyposts';
6991 $warning->module
= 'forum';
6992 $warning->additional
= $a;
6993 $warning->link
= null;
7000 * Throws an error if the user is no longer allowed to post due to having reached
7001 * or exceeded the number of posts specified in 'Post threshold for blocking'
7005 * @param stdClass $thresholdwarning the warning information returned
7006 * from the function forum_check_throttling.
7008 function forum_check_blocking_threshold($thresholdwarning) {
7009 if (!empty($thresholdwarning) && !$thresholdwarning->canpost
) {
7010 print_error($thresholdwarning->errorcode
,
7011 $thresholdwarning->module
,
7012 $thresholdwarning->link
,
7013 $thresholdwarning->additional
);
7019 * Removes all grades from gradebook
7023 * @param int $courseid
7024 * @param string $type optional
7026 function forum_reset_gradebook($courseid, $type='') {
7030 $params = array($courseid);
7032 $wheresql = "AND f.type=?";
7036 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
7037 FROM {forum} f, {course_modules} cm, {modules} m
7038 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
7040 if ($forums = $DB->get_records_sql($sql, $params)) {
7041 foreach ($forums as $forum) {
7042 forum_grade_item_update($forum, 'reset');
7048 * This function is used by the reset_course_userdata function in moodlelib.
7049 * This function will remove all posts from the specified forum
7050 * and clean up any related data.
7054 * @param $data the data submitted from the reset course.
7055 * @return array status array
7057 function forum_reset_userdata($data) {
7059 require_once($CFG->dirroot
.'/rating/lib.php');
7061 $componentstr = get_string('modulenameplural', 'forum');
7064 $params = array($data->courseid
);
7066 $removeposts = false;
7068 if (!empty($data->reset_forum_all
)) {
7069 $removeposts = true;
7070 $typesstr = get_string('resetforumsall', 'forum');
7072 } else if (!empty($data->reset_forum_types
)){
7073 $removeposts = true;
7075 $sqltypes = array();
7076 $forum_types_all = forum_get_forum_types_all();
7077 foreach ($data->reset_forum_types
as $type) {
7078 if (!array_key_exists($type, $forum_types_all)) {
7081 $types[] = $forum_types_all[$type];
7082 $sqltypes[] = $type;
7084 if (!empty($sqltypes)) {
7085 list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes);
7086 $typesql = " AND f.type " . $typesql;
7087 $params = array_merge($params, $typeparams);
7089 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
7091 $alldiscussionssql = "SELECT fd.id
7092 FROM {forum_discussions} fd, {forum} f
7093 WHERE f.course=? AND f.id=fd.forum";
7095 $allforumssql = "SELECT f.id
7099 $allpostssql = "SELECT fp.id
7100 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
7101 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
7103 $forumssql = $forums = $rm = null;
7105 // Check if we need to get additional data.
7106 if ($removeposts ||
!empty($data->reset_forum_ratings
) ||
!empty($data->reset_forum_tags
)) {
7107 // Set this up if we have to remove ratings.
7108 $rm = new rating_manager();
7109 $ratingdeloptions = new stdClass
;
7110 $ratingdeloptions->component
= 'mod_forum';
7111 $ratingdeloptions->ratingarea
= 'post';
7113 // Get the forums for actions that require it.
7114 $forumssql = "$allforumssql $typesql";
7115 $forums = $DB->get_records_sql($forumssql, $params);
7119 $discussionssql = "$alldiscussionssql $typesql";
7120 $postssql = "$allpostssql $typesql";
7122 // now get rid of all attachments
7123 $fs = get_file_storage();
7125 foreach ($forums as $forumid=>$unused) {
7126 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7129 $context = context_module
::instance($cm->id
);
7130 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment');
7131 $fs->delete_area_files($context->id
, 'mod_forum', 'post');
7134 $ratingdeloptions->contextid
= $context->id
;
7135 $rm->delete_ratings($ratingdeloptions);
7137 core_tag_tag
::delete_instances('mod_forum', null, $context->id
);
7141 // first delete all read flags
7142 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
7144 // remove tracking prefs
7145 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
7147 // remove posts from queue
7148 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
7150 // all posts - initial posts must be kept in single simple discussion forums
7151 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
7152 $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
7154 // finally all discussions except single simple forums
7155 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
7157 // remove all grades from gradebook
7158 if (empty($data->reset_gradebook_grades
)) {
7159 if (empty($types)) {
7160 forum_reset_gradebook($data->courseid
);
7162 foreach ($types as $type) {
7163 forum_reset_gradebook($data->courseid
, $type);
7168 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
7171 // remove all ratings in this course's forums
7172 if (!empty($data->reset_forum_ratings
)) {
7174 foreach ($forums as $forumid=>$unused) {
7175 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7178 $context = context_module
::instance($cm->id
);
7181 $ratingdeloptions->contextid
= $context->id
;
7182 $rm->delete_ratings($ratingdeloptions);
7186 // remove all grades from gradebook
7187 if (empty($data->reset_gradebook_grades
)) {
7188 forum_reset_gradebook($data->courseid
);
7192 // Remove all the tags.
7193 if (!empty($data->reset_forum_tags
)) {
7195 foreach ($forums as $forumid => $unused) {
7196 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
7200 $context = context_module
::instance($cm->id
);
7201 core_tag_tag
::delete_instances('mod_forum', null, $context->id
);
7205 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false);
7208 // remove all digest settings unconditionally - even for users still enrolled in course.
7209 if (!empty($data->reset_forum_digests
)) {
7210 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
7211 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
7214 // remove all subscriptions unconditionally - even for users still enrolled in course
7215 if (!empty($data->reset_forum_subscriptions
)) {
7216 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
7217 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
7218 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
7221 // remove all tracking prefs unconditionally - even for users still enrolled in course
7222 if (!empty($data->reset_forum_track_prefs
)) {
7223 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
7224 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
7227 /// updating dates - shift may be negative too
7228 if ($data->timeshift
) {
7229 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
7231 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
7232 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
7239 * Called by course/reset.php
7241 * @param $mform form passed by reference
7243 function forum_reset_course_form_definition(&$mform) {
7244 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
7246 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
7248 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
7249 $mform->setAdvanced('reset_forum_types');
7250 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
7252 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
7253 $mform->setAdvanced('reset_forum_digests');
7255 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
7256 $mform->setAdvanced('reset_forum_subscriptions');
7258 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
7259 $mform->setAdvanced('reset_forum_track_prefs');
7260 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
7262 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
7263 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
7265 $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum'));
7266 $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked');
7270 * Course reset form defaults.
7273 function forum_reset_course_form_defaults($course) {
7274 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
7278 * Returns array of forum layout modes
7282 function forum_get_layout_modes() {
7283 return array (FORUM_MODE_FLATOLDEST
=> get_string('modeflatoldestfirst', 'forum'),
7284 FORUM_MODE_FLATNEWEST
=> get_string('modeflatnewestfirst', 'forum'),
7285 FORUM_MODE_THREADED
=> get_string('modethreaded', 'forum'),
7286 FORUM_MODE_NESTED
=> get_string('modenested', 'forum'));
7290 * Returns array of forum types chooseable on the forum editing form
7294 function forum_get_forum_types() {
7295 return array ('general' => get_string('generalforum', 'forum'),
7296 'eachuser' => get_string('eachuserforum', 'forum'),
7297 'single' => get_string('singleforum', 'forum'),
7298 'qanda' => get_string('qandaforum', 'forum'),
7299 'blog' => get_string('blogforum', 'forum'));
7303 * Returns array of all forum layout modes
7307 function forum_get_forum_types_all() {
7308 return array ('news' => get_string('namenews','forum'),
7309 'social' => get_string('namesocial','forum'),
7310 'general' => get_string('generalforum', 'forum'),
7311 'eachuser' => get_string('eachuserforum', 'forum'),
7312 'single' => get_string('singleforum', 'forum'),
7313 'qanda' => get_string('qandaforum', 'forum'),
7314 'blog' => get_string('blogforum', 'forum'));
7318 * Returns all other caps used in module
7322 function forum_get_extra_capabilities() {
7323 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate');
7327 * Adds module specific settings to the settings block
7329 * @param settings_navigation $settings The settings navigation object
7330 * @param navigation_node $forumnode The node to add module settings to
7332 function forum_extend_settings_navigation(settings_navigation
$settingsnav, navigation_node
$forumnode) {
7333 global $USER, $PAGE, $CFG, $DB, $OUTPUT;
7335 $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm
->instance
));
7336 if (empty($PAGE->cm
->context
)) {
7337 $PAGE->cm
->context
= context_module
::instance($PAGE->cm
->instance
);
7340 $params = $PAGE->url
->params();
7341 if (!empty($params['d'])) {
7342 $discussionid = $params['d'];
7345 // for some actions you need to be enrolled, beiing admin is not enough sometimes here
7346 $enrolled = is_enrolled($PAGE->cm
->context
, $USER, '', false);
7347 $activeenrolled = is_enrolled($PAGE->cm
->context
, $USER, '', true);
7349 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm
->context
);
7350 $subscriptionmode = \mod_forum\subscriptions
::get_subscription_mode($forumobject);
7351 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions
::is_forcesubscribed($forumobject) &&
7352 (!\mod_forum\subscriptions
::subscription_disabled($forumobject) ||
$canmanage);
7355 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node
::TYPE_CONTAINER
);
7356 $mode->add_class('subscriptionmode');
7358 $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
);
7359 $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
);
7360 $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
);
7361 $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
);
7363 switch ($subscriptionmode) {
7364 case FORUM_CHOOSESUBSCRIBE
: // 0
7365 $allowchoice->action
= null;
7366 $allowchoice->add_class('activesetting');
7367 $allowchoice->icon
= new pix_icon('t/selected', '', 'mod_forum');
7369 case FORUM_FORCESUBSCRIBE
: // 1
7370 $forceforever->action
= null;
7371 $forceforever->add_class('activesetting');
7372 $forceforever->icon
= new pix_icon('t/selected', '', 'mod_forum');
7374 case FORUM_INITIALSUBSCRIBE
: // 2
7375 $forceinitially->action
= null;
7376 $forceinitially->add_class('activesetting');
7377 $forceinitially->icon
= new pix_icon('t/selected', '', 'mod_forum');
7379 case FORUM_DISALLOWSUBSCRIBE
: // 3
7380 $disallowchoice->action
= null;
7381 $disallowchoice->add_class('activesetting');
7382 $disallowchoice->icon
= new pix_icon('t/selected', '', 'mod_forum');
7386 } else if ($activeenrolled) {
7388 switch ($subscriptionmode) {
7389 case FORUM_CHOOSESUBSCRIBE
: // 0
7390 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
7392 case FORUM_FORCESUBSCRIBE
: // 1
7393 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
7395 case FORUM_INITIALSUBSCRIBE
: // 2
7396 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
7398 case FORUM_DISALLOWSUBSCRIBE
: // 3
7399 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
7404 if ($cansubscribe) {
7405 if (\mod_forum\subscriptions
::is_subscribed($USER->id
, $forumobject, null, $PAGE->cm
)) {
7406 $linktext = get_string('unsubscribe', 'forum');
7408 $linktext = get_string('subscribe', 'forum');
7410 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id
, 'sesskey'=>sesskey()));
7411 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7413 if (isset($discussionid)) {
7414 if (\mod_forum\subscriptions
::is_subscribed($USER->id
, $forumobject, $discussionid, $PAGE->cm
)) {
7415 $linktext = get_string('unsubscribediscussion', 'forum');
7417 $linktext = get_string('subscribediscussion', 'forum');
7419 $url = new moodle_url('/mod/forum/subscribe.php', array(
7420 'id' => $forumobject->id
,
7421 'sesskey' => sesskey(),
7422 'd' => $discussionid,
7423 'returnurl' => $PAGE->url
->out(),
7425 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7429 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm
->context
)){
7430 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id
));
7431 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node
::TYPE_SETTING
);
7434 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
7435 if ($forumobject->trackingtype
== FORUM_TRACKING_OPTIONAL
7436 ||
((!$CFG->forum_allowforcedreadtracking
) && $forumobject->trackingtype
== FORUM_TRACKING_FORCED
)) {
7437 if (forum_tp_is_tracked($forumobject)) {
7438 $linktext = get_string('notrackforum', 'forum');
7440 $linktext = get_string('trackforum', 'forum');
7442 $url = new moodle_url('/mod/forum/settracking.php', array(
7443 'id' => $forumobject->id
,
7444 'sesskey' => sesskey(),
7446 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7450 if (!isloggedin() && $PAGE->course
->id
== SITEID
) {
7451 $userid = guest_user()->id
;
7453 $userid = $USER->id
;
7456 $hascourseaccess = ($PAGE->course
->id
== SITEID
) ||
can_access_course($PAGE->course
, $userid);
7457 $enablerssfeeds = !empty($CFG->enablerssfeeds
) && !empty($CFG->forum_enablerssfeeds
);
7459 if ($enablerssfeeds && $forumobject->rsstype
&& $forumobject->rssarticles
&& $hascourseaccess) {
7461 if (!function_exists('rss_get_url')) {
7462 require_once("$CFG->libdir/rsslib.php");
7465 if ($forumobject->rsstype
== 1) {
7466 $string = get_string('rsssubscriberssdiscussions','forum');
7468 $string = get_string('rsssubscriberssposts','forum');
7471 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $userid, "mod_forum", $forumobject->id
));
7472 $forumnode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
7477 * Adds information about unread messages, that is only required for the course view page (and
7478 * similar), to the course-module object.
7479 * @param cm_info $cm Course-module object
7481 function forum_cm_info_view(cm_info
$cm) {
7484 if (forum_tp_can_track_forums()) {
7485 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
7486 $out = '<span class="unread"> <a href="' . $cm->url
. '">';
7488 $out .= get_string('unreadpostsone', 'forum');
7490 $out .= get_string('unreadpostsnumber', 'forum', $unread);
7492 $out .= '</a></span>';
7493 $cm->set_after_link($out);
7499 * Return a list of page types
7500 * @param string $pagetype current page type
7501 * @param stdClass $parentcontext Block's parent context
7502 * @param stdClass $currentcontext Current context of block
7504 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
7505 $forum_pagetype = array(
7506 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
7507 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
7508 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
7510 return $forum_pagetype;
7514 * Gets all of the courses where the provided user has posted in a forum.
7516 * @global moodle_database $DB The database connection
7517 * @param stdClass $user The user who's posts we are looking for
7518 * @param bool $discussionsonly If true only look for discussions started by the user
7519 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
7520 * @param int $limitfrom The offset of records to return
7521 * @param int $limitnum The number of records to return
7522 * @return array An array of courses
7524 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
7527 // If we are only after discussions we need only look at the forum_discussions
7528 // table and join to the userid there. If we are looking for posts then we need
7529 // to join to the forum_posts table.
7530 if (!$discussionsonly) {
7531 $subquery = "(SELECT DISTINCT fd.course
7532 FROM {forum_discussions} fd
7533 JOIN {forum_posts} fp ON fp.discussion = fd.id
7534 WHERE fp.userid = :userid )";
7536 $subquery= "(SELECT DISTINCT fd.course
7537 FROM {forum_discussions} fd
7538 WHERE fd.userid = :userid )";
7541 $params = array('userid' => $user->id
);
7543 // Join to the context table so that we can preload contexts if required.
7544 if ($includecontexts) {
7545 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
7546 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
7547 $params['contextlevel'] = CONTEXT_COURSE
;
7553 // Now we need to get all of the courses to search.
7554 // All courses where the user has posted within a forum will be returned.
7555 $sql = "SELECT c.* $ctxselect
7558 WHERE c.id IN ($subquery)";
7559 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7560 if ($includecontexts) {
7561 array_map('context_helper::preload_from_record', $courses);
7567 * Gets all of the forums a user has posted in for one or more courses.
7569 * @global moodle_database $DB
7570 * @param stdClass $user
7571 * @param array $courseids An array of courseids to search or if not provided
7572 * all courses the user has posted within
7573 * @param bool $discussionsonly If true then only forums where the user has started
7574 * a discussion will be returned.
7575 * @param int $limitfrom The offset of records to return
7576 * @param int $limitnum The number of records to return
7577 * @return array An array of forums the user has posted within in the provided courses
7579 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
7582 if (!is_null($courseids)) {
7583 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
, 'courseid');
7584 $coursewhere = ' AND f.course '.$coursewhere;
7589 $params['userid'] = $user->id
;
7590 $params['forum'] = 'forum';
7592 if ($discussionsonly) {
7593 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
7595 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
7596 JOIN {forum_posts} ff ON ff.discussion = fd.id';
7599 $sql = "SELECT f.*, cm.id AS cmid
7601 JOIN {course_modules} cm ON cm.instance = f.id
7602 JOIN {modules} m ON m.id = cm.module
7607 WHERE ff.userid = :userid
7610 WHERE m.name = :forum
7613 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7614 return $courseforums;
7618 * Returns posts made by the selected user in the requested courses.
7620 * This method can be used to return all of the posts made by the requested user
7621 * within the given courses.
7622 * For each course the access of the current user and requested user is checked
7623 * and then for each post access to the post and forum is checked as well.
7625 * This function is safe to use with usercapabilities.
7627 * @global moodle_database $DB
7628 * @param stdClass $user The user whose posts we want to get
7629 * @param array $courses The courses to search
7630 * @param bool $musthaveaccess If set to true errors will be thrown if the user
7631 * cannot access one or more of the courses to search
7632 * @param bool $discussionsonly If set to true only discussion starting posts
7634 * @param int $limitfrom The offset of records to return
7635 * @param int $limitnum The number of records to return
7636 * @return stdClass An object the following properties
7637 * ->totalcount: the total number of posts made by the requested user
7638 * that the current user can see.
7639 * ->courses: An array of courses the current user can see that the
7640 * requested user has posted in.
7641 * ->forums: An array of forums relating to the posts returned in the
7643 * ->posts: An array containing the posts to show for this request.
7645 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
7646 global $DB, $USER, $CFG;
7648 $return = new stdClass
;
7649 $return->totalcount
= 0; // The total number of posts that the current user is able to view
7650 $return->courses
= array(); // The courses the current user can access
7651 $return->forums
= array(); // The forums that the current user can access that contain posts
7652 $return->posts
= array(); // The posts to display
7654 // First up a small sanity check. If there are no courses to check we can
7655 // return immediately, there is obviously nothing to search.
7656 if (empty($courses)) {
7660 // A couple of quick setups
7661 $isloggedin = isloggedin();
7662 $isguestuser = $isloggedin && isguestuser();
7663 $iscurrentuser = $isloggedin && $USER->id
== $user->id
;
7665 // Checkout whether or not the current user has capabilities over the requested
7666 // user and if so they have the capabilities required to view the requested
7668 $usercontext = context_user
::instance($user->id
, MUST_EXIST
);
7669 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
));
7670 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
7672 // Before we actually search each course we need to check the user's access to the
7673 // course. If the user doesn't have the appropraite access then we either throw an
7674 // error if a particular course was requested or we just skip over the course.
7675 foreach ($courses as $course) {
7676 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
7677 if ($iscurrentuser ||
$hascapsonuser) {
7678 // If it is the current user, or the current user has capabilities to the
7679 // requested user then all we need to do is check the requested users
7680 // current access to the course.
7681 // Note: There is no need to check group access or anything of the like
7682 // as either the current user is the requested user, or has granted
7683 // capabilities on the requested user. Either way they can see what the
7684 // requested user posted, although its VERY unlikely in the `parent` situation
7685 // that the current user will be able to view the posts in context.
7686 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
7687 // Need to have full access to a course to see the rest of own info
7688 if ($musthaveaccess) {
7689 print_error('errorenrolmentrequired', 'forum');
7694 // Check whether the current user is enrolled or has access to view the course
7695 // if they don't we immediately have a problem.
7696 if (!can_access_course($course)) {
7697 if ($musthaveaccess) {
7698 print_error('errorenrolmentrequired', 'forum');
7703 // If groups are in use and enforced throughout the course then make sure
7704 // we can meet in at least one course level group.
7705 // Note that we check if either the current user or the requested user have
7706 // the capability to access all groups. This is because with that capability
7707 // a user in group A could post in the group B forum. Grrrr.
7708 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&& $course->groupmodeforce
7709 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id
)) {
7710 // If its the guest user to bad... the guest user cannot access groups
7711 if (!$isloggedin or $isguestuser) {
7712 // do not use require_login() here because we might have already used require_login($course)
7713 if ($musthaveaccess) {
7714 redirect(get_login_url());
7718 // Get the groups of the current user
7719 $mygroups = array_keys(groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
, 'g.id, g.name'));
7720 // Get the groups the requested user is a member of
7721 $usergroups = array_keys(groups_get_all_groups($course->id
, $user->id
, $course->defaultgroupingid
, 'g.id, g.name'));
7722 // Check whether they are members of the same group. If they are great.
7723 $intersect = array_intersect($mygroups, $usergroups);
7724 if (empty($intersect)) {
7725 // But they're not... if it was a specific course throw an error otherwise
7726 // just skip this course so that it is not searched.
7727 if ($musthaveaccess) {
7728 print_error("groupnotamember", '', $CFG->wwwroot
."/course/view.php?id=$course->id");
7734 // Woo hoo we got this far which means the current user can search this
7735 // this course for the requested user. Although this is only the course accessibility
7736 // handling that is complete, the forum accessibility tests are yet to come.
7737 $return->courses
[$course->id
] = $course;
7739 // No longer beed $courses array - lose it not it may be big
7742 // Make sure that we have some courses to search
7743 if (empty($return->courses
)) {
7744 // If we don't have any courses to search then the reality is that the current
7745 // user doesn't have access to any courses is which the requested user has posted.
7746 // Although we do know at this point that the requested user has posts.
7747 if ($musthaveaccess) {
7748 print_error('permissiondenied');
7754 // Next step: Collect all of the forums that we will want to search.
7755 // It is important to note that this step isn't actually about searching, it is
7756 // about determining which forums we can search by testing accessibility.
7757 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses
), $discussionsonly);
7759 // Will be used to build the where conditions for the search
7760 $forumsearchwhere = array();
7761 // Will be used to store the where condition params for the search
7762 $forumsearchparams = array();
7763 // Will record forums where the user can freely access everything
7764 $forumsearchfullaccess = array();
7765 // DB caching friendly
7766 $now = floor(time() / 60) * 60;
7767 // For each course to search we want to find the forums the user has posted in
7768 // and providing the current user can access the forum create a search condition
7769 // for the forum to get the requested users posts.
7770 foreach ($return->courses
as $course) {
7771 // Now we need to get the forums
7772 $modinfo = get_fast_modinfo($course);
7773 if (empty($modinfo->instances
['forum'])) {
7774 // hmmm, no forums? well at least its easy... skip!
7778 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
7779 if (!$cm->uservisible
or !isset($forums[$forumid])) {
7782 // Get the forum in question
7783 $forum = $forums[$forumid];
7785 // This is needed for functionality later on in the forum code. It is converted to an object
7786 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
7787 // code were expecting an writeable object. See {@link forum_print_post()}.
7788 $forum->cm
= new stdClass();
7789 foreach ($cm as $key => $value) {
7790 $forum->cm
->$key = $value;
7793 // Check that either the current user can view the forum, or that the
7794 // current user has capabilities over the requested user and the requested
7795 // user can view the discussion
7796 if (!has_capability('mod/forum:viewdiscussion', $cm->context
) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context
, $user->id
))) {
7800 // This will contain forum specific where clauses
7801 $forumsearchselect = array();
7802 if (!$iscurrentuser && !$hascapsonuser) {
7803 // Make sure we check group access
7804 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $cm->context
)) {
7805 $groups = $modinfo->get_groups($cm->groupingid
);
7807 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
7808 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
7809 $forumsearchselect[] = "d.groupid $groupid_sql";
7812 // hidden timed discussions
7813 if (!empty($CFG->forum_enabletimedposts
) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context
)) {
7814 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
7815 $forumsearchparams['userid'.$forumid] = $user->id
;
7816 $forumsearchparams['timestart'.$forumid] = $now;
7817 $forumsearchparams['timeend'.$forumid] = $now;
7821 if ($forum->type
== 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context
)) {
7822 // We need to check whether the user has posted in the qanda forum.
7823 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $user->id
);
7824 if (!empty($discussionspostedin)) {
7825 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
7826 foreach ($discussionspostedin as $d) {
7827 $forumonlydiscussions[] = $d->id
;
7829 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
7830 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
7831 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
7833 $forumsearchselect[] = "p.parent = 0";
7838 if (count($forumsearchselect) > 0) {
7839 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
7840 $forumsearchparams['forum'.$forumid] = $forumid;
7842 $forumsearchfullaccess[] = $forumid;
7845 // The current user/parent can see all of their own posts
7846 $forumsearchfullaccess[] = $forumid;
7851 // If we dont have any search conditions, and we don't have any forums where
7852 // the user has full access then we just return the default.
7853 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
7857 // Prepare a where condition for the full access forums.
7858 if (count($forumsearchfullaccess) > 0) {
7859 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED
, 'fula');
7860 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
7861 $forumsearchwhere[] = "(d.forum $fullidsql)";
7864 // Prepare SQL to both count and search.
7865 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
7866 // oracle and mssql.
7867 $userfields = user_picture
::fields('u', null, 'useridx');
7868 $countsql = 'SELECT COUNT(*) ';
7869 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
7870 $wheresql = implode(" OR ", $forumsearchwhere);
7872 if ($discussionsonly) {
7873 if ($wheresql == '') {
7874 $wheresql = 'p.parent = 0';
7876 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
7880 $sql = "FROM {forum_posts} p
7881 JOIN {forum_discussions} d ON d.id = p.discussion
7882 JOIN {user} u ON u.id = p.userid
7884 AND p.userid = :userid ";
7885 $orderby = "ORDER BY p.modified DESC";
7886 $forumsearchparams['userid'] = $user->id
;
7888 // Set the total number posts made by the requested user that the current user can see
7889 $return->totalcount
= $DB->count_records_sql($countsql.$sql, $forumsearchparams);
7890 // Set the collection of posts that has been requested
7891 $return->posts
= $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
7893 // We need to build an array of forums for which posts will be displayed.
7894 // We do this here to save the caller needing to retrieve them themselves before
7895 // printing these forums posts. Given we have the forums already there is
7896 // practically no overhead here.
7897 foreach ($return->posts
as $post) {
7898 if (!array_key_exists($post->forum
, $return->forums
)) {
7899 $return->forums
[$post->forum
] = $forums[$post->forum
];
7907 * Set the per-forum maildigest option for the specified user.
7909 * @param stdClass $forum The forum to set the option for.
7910 * @param int $maildigest The maildigest option.
7911 * @param stdClass $user The user object. This defaults to the global $USER object.
7912 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
7914 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
7917 if (is_number($forum)) {
7918 $forum = $DB->get_record('forum', array('id' => $forum));
7921 if ($user === null) {
7925 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
7926 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
7927 $context = context_module
::instance($cm->id
);
7929 // User must be allowed to see this forum.
7930 require_capability('mod/forum:viewdiscussion', $context, $user->id
);
7932 // Validate the maildigest setting.
7933 $digestoptions = forum_get_user_digest_options($user);
7935 if (!isset($digestoptions[$maildigest])) {
7936 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
7939 // Attempt to retrieve any existing forum digest record.
7940 $subscription = $DB->get_record('forum_digests', array(
7941 'userid' => $user->id
,
7942 'forum' => $forum->id
,
7945 // Create or Update the existing maildigest setting.
7946 if ($subscription) {
7947 if ($maildigest == -1) {
7948 $DB->delete_records('forum_digests', array('forum' => $forum->id
, 'userid' => $user->id
));
7949 } else if ($maildigest !== $subscription->maildigest
) {
7950 // Only update the maildigest setting if it's changed.
7952 $subscription->maildigest
= $maildigest;
7953 $DB->update_record('forum_digests', $subscription);
7956 if ($maildigest != -1) {
7957 // Only insert the maildigest setting if it's non-default.
7959 $subscription = new stdClass();
7960 $subscription->forum
= $forum->id
;
7961 $subscription->userid
= $user->id
;
7962 $subscription->maildigest
= $maildigest;
7963 $subscription->id
= $DB->insert_record('forum_digests', $subscription);
7969 * Determine the maildigest setting for the specified user against the
7972 * @param Array $digests An array of forums and user digest settings.
7973 * @param stdClass $user The user object containing the id and maildigest default.
7974 * @param int $forumid The ID of the forum to check.
7975 * @return int The calculated maildigest setting for this user and forum.
7977 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
7978 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id
])) {
7979 $maildigest = $digests[$forumid][$user->id
];
7980 if ($maildigest === -1) {
7981 $maildigest = $user->maildigest
;
7984 $maildigest = $user->maildigest
;
7990 * Retrieve the list of available user digest options.
7992 * @param stdClass $user The user object. This defaults to the global $USER object.
7993 * @return array The mapping of values to digest options.
7995 function forum_get_user_digest_options($user = null) {
7998 // Revert to the global user object.
7999 if ($user === null) {
8003 $digestoptions = array();
8004 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
8005 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
8006 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
8008 // We need to add the default digest option at the end - it relies on
8009 // the contents of the existing values.
8010 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
8011 $digestoptions[$user->maildigest
]);
8013 // Resort the options to be in a sensible order.
8014 ksort($digestoptions);
8016 return $digestoptions;
8020 * Determine the current context if one was not already specified.
8022 * If a context of type context_module is specified, it is immediately
8023 * returned and not checked.
8025 * @param int $forumid The ID of the forum
8026 * @param context_module $context The current context.
8027 * @return context_module The context determined
8029 function forum_get_context($forumid, $context = null) {
8032 if (!$context ||
!($context instanceof context_module
)) {
8033 // Find out forum context. First try to take current page context to save on DB query.
8034 if ($PAGE->cm
&& $PAGE->cm
->modname
=== 'forum' && $PAGE->cm
->instance
== $forumid
8035 && $PAGE->context
->contextlevel
== CONTEXT_MODULE
&& $PAGE->context
->instanceid
== $PAGE->cm
->id
) {
8036 $context = $PAGE->context
;
8038 $cm = get_coursemodule_from_instance('forum', $forumid);
8039 $context = \context_module
::instance($cm->id
);
8047 * Mark the activity completed (if required) and trigger the course_module_viewed event.
8049 * @param stdClass $forum forum object
8050 * @param stdClass $course course object
8051 * @param stdClass $cm course module object
8052 * @param stdClass $context context object
8055 function forum_view($forum, $course, $cm, $context) {
8058 $completion = new completion_info($course);
8059 $completion->set_module_viewed($cm);
8061 // Trigger course_module_viewed event.
8064 'context' => $context,
8065 'objectid' => $forum->id
8068 $event = \mod_forum\event\course_module_viewed
::create($params);
8069 $event->add_record_snapshot('course_modules', $cm);
8070 $event->add_record_snapshot('course', $course);
8071 $event->add_record_snapshot('forum', $forum);
8076 * Trigger the discussion viewed event
8078 * @param stdClass $modcontext module context object
8079 * @param stdClass $forum forum object
8080 * @param stdClass $discussion discussion object
8083 function forum_discussion_view($modcontext, $forum, $discussion) {
8085 'context' => $modcontext,
8086 'objectid' => $discussion->id
,
8089 $event = \mod_forum\event\discussion_viewed
::create($params);
8090 $event->add_record_snapshot('forum_discussions', $discussion);
8091 $event->add_record_snapshot('forum', $forum);
8096 * Set the discussion to pinned and trigger the discussion pinned event
8098 * @param stdClass $modcontext module context object
8099 * @param stdClass $forum forum object
8100 * @param stdClass $discussion discussion object
8103 function forum_discussion_pin($modcontext, $forum, $discussion) {
8106 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED
, array('id' => $discussion->id
));
8109 'context' => $modcontext,
8110 'objectid' => $discussion->id
,
8111 'other' => array('forumid' => $forum->id
)
8114 $event = \mod_forum\event\discussion_pinned
::create($params);
8115 $event->add_record_snapshot('forum_discussions', $discussion);
8120 * Set discussion to unpinned and trigger the discussion unpin event
8122 * @param stdClass $modcontext module context object
8123 * @param stdClass $forum forum object
8124 * @param stdClass $discussion discussion object
8127 function forum_discussion_unpin($modcontext, $forum, $discussion) {
8130 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED
, array('id' => $discussion->id
));
8133 'context' => $modcontext,
8134 'objectid' => $discussion->id
,
8135 'other' => array('forumid' => $forum->id
)
8138 $event = \mod_forum\event\discussion_unpinned
::create($params);
8139 $event->add_record_snapshot('forum_discussions', $discussion);
8144 * Add nodes to myprofile page.
8146 * @param \core_user\output\myprofile\tree $tree Tree object
8147 * @param stdClass $user user object
8148 * @param bool $iscurrentuser
8149 * @param stdClass $course Course object
8153 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree
$tree, $user, $iscurrentuser, $course) {
8154 if (isguestuser($user)) {
8155 // The guest user cannot post, so it is not possible to view any posts.
8156 // May as well just bail aggressively here.
8159 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id
));
8160 if (!empty($course)) {
8161 $postsurl->param('course', $course->id
);
8163 $string = get_string('forumposts', 'mod_forum');
8164 $node = new core_user\output\myprofile\node
('miscellaneous', 'forumposts', $string, null, $postsurl);
8165 $tree->add_node($node);
8167 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id
, 'mode' => 'discussions'));
8168 if (!empty($course)) {
8169 $discussionssurl->param('course', $course->id
);
8171 $string = get_string('myprofileotherdis', 'mod_forum');
8172 $node = new core_user\output\myprofile\node
('miscellaneous', 'forumdiscussions', $string, null,
8174 $tree->add_node($node);
8180 * Checks whether the author's name and picture for a given post should be hidden or not.
8182 * @param object $post The forum post.
8183 * @param object $forum The forum object.
8185 * @throws coding_exception
8187 function forum_is_author_hidden($post, $forum) {
8188 if (!isset($post->parent
)) {
8189 throw new coding_exception('$post->parent must be set.');
8191 if (!isset($forum->type
)) {
8192 throw new coding_exception('$forum->type must be set.');
8194 if ($forum->type
=== 'single' && empty($post->parent
)) {
8201 * Manage inplace editable saves.
8203 * @param string $itemtype The type of item.
8204 * @param int $itemid The ID of the item.
8205 * @param mixed $newvalue The new value
8208 function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) {
8211 if ($itemtype === 'digestoptions') {
8212 // The itemid is the forumid.
8213 $forum = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST
);
8214 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
8215 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
8216 $context = context_module
::instance($cm->id
);
8218 $PAGE->set_context($context);
8219 require_login($course, false, $cm);
8220 forum_set_user_maildigest($forum, $newvalue);
8222 $renderer = $PAGE->get_renderer('mod_forum');
8223 return $renderer->render_digest_options($forum, $newvalue);
8228 * Determine whether the specified discussion is time-locked.
8230 * @param stdClass $forum The forum that the discussion belongs to
8231 * @param stdClass $discussion The discussion to test
8234 function forum_discussion_is_locked($forum, $discussion) {
8235 if (empty($forum->lockdiscussionafter
)) {
8239 if ($forum->type
=== 'single') {
8240 // It does not make sense to lock a single discussion forum.
8244 if (($discussion->timemodified +
$forum->lockdiscussionafter
) < time()) {
8252 * Check if the module has any update that affects the current user since a given time.
8254 * @param cm_info $cm course module data
8255 * @param int $from the time to check updates from
8256 * @param array $filter if we need to check only specific updates
8257 * @return stdClass an object with the different type of areas indicating if they were updated or not
8260 function forum_check_updates_since(cm_info
$cm, $from, $filter = array()) {
8262 $context = $cm->context
;
8263 $updates = new stdClass();
8264 if (!has_capability('mod/forum:viewdiscussion', $context)) {
8268 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
8270 // Check if there are new discussions in the forum.
8271 $updates->discussions
= (object) array('updated' => false);
8272 $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS
, $from);
8273 if (!empty($discussions)) {
8274 $updates->discussions
->updated
= true;
8275 $updates->discussions
->itemids
= array_keys($discussions);
8282 * Check if the user can create attachments in a forum.
8283 * @param stdClass $forum forum object
8284 * @param stdClass $context context object
8285 * @return bool true if the user can create attachments, false otherwise
8288 function forum_can_create_attachment($forum, $context) {
8289 // If maxbytes == 1 it means no attachments at all.
8290 if (empty($forum->maxattachments
) ||
$forum->maxbytes
== 1 ||
8291 !has_capability('mod/forum:createattachment', $context)) {
8298 * Get icon mapping for font-awesome.
8302 function mod_forum_get_fontawesome_icon_map() {
8304 'mod_forum:i/pinned' => 'fa-map-pin',
8305 'mod_forum:t/selected' => 'fa-check',
8306 'mod_forum:t/subscribed' => 'fa-envelope-o',
8307 'mod_forum:t/unsubscribed' => 'fa-envelope-open-o',
8312 * Callback function that determines whether an action event should be showing its item count
8313 * based on the event type and the item count.
8315 * @param calendar_event $event The calendar event.
8316 * @param int $itemcount The item count associated with the action event.
8319 function mod_forum_core_calendar_event_action_shows_item_count(calendar_event
$event, $itemcount = 0) {
8320 // Always show item count for forums if item count is greater than 1.
8321 // If only one action is required than it is obvious and we don't show it for other modules.
8322 return $itemcount > 1;
8326 * This function receives a calendar event and returns the action associated with it, or null if there is none.
8328 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
8329 * is not displayed on the block.
8331 * @param calendar_event $event
8332 * @param \core_calendar\action_factory $factory
8333 * @return \core_calendar\local\event\entities\action_interface|null
8335 function mod_forum_core_calendar_provide_event_action(calendar_event
$event,
8336 \core_calendar\action_factory
$factory) {
8339 $cm = get_fast_modinfo($event->courseid
)->instances
['forum'][$event->instance
];
8340 $context = context_module
::instance($cm->id
);
8342 if (!has_capability('mod/forum:viewdiscussion', $context)) {
8346 $completion = new \
completion_info($cm->get_course());
8348 $completiondata = $completion->get_data($cm, false);
8350 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
8354 // Get action itemcount.
8356 $forum = $DB->get_record('forum', array('id' => $cm->instance
));
8362 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
8364 fp.userid=:userid AND fd.forum=:forumid";
8365 $postcountparams = array('userid' => $USER->id
, 'forumid' => $forum->id
);
8367 if ($forum->completiondiscussions
) {
8368 $count = $DB->count_records('forum_discussions', array('forum' => $forum->id
, 'userid' => $USER->id
));
8369 $itemcount +
= ($forum->completiondiscussions
>= $count) ?
($forum->completiondiscussions
- $count) : 0;
8372 if ($forum->completionreplies
) {
8373 $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams);
8374 $itemcount +
= ($forum->completionreplies
>= $count) ?
($forum->completionreplies
- $count) : 0;
8377 if ($forum->completionposts
) {
8378 $count = $DB->get_field_sql($postcountsql, $postcountparams);
8379 $itemcount +
= ($forum->completionposts
>= $count) ?
($forum->completionposts
- $count) : 0;
8382 // Well there is always atleast one actionable item (view forum, etc).
8383 $itemcount = $itemcount > 0 ?
$itemcount : 1;
8385 return $factory->create_instance(
8387 new \
moodle_url('/mod/forum/view.php', ['id' => $cm->id
]),
8394 * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information
8395 * for the course (see resource).
8397 * Given a course_module object, this function returns any "extra" information that may be needed
8398 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
8400 * @param stdClass $coursemodule The coursemodule object (record).
8401 * @return cached_cm_info An object on information that the courses
8402 * will know about (most noticeably, an icon).
8404 function forum_get_coursemodule_info($coursemodule) {
8407 $dbparams = ['id' => $coursemodule->instance
];
8408 $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies';
8409 if (!$forum = $DB->get_record('forum', $dbparams, $fields)) {
8413 $result = new cached_cm_info();
8414 $result->name
= $forum->name
;
8416 if ($coursemodule->showdescription
) {
8417 // Convert intro to html. Do not filter cached version, filters run at display time.
8418 $result->content
= format_module_intro('forum', $forum, $coursemodule->id
, false);
8421 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
8422 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
8423 $result->customdata
['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions
;
8424 $result->customdata
['customcompletionrules']['completionreplies'] = $forum->completionreplies
;
8425 $result->customdata
['customcompletionrules']['completionposts'] = $forum->completionposts
;
8432 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
8434 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
8435 * @return array $descriptions the array of descriptions for the custom rules.
8437 function mod_forum_get_completion_active_rule_descriptions($cm) {
8438 // Values will be present in cm_info, and we assume these are up to date.
8439 if (empty($cm->customdata
['customcompletionrules'])
8440 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
8445 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
8447 case 'completiondiscussions':
8451 $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val);
8453 case 'completionreplies':
8457 $descriptions[] = get_string('completionrepliesdesc', 'forum', $val);
8459 case 'completionposts':
8463 $descriptions[] = get_string('completionpostsdesc', 'forum', $val);
8469 return $descriptions;