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);
67 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
70 * Given an object containing all the necessary data,
71 * (defined by the form in mod_form.php) this function
72 * will create a new instance and return the id number
73 * of the new instance.
75 * @param stdClass $forum add forum instance
76 * @param mod_forum_mod_form $mform
77 * @return int intance id
79 function forum_add_instance($forum, $mform = null) {
82 $forum->timemodified
= time();
84 if (empty($forum->assessed
)) {
88 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
89 $forum->assesstimestart
= 0;
90 $forum->assesstimefinish
= 0;
93 $forum->id
= $DB->insert_record('forum', $forum);
94 $modcontext = context_module
::instance($forum->coursemodule
);
96 if ($forum->type
== 'single') { // Create related discussion.
97 $discussion = new stdClass();
98 $discussion->course
= $forum->course
;
99 $discussion->forum
= $forum->id
;
100 $discussion->name
= $forum->name
;
101 $discussion->assessed
= $forum->assessed
;
102 $discussion->message
= $forum->intro
;
103 $discussion->messageformat
= $forum->introformat
;
104 $discussion->messagetrust
= trusttext_trusted(context_course
::instance($forum->course
));
105 $discussion->mailnow
= false;
106 $discussion->groupid
= -1;
110 $discussion->id
= forum_add_discussion($discussion, null, $message);
112 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
113 // Ugly hack - we need to copy the files somehow.
114 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id
), '*', MUST_EXIST
);
115 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
117 $options = array('subdirs'=>true); // Use the same options as intro field!
118 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
119 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
123 forum_grade_item_update($forum);
129 * Handle changes following the creation of a forum instance.
130 * This function is typically called by the course_module_created observer.
132 * @param object $context the forum context
133 * @param stdClass $forum The forum object
136 function forum_instance_created($context, $forum) {
137 if ($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) {
138 $users = \mod_forum\subscriptions
::get_potential_subscribers($context, 0, 'u.id, u.email');
139 foreach ($users as $user) {
140 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $context);
146 * Given an object containing all the necessary data,
147 * (defined by the form in mod_form.php) this function
148 * will update an existing instance with new data.
151 * @param object $forum forum instance (with magic quotes)
152 * @return bool success
154 function forum_update_instance($forum, $mform) {
155 global $DB, $OUTPUT, $USER;
157 $forum->timemodified
= time();
158 $forum->id
= $forum->instance
;
160 if (empty($forum->assessed
)) {
161 $forum->assessed
= 0;
164 if (empty($forum->ratingtime
) or empty($forum->assessed
)) {
165 $forum->assesstimestart
= 0;
166 $forum->assesstimefinish
= 0;
169 $oldforum = $DB->get_record('forum', array('id'=>$forum->id
));
171 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
172 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
173 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
174 if (($oldforum->assessed
<>$forum->assessed
) or ($oldforum->scale
<>$forum->scale
)) {
175 forum_update_grades($forum); // recalculate grades for the forum
178 if ($forum->type
== 'single') { // Update related discussion and post.
179 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
), 'timemodified ASC');
180 if (!empty($discussions)) {
181 if (count($discussions) > 1) {
182 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
184 $discussion = array_pop($discussions);
186 // try to recover by creating initial discussion - MDL-16262
187 $discussion = new stdClass();
188 $discussion->course
= $forum->course
;
189 $discussion->forum
= $forum->id
;
190 $discussion->name
= $forum->name
;
191 $discussion->assessed
= $forum->assessed
;
192 $discussion->message
= $forum->intro
;
193 $discussion->messageformat
= $forum->introformat
;
194 $discussion->messagetrust
= true;
195 $discussion->mailnow
= false;
196 $discussion->groupid
= -1;
200 forum_add_discussion($discussion, null, $message);
202 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id
))) {
203 print_error('cannotadd', 'forum');
206 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
))) {
207 print_error('cannotfindfirstpost', 'forum');
210 $cm = get_coursemodule_from_instance('forum', $forum->id
);
211 $modcontext = context_module
::instance($cm->id
, MUST_EXIST
);
213 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost
), '*', MUST_EXIST
);
214 $post->subject
= $forum->name
;
215 $post->message
= $forum->intro
;
216 $post->messageformat
= $forum->introformat
;
217 $post->messagetrust
= trusttext_trusted($modcontext);
218 $post->modified
= $forum->timemodified
;
219 $post->userid
= $USER->id
; // MDL-18599, so that current teacher can take ownership of activities.
221 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
222 // Ugly hack - we need to copy the files somehow.
223 $options = array('subdirs'=>true); // Use the same options as intro field!
224 $post->message
= file_save_draft_area_files($draftid, $modcontext->id
, 'mod_forum', 'post', $post->id
, $options, $post->message
);
227 $DB->update_record('forum_posts', $post);
228 $discussion->name
= $forum->name
;
229 $DB->update_record('forum_discussions', $discussion);
232 $DB->update_record('forum', $forum);
234 $modcontext = context_module
::instance($forum->coursemodule
);
235 if (($forum->forcesubscribe
== FORUM_INITIALSUBSCRIBE
) && ($oldforum->forcesubscribe
<> $forum->forcesubscribe
)) {
236 $users = \mod_forum\subscriptions
::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
237 foreach ($users as $user) {
238 \mod_forum\subscriptions
::subscribe_user($user->id
, $forum, $modcontext);
242 forum_grade_item_update($forum);
249 * Given an ID of an instance of this module,
250 * this function will permanently delete the instance
251 * and any data that depends on it.
254 * @param int $id forum instance id
255 * @return bool success
257 function forum_delete_instance($id) {
260 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
263 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
)) {
266 if (!$course = $DB->get_record('course', array('id'=>$cm->course
))) {
270 $context = context_module
::instance($cm->id
);
272 // now get rid of all files
273 $fs = get_file_storage();
274 $fs->delete_area_files($context->id
);
278 // Delete digest and subscription preferences.
279 $DB->delete_records('forum_digests', array('forum' => $forum->id
));
280 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id
));
281 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id
));
283 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id
))) {
284 foreach ($discussions as $discussion) {
285 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
291 forum_tp_delete_read_records(-1, -1, -1, $forum->id
);
293 if (!$DB->delete_records('forum', array('id'=>$forum->id
))) {
297 forum_grade_item_delete($forum);
304 * Indicates API features that the forum supports.
306 * @uses FEATURE_GROUPS
307 * @uses FEATURE_GROUPINGS
308 * @uses FEATURE_MOD_INTRO
309 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
310 * @uses FEATURE_COMPLETION_HAS_RULES
311 * @uses FEATURE_GRADE_HAS_GRADE
312 * @uses FEATURE_GRADE_OUTCOMES
313 * @param string $feature
314 * @return mixed True if yes (some features may use other values)
316 function forum_supports($feature) {
318 case FEATURE_GROUPS
: return true;
319 case FEATURE_GROUPINGS
: return true;
320 case FEATURE_MOD_INTRO
: return true;
321 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
322 case FEATURE_COMPLETION_HAS_RULES
: return true;
323 case FEATURE_GRADE_HAS_GRADE
: return true;
324 case FEATURE_GRADE_OUTCOMES
: return true;
325 case FEATURE_RATE
: return true;
326 case FEATURE_BACKUP_MOODLE2
: return true;
327 case FEATURE_SHOW_DESCRIPTION
: return true;
328 case FEATURE_PLAGIARISM
: return true;
330 default: return null;
336 * Obtains the automatic completion state for this forum based on any conditions
341 * @param object $course Course
342 * @param object $cm Course-module
343 * @param int $userid User ID
344 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
345 * @return bool True if completed, false if not. (If no conditions, then return
346 * value depends on comparison type)
348 function forum_get_completion_state($course,$cm,$userid,$type) {
352 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance
)))) {
353 throw new Exception("Can't find forum {$cm->instance}");
356 $result=$type; // Default return value
358 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id
);
364 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
366 fp.userid=:userid AND fd.forum=:forumid";
368 if ($forum->completiondiscussions
) {
369 $value = $forum->completiondiscussions
<=
370 $DB->count_records('forum_discussions',array('forum'=>$forum->id
,'userid'=>$userid));
371 if ($type == COMPLETION_AND
) {
372 $result = $result && $value;
374 $result = $result ||
$value;
377 if ($forum->completionreplies
) {
378 $value = $forum->completionreplies
<=
379 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
380 if ($type==COMPLETION_AND
) {
381 $result = $result && $value;
383 $result = $result ||
$value;
386 if ($forum->completionposts
) {
387 $value = $forum->completionposts
<= $DB->get_field_sql($postcountsql,$postcountparams);
388 if ($type == COMPLETION_AND
) {
389 $result = $result && $value;
391 $result = $result ||
$value;
399 * Create a message-id string to use in the custom headers of forum notification emails
401 * message-id is used by email clients to identify emails and to nest conversations
403 * @param int $postid The ID of the forum post we are notifying the user about
404 * @param int $usertoid The ID of the user being notified
405 * @param string $hostname The server's hostname
406 * @return string A unique message-id
408 function forum_get_email_message_id($postid, $usertoid, $hostname) {
409 return '<'.hash('sha256',$postid.'to'.$usertoid).'@'.$hostname.'>';
413 * Removes properties from user record that are not necessary
414 * for sending post notifications.
415 * @param stdClass $user
416 * @return void, $user parameter is modified
418 function forum_cron_minimise_user_record(stdClass
$user) {
420 // We store large amount of users in one huge array,
421 // make sure we do not store info there we do not actually need
422 // in mail generation code or messaging.
424 unset($user->institution
);
425 unset($user->department
);
426 unset($user->address
);
429 unset($user->currentlogin
);
430 unset($user->description
);
431 unset($user->descriptionformat
);
435 * Function to be run periodically according to the scheduled task.
437 * Finds all posts that have yet to be mailed out, and mails them
438 * out to all subscribers as well as other maintance tasks.
440 * NOTE: Since 2.7.2 this function is run by scheduled task rather
441 * than standard cron.
443 * @todo MDL-44734 The function will be split up into seperate tasks.
445 function forum_cron() {
446 global $CFG, $USER, $DB;
450 // All users that are subscribed to any post that needs sending,
451 // please increase $CFG->extramemorylimit on large sites that
452 // send notifications to a large number of users.
454 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
457 $mailcount = array();
458 $errorcount = array();
461 $discussions = array();
464 $coursemodules = array();
465 $subscribedusers = array();
466 $messageinboundhandlers = array();
468 // Posts older than 2 days will not be mailed. This is to avoid the problem where
469 // cron has not been running for a long time, and then suddenly people are flooded
470 // with mail from the past few weeks or months
472 $endtime = $timenow - $CFG->maxeditingtime
;
473 $starttime = $endtime - 48 * 3600; // Two days earlier
475 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
476 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
478 foreach ($digestsset as $thisrow) {
479 if (!isset($digests[$thisrow->forum
])) {
480 $digests[$thisrow->forum
] = array();
482 $digests[$thisrow->forum
][$thisrow->userid
] = $thisrow->maildigest
;
484 $digestsset->close();
486 // Create the generic messageinboundgenerator.
487 $messageinboundgenerator = new \core\message\inbound\address_manager
();
488 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
490 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
491 // Mark them all now as being mailed. It's unlikely but possible there
492 // might be an error later so that a post is NOT actually mailed out,
493 // but since mail isn't crucial, we can accept this risk. Doing it now
494 // prevents the risk of duplicated mails, which is a worse problem.
496 if (!forum_mark_old_posts_as_mailed($endtime)) {
497 mtrace('Errors occurred while trying to mark some posts as being mailed.');
498 return false; // Don't continue trying to mail them, in case we are in a cron loop
501 // checking post validity, and adding users to loop through later
502 foreach ($posts as $pid => $post) {
504 $discussionid = $post->discussion
;
505 if (!isset($discussions[$discussionid])) {
506 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion
))) {
507 $discussions[$discussionid] = $discussion;
508 \mod_forum\subscriptions
::fill_subscription_cache($discussion->forum
);
509 \mod_forum\subscriptions
::fill_discussion_subscription_cache($discussion->forum
);
512 mtrace('Could not find discussion ' . $discussionid);
517 $forumid = $discussions[$discussionid]->forum
;
518 if (!isset($forums[$forumid])) {
519 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
520 $forums[$forumid] = $forum;
522 mtrace('Could not find forum '.$forumid);
527 $courseid = $forums[$forumid]->course
;
528 if (!isset($courses[$courseid])) {
529 if ($course = $DB->get_record('course', array('id' => $courseid))) {
530 $courses[$courseid] = $course;
532 mtrace('Could not find course '.$courseid);
537 if (!isset($coursemodules[$forumid])) {
538 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
539 $coursemodules[$forumid] = $cm;
541 mtrace('Could not find course module for forum '.$forumid);
547 // Save the Inbound Message datakey here to reduce DB queries later.
548 $messageinboundgenerator->set_data($pid);
549 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
551 // Caching subscribed users of each forum.
552 if (!isset($subscribedusers[$forumid])) {
553 $modcontext = context_module
::instance($coursemodules[$forumid]->id
);
554 if ($subusers = \mod_forum\subscriptions
::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
556 foreach ($subusers as $postuser) {
557 // this user is subscribed to this forum
558 $subscribedusers[$forumid][$postuser->id
] = $postuser->id
;
560 if ($userscount > FORUM_CRON_USER_CACHE
) {
561 // Store minimal user info.
562 $minuser = new stdClass();
563 $minuser->id
= $postuser->id
;
564 $users[$postuser->id
] = $minuser;
566 // Cache full user record.
567 forum_cron_minimise_user_record($postuser);
568 $users[$postuser->id
] = $postuser;
576 $mailcount[$pid] = 0;
577 $errorcount[$pid] = 0;
581 if ($users && $posts) {
583 $urlinfo = parse_url($CFG->wwwroot
);
584 $hostname = $urlinfo['host'];
586 foreach ($users as $userto) {
587 // Terminate if processing of any account takes longer than 2 minutes.
588 core_php_time_limit
::raise(120);
590 mtrace('Processing user ' . $userto->id
);
592 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
593 if (isset($userto->username
)) {
594 $userto = clone($userto);
596 $userto = $DB->get_record('user', array('id' => $userto->id
));
597 forum_cron_minimise_user_record($userto);
599 $userto->viewfullnames
= array();
600 $userto->canpost
= array();
601 $userto->markposts
= array();
603 // Setup this user so that the capabilities are cached, and environment matches receiving user.
604 cron_setup_user($userto);
607 foreach ($coursemodules as $forumid => $unused) {
608 $coursemodules[$forumid]->cache
= new stdClass();
609 $coursemodules[$forumid]->cache
->caps
= array();
610 unset($coursemodules[$forumid]->uservisible
);
613 foreach ($posts as $pid => $post) {
614 $discussion = $discussions[$post->discussion
];
615 $forum = $forums[$discussion->forum
];
616 $course = $courses[$forum->course
];
617 $cm =& $coursemodules[$forum->id
];
619 // Do some checks to see if we can bail out now.
621 // Only active enrolled users are in the list of subscribers.
622 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
623 if (!isset($subscribedusers[$forum->id
][$userto->id
])) {
624 // The user does not subscribe to this forum.
628 if (!\mod_forum\subscriptions
::is_subscribed($userto->id
, $forum, $post->discussion
, $coursemodules[$forum->id
])) {
629 // The user does not subscribe to this forum, or to this specific discussion.
633 if ($subscriptiontime = \mod_forum\subscriptions
::fetch_discussion_subscription($forum->id
, $userto->id
)) {
634 // Skip posts if the user subscribed to the discussion after it was created.
635 if (isset($subscriptiontime[$post->discussion
]) && ($subscriptiontime[$post->discussion
] > $post->created
)) {
640 // Don't send email if the forum is Q&A and the user has not posted.
641 // Initial topics are still mailed.
642 if ($forum->type
== 'qanda' && !forum_get_user_posted_time($discussion->id
, $userto->id
) && $pid != $discussion->firstpost
) {
643 mtrace('Did not email ' . $userto->id
.' because user has not posted in discussion');
647 // Get info about the sending user.
648 if (array_key_exists($post->userid
, $users)) {
649 // We might know the user already.
650 $userfrom = $users[$post->userid
];
651 if (!isset($userfrom->idnumber
)) {
652 // Minimalised user info, fetch full record.
653 $userfrom = $DB->get_record('user', array('id' => $userfrom->id
));
654 forum_cron_minimise_user_record($userfrom);
657 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid
))) {
658 forum_cron_minimise_user_record($userfrom);
659 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
660 if ($userscount <= FORUM_CRON_USER_CACHE
) {
662 $users[$userfrom->id
] = $userfrom;
665 mtrace('Could not find user ' . $post->userid
. ', author of post ' . $post->id
. '. Unable to send message.');
669 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
671 // Setup global $COURSE properly - needed for roles and languages.
672 cron_setup_user($userto, $course);
675 if (!isset($userto->viewfullnames
[$forum->id
])) {
676 $modcontext = context_module
::instance($cm->id
);
677 $userto->viewfullnames
[$forum->id
] = has_capability('moodle/site:viewfullnames', $modcontext);
679 if (!isset($userto->canpost
[$discussion->id
])) {
680 $modcontext = context_module
::instance($cm->id
);
681 $userto->canpost
[$discussion->id
] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
683 if (!isset($userfrom->groups
[$forum->id
])) {
684 if (!isset($userfrom->groups
)) {
685 $userfrom->groups
= array();
686 if (isset($users[$userfrom->id
])) {
687 $users[$userfrom->id
]->groups
= array();
690 $userfrom->groups
[$forum->id
] = groups_get_all_groups($course->id
, $userfrom->id
, $cm->groupingid
);
691 if (isset($users[$userfrom->id
])) {
692 $users[$userfrom->id
]->groups
[$forum->id
] = $userfrom->groups
[$forum->id
];
696 // Make sure groups allow this user to see this email.
697 if ($discussion->groupid
> 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
698 // Groups are being used.
699 if (!groups_group_exists($discussion->groupid
)) {
700 // Can't find group - be safe and don't this message.
704 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
705 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
710 // Make sure we're allowed to see the post.
711 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
712 mtrace('User ' . $userto->id
.' can not see ' . $post->id
. '. Not sending message.');
716 // OK so we need to send the email.
718 // Does the user want this post in a digest? If so postpone it for now.
719 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id
);
721 if ($maildigest > 0) {
722 // This user wants the mails to be in digest form.
723 $queue = new stdClass();
724 $queue->userid
= $userto->id
;
725 $queue->discussionid
= $discussion->id
;
726 $queue->postid
= $post->id
;
727 $queue->timemodified
= $post->created
;
728 $DB->insert_record('forum_queue', $queue);
732 // Prepare to actually send the post now, and build up the content.
734 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name
)));
736 $userfrom->customheaders
= array (
737 // Headers to make emails easier to track.
739 'List-Id: "' . $cleanforumname . '" <moodleforum' . $forum->id
. '@' . $hostname.'>',
740 'List-Help: ' . $CFG->wwwroot
. '/mod/forum/view.php?f=' . $forum->id
,
741 'Message-ID: ' . forum_get_email_message_id($post->id
, $userto->id
, $hostname),
742 'X-Course-Id: ' . $course->id
,
743 'X-Course-Name: ' . format_string($course->fullname
, true)
747 // This post is a reply, so add headers for threading (see MDL-22551).
748 $userfrom->customheaders
[] = 'In-Reply-To: ' . forum_get_email_message_id($post->parent
, $userto->id
, $hostname);
749 $userfrom->customheaders
[] = 'References: ' . forum_get_email_message_id($post->parent
, $userto->id
, $hostname);
752 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
754 // Generate a reply-to address from using the Inbound Message handler.
755 $replyaddress = null;
756 if ($userto->canpost
[$discussion->id
] && array_key_exists($post->id
, $messageinboundhandlers)) {
757 $messageinboundgenerator->set_data($post->id
, $messageinboundhandlers[$post->id
]);
758 $replyaddress = $messageinboundgenerator->generate($userto->id
);
762 $a->courseshortname
= $shortname;
763 $a->forumname
= $cleanforumname;
764 $a->subject
= format_string($post->subject
, true);
765 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
766 $posttext = forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false,
768 $posthtml = forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
771 // Send the post now!
772 mtrace('Sending ', '');
774 $eventdata = new stdClass();
775 $eventdata->component
= 'mod_forum';
776 $eventdata->name
= 'posts';
777 $eventdata->userfrom
= $userfrom;
778 $eventdata->userto
= $userto;
779 $eventdata->subject
= $postsubject;
780 $eventdata->fullmessage
= $posttext;
781 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
782 $eventdata->fullmessagehtml
= $posthtml;
783 $eventdata->notification
= 1;
784 $eventdata->replyto
= $replyaddress;
786 // If forum_replytouser is not set then send mail using the noreplyaddress.
787 if (empty($CFG->forum_replytouser
)) {
788 // Clone userfrom as it is referenced by $users.
789 $cloneduserfrom = clone($userfrom);
790 $cloneduserfrom->email
= $CFG->noreplyaddress
;
791 $eventdata->userfrom
= $cloneduserfrom;
794 $smallmessagestrings = new stdClass();
795 $smallmessagestrings->user
= fullname($userfrom);
796 $smallmessagestrings->forumname
= "$shortname: " . format_string($forum->name
, true) . ": " . $discussion->name
;
797 $smallmessagestrings->message
= $post->message
;
799 // Make sure strings are in message recipients language.
800 $eventdata->smallmessage
= get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang
);
802 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id
), 'p' . $post->id
);
803 $eventdata->contexturl
= $contexturl->out();
804 $eventdata->contexturlname
= $discussion->name
;
806 $mailresult = message_send($eventdata);
808 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
809 " ($userto->email) .. not trying again.");
810 $errorcount[$post->id
]++
;
812 $mailcount[$post->id
]++
;
814 // Mark post as read if forum_usermarksread is set off.
815 if (!$CFG->forum_usermarksread
) {
816 $userto->markposts
[$post->id
] = $post->id
;
820 mtrace('post ' . $post->id
. ': ' . $post->subject
);
823 // Mark processed posts as read.
824 forum_tp_mark_posts_read($userto, $userto->markposts
);
830 foreach ($posts as $post) {
831 mtrace($mailcount[$post->id
]." users were sent post $post->id, '$post->subject'");
832 if ($errorcount[$post->id
]) {
833 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR
, array('id' => $post->id
));
838 // release some memory
839 unset($subscribedusers);
845 $sitetimezone = $CFG->timezone
;
847 // Now see if there are any digest mails waiting to be sent, and if we should send them
849 mtrace('Starting digest processing...');
851 core_php_time_limit
::raise(300); // terminate if not able to fetch all digests in 5 minutes
853 if (!isset($CFG->digestmailtimelast
)) { // To catch the first time
854 set_config('digestmailtimelast', 0);
858 $digesttime = usergetmidnight($timenow, $sitetimezone) +
($CFG->digestmailtime
* 3600);
860 // Delete any really old ones (normally there shouldn't be any)
861 $weekago = $timenow - (7 * 24 * 3600);
862 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
863 mtrace ('Cleaned old digest records');
865 if ($CFG->digestmailtimelast
< $digesttime and $timenow > $digesttime) {
867 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
869 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
871 if ($digestposts_rs->valid()) {
873 // We have work to do
876 //caches - reuse the those filled before too
877 $discussionposts = array();
878 $userdiscussions = array();
880 foreach ($digestposts_rs as $digestpost) {
881 if (!isset($posts[$digestpost->postid
])) {
882 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid
))) {
883 $posts[$digestpost->postid
] = $post;
888 $discussionid = $digestpost->discussionid
;
889 if (!isset($discussions[$discussionid])) {
890 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
891 $discussions[$discussionid] = $discussion;
896 $forumid = $discussions[$discussionid]->forum
;
897 if (!isset($forums[$forumid])) {
898 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
899 $forums[$forumid] = $forum;
905 $courseid = $forums[$forumid]->course
;
906 if (!isset($courses[$courseid])) {
907 if ($course = $DB->get_record('course', array('id' => $courseid))) {
908 $courses[$courseid] = $course;
914 if (!isset($coursemodules[$forumid])) {
915 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
916 $coursemodules[$forumid] = $cm;
921 $userdiscussions[$digestpost->userid
][$digestpost->discussionid
] = $digestpost->discussionid
;
922 $discussionposts[$digestpost->discussionid
][$digestpost->postid
] = $digestpost->postid
;
924 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
926 // Data collected, start sending out emails to each user
927 foreach ($userdiscussions as $userid => $thesediscussions) {
929 core_php_time_limit
::raise(120); // terminate if processing of any account takes longer than 2 minutes
933 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
935 // First of all delete all the queue entries for this user
936 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
938 // Init user caches - we keep the cache for one cycle only,
939 // otherwise it would unnecessarily consume memory.
940 if (array_key_exists($userid, $users) and isset($users[$userid]->username
)) {
941 $userto = clone($users[$userid]);
943 $userto = $DB->get_record('user', array('id' => $userid));
944 forum_cron_minimise_user_record($userto);
946 $userto->viewfullnames
= array();
947 $userto->canpost
= array();
948 $userto->markposts
= array();
950 // Override the language and timezone of the "current" user, so that
951 // mail is customised for the receiver.
952 cron_setup_user($userto);
954 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname
, true));
956 $headerdata = new stdClass();
957 $headerdata->sitename
= format_string($site->fullname
, true);
958 $headerdata->userprefs
= $CFG->wwwroot
.'/user/edit.php?id='.$userid.'&course='.$site->id
;
960 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
961 $headerdata->userprefs
= '<a target="_blank" href="'.$headerdata->userprefs
.'">'.get_string('digestmailprefs', 'forum').'</a>';
963 $posthtml = "<head>";
964 /* foreach ($CFG->stylesheets as $stylesheet) {
966 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
968 $posthtml .= "</head>\n<body id=\"email\">\n";
969 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
971 foreach ($thesediscussions as $discussionid) {
973 core_php_time_limit
::raise(120); // to be reset for each post
975 $discussion = $discussions[$discussionid];
976 $forum = $forums[$discussion->forum
];
977 $course = $courses[$forum->course
];
978 $cm = $coursemodules[$forum->id
];
981 cron_setup_user($userto, $course);
984 if (!isset($userto->viewfullnames
[$forum->id
])) {
985 $modcontext = context_module
::instance($cm->id
);
986 $userto->viewfullnames
[$forum->id
] = has_capability('moodle/site:viewfullnames', $modcontext);
988 if (!isset($userto->canpost
[$discussion->id
])) {
989 $modcontext = context_module
::instance($cm->id
);
990 $userto->canpost
[$discussion->id
] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
993 $strforums = get_string('forums', 'forum');
994 $canunsubscribe = ! \mod_forum\subscriptions
::is_forcesubscribed($forum);
995 $canreply = $userto->canpost
[$discussion->id
];
996 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
998 $posttext .= "\n \n";
999 $posttext .= '=====================================================================';
1000 $posttext .= "\n \n";
1001 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name
,true);
1002 if ($discussion->name
!= $forum->name
) {
1003 $posttext .= " -> ".format_string($discussion->name
,true);
1006 $posttext .= $CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
;
1009 $posthtml .= "<p><font face=\"sans-serif\">".
1010 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
1011 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
1012 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name
,true)."</a>";
1013 if ($discussion->name
== $forum->name
) {
1014 $posthtml .= "</font></p>";
1016 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name
,true)."</a></font></p>";
1020 $postsarray = $discussionposts[$discussionid];
1023 foreach ($postsarray as $postid) {
1024 $post = $posts[$postid];
1026 if (array_key_exists($post->userid
, $users)) { // we might know him/her already
1027 $userfrom = $users[$post->userid
];
1028 if (!isset($userfrom->idnumber
)) {
1029 $userfrom = $DB->get_record('user', array('id' => $userfrom->id
));
1030 forum_cron_minimise_user_record($userfrom);
1033 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid
))) {
1034 forum_cron_minimise_user_record($userfrom);
1035 if ($userscount <= FORUM_CRON_USER_CACHE
) {
1037 $users[$userfrom->id
] = $userfrom;
1041 mtrace('Could not find user '.$post->userid
);
1045 if (!isset($userfrom->groups
[$forum->id
])) {
1046 if (!isset($userfrom->groups
)) {
1047 $userfrom->groups
= array();
1048 if (isset($users[$userfrom->id
])) {
1049 $users[$userfrom->id
]->groups
= array();
1052 $userfrom->groups
[$forum->id
] = groups_get_all_groups($course->id
, $userfrom->id
, $cm->groupingid
);
1053 if (isset($users[$userfrom->id
])) {
1054 $users[$userfrom->id
]->groups
[$forum->id
] = $userfrom->groups
[$forum->id
];
1058 $userfrom->customheaders
= array ("Precedence: Bulk");
1060 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id
);
1061 if ($maildigest == 2) {
1062 // Subjects and link only
1064 $posttext .= $CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
;
1065 $by = new stdClass();
1066 $by->name
= fullname($userfrom);
1067 $by->date
= userdate($post->modified
);
1068 $posttext .= "\n".format_string($post->subject
,true).' '.get_string("bynameondate", "forum", $by);
1069 $posttext .= "\n---------------------------------------------------------------------";
1071 $by->name
= "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&course=$course->id\">$by->name</a>";
1072 $posthtml .= '<div><a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
.'#p'.$post->id
.'">'.format_string($post->subject
,true).'</a> '.get_string("bynameondate", "forum", $by).'</div>';
1075 // The full treatment
1076 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
1077 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1079 // Create an array of postid's for this user to mark as read.
1080 if (!$CFG->forum_usermarksread
) {
1081 $userto->markposts
[$post->id
] = $post->id
;
1085 $footerlinks = array();
1086 if ($canunsubscribe) {
1087 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
1089 $footerlinks[] = get_string("everyoneissubscribed", "forum");
1091 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1092 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode(' ', $footerlinks) . '</font></div>';
1093 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
1095 $posthtml .= '</body>';
1097 if (empty($userto->mailformat
) ||
$userto->mailformat
!= 1) {
1098 // This user DOESN'T want to receive HTML
1102 $attachment = $attachname='';
1103 // Directly email forum digests rather than sending them via messaging, use the
1104 // site shortname as 'from name', the noreply address will be used by email_to_user.
1105 $mailresult = email_to_user($userto, $site->shortname
, $postsubject, $posttext, $posthtml, $attachment, $attachname);
1108 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1109 "($userto->email)... not trying again.");
1114 // Mark post as read if forum_usermarksread is set off
1115 forum_tp_mark_posts_read($userto, $userto->markposts
);
1119 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1120 set_config('digestmailtimelast', $timenow);
1125 if (!empty($usermailcount)) {
1126 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
1129 if (!empty($CFG->forum_lastreadclean
)) {
1131 if ($CFG->forum_lastreadclean +
(24*3600) < $timenow) {
1132 set_config('forum_lastreadclean', $timenow);
1133 mtrace('Removing old forum read tracking info...');
1134 forum_tp_clean_read_records();
1137 set_config('forum_lastreadclean', time());
1144 * Builds and returns the body of the email notification in plain text.
1148 * @uses CONTEXT_MODULE
1149 * @param object $course
1151 * @param object $forum
1152 * @param object $discussion
1153 * @param object $post
1154 * @param object $userfrom
1155 * @param object $userto
1156 * @param boolean $bare
1157 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1158 * @return string The email body in plain text format.
1160 function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false, $replyaddress = null) {
1163 $modcontext = context_module
::instance($cm->id
);
1165 if (!isset($userto->viewfullnames
[$forum->id
])) {
1166 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id
);
1168 $viewfullnames = $userto->viewfullnames
[$forum->id
];
1171 if (!isset($userto->canpost
[$discussion->id
])) {
1172 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1174 $canreply = $userto->canpost
[$discussion->id
];
1178 $by->name
= fullname($userfrom, $viewfullnames);
1179 $by->date
= userdate($post->modified
, "", $userto->timezone
);
1181 $strbynameondate = get_string('bynameondate', 'forum', $by);
1183 $strforums = get_string('forums', 'forum');
1185 $canunsubscribe = !\mod_forum\subscriptions
::is_forcesubscribed($forum);
1190 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
1191 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name
,true);
1193 if ($discussion->name
!= $forum->name
) {
1194 $posttext .= " -> ".format_string($discussion->name
,true);
1198 // add absolute file links
1199 $post->message
= file_rewrite_pluginfile_urls($post->message
, 'pluginfile.php', $modcontext->id
, 'mod_forum', 'post', $post->id
);
1202 $posttext .= $CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
;
1203 $posttext .= "\n---------------------------------------------------------------------\n";
1204 $posttext .= format_string($post->subject
,true);
1206 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
1208 $posttext .= "\n".$strbynameondate."\n";
1209 $posttext .= "---------------------------------------------------------------------\n";
1210 $posttext .= format_text_email($post->message
, $post->messageformat
);
1211 $posttext .= "\n\n";
1212 $posttext .= forum_print_attachments($post, $cm, "text");
1216 $posttext .= "---------------------------------------------------------------------\n";
1217 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1218 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1221 if ($canunsubscribe) {
1222 if (\mod_forum\subscriptions
::is_subscribed($userto->id
, $forum, null, $cm)) {
1223 // If subscribed to this forum, offer the unsubscribe link.
1224 $posttext .= "\n---------------------------------------------------------------------\n";
1225 $posttext .= get_string("unsubscribe", "forum");
1226 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1228 // Always offer the unsubscribe from discussion link.
1229 $posttext .= "\n---------------------------------------------------------------------\n";
1230 $posttext .= get_string("unsubscribediscussion", "forum");
1231 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id&d=$discussion->id\n";
1235 $posttext .= "\n---------------------------------------------------------------------\n";
1236 $posttext .= get_string("digestmailpost", "forum");
1237 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1239 if ($replyaddress) {
1240 $posttext .= "\n\n" . get_string('replytopostbyemail', 'mod_forum');
1247 * Builds and returns the body of the email notification in html format.
1250 * @param object $course
1252 * @param object $forum
1253 * @param object $discussion
1254 * @param object $post
1255 * @param object $userfrom
1256 * @param object $userto
1257 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1258 * @return string The email text in HTML format
1260 function forum_make_mail_html($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $replyaddress = null) {
1263 if ($userto->mailformat
!= 1) { // Needs to be HTML
1267 if (!isset($userto->canpost
[$discussion->id
])) {
1268 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course);
1270 $canreply = $userto->canpost
[$discussion->id
];
1273 $strforums = get_string('forums', 'forum');
1274 $canunsubscribe = ! \mod_forum\subscriptions
::is_forcesubscribed($forum);
1275 $shortname = format_string($course->shortname
, true, array('context' => context_course
::instance($course->id
)));
1277 $posthtml = '<head>';
1278 /* foreach ($CFG->stylesheets as $stylesheet) {
1280 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1282 $posthtml .= '</head>';
1283 $posthtml .= "\n<body id=\"email\">\n\n";
1285 $posthtml .= '<div class="navbar">'.
1286 '<a target="_blank" href="'.$CFG->wwwroot
.'/course/view.php?id='.$course->id
.'">'.$shortname.'</a> » '.
1287 '<a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/index.php?id='.$course->id
.'">'.$strforums.'</a> » '.
1288 '<a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/view.php?f='.$forum->id
.'">'.format_string($forum->name
,true).'</a>';
1289 if ($discussion->name
== $forum->name
) {
1290 $posthtml .= '</div>';
1292 $posthtml .= ' » <a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$discussion->id
.'">'.
1293 format_string($discussion->name
,true).'</a></div>';
1295 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
1297 if ($replyaddress) {
1298 $posthtml .= html_writer
::tag('p', get_string('replytopostbyemail', 'mod_forum'));
1301 $footerlinks = array();
1302 if ($canunsubscribe) {
1303 if (\mod_forum\subscriptions
::is_subscribed($userto->id
, $forum, null, $cm)) {
1304 // If subscribed to this forum, offer the unsubscribe link.
1305 $unsublink = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id
));
1306 $footerlinks[] = html_writer
::link($unsublink, get_string('unsubscribe', 'mod_forum'));
1308 // Always offer the unsubscribe from discussion link.
1309 $unsublink = new moodle_url('/mod/forum/subscribe.php', array(
1311 'd' => $discussion->id
,
1313 $footerlinks[] = html_writer
::link($unsublink, get_string('unsubscribediscussion', 'mod_forum'));
1315 $footerlinks[] = '<a href="' . $CFG->wwwroot
. '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
1317 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1318 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode(' ', $footerlinks) . '</div>';
1320 $posthtml .= '</body>';
1328 * @param object $course
1329 * @param object $user
1330 * @param object $mod TODO this is not used in this function, refactor
1331 * @param object $forum
1332 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
1334 function forum_user_outline($course, $user, $mod, $forum) {
1336 require_once("$CFG->libdir/gradelib.php");
1337 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
1338 if (empty($grades->items
[0]->grades
)) {
1341 $grade = reset($grades->items
[0]->grades
);
1344 $count = forum_count_user_posts($forum->id
, $user->id
);
1346 if ($count && $count->postcount
> 0) {
1347 $result = new stdClass();
1348 $result->info
= get_string("numposts", "forum", $count->postcount
);
1349 $result->time
= $count->lastpost
;
1351 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
1354 } else if ($grade) {
1355 $result = new stdClass();
1356 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
1358 //datesubmitted == time created. dategraded == time modified or time overridden
1359 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1360 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1361 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
1362 $result->time
= $grade->dategraded
;
1364 $result->time
= $grade->datesubmitted
;
1376 * @param object $coure
1377 * @param object $user
1378 * @param object $mod
1379 * @param object $forum
1381 function forum_user_complete($course, $user, $mod, $forum) {
1382 global $CFG,$USER, $OUTPUT;
1383 require_once("$CFG->libdir/gradelib.php");
1385 $grades = grade_get_grades($course->id
, 'mod', 'forum', $forum->id
, $user->id
);
1386 if (!empty($grades->items
[0]->grades
)) {
1387 $grade = reset($grades->items
[0]->grades
);
1388 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
1389 if ($grade->str_feedback
) {
1390 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
1394 if ($posts = forum_get_user_posts($forum->id
, $user->id
)) {
1396 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
)) {
1397 print_error('invalidcoursemodule');
1399 $discussions = forum_get_user_involved_discussions($forum->id
, $user->id
);
1401 foreach ($posts as $post) {
1402 if (!isset($discussions[$post->discussion
])) {
1405 $discussion = $discussions[$post->discussion
];
1407 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
1410 echo "<p>".get_string("noposts", "forum")."</p>";
1415 * Filters the forum discussions according to groups membership and config.
1417 * @since Moodle 2.8, 2.7.1, 2.6.4
1418 * @param array $discussions Discussions with new posts array
1419 * @return array Forums with the number of new posts
1421 function forum_filter_user_groups_discussions($discussions) {
1423 // Group the remaining discussions posts by their forumid.
1424 $filteredforums = array();
1426 // Discard not visible groups.
1427 foreach ($discussions as $discussion) {
1429 // Course data is already cached.
1430 $instances = get_fast_modinfo($discussion->course
)->get_instances();
1431 $forum = $instances['forum'][$discussion->forum
];
1433 // Continue if the user should not see this discussion.
1434 if (!forum_is_user_group_discussion($forum, $discussion->groupid
)) {
1438 // Grouping results by forum.
1439 if (empty($filteredforums[$forum->instance
])) {
1440 $filteredforums[$forum->instance
] = new stdClass();
1441 $filteredforums[$forum->instance
]->id
= $forum->id
;
1442 $filteredforums[$forum->instance
]->count
= 0;
1444 $filteredforums[$forum->instance
]->count +
= $discussion->count
;
1448 return $filteredforums;
1452 * Returns whether the discussion group is visible by the current user or not.
1454 * @since Moodle 2.8, 2.7.1, 2.6.4
1455 * @param cm_info $cm The discussion course module
1456 * @param int $discussiongroupid The discussion groupid
1459 function forum_is_user_group_discussion(cm_info
$cm, $discussiongroupid) {
1461 if ($discussiongroupid == -1 ||
$cm->effectivegroupmode
!= SEPARATEGROUPS
) {
1465 if (isguestuser()) {
1469 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
)) ||
1470 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid
))) {
1481 * @param array $courses
1482 * @param array $htmlarray
1484 function forum_print_overview($courses,&$htmlarray) {
1485 global $USER, $CFG, $DB, $SESSION;
1487 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1491 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
1495 // Courses to search for new posts
1496 $coursessqls = array();
1498 foreach ($courses as $course) {
1500 // If the user has never entered into the course all posts are pending
1501 if ($course->lastaccess
== 0) {
1502 $coursessqls[] = '(d.course = ?)';
1503 $params[] = $course->id
;
1505 // Only posts created after the course last access
1507 $coursessqls[] = '(d.course = ? AND p.created > ?)';
1508 $params[] = $course->id
;
1509 $params[] = $course->lastaccess
;
1512 $params[] = $USER->id
;
1513 $coursessql = implode(' OR ', $coursessqls);
1515 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1516 .'FROM {forum_discussions} d '
1517 .'JOIN {forum_posts} p ON p.discussion = d.id '
1518 ."WHERE ($coursessql) "
1519 .'AND p.userid != ? '
1520 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1521 .'ORDER BY d.course, d.forum';
1524 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1525 $discussions = array();
1528 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1530 // also get all forum tracking stuff ONCE.
1531 $trackingforums = array();
1532 foreach ($forums as $forum) {
1533 if (forum_tp_can_track_forums($forum)) {
1534 $trackingforums[$forum->id
] = $forum;
1538 if (count($trackingforums) > 0) {
1539 $cutoffdate = isset($CFG->forum_oldpostdays
) ?
(time() - ($CFG->forum_oldpostdays
*24*60*60)) : 0;
1540 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
1541 ' FROM {forum_posts} p '.
1542 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1543 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1544 $params = array($USER->id
);
1546 foreach ($trackingforums as $track) {
1547 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1548 $params[] = $track->id
;
1549 if (isset($SESSION->currentgroup
[$track->course
])) {
1550 $groupid = $SESSION->currentgroup
[$track->course
];
1552 // get first groupid
1553 $groupids = groups_get_all_groups($track->course
, $USER->id
);
1556 $groupid = key($groupids);
1557 $SESSION->currentgroup
[$track->course
] = $groupid;
1563 $params[] = $groupid;
1565 $sql = substr($sql,0,-3); // take off the last OR
1566 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1567 $params[] = $cutoffdate;
1569 if (!$unread = $DB->get_records_sql($sql, $params)) {
1576 if (empty($unread) and empty($forumsnewposts)) {
1580 $strforum = get_string('modulename','forum');
1582 foreach ($forums as $forum) {
1586 $showunread = false;
1587 // either we have something from logs, or trackposts, or nothing.
1588 if (array_key_exists($forum->id
, $forumsnewposts) && !empty($forumsnewposts[$forum->id
])) {
1589 $count = $forumsnewposts[$forum->id
]->count
;
1591 if (array_key_exists($forum->id
,$unread)) {
1592 $thisunread = $unread[$forum->id
]->count
;
1595 if ($count > 0 ||
$thisunread > 0) {
1596 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot
.'/mod/forum/view.php?f='.$forum->id
.'">'.
1597 $forum->name
.'</a></div>';
1598 $str .= '<div class="info"><span class="postsincelogin">';
1599 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
1600 if (!empty($showunread)) {
1601 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
1603 $str .= '</div></div>';
1606 if (!array_key_exists($forum->course
,$htmlarray)) {
1607 $htmlarray[$forum->course
] = array();
1609 if (!array_key_exists('forum',$htmlarray[$forum->course
])) {
1610 $htmlarray[$forum->course
]['forum'] = ''; // initialize, avoid warnings
1612 $htmlarray[$forum->course
]['forum'] .= $str;
1618 * Given a course and a date, prints a summary of all the new
1619 * messages posted in the course since that date
1624 * @uses CONTEXT_MODULE
1625 * @uses VISIBLEGROUPS
1626 * @param object $course
1627 * @param bool $viewfullnames capability
1628 * @param int $timestart
1629 * @return bool success
1631 function forum_print_recent_activity($course, $viewfullnames, $timestart) {
1632 global $CFG, $USER, $DB, $OUTPUT;
1634 // do not use log table if possible, it may be huge and is expensive to join with other tables
1636 $allnamefields = user_picture
::fields('u', null, 'duserid');
1637 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1638 d.timestart, d.timeend, $allnamefields
1639 FROM {forum_posts} p
1640 JOIN {forum_discussions} d ON d.id = p.discussion
1641 JOIN {forum} f ON f.id = d.forum
1642 JOIN {user} u ON u.id = p.userid
1643 WHERE p.created > ? AND f.course = ?
1644 ORDER BY p.id ASC", array($timestart, $course->id
))) { // order by initial posting date
1648 $modinfo = get_fast_modinfo($course);
1650 $groupmodes = array();
1653 $strftimerecent = get_string('strftimerecent');
1655 $printposts = array();
1656 foreach ($posts as $post) {
1657 if (!isset($modinfo->instances
['forum'][$post->forum
])) {
1661 $cm = $modinfo->instances
['forum'][$post->forum
];
1662 if (!$cm->uservisible
) {
1665 $context = context_module
::instance($cm->id
);
1667 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1671 if (!empty($CFG->forum_enabletimedposts
) and $USER->id
!= $post->duserid
1672 and (($post->timestart
> 0 and $post->timestart
> time()) or ($post->timeend
> 0 and $post->timeend
< time()))) {
1673 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1678 // Check that the user can see the discussion.
1679 if (forum_is_user_group_discussion($cm, $post->groupid
)) {
1680 $printposts[] = $post;
1690 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
1691 echo "\n<ul class='unlist'>\n";
1693 foreach ($printposts as $post) {
1694 $subjectclass = empty($post->parent
) ?
' bold' : '';
1696 echo '<li><div class="head">'.
1697 '<div class="date">'.userdate($post->modified
, $strftimerecent).'</div>'.
1698 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1700 echo '<div class="info'.$subjectclass.'">';
1701 if (empty($post->parent
)) {
1702 echo '"<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'">';
1704 echo '"<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'&parent='.$post->parent
.'#p'.$post->id
.'">';
1706 $post->subject
= break_up_long_words(format_string($post->subject
, true));
1707 echo $post->subject
;
1708 echo "</a>\"</div></li>\n";
1717 * Return grade for given user or all users.
1721 * @param object $forum
1722 * @param int $userid optional user id, 0 means all users
1723 * @return array array of grades, false if none
1725 function forum_get_user_grades($forum, $userid = 0) {
1728 require_once($CFG->dirroot
.'/rating/lib.php');
1730 $ratingoptions = new stdClass
;
1731 $ratingoptions->component
= 'mod_forum';
1732 $ratingoptions->ratingarea
= 'post';
1734 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1735 $ratingoptions->modulename
= 'forum';
1736 $ratingoptions->moduleid
= $forum->id
;
1737 $ratingoptions->userid
= $userid;
1738 $ratingoptions->aggregationmethod
= $forum->assessed
;
1739 $ratingoptions->scaleid
= $forum->scale
;
1740 $ratingoptions->itemtable
= 'forum_posts';
1741 $ratingoptions->itemtableusercolumn
= 'userid';
1743 $rm = new rating_manager();
1744 return $rm->get_user_grades($ratingoptions);
1748 * Update activity grades
1751 * @param object $forum
1752 * @param int $userid specific user only, 0 means all
1753 * @param boolean $nullifnone return null if grade does not exist
1756 function forum_update_grades($forum, $userid=0, $nullifnone=true) {
1758 require_once($CFG->libdir
.'/gradelib.php');
1760 if (!$forum->assessed
) {
1761 forum_grade_item_update($forum);
1763 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1764 forum_grade_item_update($forum, $grades);
1766 } else if ($userid and $nullifnone) {
1767 $grade = new stdClass();
1768 $grade->userid
= $userid;
1769 $grade->rawgrade
= NULL;
1770 forum_grade_item_update($forum, $grade);
1773 forum_grade_item_update($forum);
1778 * Create/update grade item for given forum
1781 * @uses GRADE_TYPE_NONE
1782 * @uses GRADE_TYPE_VALUE
1783 * @uses GRADE_TYPE_SCALE
1784 * @param stdClass $forum Forum object with extra cmidnumber
1785 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1786 * @return int 0 if ok
1788 function forum_grade_item_update($forum, $grades=NULL) {
1790 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1791 require_once($CFG->libdir
.'/gradelib.php');
1794 $params = array('itemname'=>$forum->name
, 'idnumber'=>$forum->cmidnumber
);
1796 if (!$forum->assessed
or $forum->scale
== 0) {
1797 $params['gradetype'] = GRADE_TYPE_NONE
;
1799 } else if ($forum->scale
> 0) {
1800 $params['gradetype'] = GRADE_TYPE_VALUE
;
1801 $params['grademax'] = $forum->scale
;
1802 $params['grademin'] = 0;
1804 } else if ($forum->scale
< 0) {
1805 $params['gradetype'] = GRADE_TYPE_SCALE
;
1806 $params['scaleid'] = -$forum->scale
;
1809 if ($grades === 'reset') {
1810 $params['reset'] = true;
1814 return grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, $grades, $params);
1818 * Delete grade item for given forum
1821 * @param stdClass $forum Forum object
1822 * @return grade_item
1824 function forum_grade_item_delete($forum) {
1826 require_once($CFG->libdir
.'/gradelib.php');
1828 return grade_update('mod/forum', $forum->course
, 'mod', 'forum', $forum->id
, 0, NULL, array('deleted'=>1));
1833 * This function returns if a scale is being used by one forum
1836 * @param int $forumid
1837 * @param int $scaleid negative number
1840 function forum_scale_used ($forumid,$scaleid) {
1844 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
1846 if (!empty($rec) && !empty($scaleid)) {
1854 * Checks if scale is being used by any instance of forum
1856 * This is used to find out if scale used anywhere
1859 * @param $scaleid int
1860 * @return boolean True if the scale is used by any forum
1862 function forum_scale_used_anywhere($scaleid) {
1864 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
1871 // SQL FUNCTIONS ///////////////////////////////////////////////////////////
1874 * Gets a post with all info ready for forum_print_post
1875 * Most of these joins are just to get the forum id
1879 * @param int $postid
1880 * @return mixed array of posts or false
1882 function forum_get_post_full($postid) {
1885 $allnames = get_all_user_name_fields(true, 'u');
1886 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
1887 FROM {forum_posts} p
1888 JOIN {forum_discussions} d ON p.discussion = d.id
1889 LEFT JOIN {user} u ON p.userid = u.id
1890 WHERE p.id = ?", array($postid));
1894 * Gets all posts in discussion including top parent.
1899 * @param int $discussionid
1900 * @param string $sort
1901 * @param bool $tracking does user track the forum?
1902 * @return array of posts
1904 function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
1905 global $CFG, $DB, $USER;
1913 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
1914 $tr_sel = ", fr.id AS postread";
1915 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1916 $params[] = $USER->id
;
1919 $allnames = get_all_user_name_fields(true, 'u');
1920 $params[] = $discussionid;
1921 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
1922 FROM {forum_posts} p
1923 LEFT JOIN {user} u ON p.userid = u.id
1925 WHERE p.discussion = ?
1926 ORDER BY $sort", $params)) {
1930 foreach ($posts as $pid=>$p) {
1932 if (forum_tp_is_post_old($p)) {
1933 $posts[$pid]->postread
= true;
1939 if (!isset($posts[$p->parent
])) {
1940 continue; // parent does not exist??
1942 if (!isset($posts[$p->parent
]->children
)) {
1943 $posts[$p->parent
]->children
= array();
1945 $posts[$p->parent
]->children
[$pid] =& $posts[$pid];
1952 * An array of forum objects that the user is allowed to read/search through.
1957 * @param int $userid
1958 * @param int $courseid if 0, we look for forums throughout the whole site.
1959 * @return array of forum objects, or false if no matches
1960 * Forum objects have the following attributes:
1961 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1962 * viewhiddentimedposts
1964 function forum_get_readable_forums($userid, $courseid=0) {
1966 global $CFG, $DB, $USER;
1967 require_once($CFG->dirroot
.'/course/lib.php');
1969 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
1970 print_error('notinstalled', 'forum');
1974 $courses = $DB->get_records('course', array('id' => $courseid));
1976 // If no course is specified, then the user can see SITE + his courses.
1977 $courses1 = $DB->get_records('course', array('id' => SITEID
));
1978 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
1979 $courses = array_merge($courses1, $courses2);
1985 $readableforums = array();
1987 foreach ($courses as $course) {
1989 $modinfo = get_fast_modinfo($course);
1991 if (empty($modinfo->instances
['forum'])) {
1996 $courseforums = $DB->get_records('forum', array('course' => $course->id
));
1998 foreach ($modinfo->instances
['forum'] as $forumid => $cm) {
1999 if (!$cm->uservisible
or !isset($courseforums[$forumid])) {
2002 $context = context_module
::instance($cm->id
);
2003 $forum = $courseforums[$forumid];
2004 $forum->context
= $context;
2007 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2012 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
2014 $forum->onlygroups
= $modinfo->get_groups($cm->groupingid
);
2015 $forum->onlygroups
[] = -1;
2018 /// hidden timed discussions
2019 $forum->viewhiddentimedposts
= true;
2020 if (!empty($CFG->forum_enabletimedposts
)) {
2021 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
2022 $forum->viewhiddentimedposts
= false;
2027 if ($forum->type
== 'qanda'
2028 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2030 // We need to check whether the user has posted in the qanda forum.
2031 $forum->onlydiscussions
= array(); // Holds discussion ids for the discussions
2032 // the user is allowed to see in this forum.
2033 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $USER->id
)) {
2034 foreach ($discussionspostedin as $d) {
2035 $forum->onlydiscussions
[] = $d->id
;
2040 $readableforums[$forum->id
] = $forum;
2045 } // End foreach $courses
2047 return $readableforums;
2051 * Returns a list of posts found using an array of search terms.
2056 * @param array $searchterms array of search terms, e.g. word +word -word
2057 * @param int $courseid if 0, we search through the whole site
2058 * @param int $limitfrom
2059 * @param int $limitnum
2060 * @param int &$totalcount
2061 * @param string $extrasql
2062 * @return array|bool Array of posts found or false
2064 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
2065 &$totalcount, $extrasql='') {
2066 global $CFG, $DB, $USER;
2067 require_once($CFG->libdir
.'/searchlib.php');
2069 $forums = forum_get_readable_forums($USER->id
, $courseid);
2071 if (count($forums) == 0) {
2076 $now = round(time(), -2); // db friendly
2078 $fullaccess = array();
2082 foreach ($forums as $forumid => $forum) {
2085 if (!$forum->viewhiddentimedposts
) {
2086 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2087 $params = array_merge($params, array('userid'.$forumid=>$USER->id
, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
2091 $context = $forum->context
;
2093 if ($forum->type
== 'qanda'
2094 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2095 if (!empty($forum->onlydiscussions
)) {
2096 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions
, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
2097 $params = array_merge($params, $discussionid_params);
2098 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
2100 $select[] = "p.parent = 0";
2104 if (!empty($forum->onlygroups
)) {
2105 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups
, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
2106 $params = array_merge($params, $groupid_params);
2107 $select[] = "d.groupid $groupid_sql";
2111 $selects = implode(" AND ", $select);
2112 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2113 $params['forum'.$forumid] = $forumid;
2115 $fullaccess[] = $forumid;
2120 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED
, 'fula');
2121 $params = array_merge($params, $fullid_params);
2122 $where[] = "(d.forum $fullid_sql)";
2125 $selectdiscussion = "(".implode(" OR ", $where).")";
2127 $messagesearch = '';
2130 // Need to concat these back together for parser to work.
2131 foreach($searchterms as $searchterm){
2132 if ($searchstring != '') {
2133 $searchstring .= ' ';
2135 $searchstring .= $searchterm;
2138 // We need to allow quoted strings for the search. The quotes *should* be stripped
2139 // by the parser, but this should be examined carefully for security implications.
2140 $searchstring = str_replace("\\\"","\"",$searchstring);
2141 $parser = new search_parser();
2142 $lexer = new search_lexer($parser);
2144 if ($lexer->parse($searchstring)) {
2145 $parsearray = $parser->get_parsed_array();
2146 // Experimental feature under 1.8! MDL-8830
2147 // Use alternative text searches if defined
2148 // This feature only works under mysql until properly implemented for other DBs
2149 // Requires manual creation of text index for forum_posts before enabling it:
2150 // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
2151 // Experimental feature under 1.8! MDL-8830
2152 if (!empty($CFG->forum_usetextsearches
)) {
2153 list($messagesearch, $msparams) = search_generate_text_SQL($parsearray, 'p.message', 'p.subject',
2154 'p.userid', 'u.id', 'u.firstname',
2155 'u.lastname', 'p.modified', 'd.forum');
2157 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2158 'p.userid', 'u.id', 'u.firstname',
2159 'u.lastname', 'p.modified', 'd.forum');
2161 $params = array_merge($params, $msparams);
2164 $fromsql = "{forum_posts} p,
2165 {forum_discussions} d,
2168 $selectsql = " $messagesearch
2169 AND p.discussion = d.id
2171 AND $selectdiscussion
2174 $countsql = "SELECT COUNT(*)
2178 $allnames = get_all_user_name_fields(true, 'u');
2179 $searchsql = "SELECT p.*,
2187 ORDER BY p.modified DESC";
2189 $totalcount = $DB->count_records_sql($countsql, $params);
2191 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
2195 * Returns a list of all new posts that have not been mailed yet
2197 * @param int $starttime posts created after this time
2198 * @param int $endtime posts created before this
2199 * @param int $now used for timed discussions only
2202 function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
2206 $params['mailed'] = FORUM_MAILED_PENDING
;
2207 $params['ptimestart'] = $starttime;
2208 $params['ptimeend'] = $endtime;
2209 $params['mailnow'] = 1;
2211 if (!empty($CFG->forum_enabletimedposts
)) {
2215 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2216 $params['dtimestart'] = $now;
2217 $params['dtimeend'] = $now;
2222 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
2223 FROM {forum_posts} p
2224 JOIN {forum_discussions} d ON d.id = p.discussion
2225 WHERE p.mailed = :mailed
2226 AND p.created >= :ptimestart
2227 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2229 ORDER BY p.modified ASC", $params);
2233 * Marks posts before a certain time as being mailed already
2237 * @param int $endtime
2238 * @param int $now Defaults to time()
2241 function forum_mark_old_posts_as_mailed($endtime, $now=null) {
2249 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS
;
2250 $params['now'] = $now;
2251 $params['endtime'] = $endtime;
2252 $params['mailnow'] = 1;
2253 $params['mailedpending'] = FORUM_MAILED_PENDING
;
2255 if (empty($CFG->forum_enabletimedposts
)) {
2256 return $DB->execute("UPDATE {forum_posts}
2257 SET mailed = :mailedsuccess
2258 WHERE (created < :endtime OR mailnow = :mailnow)
2259 AND mailed = :mailedpending", $params);
2261 return $DB->execute("UPDATE {forum_posts}
2262 SET mailed = :mailedsuccess
2263 WHERE discussion NOT IN (SELECT d.id
2264 FROM {forum_discussions} d
2265 WHERE d.timestart > :now)
2266 AND (created < :endtime OR mailnow = :mailnow)
2267 AND mailed = :mailedpending", $params);
2272 * Get all the posts for a user in a forum suitable for forum_print_post
2276 * @uses CONTEXT_MODULE
2279 function forum_get_user_posts($forumid, $userid) {
2283 $params = array($forumid, $userid);
2285 if (!empty($CFG->forum_enabletimedposts
)) {
2286 $cm = get_coursemodule_from_instance('forum', $forumid);
2287 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2289 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2295 $allnames = get_all_user_name_fields(true, 'u');
2296 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
2298 JOIN {forum_discussions} d ON d.forum = f.id
2299 JOIN {forum_posts} p ON p.discussion = d.id
2300 JOIN {user} u ON u.id = p.userid
2304 ORDER BY p.modified ASC", $params);
2308 * Get all the discussions user participated in
2312 * @uses CONTEXT_MODULE
2313 * @param int $forumid
2314 * @param int $userid
2315 * @return array Array or false
2317 function forum_get_user_involved_discussions($forumid, $userid) {
2321 $params = array($forumid, $userid);
2322 if (!empty($CFG->forum_enabletimedposts
)) {
2323 $cm = get_coursemodule_from_instance('forum', $forumid);
2324 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2326 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2332 return $DB->get_records_sql("SELECT DISTINCT d.*
2334 JOIN {forum_discussions} d ON d.forum = f.id
2335 JOIN {forum_posts} p ON p.discussion = d.id
2338 $timedsql", $params);
2342 * Get all the posts for a user in a forum suitable for forum_print_post
2346 * @param int $forumid
2347 * @param int $userid
2348 * @return array of counts or false
2350 function forum_count_user_posts($forumid, $userid) {
2354 $params = array($forumid, $userid);
2355 if (!empty($CFG->forum_enabletimedposts
)) {
2356 $cm = get_coursemodule_from_instance('forum', $forumid);
2357 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module
::instance($cm->id
))) {
2359 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2365 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2367 JOIN {forum_discussions} d ON d.forum = f.id
2368 JOIN {forum_posts} p ON p.discussion = d.id
2369 JOIN {user} u ON u.id = p.userid
2372 $timedsql", $params);
2376 * Given a log entry, return the forum post details for it.
2380 * @param object $log
2381 * @return array|null
2383 function forum_get_post_from_log($log) {
2386 $allnames = get_all_user_name_fields(true, 'u');
2387 if ($log->action
== "add post") {
2389 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2390 FROM {forum_discussions} d,
2395 AND d.id = p.discussion
2397 AND u.deleted <> '1'
2398 AND f.id = d.forum", array($log->info
));
2401 } else if ($log->action
== "add discussion") {
2403 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
2404 FROM {forum_discussions} d,
2409 AND d.firstpost = p.id
2411 AND u.deleted <> '1'
2412 AND f.id = d.forum", array($log->info
));
2418 * Given a discussion id, return the first post from the discussion
2422 * @param int $dicsussionid
2425 function forum_get_firstpost_from_discussion($discussionid) {
2428 return $DB->get_record_sql("SELECT p.*
2429 FROM {forum_discussions} d,
2432 AND d.firstpost = p.id ", array($discussionid));
2436 * Returns an array of counts of replies to each discussion
2440 * @param int $forumid
2441 * @param string $forumsort
2444 * @param int $perpage
2447 function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
2453 } else if ($page != -1) {
2454 $limitfrom = $page*$perpage;
2455 $limitnum = $perpage;
2461 if ($forumsort == "") {
2466 $orderby = "ORDER BY $forumsort";
2467 $groupby = ", ".strtolower($forumsort);
2468 $groupby = str_replace('desc', '', $groupby);
2469 $groupby = str_replace('asc', '', $groupby);
2472 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2473 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
2474 FROM {forum_posts} p
2475 JOIN {forum_discussions} d ON p.discussion = d.id
2476 WHERE p.parent > 0 AND d.forum = ?
2477 GROUP BY p.discussion";
2478 return $DB->get_records_sql($sql, array($forumid));
2481 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
2482 FROM {forum_posts} p
2483 JOIN {forum_discussions} d ON p.discussion = d.id
2485 GROUP BY p.discussion $groupby
2487 return $DB->get_records_sql("SELECT * FROM ($sql) sq", array($forumid), $limitfrom, $limitnum);
2495 * @staticvar array $cache
2496 * @param object $forum
2498 * @param object $course
2501 function forum_count_discussions($forum, $cm, $course) {
2502 global $CFG, $DB, $USER;
2504 static $cache = array();
2506 $now = round(time(), -2); // db cache friendliness
2508 $params = array($course->id
);
2510 if (!isset($cache[$course->id
])) {
2511 if (!empty($CFG->forum_enabletimedposts
)) {
2512 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2519 $sql = "SELECT f.id, COUNT(d.id) as dcount
2521 JOIN {forum_discussions} d ON d.forum = f.id
2526 if ($counts = $DB->get_records_sql($sql, $params)) {
2527 foreach ($counts as $count) {
2528 $counts[$count->id
] = $count->dcount
;
2530 $cache[$course->id
] = $counts;
2532 $cache[$course->id
] = array();
2536 if (empty($cache[$course->id
][$forum->id
])) {
2540 $groupmode = groups_get_activity_groupmode($cm, $course);
2542 if ($groupmode != SEPARATEGROUPS
) {
2543 return $cache[$course->id
][$forum->id
];
2546 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
2547 return $cache[$course->id
][$forum->id
];
2550 require_once($CFG->dirroot
.'/course/lib.php');
2552 $modinfo = get_fast_modinfo($course);
2554 $mygroups = $modinfo->get_groups($cm->groupingid
);
2556 // add all groups posts
2559 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2560 $params[] = $forum->id
;
2562 if (!empty($CFG->forum_enabletimedposts
)) {
2563 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
2570 $sql = "SELECT COUNT(d.id)
2571 FROM {forum_discussions} d
2572 WHERE d.groupid $mygroups_sql AND d.forum = ?
2575 return $DB->get_field_sql($sql, $params);
2579 * Get all discussions in a forum
2584 * @uses CONTEXT_MODULE
2585 * @uses VISIBLEGROUPS
2587 * @param string $forumsort
2588 * @param bool $fullpost
2589 * @param int $unused
2591 * @param bool $userlastmodified
2593 * @param int $perpage
2596 function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
2597 global $CFG, $DB, $USER;
2601 $now = round(time(), -2);
2602 $params = array($cm->instance
);
2604 $modcontext = context_module
::instance($cm->id
);
2606 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2610 if (!empty($CFG->forum_enabletimedposts
)) { /// Users must fulfill timed posts
2612 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2613 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2617 $timelimit .= " OR d.userid = ?";
2618 $params[] = $USER->id
;
2627 } else if ($page != -1) {
2628 $limitfrom = $page*$perpage;
2629 $limitnum = $perpage;
2635 $groupmode = groups_get_activity_groupmode($cm);
2636 $currentgroup = groups_get_activity_group($cm);
2639 if (empty($modcontext)) {
2640 $modcontext = context_module
::instance($cm->id
);
2643 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2644 if ($currentgroup) {
2645 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2646 $params[] = $currentgroup;
2652 //seprate groups without access all
2653 if ($currentgroup) {
2654 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2655 $params[] = $currentgroup;
2657 $groupselect = "AND d.groupid = -1";
2665 if (empty($forumsort)) {
2666 $forumsort = "d.timemodified DESC";
2668 if (empty($fullpost)) {
2669 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2674 if (empty($userlastmodified)) { // We don't need to know this
2678 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
2679 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
2682 $allnames = get_all_user_name_fields(true, 'u');
2683 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2684 u.email, u.picture, u.imagealt $umfields
2685 FROM {forum_discussions} d
2686 JOIN {forum_posts} p ON p.discussion = d.id
2687 JOIN {user} u ON p.userid = u.id
2689 WHERE d.forum = ? AND p.parent = 0
2690 $timelimit $groupselect
2691 ORDER BY $forumsort";
2692 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2696 * Gets the neighbours (previous and next) of a discussion.
2698 * The calculation is based on the timemodified of the discussion and does not handle
2699 * the neighbours having an identical timemodified. The reason is that we do not have any
2700 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2703 * Please note that this does not check whether or not the discussion passed is accessible
2704 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2705 * the returned neighbours are checked and are accessible to the current user.
2707 * @param object $cm The CM record.
2708 * @param object $discussion The discussion record.
2709 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2710 * they contain the record with minimal information such as 'id' and 'name'.
2711 * When the neighbour is not found the value is false.
2713 function forum_get_discussion_neighbours($cm, $discussion) {
2714 global $CFG, $DB, $USER;
2716 if ($cm->instance
!= $discussion->forum
) {
2717 throw new coding_exception('Discussion is not part of the same forum.');
2720 $neighbours = array('prev' => false, 'next' => false);
2721 $now = round(time(), -2);
2724 $modcontext = context_module
::instance($cm->id
);
2725 $groupmode = groups_get_activity_groupmode($cm);
2726 $currentgroup = groups_get_activity_group($cm);
2728 // Users must fulfill timed posts.
2730 if (!empty($CFG->forum_enabletimedposts
)) {
2731 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2732 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2733 $params['tltimestart'] = $now;
2734 $params['tltimeend'] = $now;
2736 $timelimit .= ' OR d.userid = :tluserid';
2737 $params['tluserid'] = $USER->id
;
2743 // Limiting to posts accessible according to groups.
2746 if ($groupmode == VISIBLEGROUPS ||
has_capability('moodle/site:accessallgroups', $modcontext)) {
2747 if ($currentgroup) {
2748 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2749 $params['groupid'] = $currentgroup;
2752 if ($currentgroup) {
2753 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2754 $params['groupid'] = $currentgroup;
2756 $groupselect = 'AND d.groupid = -1';
2761 $params['forumid'] = $cm->instance
;
2762 $params['discid'] = $discussion->id
;
2763 $params['disctimemodified'] = $discussion->timemodified
;
2765 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2766 FROM {forum_discussions} d
2767 WHERE d.forum = :forumid
2772 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2773 ORDER BY d.timemodified DESC";
2775 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2776 ORDER BY d.timemodified ASC";
2778 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE
);
2779 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE
);
2789 * @uses CONTEXT_MODULE
2790 * @uses VISIBLEGROUPS
2794 function forum_get_discussions_unread($cm) {
2795 global $CFG, $DB, $USER;
2797 $now = round(time(), -2);
2798 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
2801 $groupmode = groups_get_activity_groupmode($cm);
2802 $currentgroup = groups_get_activity_group($cm);
2805 $modcontext = context_module
::instance($cm->id
);
2807 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2808 if ($currentgroup) {
2809 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2810 $params['currentgroup'] = $currentgroup;
2816 //separate groups without access all
2817 if ($currentgroup) {
2818 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2819 $params['currentgroup'] = $currentgroup;
2821 $groupselect = "AND d.groupid = -1";
2828 if (!empty($CFG->forum_enabletimedposts
)) {
2829 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2830 $params['now1'] = $now;
2831 $params['now2'] = $now;
2836 $sql = "SELECT d.id, COUNT(p.id) AS unread
2837 FROM {forum_discussions} d
2838 JOIN {forum_posts} p ON p.discussion = d.id
2839 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
2840 WHERE d.forum = {$cm->instance}
2841 AND p.modified >= :cutoffdate AND r.id is NULL
2845 $params['cutoffdate'] = $cutoffdate;
2847 if ($unreads = $DB->get_records_sql($sql, $params)) {
2848 foreach ($unreads as $unread) {
2849 $unreads[$unread->id
] = $unread->unread
;
2861 * @uses CONEXT_MODULE
2862 * @uses VISIBLEGROUPS
2866 function forum_get_discussions_count($cm) {
2867 global $CFG, $DB, $USER;
2869 $now = round(time(), -2);
2870 $params = array($cm->instance
);
2871 $groupmode = groups_get_activity_groupmode($cm);
2872 $currentgroup = groups_get_activity_group($cm);
2875 $modcontext = context_module
::instance($cm->id
);
2877 if ($groupmode == VISIBLEGROUPS
or has_capability('moodle/site:accessallgroups', $modcontext)) {
2878 if ($currentgroup) {
2879 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2880 $params[] = $currentgroup;
2886 //seprate groups without access all
2887 if ($currentgroup) {
2888 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2889 $params[] = $currentgroup;
2891 $groupselect = "AND d.groupid = -1";
2898 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
2902 if (!empty($CFG->forum_enabletimedposts
)) {
2904 $modcontext = context_module
::instance($cm->id
);
2906 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2907 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2911 $timelimit .= " OR d.userid = ?";
2912 $params[] = $USER->id
;
2918 $sql = "SELECT COUNT(d.id)
2919 FROM {forum_discussions} d
2920 JOIN {forum_posts} p ON p.discussion = d.id
2921 WHERE d.forum = ? AND p.parent = 0
2922 $groupselect $timelimit";
2924 return $DB->get_field_sql($sql, $params);
2928 // OTHER FUNCTIONS ///////////////////////////////////////////////////////////
2934 * @param int $courseid
2935 * @param string $type
2937 function forum_get_course_forum($courseid, $type) {
2938 // How to set up special 1-per-course forums
2939 global $CFG, $DB, $OUTPUT, $USER;
2941 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
2942 // There should always only be ONE, but with the right combination of
2943 // errors there might be more. In this case, just return the oldest one (lowest ID).
2944 foreach ($forums as $forum) {
2945 return $forum; // ie the first one
2949 // Doesn't exist, so create one now.
2950 $forum = new stdClass();
2951 $forum->course
= $courseid;
2952 $forum->type
= "$type";
2953 if (!empty($USER->htmleditor
)) {
2954 $forum->introformat
= $USER->htmleditor
;
2956 switch ($forum->type
) {
2958 $forum->name
= get_string("namenews", "forum");
2959 $forum->intro
= get_string("intronews", "forum");
2960 $forum->forcesubscribe
= FORUM_FORCESUBSCRIBE
;
2961 $forum->assessed
= 0;
2962 if ($courseid == SITEID
) {
2963 $forum->name
= get_string("sitenews");
2964 $forum->forcesubscribe
= 0;
2968 $forum->name
= get_string("namesocial", "forum");
2969 $forum->intro
= get_string("introsocial", "forum");
2970 $forum->assessed
= 0;
2971 $forum->forcesubscribe
= 0;
2974 $forum->name
= get_string('blogforum', 'forum');
2975 $forum->intro
= get_string('introblog', 'forum');
2976 $forum->assessed
= 0;
2977 $forum->forcesubscribe
= 0;
2980 echo $OUTPUT->notification("That forum type doesn't exist!");
2985 $forum->timemodified
= time();
2986 $forum->id
= $DB->insert_record("forum", $forum);
2988 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
2989 echo $OUTPUT->notification("Could not find forum module!!");
2992 $mod = new stdClass();
2993 $mod->course
= $courseid;
2994 $mod->module
= $module->id
;
2995 $mod->instance
= $forum->id
;
2997 include_once("$CFG->dirroot/course/lib.php");
2998 if (! $mod->coursemodule
= add_course_module($mod) ) {
2999 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
3002 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule
, 0);
3003 return $DB->get_record("forum", array("id" => "$forum->id"));
3008 * Given the data about a posting, builds up the HTML to display it and
3009 * returns the HTML in a string. This is designed for sending via HTML email.
3012 * @param object $course
3014 * @param object $forum
3015 * @param object $discussion
3016 * @param object $post
3017 * @param object $userform
3018 * @param object $userto
3019 * @param bool $ownpost
3020 * @param bool $reply
3023 * @param string $footer
3026 function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
3027 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
3029 global $CFG, $OUTPUT;
3031 $modcontext = context_module
::instance($cm->id
);
3033 if (!isset($userto->viewfullnames
[$forum->id
])) {
3034 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id
);
3036 $viewfullnames = $userto->viewfullnames
[$forum->id
];
3039 // add absolute file links
3040 $post->message
= file_rewrite_pluginfile_urls($post->message
, 'pluginfile.php', $modcontext->id
, 'mod_forum', 'post', $post->id
);
3042 // format the post body
3043 $options = new stdClass();
3044 $options->para
= true;
3045 $formattedtext = format_text($post->message
, $post->messageformat
, $options, $course->id
);
3047 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
3049 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
3050 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id
));
3053 if ($post->parent
) {
3054 $output .= '<td class="topic">';
3056 $output .= '<td class="topic starter">';
3058 $output .= '<div class="subject">'.format_string($post->subject
).'</div>';
3060 $fullname = fullname($userfrom, $viewfullnames);
3061 $by = new stdClass();
3062 $by->name
= '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$userfrom->id
.'&course='.$course->id
.'">'.$fullname.'</a>';
3063 $by->date
= userdate($post->modified
, '', $userto->timezone
);
3064 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3066 $output .= '</td></tr>';
3068 $output .= '<tr><td class="left side" valign="top">';
3070 if (isset($userfrom->groups
)) {
3071 $groups = $userfrom->groups
[$forum->id
];
3073 $groups = groups_get_all_groups($course->id
, $userfrom->id
, $cm->groupingid
);
3077 $output .= print_group_picture($groups, $course->id
, false, true, true);
3079 $output .= ' ';
3082 $output .= '</td><td class="content">';
3084 $attachments = forum_print_attachments($post, $cm, 'html');
3085 if ($attachments !== '') {
3086 $output .= '<div class="attachments">';
3087 $output .= $attachments;
3088 $output .= '</div>';
3091 $output .= $formattedtext;
3094 $commands = array();
3096 if ($post->parent
) {
3097 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.
3098 $post->discussion
.'&parent='.$post->parent
.'">'.get_string('parent', 'forum').'</a>';
3102 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/post.php?reply='.$post->id
.'">'.
3103 get_string('reply', 'forum').'</a>';
3106 $output .= '<div class="commands">';
3107 $output .= implode(' | ', $commands);
3108 $output .= '</div>';
3110 // Context link to post if required
3112 $output .= '<div class="link">';
3113 $output .= '<a target="_blank" href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'#p'.$post->id
.'">'.
3114 get_string('postincontext', 'forum').'</a>';
3115 $output .= '</div>';
3119 $output .= '<div class="footer">'.$footer.'</div>';
3121 $output .= '</td></tr></table>'."\n\n";
3127 * Print a forum post
3131 * @uses FORUM_MODE_THREADED
3132 * @uses PORTFOLIO_FORMAT_PLAINHTML
3133 * @uses PORTFOLIO_FORMAT_FILE
3134 * @uses PORTFOLIO_FORMAT_RICHHTML
3135 * @uses PORTFOLIO_ADD_TEXT_LINK
3136 * @uses CONTEXT_MODULE
3137 * @param object $post The post to print.
3138 * @param object $discussion
3139 * @param object $forum
3141 * @param object $course
3142 * @param boolean $ownpost Whether this post belongs to the current user.
3143 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
3144 * @param boolean $link Just print a shortened version of the post as a link to the full post.
3145 * @param string $footer Extra stuff to print after the message.
3146 * @param string $highlight Space-separated list of terms to highlight.
3147 * @param int $post_read true, false or -99. If we already know whether this user
3148 * has read this post, pass that in, otherwise, pass in -99, and this
3149 * function will work it out.
3150 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
3151 * the current user can't see this post, if this argument is true
3152 * (the default) then print a dummy 'you can't see this post' post.
3153 * If false, don't output anything at all.
3154 * @param bool|null $istracked
3157 function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
3158 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
3159 global $USER, $CFG, $OUTPUT;
3161 require_once($CFG->libdir
. '/filelib.php');
3166 $modcontext = context_module
::instance($cm->id
);
3168 $post->course
= $course->id
;
3169 $post->forum
= $forum->id
;
3170 $post->message
= file_rewrite_pluginfile_urls($post->message
, 'pluginfile.php', $modcontext->id
, 'mod_forum', 'post', $post->id
);
3171 if (!empty($CFG->enableplagiarism
)) {
3172 require_once($CFG->libdir
.'/plagiarismlib.php');
3173 $post->message
.= plagiarism_get_links(array('userid' => $post->userid
,
3174 'content' => $post->message
,
3176 'course' => $post->course
,
3177 'forum' => $post->forum
));
3181 if (!isset($cm->cache
)) {
3182 $cm->cache
= new stdClass
;
3185 if (!isset($cm->cache
->caps
)) {
3186 $cm->cache
->caps
= array();
3187 $cm->cache
->caps
['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3188 $cm->cache
->caps
['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3189 $cm->cache
->caps
['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3190 $cm->cache
->caps
['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3191 $cm->cache
->caps
['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3192 $cm->cache
->caps
['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3193 $cm->cache
->caps
['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
3194 $cm->cache
->caps
['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3195 $cm->cache
->caps
['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
3198 if (!isset($cm->uservisible
)) {
3199 $cm->uservisible
= \core_availability\info_module
::is_user_visible($cm, 0, false);
3202 if ($istracked && is_null($postisread)) {
3203 $postisread = forum_tp_is_post_read($USER->id
, $post);
3206 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
3208 if (!$dummyifcantsee) {
3215 $output .= html_writer
::tag('a', '', array('id'=>'p'.$post->id
));
3216 $output .= html_writer
::start_tag('div', array('class'=>'forumpost clearfix',
3218 'aria-label' => get_string('hiddenforumpost', 'forum')));
3219 $output .= html_writer
::start_tag('div', array('class'=>'row header'));
3220 $output .= html_writer
::tag('div', '', array('class'=>'left picture')); // Picture
3221 if ($post->parent
) {
3222 $output .= html_writer
::start_tag('div', array('class'=>'topic'));
3224 $output .= html_writer
::start_tag('div', array('class'=>'topic starter'));
3226 $output .= html_writer
::tag('div', get_string('forumsubjecthidden','forum'), array('class' => 'subject',
3227 'role' => 'header')); // Subject.
3228 $output .= html_writer
::tag('div', get_string('forumauthorhidden', 'forum'), array('class' => 'author',
3229 'role' => 'header')); // Author.
3230 $output .= html_writer
::end_tag('div');
3231 $output .= html_writer
::end_tag('div'); // row
3232 $output .= html_writer
::start_tag('div', array('class'=>'row'));
3233 $output .= html_writer
::tag('div', ' ', array('class'=>'left side')); // Groups
3234 $output .= html_writer
::tag('div', get_string('forumbodyhidden','forum'), array('class'=>'content')); // Content
3235 $output .= html_writer
::end_tag('div'); // row
3236 $output .= html_writer
::end_tag('div'); // forumpost
3246 $str = new stdClass
;
3247 $str->edit
= get_string('edit', 'forum');
3248 $str->delete
= get_string('delete', 'forum');
3249 $str->reply
= get_string('reply', 'forum');
3250 $str->parent
= get_string('parent', 'forum');
3251 $str->pruneheading
= get_string('pruneheading', 'forum');
3252 $str->prune
= get_string('prune', 'forum');
3253 $str->displaymode
= get_user_preferences('forum_displaymode', $CFG->forum_displaymode
);
3254 $str->markread
= get_string('markread', 'forum');
3255 $str->markunread
= get_string('markunread', 'forum');
3258 $discussionlink = new moodle_url('/mod/forum/discuss.php', array('d'=>$post->discussion
));
3260 // Build an object that represents the posting user
3261 $postuser = new stdClass
;
3262 $postuserfields = explode(',', user_picture
::fields());
3263 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3264 $postuser->id
= $post->userid
;
3265 $postuser->fullname
= fullname($postuser, $cm->cache
->caps
['moodle/site:viewfullnames']);
3266 $postuser->profilelink
= new moodle_url('/user/view.php', array('id'=>$post->userid
, 'course'=>$course->id
));
3268 // Prepare the groups the posting user belongs to
3269 if (isset($cm->cache
->usersgroups
)) {
3271 if (isset($cm->cache
->usersgroups
[$post->userid
])) {
3272 foreach ($cm->cache
->usersgroups
[$post->userid
] as $gid) {
3273 $groups[$gid] = $cm->cache
->groups
[$gid];
3277 $groups = groups_get_all_groups($course->id
, $post->userid
, $cm->groupingid
);
3280 // Prepare the attachements for the post, files then images
3281 list($attachments, $attachedimages) = forum_print_attachments($post, $cm, 'separateimages');
3283 // Determine if we need to shorten this post
3284 $shortenpost = ($link && (strlen(strip_tags($post->message
)) > $CFG->forum_longpost
));
3287 // Prepare an array of commands
3288 $commands = array();
3290 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
3291 // Don't display the mark read / unread controls in this case.
3292 if ($istracked && $CFG->forum_usermarksread
&& isloggedin()) {
3293 $url = new moodle_url($discussionlink, array('postid'=>$post->id
, 'mark'=>'unread'));
3294 $text = $str->markunread
;
3296 $url->param('mark', 'read');
3297 $text = $str->markread
;
3299 if ($str->displaymode
== FORUM_MODE_THREADED
) {
3300 $url->param('parent', $post->parent
);
3302 $url->set_anchor('p'.$post->id
);
3304 $commands[] = array('url'=>$url, 'text'=>$text);
3307 // Zoom in to the parent specifically
3308 if ($post->parent
) {
3309 $url = new moodle_url($discussionlink);
3310 if ($str->displaymode
== FORUM_MODE_THREADED
) {
3311 $url->param('parent', $post->parent
);
3313 $url->set_anchor('p'.$post->parent
);
3315 $commands[] = array('url'=>$url, 'text'=>$str->parent
);
3318 // Hack for allow to edit news posts those are not displayed yet until they are displayed
3319 $age = time() - $post->created
;
3320 if (!$post->parent
&& $forum->type
== 'news' && $discussion->timestart
> time()) {
3324 if ($forum->type
== 'single' and $discussion->firstpost
== $post->id
) {
3325 if (has_capability('moodle/course:manageactivities', $modcontext)) {
3326 // The first post in single simple is the forum description.
3327 $commands[] = array('url'=>new moodle_url('/course/modedit.php', array('update'=>$cm->id
, 'sesskey'=>sesskey(), 'return'=>1)), 'text'=>$str->edit
);
3329 } else if (($ownpost && $age < $CFG->maxeditingtime
) ||
$cm->cache
->caps
['mod/forum:editanypost']) {
3330 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('edit'=>$post->id
)), 'text'=>$str->edit
);
3333 if ($cm->cache
->caps
['mod/forum:splitdiscussions'] && $post->parent
&& $forum->type
!= 'single') {
3334 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('prune'=>$post->id
)), 'text'=>$str->prune
, 'title'=>$str->pruneheading
);
3337 if ($forum->type
== 'single' and $discussion->firstpost
== $post->id
) {
3338 // Do not allow deleting of first post in single simple type.
3339 } else if (($ownpost && $age < $CFG->maxeditingtime
&& $cm->cache
->caps
['mod/forum:deleteownpost']) ||
$cm->cache
->caps
['mod/forum:deleteanypost']) {
3340 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php', array('delete'=>$post->id
)), 'text'=>$str->delete
);
3344 $commands[] = array('url'=>new moodle_url('/mod/forum/post.php#mformforum', array('reply'=>$post->id
)), 'text'=>$str->reply
);
3347 if ($CFG->enableportfolios
&& ($cm->cache
->caps
['mod/forum:exportpost'] ||
($ownpost && $cm->cache
->caps
['mod/forum:exportownpost']))) {
3348 $p = array('postid' => $post->id
);
3349 require_once($CFG->libdir
.'/portfoliolib.php');
3350 $button = new portfolio_add_button();
3351 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
), 'mod_forum');
3352 if (empty($attachments)) {
3353 $button->set_formats(PORTFOLIO_FORMAT_PLAINHTML
);
3355 $button->set_formats(PORTFOLIO_FORMAT_RICHHTML
);
3358 $porfoliohtml = $button->to_html(PORTFOLIO_ADD_TEXT_LINK
);
3359 if (!empty($porfoliohtml)) {
3360 $commands[] = $porfoliohtml;
3363 // Finished building commands
3372 $forumpostclass = ' read';
3374 $forumpostclass = ' unread';
3375 $output .= html_writer
::tag('a', '', array('name'=>'unread'));
3378 // ignore trackign status if not tracked or tracked param missing
3379 $forumpostclass = '';
3383 if (empty($post->parent
)) {
3384 $topicclass = ' firstpost starter';
3387 $postbyuser = new stdClass
;
3388 $postbyuser->post
= $post->subject
;
3389 $postbyuser->user
= $postuser->fullname
;
3390 $discussionbyuser = get_string('postbyuser', 'forum', $postbyuser);
3391 $output .= html_writer
::tag('a', '', array('id'=>'p'.$post->id
));
3392 $output .= html_writer
::start_tag('div', array('class'=>'forumpost clearfix'.$forumpostclass.$topicclass,
3394 'aria-label' => $discussionbyuser));
3395 $output .= html_writer
::start_tag('div', array('class'=>'row header clearfix'));
3396 $output .= html_writer
::start_tag('div', array('class'=>'left picture'));
3397 $output .= $OUTPUT->user_picture($postuser, array('courseid'=>$course->id
));
3398 $output .= html_writer
::end_tag('div');
3401 $output .= html_writer
::start_tag('div', array('class'=>'topic'.$topicclass));
3403 $postsubject = $post->subject
;
3404 if (empty($post->subjectnoformat
)) {
3405 $postsubject = format_string($postsubject);
3407 $output .= html_writer
::tag('div', $postsubject, array('class'=>'subject',
3408 'role' => 'heading',
3409 'aria-level' => '2'));
3411 $by = new stdClass();
3412 $by->name
= html_writer
::link($postuser->profilelink
, $postuser->fullname
);
3413 $by->date
= userdate($post->modified
);
3414 $output .= html_writer
::tag('div', get_string('bynameondate', 'forum', $by), array('class'=>'author',
3415 'role' => 'heading',
3416 'aria-level' => '2'));
3418 $output .= html_writer
::end_tag('div'); //topic
3419 $output .= html_writer
::end_tag('div'); //row
3421 $output .= html_writer
::start_tag('div', array('class'=>'row maincontent clearfix'));
3422 $output .= html_writer
::start_tag('div', array('class'=>'left'));
3426 $groupoutput = print_group_picture($groups, $course->id
, false, true, true);
3428 if (empty($groupoutput)) {
3429 $groupoutput = ' ';
3431 $output .= html_writer
::tag('div', $groupoutput, array('class'=>'grouppictures'));
3433 $output .= html_writer
::end_tag('div'); //left side
3434 $output .= html_writer
::start_tag('div', array('class'=>'no-overflow'));
3435 $output .= html_writer
::start_tag('div', array('class'=>'content'));
3437 $options = new stdClass
;
3438 $options->para
= false;
3439 $options->trusted
= $post->messagetrust
;
3440 $options->context
= $modcontext;
3442 // Prepare shortened version by filtering the text then shortening it.
3443 $postclass = 'shortenedpost';
3444 $postcontent = format_text($post->message
, $post->messageformat
, $options);
3445 $postcontent = shorten_text($postcontent, $CFG->forum_shortpost
);
3446 $postcontent .= html_writer
::link($discussionlink, get_string('readtherest', 'forum'));
3447 $postcontent .= html_writer
::tag('div', '('.get_string('numwords', 'moodle', count_words($post->message
)).')',
3448 array('class'=>'post-word-count'));
3450 // Prepare whole post
3451 $postclass = 'fullpost';
3452 $postcontent = format_text($post->message
, $post->messageformat
, $options, $course->id
);
3453 if (!empty($highlight)) {
3454 $postcontent = highlight($highlight, $postcontent);
3456 if (!empty($forum->displaywordcount
)) {
3457 $postcontent .= html_writer
::tag('div', get_string('numwords', 'moodle', count_words($post->message
)),
3458 array('class'=>'post-word-count'));
3460 $postcontent .= html_writer
::tag('div', $attachedimages, array('class'=>'attachedimages'));
3463 // Output the post content
3464 $output .= html_writer
::tag('div', $postcontent, array('class'=>'posting '.$postclass));
3465 $output .= html_writer
::end_tag('div'); // Content
3466 $output .= html_writer
::end_tag('div'); // Content mask
3467 $output .= html_writer
::end_tag('div'); // Row
3469 $output .= html_writer
::start_tag('div', array('class'=>'row side'));
3470 $output .= html_writer
::tag('div',' ', array('class'=>'left'));
3471 $output .= html_writer
::start_tag('div', array('class'=>'options clearfix'));
3473 if (!empty($attachments)) {
3474 $output .= html_writer
::tag('div', $attachments, array('class' => 'attachments'));
3478 if (!empty($post->rating
)) {
3479 $output .= html_writer
::tag('div', $OUTPUT->render($post->rating
), array('class'=>'forum-post-rating'));
3482 // Output the commands
3483 $commandhtml = array();
3484 foreach ($commands as $command) {
3485 if (is_array($command)) {
3486 $commandhtml[] = html_writer
::link($command['url'], $command['text']);
3488 $commandhtml[] = $command;
3491 $output .= html_writer
::tag('div', implode(' | ', $commandhtml), array('class'=>'commands'));
3493 // Output link to post if required
3494 if ($link && forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
3495 if ($post->replies
== 1) {
3496 $replystring = get_string('repliesone', 'forum', $post->replies
);
3498 $replystring = get_string('repliesmany', 'forum', $post->replies
);
3501 $output .= html_writer
::start_tag('div', array('class'=>'link'));
3502 $output .= html_writer
::link($discussionlink, get_string('discussthistopic', 'forum'));
3503 $output .= ' ('.$replystring.')';
3504 $output .= html_writer
::end_tag('div'); // link
3507 // Output footer if required
3509 $output .= html_writer
::tag('div', $footer, array('class'=>'footer'));
3512 // Close remaining open divs
3513 $output .= html_writer
::end_tag('div'); // content
3514 $output .= html_writer
::end_tag('div'); // row
3515 $output .= html_writer
::end_tag('div'); // forumpost
3517 // Mark the forum post as read if required
3518 if ($istracked && !$CFG->forum_usermarksread
&& !$postisread) {
3519 forum_tp_mark_post_read($USER->id
, $post, $forum->id
);
3530 * Return rating related permissions
3532 * @param string $options the context id
3533 * @return array an associative array of the user's rating permissions
3535 function forum_rating_permissions($contextid, $component, $ratingarea) {
3536 $context = context
::instance_by_id($contextid, MUST_EXIST
);
3537 if ($component != 'mod_forum' ||
$ratingarea != 'post') {
3538 // We don't know about this component/ratingarea so just return null to get the
3539 // default restrictive permissions.
3543 'view' => has_capability('mod/forum:viewrating', $context),
3544 'viewany' => has_capability('mod/forum:viewanyrating', $context),
3545 'viewall' => has_capability('mod/forum:viewallratings', $context),
3546 'rate' => has_capability('mod/forum:rate', $context)
3551 * Validates a submitted rating
3552 * @param array $params submitted data
3553 * context => object the context in which the rated items exists [required]
3554 * component => The component for this module - should always be mod_forum [required]
3555 * ratingarea => object the context in which the rated items exists [required]
3556 * itemid => int the ID of the object being rated [required]
3557 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
3558 * rating => int the submitted rating [required]
3559 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
3560 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
3561 * @return boolean true if the rating is valid. Will throw rating_exception if not
3563 function forum_rating_validate($params) {
3566 // Check the component is mod_forum
3567 if ($params['component'] != 'mod_forum') {
3568 throw new rating_exception('invalidcomponent');
3571 // Check the ratingarea is post (the only rating area in forum)
3572 if ($params['ratingarea'] != 'post') {
3573 throw new rating_exception('invalidratingarea');
3576 // Check the rateduserid is not the current user .. you can't rate your own posts
3577 if ($params['rateduserid'] == $USER->id
) {
3578 throw new rating_exception('nopermissiontorate');
3581 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
3582 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST
);
3583 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
), '*', MUST_EXIST
);
3584 $forum = $DB->get_record('forum', array('id' => $discussion->forum
), '*', MUST_EXIST
);
3585 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
3586 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
3587 $context = context_module
::instance($cm->id
);
3589 // Make sure the context provided is the context of the forum
3590 if ($context->id
!= $params['context']->id
) {
3591 throw new rating_exception('invalidcontext');
3594 if ($forum->scale
!= $params['scaleid']) {
3595 //the scale being submitted doesnt match the one in the database
3596 throw new rating_exception('invalidscaleid');
3599 // check the item we're rating was created in the assessable time window
3600 if (!empty($forum->assesstimestart
) && !empty($forum->assesstimefinish
)) {
3601 if ($post->created
< $forum->assesstimestart ||
$post->created
> $forum->assesstimefinish
) {
3602 throw new rating_exception('notavailable');
3606 //check that the submitted rating is valid for the scale
3609 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
3610 throw new rating_exception('invalidnum');
3614 if ($forum->scale
< 0) {
3615 //its a custom scale
3616 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale
));
3618 $scalearray = explode(',', $scalerecord->scale
);
3619 if ($params['rating'] > count($scalearray)) {
3620 throw new rating_exception('invalidnum');
3623 throw new rating_exception('invalidscaleid');
3625 } else if ($params['rating'] > $forum->scale
) {
3626 //if its numeric and submitted rating is above maximum
3627 throw new rating_exception('invalidnum');
3630 // Make sure groups allow this user to see the item they're rating
3631 if ($discussion->groupid
> 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
3632 if (!groups_group_exists($discussion->groupid
)) { // Can't find group
3633 throw new rating_exception('cannotfindgroup');//something is wrong
3636 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
3637 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
3638 throw new rating_exception('notmemberofgroup');
3642 // perform some final capability checks
3643 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
3644 throw new rating_exception('nopermissiontorate');
3652 * This function prints the overview of a discussion in the forum listing.
3653 * It needs some discussion information and some post information, these
3654 * happen to be combined for efficiency in the $post parameter by the function
3655 * that calls this one: forum_print_latest_discussions()
3659 * @param object $post The post object (passed by reference for speed).
3660 * @param object $forum The forum object.
3661 * @param int $group Current group.
3662 * @param string $datestring Format to use for the dates.
3663 * @param boolean $cantrack Is tracking enabled for this forum.
3664 * @param boolean $forumtracked Is the user tracking this forum.
3665 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
3667 function forum_print_discussion_header(&$post, $forum, $group=-1, $datestring="",
3668 $cantrack=true, $forumtracked=true, $canviewparticipants=true, $modcontext=NULL) {
3670 global $COURSE, $USER, $CFG, $OUTPUT;
3673 static $strmarkalldread;
3675 if (empty($modcontext)) {
3676 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
3677 print_error('invalidcoursemodule');
3679 $modcontext = context_module
::instance($cm->id
);
3682 if (!isset($rowcount)) {
3684 $strmarkalldread = get_string('markalldread', 'forum');
3686 $rowcount = ($rowcount +
1) %
2;
3689 $post->subject
= format_string($post->subject
,true);
3692 echo '<tr class="discussion r'.$rowcount.'">';
3695 echo '<td class="topic starter">';
3696 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'">'.$post->subject
.'</a>';
3700 $postuser = new stdClass();
3701 $postuserfields = explode(',', user_picture
::fields());
3702 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
3703 $postuser->id
= $post->userid
;
3704 echo '<td class="picture">';
3705 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course
));
3709 $fullname = fullname($postuser, has_capability('moodle/site:viewfullnames', $modcontext));
3710 echo '<td class="author">';
3711 echo '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$post->userid
.'&course='.$forum->course
.'">'.$fullname.'</a>';
3715 if ($group !== -1) { // Groups are active - group is a group data object or NULL
3716 echo '<td class="picture group">';
3717 if (!empty($group->picture
) and empty($group->hidepicture
)) {
3718 if ($canviewparticipants && $COURSE->groupmode
) {
3719 $picturelink = true;
3721 $picturelink = false;
3723 print_group_picture($group, $forum->course
, false, false, $picturelink);
3724 } else if (isset($group->id
)) {
3725 if ($canviewparticipants && $COURSE->groupmode
) {
3726 echo '<a href="'.$CFG->wwwroot
.'/user/index.php?id='.$forum->course
.'&group='.$group->id
.'">'.$group->name
.'</a>';
3734 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
3735 echo '<td class="replies">';
3736 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'">';
3737 echo $post->replies
.'</a>';
3741 echo '<td class="replies">';
3742 if ($forumtracked) {
3743 if ($post->unread
> 0) {
3744 echo '<span class="unread">';
3745 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.'#unread">';
3748 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot
.'/mod/forum/markposts.php?f='.
3749 $forum->id
.'&d='.$post->discussion
.'&mark=read&returnpage=view.php">' .
3750 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.$strmarkalldread.'" /></a>';
3753 echo '<span class="read">';
3758 echo '<span class="read">';
3766 echo '<td class="lastpost">';
3767 $usedate = (empty($post->timemodified
)) ?
$post->modified
: $post->timemodified
; // Just in case
3769 $usermodified = new stdClass();
3770 $usermodified->id
= $post->usermodified
;
3771 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
3773 // Show link to last poster and their post if user can see them.
3774 if ($canviewparticipants) {
3775 echo '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$post->usermodified
.'&course='.$forum->course
.'">'.
3776 fullname($usermodified).'</a><br />';
3777 $parenturl = (empty($post->lastpostid
)) ?
'' : '&parent='.$post->lastpostid
;
3780 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/discuss.php?d='.$post->discussion
.$parenturl.'">'.
3781 userdate($usedate, $datestring).'</a>';
3784 // is_guest should be used here as this also checks whether the user is a guest in the current course.
3785 // Guests and visitors cannot subscribe - only enrolled users.
3786 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
3787 // Discussion subscription.
3788 if (\mod_forum\subscriptions
::is_subscribable($forum)) {
3789 echo '<td class="discussionsubscription">';
3790 echo forum_get_discussion_subscription_icon($forum, $post->discussion
);
3800 * Return the markup for the discussion subscription toggling icon.
3802 * @param stdClass $forum The forum object.
3803 * @param int $discussionid The discussion to create an icon for.
3804 * @return string The generated markup.
3806 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
3807 global $USER, $OUTPUT, $PAGE;
3809 if ($returnurl === null && $PAGE->url
) {
3810 $returnurl = $PAGE->url
->out();
3814 $subscriptionstatus = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum, $discussionid);
3815 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
3816 'sesskey' => sesskey(),
3818 'd' => $discussionid,
3819 'returnurl' => $returnurl,
3823 $o .= $subscriptionstatus ?
get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
3826 if ($subscriptionstatus) {
3827 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
3829 $output .= get_string('subscribed', 'mod_forum');
3832 return html_writer
::link($subscriptionlink, $output, array(
3833 'title' => get_string('clicktounsubscribe', 'forum'),
3834 'class' => 'discussiontoggle iconsmall',
3835 'data-forumid' => $forum->id
,
3836 'data-discussionid' => $discussionid,
3837 'data-includetext' => $includetext,
3841 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
3843 $output .= get_string('notsubscribed', 'mod_forum');
3846 return html_writer
::link($subscriptionlink, $output, array(
3847 'title' => get_string('clicktosubscribe', 'forum'),
3848 'class' => 'discussiontoggle iconsmall',
3849 'data-forumid' => $forum->id
,
3850 'data-discussionid' => $discussionid,
3851 'data-includetext' => $includetext,
3857 * Return a pair of spans containing classes to allow the subscribe and
3858 * unsubscribe icons to be pre-loaded by a browser.
3860 * @return string The generated markup
3862 function forum_get_discussion_subscription_icon_preloaders() {
3864 $o .= html_writer
::span(' ', 'preload-subscribe');
3865 $o .= html_writer
::span(' ', 'preload-unsubscribe');
3870 * Print the drop down that allows the user to select how they want to have
3871 * the discussion displayed.
3873 * @param int $id forum id if $forumtype is 'single',
3874 * discussion id for any other forum type
3875 * @param mixed $mode forum layout mode
3876 * @param string $forumtype optional
3878 function forum_print_mode_form($id, $mode, $forumtype='') {
3880 if ($forumtype == 'single') {
3881 $select = new single_select(new moodle_url("/mod/forum/view.php", array('f'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3882 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3883 $select->class = "forummode";
3885 $select = new single_select(new moodle_url("/mod/forum/discuss.php", array('d'=>$id)), 'mode', forum_get_layout_modes(), $mode, null, "mode");
3886 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
3888 echo $OUTPUT->render($select);
3893 * @param object $course
3894 * @param string $search
3897 function forum_search_form($course, $search='') {
3898 global $CFG, $OUTPUT;
3900 $output = '<div class="forumsearch">';
3901 $output .= '<form action="'.$CFG->wwwroot
.'/mod/forum/search.php" style="display:inline">';
3902 $output .= '<fieldset class="invisiblefieldset">';
3903 $output .= $OUTPUT->help_icon('search');
3904 $output .= '<label class="accesshide" for="search" >'.get_string('search', 'forum').'</label>';
3905 $output .= '<input id="search" name="search" type="text" size="18" value="'.s($search, true).'" />';
3906 $output .= '<label class="accesshide" for="searchforums" >'.get_string('searchforums', 'forum').'</label>';
3907 $output .= '<input id="searchforums" value="'.get_string('searchforums', 'forum').'" type="submit" />';
3908 $output .= '<input name="id" type="hidden" value="'.$course->id
.'" />';
3909 $output .= '</fieldset>';
3910 $output .= '</form>';
3911 $output .= '</div>';
3921 function forum_set_return() {
3922 global $CFG, $SESSION;
3924 if (! isset($SESSION->fromdiscussion
)) {
3925 if (!empty($_SERVER['HTTP_REFERER'])) {
3926 $referer = $_SERVER['HTTP_REFERER'];
3930 // If the referer is NOT a login screen then save it.
3931 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
3932 $SESSION->fromdiscussion
= $_SERVER["HTTP_REFERER"];
3940 * @param string $default
3943 function forum_go_back_to($default) {
3946 if (!empty($SESSION->fromdiscussion
)) {
3947 $returnto = $SESSION->fromdiscussion
;
3948 unset($SESSION->fromdiscussion
);
3956 * Given a discussion object that is being moved to $forumto,
3957 * this function checks all posts in that discussion
3958 * for attachments, and if any are found, these are
3959 * moved to the new forum directory.
3962 * @param object $discussion
3963 * @param int $forumfrom source forum id
3964 * @param int $forumto target forum id
3965 * @return bool success
3967 function forum_move_attachments($discussion, $forumfrom, $forumto) {
3970 $fs = get_file_storage();
3972 $newcm = get_coursemodule_from_instance('forum', $forumto);
3973 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
3975 $newcontext = context_module
::instance($newcm->id
);
3976 $oldcontext = context_module
::instance($oldcm->id
);
3978 // loop through all posts, better not use attachment flag ;-)
3979 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id
), '', 'id, attachment')) {
3980 foreach ($posts as $post) {
3981 $fs->move_area_files_to_new_context($oldcontext->id
,
3982 $newcontext->id
, 'mod_forum', 'post', $post->id
);
3983 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id
,
3984 $newcontext->id
, 'mod_forum', 'attachment', $post->id
);
3985 if ($attachmentsmoved > 0 && $post->attachment
!= '1') {
3986 // Weird - let's fix it
3987 $post->attachment
= '1';
3988 $DB->update_record('forum_posts', $post);
3989 } else if ($attachmentsmoved == 0 && $post->attachment
!= '') {
3990 // Weird - let's fix it
3991 $post->attachment
= '';
3992 $DB->update_record('forum_posts', $post);
4001 * Returns attachments as formated text/html optionally with separate images
4006 * @param object $post
4008 * @param string $type html/text/separateimages
4009 * @return mixed string or array of (html text withouth images and image HTML)
4011 function forum_print_attachments($post, $cm, $type) {
4012 global $CFG, $DB, $USER, $OUTPUT;
4014 if (empty($post->attachment
)) {
4015 return $type !== 'separateimages' ?
'' : array('', '');
4018 if (!in_array($type, array('separateimages', 'html', 'text'))) {
4019 return $type !== 'separateimages' ?
'' : array('', '');
4022 if (!$context = context_module
::instance($cm->id
)) {
4023 return $type !== 'separateimages' ?
'' : array('', '');
4025 $strattachment = get_string('attachment', 'forum');
4027 $fs = get_file_storage();
4032 $canexport = !empty($CFG->enableportfolios
) && (has_capability('mod/forum:exportpost', $context) ||
($post->userid
== $USER->id
&& has_capability('mod/forum:exportownpost', $context)));
4035 require_once($CFG->libdir
.'/portfoliolib.php');
4038 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
4039 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
4040 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "filename", false);
4043 $button = new portfolio_add_button();
4045 foreach ($files as $file) {
4046 $filename = $file->get_filename();
4047 $mimetype = $file->get_mimetype();
4048 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
4049 $path = file_encode_url($CFG->wwwroot
.'/pluginfile.php', '/'.$context->id
.'/mod_forum/attachment/'.$post->id
.'/'.$filename);
4051 if ($type == 'html') {
4052 $output .= "<a href=\"$path\">$iconimage</a> ";
4053 $output .= "<a href=\"$path\">".s($filename)."</a>";
4055 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4056 $button->set_format_by_file($file);
4057 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4059 $output .= "<br />";
4061 } else if ($type == 'text') {
4062 $output .= "$strattachment ".s($filename).":\n$path\n";
4064 } else { //'returnimages'
4065 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
4066 // Image attachments don't get printed as links
4067 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
4069 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4070 $button->set_format_by_file($file);
4071 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4074 $output .= "<a href=\"$path\">$iconimage</a> ";
4075 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML
, array('context'=>$context));
4077 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id
, 'attachment' => $file->get_id()), 'mod_forum');
4078 $button->set_format_by_file($file);
4079 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
4081 $output .= '<br />';
4085 if (!empty($CFG->enableplagiarism
)) {
4086 require_once($CFG->libdir
.'/plagiarismlib.php');
4087 $output .= plagiarism_get_links(array('userid' => $post->userid
,
4090 'course' => $post->course
,
4091 'forum' => $post->forum
));
4092 $output .= '<br />';
4097 if ($type !== 'separateimages') {
4101 return array($output, $imagereturn);
4105 ////////////////////////////////////////////////////////////////////////////////
4107 ////////////////////////////////////////////////////////////////////////////////
4110 * Lists all browsable file areas
4112 * @package mod_forum
4114 * @param stdClass $course course object
4115 * @param stdClass $cm course module object
4116 * @param stdClass $context context object
4119 function forum_get_file_areas($course, $cm, $context) {
4121 'attachment' => get_string('areaattachment', 'mod_forum'),
4122 'post' => get_string('areapost', 'mod_forum'),
4127 * File browsing support for forum module.
4129 * @package mod_forum
4131 * @param stdClass $browser file browser object
4132 * @param stdClass $areas file areas
4133 * @param stdClass $course course object
4134 * @param stdClass $cm course module
4135 * @param stdClass $context context module
4136 * @param string $filearea file area
4137 * @param int $itemid item ID
4138 * @param string $filepath file path
4139 * @param string $filename file name
4140 * @return file_info instance or null if not found
4142 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
4143 global $CFG, $DB, $USER;
4145 if ($context->contextlevel
!= CONTEXT_MODULE
) {
4149 // filearea must contain a real area
4150 if (!isset($areas[$filearea])) {
4154 // Note that forum_user_can_see_post() additionally allows access for parent roles
4155 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
4156 // course:managefiles, we will need to extend this.
4157 if (!has_capability('mod/forum:viewdiscussion', $context)) {
4161 if (is_null($itemid)) {
4162 require_once($CFG->dirroot
.'/mod/forum/locallib.php');
4163 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
4166 static $cached = array();
4167 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
4168 // is cleared between unit tests we check if this is the same session
4169 if (!isset($cached['sesskey']) ||
$cached['sesskey'] != sesskey()) {
4170 $cached = array('sesskey' => sesskey());
4173 if (isset($cached['post']) && $cached['post']->id
== $itemid) {
4174 $post = $cached['post'];
4175 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
4176 $cached['post'] = $post;
4181 if (isset($cached['discussion']) && $cached['discussion']->id
== $post->discussion
) {
4182 $discussion = $cached['discussion'];
4183 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
))) {
4184 $cached['discussion'] = $discussion;
4189 if (isset($cached['forum']) && $cached['forum']->id
== $cm->instance
) {
4190 $forum = $cached['forum'];
4191 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance
))) {
4192 $cached['forum'] = $forum;
4197 $fs = get_file_storage();
4198 $filepath = is_null($filepath) ?
'/' : $filepath;
4199 $filename = is_null($filename) ?
'.' : $filename;
4200 if (!($storedfile = $fs->get_file($context->id
, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
4204 // Checks to see if the user can manage files or is the owner.
4205 // TODO MDL-33805 - Do not use userid here and move the capability check above.
4206 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
4209 // Make sure groups allow this user to see this file
4210 if ($discussion->groupid
> 0 && !has_capability('moodle/site:accessallgroups', $context)) {
4211 $groupmode = groups_get_activity_groupmode($cm, $course);
4212 if ($groupmode == SEPARATEGROUPS
&& !groups_is_member($discussion->groupid
)) {
4217 // Make sure we're allowed to see it...
4218 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4222 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
4223 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
4227 * Serves the forum attachments. Implements needed access control ;-)
4229 * @package mod_forum
4231 * @param stdClass $course course object
4232 * @param stdClass $cm course module object
4233 * @param stdClass $context context object
4234 * @param string $filearea file area
4235 * @param array $args extra arguments
4236 * @param bool $forcedownload whether or not force download
4237 * @param array $options additional options affecting the file serving
4238 * @return bool false if file not found, does not return if found - justsend the file
4240 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
4243 if ($context->contextlevel
!= CONTEXT_MODULE
) {
4247 require_course_login($course, true, $cm);
4249 $areas = forum_get_file_areas($course, $cm, $context);
4251 // filearea must contain a real area
4252 if (!isset($areas[$filearea])) {
4256 $postid = (int)array_shift($args);
4258 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
4262 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion
))) {
4266 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance
))) {
4270 $fs = get_file_storage();
4271 $relativepath = implode('/', $args);
4272 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
4273 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4277 // Make sure groups allow this user to see this file
4278 if ($discussion->groupid
> 0) {
4279 $groupmode = groups_get_activity_groupmode($cm, $course);
4280 if ($groupmode == SEPARATEGROUPS
) {
4281 if (!groups_is_member($discussion->groupid
) and !has_capability('moodle/site:accessallgroups', $context)) {
4287 // Make sure we're allowed to see it...
4288 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
4292 // finally send the file
4293 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
4297 * If successful, this function returns the name of the file
4300 * @param object $post is a full post record, including course and forum
4301 * @param object $forum
4303 * @param mixed $mform
4304 * @param string $unused
4307 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
4310 if (empty($mform)) {
4314 if (empty($post->attachments
)) {
4315 return true; // Nothing to do
4318 $context = context_module
::instance($cm->id
);
4320 $info = file_get_draft_area_info($post->attachments
);
4321 $present = ($info['filecount']>0) ?
'1' : '';
4322 file_save_draft_area_files($post->attachments
, $context->id
, 'mod_forum', 'attachment', $post->id
,
4323 mod_forum_post_form
::attachment_options($forum));
4325 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id
));
4331 * Add a new post in an existing discussion.
4336 * @param object $post
4337 * @param mixed $mform
4338 * @param string $unused formerly $message, renamed in 2.8 as it was unused.
4341 function forum_add_new_post($post, $mform, $unused = null) {
4342 global $USER, $CFG, $DB;
4344 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
4345 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
4346 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4347 $context = context_module
::instance($cm->id
);
4349 $post->created
= $post->modified
= time();
4350 $post->mailed
= FORUM_MAILED_PENDING
;
4351 $post->userid
= $USER->id
;
4352 $post->attachment
= "";
4353 if (!isset($post->totalscore
)) {
4354 $post->totalscore
= 0;
4356 if (!isset($post->mailnow
)) {
4360 $post->id
= $DB->insert_record("forum_posts", $post);
4361 $post->message
= file_save_draft_area_files($post->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4362 mod_forum_post_form
::editor_options($context, null), $post->message
);
4363 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
4364 forum_add_attachment($post, $forum, $cm, $mform);
4366 // Update discussion modified date
4367 $DB->set_field("forum_discussions", "timemodified", $post->modified
, array("id" => $post->discussion
));
4368 $DB->set_field("forum_discussions", "usermodified", $post->userid
, array("id" => $post->discussion
));
4370 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4371 forum_tp_mark_post_read($post->userid
, $post, $post->forum
);
4374 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4375 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
4386 * @param object $post
4387 * @param mixed $mform
4388 * @param string $message
4391 function forum_update_post($post, $mform, &$message) {
4392 global $USER, $CFG, $DB;
4394 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion
));
4395 $forum = $DB->get_record('forum', array('id' => $discussion->forum
));
4396 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4397 $context = context_module
::instance($cm->id
);
4399 $post->modified
= time();
4401 $DB->update_record('forum_posts', $post);
4403 $discussion->timemodified
= $post->modified
; // last modified tracking
4404 $discussion->usermodified
= $post->userid
; // last modified tracking
4406 if (!$post->parent
) { // Post is a discussion starter - update discussion title and times too
4407 $discussion->name
= $post->subject
;
4408 $discussion->timestart
= $post->timestart
;
4409 $discussion->timeend
= $post->timeend
;
4411 $post->message
= file_save_draft_area_files($post->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4412 mod_forum_post_form
::editor_options($context, $post->id
), $post->message
);
4413 $DB->set_field('forum_posts', 'message', $post->message
, array('id'=>$post->id
));
4415 $DB->update_record('forum_discussions', $discussion);
4417 forum_add_attachment($post, $forum, $cm, $mform, $message);
4419 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4420 forum_tp_mark_post_read($post->userid
, $post, $post->forum
);
4423 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4424 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
4430 * Given an object containing all the necessary data,
4431 * create a new discussion and return the id
4433 * @param object $post
4434 * @param mixed $mform
4435 * @param string $unused
4436 * @param int $userid
4439 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) {
4440 global $USER, $CFG, $DB;
4444 if (is_null($userid)) {
4445 $userid = $USER->id
;
4448 // The first post is stored as a real post, and linked
4449 // to from the discuss entry.
4451 $forum = $DB->get_record('forum', array('id'=>$discussion->forum
));
4452 $cm = get_coursemodule_from_instance('forum', $forum->id
);
4454 $post = new stdClass();
4455 $post->discussion
= 0;
4457 $post->userid
= $userid;
4458 $post->created
= $timenow;
4459 $post->modified
= $timenow;
4460 $post->mailed
= FORUM_MAILED_PENDING
;
4461 $post->subject
= $discussion->name
;
4462 $post->message
= $discussion->message
;
4463 $post->messageformat
= $discussion->messageformat
;
4464 $post->messagetrust
= $discussion->messagetrust
;
4465 $post->attachments
= isset($discussion->attachments
) ?
$discussion->attachments
: null;
4466 $post->forum
= $forum->id
; // speedup
4467 $post->course
= $forum->course
; // speedup
4468 $post->mailnow
= $discussion->mailnow
;
4470 $post->id
= $DB->insert_record("forum_posts", $post);
4472 // TODO: Fix the calling code so that there always is a $cm when this function is called
4473 if (!empty($cm->id
) && !empty($discussion->itemid
)) { // In "single simple discussions" this may not exist yet
4474 $context = context_module
::instance($cm->id
);
4475 $text = file_save_draft_area_files($discussion->itemid
, $context->id
, 'mod_forum', 'post', $post->id
,
4476 mod_forum_post_form
::editor_options($context, null), $post->message
);
4477 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id
));
4480 // Now do the main entry for the discussion, linking to this first post
4482 $discussion->firstpost
= $post->id
;
4483 $discussion->timemodified
= $timenow;
4484 $discussion->usermodified
= $post->userid
;
4485 $discussion->userid
= $userid;
4486 $discussion->assessed
= 0;
4488 $post->discussion
= $DB->insert_record("forum_discussions", $discussion);
4490 // Finally, set the pointer on the post.
4491 $DB->set_field("forum_posts", "discussion", $post->discussion
, array("id"=>$post->id
));
4493 if (!empty($cm->id
)) {
4494 forum_add_attachment($post, $forum, $cm, $mform, $unused);
4497 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
4498 forum_tp_mark_post_read($post->userid
, $post, $post->forum
);
4501 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
4502 if (!empty($cm->id
)) {
4503 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion');
4506 return $post->discussion
;
4511 * Deletes a discussion and handles all associated cleanup.
4514 * @param object $discussion Discussion to delete
4515 * @param bool $fulldelete True when deleting entire forum
4516 * @param object $course Course
4517 * @param object $cm Course-module
4518 * @param object $forum Forum
4521 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) {
4523 require_once($CFG->libdir
.'/completionlib.php');
4527 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id
))) {
4528 foreach ($posts as $post) {
4529 $post->course
= $discussion->course
;
4530 $post->forum
= $discussion->forum
;
4531 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) {
4537 forum_tp_delete_read_records(-1, -1, $discussion->id
);
4539 // Discussion subscriptions must be removed before discussions because of key constraints.
4540 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id
));
4541 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id
))) {
4545 // Update completion state if we are tracking completion based on number of posts
4546 // But don't bother when deleting whole thing
4548 $completion = new completion_info($course);
4549 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
4550 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
4551 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $discussion->userid
);
4560 * Deletes a single forum post.
4563 * @param object $post Forum post object
4564 * @param mixed $children Whether to delete children. If false, returns false
4565 * if there are any children (without deleting the post). If true,
4566 * recursively deletes all children. If set to special value 'ignore', deletes
4567 * post regardless of children (this is for use only when deleting all posts
4569 * @param object $course Course
4570 * @param object $cm Course-module
4571 * @param object $forum Forum
4572 * @param bool $skipcompletion True to skip updating completion state if it
4573 * would otherwise be updated, i.e. when deleting entire forum anyway.
4576 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) {
4578 require_once($CFG->libdir
.'/completionlib.php');
4580 $context = context_module
::instance($cm->id
);
4582 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id
)))) {
4584 foreach ($childposts as $childpost) {
4585 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion);
4593 require_once($CFG->dirroot
.'/rating/lib.php');
4594 $delopt = new stdClass
;
4595 $delopt->contextid
= $context->id
;
4596 $delopt->component
= 'mod_forum';
4597 $delopt->ratingarea
= 'post';
4598 $delopt->itemid
= $post->id
;
4599 $rm = new rating_manager();
4600 $rm->delete_ratings($delopt);
4602 // Delete attachments.
4603 $fs = get_file_storage();
4604 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment', $post->id
);
4605 $fs->delete_area_files($context->id
, 'mod_forum', 'post', $post->id
);
4607 // Delete cached RSS feeds.
4608 if (!empty($CFG->enablerssfeeds
)) {
4609 require_once($CFG->dirroot
.'/mod/forum/rsslib.php');
4610 forum_rss_delete_file($forum);
4613 if ($DB->delete_records("forum_posts", array("id" => $post->id
))) {
4615 forum_tp_delete_read_records(-1, $post->id
);
4617 // Just in case we are deleting the last post
4618 forum_discussion_update_last_post($post->discussion
);
4620 // Update completion state if we are tracking completion based on number of posts
4621 // But don't bother when deleting whole thing
4623 if (!$skipcompletion) {
4624 $completion = new completion_info($course);
4625 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC
&&
4626 ($forum->completiondiscussions ||
$forum->completionreplies ||
$forum->completionposts
)) {
4627 $completion->update_state($cm, COMPLETION_INCOMPLETE
, $post->userid
);
4637 * Sends post content to plagiarism plugin
4638 * @param object $post Forum post object
4639 * @param object $cm Course-module
4640 * @param string $name
4643 function forum_trigger_content_uploaded_event($post, $cm, $name) {
4644 $context = context_module
::instance($cm->id
);
4645 $fs = get_file_storage();
4646 $files = $fs->get_area_files($context->id
, 'mod_forum', 'attachment', $post->id
, "timemodified", false);
4648 'context' => $context,
4649 'objectid' => $post->id
,
4651 'content' => $post->message
,
4652 'pathnamehashes' => array_keys($files),
4653 'discussionid' => $post->discussion
,
4654 'triggeredfrom' => $name,
4657 $event = \mod_forum\event\assessable_uploaded
::create($params);
4664 * @param object $post
4665 * @param bool $children
4668 function forum_count_replies($post, $children=true) {
4673 if ($childposts = $DB->get_records('forum_posts', array('parent' => $post->id
))) {
4674 foreach ($childposts as $childpost) {
4675 $count ++
; // For this child
4676 $count +
= forum_count_replies($childpost, true);
4680 $count +
= $DB->count_records('forum_posts', array('parent' => $post->id
));
4687 * Given a new post, subscribes or unsubscribes as appropriate.
4688 * Returns some text which describes what happened.
4690 * @param object $fromform The submitted form
4691 * @param stdClass $forum The forum record
4692 * @param stdClass $discussion The forum discussion record
4695 function forum_post_subscription($fromform, $forum, $discussion) {
4698 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
4700 } else if (\mod_forum\subscriptions
::subscription_disabled($forum)) {
4701 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
4702 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course
::instance($forum->course
), $USER->id
)) {
4703 // This user should not be subscribed to the forum.
4704 \mod_forum\subscriptions
::unsubscribe_user($USER->id
, $forum);
4709 $info = new stdClass();
4710 $info->name
= fullname($USER);
4711 $info->discussion
= format_string($discussion->name
);
4712 $info->forum
= format_string($forum->name
);
4714 if ($fromform->discussionsubscribe
) {
4715 if ($result = \mod_forum\subscriptions
::subscribe_user_to_discussion($USER->id
, $discussion)) {
4716 return html_writer
::tag('p', get_string('discussionnowsubscribed', 'forum', $info));
4719 if ($result = \mod_forum\subscriptions
::unsubscribe_user_from_discussion($USER->id
, $discussion)) {
4720 return html_writer
::tag('p', get_string('discussionnownotsubscribed', 'forum', $info));
4728 * Generate and return the subscribe or unsubscribe link for a forum.
4730 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
4731 * @param object $context the context object for this forum.
4732 * @param array $messages text used for the link in its various states
4733 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
4734 * Any strings not passed in are taken from the $defaultmessages array
4735 * at the top of the function.
4736 * @param bool $cantaccessagroup
4737 * @param bool $fakelink
4738 * @param bool $backtoindex
4739 * @param array $subscribed_forums
4742 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $fakelink=true, $backtoindex=false, $subscribed_forums=null) {
4743 global $CFG, $USER, $PAGE, $OUTPUT;
4744 $defaultmessages = array(
4745 'subscribed' => get_string('unsubscribe', 'forum'),
4746 'unsubscribed' => get_string('subscribe', 'forum'),
4747 'cantaccessgroup' => get_string('no'),
4748 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'),
4749 'cantsubscribe' => get_string('disallowsubscribe','forum')
4751 $messages = $messages +
$defaultmessages;
4753 if (\mod_forum\subscriptions
::is_forcesubscribed($forum)) {
4754 return $messages['forcesubscribed'];
4755 } else if (\mod_forum\subscriptions
::subscription_disabled($forum) &&
4756 !has_capability('mod/forum:managesubscriptions', $context)) {
4757 return $messages['cantsubscribe'];
4758 } else if ($cantaccessagroup) {
4759 return $messages['cantaccessgroup'];
4761 if (!is_enrolled($context, $USER, '', true)) {
4765 $subscribed = \mod_forum\subscriptions
::is_subscribed($USER->id
, $forum);
4767 $linktext = $messages['subscribed'];
4768 $linktitle = get_string('subscribestop', 'forum');
4770 $linktext = $messages['unsubscribed'];
4771 $linktitle = get_string('subscribestart', 'forum');
4776 $backtoindexlink = '&backtoindex=1';
4777 $options['backtoindex'] = 1;
4779 $backtoindexlink = '';
4784 $PAGE->requires
->js('/mod/forum/forum.js');
4785 $PAGE->requires
->js_function_call('forum_produce_subscribe_link', array($forum->id
, $backtoindexlink, $linktext, $linktitle));
4786 $link = "<noscript>";
4788 $options['id'] = $forum->id
;
4789 $options['sesskey'] = sesskey();
4790 $url = new moodle_url('/mod/forum/subscribe.php', $options);
4791 $link .= $OUTPUT->single_button($url, $linktext, 'get', array('title'=>$linktitle));
4793 $link .= '</noscript>';
4801 * Returns true if user created new discussion already
4805 * @param int $forumid
4806 * @param int $userid
4809 function forum_user_has_posted_discussion($forumid, $userid) {
4813 FROM {forum_discussions} d, {forum_posts} p
4814 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 and p.userid = ?";
4816 return $DB->record_exists_sql($sql, array($forumid, $userid));
4822 * @param int $forumid
4823 * @param int $userid
4826 function forum_discussions_user_has_posted_in($forumid, $userid) {
4829 $haspostedsql = "SELECT d.id AS id,
4831 FROM {forum_posts} p,
4832 {forum_discussions} d
4833 WHERE p.discussion = d.id
4837 return $DB->get_records_sql($haspostedsql, array($forumid, $userid));
4843 * @param int $forumid
4845 * @param int $userid
4848 function forum_user_has_posted($forumid, $did, $userid) {
4852 // posted in any forum discussion?
4854 FROM {forum_posts} p
4855 JOIN {forum_discussions} d ON d.id = p.discussion
4856 WHERE p.userid = :userid AND d.forum = :forumid";
4857 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid));
4859 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid));
4864 * Returns creation time of the first user's post in given discussion
4865 * @global object $DB
4866 * @param int $did Discussion id
4867 * @param int $userid User id
4868 * @return int|bool post creation time stamp or return false
4870 function forum_get_user_posted_time($did, $userid) {
4873 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did));
4874 if (empty($posttime)) {
4882 * @param object $forum
4883 * @param object $currentgroup
4884 * @param int $unused
4886 * @param object $context
4889 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) {
4890 // $forum is an object
4893 // shortcut - guest and not-logged-in users can not post
4894 if (isguestuser() or !isloggedin()) {
4899 debugging('missing cm', DEBUG_DEVELOPER
);
4900 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
4901 print_error('invalidcoursemodule');
4906 $context = context_module
::instance($cm->id
);
4909 if ($currentgroup === null) {
4910 $currentgroup = groups_get_activity_group($cm);
4913 $groupmode = groups_get_activity_groupmode($cm);
4915 if ($forum->type
== 'news') {
4916 $capname = 'mod/forum:addnews';
4917 } else if ($forum->type
== 'qanda') {
4918 $capname = 'mod/forum:addquestion';
4920 $capname = 'mod/forum:startdiscussion';
4923 if (!has_capability($capname, $context)) {
4927 if ($forum->type
== 'single') {
4931 if ($forum->type
== 'eachuser') {
4932 if (forum_user_has_posted_discussion($forum->id
, $USER->id
)) {
4937 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
4941 if ($currentgroup) {
4942 return groups_is_member($currentgroup);
4944 // no group membership and no accessallgroups means no new discussions
4945 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0
4951 * This function checks whether the user can reply to posts in a forum
4952 * discussion. Use forum_user_can_post_discussion() to check whether the user
4953 * can start discussions.
4957 * @uses DEBUG_DEVELOPER
4958 * @uses CONTEXT_MODULE
4959 * @uses VISIBLEGROUPS
4960 * @param object $forum forum object
4961 * @param object $discussion
4962 * @param object $user
4964 * @param object $course
4965 * @param object $context
4968 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) {
4974 // shortcut - guest and not-logged-in users can not post
4975 if (isguestuser($user) or empty($user->id
)) {
4979 if (!isset($discussion->groupid
)) {
4980 debugging('incorrect discussion parameter', DEBUG_DEVELOPER
);
4985 debugging('missing cm', DEBUG_DEVELOPER
);
4986 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
4987 print_error('invalidcoursemodule');
4992 debugging('missing course', DEBUG_DEVELOPER
);
4993 if (!$course = $DB->get_record('course', array('id' => $forum->course
))) {
4994 print_error('invalidcourseid');
4999 $context = context_module
::instance($cm->id
);
5002 // normal users with temporary guest access can not post, suspended users can not post either
5003 if (!is_viewing($context, $user->id
) and !is_enrolled($context, $user->id
, '', true)) {
5007 if ($forum->type
== 'news') {
5008 $capname = 'mod/forum:replynews';
5010 $capname = 'mod/forum:replypost';
5013 if (!has_capability($capname, $context, $user->id
)) {
5017 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) {
5021 if (has_capability('moodle/site:accessallgroups', $context)) {
5025 if ($groupmode == VISIBLEGROUPS
) {
5026 if ($discussion->groupid
== -1) {
5027 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8
5030 return groups_is_member($discussion->groupid
);
5034 if ($discussion->groupid
== -1) {
5037 return groups_is_member($discussion->groupid
);
5042 * Check to ensure a user can view a timed discussion.
5044 * @param object $discussion
5045 * @param object $user
5046 * @param object $context
5047 * @return boolean returns true if they can view post, false otherwise
5049 function forum_user_can_see_timed_discussion($discussion, $user, $context) {
5052 // Check that the user can view a discussion that is normally hidden due to access times.
5053 if (!empty($CFG->forum_enabletimedposts
)) {
5055 if (($discussion->timestart
!= 0 && $discussion->timestart
> $time)
5056 ||
($discussion->timeend
!= 0 && $discussion->timeend
< $time)) {
5057 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id
)) {
5067 * Check to ensure a user can view a group discussion.
5069 * @param object $discussion
5071 * @param object $context
5072 * @return boolean returns true if they can view post, false otherwise
5074 function forum_user_can_see_group_discussion($discussion, $cm, $context) {
5076 // If it's a grouped discussion, make sure the user is a member.
5077 if ($discussion->groupid
> 0) {
5078 $groupmode = groups_get_activity_groupmode($cm);
5079 if ($groupmode == SEPARATEGROUPS
) {
5080 return groups_is_member($discussion->groupid
) ||
has_capability('moodle/site:accessallgroups', $context);
5090 * @uses DEBUG_DEVELOPER
5091 * @param object $forum
5092 * @param object $discussion
5093 * @param object $context
5094 * @param object $user
5097 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) {
5100 if (empty($user) ||
empty($user->id
)) {
5104 // retrieve objects (yuk)
5105 if (is_numeric($forum)) {
5106 debugging('missing full forum', DEBUG_DEVELOPER
);
5107 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5111 if (is_numeric($discussion)) {
5112 debugging('missing full discussion', DEBUG_DEVELOPER
);
5113 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5117 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5118 print_error('invalidcoursemodule');
5121 if (!has_capability('mod/forum:viewdiscussion', $context)) {
5125 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) {
5129 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) {
5133 if ($forum->type
== 'qanda' &&
5134 !forum_user_has_posted($forum->id
, $discussion->id
, $user->id
) &&
5135 !has_capability('mod/forum:viewqandawithoutposting', $context)) {
5144 * @param object $forum
5145 * @param object $discussion
5146 * @param object $post
5147 * @param object $user
5151 function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NULL) {
5152 global $CFG, $USER, $DB;
5154 // Context used throughout function.
5155 $modcontext = context_module
::instance($cm->id
);
5157 // retrieve objects (yuk)
5158 if (is_numeric($forum)) {
5159 debugging('missing full forum', DEBUG_DEVELOPER
);
5160 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) {
5165 if (is_numeric($discussion)) {
5166 debugging('missing full discussion', DEBUG_DEVELOPER
);
5167 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) {
5171 if (is_numeric($post)) {
5172 debugging('missing full post', DEBUG_DEVELOPER
);
5173 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) {
5178 if (!isset($post->id
) && isset($post->parent
)) {
5179 $post->id
= $post->parent
;
5183 debugging('missing cm', DEBUG_DEVELOPER
);
5184 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5185 print_error('invalidcoursemodule');
5189 if (empty($user) ||
empty($user->id
)) {
5193 $canviewdiscussion = !empty($cm->cache
->caps
['mod/forum:viewdiscussion']) ||
has_capability('mod/forum:viewdiscussion', $modcontext, $user->id
);
5194 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user
::instance($post->userid
))) {
5198 if (isset($cm->uservisible
)) {
5199 if (!$cm->uservisible
) {
5203 if (!\core_availability\info_module
::is_user_visible($cm, $user->id
, false)) {
5208 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) {
5212 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) {
5216 if ($forum->type
== 'qanda') {
5217 $firstpost = forum_get_firstpost_from_discussion($discussion->id
);
5218 $userfirstpost = forum_get_user_posted_time($discussion->id
, $user->id
);
5220 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime
)) ||
5221 $firstpost->id
== $post->id ||
$post->userid
== $user->id ||
$firstpost->userid
== $user->id ||
5222 has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id
));
5229 * Prints the discussion view screen for a forum.
5233 * @param object $course The current course object.
5234 * @param object $forum Forum to be printed.
5235 * @param int $maxdiscussions .
5236 * @param string $displayformat The display format to use (optional).
5237 * @param string $sort Sort arguments for database query (optional).
5238 * @param int $groupmode Group mode of the forum (optional).
5239 * @param void $unused (originally current group)
5240 * @param int $page Page mode, page to display (optional).
5241 * @param int $perpage The maximum number of discussions per page(optional)
5242 * @param boolean $subscriptionstatus Whether the user is currently subscribed to the discussion in some fashion.
5245 function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '',
5246 $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = null) {
5247 global $CFG, $USER, $OUTPUT;
5250 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
)) {
5251 print_error('invalidcoursemodule');
5254 $context = context_module
::instance($cm->id
);
5257 $sort = "d.timemodified DESC";
5260 $olddiscussionlink = false;
5262 // Sort out some defaults
5263 if ($perpage <= 0) {
5268 if ($maxdiscussions == 0) {
5269 // all discussions - backwards compatibility
5272 if ($displayformat == 'plain') {
5273 $displayformat = 'header'; // Abbreviate display by default
5276 } else if ($maxdiscussions > 0) {
5278 $perpage = $maxdiscussions;
5282 if ($displayformat == 'plain') {
5287 // Decide if current user is allowed to see ALL the current discussions or not
5289 // First check the group stuff
5290 if ($currentgroup == -1 or $groupmode == -1) {
5291 $groupmode = groups_get_activity_groupmode($cm, $course);
5292 $currentgroup = groups_get_activity_group($cm);
5295 $groups = array(); //cache
5297 // If the user can post discussions, then this is a good place to put the
5298 // button for it. We do not show the button if we are showing site news
5299 // and the current user is a guest.
5301 $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
5302 if (!$canstart and $forum->type
!== 'news') {
5303 if (isguestuser() or !isloggedin()) {
5306 if (!is_enrolled($context) and !is_viewing($context)) {
5307 // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
5308 // normal users with temporary guest access see this button too, they are asked to enrol instead
5309 // do not show the button to users with suspended enrolments here
5310 $canstart = enrol_selfenrol_available($course->id
);
5315 echo '<div class="singlebutton forumaddnew">';
5316 echo "<form id=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
5318 echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
5319 switch ($forum->type
) {
5322 $buttonadd = get_string('addanewtopic', 'forum');
5325 $buttonadd = get_string('addanewquestion', 'forum');
5328 $buttonadd = get_string('addanewdiscussion', 'forum');
5331 echo '<input type="submit" value="'.$buttonadd.'" />';
5336 } else if (isguestuser() or !isloggedin() or $forum->type
== 'news' or
5337 $forum->type
== 'qanda' and !has_capability('mod/forum:addquestion', $context) or
5338 $forum->type
!= 'qanda' and !has_capability('mod/forum:startdiscussion', $context)) {
5339 // no button and no info
5341 } else if ($groupmode and !has_capability('moodle/site:accessallgroups', $context)) {
5342 // inform users why they can not post new discussion
5343 if (!$currentgroup) {
5344 echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
5345 } else if (!groups_is_member($currentgroup)) {
5346 echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
5350 // Get all the recent discussions we're allowed to see
5352 $getuserlastmodified = ($displayformat == 'header');
5354 if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
5355 echo '<div class="forumnodiscuss">';
5356 if ($forum->type
== 'news') {
5357 echo '('.get_string('nonews', 'forum').')';
5358 } else if ($forum->type
== 'qanda') {
5359 echo '('.get_string('noquestions','forum').')';
5361 echo '('.get_string('nodiscussions', 'forum').')';
5367 // If we want paging
5369 ///Get the number of discussions found
5370 $numdiscussions = forum_get_discussions_count($cm);
5372 ///Show the paging bar
5373 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5374 if ($numdiscussions > 1000) {
5375 // saves some memory on sites with very large forums
5376 $replies = forum_count_discussion_replies($forum->id
, $sort, $maxdiscussions, $page, $perpage);
5378 $replies = forum_count_discussion_replies($forum->id
);
5382 $replies = forum_count_discussion_replies($forum->id
);
5384 if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
5385 $olddiscussionlink = true;
5389 $canviewparticipants = has_capability('moodle/course:viewparticipants',$context);
5391 $strdatestring = get_string('strftimerecentfull');
5393 // Check if the forum is tracked.
5394 if ($cantrack = forum_tp_can_track_forums($forum)) {
5395 $forumtracked = forum_tp_is_tracked($forum);
5397 $forumtracked = false;
5400 if ($forumtracked) {
5401 $unreads = forum_get_discussions_unread($cm);
5406 if ($displayformat == 'header') {
5407 echo '<table cellspacing="0" class="forumheaderlist">';
5410 echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
5411 echo '<th class="header author" colspan="2" scope="col">'.get_string('startedby', 'forum').'</th>';
5412 if ($groupmode > 0) {
5413 echo '<th class="header group" scope="col">'.get_string('group').'</th>';
5415 if (has_capability('mod/forum:viewdiscussion', $context)) {
5416 echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
5417 // If the forum can be tracked, display the unread column.
5419 echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
5420 if ($forumtracked) {
5421 echo '<a title="'.get_string('markallread', 'forum').
5422 '" href="'.$CFG->wwwroot
.'/mod/forum/markposts.php?f='.
5423 $forum->id
.'&mark=read&returnpage=view.php">'.
5424 '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.get_string('markallread', 'forum').'" /></a>';
5429 echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
5430 if ((!is_guest($context, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $context)) {
5431 if (\mod_forum\subscriptions
::is_subscribable($forum)) {
5432 echo '<th class="header discussionsubscription" scope="col">';
5433 echo forum_get_discussion_subscription_icon_preloaders();
5442 foreach ($discussions as $discussion) {
5443 if ($forum->type
== 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context) &&
5444 !forum_user_has_posted($forum->id
, $discussion->discussion
, $USER->id
)) {
5445 $canviewparticipants = false;
5448 if (!empty($replies[$discussion->discussion
])) {
5449 $discussion->replies
= $replies[$discussion->discussion
]->replies
;
5450 $discussion->lastpostid
= $replies[$discussion->discussion
]->lastpostid
;
5452 $discussion->replies
= 0;
5455 // SPECIAL CASE: The front page can display a news item post to non-logged in users.
5456 // All posts are read in this case.
5457 if (!$forumtracked) {
5458 $discussion->unread
= '-';
5459 } else if (empty($USER)) {
5460 $discussion->unread
= 0;
5462 if (empty($unreads[$discussion->discussion
])) {
5463 $discussion->unread
= 0;
5465 $discussion->unread
= $unreads[$discussion->discussion
];
5470 $ownpost = ($discussion->userid
== $USER->id
);
5474 // Use discussion name instead of subject of first post
5475 $discussion->subject
= $discussion->name
;
5477 switch ($displayformat) {
5479 if ($groupmode > 0) {
5480 if (isset($groups[$discussion->groupid
])) {
5481 $group = $groups[$discussion->groupid
];
5483 $group = $groups[$discussion->groupid
] = groups_get_group($discussion->groupid
);
5488 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
5489 $canviewparticipants, $context);
5494 if ($discussion->replies
) {
5497 $modcontext = context_module
::instance($cm->id
);
5498 $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
5501 $discussion->forum
= $forum->id
;
5503 forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
5504 '', null, true, $forumtracked);
5509 if ($displayformat == "header") {
5514 if ($olddiscussionlink) {
5515 if ($forum->type
== 'news') {
5516 $strolder = get_string('oldertopics', 'forum');
5518 $strolder = get_string('olderdiscussions', 'forum');
5520 echo '<div class="forumolddiscuss">';
5521 echo '<a href="'.$CFG->wwwroot
.'/mod/forum/view.php?f='.$forum->id
.'&showall=1">';
5522 echo $strolder.'</a> ...</div>';
5525 if ($page != -1) { ///Show the paging bar
5526 echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
5532 * Prints a forum discussion
5534 * @uses CONTEXT_MODULE
5535 * @uses FORUM_MODE_FLATNEWEST
5536 * @uses FORUM_MODE_FLATOLDEST
5537 * @uses FORUM_MODE_THREADED
5538 * @uses FORUM_MODE_NESTED
5539 * @param stdClass $course
5540 * @param stdClass $cm
5541 * @param stdClass $forum
5542 * @param stdClass $discussion
5543 * @param stdClass $post
5545 * @param mixed $canreply
5546 * @param bool $canrate
5548 function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
5551 require_once($CFG->dirroot
.'/rating/lib.php');
5553 $ownpost = (isloggedin() && $USER->id
== $post->userid
);
5555 $modcontext = context_module
::instance($cm->id
);
5556 if ($canreply === NULL) {
5557 $reply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
5562 // $cm holds general cache for forum functions
5563 $cm->cache
= new stdClass
;
5564 $cm->cache
->groups
= groups_get_all_groups($course->id
, 0, $cm->groupingid
);
5565 $cm->cache
->usersgroups
= array();
5569 // preload all posts - TODO: improve...
5570 if ($mode == FORUM_MODE_FLATNEWEST
) {
5571 $sort = "p.created DESC";
5573 $sort = "p.created ASC";
5576 $forumtracked = forum_tp_is_tracked($forum);
5577 $posts = forum_get_all_discussion_posts($discussion->id
, $sort, $forumtracked);
5578 $post = $posts[$post->id
];
5580 foreach ($posts as $pid=>$p) {
5581 $posters[$p->userid
] = $p->userid
;
5584 // preload all groups of ppl that posted in this discussion
5585 if ($postersgroups = groups_get_all_groups($course->id
, $posters, $cm->groupingid
, 'gm.id, gm.groupid, gm.userid')) {
5586 foreach($postersgroups as $pg) {
5587 if (!isset($cm->cache
->usersgroups
[$pg->userid
])) {
5588 $cm->cache
->usersgroups
[$pg->userid
] = array();
5590 $cm->cache
->usersgroups
[$pg->userid
][$pg->groupid
] = $pg->groupid
;
5592 unset($postersgroups);
5596 if ($forum->assessed
!= RATING_AGGREGATE_NONE
) {
5597 $ratingoptions = new stdClass
;
5598 $ratingoptions->context
= $modcontext;
5599 $ratingoptions->component
= 'mod_forum';
5600 $ratingoptions->ratingarea
= 'post';
5601 $ratingoptions->items
= $posts;
5602 $ratingoptions->aggregate
= $forum->assessed
;//the aggregation method
5603 $ratingoptions->scaleid
= $forum->scale
;
5604 $ratingoptions->userid
= $USER->id
;
5605 if ($forum->type
== 'single' or !$discussion->id
) {
5606 $ratingoptions->returnurl
= "$CFG->wwwroot/mod/forum/view.php?id=$cm->id";
5608 $ratingoptions->returnurl
= "$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id";
5610 $ratingoptions->assesstimestart
= $forum->assesstimestart
;
5611 $ratingoptions->assesstimefinish
= $forum->assesstimefinish
;
5613 $rm = new rating_manager();
5614 $posts = $rm->get_ratings($ratingoptions);
5618 $post->forum
= $forum->id
; // Add the forum id to the post object, later used by forum_print_post
5619 $post->forumtype
= $forum->type
;
5621 $post->subject
= format_string($post->subject
);
5623 $postread = !empty($post->postread
);
5625 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false,
5626 '', '', $postread, true, $forumtracked);
5629 case FORUM_MODE_FLATOLDEST
:
5630 case FORUM_MODE_FLATNEWEST
:
5632 forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts);
5635 case FORUM_MODE_THREADED
:
5636 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $reply, $forumtracked, $posts);
5639 case FORUM_MODE_NESTED
:
5640 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5649 * @uses FORUM_MODE_FLATNEWEST
5650 * @param object $course
5652 * @param object $forum
5653 * @param object $discussion
5654 * @param object $post
5655 * @param object $mode
5656 * @param bool $reply
5657 * @param bool $forumtracked
5658 * @param array $posts
5661 function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $reply, $forumtracked, $posts) {
5666 if ($mode == FORUM_MODE_FLATNEWEST
) {
5667 $sort = "ORDER BY created DESC";
5669 $sort = "ORDER BY created ASC";
5672 foreach ($posts as $post) {
5673 if (!$post->parent
) {
5676 $post->subject
= format_string($post->subject
);
5677 $ownpost = ($USER->id
== $post->userid
);
5679 $postread = !empty($post->postread
);
5681 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5682 '', '', $postread, true, $forumtracked);
5687 * @todo Document this function
5691 * @uses CONTEXT_MODULE
5694 function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $reply, $forumtracked, $posts) {
5699 if (!empty($posts[$parent->id
]->children
)) {
5700 $posts = $posts[$parent->id
]->children
;
5702 $modcontext = context_module
::instance($cm->id
);
5703 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
5705 foreach ($posts as $post) {
5707 echo '<div class="indent">';
5709 $ownpost = ($USER->id
== $post->userid
);
5710 $post->subject
= format_string($post->subject
);
5712 $postread = !empty($post->postread
);
5714 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5715 '', '', $postread, true, $forumtracked);
5717 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
5721 $by = new stdClass();
5722 $by->name
= fullname($post, $canviewfullnames);
5723 $by->date
= userdate($post->modified
);
5725 if ($forumtracked) {
5726 if (!empty($post->postread
)) {
5727 $style = '<span class="forumthread read">';
5729 $style = '<span class="forumthread unread">';
5732 $style = '<span class="forumthread">';
5734 echo $style."<a name=\"$post->id\"></a>".
5735 "<a href=\"discuss.php?d=$post->discussion&parent=$post->id\">".format_string($post->subject
,true)."</a> ";
5736 print_string("bynameondate", "forum", $by);
5740 forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $reply, $forumtracked, $posts);
5747 * @todo Document this function
5752 function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $reply, $forumtracked, $posts) {
5757 if (!empty($posts[$parent->id
]->children
)) {
5758 $posts = $posts[$parent->id
]->children
;
5760 foreach ($posts as $post) {
5762 echo '<div class="indent">';
5763 if (!isloggedin()) {
5766 $ownpost = ($USER->id
== $post->userid
);
5769 $post->subject
= format_string($post->subject
);
5770 $postread = !empty($post->postread
);
5772 forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link,
5773 '', '', $postread, true, $forumtracked);
5774 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $reply, $forumtracked, $posts);
5781 * Returns all forum posts since a given time in specified forum.
5783 * @todo Document this functions args
5789 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
5790 global $CFG, $COURSE, $USER, $DB;
5792 if ($COURSE->id
== $courseid) {
5795 $course = $DB->get_record('course', array('id' => $courseid));
5798 $modinfo = get_fast_modinfo($course);
5800 $cm = $modinfo->cms
[$cmid];
5801 $params = array($timestart, $cm->instance
);
5804 $userselect = "AND u.id = ?";
5805 $params[] = $userid;
5811 $groupselect = "AND d.groupid = ?";
5812 $params[] = $groupid;
5817 $allnames = get_all_user_name_fields(true, 'u');
5818 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
5819 d.timestart, d.timeend, d.userid AS duserid,
5820 $allnames, u.email, u.picture, u.imagealt, u.email
5821 FROM {forum_posts} p
5822 JOIN {forum_discussions} d ON d.id = p.discussion
5823 JOIN {forum} f ON f.id = d.forum
5824 JOIN {user} u ON u.id = p.userid
5825 WHERE p.created > ? AND f.id = ?
5826 $userselect $groupselect
5827 ORDER BY p.id ASC", $params)) { // order by initial posting date
5831 $groupmode = groups_get_activity_groupmode($cm, $course);
5832 $cm_context = context_module
::instance($cm->id
);
5833 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
5834 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
5836 $printposts = array();
5837 foreach ($posts as $post) {
5839 if (!empty($CFG->forum_enabletimedposts
) and $USER->id
!= $post->duserid
5840 and (($post->timestart
> 0 and $post->timestart
> time()) or ($post->timeend
> 0 and $post->timeend
< time()))) {
5841 if (!$viewhiddentimed) {
5847 if ($post->groupid
== -1 or $groupmode == VISIBLEGROUPS
or $accessallgroups) {
5848 // oki (Open discussions have groupid -1)
5851 if (isguestuser()) {
5856 if (!in_array($post->groupid
, $modinfo->get_groups($cm->groupingid
))) {
5862 $printposts[] = $post;
5869 $aname = format_string($cm->name
,true);
5871 foreach ($printposts as $post) {
5872 $tmpactivity = new stdClass();
5874 $tmpactivity->type
= 'forum';
5875 $tmpactivity->cmid
= $cm->id
;
5876 $tmpactivity->name
= $aname;
5877 $tmpactivity->sectionnum
= $cm->sectionnum
;
5878 $tmpactivity->timestamp
= $post->modified
;
5880 $tmpactivity->content
= new stdClass();
5881 $tmpactivity->content
->id
= $post->id
;
5882 $tmpactivity->content
->discussion
= $post->discussion
;
5883 $tmpactivity->content
->subject
= format_string($post->subject
);
5884 $tmpactivity->content
->parent
= $post->parent
;
5886 $tmpactivity->user
= new stdClass();
5887 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
5888 $additionalfields = explode(',', user_picture
::fields());
5889 $tmpactivity->user
= username_load_fields_from_object($tmpactivity->user
, $post, null, $additionalfields);
5890 $tmpactivity->user
->id
= $post->userid
;
5892 $activities[$index++
] = $tmpactivity;
5899 * @todo Document this function
5902 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
5903 global $CFG, $OUTPUT;
5905 if ($activity->content
->parent
) {
5908 $class = 'discussion';
5911 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
5913 echo "<tr><td class=\"userpicture\" valign=\"top\">";
5914 echo $OUTPUT->user_picture($activity->user
, array('courseid'=>$courseid));
5915 echo "</td><td class=\"$class\">";
5917 if ($activity->content
->parent
) {
5920 // Bold the title of new discussions so they stand out.
5921 $class = 'title bold';
5923 echo "<div class=\"{$class}\">";
5925 $aname = s($activity->name
);
5926 echo "<img src=\"" . $OUTPUT->pix_url('icon', $activity->type
) . "\" ".
5927 "class=\"icon\" alt=\"{$aname}\" />";
5929 echo "<a href=\"$CFG->wwwroot/mod/forum/discuss.php?d={$activity->content->discussion}"
5930 ."#p{$activity->content->id}\">{$activity->content->subject}</a>";
5933 echo '<div class="user">';
5934 $fullname = fullname($activity->user
, $viewfullnames);
5935 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&course=$courseid\">"
5936 ."{$fullname}</a> - ".userdate($activity->timestamp
);
5938 echo "</td></tr></table>";
5944 * recursively sets the discussion field to $discussionid on $postid and all its children
5945 * used when pruning a post
5948 * @param int $postid
5949 * @param int $discussionid
5952 function forum_change_discussionid($postid, $discussionid) {
5954 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid));
5955 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) {
5956 foreach ($posts as $post) {
5957 forum_change_discussionid($post->id
, $discussionid);
5964 * Prints the editing button on subscribers page
5968 * @param int $courseid
5969 * @param int $forumid
5972 function forum_update_subscriptions_button($courseid, $forumid) {
5975 if (!empty($USER->subscriptionsediting
)) {
5976 $string = get_string('turneditingoff');
5979 $string = get_string('turneditingon');
5983 return "<form method=\"get\" action=\"$CFG->wwwroot/mod/forum/subscribers.php\">".
5984 "<input type=\"hidden\" name=\"id\" value=\"$forumid\" />".
5985 "<input type=\"hidden\" name=\"edit\" value=\"$edit\" />".
5986 "<input type=\"submit\" value=\"$string\" /></form>";
5989 // Functions to do with read tracking.
5992 * Mark posts as read.
5996 * @param object $user object
5997 * @param array $postids array of post ids
5998 * @return boolean success
6000 function forum_tp_mark_posts_read($user, $postids) {
6003 if (!forum_tp_can_track_forums(false, $user)) {
6010 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
6012 if (empty($postids)) {
6015 } else if (count($postids) > 200) {
6016 while ($part = array_splice($postids, 0, 200)) {
6017 $status = forum_tp_mark_posts_read($user, $part) && $status;
6022 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED
, 'postid');
6024 $insertparams = array(
6025 'userid1' => $user->id
,
6026 'userid2' => $user->id
,
6027 'userid3' => $user->id
,
6028 'firstread' => $now,
6030 'cutoffdate' => $cutoffdate,
6032 $params = array_merge($postidparams, $insertparams);
6034 if ($CFG->forum_allowforcedreadtracking
) {
6035 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
6036 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL))";
6038 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6039 AND tf.id IS NULL)";
6042 // First insert any new entries.
6043 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6045 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread
6046 FROM {forum_posts} p
6047 JOIN {forum_discussions} d ON d.id = p.discussion
6048 JOIN {forum} f ON f.id = d.forum
6049 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id)
6050 LEFT JOIN {forum_read} fr ON (
6051 fr.userid = :userid3
6052 AND fr.postid = p.id
6053 AND fr.discussionid = d.id
6054 AND fr.forumid = f.id
6057 AND p.modified >= :cutoffdate
6061 $status = $DB->execute($sql, $params) && $status;
6063 // Then update all records.
6064 $updateparams = array(
6065 'userid' => $user->id
,
6068 $params = array_merge($postidparams, $updateparams);
6069 $status = $DB->set_field_select('forum_read', 'lastread', $now, '
6071 AND lastread <> :lastread
6072 AND postid ' . $usql,
6073 $params) && $status;
6079 * Mark post as read.
6082 * @param int $userid
6083 * @param int $postid
6085 function forum_tp_add_read_record($userid, $postid) {
6089 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 3600);
6091 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) {
6092 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread)
6094 SELECT ?, p.id, p.discussion, d.forum, ?, ?
6095 FROM {forum_posts} p
6096 JOIN {forum_discussions} d ON d.id = p.discussion
6097 WHERE p.id = ? AND p.modified >= ?";
6098 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate));
6101 $sql = "UPDATE {forum_read}
6103 WHERE userid = ? AND postid = ?";
6104 return $DB->execute($sql, array($now, $userid, $userid));
6109 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later.
6113 function forum_tp_mark_post_read($userid, $post, $forumid) {
6114 if (!forum_tp_is_post_old($post)) {
6115 return forum_tp_add_read_record($userid, $post->id
);
6122 * Marks a whole forum as read, for a given user
6126 * @param object $user
6127 * @param int $forumid
6128 * @param int|bool $groupid
6131 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) {
6134 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6137 $params = array($user->id
, $forumid, $cutoffdate);
6139 if ($groupid !== false) {
6140 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)";
6141 $params[] = $groupid;
6145 FROM {forum_posts} p
6146 LEFT JOIN {forum_discussions} d ON d.id = p.discussion
6147 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6149 AND p.modified >= ? AND r.id is NULL
6152 if ($posts = $DB->get_records_sql($sql, $params)) {
6153 $postids = array_keys($posts);
6154 return forum_tp_mark_posts_read($user, $postids);
6161 * Marks a whole discussion as read, for a given user
6165 * @param object $user
6166 * @param int $discussionid
6169 function forum_tp_mark_discussion_read($user, $discussionid) {
6172 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6175 FROM {forum_posts} p
6176 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6177 WHERE p.discussion = ?
6178 AND p.modified >= ? AND r.id is NULL";
6180 if ($posts = $DB->get_records_sql($sql, array($user->id
, $discussionid, $cutoffdate))) {
6181 $postids = array_keys($posts);
6182 return forum_tp_mark_posts_read($user, $postids);
6190 * @param int $userid
6191 * @param object $post
6193 function forum_tp_is_post_read($userid, $post) {
6195 return (forum_tp_is_post_old($post) ||
6196 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id
)));
6201 * @param object $post
6202 * @param int $time Defautls to time()
6204 function forum_tp_is_post_old($post, $time=null) {
6207 if (is_null($time)) {
6210 return ($post->modified
< ($time - ($CFG->forum_oldpostdays
* 24 * 3600)));
6214 * Returns the count of records for the provided user and course.
6215 * Please note that group access is ignored!
6219 * @param int $userid
6220 * @param int $courseid
6223 function forum_tp_get_course_unread_posts($userid, $courseid) {
6226 $now = round(time(), -2); // DB cache friendliness.
6227 $cutoffdate = $now - ($CFG->forum_oldpostdays
* 24 * 60 * 60);
6228 $params = array($userid, $userid, $courseid, $cutoffdate, $userid);
6230 if (!empty($CFG->forum_enabletimedposts
)) {
6231 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6238 if ($CFG->forum_allowforcedreadtracking
) {
6239 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED
."
6240 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND tf.id IS NULL
6241 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))";
6243 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6245 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)";
6248 $sql = "SELECT f.id, COUNT(p.id) AS unread
6249 FROM {forum_posts} p
6250 JOIN {forum_discussions} d ON d.id = p.discussion
6251 JOIN {forum} f ON f.id = d.forum
6252 JOIN {course} c ON c.id = f.course
6253 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6254 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id)
6256 AND p.modified >= ? AND r.id is NULL
6261 if ($return = $DB->get_records_sql($sql, $params)) {
6269 * Returns the count of records for the provided user and forum and [optionally] group.
6275 * @param object $course
6278 function forum_tp_count_forum_unread_posts($cm, $course) {
6279 global $CFG, $USER, $DB;
6281 static $readcache = array();
6283 $forumid = $cm->instance
;
6285 if (!isset($readcache[$course->id
])) {
6286 $readcache[$course->id
] = array();
6287 if ($counts = forum_tp_get_course_unread_posts($USER->id
, $course->id
)) {
6288 foreach ($counts as $count) {
6289 $readcache[$course->id
][$count->id
] = $count->unread
;
6294 if (empty($readcache[$course->id
][$forumid])) {
6295 // no need to check group mode ;-)
6299 $groupmode = groups_get_activity_groupmode($cm, $course);
6301 if ($groupmode != SEPARATEGROUPS
) {
6302 return $readcache[$course->id
][$forumid];
6305 if (has_capability('moodle/site:accessallgroups', context_module
::instance($cm->id
))) {
6306 return $readcache[$course->id
][$forumid];
6309 require_once($CFG->dirroot
.'/course/lib.php');
6311 $modinfo = get_fast_modinfo($course);
6313 $mygroups = $modinfo->get_groups($cm->groupingid
);
6315 // add all groups posts
6318 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups);
6320 $now = round(time(), -2); // db cache friendliness
6321 $cutoffdate = $now - ($CFG->forum_oldpostdays
*24*60*60);
6322 $params = array($USER->id
, $forumid, $cutoffdate);
6324 if (!empty($CFG->forum_enabletimedposts
)) {
6325 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
6332 $params = array_merge($params, $groups_params);
6334 $sql = "SELECT COUNT(p.id)
6335 FROM {forum_posts} p
6336 JOIN {forum_discussions} d ON p.discussion = d.id
6337 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?)
6339 AND p.modified >= ? AND r.id is NULL
6341 AND d.groupid $groups_sql";
6343 return $DB->get_field_sql($sql, $params);
6347 * Deletes read records for the specified index. At least one parameter must be specified.
6350 * @param int $userid
6351 * @param int $postid
6352 * @param int $discussionid
6353 * @param int $forumid
6356 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) {
6362 if ($select != '') $select .= ' AND ';
6363 $select .= 'userid = ?';
6364 $params[] = $userid;
6367 if ($select != '') $select .= ' AND ';
6368 $select .= 'postid = ?';
6369 $params[] = $postid;
6371 if ($discussionid > -1) {
6372 if ($select != '') $select .= ' AND ';
6373 $select .= 'discussionid = ?';
6374 $params[] = $discussionid;
6376 if ($forumid > -1) {
6377 if ($select != '') $select .= ' AND ';
6378 $select .= 'forumid = ?';
6379 $params[] = $forumid;
6381 if ($select == '') {
6385 return $DB->delete_records_select('forum_read', $select, $params);
6389 * Get a list of forums not tracked by the user.
6393 * @param int $userid The id of the user to use.
6394 * @param int $courseid The id of the course being checked.
6395 * @return mixed An array indexed by forum id, or false.
6397 function forum_tp_get_untracked_forums($userid, $courseid) {
6400 if ($CFG->forum_allowforcedreadtracking
) {
6401 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
6402 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." AND (ft.id IS NOT NULL
6403 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6405 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF
."
6406 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL
." OR f.trackingtype = ".FORUM_TRACKING_FORCED
.")
6407 AND (ft.id IS NOT NULL
6408 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))";
6413 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?)
6417 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) {
6418 foreach ($forums as $forum) {
6419 $forums[$forum->id
] = $forum;
6429 * Determine if a user can track forums and optionally a particular forum.
6430 * Checks the site settings, the user settings and the forum settings (if
6436 * @param mixed $forum The forum object to test, or the int id (optional).
6437 * @param mixed $userid The user object to check for (optional).
6440 function forum_tp_can_track_forums($forum=false, $user=false) {
6441 global $USER, $CFG, $DB;
6443 // if possible, avoid expensive
6445 if (empty($CFG->forum_trackreadposts
)) {
6449 if ($user === false) {
6453 if (isguestuser($user) or empty($user->id
)) {
6457 if ($forum === false) {
6458 if ($CFG->forum_allowforcedreadtracking
) {
6459 // Since we can force tracking, assume yes without a specific forum.
6462 return (bool)$user->trackforums
;
6466 // Work toward always passing an object...
6467 if (is_numeric($forum)) {
6468 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
6469 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype');
6472 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
6473 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
6475 if ($CFG->forum_allowforcedreadtracking
) {
6476 // If we allow forcing, then forced forums takes procidence over user setting.
6477 return ($forumforced ||
($forumallows && (!empty($user->trackforums
) && (bool)$user->trackforums
)));
6479 // If we don't allow forcing, user setting trumps.
6480 return ($forumforced ||
$forumallows) && !empty($user->trackforums
);
6485 * Tells whether a specific forum is tracked by the user. A user can optionally
6486 * be specified. If not specified, the current user is assumed.
6491 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object
6492 * @param int $userid The id of the user being checked (optional).
6495 function forum_tp_is_tracked($forum, $user=false) {
6496 global $USER, $CFG, $DB;
6498 if ($user === false) {
6502 if (isguestuser($user) or empty($user->id
)) {
6506 // Work toward always passing an object...
6507 if (is_numeric($forum)) {
6508 debugging('Better use proper forum object.', DEBUG_DEVELOPER
);
6509 $forum = $DB->get_record('forum', array('id' => $forum));
6512 if (!forum_tp_can_track_forums($forum, $user)) {
6516 $forumallows = ($forum->trackingtype
== FORUM_TRACKING_OPTIONAL
);
6517 $forumforced = ($forum->trackingtype
== FORUM_TRACKING_FORCED
);
6518 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id
, 'forumid' => $forum->id
));
6520 if ($CFG->forum_allowforcedreadtracking
) {
6521 return $forumforced ||
($forumallows && $userpref === false);
6523 return ($forumallows ||
$forumforced) && $userpref === false;
6530 * @param int $forumid
6531 * @param int $userid
6533 function forum_tp_start_tracking($forumid, $userid=false) {
6536 if ($userid === false) {
6537 $userid = $USER->id
;
6540 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid));
6546 * @param int $forumid
6547 * @param int $userid
6549 function forum_tp_stop_tracking($forumid, $userid=false) {
6552 if ($userid === false) {
6553 $userid = $USER->id
;
6556 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) {
6557 $track_prefs = new stdClass();
6558 $track_prefs->userid
= $userid;
6559 $track_prefs->forumid
= $forumid;
6560 $DB->insert_record('forum_track_prefs', $track_prefs);
6563 return forum_tp_delete_read_records($userid, -1, -1, $forumid);
6568 * Clean old records from the forum_read table.
6573 function forum_tp_clean_read_records() {
6576 if (!isset($CFG->forum_oldpostdays
)) {
6579 // Look for records older than the cutoffdate that are still in the forum_read table.
6580 $cutoffdate = time() - ($CFG->forum_oldpostdays
*24*60*60);
6582 //first get the oldest tracking present - we need tis to speedup the next delete query
6583 $sql = "SELECT MIN(fp.modified) AS first
6584 FROM {forum_posts} fp
6585 JOIN {forum_read} fr ON fr.postid=fp.id";
6586 if (!$first = $DB->get_field_sql($sql)) {
6587 // nothing to delete;
6591 // now delete old tracking info
6594 WHERE postid IN (SELECT fp.id
6595 FROM {forum_posts} fp
6596 WHERE fp.modified >= ? AND fp.modified < ?)";
6597 $DB->execute($sql, array($first, $cutoffdate));
6601 * Sets the last post for a given discussion
6605 * @param into $discussionid
6608 function forum_discussion_update_last_post($discussionid) {
6611 // Check the given discussion exists
6612 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) {
6616 // Use SQL to find the last post for this discussion
6617 $sql = "SELECT id, userid, modified
6620 ORDER BY modified DESC";
6622 // Lets go find the last post
6623 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) {
6624 $lastpost = reset($lastposts);
6625 $discussionobject = new stdClass();
6626 $discussionobject->id
= $discussionid;
6627 $discussionobject->usermodified
= $lastpost->userid
;
6628 $discussionobject->timemodified
= $lastpost->modified
;
6629 $DB->update_record('forum_discussions', $discussionobject);
6630 return $lastpost->id
;
6633 // To get here either we couldn't find a post for the discussion (weird)
6634 // or we couldn't update the discussion record (weird x2)
6640 * List the actions that correspond to a view of this module.
6641 * This is used by the participation report.
6643 * Note: This is not used by new logging system. Event with
6644 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
6645 * be considered as view action.
6649 function forum_get_view_actions() {
6650 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum');
6654 * List the actions that correspond to a post of this module.
6655 * This is used by the participation report.
6657 * Note: This is not used by new logging system. Event with
6658 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
6659 * will be considered as post action.
6663 function forum_get_post_actions() {
6664 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post');
6668 * Returns a warning object if a user has reached the number of posts equal to
6669 * the warning/blocking setting, or false if there is no warning to show.
6671 * @param int|stdClass $forum the forum id or the forum object
6672 * @param stdClass $cm the course module
6673 * @return stdClass|bool returns an object with the warning information, else
6674 * returns false if no warning is required.
6676 function forum_check_throttling($forum, $cm = null) {
6677 global $CFG, $DB, $USER;
6679 if (is_numeric($forum)) {
6680 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST
);
6683 if (!is_object($forum)) {
6684 return false; // This is broken.
6688 $cm = get_coursemodule_from_instance('forum', $forum->id
, $forum->course
, false, MUST_EXIST
);
6691 if (empty($forum->blockafter
)) {
6695 if (empty($forum->blockperiod
)) {
6699 $modcontext = context_module
::instance($cm->id
);
6700 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) {
6704 // Get the number of posts in the last period we care about.
6706 $timeafter = $timenow - $forum->blockperiod
;
6707 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p
6708 JOIN {forum_discussions} d
6709 ON p.discussion = d.id WHERE d.forum = ?
6710 AND p.userid = ? AND p.created > ?', array($forum->id
, $USER->id
, $timeafter));
6712 $a = new stdClass();
6713 $a->blockafter
= $forum->blockafter
;
6714 $a->numposts
= $numposts;
6715 $a->blockperiod
= get_string('secondstotime'.$forum->blockperiod
);
6717 if ($forum->blockafter
<= $numposts) {
6718 $warning = new stdClass();
6719 $warning->canpost
= false;
6720 $warning->errorcode
= 'forumblockingtoomanyposts';
6721 $warning->module
= 'error';
6722 $warning->additional
= $a;
6723 $warning->link
= $CFG->wwwroot
. '/mod/forum/view.php?f=' . $forum->id
;
6728 if ($forum->warnafter
<= $numposts) {
6729 $warning = new stdClass();
6730 $warning->canpost
= true;
6731 $warning->errorcode
= 'forumblockingalmosttoomanyposts';
6732 $warning->module
= 'forum';
6733 $warning->additional
= $a;
6734 $warning->link
= null;
6741 * Throws an error if the user is no longer allowed to post due to having reached
6742 * or exceeded the number of posts specified in 'Post threshold for blocking'
6746 * @param stdClass $thresholdwarning the warning information returned
6747 * from the function forum_check_throttling.
6749 function forum_check_blocking_threshold($thresholdwarning) {
6750 if (!empty($thresholdwarning) && !$thresholdwarning->canpost
) {
6751 print_error($thresholdwarning->errorcode
,
6752 $thresholdwarning->module
,
6753 $thresholdwarning->link
,
6754 $thresholdwarning->additional
);
6760 * Removes all grades from gradebook
6764 * @param int $courseid
6765 * @param string $type optional
6767 function forum_reset_gradebook($courseid, $type='') {
6771 $params = array($courseid);
6773 $wheresql = "AND f.type=?";
6777 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid
6778 FROM {forum} f, {course_modules} cm, {modules} m
6779 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql";
6781 if ($forums = $DB->get_records_sql($sql, $params)) {
6782 foreach ($forums as $forum) {
6783 forum_grade_item_update($forum, 'reset');
6789 * This function is used by the reset_course_userdata function in moodlelib.
6790 * This function will remove all posts from the specified forum
6791 * and clean up any related data.
6795 * @param $data the data submitted from the reset course.
6796 * @return array status array
6798 function forum_reset_userdata($data) {
6800 require_once($CFG->dirroot
.'/rating/lib.php');
6802 $componentstr = get_string('modulenameplural', 'forum');
6805 $params = array($data->courseid
);
6807 $removeposts = false;
6809 if (!empty($data->reset_forum_all
)) {
6810 $removeposts = true;
6811 $typesstr = get_string('resetforumsall', 'forum');
6813 } else if (!empty($data->reset_forum_types
)){
6814 $removeposts = true;
6817 $forum_types_all = forum_get_forum_types_all();
6818 foreach ($data->reset_forum_types
as $type) {
6819 if (!array_key_exists($type, $forum_types_all)) {
6822 $typesql .= " AND f.type=?";
6823 $types[] = $forum_types_all[$type];
6826 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
6828 $alldiscussionssql = "SELECT fd.id
6829 FROM {forum_discussions} fd, {forum} f
6830 WHERE f.course=? AND f.id=fd.forum";
6832 $allforumssql = "SELECT f.id
6836 $allpostssql = "SELECT fp.id
6837 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f
6838 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion";
6840 $forumssql = $forums = $rm = null;
6842 if( $removeposts ||
!empty($data->reset_forum_ratings
) ) {
6843 $forumssql = "$allforumssql $typesql";
6844 $forums = $forums = $DB->get_records_sql($forumssql, $params);
6845 $rm = new rating_manager();
6846 $ratingdeloptions = new stdClass
;
6847 $ratingdeloptions->component
= 'mod_forum';
6848 $ratingdeloptions->ratingarea
= 'post';
6852 $discussionssql = "$alldiscussionssql $typesql";
6853 $postssql = "$allpostssql $typesql";
6855 // now get rid of all attachments
6856 $fs = get_file_storage();
6858 foreach ($forums as $forumid=>$unused) {
6859 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
6862 $context = context_module
::instance($cm->id
);
6863 $fs->delete_area_files($context->id
, 'mod_forum', 'attachment');
6864 $fs->delete_area_files($context->id
, 'mod_forum', 'post');
6867 $ratingdeloptions->contextid
= $context->id
;
6868 $rm->delete_ratings($ratingdeloptions);
6872 // first delete all read flags
6873 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params);
6875 // remove tracking prefs
6876 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params);
6878 // remove posts from queue
6879 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params);
6881 // all posts - initial posts must be kept in single simple discussion forums
6882 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children
6883 $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
6885 // finally all discussions except single simple forums
6886 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params);
6888 // remove all grades from gradebook
6889 if (empty($data->reset_gradebook_grades
)) {
6890 if (empty($types)) {
6891 forum_reset_gradebook($data->courseid
);
6893 foreach ($types as $type) {
6894 forum_reset_gradebook($data->courseid
, $type);
6899 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false);
6902 // remove all ratings in this course's forums
6903 if (!empty($data->reset_forum_ratings
)) {
6905 foreach ($forums as $forumid=>$unused) {
6906 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
6909 $context = context_module
::instance($cm->id
);
6912 $ratingdeloptions->contextid
= $context->id
;
6913 $rm->delete_ratings($ratingdeloptions);
6917 // remove all grades from gradebook
6918 if (empty($data->reset_gradebook_grades
)) {
6919 forum_reset_gradebook($data->courseid
);
6923 // remove all digest settings unconditionally - even for users still enrolled in course.
6924 if (!empty($data->reset_forum_digests
)) {
6925 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params);
6926 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false);
6929 // remove all subscriptions unconditionally - even for users still enrolled in course
6930 if (!empty($data->reset_forum_subscriptions
)) {
6931 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params);
6932 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params);
6933 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false);
6936 // remove all tracking prefs unconditionally - even for users still enrolled in course
6937 if (!empty($data->reset_forum_track_prefs
)) {
6938 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params);
6939 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false);
6942 /// updating dates - shift may be negative too
6943 if ($data->timeshift
) {
6944 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift
, $data->courseid
);
6945 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
6952 * Called by course/reset.php
6954 * @param $mform form passed by reference
6956 function forum_reset_course_form_definition(&$mform) {
6957 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
6959 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
6961 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
6962 $mform->setAdvanced('reset_forum_types');
6963 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
6965 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum'));
6966 $mform->setAdvanced('reset_forum_digests');
6968 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum'));
6969 $mform->setAdvanced('reset_forum_subscriptions');
6971 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum'));
6972 $mform->setAdvanced('reset_forum_track_prefs');
6973 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked');
6975 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings'));
6976 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked');
6980 * Course reset form defaults.
6983 function forum_reset_course_form_defaults($course) {
6984 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1);
6988 * Returns array of forum layout modes
6992 function forum_get_layout_modes() {
6993 return array (FORUM_MODE_FLATOLDEST
=> get_string('modeflatoldestfirst', 'forum'),
6994 FORUM_MODE_FLATNEWEST
=> get_string('modeflatnewestfirst', 'forum'),
6995 FORUM_MODE_THREADED
=> get_string('modethreaded', 'forum'),
6996 FORUM_MODE_NESTED
=> get_string('modenested', 'forum'));
7000 * Returns array of forum types chooseable on the forum editing form
7004 function forum_get_forum_types() {
7005 return array ('general' => get_string('generalforum', 'forum'),
7006 'eachuser' => get_string('eachuserforum', 'forum'),
7007 'single' => get_string('singleforum', 'forum'),
7008 'qanda' => get_string('qandaforum', 'forum'),
7009 'blog' => get_string('blogforum', 'forum'));
7013 * Returns array of all forum layout modes
7017 function forum_get_forum_types_all() {
7018 return array ('news' => get_string('namenews','forum'),
7019 'social' => get_string('namesocial','forum'),
7020 'general' => get_string('generalforum', 'forum'),
7021 'eachuser' => get_string('eachuserforum', 'forum'),
7022 'single' => get_string('singleforum', 'forum'),
7023 'qanda' => get_string('qandaforum', 'forum'),
7024 'blog' => get_string('blogforum', 'forum'));
7028 * Returns all other caps used in module
7032 function forum_get_extra_capabilities() {
7033 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/site:trustcontent', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate');
7037 * Adds module specific settings to the settings block
7039 * @param settings_navigation $settings The settings navigation object
7040 * @param navigation_node $forumnode The node to add module settings to
7042 function forum_extend_settings_navigation(settings_navigation
$settingsnav, navigation_node
$forumnode) {
7043 global $USER, $PAGE, $CFG, $DB, $OUTPUT;
7045 $forumobject = $DB->get_record("forum", array("id" => $PAGE->cm
->instance
));
7046 if (empty($PAGE->cm
->context
)) {
7047 $PAGE->cm
->context
= context_module
::instance($PAGE->cm
->instance
);
7050 $params = $PAGE->url
->params();
7051 if (!empty($params['d'])) {
7052 $discussionid = $params['d'];
7055 // for some actions you need to be enrolled, beiing admin is not enough sometimes here
7056 $enrolled = is_enrolled($PAGE->cm
->context
, $USER, '', false);
7057 $activeenrolled = is_enrolled($PAGE->cm
->context
, $USER, '', true);
7059 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm
->context
);
7060 $subscriptionmode = \mod_forum\subscriptions
::get_subscription_mode($forumobject);
7061 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions
::is_forcesubscribed($forumobject) &&
7062 (!\mod_forum\subscriptions
::subscription_disabled($forumobject) ||
$canmanage);
7065 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node
::TYPE_CONTAINER
);
7067 $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
);
7068 $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
);
7069 $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
);
7070 $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
);
7072 switch ($subscriptionmode) {
7073 case FORUM_CHOOSESUBSCRIBE
: // 0
7074 $allowchoice->action
= null;
7075 $allowchoice->add_class('activesetting');
7077 case FORUM_FORCESUBSCRIBE
: // 1
7078 $forceforever->action
= null;
7079 $forceforever->add_class('activesetting');
7081 case FORUM_INITIALSUBSCRIBE
: // 2
7082 $forceinitially->action
= null;
7083 $forceinitially->add_class('activesetting');
7085 case FORUM_DISALLOWSUBSCRIBE
: // 3
7086 $disallowchoice->action
= null;
7087 $disallowchoice->add_class('activesetting');
7091 } else if ($activeenrolled) {
7093 switch ($subscriptionmode) {
7094 case FORUM_CHOOSESUBSCRIBE
: // 0
7095 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum'));
7097 case FORUM_FORCESUBSCRIBE
: // 1
7098 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum'));
7100 case FORUM_INITIALSUBSCRIBE
: // 2
7101 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum'));
7103 case FORUM_DISALLOWSUBSCRIBE
: // 3
7104 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum'));
7109 if ($cansubscribe) {
7110 if (\mod_forum\subscriptions
::is_subscribed($USER->id
, $forumobject, null, $PAGE->cm
)) {
7111 $linktext = get_string('unsubscribe', 'forum');
7113 $linktext = get_string('subscribe', 'forum');
7115 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id
, 'sesskey'=>sesskey()));
7116 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7118 if (isset($discussionid)) {
7119 if (\mod_forum\subscriptions
::is_subscribed($USER->id
, $forumobject, $discussionid, $PAGE->cm
)) {
7120 $linktext = get_string('unsubscribediscussion', 'forum');
7122 $linktext = get_string('subscribediscussion', 'forum');
7124 $url = new moodle_url('/mod/forum/subscribe.php', array(
7125 'id' => $forumobject->id
,
7126 'sesskey' => sesskey(),
7127 'd' => $discussionid,
7128 'returnurl' => $PAGE->url
->out(),
7130 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7134 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm
->context
)){
7135 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id
));
7136 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node
::TYPE_SETTING
);
7139 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments
7140 if ($forumobject->trackingtype
== FORUM_TRACKING_OPTIONAL
7141 ||
((!$CFG->forum_allowforcedreadtracking
) && $forumobject->trackingtype
== FORUM_TRACKING_FORCED
)) {
7142 if (forum_tp_is_tracked($forumobject)) {
7143 $linktext = get_string('notrackforum', 'forum');
7145 $linktext = get_string('trackforum', 'forum');
7147 $url = new moodle_url('/mod/forum/settracking.php', array(
7148 'id' => $forumobject->id
,
7149 'sesskey' => sesskey(),
7151 $forumnode->add($linktext, $url, navigation_node
::TYPE_SETTING
);
7155 if (!isloggedin() && $PAGE->course
->id
== SITEID
) {
7156 $userid = guest_user()->id
;
7158 $userid = $USER->id
;
7161 $hascourseaccess = ($PAGE->course
->id
== SITEID
) ||
can_access_course($PAGE->course
, $userid);
7162 $enablerssfeeds = !empty($CFG->enablerssfeeds
) && !empty($CFG->forum_enablerssfeeds
);
7164 if ($enablerssfeeds && $forumobject->rsstype
&& $forumobject->rssarticles
&& $hascourseaccess) {
7166 if (!function_exists('rss_get_url')) {
7167 require_once("$CFG->libdir/rsslib.php");
7170 if ($forumobject->rsstype
== 1) {
7171 $string = get_string('rsssubscriberssdiscussions','forum');
7173 $string = get_string('rsssubscriberssposts','forum');
7176 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $userid, "mod_forum", $forumobject->id
));
7177 $forumnode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
7182 * Adds information about unread messages, that is only required for the course view page (and
7183 * similar), to the course-module object.
7184 * @param cm_info $cm Course-module object
7186 function forum_cm_info_view(cm_info
$cm) {
7189 if (forum_tp_can_track_forums()) {
7190 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) {
7191 $out = '<span class="unread"> <a href="' . $cm->url
. '">';
7193 $out .= get_string('unreadpostsone', 'forum');
7195 $out .= get_string('unreadpostsnumber', 'forum', $unread);
7197 $out .= '</a></span>';
7198 $cm->set_after_link($out);
7204 * Return a list of page types
7205 * @param string $pagetype current page type
7206 * @param stdClass $parentcontext Block's parent context
7207 * @param stdClass $currentcontext Current context of block
7209 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) {
7210 $forum_pagetype = array(
7211 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'),
7212 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'),
7213 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum')
7215 return $forum_pagetype;
7219 * Gets all of the courses where the provided user has posted in a forum.
7221 * @global moodle_database $DB The database connection
7222 * @param stdClass $user The user who's posts we are looking for
7223 * @param bool $discussionsonly If true only look for discussions started by the user
7224 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded
7225 * @param int $limitfrom The offset of records to return
7226 * @param int $limitnum The number of records to return
7227 * @return array An array of courses
7229 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) {
7232 // If we are only after discussions we need only look at the forum_discussions
7233 // table and join to the userid there. If we are looking for posts then we need
7234 // to join to the forum_posts table.
7235 if (!$discussionsonly) {
7236 $subquery = "(SELECT DISTINCT fd.course
7237 FROM {forum_discussions} fd
7238 JOIN {forum_posts} fp ON fp.discussion = fd.id
7239 WHERE fp.userid = :userid )";
7241 $subquery= "(SELECT DISTINCT fd.course
7242 FROM {forum_discussions} fd
7243 WHERE fd.userid = :userid )";
7246 $params = array('userid' => $user->id
);
7248 // Join to the context table so that we can preload contexts if required.
7249 if ($includecontexts) {
7250 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
7251 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
7252 $params['contextlevel'] = CONTEXT_COURSE
;
7258 // Now we need to get all of the courses to search.
7259 // All courses where the user has posted within a forum will be returned.
7260 $sql = "SELECT c.* $ctxselect
7263 WHERE c.id IN ($subquery)";
7264 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7265 if ($includecontexts) {
7266 array_map('context_helper::preload_from_record', $courses);
7272 * Gets all of the forums a user has posted in for one or more courses.
7274 * @global moodle_database $DB
7275 * @param stdClass $user
7276 * @param array $courseids An array of courseids to search or if not provided
7277 * all courses the user has posted within
7278 * @param bool $discussionsonly If true then only forums where the user has started
7279 * a discussion will be returned.
7280 * @param int $limitfrom The offset of records to return
7281 * @param int $limitnum The number of records to return
7282 * @return array An array of forums the user has posted within in the provided courses
7284 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) {
7287 if (!is_null($courseids)) {
7288 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
, 'courseid');
7289 $coursewhere = ' AND f.course '.$coursewhere;
7294 $params['userid'] = $user->id
;
7295 $params['forum'] = 'forum';
7297 if ($discussionsonly) {
7298 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id';
7300 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id
7301 JOIN {forum_posts} ff ON ff.discussion = fd.id';
7304 $sql = "SELECT f.*, cm.id AS cmid
7306 JOIN {course_modules} cm ON cm.instance = f.id
7307 JOIN {modules} m ON m.id = cm.module
7312 WHERE ff.userid = :userid
7315 WHERE m.name = :forum
7318 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
7319 return $courseforums;
7323 * Returns posts made by the selected user in the requested courses.
7325 * This method can be used to return all of the posts made by the requested user
7326 * within the given courses.
7327 * For each course the access of the current user and requested user is checked
7328 * and then for each post access to the post and forum is checked as well.
7330 * This function is safe to use with usercapabilities.
7332 * @global moodle_database $DB
7333 * @param stdClass $user The user whose posts we want to get
7334 * @param array $courses The courses to search
7335 * @param bool $musthaveaccess If set to true errors will be thrown if the user
7336 * cannot access one or more of the courses to search
7337 * @param bool $discussionsonly If set to true only discussion starting posts
7339 * @param int $limitfrom The offset of records to return
7340 * @param int $limitnum The number of records to return
7341 * @return stdClass An object the following properties
7342 * ->totalcount: the total number of posts made by the requested user
7343 * that the current user can see.
7344 * ->courses: An array of courses the current user can see that the
7345 * requested user has posted in.
7346 * ->forums: An array of forums relating to the posts returned in the
7348 * ->posts: An array containing the posts to show for this request.
7350 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
7351 global $DB, $USER, $CFG;
7353 $return = new stdClass
;
7354 $return->totalcount
= 0; // The total number of posts that the current user is able to view
7355 $return->courses
= array(); // The courses the current user can access
7356 $return->forums
= array(); // The forums that the current user can access that contain posts
7357 $return->posts
= array(); // The posts to display
7359 // First up a small sanity check. If there are no courses to check we can
7360 // return immediately, there is obviously nothing to search.
7361 if (empty($courses)) {
7365 // A couple of quick setups
7366 $isloggedin = isloggedin();
7367 $isguestuser = $isloggedin && isguestuser();
7368 $iscurrentuser = $isloggedin && $USER->id
== $user->id
;
7370 // Checkout whether or not the current user has capabilities over the requested
7371 // user and if so they have the capabilities required to view the requested
7373 $usercontext = context_user
::instance($user->id
, MUST_EXIST
);
7374 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id
, 'contextid' => $usercontext->id
));
7375 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);
7377 // Before we actually search each course we need to check the user's access to the
7378 // course. If the user doesn't have the appropraite access then we either throw an
7379 // error if a particular course was requested or we just skip over the course.
7380 foreach ($courses as $course) {
7381 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
7382 if ($iscurrentuser ||
$hascapsonuser) {
7383 // If it is the current user, or the current user has capabilities to the
7384 // requested user then all we need to do is check the requested users
7385 // current access to the course.
7386 // Note: There is no need to check group access or anything of the like
7387 // as either the current user is the requested user, or has granted
7388 // capabilities on the requested user. Either way they can see what the
7389 // requested user posted, although its VERY unlikely in the `parent` situation
7390 // that the current user will be able to view the posts in context.
7391 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
7392 // Need to have full access to a course to see the rest of own info
7393 if ($musthaveaccess) {
7394 print_error('errorenrolmentrequired', 'forum');
7399 // Check whether the current user is enrolled or has access to view the course
7400 // if they don't we immediately have a problem.
7401 if (!can_access_course($course)) {
7402 if ($musthaveaccess) {
7403 print_error('errorenrolmentrequired', 'forum');
7408 // Check whether the requested user is enrolled or has access to view the course
7409 // if they don't we immediately have a problem.
7410 if (!can_access_course($course, $user)) {
7411 if ($musthaveaccess) {
7412 print_error('notenrolled', 'forum');
7417 // If groups are in use and enforced throughout the course then make sure
7418 // we can meet in at least one course level group.
7419 // Note that we check if either the current user or the requested user have
7420 // the capability to access all groups. This is because with that capability
7421 // a user in group A could post in the group B forum. Grrrr.
7422 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&& $course->groupmodeforce
7423 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id
)) {
7424 // If its the guest user to bad... the guest user cannot access groups
7425 if (!$isloggedin or $isguestuser) {
7426 // do not use require_login() here because we might have already used require_login($course)
7427 if ($musthaveaccess) {
7428 redirect(get_login_url());
7432 // Get the groups of the current user
7433 $mygroups = array_keys(groups_get_all_groups($course->id
, $USER->id
, $course->defaultgroupingid
, 'g.id, g.name'));
7434 // Get the groups the requested user is a member of
7435 $usergroups = array_keys(groups_get_all_groups($course->id
, $user->id
, $course->defaultgroupingid
, 'g.id, g.name'));
7436 // Check whether they are members of the same group. If they are great.
7437 $intersect = array_intersect($mygroups, $usergroups);
7438 if (empty($intersect)) {
7439 // But they're not... if it was a specific course throw an error otherwise
7440 // just skip this course so that it is not searched.
7441 if ($musthaveaccess) {
7442 print_error("groupnotamember", '', $CFG->wwwroot
."/course/view.php?id=$course->id");
7448 // Woo hoo we got this far which means the current user can search this
7449 // this course for the requested user. Although this is only the course accessibility
7450 // handling that is complete, the forum accessibility tests are yet to come.
7451 $return->courses
[$course->id
] = $course;
7453 // No longer beed $courses array - lose it not it may be big
7456 // Make sure that we have some courses to search
7457 if (empty($return->courses
)) {
7458 // If we don't have any courses to search then the reality is that the current
7459 // user doesn't have access to any courses is which the requested user has posted.
7460 // Although we do know at this point that the requested user has posts.
7461 if ($musthaveaccess) {
7462 print_error('permissiondenied');
7468 // Next step: Collect all of the forums that we will want to search.
7469 // It is important to note that this step isn't actually about searching, it is
7470 // about determining which forums we can search by testing accessibility.
7471 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses
), $discussionsonly);
7473 // Will be used to build the where conditions for the search
7474 $forumsearchwhere = array();
7475 // Will be used to store the where condition params for the search
7476 $forumsearchparams = array();
7477 // Will record forums where the user can freely access everything
7478 $forumsearchfullaccess = array();
7479 // DB caching friendly
7480 $now = round(time(), -2);
7481 // For each course to search we want to find the forums the user has posted in
7482 // and providing the current user can access the forum create a search condition
7483 // for the forum to get the requested users posts.
7484 foreach ($return->courses
as $course) {
7485 // Now we need to get the forums
7486 $modinfo = get_fast_modinfo($course);
7487 if (empty($modinfo->instances
['forum'])) {
7488 // hmmm, no forums? well at least its easy... skip!
7492 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
7493 if (!$cm->uservisible
or !isset($forums[$forumid])) {
7496 // Get the forum in question
7497 $forum = $forums[$forumid];
7499 // This is needed for functionality later on in the forum code. It is converted to an object
7500 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the
7501 // code were expecting an writeable object. See {@link forum_print_post()}.
7502 $forum->cm
= new stdClass();
7503 foreach ($cm as $key => $value) {
7504 $forum->cm
->$key = $value;
7507 // Check that either the current user can view the forum, or that the
7508 // current user has capabilities over the requested user and the requested
7509 // user can view the discussion
7510 if (!has_capability('mod/forum:viewdiscussion', $cm->context
) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context
, $user->id
))) {
7514 // This will contain forum specific where clauses
7515 $forumsearchselect = array();
7516 if (!$iscurrentuser && !$hascapsonuser) {
7517 // Make sure we check group access
7518 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $cm->context
)) {
7519 $groups = $modinfo->get_groups($cm->groupingid
);
7521 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grps'.$forumid.'_');
7522 $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
7523 $forumsearchselect[] = "d.groupid $groupid_sql";
7526 // hidden timed discussions
7527 if (!empty($CFG->forum_enabletimedposts
) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context
)) {
7528 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
7529 $forumsearchparams['userid'.$forumid] = $user->id
;
7530 $forumsearchparams['timestart'.$forumid] = $now;
7531 $forumsearchparams['timeend'.$forumid] = $now;
7535 if ($forum->type
== 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context
)) {
7536 // We need to check whether the user has posted in the qanda forum.
7537 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id
, $user->id
);
7538 if (!empty($discussionspostedin)) {
7539 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum.
7540 foreach ($discussionspostedin as $d) {
7541 $forumonlydiscussions[] = $d->id
;
7543 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED
, 'qanda'.$forumid.'_');
7544 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
7545 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
7547 $forumsearchselect[] = "p.parent = 0";
7552 if (count($forumsearchselect) > 0) {
7553 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
7554 $forumsearchparams['forum'.$forumid] = $forumid;
7556 $forumsearchfullaccess[] = $forumid;
7559 // The current user/parent can see all of their own posts
7560 $forumsearchfullaccess[] = $forumid;
7565 // If we dont have any search conditions, and we don't have any forums where
7566 // the user has full access then we just return the default.
7567 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
7571 // Prepare a where condition for the full access forums.
7572 if (count($forumsearchfullaccess) > 0) {
7573 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED
, 'fula');
7574 $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
7575 $forumsearchwhere[] = "(d.forum $fullidsql)";
7578 // Prepare SQL to both count and search.
7579 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
7580 // oracle and mssql.
7581 $userfields = user_picture
::fields('u', null, 'useridx');
7582 $countsql = 'SELECT COUNT(*) ';
7583 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
7584 $wheresql = implode(" OR ", $forumsearchwhere);
7586 if ($discussionsonly) {
7587 if ($wheresql == '') {
7588 $wheresql = 'p.parent = 0';
7590 $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
7594 $sql = "FROM {forum_posts} p
7595 JOIN {forum_discussions} d ON d.id = p.discussion
7596 JOIN {user} u ON u.id = p.userid
7598 AND p.userid = :userid ";
7599 $orderby = "ORDER BY p.modified DESC";
7600 $forumsearchparams['userid'] = $user->id
;
7602 // Set the total number posts made by the requested user that the current user can see
7603 $return->totalcount
= $DB->count_records_sql($countsql.$sql, $forumsearchparams);
7604 // Set the collection of posts that has been requested
7605 $return->posts
= $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);
7607 // We need to build an array of forums for which posts will be displayed.
7608 // We do this here to save the caller needing to retrieve them themselves before
7609 // printing these forums posts. Given we have the forums already there is
7610 // practically no overhead here.
7611 foreach ($return->posts
as $post) {
7612 if (!array_key_exists($post->forum
, $return->forums
)) {
7613 $return->forums
[$post->forum
] = $forums[$post->forum
];
7621 * Set the per-forum maildigest option for the specified user.
7623 * @param stdClass $forum The forum to set the option for.
7624 * @param int $maildigest The maildigest option.
7625 * @param stdClass $user The user object. This defaults to the global $USER object.
7626 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided.
7628 function forum_set_user_maildigest($forum, $maildigest, $user = null) {
7631 if (is_number($forum)) {
7632 $forum = $DB->get_record('forum', array('id' => $forum));
7635 if ($user === null) {
7639 $course = $DB->get_record('course', array('id' => $forum->course
), '*', MUST_EXIST
);
7640 $cm = get_coursemodule_from_instance('forum', $forum->id
, $course->id
, false, MUST_EXIST
);
7641 $context = context_module
::instance($cm->id
);
7643 // User must be allowed to see this forum.
7644 require_capability('mod/forum:viewdiscussion', $context, $user->id
);
7646 // Validate the maildigest setting.
7647 $digestoptions = forum_get_user_digest_options($user);
7649 if (!isset($digestoptions[$maildigest])) {
7650 throw new moodle_exception('invaliddigestsetting', 'mod_forum');
7653 // Attempt to retrieve any existing forum digest record.
7654 $subscription = $DB->get_record('forum_digests', array(
7655 'userid' => $user->id
,
7656 'forum' => $forum->id
,
7659 // Create or Update the existing maildigest setting.
7660 if ($subscription) {
7661 if ($maildigest == -1) {
7662 $DB->delete_records('forum_digests', array('forum' => $forum->id
, 'userid' => $user->id
));
7663 } else if ($maildigest !== $subscription->maildigest
) {
7664 // Only update the maildigest setting if it's changed.
7666 $subscription->maildigest
= $maildigest;
7667 $DB->update_record('forum_digests', $subscription);
7670 if ($maildigest != -1) {
7671 // Only insert the maildigest setting if it's non-default.
7673 $subscription = new stdClass();
7674 $subscription->forum
= $forum->id
;
7675 $subscription->userid
= $user->id
;
7676 $subscription->maildigest
= $maildigest;
7677 $subscription->id
= $DB->insert_record('forum_digests', $subscription);
7683 * Determine the maildigest setting for the specified user against the
7686 * @param Array $digests An array of forums and user digest settings.
7687 * @param stdClass $user The user object containing the id and maildigest default.
7688 * @param int $forumid The ID of the forum to check.
7689 * @return int The calculated maildigest setting for this user and forum.
7691 function forum_get_user_maildigest_bulk($digests, $user, $forumid) {
7692 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id
])) {
7693 $maildigest = $digests[$forumid][$user->id
];
7694 if ($maildigest === -1) {
7695 $maildigest = $user->maildigest
;
7698 $maildigest = $user->maildigest
;
7704 * Retrieve the list of available user digest options.
7706 * @param stdClass $user The user object. This defaults to the global $USER object.
7707 * @return array The mapping of values to digest options.
7709 function forum_get_user_digest_options($user = null) {
7712 // Revert to the global user object.
7713 if ($user === null) {
7717 $digestoptions = array();
7718 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum');
7719 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum');
7720 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum');
7722 // We need to add the default digest option at the end - it relies on
7723 // the contents of the existing values.
7724 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum',
7725 $digestoptions[$user->maildigest
]);
7727 // Resort the options to be in a sensible order.
7728 ksort($digestoptions);
7730 return $digestoptions;
7734 * Determine the current context if one was not already specified.
7736 * If a context of type context_module is specified, it is immediately
7737 * returned and not checked.
7739 * @param int $forumid The ID of the forum
7740 * @param context_module $context The current context.
7741 * @return context_module The context determined
7743 function forum_get_context($forumid, $context = null) {
7746 if (!$context ||
!($context instanceof context_module
)) {
7747 // Find out forum context. First try to take current page context to save on DB query.
7748 if ($PAGE->cm
&& $PAGE->cm
->modname
=== 'forum' && $PAGE->cm
->instance
== $forumid
7749 && $PAGE->context
->contextlevel
== CONTEXT_MODULE
&& $PAGE->context
->instanceid
== $PAGE->cm
->id
) {
7750 $context = $PAGE->context
;
7752 $cm = get_coursemodule_from_instance('forum', $forumid);
7753 $context = \context_module
::instance($cm->id
);