MDL-55982 mod_forum: Add time-based discussion locking
[moodle.git] / mod / forum / lib.php
CommitLineData
df1ba0f4 1<?php
df1ba0f4 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
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/>.
16
17/**
01030f1b
SH
18 * @package mod_forum
19 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df1ba0f4 21 */
22
bc196cbe
PS
23defined('MOODLE_INTERNAL') || die();
24
df1ba0f4 25/** Include required files */
39de876c 26require_once(__DIR__ . '/deprecatedlib.php');
f1e0649c 27require_once($CFG->libdir.'/filelib.php');
3b120e46 28require_once($CFG->libdir.'/eventslib.php');
7f6689e4 29
501cdbd8 30/// CONSTANTS ///////////////////////////////////////////////////////////
f93f848a 31
d3583b41 32define('FORUM_MODE_FLATOLDEST', 1);
33define('FORUM_MODE_FLATNEWEST', -1);
34define('FORUM_MODE_THREADED', 2);
35define('FORUM_MODE_NESTED', 3);
2e2e71a8 36
afef965e 37define('FORUM_CHOOSESUBSCRIBE', 0);
d3583b41 38define('FORUM_FORCESUBSCRIBE', 1);
39define('FORUM_INITIALSUBSCRIBE', 2);
098d27d4 40define('FORUM_DISALLOWSUBSCRIBE',3);
709f0ec8 41
bd8f5d45
EM
42/**
43 * FORUM_TRACKING_OFF - Tracking is not available for this forum.
44 */
eaf50aef 45define('FORUM_TRACKING_OFF', 0);
bd8f5d45
EM
46
47/**
48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference.
49 */
eaf50aef 50define('FORUM_TRACKING_OPTIONAL', 1);
bd8f5d45
EM
51
52/**
53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting.
54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off.
55 */
56define('FORUM_TRACKING_FORCED', 2);
57
8076010d 58define('FORUM_MAILED_PENDING', 0);
da484043
MO
59define('FORUM_MAILED_SUCCESS', 1);
60define('FORUM_MAILED_ERROR', 2);
61
103f34d8
PS
62if (!defined('FORUM_CRON_USER_CACHE')) {
63 /** Defines how many full user records are cached in forum cron. */
64 define('FORUM_CRON_USER_CACHE', 5000);
65}
66
4f3a2d21
JL
67/**
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
69 */
70define('FORUM_POSTS_ALL_USER_GROUPS', -2);
71
87b007b4
CF
72define('FORUM_DISCUSSION_PINNED', 1);
73define('FORUM_DISCUSSION_UNPINNED', 0);
74
caadf009 75/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
76
0a4ac01b 77/**
78 * Given an object containing all the necessary data,
7cac0c4b 79 * (defined by the form in mod_form.php) this function
0a4ac01b 80 * will create a new instance and return the id number
81 * of the new instance.
df1ba0f4 82 *
6b04fdc0
PS
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
6b7de0bb 85 * @return int intance id
3a5e1d06 86 */
6b04fdc0 87function forum_add_instance($forum, $mform = null) {
c18269c7 88 global $CFG, $DB;
caadf009 89
90 $forum->timemodified = time();
91
353228d8 92 if (empty($forum->assessed)) {
f2f56406 93 $forum->assessed = 0;
94 }
2b63df96 95
353228d8 96 if (empty($forum->ratingtime) or empty($forum->assessed)) {
98914efd 97 $forum->assesstimestart = 0;
98 $forum->assesstimefinish = 0;
99 }
caadf009 100
a8f3a651 101 $forum->id = $DB->insert_record('forum', $forum);
bf0f06b1 102 $modcontext = context_module::instance($forum->coursemodule);
cb9a975f 103
d3583b41 104 if ($forum->type == 'single') { // Create related discussion.
39790bd8 105 $discussion = new stdClass();
e2d7687f 106 $discussion->course = $forum->course;
107 $discussion->forum = $forum->id;
108 $discussion->name = $forum->name;
e2d7687f 109 $discussion->assessed = $forum->assessed;
6606c00f
MD
110 $discussion->message = $forum->intro;
111 $discussion->messageformat = $forum->introformat;
bf0f06b1 112 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
e2d7687f 113 $discussion->mailnow = false;
114 $discussion->groupid = -1;
caadf009 115
dbf4d660 116 $message = '';
117
42776c94
PS
118 $discussion->id = forum_add_discussion($discussion, null, $message);
119
120 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
a11aa38e 121 // Ugly hack - we need to copy the files somehow.
42776c94
PS
122 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
123 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
124
a11aa38e
PS
125 $options = array('subdirs'=>true); // Use the same options as intro field!
126 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
42776c94 127 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
caadf009 128 }
129 }
8f0cd6ef 130
8e6775d8
AN
131 forum_grade_item_update($forum);
132
133 return $forum->id;
134}
135
136/**
137 * Handle changes following the creation of a forum instance.
138 * This function is typically called by the course_module_created observer.
139 *
140 * @param object $context the forum context
141 * @param stdClass $forum The forum object
142 * @return void
143 */
144function forum_instance_created($context, $forum) {
3c268f25 145 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
59075a43 146 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
709f0ec8 147 foreach ($users as $user) {
59075a43 148 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
709f0ec8 149 }
150 }
caadf009 151}
152
13bbe067 153/**
0a4ac01b 154 * Given an object containing all the necessary data,
7cac0c4b 155 * (defined by the form in mod_form.php) this function
0a4ac01b 156 * will update an existing instance with new data.
df1ba0f4 157 *
158 * @global object
90f4745c 159 * @param object $forum forum instance (with magic quotes)
6b7de0bb 160 * @return bool success
90f4745c 161 */
42776c94 162function forum_update_instance($forum, $mform) {
862f5a49 163 global $DB, $OUTPUT, $USER;
c18269c7 164
caadf009 165 $forum->timemodified = time();
353228d8 166 $forum->id = $forum->instance;
caadf009 167
f0da6b85 168 if (empty($forum->assessed)) {
f2f56406 169 $forum->assessed = 0;
170 }
2b63df96 171
353228d8 172 if (empty($forum->ratingtime) or empty($forum->assessed)) {
98914efd 173 $forum->assesstimestart = 0;
174 $forum->assesstimefinish = 0;
175 }
176
c18269c7 177 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
13bbe067 178
179 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
180 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
181 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade
182 if (($oldforum->assessed<>$forum->assessed) or ($oldforum->scale<>$forum->scale)) {
183 forum_update_grades($forum); // recalculate grades for the forum
184 }
185
d3583b41 186 if ($forum->type == 'single') { // Update related discussion and post.
35b81f27
RT
187 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
188 if (!empty($discussions)) {
189 if (count($discussions) > 1) {
190 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
191 }
192 $discussion = array_pop($discussions);
193 } else {
194 // try to recover by creating initial discussion - MDL-16262
195 $discussion = new stdClass();
196 $discussion->course = $forum->course;
197 $discussion->forum = $forum->id;
198 $discussion->name = $forum->name;
199 $discussion->assessed = $forum->assessed;
200 $discussion->message = $forum->intro;
201 $discussion->messageformat = $forum->introformat;
202 $discussion->messagetrust = true;
203 $discussion->mailnow = false;
204 $discussion->groupid = -1;
205
206 $message = '';
207
208 forum_add_discussion($discussion, null, $message);
209
210 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
211 print_error('cannotadd', 'forum');
caadf009 212 }
213 }
c18269c7 214 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
12e57b92 215 print_error('cannotfindfirstpost', 'forum');
caadf009 216 }
217
6606c00f 218 $cm = get_coursemodule_from_instance('forum', $forum->id);
bf0f06b1 219 $modcontext = context_module::instance($cm->id, MUST_EXIST);
42776c94 220
a11aa38e 221 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
6606c00f
MD
222 $post->subject = $forum->name;
223 $post->message = $forum->intro;
224 $post->messageformat = $forum->introformat;
225 $post->messagetrust = trusttext_trusted($modcontext);
226 $post->modified = $forum->timemodified;
a11aa38e
PS
227 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
228
229 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
230 // Ugly hack - we need to copy the files somehow.
231 $options = array('subdirs'=>true); // Use the same options as intro field!
232 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
233 }
caadf009 234
a8d6ef8c 235 $DB->update_record('forum_posts', $post);
caadf009 236 $discussion->name = $forum->name;
a8d6ef8c 237 $DB->update_record('forum_discussions', $discussion);
caadf009 238 }
239
a8d6ef8c 240 $DB->update_record('forum', $forum);
353228d8 241
4a913724
GPL
242 $modcontext = context_module::instance($forum->coursemodule);
243 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
59075a43 244 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
4a913724 245 foreach ($users as $user) {
59075a43 246 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
4a913724
GPL
247 }
248 }
249
353228d8 250 forum_grade_item_update($forum);
251
252 return true;
caadf009 253}
254
255
0a4ac01b 256/**
257 * Given an ID of an instance of this module,
258 * this function will permanently delete the instance
259 * and any data that depends on it.
df1ba0f4 260 *
261 * @global object
262 * @param int $id forum instance id
90f4745c 263 * @return bool success
0a4ac01b 264 */
caadf009 265function forum_delete_instance($id) {
c18269c7 266 global $DB;
caadf009 267
c18269c7 268 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
caadf009 269 return false;
270 }
455a8fed 271 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
272 return false;
273 }
274 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
275 return false;
276 }
277
bf0f06b1 278 $context = context_module::instance($cm->id);
caadf009 279
fa686bc4 280 // now get rid of all files
281 $fs = get_file_storage();
455a8fed 282 $fs->delete_area_files($context->id);
fa686bc4 283
caadf009 284 $result = true;
285
361a41d3
AN
286 // Delete digest and subscription preferences.
287 $DB->delete_records('forum_digests', array('forum' => $forum->id));
288 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
289 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
290
c18269c7 291 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
caadf009 292 foreach ($discussions as $discussion) {
455a8fed 293 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
caadf009 294 $result = false;
295 }
296 }
297 }
298
f37da850 299 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
300
415f8c3e 301 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
caadf009 302 $result = false;
303 }
304
353228d8 305 forum_grade_item_delete($forum);
306
caadf009 307 return $result;
308}
309
310
4e781c7b 311/**
312 * Indicates API features that the forum supports.
313 *
df1ba0f4 314 * @uses FEATURE_GROUPS
315 * @uses FEATURE_GROUPINGS
df1ba0f4 316 * @uses FEATURE_MOD_INTRO
317 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
318 * @uses FEATURE_COMPLETION_HAS_RULES
319 * @uses FEATURE_GRADE_HAS_GRADE
320 * @uses FEATURE_GRADE_OUTCOMES
4e781c7b 321 * @param string $feature
322 * @return mixed True if yes (some features may use other values)
323 */
324function forum_supports($feature) {
325 switch($feature) {
42f103be 326 case FEATURE_GROUPS: return true;
327 case FEATURE_GROUPINGS: return true;
dc5c2bd9 328 case FEATURE_MOD_INTRO: return true;
4e781c7b 329 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 330 case FEATURE_COMPLETION_HAS_RULES: return true;
331 case FEATURE_GRADE_HAS_GRADE: return true;
332 case FEATURE_GRADE_OUTCOMES: return true;
4bfdcfcf
EL
333 case FEATURE_RATE: return true;
334 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 335 case FEATURE_SHOW_DESCRIPTION: return true;
50da4ddd 336 case FEATURE_PLAGIARISM: return true;
42f103be 337
49f6e5f4 338 default: return null;
4e781c7b 339 }
340}
341
342
343/**
344 * Obtains the automatic completion state for this forum based on any conditions
345 * in forum settings.
346 *
df1ba0f4 347 * @global object
348 * @global object
4e781c7b 349 * @param object $course Course
350 * @param object $cm Course-module
351 * @param int $userid User ID
352 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
353 * @return bool True if completed, false if not. (If no conditions, then return
354 * value depends on comparison type)
355 */
356function forum_get_completion_state($course,$cm,$userid,$type) {
357 global $CFG,$DB;
358
359 // Get forum details
6093af9b 360 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) {
4e781c7b 361 throw new Exception("Can't find forum {$cm->instance}");
362 }
363
364 $result=$type; // Default return value
365
366 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id);
367 $postcountsql="
5e7f2b0b 368SELECT
369 COUNT(1)
370FROM
371 {forum_posts} fp
49f6e5f4 372 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id
4e781c7b 373WHERE
374 fp.userid=:userid AND fd.forum=:forumid";
375
6093af9b 376 if ($forum->completiondiscussions) {
4e781c7b 377 $value = $forum->completiondiscussions <=
6093af9b 378 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid));
379 if ($type == COMPLETION_AND) {
380 $result = $result && $value;
4e781c7b 381 } else {
6093af9b 382 $result = $result || $value;
4e781c7b 383 }
384 }
6093af9b 385 if ($forum->completionreplies) {
5e7f2b0b 386 $value = $forum->completionreplies <=
6093af9b 387 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams);
388 if ($type==COMPLETION_AND) {
389 $result = $result && $value;
4e781c7b 390 } else {
6093af9b 391 $result = $result || $value;
4e781c7b 392 }
393 }
6093af9b 394 if ($forum->completionposts) {
4e781c7b 395 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams);
6093af9b 396 if ($type == COMPLETION_AND) {
397 $result = $result && $value;
4e781c7b 398 } else {
6093af9b 399 $result = $result || $value;
4e781c7b 400 }
401 }
402
5e7f2b0b 403 return $result;
4e781c7b 404}
405
8260050d
AD
406/**
407 * Create a message-id string to use in the custom headers of forum notification emails
408 *
409 * message-id is used by email clients to identify emails and to nest conversations
410 *
411 * @param int $postid The ID of the forum post we are notifying the user about
412 * @param int $usertoid The ID of the user being notified
8260050d
AD
413 * @return string A unique message-id
414 */
54dceeed
BH
415function forum_get_email_message_id($postid, $usertoid) {
416 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
1376b0dd 417}
4e781c7b 418
103f34d8
PS
419/**
420 * Removes properties from user record that are not necessary
421 * for sending post notifications.
422 * @param stdClass $user
423 * @return void, $user parameter is modified
424 */
425function forum_cron_minimise_user_record(stdClass $user) {
426
427 // We store large amount of users in one huge array,
428 // make sure we do not store info there we do not actually need
429 // in mail generation code or messaging.
430
431 unset($user->institution);
432 unset($user->department);
433 unset($user->address);
434 unset($user->city);
435 unset($user->url);
436 unset($user->currentlogin);
437 unset($user->description);
438 unset($user->descriptionformat);
439}
440
0a4ac01b 441/**
cae945d2
DP
442 * Function to be run periodically according to the scheduled task.
443 *
0a4ac01b 444 * Finds all posts that have yet to be mailed out, and mails them
cae945d2 445 * out to all subscribers as well as other maintance tasks.
df1ba0f4 446 *
cae945d2
DP
447 * NOTE: Since 2.7.2 this function is run by scheduled task rather
448 * than standard cron.
449 *
450 * @todo MDL-44734 The function will be split up into seperate tasks.
90f4745c 451 */
0fa18d5a 452function forum_cron() {
31793839 453 global $CFG, $USER, $DB, $PAGE;
857b798b 454
a974c799 455 $site = get_site();
456
31793839
AN
457 // The main renderers.
458 $htmlout = $PAGE->get_renderer('mod_forum', 'email', 'htmlemail');
459 $textout = $PAGE->get_renderer('mod_forum', 'email', 'textemail');
460 $htmldigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'htmlemail');
461 $textdigestfullout = $PAGE->get_renderer('mod_forum', 'emaildigestfull', 'textemail');
462 $htmldigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'htmlemail');
463 $textdigestbasicout = $PAGE->get_renderer('mod_forum', 'emaildigestbasic', 'textemail');
464
103f34d8
PS
465 // All users that are subscribed to any post that needs sending,
466 // please increase $CFG->extramemorylimit on large sites that
467 // send notifications to a large number of users.
a974c799 468 $users = array();
103f34d8 469 $userscount = 0; // Cached user counter - count($users) in PHP is horribly slow!!!
a974c799 470
49566c8a 471 // Status arrays.
a974c799 472 $mailcount = array();
473 $errorcount = array();
474
475 // caches
49566c8a
AN
476 $discussions = array();
477 $forums = array();
478 $courses = array();
479 $coursemodules = array();
480 $subscribedusers = array();
91223df6 481 $messageinboundhandlers = array();
ec2137ba 482
0a4ac01b 483 // Posts older than 2 days will not be mailed. This is to avoid the problem where
484 // cron has not been running for a long time, and then suddenly people are flooded
485 // with mail from the past few weeks or months
3ecca1ee 486 $timenow = time();
487 $endtime = $timenow - $CFG->maxeditingtime;
0a4ac01b 488 $starttime = $endtime - 48 * 3600; // Two days earlier
3ecca1ee 489
8e08c731
AN
490 // Get the list of forum subscriptions for per-user per-forum maildigest settings.
491 $digestsset = $DB->get_recordset('forum_digests', null, '', 'id, userid, forum, maildigest');
492 $digests = array();
493 foreach ($digestsset as $thisrow) {
494 if (!isset($digests[$thisrow->forum])) {
495 $digests[$thisrow->forum] = array();
496 }
497 $digests[$thisrow->forum][$thisrow->userid] = $thisrow->maildigest;
498 }
499 $digestsset->close();
500
91223df6
AN
501 // Create the generic messageinboundgenerator.
502 $messageinboundgenerator = new \core\message\inbound\address_manager();
503 $messageinboundgenerator->set_handler('\mod_forum\message\inbound\reply_handler');
504
90f4745c 505 if ($posts = forum_get_unmailed_posts($starttime, $endtime, $timenow)) {
0a4ac01b 506 // Mark them all now as being mailed. It's unlikely but possible there
507 // might be an error later so that a post is NOT actually mailed out,
508 // but since mail isn't crucial, we can accept this risk. Doing it now
509 // prevents the risk of duplicated mails, which is a worse problem.
16b4e5b6 510
5fac3a5e 511 if (!forum_mark_old_posts_as_mailed($endtime)) {
512 mtrace('Errors occurred while trying to mark some posts as being mailed.');
513 return false; // Don't continue trying to mail them, in case we are in a cron loop
514 }
515
516 // checking post validity, and adding users to loop through later
517 foreach ($posts as $pid => $post) {
518
a974c799 519 $discussionid = $post->discussion;
520 if (!isset($discussions[$discussionid])) {
4e445355 521 if ($discussion = $DB->get_record('forum_discussions', array('id'=> $post->discussion))) {
a974c799 522 $discussions[$discussionid] = $discussion;
49566c8a
AN
523 \mod_forum\subscriptions::fill_subscription_cache($discussion->forum);
524 \mod_forum\subscriptions::fill_discussion_subscription_cache($discussion->forum);
525
a974c799 526 } else {
49566c8a 527 mtrace('Could not find discussion ' . $discussionid);
a974c799 528 unset($posts[$pid]);
529 continue;
530 }
5fac3a5e 531 }
a974c799 532 $forumid = $discussions[$discussionid]->forum;
533 if (!isset($forums[$forumid])) {
4e445355 534 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
a974c799 535 $forums[$forumid] = $forum;
536 } else {
537 mtrace('Could not find forum '.$forumid);
538 unset($posts[$pid]);
539 continue;
540 }
5fac3a5e 541 }
a974c799 542 $courseid = $forums[$forumid]->course;
543 if (!isset($courses[$courseid])) {
4e445355 544 if ($course = $DB->get_record('course', array('id' => $courseid))) {
a974c799 545 $courses[$courseid] = $course;
546 } else {
547 mtrace('Could not find course '.$courseid);
548 unset($posts[$pid]);
549 continue;
550 }
5fac3a5e 551 }
a974c799 552 if (!isset($coursemodules[$forumid])) {
553 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
554 $coursemodules[$forumid] = $cm;
555 } else {
9c670df6 556 mtrace('Could not find course module for forum '.$forumid);
a974c799 557 unset($posts[$pid]);
558 continue;
559 }
560 }
561
e7f0b4d3
AN
562 // Save the Inbound Message datakey here to reduce DB queries later.
563 $messageinboundgenerator->set_data($pid);
564 $messageinboundhandlers[$pid] = $messageinboundgenerator->fetch_data_key();
565
49566c8a 566 // Caching subscribed users of each forum.
a974c799 567 if (!isset($subscribedusers[$forumid])) {
bf0f06b1 568 $modcontext = context_module::instance($coursemodules[$forumid]->id);
e3bbfb52 569 if ($subusers = \mod_forum\subscriptions::fetch_subscribed_users($forums[$forumid], 0, $modcontext, 'u.*', true)) {
91223df6 570
704ca25c 571 foreach ($subusers as $postuser) {
572 // this user is subscribed to this forum
a5cef9c8 573 $subscribedusers[$forumid][$postuser->id] = $postuser->id;
103f34d8
PS
574 $userscount++;
575 if ($userscount > FORUM_CRON_USER_CACHE) {
576 // Store minimal user info.
577 $minuser = new stdClass();
578 $minuser->id = $postuser->id;
579 $users[$postuser->id] = $minuser;
580 } else {
581 // Cache full user record.
582 forum_cron_minimise_user_record($postuser);
583 $users[$postuser->id] = $postuser;
584 }
704ca25c 585 }
103f34d8
PS
586 // Release memory.
587 unset($subusers);
588 unset($postuser);
a974c799 589 }
5fac3a5e 590 }
5fac3a5e 591 $mailcount[$pid] = 0;
592 $errorcount[$pid] = 0;
a974c799 593 }
5fac3a5e 594 }
caadf009 595
4dad2828 596 if ($users && $posts) {
edffca15 597
5fac3a5e 598 foreach ($users as $userto) {
49566c8a
AN
599 // Terminate if processing of any account takes longer than 2 minutes.
600 core_php_time_limit::raise(120);
a974c799 601
49566c8a 602 mtrace('Processing user ' . $userto->id);
caadf009 603
49566c8a 604 // Init user caches - we keep the cache for one cycle only, otherwise it could consume too much memory.
103f34d8
PS
605 if (isset($userto->username)) {
606 $userto = clone($userto);
607 } else {
608 $userto = $DB->get_record('user', array('id' => $userto->id));
609 forum_cron_minimise_user_record($userto);
610 }
df1c2c71 611 $userto->viewfullnames = array();
612 $userto->canpost = array();
90f4745c 613 $userto->markposts = array();
669f2499 614
49566c8a 615 // Setup this user so that the capabilities are cached, and environment matches receiving user.
103f34d8
PS
616 cron_setup_user($userto);
617
49566c8a
AN
618 // Reset the caches.
619 foreach ($coursemodules as $forumid => $unused) {
39790bd8 620 $coursemodules[$forumid]->cache = new stdClass();
9db5d080 621 $coursemodules[$forumid]->cache->caps = array();
622 unset($coursemodules[$forumid]->uservisible);
623 }
624
4dad2828 625 foreach ($posts as $pid => $post) {
a974c799 626 $discussion = $discussions[$post->discussion];
627 $forum = $forums[$discussion->forum];
628 $course = $courses[$forum->course];
90f4745c 629 $cm =& $coursemodules[$forum->id];
4dad2828 630
49566c8a
AN
631 // Do some checks to see if we can bail out now.
632
633 // Only active enrolled users are in the list of subscribers.
634 // This does not necessarily mean that the user is subscribed to the forum or to the discussion though.
a5cef9c8 635 if (!isset($subscribedusers[$forum->id][$userto->id])) {
49566c8a
AN
636 // The user does not subscribe to this forum.
637 continue;
638 }
639
4238983e 640 if (!\mod_forum\subscriptions::is_subscribed($userto->id, $forum, $post->discussion, $coursemodules[$forum->id])) {
49566c8a
AN
641 // The user does not subscribe to this forum, or to this specific discussion.
642 continue;
4dad2828 643 }
4dad2828 644
eb451c79
AN
645 if ($subscriptiontime = \mod_forum\subscriptions::fetch_discussion_subscription($forum->id, $userto->id)) {
646 // Skip posts if the user subscribed to the discussion after it was created.
647 if (isset($subscriptiontime[$post->discussion]) && ($subscriptiontime[$post->discussion] > $post->created)) {
648 continue;
649 }
650 }
651
49566c8a
AN
652 // Don't send email if the forum is Q&A and the user has not posted.
653 // Initial topics are still mailed.
1e966b8a 654 if ($forum->type == 'qanda' && !forum_get_user_posted_time($discussion->id, $userto->id) && $pid != $discussion->firstpost) {
49566c8a 655 mtrace('Did not email ' . $userto->id.' because user has not posted in discussion');
67fc4f00
DC
656 continue;
657 }
90f4745c 658
49566c8a
AN
659 // Get info about the sending user.
660 if (array_key_exists($post->userid, $users)) {
661 // We might know the user already.
a5cef9c8 662 $userfrom = $users[$post->userid];
103f34d8
PS
663 if (!isset($userfrom->idnumber)) {
664 // Minimalised user info, fetch full record.
665 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
666 forum_cron_minimise_user_record($userfrom);
667 }
668
4e445355 669 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
103f34d8
PS
670 forum_cron_minimise_user_record($userfrom);
671 // Fetch only once if possible, we can add it to user list, it will be skipped anyway.
672 if ($userscount <= FORUM_CRON_USER_CACHE) {
673 $userscount++;
674 $users[$userfrom->id] = $userfrom;
675 }
a5cef9c8 676 } else {
49566c8a 677 mtrace('Could not find user ' . $post->userid . ', author of post ' . $post->id . '. Unable to send message.');
a5cef9c8 678 continue;
679 }
680
49566c8a 681 // Note: If we want to check that userto and userfrom are not the same person this is probably the spot to do it.
505ab5aa 682
49566c8a 683 // Setup global $COURSE properly - needed for roles and languages.
e8b7114d 684 cron_setup_user($userto, $course);
4dad2828 685
49566c8a 686 // Fill caches.
df1c2c71 687 if (!isset($userto->viewfullnames[$forum->id])) {
bf0f06b1 688 $modcontext = context_module::instance($cm->id);
df1c2c71 689 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
690 }
8b79a625 691 if (!isset($userto->canpost[$discussion->id])) {
bf0f06b1 692 $modcontext = context_module::instance($cm->id);
8b79a625 693 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
df1c2c71 694 }
695 if (!isset($userfrom->groups[$forum->id])) {
696 if (!isset($userfrom->groups)) {
697 $userfrom->groups = array();
103f34d8
PS
698 if (isset($users[$userfrom->id])) {
699 $users[$userfrom->id]->groups = array();
700 }
df1c2c71 701 }
702 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
103f34d8
PS
703 if (isset($users[$userfrom->id])) {
704 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
705 }
df1c2c71 706 }
9f2ded76 707
49566c8a
AN
708 // Make sure groups allow this user to see this email.
709 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {
710 // Groups are being used.
711 if (!groups_group_exists($discussion->groupid)) {
712 // Can't find group - be safe and don't this message.
713 continue;
5fac3a5e 714 }
918e9805 715
2c386f82 716 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $modcontext)) {
49566c8a 717 // Do not send posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS.
38bd362a 718 continue;
9197e147 719 }
4dad2828 720 }
2b63df96 721
49566c8a
AN
722 // Make sure we're allowed to see the post.
723 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
724 mtrace('User ' . $userto->id .' can not see ' . $post->id . '. Not sending message.');
4dad2828 725 continue;
726 }
727
728 // OK so we need to send the email.
729
730 // Does the user want this post in a digest? If so postpone it for now.
8e08c731
AN
731 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
732
733 if ($maildigest > 0) {
49566c8a 734 // This user wants the mails to be in digest form.
39790bd8 735 $queue = new stdClass();
a974c799 736 $queue->userid = $userto->id;
4dad2828 737 $queue->discussionid = $discussion->id;
a974c799 738 $queue->postid = $post->id;
90f4745c 739 $queue->timemodified = $post->created;
fc29e51b 740 $DB->insert_record('forum_queue', $queue);
4dad2828 741 continue;
742 }
65b0e537 743
49566c8a 744 // Prepare to actually send the post now, and build up the content.
4dad2828 745
a974c799 746 $cleanforumname = str_replace('"', "'", strip_tags(format_string($forum->name)));
4dad2828 747
49566c8a
AN
748 $userfrom->customheaders = array (
749 // Headers to make emails easier to track.
54dceeed 750 'List-Id: "' . $cleanforumname . '" ' . generate_email_messageid('moodleforum' . $forum->id),
49566c8a 751 'List-Help: ' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id,
54dceeed 752 'Message-ID: ' . forum_get_email_message_id($post->id, $userto->id),
49566c8a 753 'X-Course-Id: ' . $course->id,
c9fa2dee
AN
754 'X-Course-Name: ' . format_string($course->fullname, true),
755
756 // Headers to help prevent auto-responders.
757 'Precedence: Bulk',
758 'X-Auto-Response-Suppress: All',
759 'Auto-Submitted: auto-generated',
4dad2828 760 );
a974c799 761
bf0f06b1 762 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
8ebbb06a 763
91223df6
AN
764 // Generate a reply-to address from using the Inbound Message handler.
765 $replyaddress = null;
766 if ($userto->canpost[$discussion->id] && array_key_exists($post->id, $messageinboundhandlers)) {
767 $messageinboundgenerator->set_data($post->id, $messageinboundhandlers[$post->id]);
768 $replyaddress = $messageinboundgenerator->generate($userto->id);
769 }
770
31793839
AN
771 if (!isset($userto->canpost[$discussion->id])) {
772 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
773 } else {
774 $canreply = $userto->canpost[$discussion->id];
775 }
776
777 $data = new \mod_forum\output\forum_post_email(
778 $course,
779 $cm,
780 $forum,
781 $discussion,
782 $post,
783 $userfrom,
784 $userto,
785 $canreply
786 );
787
7898d616
BH
788 $userfrom->customheaders[] = sprintf('List-Unsubscribe: <%s>',
789 $data->get_unsubscribediscussionlink());
790
31793839
AN
791 if (!isset($userto->viewfullnames[$forum->id])) {
792 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
793 } else {
794 $data->viewfullnames = $userto->viewfullnames[$forum->id];
795 }
796
091420f9
BH
797 // Not all of these variables are used in the default language
798 // string but are made available to support custom subjects.
013e85bb 799 $a = new stdClass();
31793839 800 $a->subject = $data->get_subject();
091420f9
BH
801 $a->forumname = $cleanforumname;
802 $a->sitefullname = format_string($site->fullname);
803 $a->siteshortname = format_string($site->shortname);
804 $a->courseidnumber = $data->get_courseidnumber();
805 $a->coursefullname = $data->get_coursefullname();
806 $a->courseshortname = $data->get_coursename();
28c0c4af 807 $postsubject = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
4dad2828 808
54dceeed 809 $rootid = forum_get_email_message_id($discussion->firstpost, $userto->id);
b1b480f9
BH
810
811 if ($post->parent) {
812 // This post is a reply, so add reply header (RFC 2822).
54dceeed 813 $parentid = forum_get_email_message_id($post->parent, $userto->id);
b1b480f9
BH
814 $userfrom->customheaders[] = "In-Reply-To: $parentid";
815
816 // If the post is deeply nested we also reference the parent message id and
817 // the root message id (if different) to aid threading when parts of the email
818 // conversation have been deleted (RFC1036).
819 if ($post->parent != $discussion->firstpost) {
820 $userfrom->customheaders[] = "References: $rootid $parentid";
821 } else {
822 $userfrom->customheaders[] = "References: $parentid";
823 }
824 }
825
826 // MS Outlook / Office uses poorly documented and non standard headers, including
827 // Thread-Topic which overrides the Subject and shouldn't contain Re: or Fwd: etc.
828 $a->subject = $discussion->name;
318e5cb3
BH
829 $threadtopic = html_to_text(get_string('postmailsubject', 'forum', $a), 0);
830 $userfrom->customheaders[] = "Thread-Topic: $threadtopic";
b1b480f9
BH
831 $userfrom->customheaders[] = "Thread-Index: " . substr($rootid, 1, 28);
832
4dad2828 833 // Send the post now!
4dad2828 834 mtrace('Sending ', '');
5e7f2b0b 835
9bb71899 836 $eventdata = new \core\message\message();
49566c8a
AN
837 $eventdata->component = 'mod_forum';
838 $eventdata->name = 'posts';
839 $eventdata->userfrom = $userfrom;
840 $eventdata->userto = $userto;
841 $eventdata->subject = $postsubject;
31793839 842 $eventdata->fullmessage = $textout->render($data);
49566c8a 843 $eventdata->fullmessageformat = FORMAT_PLAIN;
31793839 844 $eventdata->fullmessagehtml = $htmlout->render($data);
49566c8a 845 $eventdata->notification = 1;
91223df6 846 $eventdata->replyto = $replyaddress;
9bb71899
AA
847 if (!empty($replyaddress)) {
848 // Add extra text to email messages if they can reply back.
849 $textfooter = "\n\n" . get_string('replytopostbyemail', 'mod_forum');
850 $htmlfooter = html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
851 $additionalcontent = array('fullmessage' => array('footer' => $textfooter),
852 'fullmessagehtml' => array('footer' => $htmlfooter));
853 $eventdata->set_additional_content('email', $additionalcontent);
854 }
6ee2611c 855
e9c55e39
RT
856 // If forum_replytouser is not set then send mail using the noreplyaddress.
857 if (empty($CFG->forum_replytouser)) {
7cd4a0f6 858 $eventdata->userfrom = core_user::get_noreply_user();
e9c55e39
RT
859 }
860
6ee2611c 861 $smallmessagestrings = new stdClass();
49566c8a
AN
862 $smallmessagestrings->user = fullname($userfrom);
863 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
864 $smallmessagestrings->message = $post->message;
865
866 // Make sure strings are in message recipients language.
4ffa1463 867 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
14a0e7dd 868
49566c8a
AN
869 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
870 $eventdata->contexturl = $contexturl->out();
14a0e7dd 871 $eventdata->contexturlname = $discussion->name;
3b120e46 872
505ab5aa 873 $mailresult = message_send($eventdata);
49566c8a 874 if (!$mailresult) {
505ab5aa 875 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
49566c8a 876 " ($userto->email) .. not trying again.");
4dad2828 877 $errorcount[$post->id]++;
4dad2828 878 } else {
879 $mailcount[$post->id]++;
880
49566c8a 881 // Mark post as read if forum_usermarksread is set off.
90f4745c 882 if (!$CFG->forum_usermarksread) {
883 $userto->markposts[$post->id] = $post->id;
caadf009 884 }
aaf7a9dc 885 }
4dad2828 886
49566c8a 887 mtrace('post ' . $post->id . ': ' . $post->subject);
aaf7a9dc 888 }
90f4745c 889
49566c8a 890 // Mark processed posts as read.
90f4745c 891 forum_tp_mark_posts_read($userto, $userto->markposts);
103f34d8 892 unset($userto);
5fac3a5e 893 }
894 }
895
896 if ($posts) {
897 foreach ($posts as $post) {
16b4e5b6 898 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
5fac3a5e 899 if ($errorcount[$post->id]) {
8076010d 900 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
a974c799 901 }
aaf7a9dc 902 }
903 }
904
8cb121cc 905 // release some memory
906 unset($subscribedusers);
907 unset($mailcount);
908 unset($errorcount);
909
e8b7114d 910 cron_setup_user();
ad9ff3d3 911
d6e7a63d 912 $sitetimezone = core_date::get_server_timezone();
944a2b28 913
0a4ac01b 914 // Now see if there are any digest mails waiting to be sent, and if we should send them
aaf7a9dc 915
f3c3a4d3 916 mtrace('Starting digest processing...');
917
3ef7279f 918 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
910b6fa7 919
8f0cd6ef 920 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
ca8e8a10 921 set_config('digestmailtimelast', 0);
922 }
923
924 $timenow = time();
944a2b28 925 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
ca8e8a10 926
f3c3a4d3 927 // Delete any really old ones (normally there shouldn't be any)
928 $weekago = $timenow - (7 * 24 * 3600);
2ac897cd 929 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
910b6fa7 930 mtrace ('Cleaned old digest records');
9f2ded76 931
ca8e8a10 932 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
b140ae85 933
b140ae85 934 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
935
4e445355 936 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
910b6fa7 937
4e445355 938 if ($digestposts_rs->valid()) {
8ad64455 939
aaf7a9dc 940 // We have work to do
941 $usermailcount = 0;
aaf7a9dc 942
a974c799 943 //caches - reuse the those filled before too
aaf7a9dc 944 $discussionposts = array();
945 $userdiscussions = array();
a974c799 946
4e445355 947 foreach ($digestposts_rs as $digestpost) {
a974c799 948 if (!isset($posts[$digestpost->postid])) {
4e445355 949 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
a974c799 950 $posts[$digestpost->postid] = $post;
951 } else {
952 continue;
953 }
954 }
955 $discussionid = $digestpost->discussionid;
956 if (!isset($discussions[$discussionid])) {
4e445355 957 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
a974c799 958 $discussions[$discussionid] = $discussion;
959 } else {
960 continue;
961 }
aaf7a9dc 962 }
a974c799 963 $forumid = $discussions[$discussionid]->forum;
964 if (!isset($forums[$forumid])) {
4e445355 965 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
a974c799 966 $forums[$forumid] = $forum;
967 } else {
968 continue;
969 }
970 }
971
972 $courseid = $forums[$forumid]->course;
973 if (!isset($courses[$courseid])) {
4e445355 974 if ($course = $DB->get_record('course', array('id' => $courseid))) {
a974c799 975 $courses[$courseid] = $course;
976 } else {
977 continue;
978 }
aaf7a9dc 979 }
a974c799 980
981 if (!isset($coursemodules[$forumid])) {
982 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
983 $coursemodules[$forumid] = $cm;
984 } else {
985 continue;
986 }
aaf7a9dc 987 }
988 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
989 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
990 }
4e445355 991 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
aaf7a9dc 992
993 // Data collected, start sending out emails to each user
a974c799 994 foreach ($userdiscussions as $userid => $thesediscussions) {
aaf7a9dc 995
3ef7279f 996 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
aaf7a9dc 997
e8b7114d 998 cron_setup_user();
90f4745c 999
a974c799 1000 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
aaf7a9dc 1001
1002 // First of all delete all the queue entries for this user
4e445355 1003 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
aaf7a9dc 1004
103f34d8
PS
1005 // Init user caches - we keep the cache for one cycle only,
1006 // otherwise it would unnecessarily consume memory.
1007 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
1008 $userto = clone($users[$userid]);
1009 } else {
1010 $userto = $DB->get_record('user', array('id' => $userid));
1011 forum_cron_minimise_user_record($userto);
1012 }
df1c2c71 1013 $userto->viewfullnames = array();
1014 $userto->canpost = array();
90f4745c 1015 $userto->markposts = array();
df1c2c71 1016
103f34d8
PS
1017 // Override the language and timezone of the "current" user, so that
1018 // mail is customised for the receiver.
1019 cron_setup_user($userto);
1020
a974c799 1021 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
aaf7a9dc 1022
39790bd8 1023 $headerdata = new stdClass();
a974c799 1024 $headerdata->sitename = format_string($site->fullname, true);
d1a62a50 1025 $headerdata->userprefs = $CFG->wwwroot.'/user/forum.php?id='.$userid.'&amp;course='.$site->id;
aaf7a9dc 1026
1027 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
1028 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
9c674431 1029
efd42060
BH
1030 $posthtml = '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p>'
1031 . '<br /><hr size="1" noshade="noshade" />';
aaf7a9dc 1032
a974c799 1033 foreach ($thesediscussions as $discussionid) {
aaf7a9dc 1034
3ef7279f 1035 core_php_time_limit::raise(120); // to be reset for each post
a974c799 1036
1037 $discussion = $discussions[$discussionid];
1038 $forum = $forums[$discussion->forum];
1039 $course = $courses[$forum->course];
1040 $cm = $coursemodules[$forum->id];
65b0e537 1041
9152fc99 1042 //override language
e8b7114d 1043 cron_setup_user($userto, $course);
9152fc99 1044
df1c2c71 1045 // Fill caches
1046 if (!isset($userto->viewfullnames[$forum->id])) {
bf0f06b1 1047 $modcontext = context_module::instance($cm->id);
df1c2c71 1048 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
1049 }
8b79a625 1050 if (!isset($userto->canpost[$discussion->id])) {
bf0f06b1 1051 $modcontext = context_module::instance($cm->id);
8b79a625 1052 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
df1c2c71 1053 }
caadf009 1054
de85c320 1055 $strforums = get_string('forums', 'forum');
59075a43 1056 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
8b79a625 1057 $canreply = $userto->canpost[$discussion->id];
bf0f06b1 1058 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
de85c320 1059
aaf7a9dc 1060 $posttext .= "\n \n";
1061 $posttext .= '=====================================================================';
1062 $posttext .= "\n \n";
8ebbb06a 1063 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
aaf7a9dc 1064 if ($discussion->name != $forum->name) {
c78ac798 1065 $posttext .= " -> ".format_string($discussion->name,true);
caadf009 1066 }
aaf7a9dc 1067 $posttext .= "\n";
3f213cd3
DNA
1068 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1069 $posttext .= "\n";
65b0e537 1070
aaf7a9dc 1071 $posthtml .= "<p><font face=\"sans-serif\">".
8ebbb06a 1072 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
aaf7a9dc 1073 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
3849dae8 1074 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
aaf7a9dc 1075 if ($discussion->name == $forum->name) {
1076 $posthtml .= "</font></p>";
caadf009 1077 } else {
c78ac798 1078 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
caadf009 1079 }
aaf7a9dc 1080 $posthtml .= '<p>';
1081
e1c6dde1 1082 $postsarray = $discussionposts[$discussionid];
1083 sort($postsarray);
00999605 1084 $sentcount = 0;
e1c6dde1 1085
857b798b 1086 foreach ($postsarray as $postid) {
a974c799 1087 $post = $posts[$postid];
1088
1089 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1090 $userfrom = $users[$post->userid];
103f34d8
PS
1091 if (!isset($userfrom->idnumber)) {
1092 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1093 forum_cron_minimise_user_record($userfrom);
1094 }
1095
4e445355 1096 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
103f34d8
PS
1097 forum_cron_minimise_user_record($userfrom);
1098 if ($userscount <= FORUM_CRON_USER_CACHE) {
1099 $userscount++;
1100 $users[$userfrom->id] = $userfrom;
1101 }
1102
df1c2c71 1103 } else {
a974c799 1104 mtrace('Could not find user '.$post->userid);
aaf7a9dc 1105 continue;
1106 }
1107
df1c2c71 1108 if (!isset($userfrom->groups[$forum->id])) {
1109 if (!isset($userfrom->groups)) {
1110 $userfrom->groups = array();
103f34d8
PS
1111 if (isset($users[$userfrom->id])) {
1112 $users[$userfrom->id]->groups = array();
1113 }
df1c2c71 1114 }
1115 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
103f34d8
PS
1116 if (isset($users[$userfrom->id])) {
1117 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1118 }
df1c2c71 1119 }
1120
c9fa2dee
AN
1121 // Headers to help prevent auto-responders.
1122 $userfrom->customheaders = array(
1123 "Precedence: Bulk",
1124 'X-Auto-Response-Suppress: All',
1125 'Auto-Submitted: auto-generated',
1126 );
857b798b 1127
8e08c731 1128 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
31793839
AN
1129 if (!isset($userto->canpost[$discussion->id])) {
1130 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
1131 } else {
1132 $canreply = $userto->canpost[$discussion->id];
1133 }
1134
1135 $data = new \mod_forum\output\forum_post_email(
1136 $course,
1137 $cm,
1138 $forum,
1139 $discussion,
1140 $post,
1141 $userfrom,
1142 $userto,
1143 $canreply
1144 );
1145
1146 if (!isset($userto->viewfullnames[$forum->id])) {
1147 $data->viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1148 } else {
1149 $data->viewfullnames = $userto->viewfullnames[$forum->id];
1150 }
857b798b 1151
31793839
AN
1152 if ($maildigest == 2) {
1153 // Subjects and link only.
1154 $posttext .= $textdigestbasicout->render($data);
1155 $posthtml .= $htmldigestbasicout->render($data);
857b798b 1156 } else {
31793839
AN
1157 // The full treatment.
1158 $posttext .= $textdigestfullout->render($data);
1159 $posthtml .= $htmldigestfullout->render($data);
df1c2c71 1160
31793839 1161 // Create an array of postid's for this user to mark as read.
90f4745c 1162 if (!$CFG->forum_usermarksread) {
1163 $userto->markposts[$post->id] = $post->id;
f37da850 1164 }
aaf7a9dc 1165 }
00999605 1166 $sentcount++;
aaf7a9dc 1167 }
b28118f6 1168 $footerlinks = array();
aaf7a9dc 1169 if ($canunsubscribe) {
b28118f6 1170 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
857b798b 1171 } else {
b28118f6 1172 $footerlinks[] = get_string("everyoneissubscribed", "forum");
aaf7a9dc 1173 }
b28118f6
AN
1174 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1175 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode('&nbsp;', $footerlinks) . '</font></div>';
aaf7a9dc 1176 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
caadf009 1177 }
caadf009 1178
6d2e6936 1179 if (empty($userto->mailformat) || $userto->mailformat != 1) {
379a42cb 1180 // This user DOESN'T want to receive HTML
1181 $posthtml = '';
1182 }
5e7f2b0b 1183
00999605
AN
1184 $eventdata = new \core\message\message();
1185 $eventdata->component = 'mod_forum';
1186 $eventdata->name = 'digests';
1187 $eventdata->userfrom = core_user::get_noreply_user();
1188 $eventdata->userto = $userto;
1189 $eventdata->subject = $postsubject;
1190 $eventdata->fullmessage = $posttext;
1191 $eventdata->fullmessageformat = FORMAT_PLAIN;
1192 $eventdata->fullmessagehtml = $posthtml;
1193 $eventdata->notification = 1;
1194 $eventdata->smallmessage = get_string('smallmessagedigest', 'forum', $sentcount);
1195 $mailresult = message_send($eventdata);
b58bd1a2
AD
1196
1197 if (!$mailresult) {
33c40cc6
DP
1198 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1199 "($userto->email)... not trying again.");
aaf7a9dc 1200 } else {
b140ae85 1201 mtrace("success.");
aaf7a9dc 1202 $usermailcount++;
e3ff14ca 1203
90f4745c 1204 // Mark post as read if forum_usermarksread is set off
1205 forum_tp_mark_posts_read($userto, $userto->markposts);
3d94772d 1206 }
caadf009 1207 }
caadf009 1208 }
226a1d9d 1209 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1210 set_config('digestmailtimelast', $timenow);
caadf009 1211 }
1212
e8b7114d 1213 cron_setup_user();
de85c320 1214
a974c799 1215 if (!empty($usermailcount)) {
b140ae85 1216 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
aaf7a9dc 1217 }
1218
8ad64455 1219 if (!empty($CFG->forum_lastreadclean)) {
f37da850 1220 $timenow = time();
8ad64455 1221 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1222 set_config('forum_lastreadclean', $timenow);
8cb121cc 1223 mtrace('Removing old forum read tracking info...');
f37da850 1224 forum_tp_clean_read_records();
1225 }
1226 } else {
8ad64455 1227 set_config('forum_lastreadclean', time());
f37da850 1228 }
1229
caadf009 1230 return true;
1231}
1232
0a4ac01b 1233/**
13bbe067 1234 *
1670305d 1235 * @param object $course
1236 * @param object $user
1237 * @param object $mod TODO this is not used in this function, refactor
1238 * @param object $forum
1239 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
0a4ac01b 1240 */
caadf009 1241function forum_user_outline($course, $user, $mod, $forum) {
1a96363a
NC
1242 global $CFG;
1243 require_once("$CFG->libdir/gradelib.php");
1244 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1245 if (empty($grades->items[0]->grades)) {
1246 $grade = false;
1247 } else {
1248 $grade = reset($grades->items[0]->grades);
1249 }
1250
1251 $count = forum_count_user_posts($forum->id, $user->id);
1252
1253 if ($count && $count->postcount > 0) {
39790bd8 1254 $result = new stdClass();
1a96363a
NC
1255 $result->info = get_string("numposts", "forum", $count->postcount);
1256 $result->time = $count->lastpost;
1257 if ($grade) {
1258 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
90f4745c 1259 }
1a96363a
NC
1260 return $result;
1261 } else if ($grade) {
39790bd8 1262 $result = new stdClass();
1a96363a 1263 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
4433f871
AD
1264
1265 //datesubmitted == time created. dategraded == time modified or time overridden
1266 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
94a74f54 1267 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
4433f871
AD
1268 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1269 $result->time = $grade->dategraded;
1270 } else {
1271 $result->time = $grade->datesubmitted;
1272 }
1273
1a96363a 1274 return $result;
caadf009 1275 }
1276 return NULL;
1277}
1278
1279
0a4ac01b 1280/**
df1ba0f4 1281 * @global object
1282 * @global object
1283 * @param object $coure
1284 * @param object $user
1285 * @param object $mod
1286 * @param object $forum
0a4ac01b 1287 */
caadf009 1288function forum_user_complete($course, $user, $mod, $forum) {
1a96363a
NC
1289 global $CFG,$USER, $OUTPUT;
1290 require_once("$CFG->libdir/gradelib.php");
1291
1292 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1293 if (!empty($grades->items[0]->grades)) {
1294 $grade = reset($grades->items[0]->grades);
1295 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1296 if ($grade->str_feedback) {
1297 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1298 }
1299 }
caadf009 1300
1f48942e 1301 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
e3ff14ca 1302
65bcf17b 1303 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
12e57b92 1304 print_error('invalidcoursemodule');
65bcf17b 1305 }
90f4745c 1306 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
65bcf17b 1307
1308 foreach ($posts as $post) {
5e7f2b0b 1309 if (!isset($discussions[$post->discussion])) {
90f4745c 1310 continue;
1311 }
7a8d8f22 1312 $discussion = $discussions[$post->discussion];
5e7f2b0b 1313
63e87951 1314 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
5e7f2b0b 1315 }
caadf009 1316 } else {
41905731 1317 echo "<p>".get_string("noposts", "forum")."</p>";
caadf009 1318 }
caadf009 1319}
1320
8538c562
DM
1321/**
1322 * Filters the forum discussions according to groups membership and config.
1323 *
1324 * @since Moodle 2.8, 2.7.1, 2.6.4
1325 * @param array $discussions Discussions with new posts array
1326 * @return array Forums with the number of new posts
1327 */
1328function forum_filter_user_groups_discussions($discussions) {
c38965fb 1329
8538c562
DM
1330 // Group the remaining discussions posts by their forumid.
1331 $filteredforums = array();
c38965fb 1332
8538c562
DM
1333 // Discard not visible groups.
1334 foreach ($discussions as $discussion) {
c38965fb 1335
8538c562
DM
1336 // Course data is already cached.
1337 $instances = get_fast_modinfo($discussion->course)->get_instances();
1338 $forum = $instances['forum'][$discussion->forum];
5e7f2b0b 1339
8538c562
DM
1340 // Continue if the user should not see this discussion.
1341 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1342 continue;
1343 }
1344
1345 // Grouping results by forum.
1346 if (empty($filteredforums[$forum->instance])) {
1347 $filteredforums[$forum->instance] = new stdClass();
1348 $filteredforums[$forum->instance]->id = $forum->id;
1349 $filteredforums[$forum->instance]->count = 0;
1350 }
1351 $filteredforums[$forum->instance]->count += $discussion->count;
1352
1353 }
1354
1355 return $filteredforums;
1356}
1357
1358/**
1359 * Returns whether the discussion group is visible by the current user or not.
1360 *
1361 * @since Moodle 2.8, 2.7.1, 2.6.4
1362 * @param cm_info $cm The discussion course module
1363 * @param int $discussiongroupid The discussion groupid
1364 * @return bool
1365 */
1366function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1367
1368 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1369 return true;
1370 }
1371
1372 if (isguestuser()) {
1373 return false;
1374 }
1375
1376 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1377 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1378 return true;
1379 }
1380
1381 return false;
1382}
5e7f2b0b 1383
0a4ac01b 1384/**
df1ba0f4 1385 * @global object
1386 * @global object
1387 * @global object
1388 * @param array $courses
1389 * @param array $htmlarray
0a4ac01b 1390 */
185cfb09 1391function forum_print_overview($courses,&$htmlarray) {
261c6ef0 1392 global $USER, $CFG, $DB, $SESSION;
493f0820 1393
185cfb09 1394 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1395 return array();
1396 }
f8716988 1397
185cfb09 1398 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
f8716988 1399 return;
1400 }
185cfb09 1401
ba4ee840
DM
1402 // Courses to search for new posts
1403 $coursessqls = array();
4e445355 1404 $params = array();
185cfb09 1405 foreach ($courses as $course) {
ba4ee840
DM
1406
1407 // If the user has never entered into the course all posts are pending
1408 if ($course->lastaccess == 0) {
8538c562 1409 $coursessqls[] = '(d.course = ?)';
ba4ee840
DM
1410 $params[] = $course->id;
1411
1412 // Only posts created after the course last access
1413 } else {
8538c562 1414 $coursessqls[] = '(d.course = ? AND p.created > ?)';
ba4ee840
DM
1415 $params[] = $course->id;
1416 $params[] = $course->lastaccess;
1417 }
185cfb09 1418 }
4e445355 1419 $params[] = $USER->id;
ba4ee840
DM
1420 $coursessql = implode(' OR ', $coursessqls);
1421
8538c562
DM
1422 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1423 .'FROM {forum_discussions} d '
ba4ee840
DM
1424 .'JOIN {forum_posts} p ON p.discussion = d.id '
1425 ."WHERE ($coursessql) "
1426 .'AND p.userid != ? '
6667ebb9 1427 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
81ba2632
JH
1428 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1429 .'ORDER BY d.course, d.forum';
6667ebb9
AN
1430 $params[] = time();
1431 $params[] = time();
2b63df96 1432
8538c562
DM
1433 // Avoid warnings.
1434 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1435 $discussions = array();
185cfb09 1436 }
2b63df96 1437
8538c562
DM
1438 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1439
185cfb09 1440 // also get all forum tracking stuff ONCE.
1441 $trackingforums = array();
1442 foreach ($forums as $forum) {
1443 if (forum_tp_can_track_forums($forum)) {
1444 $trackingforums[$forum->id] = $forum;
1445 }
1446 }
2b63df96 1447
185cfb09 1448 if (count($trackingforums) > 0) {
1449 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1450 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
4e445355 1451 ' FROM {forum_posts} p '.
1452 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1453 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1454 $params = array($USER->id);
1455
d3553951 1456 foreach ($trackingforums as $track) {
4e445355 1457 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1458 $params[] = $track->id;
261c6ef0 1459 if (isset($SESSION->currentgroup[$track->course])) {
1460 $groupid = $SESSION->currentgroup[$track->course];
1461 } else {
0209f964
PS
1462 // get first groupid
1463 $groupids = groups_get_all_groups($track->course, $USER->id);
1464 if ($groupids) {
1465 reset($groupids);
1466 $groupid = key($groupids);
261c6ef0 1467 $SESSION->currentgroup[$track->course] = $groupid;
1468 } else {
1469 $groupid = 0;
1470 }
0209f964 1471 unset($groupids);
261c6ef0 1472 }
1473 $params[] = $groupid;
185cfb09 1474 }
1475 $sql = substr($sql,0,-3); // take off the last OR
6667ebb9
AN
1476 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1477 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1478 $sql .= 'GROUP BY d.forum,d.course';
4e445355 1479 $params[] = $cutoffdate;
6667ebb9
AN
1480 $params[] = time();
1481 $params[] = time();
185cfb09 1482
4e445355 1483 if (!$unread = $DB->get_records_sql($sql, $params)) {
185cfb09 1484 $unread = array();
1485 }
1486 } else {
1487 $unread = array();
95d71ad3 1488 }
185cfb09 1489
8538c562 1490 if (empty($unread) and empty($forumsnewposts)) {
9cba7a8c 1491 return;
1492 }
1493
1494 $strforum = get_string('modulename','forum');
9cba7a8c 1495
f8716988 1496 foreach ($forums as $forum) {
185cfb09 1497 $str = '';
f8716988 1498 $count = 0;
185cfb09 1499 $thisunread = 0;
f8716988 1500 $showunread = false;
1501 // either we have something from logs, or trackposts, or nothing.
8538c562
DM
1502 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1503 $count = $forumsnewposts[$forum->id]->count;
90558ec4 1504 }
185cfb09 1505 if (array_key_exists($forum->id,$unread)) {
1506 $thisunread = $unread[$forum->id]->count;
f8716988 1507 $showunread = true;
0d6b9d4f 1508 }
185cfb09 1509 if ($count > 0 || $thisunread > 0) {
e23800b7 1510 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1511 $forum->name.'</a></div>';
6d641063 1512 $str .= '<div class="info"><span class="postsincelogin">';
54294601 1513 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
f8716988 1514 if (!empty($showunread)) {
54294601 1515 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
f8716988 1516 }
e23800b7 1517 $str .= '</div></div>';
f8716988 1518 }
2b63df96 1519 if (!empty($str)) {
185cfb09 1520 if (!array_key_exists($forum->course,$htmlarray)) {
1521 $htmlarray[$forum->course] = array();
1522 }
1523 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1524 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1525 }
1526 $htmlarray[$forum->course]['forum'] .= $str;
1527 }
2b63df96 1528 }
0d6b9d4f 1529}
1530
0a4ac01b 1531/**
1532 * Given a course and a date, prints a summary of all the new
1533 * messages posted in the course since that date
df1ba0f4 1534 *
1535 * @global object
1536 * @global object
1537 * @global object
1538 * @uses CONTEXT_MODULE
1539 * @uses VISIBLEGROUPS
90f4745c 1540 * @param object $course
1541 * @param bool $viewfullnames capability
1542 * @param int $timestart
1543 * @return bool success
0a4ac01b 1544 */
dd97c328 1545function forum_print_recent_activity($course, $viewfullnames, $timestart) {
cb860491 1546 global $CFG, $USER, $DB, $OUTPUT;
caadf009 1547
dd97c328 1548 // do not use log table if possible, it may be huge and is expensive to join with other tables
caadf009 1549
dda60f88 1550 $allnamefields = user_picture::fields('u', null, 'duserid');
4e445355 1551 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
dda60f88 1552 d.timestart, d.timeend, $allnamefields
4e445355 1553 FROM {forum_posts} p
1554 JOIN {forum_discussions} d ON d.id = p.discussion
1555 JOIN {forum} f ON f.id = d.forum
1556 JOIN {user} u ON u.id = p.userid
1557 WHERE p.created > ? AND f.course = ?
1558 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
dd97c328 1559 return false;
1b5910c4 1560 }
1561
f20edd52 1562 $modinfo = get_fast_modinfo($course);
dcde9f02 1563
dd97c328 1564 $groupmodes = array();
1565 $cms = array();
d05956ac 1566
dd97c328 1567 $strftimerecent = get_string('strftimerecent');
d05956ac 1568
dd97c328 1569 $printposts = array();
1570 foreach ($posts as $post) {
1571 if (!isset($modinfo->instances['forum'][$post->forum])) {
1572 // not visible
1573 continue;
1574 }
1575 $cm = $modinfo->instances['forum'][$post->forum];
1576 if (!$cm->uservisible) {
1577 continue;
1578 }
bf0f06b1 1579 $context = context_module::instance($cm->id);
6b7de0bb 1580
1581 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1582 continue;
1583 }
583b57b4 1584
dd97c328 1585 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1586 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
6b7de0bb 1587 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
dd97c328 1588 continue;
ac1d9a22 1589 }
dd97c328 1590 }
583b57b4 1591
8538c562
DM
1592 // Check that the user can see the discussion.
1593 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1594 $printposts[] = $post;
dd97c328 1595 }
8f7dc7f1 1596
dd97c328 1597 }
1598 unset($posts);
8f7dc7f1 1599
dd97c328 1600 if (!$printposts) {
1601 return false;
1602 }
1603
cb860491 1604 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
af0fc6a2 1605 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
dd97c328 1606
1607 foreach ($printposts as $post) {
1608 $subjectclass = empty($post->parent) ? ' bold' : '';
af0fc6a2 1609 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
dd97c328 1610
af0fc6a2
JP
1611 $list .= html_writer::start_tag('li');
1612 $list .= html_writer::start_div('head');
1613 $list .= html_writer::div(userdate($post->modified, $strftimerecent), 'date');
1614 if (!$authorhidden) {
1615 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
1616 }
1617 $list .= html_writer::end_div(); // Head.
1618
1619 $list .= html_writer::start_div('info' . $subjectclass);
1620 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
1621 if (!empty($post->parent)) {
1622 $discussionurl->param('parent', $post->parent);
1623 $discussionurl->set_anchor('p'. $post->id);
caadf009 1624 }
dd97c328 1625 $post->subject = break_up_long_words(format_string($post->subject, true));
af0fc6a2
JP
1626 $list .= html_writer::link($discussionurl, $post->subject);
1627 $list .= html_writer::end_div(); // Info.
1628 $list .= html_writer::end_tag('li');
caadf009 1629 }
dd97c328 1630
af0fc6a2
JP
1631 $list .= html_writer::end_tag('ul');
1632 echo $list;
dd97c328 1633
1634 return true;
caadf009 1635}
1636
353228d8 1637/**
1638 * Return grade for given user or all users.
1639 *
df1ba0f4 1640 * @global object
1641 * @global object
1642 * @param object $forum
353228d8 1643 * @param int $userid optional user id, 0 means all users
1644 * @return array array of grades, false if none
1645 */
2b04c41c 1646function forum_get_user_grades($forum, $userid = 0) {
63e87951 1647 global $CFG;
df997f84 1648
63e87951 1649 require_once($CFG->dirroot.'/rating/lib.php');
df997f84 1650
2b04c41c
SH
1651 $ratingoptions = new stdClass;
1652 $ratingoptions->component = 'mod_forum';
1653 $ratingoptions->ratingarea = 'post';
353228d8 1654
63e87951
AD
1655 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1656 $ratingoptions->modulename = 'forum';
1657 $ratingoptions->moduleid = $forum->id;
63e87951
AD
1658 $ratingoptions->userid = $userid;
1659 $ratingoptions->aggregationmethod = $forum->assessed;
1660 $ratingoptions->scaleid = $forum->scale;
1661 $ratingoptions->itemtable = 'forum_posts';
1662 $ratingoptions->itemtableusercolumn = 'userid';
353228d8 1663
2b04c41c 1664 $rm = new rating_manager();
63e87951 1665 return $rm->get_user_grades($ratingoptions);
353228d8 1666}
caadf009 1667
0a4ac01b 1668/**
775f811a 1669 * Update activity grades
353228d8 1670 *
a153c9f2 1671 * @category grade
775f811a 1672 * @param object $forum
1673 * @param int $userid specific user only, 0 means all
6b7de0bb 1674 * @param boolean $nullifnone return null if grade does not exist
90f4745c 1675 * @return void
0a4ac01b 1676 */
775f811a 1677function forum_update_grades($forum, $userid=0, $nullifnone=true) {
4e445355 1678 global $CFG, $DB;
775f811a 1679 require_once($CFG->libdir.'/gradelib.php');
caadf009 1680
775f811a 1681 if (!$forum->assessed) {
1682 forum_grade_item_update($forum);
02ebf404 1683
775f811a 1684 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1685 forum_grade_item_update($forum, $grades);
eafb9d9e 1686
775f811a 1687 } else if ($userid and $nullifnone) {
39790bd8 1688 $grade = new stdClass();
775f811a 1689 $grade->userid = $userid;
1690 $grade->rawgrade = NULL;
1691 forum_grade_item_update($forum, $grade);
02ebf404 1692
353228d8 1693 } else {
775f811a 1694 forum_grade_item_update($forum);
1695 }
1696}
1697
353228d8 1698/**
612607bd 1699 * Create/update grade item for given forum
353228d8 1700 *
a153c9f2 1701 * @category grade
df1ba0f4 1702 * @uses GRADE_TYPE_NONE
1703 * @uses GRADE_TYPE_VALUE
1704 * @uses GRADE_TYPE_SCALE
a153c9f2
AD
1705 * @param stdClass $forum Forum object with extra cmidnumber
1706 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 1707 * @return int 0 if ok
353228d8 1708 */
0b5a80a1 1709function forum_grade_item_update($forum, $grades=NULL) {
612607bd 1710 global $CFG;
1711 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1712 require_once($CFG->libdir.'/gradelib.php');
353228d8 1713 }
1714
612607bd 1715 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
353228d8 1716
5980d52f 1717 if (!$forum->assessed or $forum->scale == 0) {
612607bd 1718 $params['gradetype'] = GRADE_TYPE_NONE;
353228d8 1719
1720 } else if ($forum->scale > 0) {
1721 $params['gradetype'] = GRADE_TYPE_VALUE;
1722 $params['grademax'] = $forum->scale;
1723 $params['grademin'] = 0;
1724
1725 } else if ($forum->scale < 0) {
1726 $params['gradetype'] = GRADE_TYPE_SCALE;
1727 $params['scaleid'] = -$forum->scale;
1728 }
1729
0b5a80a1 1730 if ($grades === 'reset') {
1731 $params['reset'] = true;
1732 $grades = NULL;
1733 }
1734
1735 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
353228d8 1736}
1737
1738/**
1739 * Delete grade item for given forum
1740 *
a153c9f2
AD
1741 * @category grade
1742 * @param stdClass $forum Forum object
1743 * @return grade_item
353228d8 1744 */
1745function forum_grade_item_delete($forum) {
612607bd 1746 global $CFG;
1747 require_once($CFG->libdir.'/gradelib.php');
1748
b67ec72f 1749 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
caadf009 1750}
1751
353228d8 1752
0a4ac01b 1753/**
90f4745c 1754 * This function returns if a scale is being used by one forum
df1ba0f4 1755 *
1756 * @global object
90f4745c 1757 * @param int $forumid
1758 * @param int $scaleid negative number
1759 * @return bool
0a4ac01b 1760 */
0f1a97c2 1761function forum_scale_used ($forumid,$scaleid) {
4e445355 1762 global $DB;
0f1a97c2 1763 $return = false;
65b0e537 1764
4e445355 1765 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
65b0e537 1766
fa22fd5f 1767 if (!empty($rec) && !empty($scaleid)) {
0f1a97c2 1768 $return = true;
1769 }
65b0e537 1770
0f1a97c2 1771 return $return;
1772}
1773
85c9ebb9 1774/**
1775 * Checks if scale is being used by any instance of forum
1776 *
1777 * This is used to find out if scale used anywhere
df1ba0f4 1778 *
1779 * @global object
85c9ebb9 1780 * @param $scaleid int
1781 * @return boolean True if the scale is used by any forum
1782 */
1783function forum_scale_used_anywhere($scaleid) {
4e445355 1784 global $DB;
1785 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
85c9ebb9 1786 return true;
1787 } else {
1788 return false;
1789 }
1790}
1791
0a4ac01b 1792// SQL FUNCTIONS ///////////////////////////////////////////////////////////
9fa49e22 1793
0a4ac01b 1794/**
1795 * Gets a post with all info ready for forum_print_post
1796 * Most of these joins are just to get the forum id
df1ba0f4 1797 *
1798 * @global object
1799 * @global object
90f4745c 1800 * @param int $postid
1801 * @return mixed array of posts or false
0a4ac01b 1802 */
1f48942e 1803function forum_get_post_full($postid) {
4e445355 1804 global $CFG, $DB;
1f48942e 1805
a327f25e
AG
1806 $allnames = get_all_user_name_fields(true, 'u');
1807 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 1808 FROM {forum_posts} p
1809 JOIN {forum_discussions} d ON p.discussion = d.id
1810 LEFT JOIN {user} u ON p.userid = u.id
1811 WHERE p.id = ?", array($postid));
1f48942e 1812}
1813
65bcf17b 1814/**
1815 * Gets all posts in discussion including top parent.
df1ba0f4 1816 *
1817 * @global object
1818 * @global object
1819 * @global object
90f4745c 1820 * @param int $discussionid
1821 * @param string $sort
1822 * @param bool $tracking does user track the forum?
1823 * @return array of posts
65bcf17b 1824 */
90f4745c 1825function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
4e445355 1826 global $CFG, $DB, $USER;
65bcf17b 1827
3c2bf848 1828 $tr_sel = "";
1829 $tr_join = "";
4e445355 1830 $params = array();
3c2bf848 1831
90f4745c 1832 if ($tracking) {
90f4745c 1833 $tr_sel = ", fr.id AS postread";
4e445355 1834 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1835 $params[] = $USER->id;
90f4745c 1836 }
1837
a327f25e 1838 $allnames = get_all_user_name_fields(true, 'u');
4e445355 1839 $params[] = $discussionid;
a327f25e 1840 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
4e445355 1841 FROM {forum_posts} p
1842 LEFT JOIN {user} u ON p.userid = u.id
90f4745c 1843 $tr_join
4e445355 1844 WHERE p.discussion = ?
1845 ORDER BY $sort", $params)) {
65bcf17b 1846 return array();
1847 }
1848
1849 foreach ($posts as $pid=>$p) {
90f4745c 1850 if ($tracking) {
1851 if (forum_tp_is_post_old($p)) {
6b7de0bb 1852 $posts[$pid]->postread = true;
90f4745c 1853 }
1854 }
65bcf17b 1855 if (!$p->parent) {
1856 continue;
1857 }
1858 if (!isset($posts[$p->parent])) {
1859 continue; // parent does not exist??
1860 }
1861 if (!isset($posts[$p->parent]->children)) {
1862 $posts[$p->parent]->children = array();
1863 }
1864 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1865 }
1866
bfa7bece
AN
1867 // Start with the last child of the first post.
1868 $post = &$posts[reset($posts)->id];
1869
1870 $lastpost = false;
1871 while (!$lastpost) {
1872 if (!isset($post->children)) {
1873 $post->lastpost = true;
1874 $lastpost = true;
1875 } else {
1876 // Go to the last child of this post.
1877 $post = &$posts[end($post->children)->id];
1878 }
1879 }
1880
65bcf17b 1881 return $posts;
1882}
1883
42fb3c85 1884/**
1885 * An array of forum objects that the user is allowed to read/search through.
df1ba0f4 1886 *
1887 * @global object
1888 * @global object
1889 * @global object
1890 * @param int $userid
1891 * @param int $courseid if 0, we look for forums throughout the whole site.
42fb3c85 1892 * @return array of forum objects, or false if no matches
1893 * Forum objects have the following attributes:
1894 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1895 * viewhiddentimedposts
1896 */
1897function forum_get_readable_forums($userid, $courseid=0) {
2b63df96 1898
4e445355 1899 global $CFG, $DB, $USER;
6b7de0bb 1900 require_once($CFG->dirroot.'/course/lib.php');
2b63df96 1901
4e445355 1902 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
12e57b92 1903 print_error('notinstalled', 'forum');
42fb3c85 1904 }
2b63df96 1905
42fb3c85 1906 if ($courseid) {
4e445355 1907 $courses = $DB->get_records('course', array('id' => $courseid));
42fb3c85 1908 } else {
65bcf17b 1909 // If no course is specified, then the user can see SITE + his courses.
4e445355 1910 $courses1 = $DB->get_records('course', array('id' => SITEID));
b1d5d015 1911 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
6155150c 1912 $courses = array_merge($courses1, $courses2);
42fb3c85 1913 }
1914 if (!$courses) {
6b7de0bb 1915 return array();
42fb3c85 1916 }
1917
1918 $readableforums = array();
2b63df96 1919
6527b5c2 1920 foreach ($courses as $course) {
1921
f20edd52 1922 $modinfo = get_fast_modinfo($course);
2b63df96 1923
6b7de0bb 1924 if (empty($modinfo->instances['forum'])) {
1925 // hmm, no forums?
1926 continue;
1927 }
2b63df96 1928
4e445355 1929 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2b63df96 1930
6b7de0bb 1931 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1932 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1933 continue;
1934 }
bf0f06b1 1935 $context = context_module::instance($cm->id);
6b7de0bb 1936 $forum = $courseforums[$forumid];
2e945910
AB
1937 $forum->context = $context;
1938 $forum->cm = $cm;
d50704bf 1939
6b7de0bb 1940 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1941 continue;
1942 }
6527b5c2 1943
6b7de0bb 1944 /// group access
1945 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2c1bbbc5
MG
1946
1947 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1948 $forum->onlygroups[] = -1;
6b7de0bb 1949 }
2b63df96 1950
6b7de0bb 1951 /// hidden timed discussions
1952 $forum->viewhiddentimedposts = true;
1953 if (!empty($CFG->forum_enabletimedposts)) {
1954 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1955 $forum->viewhiddentimedposts = false;
1956 }
1957 }
d50704bf 1958
6b7de0bb 1959 /// qanda access
1960 if ($forum->type == 'qanda'
1961 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2b63df96 1962
6b7de0bb 1963 // We need to check whether the user has posted in the qanda forum.
1964 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1965 // the user is allowed to see in this forum.
1966 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1967 foreach ($discussionspostedin as $d) {
1968 $forum->onlydiscussions[] = $d->id;
d50704bf 1969 }
42fb3c85 1970 }
1971 }
6b7de0bb 1972
1973 $readableforums[$forum->id] = $forum;
42fb3c85 1974 }
6b7de0bb 1975
1976 unset($modinfo);
1977
42fb3c85 1978 } // End foreach $courses
2b63df96 1979
42fb3c85 1980 return $readableforums;
1981}
1982
bbbf2d40 1983/**
1984 * Returns a list of posts found using an array of search terms.
df1ba0f4 1985 *
1986 * @global object
1987 * @global object
1988 * @global object
1989 * @param array $searchterms array of search terms, e.g. word +word -word
1990 * @param int $courseid if 0, we search through the whole site
1991 * @param int $limitfrom
1992 * @param int $limitnum
1993 * @param int &$totalcount
1994 * @param string $extrasql
1995 * @return array|bool Array of posts found or false
42fb3c85 1996 */
2b63df96 1997function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
42fb3c85 1998 &$totalcount, $extrasql='') {
4e445355 1999 global $CFG, $DB, $USER;
42fb3c85 2000 require_once($CFG->libdir.'/searchlib.php');
2001
2002 $forums = forum_get_readable_forums($USER->id, $courseid);
2b63df96 2003
67875aa1 2004 if (count($forums) == 0) {
6b7de0bb 2005 $totalcount = 0;
67875aa1 2006 return false;
2007 }
42fb3c85 2008
6b7de0bb 2009 $now = round(time(), -2); // db friendly
2010
2011 $fullaccess = array();
2012 $where = array();
4e445355 2013 $params = array();
6b7de0bb 2014
2015 foreach ($forums as $forumid => $forum) {
2016 $select = array();
2017
2018 if (!$forum->viewhiddentimedposts) {
b1d5d015
PS
2019 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2020 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
42fb3c85 2021 }
6b7de0bb 2022
2e945910
AB
2023 $cm = $forum->cm;
2024 $context = $forum->context;
ad9c22aa 2025
2026 if ($forum->type == 'qanda'
2027 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
6b7de0bb 2028 if (!empty($forum->onlydiscussions)) {
cf717dc2 2029 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
4e445355 2030 $params = array_merge($params, $discussionid_params);
2031 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
d50704bf 2032 } else {
6b7de0bb 2033 $select[] = "p.parent = 0";
d50704bf 2034 }
2035 }
6b7de0bb 2036
2037 if (!empty($forum->onlygroups)) {
cf717dc2 2038 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
4e445355 2039 $params = array_merge($params, $groupid_params);
2040 $select[] = "d.groupid $groupid_sql";
42fb3c85 2041 }
6b7de0bb 2042
2043 if ($select) {
2044 $selects = implode(" AND ", $select);
b1d5d015
PS
2045 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2046 $params['forum'.$forumid] = $forumid;
6b7de0bb 2047 } else {
2048 $fullaccess[] = $forumid;
2049 }
2050 }
2051
2052 if ($fullaccess) {
cf717dc2 2053 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
4e445355 2054 $params = array_merge($params, $fullid_params);
2055 $where[] = "(d.forum $fullid_sql)";
42fb3c85 2056 }
42fb3c85 2057
6b7de0bb 2058 $selectdiscussion = "(".implode(" OR ", $where).")";
42fb3c85 2059
42fb3c85 2060 $messagesearch = '';
2061 $searchstring = '';
2b63df96 2062
42fb3c85 2063 // Need to concat these back together for parser to work.
2064 foreach($searchterms as $searchterm){
2065 if ($searchstring != '') {
2066 $searchstring .= ' ';
2067 }
2068 $searchstring .= $searchterm;
2069 }
2070
2071 // We need to allow quoted strings for the search. The quotes *should* be stripped
2072 // by the parser, but this should be examined carefully for security implications.
2073 $searchstring = str_replace("\\\"","\"",$searchstring);
2074 $parser = new search_parser();
2075 $lexer = new search_lexer($parser);
2076
2077 if ($lexer->parse($searchstring)) {
2078 $parsearray = $parser->get_parsed_array();
2f194173
AN
2079 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2080 'p.userid', 'u.id', 'u.firstname',
2081 'u.lastname', 'p.modified', 'd.forum');
004efe66 2082 $params = array_merge($params, $msparams);
42fb3c85 2083 }
2084
4e445355 2085 $fromsql = "{forum_posts} p,
2086 {forum_discussions} d,
2087 {user} u";
42fb3c85 2088
2089 $selectsql = " $messagesearch
2090 AND p.discussion = d.id
2091 AND p.userid = u.id
2092 AND $selectdiscussion
2093 $extrasql";
2094
2095 $countsql = "SELECT COUNT(*)
2096 FROM $fromsql
2097 WHERE $selectsql";
2098
a327f25e 2099 $allnames = get_all_user_name_fields(true, 'u');
7f094149 2100 $searchsql = "SELECT p.*,
42fb3c85 2101 d.forum,
a327f25e 2102 $allnames,
42fb3c85 2103 u.email,
8ba59d07 2104 u.picture,
ce7382c9 2105 u.imagealt
42fb3c85 2106 FROM $fromsql
2107 WHERE $selectsql
2108 ORDER BY p.modified DESC";
2109
4e445355 2110 $totalcount = $DB->count_records_sql($countsql, $params);
d50704bf 2111
4e445355 2112 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
42fb3c85 2113}
2114
0a4ac01b 2115/**
2116 * Returns a list of all new posts that have not been mailed yet
df1ba0f4 2117 *
df1ba0f4 2118 * @param int $starttime posts created after this time
2119 * @param int $endtime posts created before this
2120 * @param int $now used for timed discussions only
2121 * @return array
0a4ac01b 2122 */
90f4745c 2123function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
4e445355 2124 global $CFG, $DB;
90f4745c 2125
8076010d
MN
2126 $params = array();
2127 $params['mailed'] = FORUM_MAILED_PENDING;
2128 $params['ptimestart'] = $starttime;
2129 $params['ptimeend'] = $endtime;
2130 $params['mailnow'] = 1;
2131
90f4745c 2132 if (!empty($CFG->forum_enabletimedposts)) {
2133 if (empty($now)) {
2134 $now = time();
2135 }
86a77c91
JM
2136 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2137 $params['pptimestart'] = $starttime;
8076010d
MN
2138 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2139 $params['dtimestart'] = $now;
2140 $params['dtimeend'] = $now;
90f4745c 2141 } else {
2142 $timedsql = "";
86a77c91 2143 $selectsql = "AND p.created >= :ptimestart";
90f4745c 2144 }
2145
4e445355 2146 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
8076010d
MN
2147 FROM {forum_posts} p
2148 JOIN {forum_discussions} d ON d.id = p.discussion
2149 WHERE p.mailed = :mailed
86a77c91 2150 $selectsql
8076010d
MN
2151 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2152 $timedsql
2153 ORDER BY p.modified ASC", $params);
1f48942e 2154}
2155
0a4ac01b 2156/**
2157 * Marks posts before a certain time as being mailed already
df1ba0f4 2158 *
2159 * @global object
2160 * @global object
2161 * @param int $endtime
2162 * @param int $now Defaults to time()
2163 * @return bool
0a4ac01b 2164 */
90f4745c 2165function forum_mark_old_posts_as_mailed($endtime, $now=null) {
4e445355 2166 global $CFG, $DB;
8076010d 2167
90f4745c 2168 if (empty($now)) {
2169 $now = time();
2170 }
2171
8076010d
MN
2172 $params = array();
2173 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2174 $params['now'] = $now;
2175 $params['endtime'] = $endtime;
2176 $params['mailnow'] = 1;
2177 $params['mailedpending'] = FORUM_MAILED_PENDING;
2178
90f4745c 2179 if (empty($CFG->forum_enabletimedposts)) {
4e445355 2180 return $DB->execute("UPDATE {forum_posts}
8076010d
MN
2181 SET mailed = :mailedsuccess
2182 WHERE (created < :endtime OR mailnow = :mailnow)
2183 AND mailed = :mailedpending", $params);
0f620d4b 2184 } else {
4e445355 2185 return $DB->execute("UPDATE {forum_posts}
8076010d 2186 SET mailed = :mailedsuccess
90f4745c 2187 WHERE discussion NOT IN (SELECT d.id
8076010d
MN
2188 FROM {forum_discussions} d
2189 WHERE d.timestart > :now)
2190 AND (created < :endtime OR mailnow = :mailnow)
2191 AND mailed = :mailedpending", $params);
0f620d4b 2192 }
3ecca1ee 2193}
2194
0a4ac01b 2195/**
2196 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2197 *
2198 * @global object
2199 * @global object
2200 * @uses CONTEXT_MODULE
2201 * @return array
0a4ac01b 2202 */
1f48942e 2203function forum_get_user_posts($forumid, $userid) {
4e445355 2204 global $CFG, $DB;
1f48942e 2205
90f4745c 2206 $timedsql = "";
4e445355 2207 $params = array($forumid, $userid);
2208
90f4745c 2209 if (!empty($CFG->forum_enabletimedposts)) {
2210 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2211 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2212 $now = time();
4e445355 2213 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2214 $params[] = $now;
2215 $params[] = $now;
6b7de0bb 2216 }
90f4745c 2217 }
2218
a327f25e
AG
2219 $allnames = get_all_user_name_fields(true, 'u');
2220 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 2221 FROM {forum} f
2222 JOIN {forum_discussions} d ON d.forum = f.id
2223 JOIN {forum_posts} p ON p.discussion = d.id
2224 JOIN {user} u ON u.id = p.userid
2225 WHERE f.id = ?
2226 AND p.userid = ?
90f4745c 2227 $timedsql
4e445355 2228 ORDER BY p.modified ASC", $params);
1f48942e 2229}
2230
90f4745c 2231/**
2232 * Get all the discussions user participated in
df1ba0f4 2233 *
2234 * @global object
2235 * @global object
2236 * @uses CONTEXT_MODULE
90f4745c 2237 * @param int $forumid
2238 * @param int $userid
df1ba0f4 2239 * @return array Array or false
90f4745c 2240 */
2241function forum_get_user_involved_discussions($forumid, $userid) {
4e445355 2242 global $CFG, $DB;
90f4745c 2243
2244 $timedsql = "";
4e445355 2245 $params = array($forumid, $userid);
90f4745c 2246 if (!empty($CFG->forum_enabletimedposts)) {
2247 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2248 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2249 $now = time();
4e445355 2250 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2251 $params[] = $now;
2252 $params[] = $now;
6b7de0bb 2253 }
90f4745c 2254 }
2255
4e445355 2256 return $DB->get_records_sql("SELECT DISTINCT d.*
2257 FROM {forum} f
2258 JOIN {forum_discussions} d ON d.forum = f.id
2259 JOIN {forum_posts} p ON p.discussion = d.id
2260 WHERE f.id = ?
2261 AND p.userid = ?
2262 $timedsql", $params);
90f4745c 2263}
2264
2265/**
2266 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2267 *
2268 * @global object
2269 * @global object
90f4745c 2270 * @param int $forumid
2271 * @param int $userid
2272 * @return array of counts or false
2273 */
2274function forum_count_user_posts($forumid, $userid) {
4e445355 2275 global $CFG, $DB;
90f4745c 2276
2277 $timedsql = "";
4e445355 2278 $params = array($forumid, $userid);
90f4745c 2279 if (!empty($CFG->forum_enabletimedposts)) {
2280 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2281 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2282 $now = time();
4e445355 2283 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2284 $params[] = $now;
2285 $params[] = $now;
6b7de0bb 2286 }
90f4745c 2287 }
2288
4e445355 2289 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2290 FROM {forum} f
2291 JOIN {forum_discussions} d ON d.forum = f.id
2292 JOIN {forum_posts} p ON p.discussion = d.id
2293 JOIN {user} u ON u.id = p.userid
2294 WHERE f.id = ?
2295 AND p.userid = ?
2296 $timedsql", $params);
90f4745c 2297}
2298
0a4ac01b 2299/**
2300 * Given a log entry, return the forum post details for it.
df1ba0f4 2301 *
2302 * @global object
2303 * @global object
2304 * @param object $log
2305 * @return array|null
0a4ac01b 2306 */
1f48942e 2307function forum_get_post_from_log($log) {
4e445355 2308 global $CFG, $DB;
1f48942e 2309
a327f25e 2310 $allnames = get_all_user_name_fields(true, 'u');
1f48942e 2311 if ($log->action == "add post") {
2312
a327f25e 2313 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2314 FROM {forum_discussions} d,
2315 {forum_posts} p,
2316 {forum} f,
2317 {user} u
2318 WHERE p.id = ?
65b0e537 2319 AND d.id = p.discussion
2320 AND p.userid = u.id
8f7dc7f1 2321 AND u.deleted <> '1'
4e445355 2322 AND f.id = d.forum", array($log->info));
1f48942e 2323
2324
2325 } else if ($log->action == "add discussion") {
2326
a327f25e 2327 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2328 FROM {forum_discussions} d,
2329 {forum_posts} p,
2330 {forum} f,
2331 {user} u
2332 WHERE d.id = ?
65b0e537 2333 AND d.firstpost = p.id
2334 AND p.userid = u.id
8f7dc7f1 2335 AND u.deleted <> '1'
4e445355 2336 AND f.id = d.forum", array($log->info));
1f48942e 2337 }
2338 return NULL;
2339}
2340
0a4ac01b 2341/**
2342 * Given a discussion id, return the first post from the discussion
df1ba0f4 2343 *
2344 * @global object
2345 * @global object
2346 * @param int $dicsussionid
2347 * @return array
0a4ac01b 2348 */
d05956ac 2349function forum_get_firstpost_from_discussion($discussionid) {
4e445355 2350 global $CFG, $DB;
d05956ac 2351
4e445355 2352 return $DB->get_record_sql("SELECT p.*
2353 FROM {forum_discussions} d,
2354 {forum_posts} p
2355 WHERE d.id = ?
2356 AND d.firstpost = p.id ", array($discussionid));
d05956ac 2357}
2358
0a4ac01b 2359/**
90f4745c 2360 * Returns an array of counts of replies to each discussion
df1ba0f4 2361 *
2362 * @global object
2363 * @global object
2364 * @param int $forumid
2365 * @param string $forumsort
2366 * @param int $limit
2367 * @param int $page
2368 * @param int $perpage
2369 * @return array
0a4ac01b 2370 */
90f4745c 2371function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
4e445355 2372 global $CFG, $DB;
1f48942e 2373
90f4745c 2374 if ($limit > 0) {
2375 $limitfrom = 0;
2376 $limitnum = $limit;
2377 } else if ($page != -1) {
2378 $limitfrom = $page*$perpage;
2379 $limitnum = $perpage;
2380 } else {
2381 $limitfrom = 0;
2382 $limitnum = 0;
2383 }
2384
2385 if ($forumsort == "") {
2386 $orderby = "";
2387 $groupby = "";
2388
2389 } else {
2390 $orderby = "ORDER BY $forumsort";
2391 $groupby = ", ".strtolower($forumsort);
2392 $groupby = str_replace('desc', '', $groupby);
2393 $groupby = str_replace('asc', '', $groupby);
2394 }
2395
bfeb10b7 2396 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2397 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
4e445355 2398 FROM {forum_posts} p
2399 JOIN {forum_discussions} d ON p.discussion = d.id
2400 WHERE p.parent > 0 AND d.forum = ?
bfeb10b7 2401 GROUP BY p.discussion";
4e445355 2402 return $DB->get_records_sql($sql, array($forumid));
bfeb10b7 2403
90f4745c 2404 } else {
bfeb10b7 2405 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
4e445355 2406 FROM {forum_posts} p
2407 JOIN {forum_discussions} d ON p.discussion = d.id
2408 WHERE d.forum = ?
38ec3fb0
AN
2409 GROUP BY p.discussion $groupby $orderby";
2410 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
90f4745c 2411 }
2412}
2413
df1ba0f4 2414/**
2415 * @global object
2416 * @global object
2417 * @global object
2418 * @staticvar array $cache
2419 * @param object $forum
2420 * @param object $cm
2421 * @param object $course
2422 * @return mixed
2423 */
90f4745c 2424function forum_count_discussions($forum, $cm, $course) {
4e445355 2425 global $CFG, $DB, $USER;
90f4745c 2426
2427 static $cache = array();
2428
2429 $now = round(time(), -2); // db cache friendliness
2430
4e445355 2431 $params = array($course->id);
2432
90f4745c 2433 if (!isset($cache[$course->id])) {
2434 if (!empty($CFG->forum_enabletimedposts)) {
4e445355 2435 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2436 $params[] = $now;
2437 $params[] = $now;
90f4745c 2438 } else {
2439 $timedsql = "";
2440 }
2441
2442 $sql = "SELECT f.id, COUNT(d.id) as dcount
4e445355 2443 FROM {forum} f
2444 JOIN {forum_discussions} d ON d.forum = f.id
2445 WHERE f.course = ?
90f4745c 2446 $timedsql
2447 GROUP BY f.id";
a48e8c4b 2448
4e445355 2449 if ($counts = $DB->get_records_sql($sql, $params)) {
90f4745c 2450 foreach ($counts as $count) {
2451 $counts[$count->id] = $count->dcount;
2452 }
2453 $cache[$course->id] = $counts;
2454 } else {
2455 $cache[$course->id] = array();
2456 }
a48e8c4b 2457 }
90f4745c 2458
2459 if (empty($cache[$course->id][$forum->id])) {
2460 return 0;
a48e8c4b 2461 }
90f4745c 2462
2463 $groupmode = groups_get_activity_groupmode($cm, $course);
2464
2465 if ($groupmode != SEPARATEGROUPS) {
2466 return $cache[$course->id][$forum->id];
1f48942e 2467 }
90f4745c 2468
bf0f06b1 2469 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
90f4745c 2470 return $cache[$course->id][$forum->id];
2471 }
2472
2473 require_once($CFG->dirroot.'/course/lib.php');
2474
f20edd52 2475 $modinfo = get_fast_modinfo($course);
90f4745c 2476
2c1bbbc5 2477 $mygroups = $modinfo->get_groups($cm->groupingid);
90f4745c 2478
2479 // add all groups posts
2c1bbbc5 2480 $mygroups[-1] = -1;
4e445355 2481
2482 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2483 $params[] = $forum->id;
90f4745c 2484
2485 if (!empty($CFG->forum_enabletimedposts)) {
2486 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
4e445355 2487 $params[] = $now;
2488 $params[] = $now;
90f4745c 2489 } else {
2490 $timedsql = "";
2491 }
2492
2493 $sql = "SELECT COUNT(d.id)
4e445355 2494 FROM {forum_discussions} d
342650a7 2495 WHERE d.groupid $mygroups_sql AND d.forum = ?
90f4745c 2496 $timedsql";
2497
4e445355 2498 return $DB->get_field_sql($sql, $params);
1f48942e 2499}
2500
0a4ac01b 2501/**
2502 * Get all discussions in a forum
df1ba0f4 2503 *
2504 * @global object
2505 * @global object
2506 * @global object
2507 * @uses CONTEXT_MODULE
2508 * @uses VISIBLEGROUPS
2509 * @param object $cm
2510 * @param string $forumsort
2511 * @param bool $fullpost
2512 * @param int $unused
2513 * @param int $limit
2514 * @param bool $userlastmodified
2515 * @param int $page
2516 * @param int $perpage
4f3a2d21
JL
2517 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2518 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
df1ba0f4 2519 * @return array
0a4ac01b 2520 */
1e366657 2521function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
4f3a2d21 2522 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1) {
4e445355 2523 global $CFG, $DB, $USER;
0fcac008 2524
3d284127 2525 $timelimit = '';
2526
90f4745c 2527 $now = round(time(), -2);
4e445355 2528 $params = array($cm->instance);
90f4745c 2529
bf0f06b1 2530 $modcontext = context_module::instance($cm->id);
2b63df96 2531
4436a63b 2532 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2533 return array();
2534 }
2535
2536 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2b63df96 2537
0468976c 2538 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2539 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2540 $params[] = $now;
2541 $params[] = $now;
90f4745c 2542 if (isloggedin()) {
4e445355 2543 $timelimit .= " OR d.userid = ?";
2544 $params[] = $USER->id;
3d284127 2545 }
90f4745c 2546 $timelimit .= ")";
fbc21e82 2547 }
fbc21e82 2548 }
1f48942e 2549
90f4745c 2550 if ($limit > 0) {
2551 $limitfrom = 0;
2552 $limitnum = $limit;
2553 } else if ($page != -1) {
2554 $limitfrom = $page*$perpage;
2555 $limitnum = $perpage;
2556 } else {
2557 $limitfrom = 0;
2558 $limitnum = 0;
90ec387a 2559 }
8f0cd6ef 2560
90f4745c 2561 $groupmode = groups_get_activity_groupmode($cm);
353228d8 2562
fffa8b35 2563 if ($groupmode) {
4f3a2d21 2564
fffa8b35 2565 if (empty($modcontext)) {
bf0f06b1 2566 $modcontext = context_module::instance($cm->id);
fffa8b35 2567 }
2568
4f3a2d21
JL
2569 // Special case, we received a groupid to override currentgroup.
2570 if ($groupid > 0) {
2571 $course = get_course($cm->course);
2572 if (!groups_group_visible($groupid, $course, $cm)) {
2573 // User doesn't belong to this group, return nothing.
2574 return array();
2575 }
2576 $currentgroup = $groupid;
2577 } else if ($groupid === -1) {
2578 $currentgroup = groups_get_activity_group($cm);
2579 } else {
2580 // Get discussions for all groups current user can see.
2581 $currentgroup = null;
2582 }
2583
fffa8b35 2584 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2585 if ($currentgroup) {
4e445355 2586 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2587 $params[] = $currentgroup;
fffa8b35 2588 } else {
2589 $groupselect = "";
2590 }
2591
2592 } else {
4f3a2d21
JL
2593 // Separate groups.
2594
2595 // Get discussions for all groups current user can see.
2596 if ($currentgroup === null) {
2597 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
2598 if (empty($mygroups)) {
2599 $groupselect = "AND d.groupid = -1";
2600 } else {
2601 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2602 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2603 $params = array_merge($params, $inparamsgroups);
2604 }
2605 } else if ($currentgroup) {
4e445355 2606 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2607 $params[] = $currentgroup;
fffa8b35 2608 } else {
2609 $groupselect = "AND d.groupid = -1";
2610 }
2611 }
353228d8 2612 } else {
02509fe6 2613 $groupselect = "";
2614 }
29507631 2615 if (empty($forumsort)) {
1e366657 2616 $forumsort = forum_get_default_sort_order();
29507631 2617 }
2ab968e9 2618 if (empty($fullpost)) {
b879effb 2619 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2ab968e9 2620 } else {
2621 $postdata = "p.*";
2622 }
9197e147 2623
13597d01 2624 if (empty($userlastmodified)) { // We don't need to know this
fffa8b35 2625 $umfields = "";
2626 $umtable = "";
13597d01 2627 } else {
d85bedf7
JL
2628 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2629 um.imagealt AS umimagealt';
4e445355 2630 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
90f4745c 2631 }
2632
a327f25e 2633 $allnames = get_all_user_name_fields(true, 'u');
5f219cf1 2634 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
a327f25e 2635 u.email, u.picture, u.imagealt $umfields
4e445355 2636 FROM {forum_discussions} d
2637 JOIN {forum_posts} p ON p.discussion = d.id
2638 JOIN {user} u ON p.userid = u.id
90f4745c 2639 $umtable
4e445355 2640 WHERE d.forum = ? AND p.parent = 0
90f4745c 2641 $timelimit $groupselect
5f219cf1 2642 ORDER BY $forumsort, d.id DESC";
4e445355 2643 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
90f4745c 2644}
2645
8d3a5ba1
FM
2646/**
2647 * Gets the neighbours (previous and next) of a discussion.
2648 *
5f219cf1
BK
2649 * The calculation is based on the timemodified when time modified or time created is identical
2650 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
8d3a5ba1 2651 *
9e381efd
DM
2652 * For blog-style forums, the calculation is based on the original creation time of the
2653 * blog post.
2654 *
8d3a5ba1
FM
2655 * Please note that this does not check whether or not the discussion passed is accessible
2656 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2657 * the returned neighbours are checked and are accessible to the current user.
2658 *
2659 * @param object $cm The CM record.
2660 * @param object $discussion The discussion record.
9e381efd 2661 * @param object $forum The forum instance record.
8d3a5ba1
FM
2662 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2663 * they contain the record with minimal information such as 'id' and 'name'.
2664 * When the neighbour is not found the value is false.
2665 */
9e381efd 2666function forum_get_discussion_neighbours($cm, $discussion, $forum) {
8d3a5ba1
FM
2667 global $CFG, $DB, $USER;
2668
9e381efd 2669 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
8d3a5ba1
FM
2670 throw new coding_exception('Discussion is not part of the same forum.');
2671 }
2672
2673 $neighbours = array('prev' => false, 'next' => false);
2674 $now = round(time(), -2);
2675 $params = array();
2676
2677 $modcontext = context_module::instance($cm->id);
2678 $groupmode = groups_get_activity_groupmode($cm);
2679 $currentgroup = groups_get_activity_group($cm);
2680
2681 // Users must fulfill timed posts.
2682 $timelimit = '';
2683 if (!empty($CFG->forum_enabletimedposts)) {
2684 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2685 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2686 $params['tltimestart'] = $now;
2687 $params['tltimeend'] = $now;
2688 if (isloggedin()) {
2689 $timelimit .= ' OR d.userid = :tluserid';
2690 $params['tluserid'] = $USER->id;
2691 }
2692 $timelimit .= ')';
2693 }
2694 }
2695
2696 // Limiting to posts accessible according to groups.
2697 $groupselect = '';
2698 if ($groupmode) {
2699 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2700 if ($currentgroup) {
2701 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2702 $params['groupid'] = $currentgroup;
2703 }
2704 } else {
2705 if ($currentgroup) {
2706 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2707 $params['groupid'] = $currentgroup;
2708 } else {
2709 $groupselect = 'AND d.groupid = -1';
2710 }
2711 }
2712 }
2713
5f219cf1
BK
2714 $params['forumid'] = $cm->instance;
2715 $params['discid1'] = $discussion->id;
2716 $params['discid2'] = $discussion->id;
2717 $params['discid3'] = $discussion->id;
2718 $params['discid4'] = $discussion->id;
2719 $params['disctimecompare1'] = $discussion->timemodified;
2720 $params['disctimecompare2'] = $discussion->timemodified;
2721 $params['pinnedstate1'] = (int) $discussion->pinned;
2722 $params['pinnedstate2'] = (int) $discussion->pinned;
2723 $params['pinnedstate3'] = (int) $discussion->pinned;
2724 $params['pinnedstate4'] = (int) $discussion->pinned;
9e381efd 2725
5f219cf1
BK
2726 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2727 FROM {forum_discussions} d
2728 JOIN {forum_posts} p ON d.firstpost = p.id
2729 WHERE d.forum = :forumid
2730 AND d.id <> :discid1
2731 $timelimit
2732 $groupselect";
2733 $comparefield = "d.timemodified";
2734 $comparevalue = ":disctimecompare1";
2735 $comparevalue2 = ":disctimecompare2";
2736 if (!empty($CFG->forum_enabletimedposts)) {
2737 // Here we need to take into account the release time (timestart)
2738 // if one is set, of the neighbouring posts and compare it to the
2739 // timestart or timemodified of *this* post depending on if the
2740 // release date of this post is in the future or not.
2741 // This stops discussions that appear later because of the
2742 // timestart value from being buried under discussions that were
2743 // made afterwards.
2744 $comparefield = "CASE WHEN d.timemodified < d.timestart
2745 THEN d.timestart ELSE d.timemodified END";
2746 if ($discussion->timemodified < $discussion->timestart) {
2747 // Normally we would just use the timemodified for sorting
2748 // discussion posts. However, when timed discussions are enabled,
2749 // then posts need to be sorted base on the later of timemodified
2750 // or the release date of the post (timestart).
2751 $params['disctimecompare1'] = $discussion->timestart;
2752 $params['disctimecompare2'] = $discussion->timestart;
2753 }
2754 }
2755 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2756 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
9e381efd 2757
5f219cf1
BK
2758 if ($forum->type === 'blog') {
2759 $subselect = "SELECT pp.created
2760 FROM {forum_discussions} dd
2761 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
8d3a5ba1 2762
5f219cf1
BK
2763 $subselectwhere1 = " WHERE dd.id = :discid3";
2764 $subselectwhere2 = " WHERE dd.id = :discid4";
8d3a5ba1 2765
5f219cf1 2766 $comparefield = "p.created";
9e381efd 2767
5f219cf1
BK
2768 $sub1 = $subselect.$subselectwhere1;
2769 $comparevalue = "($sub1)";
9e381efd 2770
5f219cf1
BK
2771 $sub2 = $subselect.$subselectwhere2;
2772 $comparevalue2 = "($sub2)";
8d3a5ba1 2773
5f219cf1
BK
2774 $orderbydesc = "d.pinned, p.created DESC";
2775 $orderbyasc = "d.pinned, p.created ASC";
2776 }
1e366657 2777
5f219cf1
BK
2778 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2779 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2780 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2781 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
9e381efd 2782
5f219cf1
BK
2783 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2784 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2785 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2786 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
8d3a5ba1 2787
5f219cf1
BK
2788 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2789 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
8d3a5ba1
FM
2790 return $neighbours;
2791}
2792
1e366657
AO
2793/**
2794 * Get the sql to use in the ORDER BY clause for forum discussions.
2795 *
2796 * This has the ordering take timed discussion windows into account.
2797 *
2798 * @param bool $desc True for DESC, False for ASC.
2799 * @param string $compare The field in the SQL to compare to normally sort by.
2800 * @param string $prefix The prefix being used for the discussion table.
5f219cf1 2801 * @param bool $pinned sort pinned posts to the top
1e366657
AO
2802 * @return string
2803 */
5f219cf1 2804function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1e366657
AO
2805 global $CFG;
2806
2807 if (!empty($prefix)) {
2808 $prefix .= '.';
2809 }
2810
2811 $dir = $desc ? 'DESC' : 'ASC';
2812
5f219cf1
BK
2813 if ($pinned == true) {
2814 $pinned = "{$prefix}pinned DESC,";
2815 } else {
2816 $pinned = '';
2817 }
2818
1e366657
AO
2819 $sort = "{$prefix}timemodified";
2820 if (!empty($CFG->forum_enabletimedposts)) {
2821 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2822 THEN {$prefix}timestart
2823 ELSE {$compare}
2824 END";
2825 }
5f219cf1 2826 return "$pinned $sort $dir";
1e366657
AO
2827}
2828
df1ba0f4 2829/**
2830 *
2831 * @global object
2832 * @global object
2833 * @global object
2834 * @uses CONTEXT_MODULE
2835 * @uses VISIBLEGROUPS
2836 * @param object $cm
2837 * @return array
2838 */
bfeb10b7 2839function forum_get_discussions_unread($cm) {
4e445355 2840 global $CFG, $DB, $USER;
90f4745c 2841
2842 $now = round(time(), -2);
ee151230 2843 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
35716b86 2844
ee151230 2845 $params = array();
90f4745c 2846 $groupmode = groups_get_activity_groupmode($cm);
2847 $currentgroup = groups_get_activity_group($cm);
2848
2849 if ($groupmode) {
bf0f06b1 2850 $modcontext = context_module::instance($cm->id);
90f4745c 2851
2852 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2853 if ($currentgroup) {
ee151230
AD
2854 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2855 $params['currentgroup'] = $currentgroup;
90f4745c 2856 } else {
2857 $groupselect = "";
2858 }
2859
2860 } else {
ee151230 2861 //separate groups without access all
90f4745c 2862 if ($currentgroup) {
ee151230
AD
2863 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2864 $params['currentgroup'] = $currentgroup;
90f4745c 2865 } else {
2866 $groupselect = "AND d.groupid = -1";
2867 }
2868 }
2869 } else {
2870 $groupselect = "";
13597d01 2871 }
2872
90f4745c 2873 if (!empty($CFG->forum_enabletimedposts)) {
ee151230
AD
2874 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2875 $params['now1'] = $now;
2876 $params['now2'] = $now;
90f4745c 2877 } else {
2878 $timedsql = "";
2879 }
2880
2881 $sql = "SELECT d.id, COUNT(p.id) AS unread
4e445355 2882 FROM {forum_discussions} d
2883 JOIN {forum_posts} p ON p.discussion = d.id
2884 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
90f4745c 2885 WHERE d.forum = {$cm->instance}
ee151230 2886 AND p.modified >= :cutoffdate AND r.id is NULL
90f4745c 2887 $groupselect
4e445355 2888 $timedsql
bfeb10b7 2889 GROUP BY d.id";
ee151230
AD
2890 $params['cutoffdate'] = $cutoffdate;
2891
4e445355 2892 if ($unreads = $DB->get_records_sql($sql, $params)) {
90f4745c 2893 foreach ($unreads as $unread) {
2894 $unreads[$unread->id] = $unread->unread;
2895 }
2896 return $unreads;
2897 } else {
2898 return array();
2899 }
1f48942e 2900}
2901
df1ba0f4 2902/**
2903 * @global object
2904 * @global object
2905 * @global object
2906 * @uses CONEXT_MODULE
2907 * @uses VISIBLEGROUPS
2908 * @param object $cm
2909 * @return array
2910 */
90f4745c 2911function forum_get_discussions_count($cm) {
4e445355 2912 global $CFG, $DB, $USER;
90f4745c 2913
2914 $now = round(time(), -2);
4e445355 2915 $params = array($cm->instance);
90f4745c 2916 $groupmode = groups_get_activity_groupmode($cm);
2917 $currentgroup = groups_get_activity_group($cm);
2918
2919 if ($groupmode) {
bf0f06b1 2920 $modcontext = context_module::instance($cm->id);
90f4745c 2921
2922 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2923 if ($currentgroup) {
4e445355 2924 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2925 $params[] = $currentgroup;
90f4745c 2926 } else {
2927 $groupselect = "";
2928 }
2929
2930 } else {
2931 //seprate groups without access all
2932 if ($currentgroup) {
4e445355 2933 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2934 $params[] = $currentgroup;
90f4745c 2935 } else {
2936 $groupselect = "AND d.groupid = -1";
2937 }
2938 }
2939 } else {
2940 $groupselect = "";
2941 }
2942
90f4745c 2943 $timelimit = "";
2944
2945 if (!empty($CFG->forum_enabletimedposts)) {
2946
bf0f06b1 2947 $modcontext = context_module::instance($cm->id);
90f4745c 2948
2949 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2950 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2951 $params[] = $now;
2952 $params[] = $now;
90f4745c 2953 if (isloggedin()) {
4e445355 2954 $timelimit .= " OR d.userid = ?";
2955 $params[] = $USER->id;
90f4745c 2956 }
2957 $timelimit .= ")";
2958 }
2959 }
2960
2961 $sql = "SELECT COUNT(d.id)
4e445355 2962 FROM {forum_discussions} d
2963 JOIN {forum_posts} p ON p.discussion = d.id
2964 WHERE d.forum = ? AND p.parent = 0
2965 $groupselect $timelimit";
90f4745c 2966
4e445355 2967 return $DB->get_field_sql($sql, $params);
90f4745c 2968}
1f48942e 2969
2970
0a4ac01b 2971// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 2972
2973
df1ba0f4 2974/**
2975 * @global object
2976 * @global object
2977 * @param int $courseid
2978 * @param string $type
2979 */
11b0c469 2980function forum_get_course_forum($courseid, $type) {
2981// How to set up special 1-per-course forums
c112bc60 2982 global $CFG, $DB, $OUTPUT, $USER;
a6fcdf98 2983
4e445355 2984 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
65b0e537 2985 // There should always only be ONE, but with the right combination of
29cbd93a 2986 // errors there might be more. In this case, just return the oldest one (lowest ID).
2987 foreach ($forums as $forum) {
2988 return $forum; // ie the first one
11b0c469 2989 }
8daaf761 2990 }
e6874d9f 2991
8daaf761 2992 // Doesn't exist, so create one now.
b85b25eb 2993 $forum = new stdClass();
8daaf761 2994 $forum->course = $courseid;
2995 $forum->type = "$type";
c112bc60
ARN
2996 if (!empty($USER->htmleditor)) {
2997 $forum->introformat = $USER->htmleditor;
2998 }
8daaf761 2999 switch ($forum->type) {
3000 case "news":
294ce987 3001 $forum->name = get_string("namenews", "forum");
3002 $forum->intro = get_string("intronews", "forum");
906fef94 3003 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 3004 $forum->assessed = 0;
709f0ec8 3005 if ($courseid == SITEID) {
3006 $forum->name = get_string("sitenews");
3007 $forum->forcesubscribe = 0;
8f0cd6ef 3008 }
8daaf761 3009 break;
3010 case "social":
294ce987 3011 $forum->name = get_string("namesocial", "forum");
3012 $forum->intro = get_string("introsocial", "forum");
8daaf761 3013 $forum->assessed = 0;
3014 $forum->forcesubscribe = 0;
3015 break;
1c7b8b93
NC
3016 case "blog":
3017 $forum->name = get_string('blogforum', 'forum');
3018 $forum->intro = get_string('introblog', 'forum');
3019 $forum->assessed = 0;
3020 $forum->forcesubscribe = 0;
3021 break;
8daaf761 3022 default:
9146b979 3023 echo $OUTPUT->notification("That forum type doesn't exist!");
8daaf761 3024 return false;
3025 break;
3026 }
3027
3028 $forum->timemodified = time();
4e445355 3029 $forum->id = $DB->insert_record("forum", $forum);
8daaf761 3030
4e445355 3031 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
9146b979 3032 echo $OUTPUT->notification("Could not find forum module!!");
e1b5643f 3033 return false;
82aa0e8d 3034 }
39790bd8 3035 $mod = new stdClass();
e1b5643f 3036 $mod->course = $courseid;
3037 $mod->module = $module->id;
3038 $mod->instance = $forum->id;
3039 $mod->section = 0;
722e6ba9
MG
3040 include_once("$CFG->dirroot/course/lib.php");
3041 if (! $mod->coursemodule = add_course_module($mod) ) {
11cd754e 3042 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
e1b5643f 3043 return false;
3044 }
722e6ba9 3045 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
4e445355 3046 return $DB->get_record("forum", array("id" => "$forum->id"));
82aa0e8d 3047}
3048
0a4ac01b 3049/**
21976af1 3050 * Print a forum post
65bcf17b 3051 *
df1ba0f4 3052 * @global object
3053 * @global object
3054 * @uses FORUM_MODE_THREADED
3055 * @uses PORTFOLIO_FORMAT_PLAINHTML
3056 * @uses PORTFOLIO_FORMAT_FILE
3057 * @uses PORTFOLIO_FORMAT_RICHHTML
3058 * @uses PORTFOLIO_ADD_TEXT_LINK
3059 * @uses CONTEXT_MODULE
21976af1 3060 * @param object $post The post to print.
df1ba0f4 3061 * @param object $discussion
3062 * @param object $forum
3063 * @param object $cm
3064 * @param object $course
21976af1 3065 * @param boolean $ownpost Whether this post belongs to the current user.
65bcf17b 3066 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
21976af1 3067 * @param boolean $link Just print a shortened version of the post as a link to the full post.
21976af1 3068 * @param string $footer Extra stuff to print after the message.
3069 * @param string $highlight Space-separated list of terms to highlight.
3070 * @param int $post_read true, false or -99. If we already know whether this user
3071 * has read this post, pass that in, otherwise, pass in -99, and this
3072 * function will work it out.
3073 * @param boolean $dummyifcantsee When forum_user_can_see_post says that
65bcf17b 3074 * the current user can't see this post, if this argument is true
21976af1 3075 * (the default) then print a dummy 'you can't see this post' post.
3076 * If false, don't output anything at all.
df1ba0f4 3077 * @param bool|null $istracked
63e87951 3078 * @return void
0a4ac01b 3079 */
65bcf17b 3080function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
367a75fa 3081 $footer="", $highlight="", $postisread=null, $dummyifcantsee=true, $istracked=null, $return=false) {
5d9827e4 3082 global $USER, $CFG, $OUTPUT;
501cdbd8 3083
99d19c13
PS
3084 require_once($CFG->libdir . '/filelib.php');
3085
367a75fa
SH
3086 // String cache
3087 static $str;
654e77e7
DP
3088 // This is an extremely hacky way to ensure we only print the 'unread' anchor
3089 // the first time we encounter an unread post on a page. Ideally this would
3090 // be moved into the caller somehow, and be better testable. But at the time
3091 // of dealing with this bug, this static workaround was the most surgical and
3092 // it fits together with only printing th unread anchor id once on a given page.
3093 static $firstunreadanchorprinted = false;
f37da850 3094
bf0f06b1 3095 $modcontext = context_module::instance($cm->id);
8d96a7b4 3096
65bcf17b 3097 $post->course = $course->id;
3098 $post->forum = $forum->id;
64f93798 3099 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
103e7cba
KG
3100 if (!empty($CFG->enableplagiarism)) {
3101 require_once($CFG->libdir.'/plagiarismlib.php');
3102 $post->message .= plagiarism_get_links(array('userid' => $post->userid,
3103 'content' => $post->message,
3104 'cmid' => $cm->id,
3105 'course' => $post->course,
3106 'forum' => $post->forum));
3107 }
951e1073 3108
65bcf17b 3109 // caching
3110 if (!isset($cm->cache)) {
367a75fa 3111 $cm->cache = new stdClass;
65bcf17b 3112 }
13bbe067 3113
65bcf17b 3114 if (!isset($cm->cache->caps)) {
3115 $cm->cache->caps = array();
65bcf17b 3116 $cm->cache->caps['mod/forum:viewdiscussion'] = has_capability('mod/forum:viewdiscussion', $modcontext);
3117 $cm->cache->caps['moodle/site:viewfullnames'] = has_capability('moodle/site:viewfullnames', $modcontext);
3118 $cm->cache->caps['mod/forum:editanypost'] = has_capability('mod/forum:editanypost', $modcontext);
3119 $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
3120 $cm->cache->caps['mod/forum:deleteownpost'] = has_capability('mod/forum:deleteownpost', $modcontext);
3121 $cm->cache->caps['mod/forum:deleteanypost'] = has_capability('mod/forum:deleteanypost', $modcontext);
3122 $cm->cache->caps['mod/forum:viewanyrating'] = has_capability('mod/forum:viewanyrating', $modcontext);
f98b13a6 3123 $cm->cache->caps['mod/forum:exportpost'] = has_capability('mod/forum:exportpost', $modcontext);
3124 $cm->cache->caps['mod/forum:exportownpost'] = has_capability('mod/forum:exportownpost', $modcontext);
951e1073 3125 }
951e1073 3126
65bcf17b 3127 if (!isset($cm->uservisible)) {