MDL-41851 mod_forum: Use noreply user when sending forum notifications
[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
39790bd8 778 $eventdata = new stdClass();
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;
6ee2611c 789
e9c55e39
RT
790 // If forum_replytouser is not set then send mail using the noreplyaddress.
791 if (empty($CFG->forum_replytouser)) {
7cd4a0f6 792 $eventdata->userfrom = core_user::get_noreply_user();
e9c55e39
RT
793 }
794
6ee2611c 795 $smallmessagestrings = new stdClass();
49566c8a
AN
796 $smallmessagestrings->user = fullname($userfrom);
797 $smallmessagestrings->forumname = "$shortname: " . format_string($forum->name, true) . ": " . $discussion->name;
798 $smallmessagestrings->message = $post->message;
799
800 // Make sure strings are in message recipients language.
4ffa1463 801 $eventdata->smallmessage = get_string_manager()->get_string('smallmessage', 'forum', $smallmessagestrings, $userto->lang);
14a0e7dd 802
49566c8a
AN
803 $contexturl = new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id), 'p' . $post->id);
804 $eventdata->contexturl = $contexturl->out();
14a0e7dd 805 $eventdata->contexturlname = $discussion->name;
3b120e46 806
505ab5aa 807 $mailresult = message_send($eventdata);
49566c8a 808 if (!$mailresult) {
505ab5aa 809 mtrace("Error: mod/forum/lib.php forum_cron(): Could not send out mail for id $post->id to user $userto->id".
49566c8a 810 " ($userto->email) .. not trying again.");
4dad2828 811 $errorcount[$post->id]++;
4dad2828 812 } else {
813 $mailcount[$post->id]++;
814
49566c8a 815 // Mark post as read if forum_usermarksread is set off.
90f4745c 816 if (!$CFG->forum_usermarksread) {
817 $userto->markposts[$post->id] = $post->id;
caadf009 818 }
aaf7a9dc 819 }
4dad2828 820
49566c8a 821 mtrace('post ' . $post->id . ': ' . $post->subject);
aaf7a9dc 822 }
90f4745c 823
49566c8a 824 // Mark processed posts as read.
90f4745c 825 forum_tp_mark_posts_read($userto, $userto->markposts);
103f34d8 826 unset($userto);
5fac3a5e 827 }
828 }
829
830 if ($posts) {
831 foreach ($posts as $post) {
16b4e5b6 832 mtrace($mailcount[$post->id]." users were sent post $post->id, '$post->subject'");
5fac3a5e 833 if ($errorcount[$post->id]) {
8076010d 834 $DB->set_field('forum_posts', 'mailed', FORUM_MAILED_ERROR, array('id' => $post->id));
a974c799 835 }
aaf7a9dc 836 }
837 }
838
8cb121cc 839 // release some memory
840 unset($subscribedusers);
841 unset($mailcount);
842 unset($errorcount);
843
e8b7114d 844 cron_setup_user();
ad9ff3d3 845
9152fc99 846 $sitetimezone = $CFG->timezone;
944a2b28 847
0a4ac01b 848 // Now see if there are any digest mails waiting to be sent, and if we should send them
aaf7a9dc 849
f3c3a4d3 850 mtrace('Starting digest processing...');
851
3ef7279f 852 core_php_time_limit::raise(300); // terminate if not able to fetch all digests in 5 minutes
910b6fa7 853
8f0cd6ef 854 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
ca8e8a10 855 set_config('digestmailtimelast', 0);
856 }
857
858 $timenow = time();
944a2b28 859 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
ca8e8a10 860
f3c3a4d3 861 // Delete any really old ones (normally there shouldn't be any)
862 $weekago = $timenow - (7 * 24 * 3600);
2ac897cd 863 $DB->delete_records_select('forum_queue', "timemodified < ?", array($weekago));
910b6fa7 864 mtrace ('Cleaned old digest records');
9f2ded76 865
ca8e8a10 866 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
b140ae85 867
b140ae85 868 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
869
4e445355 870 $digestposts_rs = $DB->get_recordset_select('forum_queue', "timemodified < ?", array($digesttime));
910b6fa7 871
4e445355 872 if ($digestposts_rs->valid()) {
8ad64455 873
aaf7a9dc 874 // We have work to do
875 $usermailcount = 0;
aaf7a9dc 876
a974c799 877 //caches - reuse the those filled before too
aaf7a9dc 878 $discussionposts = array();
879 $userdiscussions = array();
a974c799 880
4e445355 881 foreach ($digestposts_rs as $digestpost) {
a974c799 882 if (!isset($posts[$digestpost->postid])) {
4e445355 883 if ($post = $DB->get_record('forum_posts', array('id' => $digestpost->postid))) {
a974c799 884 $posts[$digestpost->postid] = $post;
885 } else {
886 continue;
887 }
888 }
889 $discussionid = $digestpost->discussionid;
890 if (!isset($discussions[$discussionid])) {
4e445355 891 if ($discussion = $DB->get_record('forum_discussions', array('id' => $discussionid))) {
a974c799 892 $discussions[$discussionid] = $discussion;
893 } else {
894 continue;
895 }
aaf7a9dc 896 }
a974c799 897 $forumid = $discussions[$discussionid]->forum;
898 if (!isset($forums[$forumid])) {
4e445355 899 if ($forum = $DB->get_record('forum', array('id' => $forumid))) {
a974c799 900 $forums[$forumid] = $forum;
901 } else {
902 continue;
903 }
904 }
905
906 $courseid = $forums[$forumid]->course;
907 if (!isset($courses[$courseid])) {
4e445355 908 if ($course = $DB->get_record('course', array('id' => $courseid))) {
a974c799 909 $courses[$courseid] = $course;
910 } else {
911 continue;
912 }
aaf7a9dc 913 }
a974c799 914
915 if (!isset($coursemodules[$forumid])) {
916 if ($cm = get_coursemodule_from_instance('forum', $forumid, $courseid)) {
917 $coursemodules[$forumid] = $cm;
918 } else {
919 continue;
920 }
aaf7a9dc 921 }
922 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
923 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
924 }
4e445355 925 $digestposts_rs->close(); /// Finished iteration, let's close the resultset
aaf7a9dc 926
927 // Data collected, start sending out emails to each user
a974c799 928 foreach ($userdiscussions as $userid => $thesediscussions) {
aaf7a9dc 929
3ef7279f 930 core_php_time_limit::raise(120); // terminate if processing of any account takes longer than 2 minutes
aaf7a9dc 931
e8b7114d 932 cron_setup_user();
90f4745c 933
a974c799 934 mtrace(get_string('processingdigest', 'forum', $userid), '... ');
aaf7a9dc 935
936 // First of all delete all the queue entries for this user
4e445355 937 $DB->delete_records_select('forum_queue', "userid = ? AND timemodified < ?", array($userid, $digesttime));
aaf7a9dc 938
103f34d8
PS
939 // Init user caches - we keep the cache for one cycle only,
940 // otherwise it would unnecessarily consume memory.
941 if (array_key_exists($userid, $users) and isset($users[$userid]->username)) {
942 $userto = clone($users[$userid]);
943 } else {
944 $userto = $DB->get_record('user', array('id' => $userid));
945 forum_cron_minimise_user_record($userto);
946 }
df1c2c71 947 $userto->viewfullnames = array();
948 $userto->canpost = array();
90f4745c 949 $userto->markposts = array();
df1c2c71 950
103f34d8
PS
951 // Override the language and timezone of the "current" user, so that
952 // mail is customised for the receiver.
953 cron_setup_user($userto);
954
a974c799 955 $postsubject = get_string('digestmailsubject', 'forum', format_string($site->shortname, true));
aaf7a9dc 956
39790bd8 957 $headerdata = new stdClass();
a974c799 958 $headerdata->sitename = format_string($site->fullname, true);
839f2456 959 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&amp;course='.$site->id;
aaf7a9dc 960
961 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
962 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
9c674431 963
78c0d909 964 $posthtml = "<head>";
78946b9b
PS
965/* foreach ($CFG->stylesheets as $stylesheet) {
966 //TODO: MDL-21120
78c0d909 967 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
78946b9b 968 }*/
449b1c1a 969 $posthtml .= "</head>\n<body id=\"email\">\n";
a0330747 970 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
aaf7a9dc 971
a974c799 972 foreach ($thesediscussions as $discussionid) {
aaf7a9dc 973
3ef7279f 974 core_php_time_limit::raise(120); // to be reset for each post
a974c799 975
976 $discussion = $discussions[$discussionid];
977 $forum = $forums[$discussion->forum];
978 $course = $courses[$forum->course];
979 $cm = $coursemodules[$forum->id];
65b0e537 980
9152fc99 981 //override language
e8b7114d 982 cron_setup_user($userto, $course);
9152fc99 983
df1c2c71 984 // Fill caches
985 if (!isset($userto->viewfullnames[$forum->id])) {
bf0f06b1 986 $modcontext = context_module::instance($cm->id);
df1c2c71 987 $userto->viewfullnames[$forum->id] = has_capability('moodle/site:viewfullnames', $modcontext);
988 }
8b79a625 989 if (!isset($userto->canpost[$discussion->id])) {
bf0f06b1 990 $modcontext = context_module::instance($cm->id);
8b79a625 991 $userto->canpost[$discussion->id] = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
df1c2c71 992 }
caadf009 993
de85c320 994 $strforums = get_string('forums', 'forum');
59075a43 995 $canunsubscribe = ! \mod_forum\subscriptions::is_forcesubscribed($forum);
8b79a625 996 $canreply = $userto->canpost[$discussion->id];
bf0f06b1 997 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
de85c320 998
aaf7a9dc 999 $posttext .= "\n \n";
1000 $posttext .= '=====================================================================';
1001 $posttext .= "\n \n";
8ebbb06a 1002 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
aaf7a9dc 1003 if ($discussion->name != $forum->name) {
c78ac798 1004 $posttext .= " -> ".format_string($discussion->name,true);
caadf009 1005 }
aaf7a9dc 1006 $posttext .= "\n";
3f213cd3
DNA
1007 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
1008 $posttext .= "\n";
65b0e537 1009
aaf7a9dc 1010 $posthtml .= "<p><font face=\"sans-serif\">".
8ebbb06a 1011 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$shortname</a> -> ".
aaf7a9dc 1012 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
3849dae8 1013 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
aaf7a9dc 1014 if ($discussion->name == $forum->name) {
1015 $posthtml .= "</font></p>";
caadf009 1016 } else {
c78ac798 1017 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
caadf009 1018 }
aaf7a9dc 1019 $posthtml .= '<p>';
1020
e1c6dde1 1021 $postsarray = $discussionposts[$discussionid];
1022 sort($postsarray);
1023
857b798b 1024 foreach ($postsarray as $postid) {
a974c799 1025 $post = $posts[$postid];
1026
1027 if (array_key_exists($post->userid, $users)) { // we might know him/her already
1028 $userfrom = $users[$post->userid];
103f34d8
PS
1029 if (!isset($userfrom->idnumber)) {
1030 $userfrom = $DB->get_record('user', array('id' => $userfrom->id));
1031 forum_cron_minimise_user_record($userfrom);
1032 }
1033
4e445355 1034 } else if ($userfrom = $DB->get_record('user', array('id' => $post->userid))) {
103f34d8
PS
1035 forum_cron_minimise_user_record($userfrom);
1036 if ($userscount <= FORUM_CRON_USER_CACHE) {
1037 $userscount++;
1038 $users[$userfrom->id] = $userfrom;
1039 }
1040
df1c2c71 1041 } else {
a974c799 1042 mtrace('Could not find user '.$post->userid);
aaf7a9dc 1043 continue;
1044 }
1045
df1c2c71 1046 if (!isset($userfrom->groups[$forum->id])) {
1047 if (!isset($userfrom->groups)) {
1048 $userfrom->groups = array();
103f34d8
PS
1049 if (isset($users[$userfrom->id])) {
1050 $users[$userfrom->id]->groups = array();
1051 }
df1c2c71 1052 }
1053 $userfrom->groups[$forum->id] = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
103f34d8
PS
1054 if (isset($users[$userfrom->id])) {
1055 $users[$userfrom->id]->groups[$forum->id] = $userfrom->groups[$forum->id];
1056 }
df1c2c71 1057 }
1058
c9fa2dee
AN
1059 // Headers to help prevent auto-responders.
1060 $userfrom->customheaders = array(
1061 "Precedence: Bulk",
1062 'X-Auto-Response-Suppress: All',
1063 'Auto-Submitted: auto-generated',
1064 );
857b798b 1065
8e08c731
AN
1066 $maildigest = forum_get_user_maildigest_bulk($digests, $userto, $forum->id);
1067 if ($maildigest == 2) {
3f213cd3
DNA
1068 // Subjects and link only
1069 $posttext .= "\n";
1070 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
39790bd8 1071 $by = new stdClass();
aaf7a9dc 1072 $by->name = fullname($userfrom);
1073 $by->date = userdate($post->modified);
17dc3f3c 1074 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
aaf7a9dc 1075 $posttext .= "\n---------------------------------------------------------------------";
1076
839f2456 1077 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&amp;course=$course->id\">$by->name</a>";
0be4d8bf 1078 $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 1079
1080 } else {
aaf7a9dc 1081 // The full treatment
0faf6791 1082 $posttext .= forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, true);
1083 $posthtml .= forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto, false, $canreply, true, false);
df1c2c71 1084
0a4ac01b 1085 // Create an array of postid's for this user to mark as read.
90f4745c 1086 if (!$CFG->forum_usermarksread) {
1087 $userto->markposts[$post->id] = $post->id;
f37da850 1088 }
aaf7a9dc 1089 }
1090 }
b28118f6 1091 $footerlinks = array();
aaf7a9dc 1092 if ($canunsubscribe) {
b28118f6 1093 $footerlinks[] = "<a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">" . get_string("unsubscribe", "forum") . "</a>";
857b798b 1094 } else {
b28118f6 1095 $footerlinks[] = get_string("everyoneissubscribed", "forum");
aaf7a9dc 1096 }
b28118f6
AN
1097 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string("digestmailpost", "forum") . '</a>';
1098 $posthtml .= "\n<div class='mdl-right'><font size=\"1\">" . implode('&nbsp;', $footerlinks) . '</font></div>';
aaf7a9dc 1099 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
caadf009 1100 }
a0330747 1101 $posthtml .= '</body>';
caadf009 1102
6d2e6936 1103 if (empty($userto->mailformat) || $userto->mailformat != 1) {
379a42cb 1104 // This user DOESN'T want to receive HTML
1105 $posthtml = '';
1106 }
5e7f2b0b 1107
b58bd1a2 1108 $attachment = $attachname='';
f2719728
DP
1109 // Directly email forum digests rather than sending them via messaging, use the
1110 // site shortname as 'from name', the noreply address will be used by email_to_user.
a7a1e05f 1111 $mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml, $attachment, $attachname);
b58bd1a2
AD
1112
1113 if (!$mailresult) {
33c40cc6
DP
1114 mtrace("ERROR: mod/forum/cron.php: Could not send out digest mail to user $userto->id ".
1115 "($userto->email)... not trying again.");
aaf7a9dc 1116 } else {
b140ae85 1117 mtrace("success.");
aaf7a9dc 1118 $usermailcount++;
e3ff14ca 1119
90f4745c 1120 // Mark post as read if forum_usermarksread is set off
1121 forum_tp_mark_posts_read($userto, $userto->markposts);
3d94772d 1122 }
caadf009 1123 }
caadf009 1124 }
226a1d9d 1125 /// We have finishied all digest emails, update $CFG->digestmailtimelast
1126 set_config('digestmailtimelast', $timenow);
caadf009 1127 }
1128
e8b7114d 1129 cron_setup_user();
de85c320 1130
a974c799 1131 if (!empty($usermailcount)) {
b140ae85 1132 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
aaf7a9dc 1133 }
1134
8ad64455 1135 if (!empty($CFG->forum_lastreadclean)) {
f37da850 1136 $timenow = time();
8ad64455 1137 if ($CFG->forum_lastreadclean + (24*3600) < $timenow) {
1138 set_config('forum_lastreadclean', $timenow);
8cb121cc 1139 mtrace('Removing old forum read tracking info...');
f37da850 1140 forum_tp_clean_read_records();
1141 }
1142 } else {
8ad64455 1143 set_config('forum_lastreadclean', time());
f37da850 1144 }
1145
caadf009 1146 return true;
1147}
1148
0a4ac01b 1149/**
1670305d 1150 * Builds and returns the body of the email notification in plain text.
1151 *
df1ba0f4 1152 * @global object
1153 * @global object
1154 * @uses CONTEXT_MODULE
1670305d 1155 * @param object $course
df1ba0f4 1156 * @param object $cm
1670305d 1157 * @param object $forum
1158 * @param object $discussion
1159 * @param object $post
1160 * @param object $userfrom
1161 * @param object $userto
1162 * @param boolean $bare
e90a0396 1163 * @param string $replyaddress The inbound address that a user can reply to the generated e-mail with. [Since 2.8].
1670305d 1164 * @return string The email body in plain text format.
0a4ac01b 1165 */
91223df6 1166function forum_make_mail_text($course, $cm, $forum, $discussion, $post, $userfrom, $userto, $bare = false, $replyaddress = null) {
15f81ee3 1167 global $CFG, $USER;
2b63df96 1168
bf0f06b1 1169 $modcontext = context_module::instance($cm->id);
18ff4d42 1170
df1c2c71 1171 if (!isset($userto->viewfullnames[$forum->id])) {
df1c2c71 1172 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
1173 } else {
1174 $viewfullnames = $userto->viewfullnames[$forum->id];
1175 }
1176
8b79a625 1177 if (!isset($userto->canpost[$discussion->id])) {
8b79a625 1178 $canreply = forum_user_can_post($forum, $discussion, $userto, $cm, $course, $modcontext);
df1c2c71 1179 } else {
8b79a625 1180 $canreply = $userto->canpost[$discussion->id];
0fa18d5a 1181 }
2b63df96 1182
aaf7a9dc 1183 $by = New stdClass;
df1c2c71 1184 $by->name = fullname($userfrom, $viewfullnames);
aaf7a9dc 1185 $by->date = userdate($post->modified, "", $userto->timezone);
1186
1187 $strbynameondate = get_string('bynameondate', 'forum', $by);
1188
64762ddc 1189 $strforums = get_string('forums', 'forum');
1190
4e3af3cf 1191 $canunsubscribe = !\mod_forum\subscriptions::is_forcesubscribed($forum);
aaf7a9dc 1192
1193 $posttext = '';
1194
0fa18d5a 1195 if (!$bare) {
bf0f06b1 1196 $shortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
4ee41261 1197 $posttext .= "$shortname -> $strforums -> ".format_string($forum->name,true);
aaf7a9dc 1198
1199 if ($discussion->name != $forum->name) {
c78ac798 1200 $posttext .= " -> ".format_string($discussion->name,true);
aaf7a9dc 1201 }
1202 }
1203
18ff4d42
PS
1204 // add absolute file links
1205 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
1206
3f213cd3
DNA
1207 $posttext .= "\n";
1208 $posttext .= $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id;
aaf7a9dc 1209 $posttext .= "\n---------------------------------------------------------------------\n";
17dc3f3c 1210 $posttext .= format_string($post->subject,true);
0fa18d5a 1211 if ($bare) {
0be4d8bf 1212 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#p$post->id)";
aaf7a9dc 1213 }
1214 $posttext .= "\n".$strbynameondate."\n";
1215 $posttext .= "---------------------------------------------------------------------\n";
e2d7687f 1216 $posttext .= format_text_email($post->message, $post->messageformat);
aaf7a9dc 1217 $posttext .= "\n\n";
0faf6791 1218 $posttext .= forum_print_attachments($post, $cm, "text");
1219
4e3af3cf
AN
1220 if (!$bare) {
1221 if ($canreply) {
1222 $posttext .= "---------------------------------------------------------------------\n";
1223 $posttext .= get_string("postmailinfo", "forum", $shortname)."\n";
1224 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
1225 }
1226
1227 if ($canunsubscribe) {
1228 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1229 // If subscribed to this forum, offer the unsubscribe link.
1230 $posttext .= "\n---------------------------------------------------------------------\n";
1231 $posttext .= get_string("unsubscribe", "forum");
1232 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
1233 }
1234 // Always offer the unsubscribe from discussion link.
1235 $posttext .= "\n---------------------------------------------------------------------\n";
1236 $posttext .= get_string("unsubscribediscussion", "forum");
06e23acc 1237 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id&d=$discussion->id\n";
4e3af3cf 1238 }
aaf7a9dc 1239 }
1240
b28118f6
AN
1241 $posttext .= "\n---------------------------------------------------------------------\n";
1242 $posttext .= get_string("digestmailpost", "forum");
1243 $posttext .= ": {$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}\n";
1244
91223df6 1245 if ($replyaddress) {
9ef82a9a 1246 $posttext .= "\n\n" . get_string('replytopostbyemail', 'mod_forum');
91223df6
AN
1247 }
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
91223df6 1303 if ($replyaddress) {
9ef82a9a 1304 $posthtml .= html_writer::tag('p', get_string('replytopostbyemail', 'mod_forum'));
91223df6
AN
1305 }
1306
b28118f6 1307 $footerlinks = array();
a0288610 1308 if ($canunsubscribe) {
4e3af3cf
AN
1309 if (\mod_forum\subscriptions::is_subscribed($userto->id, $forum, null, $cm)) {
1310 // If subscribed to this forum, offer the unsubscribe link.
1311 $unsublink = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id));
1312 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribe', 'mod_forum'));
1313 }
1314 // Always offer the unsubscribe from discussion link.
2b0a7419
AN
1315 $unsublink = new moodle_url('/mod/forum/subscribe.php', array(
1316 'id' => $forum->id,
1317 'd' => $discussion->id,
1318 ));
4e3af3cf
AN
1319 $footerlinks[] = html_writer::link($unsublink, get_string('unsubscribediscussion', 'mod_forum'));
1320
b28118f6 1321 $footerlinks[] = '<a href="' . $CFG->wwwroot . '/mod/forum/unsubscribeall.php">' . get_string('unsubscribeall', 'forum') . '</a>';
a0288610 1322 }
b28118f6
AN
1323 $footerlinks[] = "<a href='{$CFG->wwwroot}/mod/forum/index.php?id={$forum->course}'>" . get_string('digestmailpost', 'forum') . '</a>';
1324 $posthtml .= '<hr /><div class="mdl-align unsubscribelink">' . implode('&nbsp;', $footerlinks) . '</div>';
a0288610 1325
f2379d2d 1326 $posthtml .= '</body>';
1327
a0288610 1328 return $posthtml;
aaf7a9dc 1329}
1670305d 1330
1331
0a4ac01b 1332/**
13bbe067 1333 *
1670305d 1334 * @param object $course
1335 * @param object $user
1336 * @param object $mod TODO this is not used in this function, refactor
1337 * @param object $forum
1338 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
0a4ac01b 1339 */
caadf009 1340function forum_user_outline($course, $user, $mod, $forum) {
1a96363a
NC
1341 global $CFG;
1342 require_once("$CFG->libdir/gradelib.php");
1343 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1344 if (empty($grades->items[0]->grades)) {
1345 $grade = false;
1346 } else {
1347 $grade = reset($grades->items[0]->grades);
1348 }
1349
1350 $count = forum_count_user_posts($forum->id, $user->id);
1351
1352 if ($count && $count->postcount > 0) {
39790bd8 1353 $result = new stdClass();
1a96363a
NC
1354 $result->info = get_string("numposts", "forum", $count->postcount);
1355 $result->time = $count->lastpost;
1356 if ($grade) {
1357 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
90f4745c 1358 }
1a96363a
NC
1359 return $result;
1360 } else if ($grade) {
39790bd8 1361 $result = new stdClass();
1a96363a 1362 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
4433f871
AD
1363
1364 //datesubmitted == time created. dategraded == time modified or time overridden
1365 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
94a74f54 1366 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
4433f871
AD
1367 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1368 $result->time = $grade->dategraded;
1369 } else {
1370 $result->time = $grade->datesubmitted;
1371 }
1372
1a96363a 1373 return $result;
caadf009 1374 }
1375 return NULL;
1376}
1377
1378
0a4ac01b 1379/**
df1ba0f4 1380 * @global object
1381 * @global object
1382 * @param object $coure
1383 * @param object $user
1384 * @param object $mod
1385 * @param object $forum
0a4ac01b 1386 */
caadf009 1387function forum_user_complete($course, $user, $mod, $forum) {
1a96363a
NC
1388 global $CFG,$USER, $OUTPUT;
1389 require_once("$CFG->libdir/gradelib.php");
1390
1391 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
1392 if (!empty($grades->items[0]->grades)) {
1393 $grade = reset($grades->items[0]->grades);
1394 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1395 if ($grade->str_feedback) {
1396 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1397 }
1398 }
caadf009 1399
1f48942e 1400 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
e3ff14ca 1401
65bcf17b 1402 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
12e57b92 1403 print_error('invalidcoursemodule');
65bcf17b 1404 }
90f4745c 1405 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
65bcf17b 1406
1407 foreach ($posts as $post) {
5e7f2b0b 1408 if (!isset($discussions[$post->discussion])) {
90f4745c 1409 continue;
1410 }
7a8d8f22 1411 $discussion = $discussions[$post->discussion];
5e7f2b0b 1412
63e87951 1413 forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
5e7f2b0b 1414 }
caadf009 1415 } else {
41905731 1416 echo "<p>".get_string("noposts", "forum")."</p>";
caadf009 1417 }
caadf009 1418}
1419
8538c562
DM
1420/**
1421 * Filters the forum discussions according to groups membership and config.
1422 *
1423 * @since Moodle 2.8, 2.7.1, 2.6.4
1424 * @param array $discussions Discussions with new posts array
1425 * @return array Forums with the number of new posts
1426 */
1427function forum_filter_user_groups_discussions($discussions) {
c38965fb 1428
8538c562
DM
1429 // Group the remaining discussions posts by their forumid.
1430 $filteredforums = array();
c38965fb 1431
8538c562
DM
1432 // Discard not visible groups.
1433 foreach ($discussions as $discussion) {
c38965fb 1434
8538c562
DM
1435 // Course data is already cached.
1436 $instances = get_fast_modinfo($discussion->course)->get_instances();
1437 $forum = $instances['forum'][$discussion->forum];
5e7f2b0b 1438
8538c562
DM
1439 // Continue if the user should not see this discussion.
1440 if (!forum_is_user_group_discussion($forum, $discussion->groupid)) {
1441 continue;
1442 }
1443
1444 // Grouping results by forum.
1445 if (empty($filteredforums[$forum->instance])) {
1446 $filteredforums[$forum->instance] = new stdClass();
1447 $filteredforums[$forum->instance]->id = $forum->id;
1448 $filteredforums[$forum->instance]->count = 0;
1449 }
1450 $filteredforums[$forum->instance]->count += $discussion->count;
1451
1452 }
1453
1454 return $filteredforums;
1455}
1456
1457/**
1458 * Returns whether the discussion group is visible by the current user or not.
1459 *
1460 * @since Moodle 2.8, 2.7.1, 2.6.4
1461 * @param cm_info $cm The discussion course module
1462 * @param int $discussiongroupid The discussion groupid
1463 * @return bool
1464 */
1465function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
1466
1467 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
1468 return true;
1469 }
1470
1471 if (isguestuser()) {
1472 return false;
1473 }
1474
1475 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
1476 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
1477 return true;
1478 }
1479
1480 return false;
1481}
5e7f2b0b 1482
0a4ac01b 1483/**
df1ba0f4 1484 * @global object
1485 * @global object
1486 * @global object
1487 * @param array $courses
1488 * @param array $htmlarray
0a4ac01b 1489 */
185cfb09 1490function forum_print_overview($courses,&$htmlarray) {
261c6ef0 1491 global $USER, $CFG, $DB, $SESSION;
493f0820 1492
185cfb09 1493 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1494 return array();
1495 }
f8716988 1496
185cfb09 1497 if (!$forums = get_all_instances_in_courses('forum',$courses)) {
f8716988 1498 return;
1499 }
185cfb09 1500
ba4ee840
DM
1501 // Courses to search for new posts
1502 $coursessqls = array();
4e445355 1503 $params = array();
185cfb09 1504 foreach ($courses as $course) {
ba4ee840
DM
1505
1506 // If the user has never entered into the course all posts are pending
1507 if ($course->lastaccess == 0) {
8538c562 1508 $coursessqls[] = '(d.course = ?)';
ba4ee840
DM
1509 $params[] = $course->id;
1510
1511 // Only posts created after the course last access
1512 } else {
8538c562 1513 $coursessqls[] = '(d.course = ? AND p.created > ?)';
ba4ee840
DM
1514 $params[] = $course->id;
1515 $params[] = $course->lastaccess;
1516 }
185cfb09 1517 }
4e445355 1518 $params[] = $USER->id;
ba4ee840
DM
1519 $coursessql = implode(' OR ', $coursessqls);
1520
8538c562
DM
1521 $sql = "SELECT d.id, d.forum, d.course, d.groupid, COUNT(*) as count "
1522 .'FROM {forum_discussions} d '
ba4ee840
DM
1523 .'JOIN {forum_posts} p ON p.discussion = d.id '
1524 ."WHERE ($coursessql) "
1525 .'AND p.userid != ? '
81ba2632
JH
1526 .'GROUP BY d.id, d.forum, d.course, d.groupid '
1527 .'ORDER BY d.course, d.forum';
2b63df96 1528
8538c562
DM
1529 // Avoid warnings.
1530 if (!$discussions = $DB->get_records_sql($sql, $params)) {
1531 $discussions = array();
185cfb09 1532 }
2b63df96 1533
8538c562
DM
1534 $forumsnewposts = forum_filter_user_groups_discussions($discussions);
1535
185cfb09 1536 // also get all forum tracking stuff ONCE.
1537 $trackingforums = array();
1538 foreach ($forums as $forum) {
1539 if (forum_tp_can_track_forums($forum)) {
1540 $trackingforums[$forum->id] = $forum;
1541 }
1542 }
2b63df96 1543
185cfb09 1544 if (count($trackingforums) > 0) {
1545 $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0;
1546 $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '.
4e445355 1547 ' FROM {forum_posts} p '.
1548 ' JOIN {forum_discussions} d ON p.discussion = d.id '.
1549 ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE (';
1550 $params = array($USER->id);
1551
d3553951 1552 foreach ($trackingforums as $track) {
4e445355 1553 $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR ';
1554 $params[] = $track->id;
261c6ef0 1555 if (isset($SESSION->currentgroup[$track->course])) {
1556 $groupid = $SESSION->currentgroup[$track->course];
1557 } else {
0209f964
PS
1558 // get first groupid
1559 $groupids = groups_get_all_groups($track->course, $USER->id);
1560 if ($groupids) {
1561 reset($groupids);
1562 $groupid = key($groupids);
261c6ef0 1563 $SESSION->currentgroup[$track->course] = $groupid;
1564 } else {
1565 $groupid = 0;
1566 }
0209f964 1567 unset($groupids);
261c6ef0 1568 }
1569 $params[] = $groupid;
185cfb09 1570 }
1571 $sql = substr($sql,0,-3); // take off the last OR
4e445355 1572 $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course';
1573 $params[] = $cutoffdate;
185cfb09 1574
4e445355 1575 if (!$unread = $DB->get_records_sql($sql, $params)) {
185cfb09 1576 $unread = array();
1577 }
1578 } else {
1579 $unread = array();
95d71ad3 1580 }
185cfb09 1581
8538c562 1582 if (empty($unread) and empty($forumsnewposts)) {
9cba7a8c 1583 return;
1584 }
1585
1586 $strforum = get_string('modulename','forum');
9cba7a8c 1587
f8716988 1588 foreach ($forums as $forum) {
185cfb09 1589 $str = '';
f8716988 1590 $count = 0;
185cfb09 1591 $thisunread = 0;
f8716988 1592 $showunread = false;
1593 // either we have something from logs, or trackposts, or nothing.
8538c562
DM
1594 if (array_key_exists($forum->id, $forumsnewposts) && !empty($forumsnewposts[$forum->id])) {
1595 $count = $forumsnewposts[$forum->id]->count;
90558ec4 1596 }
185cfb09 1597 if (array_key_exists($forum->id,$unread)) {
1598 $thisunread = $unread[$forum->id]->count;
f8716988 1599 $showunread = true;
0d6b9d4f 1600 }
185cfb09 1601 if ($count > 0 || $thisunread > 0) {
e23800b7 1602 $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.
1603 $forum->name.'</a></div>';
6d641063 1604 $str .= '<div class="info"><span class="postsincelogin">';
54294601 1605 $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>";
f8716988 1606 if (!empty($showunread)) {
54294601 1607 $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>';
f8716988 1608 }
e23800b7 1609 $str .= '</div></div>';
f8716988 1610 }
2b63df96 1611 if (!empty($str)) {
185cfb09 1612 if (!array_key_exists($forum->course,$htmlarray)) {
1613 $htmlarray[$forum->course] = array();
1614 }
1615 if (!array_key_exists('forum',$htmlarray[$forum->course])) {
1616 $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings
1617 }
1618 $htmlarray[$forum->course]['forum'] .= $str;
1619 }
2b63df96 1620 }
0d6b9d4f 1621}
1622
0a4ac01b 1623/**
1624 * Given a course and a date, prints a summary of all the new
1625 * messages posted in the course since that date
df1ba0f4 1626 *
1627 * @global object
1628 * @global object
1629 * @global object
1630 * @uses CONTEXT_MODULE
1631 * @uses VISIBLEGROUPS
90f4745c 1632 * @param object $course
1633 * @param bool $viewfullnames capability
1634 * @param int $timestart
1635 * @return bool success
0a4ac01b 1636 */
dd97c328 1637function forum_print_recent_activity($course, $viewfullnames, $timestart) {
cb860491 1638 global $CFG, $USER, $DB, $OUTPUT;
caadf009 1639
dd97c328 1640 // do not use log table if possible, it may be huge and is expensive to join with other tables
caadf009 1641
dda60f88 1642 $allnamefields = user_picture::fields('u', null, 'duserid');
4e445355 1643 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
dda60f88 1644 d.timestart, d.timeend, $allnamefields
4e445355 1645 FROM {forum_posts} p
1646 JOIN {forum_discussions} d ON d.id = p.discussion
1647 JOIN {forum} f ON f.id = d.forum
1648 JOIN {user} u ON u.id = p.userid
1649 WHERE p.created > ? AND f.course = ?
1650 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
dd97c328 1651 return false;
1b5910c4 1652 }
1653
f20edd52 1654 $modinfo = get_fast_modinfo($course);
dcde9f02 1655
dd97c328 1656 $groupmodes = array();
1657 $cms = array();
d05956ac 1658
dd97c328 1659 $strftimerecent = get_string('strftimerecent');
d05956ac 1660
dd97c328 1661 $printposts = array();
1662 foreach ($posts as $post) {
1663 if (!isset($modinfo->instances['forum'][$post->forum])) {
1664 // not visible
1665 continue;
1666 }
1667 $cm = $modinfo->instances['forum'][$post->forum];
1668 if (!$cm->uservisible) {
1669 continue;
1670 }
bf0f06b1 1671 $context = context_module::instance($cm->id);
6b7de0bb 1672
1673 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1674 continue;
1675 }
583b57b4 1676
dd97c328 1677 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid
1678 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) {
6b7de0bb 1679 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
dd97c328 1680 continue;
ac1d9a22 1681 }
dd97c328 1682 }
583b57b4 1683
8538c562
DM
1684 // Check that the user can see the discussion.
1685 if (forum_is_user_group_discussion($cm, $post->groupid)) {
1686 $printposts[] = $post;
dd97c328 1687 }
8f7dc7f1 1688
dd97c328 1689 }
1690 unset($posts);
8f7dc7f1 1691
dd97c328 1692 if (!$printposts) {
1693 return false;
1694 }
1695
cb860491 1696 echo $OUTPUT->heading(get_string('newforumposts', 'forum').':', 3);
dd97c328 1697 echo "\n<ul class='unlist'>\n";
1698
1699 foreach ($printposts as $post) {
1700 $subjectclass = empty($post->parent) ? ' bold' : '';
1701
1702 echo '<li><div class="head">'.
1703 '<div class="date">'.userdate($post->modified, $strftimerecent).'</div>'.
1704 '<div class="name">'.fullname($post, $viewfullnames).'</div>'.
1705 '</div>';
1706 echo '<div class="info'.$subjectclass.'">';
1707 if (empty($post->parent)) {
1708 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1709 } else {
1710 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'&amp;parent='.$post->parent.'#p'.$post->id.'">';
caadf009 1711 }
dd97c328 1712 $post->subject = break_up_long_words(format_string($post->subject, true));
1713 echo $post->subject;
1714 echo "</a>\"</div></li>\n";
caadf009 1715 }
dd97c328 1716
1306c5ea 1717 echo "</ul>\n";
dd97c328 1718
1719 return true;
caadf009 1720}
1721
353228d8 1722/**
1723 * Return grade for given user or all users.
1724 *
df1ba0f4 1725 * @global object
1726 * @global object
1727 * @param object $forum
353228d8 1728 * @param int $userid optional user id, 0 means all users
1729 * @return array array of grades, false if none
1730 */
2b04c41c 1731function forum_get_user_grades($forum, $userid = 0) {
63e87951 1732 global $CFG;
df997f84 1733
63e87951 1734 require_once($CFG->dirroot.'/rating/lib.php');
df997f84 1735
2b04c41c
SH
1736 $ratingoptions = new stdClass;
1737 $ratingoptions->component = 'mod_forum';
1738 $ratingoptions->ratingarea = 'post';
353228d8 1739
63e87951
AD
1740 //need these to work backwards to get a context id. Is there a better way to get contextid from a module instance?
1741 $ratingoptions->modulename = 'forum';
1742 $ratingoptions->moduleid = $forum->id;
63e87951
AD
1743 $ratingoptions->userid = $userid;
1744 $ratingoptions->aggregationmethod = $forum->assessed;
1745 $ratingoptions->scaleid = $forum->scale;
1746 $ratingoptions->itemtable = 'forum_posts';
1747 $ratingoptions->itemtableusercolumn = 'userid';
353228d8 1748
2b04c41c 1749 $rm = new rating_manager();
63e87951 1750 return $rm->get_user_grades($ratingoptions);
353228d8 1751}
caadf009 1752
0a4ac01b 1753/**
775f811a 1754 * Update activity grades
353228d8 1755 *
a153c9f2 1756 * @category grade
775f811a 1757 * @param object $forum
1758 * @param int $userid specific user only, 0 means all
6b7de0bb 1759 * @param boolean $nullifnone return null if grade does not exist
90f4745c 1760 * @return void
0a4ac01b 1761 */
775f811a 1762function forum_update_grades($forum, $userid=0, $nullifnone=true) {
4e445355 1763 global $CFG, $DB;
775f811a 1764 require_once($CFG->libdir.'/gradelib.php');
caadf009 1765
775f811a 1766 if (!$forum->assessed) {
1767 forum_grade_item_update($forum);
02ebf404 1768
775f811a 1769 } else if ($grades = forum_get_user_grades($forum, $userid)) {
1770 forum_grade_item_update($forum, $grades);
eafb9d9e 1771
775f811a 1772 } else if ($userid and $nullifnone) {
39790bd8 1773 $grade = new stdClass();
775f811a 1774 $grade->userid = $userid;
1775 $grade->rawgrade = NULL;
1776 forum_grade_item_update($forum, $grade);
02ebf404 1777
353228d8 1778 } else {
775f811a 1779 forum_grade_item_update($forum);
1780 }
1781}
1782
353228d8 1783/**
612607bd 1784 * Create/update grade item for given forum
353228d8 1785 *
a153c9f2 1786 * @category grade
df1ba0f4 1787 * @uses GRADE_TYPE_NONE
1788 * @uses GRADE_TYPE_VALUE
1789 * @uses GRADE_TYPE_SCALE
a153c9f2
AD
1790 * @param stdClass $forum Forum object with extra cmidnumber
1791 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 1792 * @return int 0 if ok
353228d8 1793 */
0b5a80a1 1794function forum_grade_item_update($forum, $grades=NULL) {
612607bd 1795 global $CFG;
1796 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1797 require_once($CFG->libdir.'/gradelib.php');
353228d8 1798 }
1799
612607bd 1800 $params = array('itemname'=>$forum->name, 'idnumber'=>$forum->cmidnumber);
353228d8 1801
5980d52f 1802 if (!$forum->assessed or $forum->scale == 0) {
612607bd 1803 $params['gradetype'] = GRADE_TYPE_NONE;
353228d8 1804
1805 } else if ($forum->scale > 0) {
1806 $params['gradetype'] = GRADE_TYPE_VALUE;
1807 $params['grademax'] = $forum->scale;
1808 $params['grademin'] = 0;
1809
1810 } else if ($forum->scale < 0) {
1811 $params['gradetype'] = GRADE_TYPE_SCALE;
1812 $params['scaleid'] = -$forum->scale;
1813 }
1814
0b5a80a1 1815 if ($grades === 'reset') {
1816 $params['reset'] = true;
1817 $grades = NULL;
1818 }
1819
1820 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $grades, $params);
353228d8 1821}
1822
1823/**
1824 * Delete grade item for given forum
1825 *
a153c9f2
AD
1826 * @category grade
1827 * @param stdClass $forum Forum object
1828 * @return grade_item
353228d8 1829 */
1830function forum_grade_item_delete($forum) {
612607bd 1831 global $CFG;
1832 require_once($CFG->libdir.'/gradelib.php');
1833
b67ec72f 1834 return grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, NULL, array('deleted'=>1));
caadf009 1835}
1836
353228d8 1837
0a4ac01b 1838/**
90f4745c 1839 * This function returns if a scale is being used by one forum
df1ba0f4 1840 *
1841 * @global object
90f4745c 1842 * @param int $forumid
1843 * @param int $scaleid negative number
1844 * @return bool
0a4ac01b 1845 */
0f1a97c2 1846function forum_scale_used ($forumid,$scaleid) {
4e445355 1847 global $DB;
0f1a97c2 1848 $return = false;
65b0e537 1849
4e445355 1850 $rec = $DB->get_record("forum",array("id" => "$forumid","scale" => "-$scaleid"));
65b0e537 1851
fa22fd5f 1852 if (!empty($rec) && !empty($scaleid)) {
0f1a97c2 1853 $return = true;
1854 }
65b0e537 1855
0f1a97c2 1856 return $return;
1857}
1858
85c9ebb9 1859/**
1860 * Checks if scale is being used by any instance of forum
1861 *
1862 * This is used to find out if scale used anywhere
df1ba0f4 1863 *
1864 * @global object
85c9ebb9 1865 * @param $scaleid int
1866 * @return boolean True if the scale is used by any forum
1867 */
1868function forum_scale_used_anywhere($scaleid) {
4e445355 1869 global $DB;
1870 if ($scaleid and $DB->record_exists('forum', array('scale' => -$scaleid))) {
85c9ebb9 1871 return true;
1872 } else {
1873 return false;
1874 }
1875}
1876
0a4ac01b 1877// SQL FUNCTIONS ///////////////////////////////////////////////////////////
9fa49e22 1878
0a4ac01b 1879/**
1880 * Gets a post with all info ready for forum_print_post
1881 * Most of these joins are just to get the forum id
df1ba0f4 1882 *
1883 * @global object
1884 * @global object
90f4745c 1885 * @param int $postid
1886 * @return mixed array of posts or false
0a4ac01b 1887 */
1f48942e 1888function forum_get_post_full($postid) {
4e445355 1889 global $CFG, $DB;
1f48942e 1890
a327f25e
AG
1891 $allnames = get_all_user_name_fields(true, 'u');
1892 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 1893 FROM {forum_posts} p
1894 JOIN {forum_discussions} d ON p.discussion = d.id
1895 LEFT JOIN {user} u ON p.userid = u.id
1896 WHERE p.id = ?", array($postid));
1f48942e 1897}
1898
65bcf17b 1899/**
1900 * Gets all posts in discussion including top parent.
df1ba0f4 1901 *
1902 * @global object
1903 * @global object
1904 * @global object
90f4745c 1905 * @param int $discussionid
1906 * @param string $sort
1907 * @param bool $tracking does user track the forum?
1908 * @return array of posts
65bcf17b 1909 */
90f4745c 1910function forum_get_all_discussion_posts($discussionid, $sort, $tracking=false) {
4e445355 1911 global $CFG, $DB, $USER;
65bcf17b 1912
3c2bf848 1913 $tr_sel = "";
1914 $tr_join = "";
4e445355 1915 $params = array();
3c2bf848 1916
90f4745c 1917 if ($tracking) {
1918 $now = time();
1919 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600);
1920 $tr_sel = ", fr.id AS postread";
4e445355 1921 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
1922 $params[] = $USER->id;
90f4745c 1923 }
1924
a327f25e 1925 $allnames = get_all_user_name_fields(true, 'u');
4e445355 1926 $params[] = $discussionid;
a327f25e 1927 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
4e445355 1928 FROM {forum_posts} p
1929 LEFT JOIN {user} u ON p.userid = u.id
90f4745c 1930 $tr_join
4e445355 1931 WHERE p.discussion = ?
1932 ORDER BY $sort", $params)) {
65bcf17b 1933 return array();
1934 }
1935
1936 foreach ($posts as $pid=>$p) {
90f4745c 1937 if ($tracking) {
1938 if (forum_tp_is_post_old($p)) {
6b7de0bb 1939 $posts[$pid]->postread = true;
90f4745c 1940 }
1941 }
65bcf17b 1942 if (!$p->parent) {
1943 continue;
1944 }
1945 if (!isset($posts[$p->parent])) {
1946 continue; // parent does not exist??
1947 }
1948 if (!isset($posts[$p->parent]->children)) {
1949 $posts[$p->parent]->children = array();
1950 }
1951 $posts[$p->parent]->children[$pid] =& $posts[$pid];
1952 }
1953
1954 return $posts;
1955}
1956
42fb3c85 1957/**
1958 * An array of forum objects that the user is allowed to read/search through.
df1ba0f4 1959 *
1960 * @global object
1961 * @global object
1962 * @global object
1963 * @param int $userid
1964 * @param int $courseid if 0, we look for forums throughout the whole site.
42fb3c85 1965 * @return array of forum objects, or false if no matches
1966 * Forum objects have the following attributes:
1967 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1968 * viewhiddentimedposts
1969 */
1970function forum_get_readable_forums($userid, $courseid=0) {
2b63df96 1971
4e445355 1972 global $CFG, $DB, $USER;
6b7de0bb 1973 require_once($CFG->dirroot.'/course/lib.php');
2b63df96 1974
4e445355 1975 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
12e57b92 1976 print_error('notinstalled', 'forum');
42fb3c85 1977 }
2b63df96 1978
42fb3c85 1979 if ($courseid) {
4e445355 1980 $courses = $DB->get_records('course', array('id' => $courseid));
42fb3c85 1981 } else {
65bcf17b 1982 // If no course is specified, then the user can see SITE + his courses.
4e445355 1983 $courses1 = $DB->get_records('course', array('id' => SITEID));
b1d5d015 1984 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
6155150c 1985 $courses = array_merge($courses1, $courses2);
42fb3c85 1986 }
1987 if (!$courses) {
6b7de0bb 1988 return array();
42fb3c85 1989 }
1990
1991 $readableforums = array();
2b63df96 1992
6527b5c2 1993 foreach ($courses as $course) {
1994
f20edd52 1995 $modinfo = get_fast_modinfo($course);
2b63df96 1996
6b7de0bb 1997 if (empty($modinfo->instances['forum'])) {
1998 // hmm, no forums?
1999 continue;
2000 }
2b63df96 2001
4e445355 2002 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2b63df96 2003
6b7de0bb 2004 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
2005 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
2006 continue;
2007 }
bf0f06b1 2008 $context = context_module::instance($cm->id);
6b7de0bb 2009 $forum = $courseforums[$forumid];
2e945910
AB
2010 $forum->context = $context;
2011 $forum->cm = $cm;
d50704bf 2012
6b7de0bb 2013 if (!has_capability('mod/forum:viewdiscussion', $context)) {
2014 continue;
2015 }
6527b5c2 2016
6b7de0bb 2017 /// group access
2018 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2c1bbbc5
MG
2019
2020 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
2021 $forum->onlygroups[] = -1;
6b7de0bb 2022 }
2b63df96 2023
6b7de0bb 2024 /// hidden timed discussions
2025 $forum->viewhiddentimedposts = true;
2026 if (!empty($CFG->forum_enabletimedposts)) {
2027 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
2028 $forum->viewhiddentimedposts = false;
2029 }
2030 }
d50704bf 2031
6b7de0bb 2032 /// qanda access
2033 if ($forum->type == 'qanda'
2034 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2b63df96 2035
6b7de0bb 2036 // We need to check whether the user has posted in the qanda forum.
2037 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
2038 // the user is allowed to see in this forum.
2039 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
2040 foreach ($discussionspostedin as $d) {
2041 $forum->onlydiscussions[] = $d->id;
d50704bf 2042 }
42fb3c85 2043 }
2044 }
6b7de0bb 2045
2046 $readableforums[$forum->id] = $forum;
42fb3c85 2047 }
6b7de0bb 2048
2049 unset($modinfo);
2050
42fb3c85 2051 } // End foreach $courses
2b63df96 2052
42fb3c85 2053 return $readableforums;
2054}
2055
bbbf2d40 2056/**
2057 * Returns a list of posts found using an array of search terms.
df1ba0f4 2058 *
2059 * @global object
2060 * @global object
2061 * @global object
2062 * @param array $searchterms array of search terms, e.g. word +word -word
2063 * @param int $courseid if 0, we search through the whole site
2064 * @param int $limitfrom
2065 * @param int $limitnum
2066 * @param int &$totalcount
2067 * @param string $extrasql
2068 * @return array|bool Array of posts found or false
42fb3c85 2069 */
2b63df96 2070function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50,
42fb3c85 2071 &$totalcount, $extrasql='') {
4e445355 2072 global $CFG, $DB, $USER;
42fb3c85 2073 require_once($CFG->libdir.'/searchlib.php');
2074
2075 $forums = forum_get_readable_forums($USER->id, $courseid);
2b63df96 2076
67875aa1 2077 if (count($forums) == 0) {
6b7de0bb 2078 $totalcount = 0;
67875aa1 2079 return false;
2080 }
42fb3c85 2081
6b7de0bb 2082 $now = round(time(), -2); // db friendly
2083
2084 $fullaccess = array();
2085 $where = array();
4e445355 2086 $params = array();
6b7de0bb 2087
2088 foreach ($forums as $forumid => $forum) {
2089 $select = array();
2090
2091 if (!$forum->viewhiddentimedposts) {
b1d5d015
PS
2092 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
2093 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
42fb3c85 2094 }
6b7de0bb 2095
2e945910
AB
2096 $cm = $forum->cm;
2097 $context = $forum->context;
ad9c22aa 2098
2099 if ($forum->type == 'qanda'
2100 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
6b7de0bb 2101 if (!empty($forum->onlydiscussions)) {
cf717dc2 2102 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
4e445355 2103 $params = array_merge($params, $discussionid_params);
2104 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
d50704bf 2105 } else {
6b7de0bb 2106 $select[] = "p.parent = 0";
d50704bf 2107 }
2108 }
6b7de0bb 2109
2110 if (!empty($forum->onlygroups)) {
cf717dc2 2111 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
4e445355 2112 $params = array_merge($params, $groupid_params);
2113 $select[] = "d.groupid $groupid_sql";
42fb3c85 2114 }
6b7de0bb 2115
2116 if ($select) {
2117 $selects = implode(" AND ", $select);
b1d5d015
PS
2118 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
2119 $params['forum'.$forumid] = $forumid;
6b7de0bb 2120 } else {
2121 $fullaccess[] = $forumid;
2122 }
2123 }
2124
2125 if ($fullaccess) {
cf717dc2 2126 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
4e445355 2127 $params = array_merge($params, $fullid_params);
2128 $where[] = "(d.forum $fullid_sql)";
42fb3c85 2129 }
42fb3c85 2130
6b7de0bb 2131 $selectdiscussion = "(".implode(" OR ", $where).")";
42fb3c85 2132
42fb3c85 2133 $messagesearch = '';
2134 $searchstring = '';
2b63df96 2135
42fb3c85 2136 // Need to concat these back together for parser to work.
2137 foreach($searchterms as $searchterm){
2138 if ($searchstring != '') {
2139 $searchstring .= ' ';
2140 }
2141 $searchstring .= $searchterm;
2142 }
2143
2144 // We need to allow quoted strings for the search. The quotes *should* be stripped
2145 // by the parser, but this should be examined carefully for security implications.
2146 $searchstring = str_replace("\\\"","\"",$searchstring);
2147 $parser = new search_parser();
2148 $lexer = new search_lexer($parser);
2149
2150 if ($lexer->parse($searchstring)) {
2151 $parsearray = $parser->get_parsed_array();
0a4ac01b 2152 // Experimental feature under 1.8! MDL-8830
2153 // Use alternative text searches if defined
2154 // This feature only works under mysql until properly implemented for other DBs
2155 // Requires manual creation of text index for forum_posts before enabling it:
2156 // CREATE FULLTEXT INDEX foru_post_tix ON [prefix]forum_posts (subject, message)
2157 // Experimental feature under 1.8! MDL-8830
532daab4 2158 if (!empty($CFG->forum_usetextsearches)) {
004efe66 2159 list($messagesearch, $msparams) = search_generate_text_SQL($parsearray, 'p.message', 'p.subject',
532daab4 2160 'p.userid', 'u.id', 'u.firstname',
2161 'u.lastname', 'p.modified', 'd.forum');
2162 } else {
004efe66 2163 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
532daab4 2164 'p.userid', 'u.id', 'u.firstname',
2165 'u.lastname', 'p.modified', 'd.forum');
2166 }
004efe66 2167 $params = array_merge($params, $msparams);
42fb3c85 2168 }
2169
4e445355 2170 $fromsql = "{forum_posts} p,
2171 {forum_discussions} d,
2172 {user} u";
42fb3c85 2173
2174 $selectsql = " $messagesearch
2175 AND p.discussion = d.id
2176 AND p.userid = u.id
2177 AND $selectdiscussion
2178 $extrasql";
2179
2180 $countsql = "SELECT COUNT(*)
2181 FROM $fromsql
2182 WHERE $selectsql";
2183
a327f25e 2184 $allnames = get_all_user_name_fields(true, 'u');
7f094149 2185 $searchsql = "SELECT p.*,
42fb3c85 2186 d.forum,
a327f25e 2187 $allnames,
42fb3c85 2188 u.email,
8ba59d07 2189 u.picture,
ce7382c9 2190 u.imagealt
42fb3c85 2191 FROM $fromsql
2192 WHERE $selectsql
2193 ORDER BY p.modified DESC";
2194
4e445355 2195 $totalcount = $DB->count_records_sql($countsql, $params);
d50704bf 2196
4e445355 2197 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
42fb3c85 2198}
2199
0a4ac01b 2200/**
2201 * Returns a list of all new posts that have not been mailed yet
df1ba0f4 2202 *
df1ba0f4 2203 * @param int $starttime posts created after this time
2204 * @param int $endtime posts created before this
2205 * @param int $now used for timed discussions only
2206 * @return array
0a4ac01b 2207 */
90f4745c 2208function forum_get_unmailed_posts($starttime, $endtime, $now=null) {
4e445355 2209 global $CFG, $DB;
90f4745c 2210
8076010d
MN
2211 $params = array();
2212 $params['mailed'] = FORUM_MAILED_PENDING;
2213 $params['ptimestart'] = $starttime;
2214 $params['ptimeend'] = $endtime;
2215 $params['mailnow'] = 1;
2216
90f4745c 2217 if (!empty($CFG->forum_enabletimedposts)) {
2218 if (empty($now)) {
2219 $now = time();
2220 }
8076010d
MN
2221 $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
2222 $params['dtimestart'] = $now;
2223 $params['dtimeend'] = $now;
90f4745c 2224 } else {
2225 $timedsql = "";
2226 }
2227
4e445355 2228 return $DB->get_records_sql("SELECT p.*, d.course, d.forum
8076010d
MN
2229 FROM {forum_posts} p
2230 JOIN {forum_discussions} d ON d.id = p.discussion
2231 WHERE p.mailed = :mailed
2232 AND p.created >= :ptimestart
2233 AND (p.created < :ptimeend OR p.mailnow = :mailnow)
2234 $timedsql
2235 ORDER BY p.modified ASC", $params);
1f48942e 2236}
2237
0a4ac01b 2238/**
2239 * Marks posts before a certain time as being mailed already
df1ba0f4 2240 *
2241 * @global object
2242 * @global object
2243 * @param int $endtime
2244 * @param int $now Defaults to time()
2245 * @return bool
0a4ac01b 2246 */
90f4745c 2247function forum_mark_old_posts_as_mailed($endtime, $now=null) {
4e445355 2248 global $CFG, $DB;
8076010d 2249
90f4745c 2250 if (empty($now)) {
2251 $now = time();
2252 }
2253
8076010d
MN
2254 $params = array();
2255 $params['mailedsuccess'] = FORUM_MAILED_SUCCESS;
2256 $params['now'] = $now;
2257 $params['endtime'] = $endtime;
2258 $params['mailnow'] = 1;
2259 $params['mailedpending'] = FORUM_MAILED_PENDING;
2260
90f4745c 2261 if (empty($CFG->forum_enabletimedposts)) {
4e445355 2262 return $DB->execute("UPDATE {forum_posts}
8076010d
MN
2263 SET mailed = :mailedsuccess
2264 WHERE (created < :endtime OR mailnow = :mailnow)
2265 AND mailed = :mailedpending", $params);
0f620d4b 2266 } else {
4e445355 2267 return $DB->execute("UPDATE {forum_posts}
8076010d 2268 SET mailed = :mailedsuccess
90f4745c 2269 WHERE discussion NOT IN (SELECT d.id
8076010d
MN
2270 FROM {forum_discussions} d
2271 WHERE d.timestart > :now)
2272 AND (created < :endtime OR mailnow = :mailnow)
2273 AND mailed = :mailedpending", $params);
0f620d4b 2274 }
3ecca1ee 2275}
2276
0a4ac01b 2277/**
2278 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2279 *
2280 * @global object
2281 * @global object
2282 * @uses CONTEXT_MODULE
2283 * @return array
0a4ac01b 2284 */
1f48942e 2285function forum_get_user_posts($forumid, $userid) {
4e445355 2286 global $CFG, $DB;
1f48942e 2287
90f4745c 2288 $timedsql = "";
4e445355 2289 $params = array($forumid, $userid);
2290
90f4745c 2291 if (!empty($CFG->forum_enabletimedposts)) {
2292 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2293 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2294 $now = time();
4e445355 2295 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2296 $params[] = $now;
2297 $params[] = $now;
6b7de0bb 2298 }
90f4745c 2299 }
2300
a327f25e
AG
2301 $allnames = get_all_user_name_fields(true, 'u');
2302 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 2303 FROM {forum} f
2304 JOIN {forum_discussions} d ON d.forum = f.id
2305 JOIN {forum_posts} p ON p.discussion = d.id
2306 JOIN {user} u ON u.id = p.userid
2307 WHERE f.id = ?
2308 AND p.userid = ?
90f4745c 2309 $timedsql
4e445355 2310 ORDER BY p.modified ASC", $params);
1f48942e 2311}
2312
90f4745c 2313/**
2314 * Get all the discussions user participated in
df1ba0f4 2315 *
2316 * @global object
2317 * @global object
2318 * @uses CONTEXT_MODULE
90f4745c 2319 * @param int $forumid
2320 * @param int $userid
df1ba0f4 2321 * @return array Array or false
90f4745c 2322 */
2323function forum_get_user_involved_discussions($forumid, $userid) {
4e445355 2324 global $CFG, $DB;
90f4745c 2325
2326 $timedsql = "";
4e445355 2327 $params = array($forumid, $userid);
90f4745c 2328 if (!empty($CFG->forum_enabletimedposts)) {
2329 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2330 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2331 $now = time();
4e445355 2332 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2333 $params[] = $now;
2334 $params[] = $now;
6b7de0bb 2335 }
90f4745c 2336 }
2337
4e445355 2338 return $DB->get_records_sql("SELECT DISTINCT d.*
2339 FROM {forum} f
2340 JOIN {forum_discussions} d ON d.forum = f.id
2341 JOIN {forum_posts} p ON p.discussion = d.id
2342 WHERE f.id = ?
2343 AND p.userid = ?
2344 $timedsql", $params);
90f4745c 2345}
2346
2347/**
2348 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 2349 *
2350 * @global object
2351 * @global object
90f4745c 2352 * @param int $forumid
2353 * @param int $userid
2354 * @return array of counts or false
2355 */
2356function forum_count_user_posts($forumid, $userid) {
4e445355 2357 global $CFG, $DB;
90f4745c 2358
2359 $timedsql = "";
4e445355 2360 $params = array($forumid, $userid);
90f4745c 2361 if (!empty($CFG->forum_enabletimedposts)) {
2362 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 2363 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 2364 $now = time();
4e445355 2365 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
2366 $params[] = $now;
2367 $params[] = $now;
6b7de0bb 2368 }
90f4745c 2369 }
2370
4e445355 2371 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
2372 FROM {forum} f
2373 JOIN {forum_discussions} d ON d.forum = f.id
2374 JOIN {forum_posts} p ON p.discussion = d.id
2375 JOIN {user} u ON u.id = p.userid
2376 WHERE f.id = ?
2377 AND p.userid = ?
2378 $timedsql", $params);
90f4745c 2379}
2380
0a4ac01b 2381/**
2382 * Given a log entry, return the forum post details for it.
df1ba0f4 2383 *
2384 * @global object
2385 * @global object
2386 * @param object $log
2387 * @return array|null
0a4ac01b 2388 */
1f48942e 2389function forum_get_post_from_log($log) {
4e445355 2390 global $CFG, $DB;
1f48942e 2391
a327f25e 2392 $allnames = get_all_user_name_fields(true, 'u');
1f48942e 2393 if ($log->action == "add post") {
2394
a327f25e 2395 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2396 FROM {forum_discussions} d,
2397 {forum_posts} p,
2398 {forum} f,
2399 {user} u
2400 WHERE p.id = ?
65b0e537 2401 AND d.id = p.discussion
2402 AND p.userid = u.id
8f7dc7f1 2403 AND u.deleted <> '1'
4e445355 2404 AND f.id = d.forum", array($log->info));
1f48942e 2405
2406
2407 } else if ($log->action == "add discussion") {
2408
a327f25e 2409 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 2410 FROM {forum_discussions} d,
2411 {forum_posts} p,
2412 {forum} f,
2413 {user} u
2414 WHERE d.id = ?
65b0e537 2415 AND d.firstpost = p.id
2416 AND p.userid = u.id
8f7dc7f1 2417 AND u.deleted <> '1'
4e445355 2418 AND f.id = d.forum", array($log->info));
1f48942e 2419 }
2420 return NULL;
2421}
2422
0a4ac01b 2423/**
2424 * Given a discussion id, return the first post from the discussion
df1ba0f4 2425 *
2426 * @global object
2427 * @global object
2428 * @param int $dicsussionid
2429 * @return array
0a4ac01b 2430 */
d05956ac 2431function forum_get_firstpost_from_discussion($discussionid) {
4e445355 2432 global $CFG, $DB;
d05956ac 2433
4e445355 2434 return $DB->get_record_sql("SELECT p.*
2435 FROM {forum_discussions} d,
2436 {forum_posts} p
2437 WHERE d.id = ?
2438 AND d.firstpost = p.id ", array($discussionid));
d05956ac 2439}
2440
0a4ac01b 2441/**
90f4745c 2442 * Returns an array of counts of replies to each discussion
df1ba0f4 2443 *
2444 * @global object
2445 * @global object
2446 * @param int $forumid
2447 * @param string $forumsort
2448 * @param int $limit
2449 * @param int $page
2450 * @param int $perpage
2451 * @return array
0a4ac01b 2452 */
90f4745c 2453function forum_count_discussion_replies($forumid, $forumsort="", $limit=-1, $page=-1, $perpage=0) {
4e445355 2454 global $CFG, $DB;
1f48942e 2455
90f4745c 2456 if ($limit > 0) {
2457 $limitfrom = 0;
2458 $limitnum = $limit;
2459 } else if ($page != -1) {
2460 $limitfrom = $page*$perpage;
2461 $limitnum = $perpage;
2462 } else {
2463 $limitfrom = 0;
2464 $limitnum = 0;
2465 }
2466
2467 if ($forumsort == "") {
2468 $orderby = "";
2469 $groupby = "";
2470
2471 } else {
2472 $orderby = "ORDER BY $forumsort";
2473 $groupby = ", ".strtolower($forumsort);
2474 $groupby = str_replace('desc', '', $groupby);
2475 $groupby = str_replace('asc', '', $groupby);
2476 }
2477
bfeb10b7 2478 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
2479 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
4e445355 2480 FROM {forum_posts} p
2481 JOIN {forum_discussions} d ON p.discussion = d.id
2482 WHERE p.parent > 0 AND d.forum = ?
bfeb10b7 2483 GROUP BY p.discussion";
4e445355 2484 return $DB->get_records_sql($sql, array($forumid));
bfeb10b7 2485
90f4745c 2486 } else {
bfeb10b7 2487 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
4e445355 2488 FROM {forum_posts} p
2489 JOIN {forum_discussions} d ON p.discussion = d.id
2490 WHERE d.forum = ?
bfeb10b7 2491 GROUP BY p.discussion $groupby
2492 $orderby";
4e445355 2493 return $DB->get_records_sql("SELECT * FROM ($sql) sq", array($forumid), $limitfrom, $limitnum);
90f4745c 2494 }
2495}
2496
df1ba0f4 2497/**
2498 * @global object
2499 * @global object
2500 * @global object
2501 * @staticvar array $cache
2502 * @param object $forum
2503 * @param object $cm
2504 * @param object $course
2505 * @return mixed
2506 */
90f4745c 2507function forum_count_discussions($forum, $cm, $course) {
4e445355 2508 global $CFG, $DB, $USER;
90f4745c 2509
2510 static $cache = array();
2511
2512 $now = round(time(), -2); // db cache friendliness
2513
4e445355 2514 $params = array($course->id);
2515
90f4745c 2516 if (!isset($cache[$course->id])) {
2517 if (!empty($CFG->forum_enabletimedposts)) {
4e445355 2518 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
2519 $params[] = $now;
2520 $params[] = $now;
90f4745c 2521 } else {
2522 $timedsql = "";
2523 }
2524
2525 $sql = "SELECT f.id, COUNT(d.id) as dcount
4e445355 2526 FROM {forum} f
2527 JOIN {forum_discussions} d ON d.forum = f.id
2528 WHERE f.course = ?
90f4745c 2529 $timedsql
2530 GROUP BY f.id";
a48e8c4b 2531
4e445355 2532 if ($counts = $DB->get_records_sql($sql, $params)) {
90f4745c 2533 foreach ($counts as $count) {
2534 $counts[$count->id] = $count->dcount;
2535 }
2536 $cache[$course->id] = $counts;
2537 } else {
2538 $cache[$course->id] = array();
2539 }
a48e8c4b 2540 }
90f4745c 2541
2542 if (empty($cache[$course->id][$forum->id])) {
2543 return 0;
a48e8c4b 2544 }
90f4745c 2545
2546 $groupmode = groups_get_activity_groupmode($cm, $course);
2547
2548 if ($groupmode != SEPARATEGROUPS) {
2549 return $cache[$course->id][$forum->id];
1f48942e 2550 }
90f4745c 2551
bf0f06b1 2552 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
90f4745c 2553 return $cache[$course->id][$forum->id];
2554 }
2555
2556 require_once($CFG->dirroot.'/course/lib.php');
2557
f20edd52 2558 $modinfo = get_fast_modinfo($course);
90f4745c 2559
2c1bbbc5 2560 $mygroups = $modinfo->get_groups($cm->groupingid);
90f4745c 2561
2562 // add all groups posts
2c1bbbc5 2563 $mygroups[-1] = -1;
4e445355 2564
2565 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
2566 $params[] = $forum->id;
90f4745c 2567
2568 if (!empty($CFG->forum_enabletimedposts)) {
2569 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
4e445355 2570 $params[] = $now;
2571 $params[] = $now;
90f4745c 2572 } else {
2573 $timedsql = "";
2574 }
2575
2576 $sql = "SELECT COUNT(d.id)
4e445355 2577 FROM {forum_discussions} d
342650a7 2578 WHERE d.groupid $mygroups_sql AND d.forum = ?
90f4745c 2579 $timedsql";
2580
4e445355 2581 return $DB->get_field_sql($sql, $params);
1f48942e 2582}
2583
0a4ac01b 2584/**
2585 * Get all discussions in a forum
df1ba0f4 2586 *
2587 * @global object
2588 * @global object
2589 * @global object
2590 * @uses CONTEXT_MODULE
2591 * @uses VISIBLEGROUPS
2592 * @param object $cm
2593 * @param string $forumsort
2594 * @param bool $fullpost
2595 * @param int $unused
2596 * @param int $limit
2597 * @param bool $userlastmodified
2598 * @param int $page
2599 * @param int $perpage
2600 * @return array
0a4ac01b 2601 */
90f4745c 2602function forum_get_discussions($cm, $forumsort="d.timemodified DESC", $fullpost=true, $unused=-1, $limit=-1, $userlastmodified=false, $page=-1, $perpage=0) {
4e445355 2603 global $CFG, $DB, $USER;
0fcac008 2604
3d284127 2605 $timelimit = '';
2606
90f4745c 2607 $now = round(time(), -2);
4e445355 2608 $params = array($cm->instance);
90f4745c 2609
bf0f06b1 2610 $modcontext = context_module::instance($cm->id);
2b63df96 2611
4436a63b 2612 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
2613 return array();
2614 }
2615
2616 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2b63df96 2617
0468976c 2618 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2619 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2620 $params[] = $now;
2621 $params[] = $now;
90f4745c 2622 if (isloggedin()) {
4e445355 2623 $timelimit .= " OR d.userid = ?";
2624 $params[] = $USER->id;
3d284127 2625 }
90f4745c 2626 $timelimit .= ")";
fbc21e82 2627 }
fbc21e82 2628 }
1f48942e 2629
90f4745c 2630 if ($limit > 0) {
2631 $limitfrom = 0;
2632 $limitnum = $limit;
2633 } else if ($page != -1) {
2634 $limitfrom = $page*$perpage;
2635 $limitnum = $perpage;
2636 } else {
2637 $limitfrom = 0;
2638 $limitnum = 0;
90ec387a 2639 }
8f0cd6ef 2640
90f4745c 2641 $groupmode = groups_get_activity_groupmode($cm);
2642 $currentgroup = groups_get_activity_group($cm);
353228d8 2643
fffa8b35 2644 if ($groupmode) {
2645 if (empty($modcontext)) {
bf0f06b1 2646 $modcontext = context_module::instance($cm->id);
fffa8b35 2647 }
2648
2649 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2650 if ($currentgroup) {
4e445355 2651 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2652 $params[] = $currentgroup;
fffa8b35 2653 } else {
2654 $groupselect = "";
2655 }
2656
2657 } else {
2658 //seprate groups without access all
2659 if ($currentgroup) {
4e445355 2660 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2661 $params[] = $currentgroup;
fffa8b35 2662 } else {
2663 $groupselect = "AND d.groupid = -1";
2664 }
2665 }
353228d8 2666 } else {
02509fe6 2667 $groupselect = "";
2668 }
2862b309 2669
fffa8b35 2670
29507631 2671 if (empty($forumsort)) {
2672 $forumsort = "d.timemodified DESC";
2673 }
2ab968e9 2674 if (empty($fullpost)) {
b879effb 2675 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2ab968e9 2676 } else {
2677 $postdata = "p.*";
2678 }
9197e147 2679
13597d01 2680 if (empty($userlastmodified)) { // We don't need to know this
fffa8b35 2681 $umfields = "";
2682 $umtable = "";
13597d01 2683 } else {
5b1944bb 2684 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um');
4e445355 2685 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
90f4745c 2686 }
2687
a327f25e
AG
2688 $allnames = get_all_user_name_fields(true, 'u');
2689 $sql = "SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, $allnames,
2690 u.email, u.picture, u.imagealt $umfields
4e445355 2691 FROM {forum_discussions} d
2692 JOIN {forum_posts} p ON p.discussion = d.id
2693 JOIN {user} u ON p.userid = u.id
90f4745c 2694 $umtable
4e445355 2695 WHERE d.forum = ? AND p.parent = 0
90f4745c 2696 $timelimit $groupselect
2697 ORDER BY $forumsort";
4e445355 2698 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
90f4745c 2699}
2700
8d3a5ba1
FM
2701/**
2702 * Gets the neighbours (previous and next) of a discussion.
2703 *
2704 * The calculation is based on the timemodified of the discussion and does not handle
2705 * the neighbours having an identical timemodified. The reason is that we do not have any
2706 * other mean to sort the records, e.g. we cannot use IDs as a greater ID can have a lower
2707 * timemodified.
2708 *
2709 * Please note that this does not check whether or not the discussion passed is accessible
2710 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
2711 * the returned neighbours are checked and are accessible to the current user.
2712 *
2713 * @param object $cm The CM record.
2714 * @param object $discussion The discussion record.
2715 * @return array That always contains the keys 'prev' and 'next'. When there is a result
2716 * they contain the record with minimal information such as 'id' and 'name'.
2717 * When the neighbour is not found the value is false.
2718 */
2719function forum_get_discussion_neighbours($cm, $discussion) {
2720 global $CFG, $DB, $USER;
2721
2722 if ($cm->instance != $discussion->forum) {
2723 throw new coding_exception('Discussion is not part of the same forum.');
2724 }
2725
2726 $neighbours = array('prev' => false, 'next' => false);
2727 $now = round(time(), -2);
2728 $params = array();
2729
2730 $modcontext = context_module::instance($cm->id);
2731 $groupmode = groups_get_activity_groupmode($cm);
2732 $currentgroup = groups_get_activity_group($cm);
2733
2734 // Users must fulfill timed posts.
2735 $timelimit = '';
2736 if (!empty($CFG->forum_enabletimedposts)) {
2737 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
2738 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
2739 $params['tltimestart'] = $now;
2740 $params['tltimeend'] = $now;
2741 if (isloggedin()) {
2742 $timelimit .= ' OR d.userid = :tluserid';
2743 $params['tluserid'] = $USER->id;
2744 }
2745 $timelimit .= ')';
2746 }
2747 }
2748
2749 // Limiting to posts accessible according to groups.
2750 $groupselect = '';
2751 if ($groupmode) {
2752 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
2753 if ($currentgroup) {
2754 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2755 $params['groupid'] = $currentgroup;
2756 }
2757 } else {
2758 if ($currentgroup) {
2759 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
2760 $params['groupid'] = $currentgroup;
2761 } else {
2762 $groupselect = 'AND d.groupid = -1';
2763 }
2764 }
2765 }
2766
2767 $params['forumid'] = $cm->instance;
2768 $params['discid'] = $discussion->id;
2769 $params['disctimemodified'] = $discussion->timemodified;
2770
2771 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
2772 FROM {forum_discussions} d
2773 WHERE d.forum = :forumid
2774 AND d.id <> :discid
2775 $timelimit
2776 $groupselect";
2777
2778 $prevsql = $sql . " AND d.timemodified < :disctimemodified
2779 ORDER BY d.timemodified DESC";
2780
2781 $nextsql = $sql . " AND d.timemodified > :disctimemodified
2782 ORDER BY d.timemodified ASC";
2783
2784 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
2785 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
2786
2787 return $neighbours;
2788}
2789
df1ba0f4 2790/**
2791 *
2792 * @global object
2793 * @global object
2794 * @global object
2795 * @uses CONTEXT_MODULE
2796 * @uses VISIBLEGROUPS
2797 * @param object $cm
2798 * @return array
2799 */
bfeb10b7 2800function forum_get_discussions_unread($cm) {
4e445355 2801 global $CFG, $DB, $USER;
90f4745c 2802
2803 $now = round(time(), -2);
ee151230 2804 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
35716b86 2805
ee151230 2806 $params = array();
90f4745c 2807 $groupmode = groups_get_activity_groupmode($cm);
2808 $currentgroup = groups_get_activity_group($cm);
2809
2810 if ($groupmode) {
bf0f06b1 2811 $modcontext = context_module::instance($cm->id);
90f4745c 2812
2813 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2814 if ($currentgroup) {
ee151230
AD
2815 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2816 $params['currentgroup'] = $currentgroup;
90f4745c 2817 } else {
2818 $groupselect = "";
2819 }
2820
2821 } else {
ee151230 2822 //separate groups without access all
90f4745c 2823 if ($currentgroup) {
ee151230
AD
2824 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
2825 $params['currentgroup'] = $currentgroup;
90f4745c 2826 } else {
2827 $groupselect = "AND d.groupid = -1";
2828 }
2829 }
2830 } else {
2831 $groupselect = "";
13597d01 2832 }
2833
90f4745c 2834 if (!empty($CFG->forum_enabletimedposts)) {
ee151230
AD
2835 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
2836 $params['now1'] = $now;
2837 $params['now2'] = $now;
90f4745c 2838 } else {
2839 $timedsql = "";
2840 }
2841
2842 $sql = "SELECT d.id, COUNT(p.id) AS unread
4e445355 2843 FROM {forum_discussions} d
2844 JOIN {forum_posts} p ON p.discussion = d.id
2845 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
90f4745c 2846 WHERE d.forum = {$cm->instance}
ee151230 2847 AND p.modified >= :cutoffdate AND r.id is NULL
90f4745c 2848 $groupselect
4e445355 2849 $timedsql
bfeb10b7 2850 GROUP BY d.id";
ee151230
AD
2851 $params['cutoffdate'] = $cutoffdate;
2852
4e445355 2853 if ($unreads = $DB->get_records_sql($sql, $params)) {
90f4745c 2854 foreach ($unreads as $unread) {
2855 $unreads[$unread->id] = $unread->unread;
2856 }
2857 return $unreads;
2858 } else {
2859 return array();
2860 }
1f48942e 2861}
2862
df1ba0f4 2863/**
2864 * @global object
2865 * @global object
2866 * @global object
2867 * @uses CONEXT_MODULE
2868 * @uses VISIBLEGROUPS
2869 * @param object $cm
2870 * @return array
2871 */
90f4745c 2872function forum_get_discussions_count($cm) {
4e445355 2873 global $CFG, $DB, $USER;
90f4745c 2874
2875 $now = round(time(), -2);
4e445355 2876 $params = array($cm->instance);
90f4745c 2877 $groupmode = groups_get_activity_groupmode($cm);
2878 $currentgroup = groups_get_activity_group($cm);
2879
2880 if ($groupmode) {
bf0f06b1 2881 $modcontext = context_module::instance($cm->id);
90f4745c 2882
2883 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2884 if ($currentgroup) {
4e445355 2885 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2886 $params[] = $currentgroup;
90f4745c 2887 } else {
2888 $groupselect = "";
2889 }
2890
2891 } else {
2892 //seprate groups without access all
2893 if ($currentgroup) {
4e445355 2894 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2895 $params[] = $currentgroup;
90f4745c 2896 } else {
2897 $groupselect = "AND d.groupid = -1";
2898 }
2899 }
2900 } else {
2901 $groupselect = "";
2902 }
2903
2904 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
2905
2906 $timelimit = "";
2907
2908 if (!empty($CFG->forum_enabletimedposts)) {
2909
bf0f06b1 2910 $modcontext = context_module::instance($cm->id);
90f4745c 2911
2912 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2913 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2914 $params[] = $now;
2915 $params[] = $now;
90f4745c 2916 if (isloggedin()) {
4e445355 2917 $timelimit .= " OR d.userid = ?";
2918 $params[] = $USER->id;
90f4745c 2919 }
2920 $timelimit .= ")";
2921 }
2922 }
2923
2924 $sql = "SELECT COUNT(d.id)
4e445355 2925 FROM {forum_discussions} d
2926 JOIN {forum_posts} p ON p.discussion = d.id
2927 WHERE d.forum = ? AND p.parent = 0
2928 $groupselect $timelimit";
90f4745c 2929
4e445355 2930 return $DB->get_field_sql($sql, $params);
90f4745c 2931}
1f48942e 2932
2933
0a4ac01b 2934// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 2935
2936
df1ba0f4 2937/**
2938 * @global object
2939 * @global object
2940 * @param int $courseid
2941 * @param string $type
2942 */
11b0c469 2943function forum_get_course_forum($courseid, $type) {
2944// How to set up special 1-per-course forums
c112bc60 2945 global $CFG, $DB, $OUTPUT, $USER;
a6fcdf98 2946
4e445355 2947 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
65b0e537 2948 // There should always only be ONE, but with the right combination of
29cbd93a 2949 // errors there might be more. In this case, just return the oldest one (lowest ID).
2950 foreach ($forums as $forum) {
2951 return $forum; // ie the first one
11b0c469 2952 }
8daaf761 2953 }
e6874d9f 2954
8daaf761 2955 // Doesn't exist, so create one now.
b85b25eb 2956 $forum = new stdClass();
8daaf761 2957 $forum->course = $courseid;
2958 $forum->type = "$type";
c112bc60
ARN
2959 if (!empty($USER->htmleditor)) {
2960 $forum->introformat = $USER->htmleditor;
2961 }
8daaf761 2962 switch ($forum->type) {
2963 case "news":
294ce987 2964 $forum->name = get_string("namenews", "forum");
2965 $forum->intro = get_string("intronews", "forum");
906fef94 2966 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 2967 $forum->assessed = 0;
709f0ec8 2968 if ($courseid == SITEID) {
2969 $forum->name = get_string("sitenews");
2970 $forum->forcesubscribe = 0;
8f0cd6ef 2971 }
8daaf761 2972 break;
2973 case "social":
294ce987 2974 $forum->name = get_string("namesocial", "forum");
2975 $forum->intro = get_string("introsocial", "forum");
8daaf761 2976 $forum->assessed = 0;
2977 $forum->forcesubscribe = 0;
2978 break;
1c7b8b93
NC
2979 case "blog":
2980 $forum->name = get_string('blogforum', 'forum');
2981 $forum->intro = get_string('introblog', 'forum');
2982 $forum->assessed = 0;
2983 $forum->forcesubscribe = 0;
2984 break;
8daaf761 2985 default:
9146b979 2986 echo $OUTPUT->notification("That forum type doesn't exist!");
8daaf761 2987 return false;
2988 break;
2989 }
2990
2991 $forum->timemodified = time();
4e445355 2992 $forum->id = $DB->insert_record("forum", $forum);
8daaf761 2993
4e445355 2994 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
9146b979 2995 echo $OUTPUT->notification("Could not find forum module!!");
e1b5643f 2996 return false;
82aa0e8d 2997 }
39790bd8 2998 $mod = new stdClass();
e1b5643f 2999 $mod->course = $courseid;
3000 $mod->module = $module->id;
3001 $mod->instance = $forum->id;
3002 $mod->section = 0;
722e6ba9
MG
3003 include_once("$CFG->dirroot/course/lib.php");
3004 if (! $mod->coursemodule = add_course_module($mod) ) {
11cd754e 3005 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
e1b5643f 3006 return false;
3007 }
722e6ba9 3008 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
4e445355 3009 return $DB->get_record("forum", array("id" => "$forum->id"));
82aa0e8d 3010}
3011
f93f848a 3012
0a4ac01b 3013/**
df1ba0f4 3014 * Given the data about a posting, builds up the HTML to display it and
3015 * returns the HTML in a string. This is designed for sending via HTML email.
3016 *
3017 * @global object
3018 * @param object $course
3019 * @param object $cm
3020 * @param object $forum
3021 * @param object $discussion
3022 * @param object $post
3023 * @param object $userform
3024 * @param object $userto
3025 * @param bool $ownpost
3026 * @param bool $reply
3027 * @param bool $link
3028 * @param bool $rate
3029 * @param string $footer
3030 * @return string
3031 */
0faf6791 3032function forum_make_mail_post($course, $cm, $forum, $discussion, $post, $userfrom, $userto,
11b0c469 3033 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
2b63df96 3034
59e28d8f 3035 global $CFG, $OUTPUT;
501cdbd8 3036
bf0f06b1 3037 $modcontext = context_module::instance($cm->id);
18ff4d42 3038
df1c2c71 3039 if (!isset($userto->viewfullnames[$forum->id])) {
df1c2c71 3040 $viewfullnames = has_capability('moodle/site:viewfullnames', $modcontext, $userto->id);
3041 } else {
3042 $viewfullnames = $userto->viewfullnames[$forum->id];
7613e6d7 3043 }
7613e6d7 3044
18ff4d42
PS
3045 // add absolute file links
3046 $post->message = file_rewrite_pluginfile_urls($post->message, 'pluginfile.php', $modcontext->id, 'mod_forum', 'post', $post->id);
3047
1306c5ea 3048 // format the post body
39790bd8 3049 $options = new stdClass();
1306c5ea 3050 $options->para = true;
e2d7687f 3051 $formattedtext = format_text($post->message, $post->messageformat, $options, $course->id);
0d851f90 3052
add3201e 3053 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
501cdbd8 3054
add3201e 3055 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
812dbaf7 3056 $output .= $OUTPUT->user_picture($userfrom, array('courseid'=>$course->id));
add3201e 3057 $output .= '</td>';
501cdbd8 3058
3059 if ($post->parent) {
add3201e 3060 $output .= '<td class="topic">';
501cdbd8 3061 } else {
add3201e 3062 $output .= '<td class="topic starter">';
501cdbd8 3063 }
add3201e 3064 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
1b26d5e7 3065
df1c2c71 3066 $fullname = fullname($userfrom, $viewfullnames);
39790bd8 3067 $by = new stdClass();
df1c2c71 3068 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$userfrom->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
3069 $by->date = userdate($post->modified, '', $userto->timezone);
add3201e 3070 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
3071
3072 $output .= '</td></tr>';
3073
7b54f563 3074 $output .= '<tr><td class="left side" valign="top">';
df1c2c71 3075
3076 if (isset($userfrom->groups)) {
3077 $groups = $userfrom->groups[$forum->id];
3078 } else {
18ff4d42 3079 $groups = groups_get_all_groups($course->id, $userfrom->id, $cm->groupingid);
df1c2c71 3080 }
3081
3082 if ($groups) {
3083 $output .= print_group_picture($groups, $course->id, false, true, true);
add3201e 3084 } else {
3085 $output .= '&nbsp;';
3086 }
1b26d5e7 3087
add3201e 3088 $output .= '</td><td class="content">';
501cdbd8 3089
0faf6791 3090 $attachments = forum_print_attachments($post, $cm, 'html');
3091 if ($attachments !== '') {
add3201e 3092 $output .= '<div class="attachments">';
0faf6791 3093 $output .= $attachments;
3094 $output .= '</div>';
7f6689e4 3095 }
3096
0d851f90 3097 $output .= $formattedtext;
501cdbd8 3098
0a4ac01b 3099// Commands
add3201e 3100 $commands = array();