MDL-55188 events: First deprecation of eventslib.php
[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
63e87951 1324 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
5e7f2b0b 1325 }
caadf009 1326 } else {
41905731 1327 echo "<p>".get_string("noposts", "forum")."</p>";
caadf009 1328 }
caadf009 1329}
1330
8538c562
DM
1331/**
1332 * Filters the forum discussions according to groups membership and config.
1333 *
e9dfeec9 1334 * @deprecated since 3.3
063b7ee6 1335 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
8538c562
DM
1336 * @since Moodle 2.8, 2.7.1, 2.6.4
1337 * @param array $discussions Discussions with new posts array
1338 * @return array Forums with the number of new posts
1339 */
1340function forum_filter_user_groups_discussions($discussions) {
c38965fb 1341
e9dfeec9
MN
1342 debugging('The function forum_filter_user_groups_discussions() is now deprecated.', DEBUG_DEVELOPER);
1343
8538c562
DM
1344 // Group the remaining discussions posts by their forumid.
1345 $filteredforums = array();
c38965fb 1346
8538c562
DM
1347 // Discard not visible groups.
1348 foreach ($discussions as $discussion) {
c38965fb 1349
8538c562
DM
1350 // Course data is already cached.
1351 $instances = get_fast_modinfo($discussion->course)->get_instances();
1352 $forum = $instances['forum'][$discussion->forum];
5e7f2b0b 1353
8538c562
DM
1354 // Continue if the user should not see this discussion.
1355 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1356 continue;
1357 }
1358
1359 // Grouping results by forum.
1360 if (empty($filteredforums[$forum->instance])) {
1361 $filteredforums[$forum->instance] = new stdClass();
1362 $filteredforums[$forum->instance]->id = $forum->id;
1363 $filteredforums[$forum->instance]->count = 0;
1364 }
1365 $filteredforums[$forum->instance]->count += $discussion->count;
1366
1367 }
1368
1369 return $filteredforums;
1370}
1371
1372/**
1373 * Returns whether the discussion group is visible by the current user or not.
1374 *
1375 * @since Moodle 2.8, 2.7.1, 2.6.4
1376 * @param cm_info $cm The discussion course module
1377 * @param int $discussiongroupid The discussion groupid
1378 * @return bool
1379 */
1380function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1381
1382 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1383 return true;
1384 }
1385
1386 if (isguestuser()) {
1387 return false;
1388 }
1389
1390 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1391 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1392 return true;
1393 }
1394
1395 return false;
1396}
5e7f2b0b 1397
0a4ac01b 1398/**
e9dfeec9 1399 * @deprecated since 3.3
063b7ee6 1400 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
df1ba0f4 1401 * @global object
1402 * @global object
1403 * @global object
1404 * @param array $courses
1405 * @param array $htmlarray
0a4ac01b 1406 */
185cfb09 1407function forum_print_overview($courses,&$htmlarray) {
261c6ef0 1408 global $USER, $CFG, $DB, $SESSION;
493f0820 1409
e9dfeec9
MN
1410 debugging('The function forum_print_overview() is now deprecated.', DEBUG_DEVELOPER);
1411
185cfb09 1412 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1413 return array();
1414 }
f8716988 1415
185cfb09 1416 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
f8716988 1417 return;
1418 }
185cfb09 1419
ba4ee840
DM
1420 // Courses to search for new posts
1421 $coursessqls = array();
4e445355 1422 $params = array();
185cfb09 1423 foreach ($courses as $course) {
ba4ee840
DM
1424
1425 // If the user has never entered into the course all posts are pending
1426 if ($course->lastaccess == 0) {
8538c562 1427 $coursessqls[] = '(d.course = ?)';
ba4ee840
DM
1428 $params[] = $course->id;
1429
1430 // Only posts created after the course last access
1431 } else {
8538c562 1432 $coursessqls[] = '(d.course = ? AND p.created > ?)';
ba4ee840
DM
1433 $params[] = $course->id;
1434 $params[] = $course->lastaccess;
1435 }
185cfb09 1436 }
4e445355 1437 $params[] = $USER->id;
ba4ee840
DM
1438 $coursessql = implode(' OR ', $coursessqls);
1439
8538c562
DM
1440 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1441 .'FROM {forum_discussions} d '
ba4ee840
DM
1442 .'JOIN {forum_posts} p ON p.discussion = d.id '
1443 ."WHERE ($coursessql) "
3e95e09b 1444 .'AND p.deleted <> 1 '
ba4ee840 1445 .'AND p.userid != ? '
6667ebb9 1446 .'AND (d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?)) '
81ba2632
JH
1447 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1448 .'ORDER BY d.course, d.forum';
6667ebb9
AN
1449 $params[] = time();
1450 $params[] = time();
2b63df96 1451
8538c562
DM
1452 // Avoid warnings.
1453 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1454 $discussions = array();
185cfb09 1455 }
2b63df96 1456
8538c562
DM
1457 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1458
185cfb09 1459 // also get all forum tracking stuff ONCE.
1460 $trackingforums = array();
1461 foreach ($forums as $forum) {
1462 if (forum_tp_can_track_forums($forum)) {
1463 $trackingforums[$forum->id] = $forum;
1464 }
1465 }
2b63df96 1466
185cfb09 1467 if (count($trackingforums) > 0) {
1468 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1469 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
4e445355 1470 ' FROM {forum_posts} p '.
1471 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
3e95e09b 1472 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE p.deleted <> 1 AND (';
4e445355 1473 $params = array($USER->id);
1474
d3553951 1475 foreach ($trackingforums as $track) {
4e445355 1476 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1477 $params[] = $track->id;
261c6ef0 1478 if (isset($SESSION->currentgroup[$track->course])) {
1479 $groupid = $SESSION->currentgroup[$track->course];
1480 } else {
0209f964
PS
1481 // get first groupid
1482 $groupids = groups_get_all_groups($track->course, $USER->id);
1483 if ($groupids) {
1484 reset($groupids);
1485 $groupid = key($groupids);
261c6ef0 1486 $SESSION->currentgroup[$track->course] = $groupid;
1487 } else {
1488 $groupid = 0;
1489 }
0209f964 1490 unset($groupids);
261c6ef0 1491 }
1492 $params[] = $groupid;
185cfb09 1493 }
1494 $sql = substr($sql,0,-3); // take off the last OR
6667ebb9
AN
1495 $sql .= ') AND p.modified >= ? AND r.id is NULL ';
1496 $sql .= 'AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)) ';
1497 $sql .= 'GROUP BY d.forum,d.course';
4e445355 1498 $params[] = $cutoffdate;
6667ebb9
AN
1499 $params[] = time();
1500 $params[] = time();
185cfb09 1501
4e445355 1502 if (!$unread = $DB->get_records_sql($sql, $params)) {
185cfb09 1503 $unread = array();
1504 }
1505 } else {
1506 $unread = array();
95d71ad3 1507 }
185cfb09 1508
8538c562 1509 if (empty($unread) and empty($forumsnewposts)) {
9cba7a8c 1510 return;
1511 }
1512
1513 $strforum = get_string('modulename','forum');
9cba7a8c 1514
f8716988 1515 foreach ($forums as $forum) {
185cfb09 1516 $str = '';
f8716988 1517 $count = 0;
185cfb09 1518 $thisunread = 0;
f8716988 1519 $showunread = false;
1520 // either we have something from logs, or trackposts, or nothing.
8538c562
DM
1521 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1522 $count = $forumsnewposts[$forum->id]->count;
90558ec4 1523 }
185cfb09 1524 if (array_key_exists($forum->id,$unread)) {
1525 $thisunread = $unread[$forum->id]->count;
f8716988 1526 $showunread = true;
0d6b9d4f 1527 }
185cfb09 1528 if ($count > 0 || $thisunread > 0) {
e23800b7 1529 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1530 $forum->name.'</a></div>';
6d641063 1531 $str .= '<div class="info"><span class="postsincelogin">';
54294601 1532 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
f8716988 1533 if (!empty($showunread)) {
54294601 1534 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
f8716988 1535 }
e23800b7 1536 $str .= '</div></div>';
f8716988 1537 }
2b63df96 1538 if (!empty($str)) {
185cfb09 1539 if (!array_key_exists($forum->course,$htmlarray)) {
1540 $htmlarray[$forum->course] = array();
1541 }
1542 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1543 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1544 }
1545 $htmlarray[$forum->course]['forum'] .= $str;
1546 }
2b63df96 1547 }
0d6b9d4f 1548}
1549
0a4ac01b 1550/**
1551 * Given a course and a date, prints a summary of all the new
1552 * messages posted in the course since that date
df1ba0f4 1553 *
1554 * @global object
1555 * @global object
1556 * @global object
1557 * @uses CONTEXT_MODULE
1558 * @uses VISIBLEGROUPS
90f4745c 1559 * @param object $course
1560 * @param bool $viewfullnames capability
1561 * @param int $timestart
1562 * @return bool success
0a4ac01b 1563 */
dd97c328 1564function forum_print_recent_activity($course, $viewfullnames, $timestart) {
cb860491 1565 global $CFG, $USER, $DB, $OUTPUT;
caadf009 1566
dd97c328 1567 // do not use log table if possible, it may be huge and is expensive to join with other tables
caadf009 1568
dda60f88 1569 $allnamefields = user_picture::fields('u', null, 'duserid');
4e445355 1570 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
dda60f88 1571 d.timestart, d.timeend, $allnamefields
4e445355 1572 FROM {forum_posts} p
1573 JOIN {forum_discussions} d ON d.id = p.discussion
1574 JOIN {forum} f ON f.id = d.forum
1575 JOIN {user} u ON u.id = p.userid
3e95e09b 1576 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
4e445355 1577 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
dd97c328 1578 return false;
1b5910c4 1579 }
1580
f20edd52 1581 $modinfo = get_fast_modinfo($course);
dcde9f02 1582
dd97c328 1583 $groupmodes = array();
1584 $cms = array();
d05956ac 1585
dd97c328 1586 $strftimerecent = get_string('strftimerecent');
d05956ac 1587
dd97c328 1588 $printposts = array();
1589 foreach ($posts as $post) {
1590 if (!isset($modinfo->instances['forum'][$post->forum])) {
1591 // not visible
1592 continue;
1593 }
1594 $cm = $modinfo->instances['forum'][$post->forum];
1595 if (!$cm->uservisible) {
1596 continue;
1597 }
bf0f06b1 1598 $context = context_module::instance($cm->id);
6b7de0bb 1599
1600 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1601 continue;
1602 }
583b57b4 1603
dd97c328 1604 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1605 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
6b7de0bb 1606 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
dd97c328 1607 continue;
ac1d9a22 1608 }
dd97c328 1609 }
583b57b4 1610
8538c562
DM
1611 // Check that the user can see the discussion.
1612 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1613 $printposts[] = $post;
dd97c328 1614 }
8f7dc7f1 1615
dd97c328 1616 }
1617 unset($posts);
8f7dc7f1 1618
dd97c328 1619 if (!$printposts) {
1620 return false;
1621 }
1622
cb860491 1623 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
af0fc6a2 1624 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
dd97c328 1625
1626 foreach ($printposts as $post) {
1627 $subjectclass = empty($post->parent) ? ' bold' : '';
af0fc6a2 1628 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
dd97c328 1629
af0fc6a2
JP
1630 $list .= html_writer::start_tag('li');
1631 $list .= html_writer::start_div('head');
1632 $list .= html_writer::div(userdate($post->modified, $strftimerecent), 'date');
1633 if (!$authorhidden) {
1634 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
1635 }
1636 $list .= html_writer::end_div(); // Head.
1637
1638 $list .= html_writer::start_div('info' . $subjectclass);
1639 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
1640 if (!empty($post->parent)) {
1641 $discussionurl->param('parent', $post->parent);
1642 $discussionurl->set_anchor('p'. $post->id);
caadf009 1643 }
dd97c328 1644 $post->subject = break_up_long_words(format_string($post->subject, true));
af0fc6a2
JP
1645 $list .= html_writer::link($discussionurl, $post->subject);
1646 $list .= html_writer::end_div(); // Info.
1647 $list .= html_writer::end_tag('li');
caadf009 1648 }
dd97c328 1649
af0fc6a2
JP
1650 $list .= html_writer::end_tag('ul');
1651 echo $list;
dd97c328 1652
1653 return true;
caadf009 1654}
1655
353228d8 1656/**
1657 * Return grade for given user or all users.
1658 *
df1ba0f4 1659 * @global object
1660 * @global object
1661 * @param object $forum
353228d8 1662 * @param int $userid optional user id, 0 means all users
1663 * @return array array of grades, false if none
1664 */
2b04c41c 1665function forum_get_user_grades($forum, $userid = 0) {
63e87951 1666 global $CFG;
df997f84 1667
63e87951 1668 require_once($CFG->dirroot.'/rating/lib.php');
df997f84 1669
2b04c41c
SH
1670 $ratingoptions = new stdClass;
1671 $ratingoptions->component = 'mod_forum';
1672 $ratingoptions->ratingarea = 'post';
353228d8 1673
63e87951
AD
1674 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1675 $ratingoptions->modulename = 'forum';
1676 $ratingoptions->moduleid = $forum->id;
63e87951
AD
1677 $ratingoptions->userid = $userid;
1678 $ratingoptions->aggregationmethod = $forum->assessed;
1679 $ratingoptions->scaleid = $forum->scale;
1680 $ratingoptions->itemtable = 'forum_posts';
1681 $ratingoptions->itemtableusercolumn = 'userid';
353228d8 1682
2b04c41c 1683 $rm = new rating_manager();
63e87951 1684 return $rm->get_user_grades($ratingoptions);
353228d8 1685}
caadf009 1686
0a4ac01b 1687/**
775f811a 1688 * Update activity grades
353228d8 1689 *
a153c9f2 1690 * @category grade
775f811a 1691 * @param object $forum
1692 * @param int $userid specific user only, 0 means all
6b7de0bb 1693 * @param boolean $nullifnone return null if grade does not exist
90f4745c 1694 * @return void
0a4ac01b 1695 */
775f811a 1696function forum_update_grades($forum, $userid=0, $nullifnone=true) {
4e445355 1697 global $CFG, $DB;
775f811a 1698 require_once($CFG->libdir.'/gradelib.php');
caadf009 1699
775f811a 1700 if (!$forum->assessed) {
1701 forum_grade_item_update($forum);
02ebf404 1702
775f811a 1703 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1704 forum_grade_item_update($forum, $grades);
eafb9d9e 1705
775f811a 1706 } else if ($userid and $nullifnone) {
39790bd8 1707 $grade = new stdClass();
775f811a 1708 $grade->userid = $userid;
1709 $grade->rawgrade = NULL;
1710 forum_grade_item_update($forum, $grade);
02ebf404 1711
353228d8 1712 } else {
775f811a 1713 forum_grade_item_update($forum);
1714 }
1715}
1716
353228d8 1717/**
612607bd 1718 * Create/update grade item for given forum
353228d8 1719 *
a153c9f2 1720 * @category grade
df1ba0f4 1721 * @uses GRADE_TYPE_NONE
1722 * @uses GRADE_TYPE_VALUE
1723 * @uses GRADE_TYPE_SCALE
a153c9f2
AD
1724 * @param stdClass $forum Forum object with extra cmidnumber
1725 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 1726 * @return int 0 if ok
353228d8 1727 */
0b5a80a1 1728function forum_grade_item_update($forum, $grades=NULL) {
612607bd 1729 global $CFG;
1730 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1731 require_once($CFG->libdir.'/gradelib.php');
353228d8 1732 }
1733
612607bd 1734 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
353228d8 1735
5980d52f 1736 if (!$forum->assessed or $forum->scale == 0) {
612607bd 1737 $params['gradetype'] = GRADE_TYPE_NONE;
353228d8 1738
1739 } else if ($forum->scale > 0) {
1740 $params['gradetype'] = GRADE_TYPE_VALUE;
1741 $params['grademax'] = $forum->scale;
1742 $params['grademin'] = 0;
1743
1744 } else if ($forum->scale < 0) {
1745 $params['gradetype'] = GRADE_TYPE_SCALE;
1746 $params['scaleid'] = -$forum->scale;
1747 }
1748
0b5a80a1 1749 if ($grades === 'reset') {
1750 $params['reset'] = true;
1751 $grades = NULL;
1752 }
1753
1754 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
353228d8 1755}
1756
1757/**
1758 * Delete grade item for given forum
1759 *
a153c9f2
AD
1760 * @category grade
1761 * @param stdClass $forum Forum object
1762 * @return grade_item
353228d8 1763 */
1764function forum_grade_item_delete($forum) {
612607bd 1765 global $CFG;
1766 require_once($CFG->libdir.'/gradelib.php');
1767
b67ec72f 1768 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
caadf009 1769}
1770
353228d8 1771
0a4ac01b 1772/**
90f4745c 1773 * This function returns if a scale is being used by one forum
df1ba0f4 1774 *
1775 * @global object
90f4745c 1776 * @param int $forumid
1777 * @param int $scaleid negative number
1778 * @return bool
0a4ac01b 1779 */
0f1a97c2 1780function forum_scale_used ($forumid,$scaleid) {
4e445355 1781 global $DB;
0f1a97c2 1782 $return = false;
65b0e537 1783
4e445355 1784 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
65b0e537 1785
fa22fd5f 1786 if (!empty($rec) && !empty($scaleid)) {
0f1a97c2 1787 $return = true;
1788 }
65b0e537 1789
0f1a97c2 1790 return $return;
1791}
1792
85c9ebb9 1793/**
1794 * Checks if scale is being used by any instance of forum
1795 *
1796 * This is used to find out if scale used anywhere
df1ba0f4 1797 *
1798 * @global object
85c9ebb9 1799 * @param $scaleid int
1800 * @return boolean True if the scale is used by any forum
1801 */
1802function forum_scale_used_anywhere($scaleid) {
4e445355 1803 global $DB;
1804 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
85c9ebb9 1805 return true;
1806 } else {
1807 return false;
1808 }
1809}
1810
0a4ac01b 1811// SQL FUNCTIONS ///////////////////////////////////////////////////////////
9fa49e22 1812
0a4ac01b 1813/**
1814 * Gets a post with all info ready for forum_print_post
1815 * Most of these joins are just to get the forum id
df1ba0f4 1816 *
1817 * @global object
1818 * @global object
90f4745c 1819 * @param int $postid
1820 * @return mixed array of posts or false
0a4ac01b 1821 */
1f48942e 1822function forum_get_post_full($postid) {
4e445355 1823 global $CFG, $DB;
1f48942e 1824
a327f25e
AG
1825 $allnames = get_all_user_name_fields(true, 'u');
1826 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 1827 FROM {forum_posts} p
1828 JOIN {forum_discussions} d ON p.discussion = d.id
1829 LEFT JOIN {user} u ON p.userid = u.id
1830 WHERE p.id = ?", array($postid));
1f48942e 1831}
1832
65bcf17b 1833/**
1834 * Gets all posts in discussion including top parent.
df1ba0f4 1835 *
1836 * @global object
1837 * @global object
1838 * @global object
90f4745c 1839 * @param int $discussionid
1840 * @param string $sort
1841 * @param bool $tracking does user track the forum?
1842 * @return array of posts
65bcf17b 1843 */
90f4745c 1844function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
4e445355 1845 global $CFG, $DB, $USER;
65bcf17b 1846
3c2bf848 1847 $tr_sel = "";
1848 $tr_join = "";
4e445355 1849 $params = array();
3c2bf848 1850
90f4745c 1851 if ($tracking) {
90f4745c 1852 $tr_sel = ", fr.id AS postread";
4e445355 1853 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1854 $params[] = $USER->id;
90f4745c 1855 }
1856
a327f25e 1857 $allnames = get_all_user_name_fields(true, 'u');
4e445355 1858 $params[] = $discussionid;
a327f25e 1859 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
4e445355 1860 FROM {forum_posts} p
1861 LEFT JOIN {user} u ON p.userid = u.id
90f4745c 1862 $tr_join
4e445355 1863 WHERE p.discussion = ?
1864 ORDER BY $sort", $params)) {
65bcf17b 1865 return array();
1866 }
1867
1868 foreach ($posts as $pid=>$p) {
90f4745c 1869 if ($tracking) {
1870 if (forum_tp_is_post_old($p)) {
6b7de0bb 1871 $posts[$pid]->postread = true;
90f4745c 1872 }
1873 }
65bcf17b 1874 if (!$p->parent) {
1875 continue;
1876 }
1877 if (!isset($posts[$p->parent])) {
1878 continue; // parent does not exist??
1879 }
1880 if (!isset($posts[$p->parent]->children)) {
1881 $posts[$p->parent]->children = array();
1882 }
1883 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1884 }
1885
bfa7bece
AN
1886 // Start with the last child of the first post.
1887 $post = &$posts[reset($posts)->id];
1888
1889 $lastpost = false;
1890 while (!$lastpost) {
1891 if (!isset($post->children)) {
1892 $post->lastpost = true;
1893 $lastpost = true;
1894 } else {
1895 // Go to the last child of this post.
1896 $post = &$posts[end($post->children)->id];
1897 }
1898 }
1899
65bcf17b 1900 return $posts;
1901}
1902
42fb3c85 1903/**
1904 * An array of forum objects that the user is allowed to read/search through.
df1ba0f4 1905 *
1906 * @global object
1907 * @global object
1908 * @global object
1909 * @param int $userid
1910 * @param int $courseid if 0, we look for forums throughout the whole site.
42fb3c85 1911 * @return array of forum objects, or false if no matches
1912 * Forum objects have the following attributes:
1913 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1914 * viewhiddentimedposts
1915 */
1916function forum_get_readable_forums($userid, $courseid=0) {
2b63df96 1917
4e445355 1918 global $CFG, $DB, $USER;
6b7de0bb 1919 require_once($CFG->dirroot.'/course/lib.php');
2b63df96 1920
4e445355 1921 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
12e57b92 1922 print_error('notinstalled', 'forum');
42fb3c85 1923 }
2b63df96 1924
42fb3c85 1925 if ($courseid) {
4e445355 1926 $courses = $DB->get_records('course', array('id' => $courseid));
42fb3c85 1927 } else {
65bcf17b 1928 // If no course is specified, then the user can see SITE + his courses.
4e445355 1929 $courses1 = $DB->get_records('course', array('id' => SITEID));
b1d5d015 1930 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
6155150c 1931 $courses = array_merge($courses1, $courses2);
42fb3c85 1932 }
1933 if (!$courses) {
6b7de0bb 1934 return array();
42fb3c85 1935 }
1936
1937 $readableforums = array();
2b63df96 1938
6527b5c2 1939 foreach ($courses as $course) {
1940
f20edd52 1941 $modinfo = get_fast_modinfo($course);
2b63df96 1942
6b7de0bb 1943 if (empty($modinfo->instances['forum'])) {
1944 // hmm, no forums?
1945 continue;
1946 }
2b63df96 1947
4e445355 1948 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2b63df96 1949
6b7de0bb 1950 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1951 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1952 continue;
1953 }
bf0f06b1 1954 $context = context_module::instance($cm->id);
6b7de0bb 1955 $forum = $courseforums[$forumid];
2e945910
AB
1956 $forum->context = $context;
1957 $forum->cm = $cm;
d50704bf 1958
6b7de0bb 1959 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1960 continue;
1961 }
6527b5c2 1962
6b7de0bb 1963 /// group access
1964 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2c1bbbc5
MG
1965
1966 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1967 $forum->onlygroups[] = -1;
6b7de0bb 1968 }
2b63df96 1969
6b7de0bb 1970 /// hidden timed discussions
1971 $forum->viewhiddentimedposts = true;
1972 if (!empty($CFG->forum_enabletimedposts)) {
1973 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1974 $forum->viewhiddentimedposts = false;
1975 }
1976 }
d50704bf 1977
6b7de0bb 1978 /// qanda access
1979 if ($forum->type == 'qanda'
1980 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2b63df96 1981
6b7de0bb 1982 // We need to check whether the user has posted in the qanda forum.
1983 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1984 // the user is allowed to see in this forum.
1985 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1986 foreach ($discussionspostedin as $d) {
1987 $forum->onlydiscussions[] = $d->id;
d50704bf 1988 }
42fb3c85 1989 }
1990 }
6b7de0bb 1991
1992 $readableforums[$forum->id] = $forum;
42fb3c85 1993 }
6b7de0bb 1994
1995 unset($modinfo);
1996
42fb3c85 1997 } // End foreach $courses
2b63df96 1998
42fb3c85 1999 return $readableforums;
2000}
2001
bbbf2d40 2002/**
2003 * Returns a list of posts found using an array of search terms.
df1ba0f4 2004 *
2005 * @global object
2006 * @global object
2007 * @global object
2008 * @param array $searchterms array of search terms, e.g. word +word -word
2009 * @param int $courseid if 0, we search through the whole site
2010 * @param int $limitfrom
2011 * @param int $limitnum
2012 * @param int &$totalcount
2013 * @param string $extrasql
2014 * @return array|bool Array of posts found or false
42fb3c85 2015 */
2b63df96 2016function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
42fb3c85 2017 &$totalcount, $extrasql='') {
4e445355 2018 global $CFG, $DB, $USER;
42fb3c85 2019 require_once($CFG->libdir.'/searchlib.php');
2020
2021 $forums = forum_get_readable_forums($USER->id, $courseid);
2b63df96 2022
67875aa1 2023 if (count($forums) == 0) {
6b7de0bb 2024 $totalcount = 0;
67875aa1 2025 return false;
2026 }
42fb3c85 2027
098f4337 2028 $now = floor(time() / 60) * 60; // DB Cache Friendly.
6b7de0bb 2029
2030 $fullaccess = array();
2031 $where = array();
4e445355 2032 $params = array();
6b7de0bb 2033
2034 foreach ($forums as $forumid => $forum) {
2035 $select = array();
2036
2037 if (!$forum->viewhiddentimedposts) {
b1d5d015
PS
2038 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2039 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
42fb3c85 2040 }
6b7de0bb 2041
2e945910
AB
2042 $cm = $forum->cm;
2043 $context = $forum->context;
ad9c22aa 2044
2045 if ($forum->type == 'qanda'
2046 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
6b7de0bb 2047 if (!empty($forum->onlydiscussions)) {
cf717dc2 2048 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
4e445355 2049 $params = array_merge($params, $discussionid_params);
2050 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
d50704bf 2051 } else {
6b7de0bb 2052 $select[] = "p.parent = 0";
d50704bf 2053 }
2054 }
6b7de0bb 2055
2056 if (!empty($forum->onlygroups)) {
cf717dc2 2057 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
4e445355 2058 $params = array_merge($params, $groupid_params);
2059 $select[] = "d.groupid $groupid_sql";
42fb3c85 2060 }
6b7de0bb 2061
2062 if ($select) {
2063 $selects = implode(" AND ", $select);
b1d5d015
PS
2064 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2065 $params['forum'.$forumid] = $forumid;
6b7de0bb 2066 } else {
2067 $fullaccess[] = $forumid;
2068 }
2069 }
2070
2071 if ($fullaccess) {
cf717dc2 2072 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
4e445355 2073 $params = array_merge($params, $fullid_params);
2074 $where[] = "(d.forum $fullid_sql)";
42fb3c85 2075 }
42fb3c85 2076
6b7de0bb 2077 $selectdiscussion = "(".implode(" OR ", $where).")";
42fb3c85 2078
42fb3c85 2079 $messagesearch = '';
2080 $searchstring = '';
2b63df96 2081
42fb3c85 2082 // Need to concat these back together for parser to work.
2083 foreach($searchterms as $searchterm){
2084 if ($searchstring != '') {
2085 $searchstring .= ' ';
2086 }
2087 $searchstring .= $searchterm;
2088 }
2089
2090 // We need to allow quoted strings for the search. The quotes *should* be stripped
2091 // by the parser, but this should be examined carefully for security implications.
2092 $searchstring = str_replace("\\\"","\"",$searchstring);
2093 $parser = new search_parser();
2094 $lexer = new search_lexer($parser);
2095
2096 if ($lexer->parse($searchstring)) {
2097 $parsearray = $parser->get_parsed_array();
d2ba493c
AH
2098
2099 $tagjoins = '';
2100 $tagfields = [];
e9c46768 2101 $tagfieldcount = 0;
d2ba493c
AH
2102 foreach ($parsearray as $token) {
2103 if ($token->getType() == TOKEN_TAGS) {
e9c46768
AH
2104 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
2105 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
2106 if ($tagfieldcount > 10) {
2107 continue;
2108 }
2109 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
2110 ON p.id = ti_$tagfieldcount.itemid
2111 AND ti_$tagfieldcount.component = 'mod_forum'
2112 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
2113 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
2114 $tagfields[] = "t_$tagfieldcount.rawname";
2115 $tagfieldcount++;
d2ba493c
AH
2116 }
2117 }
2118 }
2f194173
AN
2119 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
2120 'p.userid', 'u.id', 'u.firstname',
d2ba493c
AH
2121 'u.lastname', 'p.modified', 'd.forum',
2122 $tagfields);
004efe66 2123 $params = array_merge($params, $msparams);
42fb3c85 2124 }
2125
d2ba493c
AH
2126 $fromsql = "{forum_posts} p
2127 INNER JOIN {forum_discussions} d ON d.id = p.discussion
2128 INNER JOIN {user} u ON u.id = p.userid $tagjoins";
42fb3c85 2129
2130 $selectsql = " $messagesearch
2131 AND p.discussion = d.id
2132 AND p.userid = u.id
2133 AND $selectdiscussion
2134 $extrasql";
2135
2136 $countsql = "SELECT COUNT(*)
2137 FROM $fromsql
2138 WHERE $selectsql";
2139
a327f25e 2140 $allnames = get_all_user_name_fields(true, 'u');
7f094149 2141 $searchsql = "SELECT p.*,
42fb3c85 2142 d.forum,
a327f25e 2143 $allnames,
42fb3c85 2144 u.email,
8ba59d07 2145 u.picture,
ce7382c9 2146 u.imagealt
42fb3c85 2147 FROM $fromsql
2148 WHERE $selectsql
2149 ORDER BY p.modified DESC";
2150
4e445355 2151 $totalcount = $DB->count_records_sql($countsql, $params);
d50704bf 2152
4e445355 2153 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
42fb3c85 2154}
2155
0a4ac01b 2156/**
2157 * Returns a list of all new posts that have not been mailed yet
df1ba0f4 2158 *
df1ba0f4 2159 * @param int $starttime posts created after this time
2160 * @param int $endtime posts created before this
2161 * @param int $now used for timed discussions only
2162 * @return array
0a4ac01b 2163 */
90f4745c 2164function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
4e445355 2165 global $CFG, $DB;
90f4745c 2166
8076010d
MN
2167 $params = array();
2168 $params['mailed'] = FORUM_MAILED_PENDING;
2169 $params['ptimestart'] = $starttime;
2170 $params['ptimeend'] = $endtime;
2171 $params['mailnow'] = 1;
2172
90f4745c 2173 if (!empty($CFG->forum_enabletimedposts)) {
2174 if (empty($now)) {
2175 $now = time();
2176 }
86a77c91
JM
2177 $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
2178 $params['pptimestart'] = $starttime;
8076010d
MN
2179 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2180 $params['dtimestart'] = $now;
2181 $params['dtimeend'] = $now;
90f4745c 2182 } else {
2183 $timedsql = "";
86a77c91 2184 $selectsql = "AND p.created >= :ptimestart";
90f4745c 2185 }
2186
4e445355 2187 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
8076010d
MN
2188 FROM {forum_posts} p
2189 JOIN {forum_discussions} d ON d.id = p.discussion
2190 WHERE p.mailed = :mailed
86a77c91 2191 $selectsql
8076010d
MN
2192 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2193 $timedsql
2194 ORDER BY p.modified ASC", $params);
1f48942e 2195}
2196
0a4ac01b 2197/**
2198 * Marks posts before a certain time as being mailed already
df1ba0f4 2199 *
2200 * @global object
2201 * @global object
2202 * @param int $endtime
2203 * @param int $now Defaults to time()
2204 * @return bool
0a4ac01b 2205 */
90f4745c 2206function forum_mark_old_posts_as_mailed($endtime, $now=null) {
4e445355 2207 global $CFG, $DB;
8076010d 2208
90f4745c 2209 if (empty($now)) {
2210 $now = time();
2211 }
2212
8076010d
MN
2213 $params = array();
2214 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2215 $params['now'] = $now;
2216 $params['endtime'] = $endtime;
2217 $params['mailnow'] = 1;
2218 $params['mailedpending'] = FORUM_MAILED_PENDING;
2219
90f4745c 2220 if (empty($CFG->forum_enabletimedposts)) {
4e445355 2221 return $DB->execute("UPDATE {forum_posts}
8076010d
MN
2222 SET mailed = :mailedsuccess
2223 WHERE (created < :endtime OR mailnow = :mailnow)
2224 AND mailed = :mailedpending", $params);
0f620d4b 2225 } else {
4e445355 2226 return $DB->execute("UPDATE {forum_posts}
8076010d 2227 SET mailed = :mailedsuccess
90f4745c 2228 WHERE discussion NOT IN (SELECT d.id
8076010d
MN
2229 FROM {forum_discussions} d
2230 WHERE d.timestart > :now)
2231 AND (created < :endtime OR mailnow = :mailnow)
2232 AND mailed = :mailedpending", $params);
0f620d4b 2233 }
3ecca1ee 2234}
2235
0a4ac01b 2236/**
2237 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2238 *
2239 * @global object
2240 * @global object
2241 * @uses CONTEXT_MODULE
2242 * @return array
0a4ac01b 2243 */
1f48942e 2244function forum_get_user_posts($forumid, $userid) {
4e445355 2245 global $CFG, $DB;
1f48942e 2246
90f4745c 2247 $timedsql = "";
4e445355 2248 $params = array($forumid, $userid);
2249
90f4745c 2250 if (!empty($CFG->forum_enabletimedposts)) {
2251 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2252 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2253 $now = time();
4e445355 2254 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2255 $params[] = $now;
2256 $params[] = $now;
6b7de0bb 2257 }
90f4745c 2258 }
2259
a327f25e
AG
2260 $allnames = get_all_user_name_fields(true, 'u');
2261 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 2262 FROM {forum} f
2263 JOIN {forum_discussions} d ON d.forum = f.id
2264 JOIN {forum_posts} p ON p.discussion = d.id
2265 JOIN {user} u ON u.id = p.userid
2266 WHERE f.id = ?
2267 AND p.userid = ?
90f4745c 2268 $timedsql
4e445355 2269 ORDER BY p.modified ASC", $params);
1f48942e 2270}
2271
90f4745c 2272/**
2273 * Get all the discussions user participated in
df1ba0f4 2274 *
2275 * @global object
2276 * @global object
2277 * @uses CONTEXT_MODULE
90f4745c 2278 * @param int $forumid
2279 * @param int $userid
df1ba0f4 2280 * @return array Array or false
90f4745c 2281 */
2282function forum_get_user_involved_discussions($forumid, $userid) {
4e445355 2283 global $CFG, $DB;
90f4745c 2284
2285 $timedsql = "";
4e445355 2286 $params = array($forumid, $userid);
90f4745c 2287 if (!empty($CFG->forum_enabletimedposts)) {
2288 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2289 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2290 $now = time();
4e445355 2291 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2292 $params[] = $now;
2293 $params[] = $now;
6b7de0bb 2294 }
90f4745c 2295 }
2296
4e445355 2297 return $DB->get_records_sql("SELECT DISTINCT d.*
2298 FROM {forum} f
2299 JOIN {forum_discussions} d ON d.forum = f.id
2300 JOIN {forum_posts} p ON p.discussion = d.id
2301 WHERE f.id = ?
2302 AND p.userid = ?
2303 $timedsql", $params);
90f4745c 2304}
2305
2306/**
2307 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2308 *
2309 * @global object
2310 * @global object
90f4745c 2311 * @param int $forumid
2312 * @param int $userid
2313 * @return array of counts or false
2314 */
2315function forum_count_user_posts($forumid, $userid) {
4e445355 2316 global $CFG, $DB;
90f4745c 2317
2318 $timedsql = "";
4e445355 2319 $params = array($forumid, $userid);
90f4745c 2320 if (!empty($CFG->forum_enabletimedposts)) {
2321 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2322 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2323 $now = time();
4e445355 2324 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2325 $params[] = $now;
2326 $params[] = $now;
6b7de0bb 2327 }
90f4745c 2328 }
2329
4e445355 2330 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2331 FROM {forum} f
2332 JOIN {forum_discussions} d ON d.forum = f.id
2333 JOIN {forum_posts} p ON p.discussion = d.id
2334 JOIN {user} u ON u.id = p.userid
2335 WHERE f.id = ?
2336 AND p.userid = ?
2337 $timedsql", $params);
90f4745c 2338}
2339
0a4ac01b 2340/**
2341 * Given a log entry, return the forum post details for it.
df1ba0f4 2342 *
2343 * @global object
2344 * @global object
2345 * @param object $log
2346 * @return array|null
0a4ac01b 2347 */
1f48942e 2348function forum_get_post_from_log($log) {
4e445355 2349 global $CFG, $DB;
1f48942e 2350
a327f25e 2351 $allnames = get_all_user_name_fields(true, 'u');
1f48942e 2352 if ($log->action == "add post") {
2353
a327f25e 2354 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2355 FROM {forum_discussions} d,
2356 {forum_posts} p,
2357 {forum} f,
2358 {user} u
2359 WHERE p.id = ?
65b0e537 2360 AND d.id = p.discussion
2361 AND p.userid = u.id
8f7dc7f1 2362 AND u.deleted <> '1'
4e445355 2363 AND f.id = d.forum", array($log->info));
1f48942e 2364
2365
2366 } else if ($log->action == "add discussion") {
2367
a327f25e 2368 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2369 FROM {forum_discussions} d,
2370 {forum_posts} p,
2371 {forum} f,
2372 {user} u
2373 WHERE d.id = ?
65b0e537 2374 AND d.firstpost = p.id
2375 AND p.userid = u.id
8f7dc7f1 2376 AND u.deleted <> '1'
4e445355 2377 AND f.id = d.forum", array($log->info));
1f48942e 2378 }
2379 return NULL;
2380}
2381
0a4ac01b 2382/**
2383 * Given a discussion id, return the first post from the discussion
df1ba0f4 2384 *
2385 * @global object
2386 * @global object
2387 * @param int $dicsussionid
2388 * @return array
0a4ac01b 2389 */
d05956ac 2390function forum_get_firstpost_from_discussion($discussionid) {
4e445355 2391 global $CFG, $DB;
d05956ac 2392
4e445355 2393 return $DB->get_record_sql("SELECT p.*
2394 FROM {forum_discussions} d,
2395 {forum_posts} p
2396 WHERE d.id = ?
2397 AND d.firstpost = p.id ", array($discussionid));
d05956ac 2398}
2399
0a4ac01b 2400/**
90f4745c 2401 * Returns an array of counts of replies to each discussion
df1ba0f4 2402 *
2403 * @global object
2404 * @global object
2405 * @param int $forumid
2406 * @param string $forumsort
2407 * @param int $limit
2408 * @param int $page
2409 * @param int $perpage
2410 * @return array
0a4ac01b 2411 */
90f4745c 2412function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
4e445355 2413 global $CFG, $DB;
1f48942e 2414
90f4745c 2415 if ($limit > 0) {
2416 $limitfrom = 0;
2417 $limitnum = $limit;
2418 } else if ($page != -1) {
2419 $limitfrom = $page*$perpage;
2420 $limitnum = $perpage;
2421 } else {
2422 $limitfrom = 0;
2423 $limitnum = 0;
2424 }
2425
2426 if ($forumsort == "") {
2427 $orderby = "";
2428 $groupby = "";
2429
2430 } else {
2431 $orderby = "ORDER BY $forumsort";
2432 $groupby = ", ".strtolower($forumsort);
2433 $groupby = str_replace('desc', '', $groupby);
2434 $groupby = str_replace('asc', '', $groupby);
2435 }
2436
bfeb10b7 2437 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2438 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
4e445355 2439 FROM {forum_posts} p
2440 JOIN {forum_discussions} d ON p.discussion = d.id
2441 WHERE p.parent > 0 AND d.forum = ?
bfeb10b7 2442 GROUP BY p.discussion";
4e445355 2443 return $DB->get_records_sql($sql, array($forumid));
bfeb10b7 2444
90f4745c 2445 } else {
bfeb10b7 2446 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
4e445355 2447 FROM {forum_posts} p
2448 JOIN {forum_discussions} d ON p.discussion = d.id
2449 WHERE d.forum = ?
38ec3fb0
AN
2450 GROUP BY p.discussion $groupby $orderby";
2451 return $DB->get_records_sql($sql, array($forumid), $limitfrom, $limitnum);
90f4745c 2452 }
2453}
2454
df1ba0f4 2455/**
2456 * @global object
2457 * @global object
2458 * @global object
2459 * @staticvar array $cache
2460 * @param object $forum
2461 * @param object $cm
2462 * @param object $course
2463 * @return mixed
2464 */
90f4745c 2465function forum_count_discussions($forum, $cm, $course) {
4e445355 2466 global $CFG, $DB, $USER;
90f4745c 2467
2468 static $cache = array();
2469
098f4337 2470 $now = floor(time() / 60) * 60; // DB Cache Friendly.
90f4745c 2471
4e445355 2472 $params = array($course->id);
2473
90f4745c 2474 if (!isset($cache[$course->id])) {
2475 if (!empty($CFG->forum_enabletimedposts)) {
4e445355 2476 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2477 $params[] = $now;
2478 $params[] = $now;
90f4745c 2479 } else {
2480 $timedsql = "";
2481 }
2482
2483 $sql = "SELECT f.id, COUNT(d.id) as dcount
4e445355 2484 FROM {forum} f
2485 JOIN {forum_discussions} d ON d.forum = f.id
2486 WHERE f.course = ?
90f4745c 2487 $timedsql
2488 GROUP BY f.id";
a48e8c4b 2489
4e445355 2490 if ($counts = $DB->get_records_sql($sql, $params)) {
90f4745c 2491 foreach ($counts as $count) {
2492 $counts[$count->id] = $count->dcount;
2493 }
2494 $cache[$course->id] = $counts;
2495 } else {
2496 $cache[$course->id] = array();
2497 }
a48e8c4b 2498 }
90f4745c 2499
2500 if (empty($cache[$course->id][$forum->id])) {
2501 return 0;
a48e8c4b 2502 }
90f4745c 2503
2504 $groupmode = groups_get_activity_groupmode($cm, $course);
2505
2506 if ($groupmode != SEPARATEGROUPS) {
2507 return $cache[$course->id][$forum->id];
1f48942e 2508 }
90f4745c 2509
bf0f06b1 2510 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
90f4745c 2511 return $cache[$course->id][$forum->id];
2512 }
2513
2514 require_once($CFG->dirroot.'/course/lib.php');
2515
f20edd52 2516 $modinfo = get_fast_modinfo($course);
90f4745c 2517
2c1bbbc5 2518 $mygroups = $modinfo->get_groups($cm->groupingid);
90f4745c 2519
2520 // add all groups posts
2c1bbbc5 2521 $mygroups[-1] = -1;
4e445355 2522
2523 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2524 $params[] = $forum->id;
90f4745c 2525
2526 if (!empty($CFG->forum_enabletimedposts)) {
2527 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
4e445355 2528 $params[] = $now;
2529 $params[] = $now;
90f4745c 2530 } else {
2531 $timedsql = "";
2532 }
2533
2534 $sql = "SELECT COUNT(d.id)
4e445355 2535 FROM {forum_discussions} d
342650a7 2536 WHERE d.groupid $mygroups_sql AND d.forum = ?
90f4745c 2537 $timedsql";
2538
4e445355 2539 return $DB->get_field_sql($sql, $params);
1f48942e 2540}
2541
0a4ac01b 2542/**
2543 * Get all discussions in a forum
df1ba0f4 2544 *
2545 * @global object
2546 * @global object
2547 * @global object
2548 * @uses CONTEXT_MODULE
2549 * @uses VISIBLEGROUPS
2550 * @param object $cm
2551 * @param string $forumsort
2552 * @param bool $fullpost
2553 * @param int $unused
2554 * @param int $limit
2555 * @param bool $userlastmodified
2556 * @param int $page
2557 * @param int $perpage
4f3a2d21
JL
2558 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
2559 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
65b2669d 2560 * @param int $updatedsince retrieve only discussions updated since the given time
df1ba0f4 2561 * @return array
0a4ac01b 2562 */
1e366657 2563function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
02a73d76 2564 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
65b2669d 2565 $updatedsince = 0) {
4e445355 2566 global $CFG, $DB, $USER;
0fcac008 2567
3d284127 2568 $timelimit = '';
2569
098f4337 2570 $now = floor(time() / 60) * 60;
4e445355 2571 $params = array($cm->instance);
90f4745c 2572
bf0f06b1 2573 $modcontext = context_module::instance($cm->id);
2b63df96 2574
4436a63b 2575 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2576 return array();
2577 }
2578
2579 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2b63df96 2580
0468976c 2581 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2582 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2583 $params[] = $now;
2584 $params[] = $now;
90f4745c 2585 if (isloggedin()) {
4e445355 2586 $timelimit .= " OR d.userid = ?";
2587 $params[] = $USER->id;
3d284127 2588 }
90f4745c 2589 $timelimit .= ")";
fbc21e82 2590 }
fbc21e82 2591 }
1f48942e 2592
90f4745c 2593 if ($limit > 0) {
2594 $limitfrom = 0;
2595 $limitnum = $limit;
2596 } else if ($page != -1) {
2597 $limitfrom = $page*$perpage;
2598 $limitnum = $perpage;
2599 } else {
2600 $limitfrom = 0;
2601 $limitnum = 0;
90ec387a 2602 }
8f0cd6ef 2603
90f4745c 2604 $groupmode = groups_get_activity_groupmode($cm);
353228d8 2605
fffa8b35 2606 if ($groupmode) {
4f3a2d21 2607
fffa8b35 2608 if (empty($modcontext)) {
bf0f06b1 2609 $modcontext = context_module::instance($cm->id);
fffa8b35 2610 }
2611
4f3a2d21
JL
2612 // Special case, we received a groupid to override currentgroup.
2613 if ($groupid > 0) {
2614 $course = get_course($cm->course);
2615 if (!groups_group_visible($groupid, $course, $cm)) {
2616 // User doesn't belong to this group, return nothing.
2617 return array();
2618 }
2619 $currentgroup = $groupid;
2620 } else if ($groupid === -1) {
2621 $currentgroup = groups_get_activity_group($cm);
2622 } else {
2623 // Get discussions for all groups current user can see.
2624 $currentgroup = null;
2625 }
2626
fffa8b35 2627 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2628 if ($currentgroup) {
4e445355 2629 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2630 $params[] = $currentgroup;
fffa8b35 2631 } else {
2632 $groupselect = "";
2633 }
2634
2635 } else {
4f3a2d21
JL
2636 // Separate groups.
2637
2638 // Get discussions for all groups current user can see.
2639 if ($currentgroup === null) {
2640 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
2641 if (empty($mygroups)) {
2642 $groupselect = "AND d.groupid = -1";
2643 } else {
2644 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
2645 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
2646 $params = array_merge($params, $inparamsgroups);
2647 }
2648 } else if ($currentgroup) {
4e445355 2649 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2650 $params[] = $currentgroup;
fffa8b35 2651 } else {
2652 $groupselect = "AND d.groupid = -1";
2653 }
2654 }
353228d8 2655 } else {
02509fe6 2656 $groupselect = "";
2657 }
29507631 2658 if (empty($forumsort)) {
1e366657 2659 $forumsort = forum_get_default_sort_order();
29507631 2660 }
2ab968e9 2661 if (empty($fullpost)) {
b879effb 2662 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2ab968e9 2663 } else {
2664 $postdata = "p.*";
2665 }
9197e147 2666
13597d01 2667 if (empty($userlastmodified)) { // We don't need to know this
fffa8b35 2668 $umfields = "";
2669 $umtable = "";
13597d01 2670 } else {
d85bedf7
JL
2671 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
2672 um.imagealt AS umimagealt';
4e445355 2673 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
90f4745c 2674 }
2675
65b2669d
JL
2676 $updatedsincesql = '';
2677 if (!empty($updatedsince)) {
2678 $updatedsincesql = 'AND d.timemodified > ?';
2679 $params[] = $updatedsince;
2680 }
2681
a327f25e 2682 $allnames = get_all_user_name_fields(true, 'u');
5f219cf1 2683 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, $allnames,
a327f25e 2684 u.email, u.picture, u.imagealt $umfields
4e445355 2685 FROM {forum_discussions} d
2686 JOIN {forum_posts} p ON p.discussion = d.id
2687 JOIN {user} u ON p.userid = u.id
90f4745c 2688 $umtable
4e445355 2689 WHERE d.forum = ? AND p.parent = 0
65b2669d 2690 $timelimit $groupselect $updatedsincesql
5f219cf1 2691 ORDER BY $forumsort, d.id DESC";
65b2669d 2692
4e445355 2693 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
90f4745c 2694}
2695
8d3a5ba1
FM
2696/**
2697 * Gets the neighbours (previous and next) of a discussion.
2698 *
5f219cf1
BK
2699 * The calculation is based on the timemodified when time modified or time created is identical
2700 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
8d3a5ba1 2701 *
9e381efd
DM
2702 * For blog-style forums, the calculation is based on the original creation time of the
2703 * blog post.
2704 *
8d3a5ba1
FM
2705 * Please note that this does not check whether or not the discussion passed is accessible
2706 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2707 * the returned neighbours are checked and are accessible to the current user.
2708 *
2709 * @param object $cm The CM record.
2710 * @param object $discussion The discussion record.
9e381efd 2711 * @param object $forum The forum instance record.
8d3a5ba1
FM
2712 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2713 * they contain the record with minimal information such as 'id' and 'name'.
2714 * When the neighbour is not found the value is false.
2715 */
9e381efd 2716function forum_get_discussion_neighbours($cm, $discussion, $forum) {
8d3a5ba1
FM
2717 global $CFG, $DB, $USER;
2718
9e381efd 2719 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
8d3a5ba1
FM
2720 throw new coding_exception('Discussion is not part of the same forum.');
2721 }
2722
2723 $neighbours = array('prev' => false, 'next' => false);
098f4337 2724 $now = floor(time() / 60) * 60;
8d3a5ba1
FM
2725 $params = array();
2726
2727 $modcontext = context_module::instance($cm->id);
2728 $groupmode = groups_get_activity_groupmode($cm);
2729 $currentgroup = groups_get_activity_group($cm);
2730
2731 // Users must fulfill timed posts.
2732 $timelimit = '';
2733 if (!empty($CFG->forum_enabletimedposts)) {
2734 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2735 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2736 $params['tltimestart'] = $now;
2737 $params['tltimeend'] = $now;
2738 if (isloggedin()) {
2739 $timelimit .= ' OR d.userid = :tluserid';
2740 $params['tluserid'] = $USER->id;
2741 }
2742 $timelimit .= ')';
2743 }
2744 }
2745
2746 // Limiting to posts accessible according to groups.
2747 $groupselect = '';
2748 if ($groupmode) {
2749 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2750 if ($currentgroup) {
2751 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2752 $params['groupid'] = $currentgroup;
2753 }
2754 } else {
2755 if ($currentgroup) {
2756 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2757 $params['groupid'] = $currentgroup;
2758 } else {
2759 $groupselect = 'AND d.groupid = -1';
2760 }
2761 }
2762 }
2763
5f219cf1
BK
2764 $params['forumid'] = $cm->instance;
2765 $params['discid1'] = $discussion->id;
2766 $params['discid2'] = $discussion->id;
2767 $params['discid3'] = $discussion->id;
2768 $params['discid4'] = $discussion->id;
2769 $params['disctimecompare1'] = $discussion->timemodified;
2770 $params['disctimecompare2'] = $discussion->timemodified;
2771 $params['pinnedstate1'] = (int) $discussion->pinned;
2772 $params['pinnedstate2'] = (int) $discussion->pinned;
2773 $params['pinnedstate3'] = (int) $discussion->pinned;
2774 $params['pinnedstate4'] = (int) $discussion->pinned;
9e381efd 2775
5f219cf1
BK
2776 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2777 FROM {forum_discussions} d
2778 JOIN {forum_posts} p ON d.firstpost = p.id
2779 WHERE d.forum = :forumid
2780 AND d.id <> :discid1
2781 $timelimit
2782 $groupselect";
2783 $comparefield = "d.timemodified";
2784 $comparevalue = ":disctimecompare1";
2785 $comparevalue2 = ":disctimecompare2";
2786 if (!empty($CFG->forum_enabletimedposts)) {
2787 // Here we need to take into account the release time (timestart)
2788 // if one is set, of the neighbouring posts and compare it to the
2789 // timestart or timemodified of *this* post depending on if the
2790 // release date of this post is in the future or not.
2791 // This stops discussions that appear later because of the
2792 // timestart value from being buried under discussions that were
2793 // made afterwards.
2794 $comparefield = "CASE WHEN d.timemodified < d.timestart
2795 THEN d.timestart ELSE d.timemodified END";
2796 if ($discussion->timemodified < $discussion->timestart) {
2797 // Normally we would just use the timemodified for sorting
2798 // discussion posts. However, when timed discussions are enabled,
2799 // then posts need to be sorted base on the later of timemodified
2800 // or the release date of the post (timestart).
2801 $params['disctimecompare1'] = $discussion->timestart;
2802 $params['disctimecompare2'] = $discussion->timestart;
2803 }
2804 }
2805 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
2806 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
9e381efd 2807
5f219cf1
BK
2808 if ($forum->type === 'blog') {
2809 $subselect = "SELECT pp.created
2810 FROM {forum_discussions} dd
2811 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
8d3a5ba1 2812
5f219cf1
BK
2813 $subselectwhere1 = " WHERE dd.id = :discid3";
2814 $subselectwhere2 = " WHERE dd.id = :discid4";
8d3a5ba1 2815
5f219cf1 2816 $comparefield = "p.created";
9e381efd 2817
5f219cf1
BK
2818 $sub1 = $subselect.$subselectwhere1;
2819 $comparevalue = "($sub1)";
9e381efd 2820
5f219cf1
BK
2821 $sub2 = $subselect.$subselectwhere2;
2822 $comparevalue2 = "($sub2)";
8d3a5ba1 2823
5f219cf1
BK
2824 $orderbydesc = "d.pinned, p.created DESC";
2825 $orderbyasc = "d.pinned, p.created ASC";
2826 }
1e366657 2827
5f219cf1
BK
2828 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
2829 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
2830 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
2831 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
9e381efd 2832
5f219cf1
BK
2833 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
2834 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
2835 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
2836 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
8d3a5ba1 2837
5f219cf1
BK
2838 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2839 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
8d3a5ba1
FM
2840 return $neighbours;
2841}
2842
1e366657
AO
2843/**
2844 * Get the sql to use in the ORDER BY clause for forum discussions.
2845 *
2846 * This has the ordering take timed discussion windows into account.
2847 *
2848 * @param bool $desc True for DESC, False for ASC.
2849 * @param string $compare The field in the SQL to compare to normally sort by.
2850 * @param string $prefix The prefix being used for the discussion table.
5f219cf1 2851 * @param bool $pinned sort pinned posts to the top
1e366657
AO
2852 * @return string
2853 */
5f219cf1 2854function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1e366657
AO
2855 global $CFG;
2856
2857 if (!empty($prefix)) {
2858 $prefix .= '.';
2859 }
2860
2861 $dir = $desc ? 'DESC' : 'ASC';
2862
5f219cf1
BK
2863 if ($pinned == true) {
2864 $pinned = "{$prefix}pinned DESC,";
2865 } else {
2866 $pinned = '';
2867 }
2868
1e366657
AO
2869 $sort = "{$prefix}timemodified";
2870 if (!empty($CFG->forum_enabletimedposts)) {
2871 $sort = "CASE WHEN {$compare} < {$prefix}timestart
2872 THEN {$prefix}timestart
2873 ELSE {$compare}
2874 END";
2875 }
5f219cf1 2876 return "$pinned $sort $dir";
1e366657
AO
2877}
2878
df1ba0f4 2879/**
2880 *
2881 * @global object
2882 * @global object
2883 * @global object
2884 * @uses CONTEXT_MODULE
2885 * @uses VISIBLEGROUPS
2886 * @param object $cm
2887 * @return array
2888 */
bfeb10b7 2889function forum_get_discussions_unread($cm) {
4e445355 2890 global $CFG, $DB, $USER;
90f4745c 2891
098f4337 2892 $now = floor(time() / 60) * 60;
ee151230 2893 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
35716b86 2894
ee151230 2895 $params = array();
90f4745c 2896 $groupmode = groups_get_activity_groupmode($cm);
2897 $currentgroup = groups_get_activity_group($cm);
2898
2899 if ($groupmode) {
bf0f06b1 2900 $modcontext = context_module::instance($cm->id);
90f4745c 2901
2902 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2903 if ($currentgroup) {
ee151230
AD
2904 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2905 $params['currentgroup'] = $currentgroup;
90f4745c 2906 } else {
2907 $groupselect = "";
2908 }
2909
2910 } else {
ee151230 2911 //separate groups without access all
90f4745c 2912 if ($currentgroup) {
ee151230
AD
2913 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2914 $params['currentgroup'] = $currentgroup;
90f4745c 2915 } else {
2916 $groupselect = "AND d.groupid = -1";
2917 }
2918 }
2919 } else {
2920 $groupselect = "";
13597d01 2921 }
2922
90f4745c 2923 if (!empty($CFG->forum_enabletimedposts)) {
ee151230
AD
2924 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2925 $params['now1'] = $now;
2926 $params['now2'] = $now;
90f4745c 2927 } else {
2928 $timedsql = "";
2929 }
2930
2931 $sql = "SELECT d.id, COUNT(p.id) AS unread
4e445355 2932 FROM {forum_discussions} d
2933 JOIN {forum_posts} p ON p.discussion = d.id
2934 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
90f4745c 2935 WHERE d.forum = {$cm->instance}
ee151230 2936 AND p.modified >= :cutoffdate AND r.id is NULL
90f4745c 2937 $groupselect
4e445355 2938 $timedsql
bfeb10b7 2939 GROUP BY d.id";
ee151230
AD
2940 $params['cutoffdate'] = $cutoffdate;
2941
4e445355 2942 if ($unreads = $DB->get_records_sql($sql, $params)) {
90f4745c 2943 foreach ($unreads as $unread) {
2944 $unreads[$unread->id] = $unread->unread;
2945 }
2946 return $unreads;
2947 } else {
2948 return array();
2949 }
1f48942e 2950}
2951
df1ba0f4 2952/**
2953 * @global object
2954 * @global object
2955 * @global object
2956 * @uses CONEXT_MODULE
2957 * @uses VISIBLEGROUPS
2958 * @param object $cm
2959 * @return array
2960 */
90f4745c 2961function forum_get_discussions_count($cm) {
4e445355 2962 global $CFG, $DB, $USER;
90f4745c 2963
098f4337 2964 $now = floor(time() / 60) * 60;
4e445355 2965 $params = array($cm->instance);
90f4745c 2966 $groupmode = groups_get_activity_groupmode($cm);
2967 $currentgroup = groups_get_activity_group($cm);
2968
2969 if ($groupmode) {
bf0f06b1 2970 $modcontext = context_module::instance($cm->id);
90f4745c 2971
2972 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2973 if ($currentgroup) {
4e445355 2974 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2975 $params[] = $currentgroup;
90f4745c 2976 } else {
2977 $groupselect = "";
2978 }
2979
2980 } else {
2981 //seprate groups without access all
2982 if ($currentgroup) {
4e445355 2983 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2984 $params[] = $currentgroup;
90f4745c 2985 } else {
2986 $groupselect = "AND d.groupid = -1";
2987 }
2988 }
2989 } else {
2990 $groupselect = "";
2991 }
2992
90f4745c 2993 $timelimit = "";
2994
2995 if (!empty($CFG->forum_enabletimedposts)) {
2996
bf0f06b1 2997 $modcontext = context_module::instance($cm->id);
90f4745c 2998
2999 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 3000 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
3001 $params[] = $now;
3002 $params[] = $now;
90f4745c 3003 if (isloggedin()) {
4e445355 3004 $timelimit .= " OR d.userid = ?";
3005 $params[] = $USER->id;
90f4745c 3006 }
3007 $timelimit .= ")";
3008 }
3009 }
3010
3011 $sql = "SELECT COUNT(d.id)
4e445355 3012 FROM {forum_discussions} d
3013 JOIN {forum_posts} p ON p.discussion = d.id
3014 WHERE d.forum = ? AND p.parent = 0
3015 $groupselect $timelimit";
90f4745c 3016
4e445355 3017 return $DB->get_field_sql($sql, $params);
90f4745c 3018}
1f48942e 3019
3020
0a4ac01b 3021// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 3022
3023
df1ba0f4 3024/**
3025 * @global object
3026 * @global object
3027 * @param int $courseid
3028 * @param string $type
3029 */
11b0c469 3030function forum_get_course_forum($courseid, $type) {
3031// How to set up special 1-per-course forums
c112bc60 3032 global $CFG, $DB, $OUTPUT, $USER;
a6fcdf98 3033
4e445355 3034 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
65b0e537 3035 // There should always only be ONE, but with the right combination of
29cbd93a 3036 // errors there might be more. In this case, just return the oldest one (lowest ID).
3037 foreach ($forums as $forum) {
3038 return $forum; // ie the first one
11b0c469 3039 }
8daaf761 3040 }
e6874d9f 3041
8daaf761 3042 // Doesn't exist, so create one now.
b85b25eb 3043 $forum = new stdClass();
8daaf761 3044 $forum->course = $courseid;
3045 $forum->type = "$type";
c112bc60
ARN
3046 if (!empty($USER->htmleditor)) {
3047 $forum->introformat = $USER->htmleditor;
3048 }
8daaf761 3049 switch ($forum->type) {
3050 case "news":
294ce987 3051 $forum->name = get_string("namenews", "forum");
3052 $forum->intro = get_string("intronews", "forum");
906fef94 3053 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 3054 $forum->assessed = 0;
709f0ec8 3055 if ($courseid == SITEID) {
3056 $forum->name = get_string("sitenews");
3057 $forum->forcesubscribe = 0;
8f0cd6ef 3058 }
8daaf761 3059 break;
3060 case "social":
294ce987 3061 $forum->name = get_string("namesocial", "forum");
3062 $forum->intro = get_string("introsocial", "forum");
8daaf761 3063 $forum->assessed = 0;
3064 $forum->forcesubscribe = 0;
3065 break;
1c7b8b93
NC
3066 case "blog":
3067 $forum->name = get_string('blogforum', 'forum');
3068 $forum->intro = get_string('introblog', 'forum');
3069 $forum->assessed = 0;
3070 $forum->forcesubscribe = 0;
3071 break;
8daaf761 3072 default:
9146b979 3073 echo $OUTPUT->notification("That forum type doesn't exist!");
8daaf761 3074 return false;
3075 break;
3076 }
3077
3078 $forum->timemodified = time();
4e445355 3079 $forum->id = $DB->insert_record("forum", $forum);
8daaf761 3080
4e445355 3081 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
9146b979 3082 echo $OUTPUT->notification("Could not find forum module!!");
e1b5643f 3083 return false;
82aa0e8d 3084 }
39790bd8 3085 $mod = new stdClass();
e1b5643f 3086 $mod->course = $courseid;
3087 $mod->module = $module->id;
3088 $mod->instance = $forum->id;
3089 $mod->section = 0;
722e6ba9
MG
3090 include_once("$CFG->dirroot/course/lib.php");
3091 if (! $mod->coursemodule = add_course_module($mod) ) {
11cd754e 3092 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
e1b5643f 3093 return false;
3094 }
722e6ba9 3095 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
4e445355 3096 return $DB->get_record("forum", array("id" => "$forum->id"));
82aa0e8d 3097}
3098
0a4ac01b 3099/**
21976af1 3100 * Print a forum post
65bcf17b 3101 *
df1ba0f4 3102 * @global object
3103 * @global object
3104 * @uses FORUM_MODE_THREADED
3105 * @uses PORTFOLIO_FORMAT_PLAINHTML
3106 * @uses PORTFOLIO_FORMAT_FILE
3107 * @uses PORTFOLIO_FORMAT_RICHHTML
3108 * @uses PORTFOLIO_ADD_TEXT_LINK
3109 * @uses CONTEXT_MODULE
21976af1 3110 * @param object $post The post to print.
df1ba0f4 3111 * @param object $discussion
3112 * @param object $forum
3113 * @param object $cm
3114 * @param object $course
21976af1 3115 * @param boolean $ownpost Whether this post belongs to the current user.
65bcf17b 3116 * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
21976af1 3117 * @param boolean $link Just print a shortened version of the post as a link to the full post.
21976af1 3118 * @param string $footer Extra stuff to print after the message.
3119 * @param string $highlight Space-separated list of terms to highlight.
3120 * @param int $post_read true, false or -99. If we already know whether this user
3121 * has read this post, pass that in, otherwise, pass in -99, and this
3122 * function will work it out.