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