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