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