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