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