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