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