weekly release 4.0dev
[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');
7f6689e4 28
501cdbd8 29/// CONSTANTS ///////////////////////////////////////////////////////////
f93f848a 30
d3583b41 31define('FORUM_MODE_FLATOLDEST', 1);
32define('FORUM_MODE_FLATNEWEST', -1);
33define('FORUM_MODE_THREADED', 2);
34define('FORUM_MODE_NESTED', 3);
2602c7bf 35define('FORUM_MODE_NESTED_V2', 4);
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
4f3a2d21
JL
67/**
68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled.
69 */
70define('FORUM_POSTS_ALL_USER_GROUPS', -2);
71
87b007b4
CF
72define('FORUM_DISCUSSION_PINNED', 1);
73define('FORUM_DISCUSSION_UNPINNED', 0);
74
caadf009 75/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
76
0a4ac01b 77/**
78 * Given an object containing all the necessary data,
7cac0c4b 79 * (defined by the form in mod_form.php) this function
0a4ac01b 80 * will create a new instance and return the id number
81 * of the new instance.
df1ba0f4 82 *
6b04fdc0
PS
83 * @param stdClass $forum add forum instance
84 * @param mod_forum_mod_form $mform
6b7de0bb 85 * @return int intance id
3a5e1d06 86 */
6b04fdc0 87function forum_add_instance($forum, $mform = null) {
c18269c7 88 global $CFG, $DB;
caadf009 89
bbbf1820
SR
90 require_once($CFG->dirroot.'/mod/forum/locallib.php');
91
caadf009 92 $forum->timemodified = time();
93
353228d8 94 if (empty($forum->assessed)) {
f2f56406 95 $forum->assessed = 0;
96 }
2b63df96 97
353228d8 98 if (empty($forum->ratingtime) or empty($forum->assessed)) {
98914efd 99 $forum->assesstimestart = 0;
100 $forum->assesstimefinish = 0;
101 }
caadf009 102
a8f3a651 103 $forum->id = $DB->insert_record('forum', $forum);
bf0f06b1 104 $modcontext = context_module::instance($forum->coursemodule);
cb9a975f 105
d3583b41 106 if ($forum->type == 'single') { // Create related discussion.
39790bd8 107 $discussion = new stdClass();
e2d7687f 108 $discussion->course = $forum->course;
109 $discussion->forum = $forum->id;
110 $discussion->name = $forum->name;
e2d7687f 111 $discussion->assessed = $forum->assessed;
6606c00f
MD
112 $discussion->message = $forum->intro;
113 $discussion->messageformat = $forum->introformat;
bf0f06b1 114 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course));
e2d7687f 115 $discussion->mailnow = false;
116 $discussion->groupid = -1;
caadf009 117
dbf4d660 118 $message = '';
119
42776c94
PS
120 $discussion->id = forum_add_discussion($discussion, null, $message);
121
122 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
a11aa38e 123 // Ugly hack - we need to copy the files somehow.
42776c94
PS
124 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST);
125 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
126
a11aa38e
PS
127 $options = array('subdirs'=>true); // Use the same options as intro field!
128 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
42776c94 129 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
caadf009 130 }
131 }
8f0cd6ef 132
bbbf1820 133 forum_update_calendar($forum, $forum->coursemodule);
8e6775d8
AN
134 forum_grade_item_update($forum);
135
b3bd7a66
MN
136 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
137 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
138
8e6775d8
AN
139 return $forum->id;
140}
141
142/**
143 * Handle changes following the creation of a forum instance.
144 * This function is typically called by the course_module_created observer.
145 *
146 * @param object $context the forum context
147 * @param stdClass $forum The forum object
148 * @return void
149 */
150function forum_instance_created($context, $forum) {
3c268f25 151 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) {
59075a43 152 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email');
709f0ec8 153 foreach ($users as $user) {
59075a43 154 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context);
709f0ec8 155 }
156 }
caadf009 157}
158
13bbe067 159/**
0a4ac01b 160 * Given an object containing all the necessary data,
7cac0c4b 161 * (defined by the form in mod_form.php) this function
0a4ac01b 162 * will update an existing instance with new data.
df1ba0f4 163 *
164 * @global object
90f4745c 165 * @param object $forum forum instance (with magic quotes)
6b7de0bb 166 * @return bool success
90f4745c 167 */
42776c94 168function forum_update_instance($forum, $mform) {
bbbf1820
SR
169 global $CFG, $DB, $OUTPUT, $USER;
170
171 require_once($CFG->dirroot.'/mod/forum/locallib.php');
c18269c7 172
caadf009 173 $forum->timemodified = time();
353228d8 174 $forum->id = $forum->instance;
caadf009 175
f0da6b85 176 if (empty($forum->assessed)) {
f2f56406 177 $forum->assessed = 0;
178 }
2b63df96 179
353228d8 180 if (empty($forum->ratingtime) or empty($forum->assessed)) {
98914efd 181 $forum->assesstimestart = 0;
182 $forum->assesstimefinish = 0;
183 }
184
c18269c7 185 $oldforum = $DB->get_record('forum', array('id'=>$forum->id));
13bbe067 186
187 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum
188 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond?
189 // 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
92b229c5
AN
190 $updategrades = false;
191
192 if ($oldforum->assessed <> $forum->assessed) {
193 // Whether this forum is rated.
194 $updategrades = true;
195 }
196
197 if ($oldforum->scale <> $forum->scale) {
198 // The scale currently in use.
199 $updategrades = true;
200 }
201
202 if (empty($oldforum->grade_forum) || $oldforum->grade_forum <> $forum->grade_forum) {
203 // The whole forum grading.
204 $updategrades = true;
205 }
206
207 if ($updategrades) {
208 forum_update_grades($forum); // Recalculate grades for the forum.
13bbe067 209 }
210
d3583b41 211 if ($forum->type == 'single') { // Update related discussion and post.
35b81f27
RT
212 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC');
213 if (!empty($discussions)) {
214 if (count($discussions) > 1) {
215 echo $OUTPUT->notification(get_string('warnformorepost', 'forum'));
216 }
217 $discussion = array_pop($discussions);
218 } else {
219 // try to recover by creating initial discussion - MDL-16262
220 $discussion = new stdClass();
221 $discussion->course = $forum->course;
222 $discussion->forum = $forum->id;
223 $discussion->name = $forum->name;
224 $discussion->assessed = $forum->assessed;
225 $discussion->message = $forum->intro;
226 $discussion->messageformat = $forum->introformat;
227 $discussion->messagetrust = true;
228 $discussion->mailnow = false;
229 $discussion->groupid = -1;
230
231 $message = '';
232
233 forum_add_discussion($discussion, null, $message);
234
235 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) {
236 print_error('cannotadd', 'forum');
caadf009 237 }
238 }
c18269c7 239 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) {
12e57b92 240 print_error('cannotfindfirstpost', 'forum');
caadf009 241 }
242
6606c00f 243 $cm = get_coursemodule_from_instance('forum', $forum->id);
bf0f06b1 244 $modcontext = context_module::instance($cm->id, MUST_EXIST);
42776c94 245
a11aa38e 246 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST);
6606c00f
MD
247 $post->subject = $forum->name;
248 $post->message = $forum->intro;
249 $post->messageformat = $forum->introformat;
250 $post->messagetrust = trusttext_trusted($modcontext);
251 $post->modified = $forum->timemodified;
a11aa38e
PS
252 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities.
253
254 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) {
255 // Ugly hack - we need to copy the files somehow.
256 $options = array('subdirs'=>true); // Use the same options as intro field!
257 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message);
258 }
caadf009 259
3eb0a82f 260 \mod_forum\local\entities\post::add_message_counts($post);
a8d6ef8c 261 $DB->update_record('forum_posts', $post);
caadf009 262 $discussion->name = $forum->name;
a8d6ef8c 263 $DB->update_record('forum_discussions', $discussion);
caadf009 264 }
265
a8d6ef8c 266 $DB->update_record('forum', $forum);
353228d8 267
4a913724
GPL
268 $modcontext = context_module::instance($forum->coursemodule);
269 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) {
59075a43 270 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', '');
4a913724 271 foreach ($users as $user) {
59075a43 272 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext);
4a913724
GPL
273 }
274 }
275
bbbf1820 276 forum_update_calendar($forum, $forum->coursemodule);
353228d8 277 forum_grade_item_update($forum);
278
b3bd7a66
MN
279 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null;
280 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected);
281
353228d8 282 return true;
caadf009 283}
284
285
0a4ac01b 286/**
287 * Given an ID of an instance of this module,
288 * this function will permanently delete the instance
289 * and any data that depends on it.
df1ba0f4 290 *
291 * @global object
292 * @param int $id forum instance id
90f4745c 293 * @return bool success
0a4ac01b 294 */
caadf009 295function forum_delete_instance($id) {
c18269c7 296 global $DB;
caadf009 297
c18269c7 298 if (!$forum = $DB->get_record('forum', array('id'=>$id))) {
caadf009 299 return false;
300 }
455a8fed 301 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
302 return false;
303 }
304 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
305 return false;
306 }
307
bf0f06b1 308 $context = context_module::instance($cm->id);
caadf009 309
fa686bc4 310 // now get rid of all files
311 $fs = get_file_storage();
455a8fed 312 $fs->delete_area_files($context->id);
fa686bc4 313
caadf009 314 $result = true;
315
b3bd7a66
MN
316 \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null);
317
361a41d3
AN
318 // Delete digest and subscription preferences.
319 $DB->delete_records('forum_digests', array('forum' => $forum->id));
320 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id));
321 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id));
322
c18269c7 323 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) {
caadf009 324 foreach ($discussions as $discussion) {
455a8fed 325 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) {
caadf009 326 $result = false;
327 }
328 }
329 }
330
f37da850 331 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
332
40fe1538
DW
333 forum_grade_item_delete($forum);
334
335 // We must delete the module record after we delete the grade item.
415f8c3e 336 if (!$DB->delete_records('forum', array('id'=>$forum->id))) {
caadf009 337 $result = false;
338 }
339
340 return $result;
341}
342
343
4e781c7b 344/**
345 * Indicates API features that the forum supports.
346 *
df1ba0f4 347 * @uses FEATURE_GROUPS
348 * @uses FEATURE_GROUPINGS
df1ba0f4 349 * @uses FEATURE_MOD_INTRO
350 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
351 * @uses FEATURE_COMPLETION_HAS_RULES
352 * @uses FEATURE_GRADE_HAS_GRADE
353 * @uses FEATURE_GRADE_OUTCOMES
4e781c7b 354 * @param string $feature
355 * @return mixed True if yes (some features may use other values)
356 */
357function forum_supports($feature) {
358 switch($feature) {
42f103be 359 case FEATURE_GROUPS: return true;
360 case FEATURE_GROUPINGS: return true;
dc5c2bd9 361 case FEATURE_MOD_INTRO: return true;
4e781c7b 362 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 363 case FEATURE_COMPLETION_HAS_RULES: return true;
364 case FEATURE_GRADE_HAS_GRADE: return true;
365 case FEATURE_GRADE_OUTCOMES: return true;
4bfdcfcf
EL
366 case FEATURE_RATE: return true;
367 case FEATURE_BACKUP_MOODLE2: return true;
3e4c2435 368 case FEATURE_SHOW_DESCRIPTION: return true;
50da4ddd 369 case FEATURE_PLAGIARISM: return true;
92b229c5 370 case FEATURE_ADVANCED_GRADING: return true;
42f103be 371
49f6e5f4 372 default: return null;
4e781c7b 373 }
374}
375
8260050d
AD
376/**
377 * Create a message-id string to use in the custom headers of forum notification emails
378 *
379 * message-id is used by email clients to identify emails and to nest conversations
380 *
381 * @param int $postid The ID of the forum post we are notifying the user about
382 * @param int $usertoid The ID of the user being notified
8260050d
AD
383 * @return string A unique message-id
384 */
54dceeed
BH
385function forum_get_email_message_id($postid, $usertoid) {
386 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid));
1376b0dd 387}
4e781c7b 388
0a4ac01b 389/**
13bbe067 390 *
1670305d 391 * @param object $course
392 * @param object $user
393 * @param object $mod TODO this is not used in this function, refactor
394 * @param object $forum
395 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified)
0a4ac01b 396 */
caadf009 397function forum_user_outline($course, $user, $mod, $forum) {
1a96363a
NC
398 global $CFG;
399 require_once("$CFG->libdir/gradelib.php");
92b229c5
AN
400
401 $gradeinfo = '';
402 $gradetime = 0;
403
1a96363a 404 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
92b229c5
AN
405 if (!empty($grades->items[0]->grades)) {
406 // Item 0 is the rating.
1a96363a 407 $grade = reset($grades->items[0]->grades);
92b229c5
AN
408 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
409 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
410 $gradeinfo .= get_string('gradeforrating', 'forum', $grade) . html_writer::empty_tag('br');
411 } else {
412 $gradeinfo .= get_string('gradeforratinghidden', 'forum') . html_writer::empty_tag('br');
413 }
1a96363a
NC
414 }
415
92b229c5
AN
416 // Item 1 is the whole-forum grade.
417 if (!empty($grades->items[1]->grades)) {
418 $grade = reset($grades->items[1]->grades);
419 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user));
f5d1dbb3 420 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
92b229c5 421 $gradeinfo .= get_string('gradeforwholeforum', 'forum', $grade) . html_writer::empty_tag('br');
f5d1dbb3 422 } else {
92b229c5 423 $gradeinfo .= get_string('gradeforwholeforumhidden', 'forum') . html_writer::empty_tag('br');
f5d1dbb3 424 }
92b229c5 425 }
4433f871 426
92b229c5
AN
427 $count = forum_count_user_posts($forum->id, $user->id);
428 if ($count && $count->postcount > 0) {
429 $info = get_string("numposts", "forum", $count->postcount);
430 $time = $count->lastpost;
431
432 if ($gradeinfo) {
433 $info .= ', ' . $gradeinfo;
434 $time = max($time, $gradetime);
435 }
436
437 return (object) [
438 'info' => $info,
439 'time' => $time,
440 ];
441 } else if ($gradeinfo) {
442 return (object) [
443 'info' => $gradeinfo,
444 'time' => $gradetime,
445 ];
caadf009 446 }
92b229c5
AN
447
448 return null;
caadf009 449}
450
451
0a4ac01b 452/**
df1ba0f4 453 * @global object
454 * @global object
455 * @param object $coure
456 * @param object $user
457 * @param object $mod
458 * @param object $forum
0a4ac01b 459 */
caadf009 460function forum_user_complete($course, $user, $mod, $forum) {
92b229c5 461 global $CFG, $USER;
1a96363a
NC
462 require_once("$CFG->libdir/gradelib.php");
463
92b229c5
AN
464 $getgradeinfo = function($grades, string $type) use ($course): string {
465 global $OUTPUT;
466
467 if (empty($grades)) {
468 return '';
469 }
470
471 $result = '';
472 $grade = reset($grades);
f5d1dbb3 473 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
92b229c5 474 $result .= $OUTPUT->container(get_string("gradefor{$type}", "forum", $grade));
f5d1dbb3 475 if ($grade->str_feedback) {
92b229c5 476 $result .= $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
f5d1dbb3
MF
477 }
478 } else {
92b229c5 479 $result .= $OUTPUT->container(get_string("gradefor{$type}hidden", "forum"));
1a96363a 480 }
caadf009 481
92b229c5
AN
482 return $result;
483 };
e3ff14ca 484
92b229c5 485 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id);
ff25eb0f
SR
486
487 // Item 0 is the rating.
488 if (!empty($grades->items[0]->grades)) {
489 echo $getgradeinfo($grades->items[0]->grades, 'rating');
490 }
491
492 // Item 1 is the whole-forum grade.
493 if (!empty($grades->items[1]->grades)) {
494 echo $getgradeinfo($grades->items[1]->grades, 'wholeforum');
495 }
92b229c5
AN
496
497 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
65bcf17b 498 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
12e57b92 499 print_error('invalidcoursemodule');
65bcf17b 500 }
2e19ca18 501 $context = context_module::instance($cm->id);
90f4745c 502 $discussions = forum_get_user_involved_discussions($forum->id, $user->id);
2e19ca18
RW
503 $posts = array_filter($posts, function($post) use ($discussions) {
504 return isset($discussions[$post->discussion]);
505 });
506 $entityfactory = mod_forum\local\container::get_entity_factory();
507 $rendererfactory = mod_forum\local\container::get_renderer_factory();
508 $postrenderer = $rendererfactory->get_posts_renderer();
509
510 echo $postrenderer->render(
511 $USER,
512 [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)],
513 array_map(function($discussion) use ($entityfactory) {
514 return $entityfactory->get_discussion_from_stdclass($discussion);
515 }, $discussions),
516 array_map(function($post) use ($entityfactory) {
517 return $entityfactory->get_post_from_stdclass($post);
518 }, $posts)
519 );
caadf009 520 } else {
41905731 521 echo "<p>".get_string("noposts", "forum")."</p>";
caadf009 522 }
caadf009 523}
524
8538c562 525/**
b18015c6 526 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
8538c562 527 */
b18015c6
SA
528function forum_filter_user_groups_discussions() {
529 throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.');
8538c562
DM
530}
531
532/**
533 * Returns whether the discussion group is visible by the current user or not.
534 *
535 * @since Moodle 2.8, 2.7.1, 2.6.4
536 * @param cm_info $cm The discussion course module
537 * @param int $discussiongroupid The discussion groupid
538 * @return bool
539 */
540function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) {
541
542 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) {
543 return true;
544 }
545
546 if (isguestuser()) {
547 return false;
548 }
549
550 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) ||
551 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) {
552 return true;
553 }
554
555 return false;
556}
5e7f2b0b 557
0a4ac01b 558/**
b18015c6 559 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
0a4ac01b 560 */
b18015c6
SA
561function forum_print_overview() {
562 throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.');
0d6b9d4f 563}
564
0a4ac01b 565/**
566 * Given a course and a date, prints a summary of all the new
567 * messages posted in the course since that date
df1ba0f4 568 *
569 * @global object
570 * @global object
571 * @global object
572 * @uses CONTEXT_MODULE
573 * @uses VISIBLEGROUPS
90f4745c 574 * @param object $course
575 * @param bool $viewfullnames capability
576 * @param int $timestart
577 * @return bool success
0a4ac01b 578 */
dd97c328 579function forum_print_recent_activity($course, $viewfullnames, $timestart) {
7cce925f 580 global $USER, $DB, $OUTPUT;
caadf009 581
dd97c328 582 // do not use log table if possible, it may be huge and is expensive to join with other tables
caadf009 583
5e72715e 584 $userfieldsapi = \core_user\fields::for_userpic();
558cc1b8 585 $allnamefields = $userfieldsapi->get_sql('u', false, '', 'duserid', false)->selects;
7cce925f
JP
586 if (!$posts = $DB->get_records_sql("SELECT p.*,
587 f.course, f.type AS forumtype, f.name AS forumname, f.intro, f.introformat, f.duedate,
588 f.cutoffdate, f.assessed AS forumassessed, f.assesstimestart, f.assesstimefinish,
589 f.scale, f.grade_forum, f.maxbytes, f.maxattachments, f.forcesubscribe,
590 f.trackingtype, f.rsstype, f.rssarticles, f.timemodified, f.warnafter, f.blockafter,
591 f.blockperiod, f.completiondiscussions, f.completionreplies, f.completionposts,
592 f.displaywordcount, f.lockdiscussionafter, f.grade_forum_notify,
593 d.name AS discussionname, d.firstpost, d.userid AS discussionstarter,
594 d.assessed AS discussionassessed, d.timemodified, d.usermodified, d.forum, d.groupid,
595 d.timestart, d.timeend, d.pinned, d.timelocked,
596 $allnamefields
4e445355 597 FROM {forum_posts} p
598 JOIN {forum_discussions} d ON d.id = p.discussion
599 JOIN {forum} f ON f.id = d.forum
600 JOIN {user} u ON u.id = p.userid
3e95e09b 601 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1
4e445355 602 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date
dd97c328 603 return false;
1b5910c4 604 }
605
f20edd52 606 $modinfo = get_fast_modinfo($course);
dcde9f02 607
dd97c328 608 $strftimerecent = get_string('strftimerecent');
d05956ac 609
7cce925f
JP
610 $managerfactory = mod_forum\local\container::get_manager_factory();
611 $entityfactory = mod_forum\local\container::get_entity_factory();
612
613 $discussions = [];
614 $capmanagers = [];
615 $printposts = [];
dd97c328 616 foreach ($posts as $post) {
617 if (!isset($modinfo->instances['forum'][$post->forum])) {
618 // not visible
619 continue;
620 }
621 $cm = $modinfo->instances['forum'][$post->forum];
622 if (!$cm->uservisible) {
623 continue;
624 }
6b7de0bb 625
7cce925f
JP
626 // Get the discussion. Cache if not yet available.
627 if (!isset($discussions[$post->discussion])) {
628 // Build the discussion record object from the post data.
629 $discussionrecord = (object)[
630 'id' => $post->discussion,
631 'course' => $post->course,
632 'forum' => $post->forum,
633 'name' => $post->discussionname,
634 'firstpost' => $post->firstpost,
635 'userid' => $post->discussionstarter,
636 'groupid' => $post->groupid,
637 'assessed' => $post->discussionassessed,
638 'timemodified' => $post->timemodified,
639 'usermodified' => $post->usermodified,
640 'timestart' => $post->timestart,
641 'timeend' => $post->timeend,
642 'pinned' => $post->pinned,
643 'timelocked' => $post->timelocked
644 ];
645 // Build the discussion entity from the factory and cache it.
646 $discussions[$post->discussion] = $entityfactory->get_discussion_from_stdclass($discussionrecord);
6b7de0bb 647 }
7cce925f
JP
648 $discussionentity = $discussions[$post->discussion];
649
650 // Get the capability manager. Cache if not yet available.
651 if (!isset($capmanagers[$post->forum])) {
652 $context = context_module::instance($cm->id);
653 $coursemodule = $cm->get_course_module_record();
654 // Build the forum record object from the post data.
655 $forumrecord = (object)[
656 'id' => $post->forum,
657 'course' => $post->course,
658 'type' => $post->forumtype,
659 'name' => $post->forumname,
660 'intro' => $post->intro,
661 'introformat' => $post->introformat,
662 'duedate' => $post->duedate,
663 'cutoffdate' => $post->cutoffdate,
664 'assessed' => $post->forumassessed,
665 'assesstimestart' => $post->assesstimestart,
666 'assesstimefinish' => $post->assesstimefinish,
667 'scale' => $post->scale,
668 'grade_forum' => $post->grade_forum,
669 'maxbytes' => $post->maxbytes,
670 'maxattachments' => $post->maxattachments,
671 'forcesubscribe' => $post->forcesubscribe,
672 'trackingtype' => $post->trackingtype,
673 'rsstype' => $post->rsstype,
674 'rssarticles' => $post->rssarticles,
675 'timemodified' => $post->timemodified,
676 'warnafter' => $post->warnafter,
677 'blockafter' => $post->blockafter,
678 'blockperiod' => $post->blockperiod,
679 'completiondiscussions' => $post->completiondiscussions,
680 'completionreplies' => $post->completionreplies,
681 'completionposts' => $post->completionposts,
682 'displaywordcount' => $post->displaywordcount,
683 'lockdiscussionafter' => $post->lockdiscussionafter,
684 'grade_forum_notify' => $post->grade_forum_notify
685 ];
686 // Build the forum entity from the factory.
687 $forumentity = $entityfactory->get_forum_from_stdclass($forumrecord, $context, $coursemodule, $course);
688 // Get the capability manager of this forum and cache it.
689 $capmanagers[$post->forum] = $managerfactory->get_capability_manager($forumentity);
dd97c328 690 }
7cce925f 691 $capabilitymanager = $capmanagers[$post->forum];
583b57b4 692
7cce925f
JP
693 // Get the post entity.
694 $postentity = $entityfactory->get_post_from_stdclass($post);
bc4c7337 695
7cce925f
JP
696 // Check if the user can view the post.
697 if ($capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) {
8538c562 698 $printposts[] = $post;
dd97c328 699 }
dd97c328 700 }
701 unset($posts);
8f7dc7f1 702
dd97c328 703 if (!$printposts) {
704 return false;
705 }
706
439c8c59 707 echo $OUTPUT->heading(get_string('newforumposts', 'forum') . ':', 6);
af0fc6a2 708 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
dd97c328 709
710 foreach ($printposts as $post) {
711 $subjectclass = empty($post->parent) ? ' bold' : '';
af0fc6a2 712 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]);
dd97c328 713
af0fc6a2
JP
714 $list .= html_writer::start_tag('li');
715 $list .= html_writer::start_div('head');
1bf3a76a 716 $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date');
af0fc6a2
JP
717 if (!$authorhidden) {
718 $list .= html_writer::div(fullname($post, $viewfullnames), 'name');
719 }
720 $list .= html_writer::end_div(); // Head.
721
722 $list .= html_writer::start_div('info' . $subjectclass);
723 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]);
724 if (!empty($post->parent)) {
725 $discussionurl->param('parent', $post->parent);
726 $discussionurl->set_anchor('p'. $post->id);
caadf009 727 }
dd97c328 728 $post->subject = break_up_long_words(format_string($post->subject, true));
934ee47b 729 $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']);
af0fc6a2
JP
730 $list .= html_writer::end_div(); // Info.
731 $list .= html_writer::end_tag('li');
caadf009 732 }
dd97c328 733
af0fc6a2
JP
734 $list .= html_writer::end_tag('ul');
735 echo $list;
dd97c328 736
737 return true;
caadf009 738}
739
353228d8 740/**
92b229c5 741 * Update activity grades.
353228d8 742 *
775f811a 743 * @param object $forum
744 * @param int $userid specific user only, 0 means all
0a4ac01b 745 */
92b229c5 746function forum_update_grades($forum, $userid = 0): void {
4e445355 747 global $CFG, $DB;
775f811a 748 require_once($CFG->libdir.'/gradelib.php');
caadf009 749
92b229c5
AN
750 $ratings = null;
751 if ($forum->assessed) {
752 require_once($CFG->dirroot.'/rating/lib.php');
02ebf404 753
e9a5485f
PH
754 $cm = get_coursemodule_from_instance('forum', $forum->id);
755
92b229c5
AN
756 $rm = new rating_manager();
757 $ratings = $rm->get_user_grades((object) [
758 'component' => 'mod_forum',
759 'ratingarea' => 'post',
760 'contextid' => \context_module::instance($cm->id)->id,
eafb9d9e 761
92b229c5
AN
762 'modulename' => 'forum',
763 'moduleid ' => $forum->id,
764 'userid' => $userid,
765 'aggregationmethod' => $forum->assessed,
766 'scaleid' => $forum->scale,
767 'itemtable' => 'forum_posts',
768 'itemtableusercolumn' => 'userid',
769 ]);
770 }
02ebf404 771
92b229c5
AN
772 $forumgrades = null;
773 if ($forum->grade_forum) {
f8da1b93
AN
774 $sql = <<<EOF
775SELECT
776 g.userid,
777 0 as datesubmitted,
778 g.grade as rawgrade,
779 g.timemodified as dategraded
780 FROM {forum} f
781 JOIN {forum_grades} g ON g.forum = f.id
782 WHERE f.id = :forumid
783EOF;
784
785 $params = [
786 'forumid' => $forum->id,
787 ];
788
789 if ($userid) {
54b3ffa0 790 $sql .= " AND g.userid = :userid";
f8da1b93
AN
791 $params['userid'] = $userid;
792 }
793
794 $forumgrades = [];
795 if ($grades = $DB->get_recordset_sql($sql, $params)) {
796 foreach ($grades as $userid => $grade) {
797 if ($grade->rawgrade != -1) {
798 $forumgrades[$userid] = $grade;
799 }
800 }
801 $grades->close();
802 }
775f811a 803 }
92b229c5
AN
804
805 forum_grade_item_update($forum, $ratings, $forumgrades);
775f811a 806}
807
353228d8 808/**
92b229c5 809 * Create/update grade items for given forum.
353228d8 810 *
a153c9f2
AD
811 * @param stdClass $forum Forum object with extra cmidnumber
812 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
353228d8 813 */
92b229c5 814function forum_grade_item_update($forum, $ratings = null, $forumgrades = null): void {
612607bd 815 global $CFG;
92b229c5 816 require_once("{$CFG->libdir}/gradelib.php");
353228d8 817
92b229c5
AN
818 // Update the rating.
819 $item = [
820 'itemname' => get_string('gradeitemnameforrating', 'forum', $forum),
821 'idnumber' => $forum->cmidnumber,
822 ];
353228d8 823
92b229c5
AN
824 if (!$forum->assessed || $forum->scale == 0) {
825 $item['gradetype'] = GRADE_TYPE_NONE;
353228d8 826 } else if ($forum->scale > 0) {
92b229c5
AN
827 $item['gradetype'] = GRADE_TYPE_VALUE;
828 $item['grademax'] = $forum->scale;
829 $item['grademin'] = 0;
353228d8 830 } else if ($forum->scale < 0) {
92b229c5
AN
831 $item['gradetype'] = GRADE_TYPE_SCALE;
832 $item['scaleid'] = -$forum->scale;
353228d8 833 }
834
92b229c5
AN
835 if ($ratings === 'reset') {
836 $item['reset'] = true;
837 $ratings = null;
0b5a80a1 838 }
92b229c5
AN
839 // Itemnumber 0 is the rating.
840 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $ratings, $item);
0b5a80a1 841
92b229c5
AN
842 // Whole forum grade.
843 $item = [
844 'itemname' => get_string('gradeitemnameforwholeforum', 'forum', $forum),
845 // Note: We do not need to store the idnumber here.
846 ];
847
848 if (!$forum->grade_forum) {
849 $item['gradetype'] = GRADE_TYPE_NONE;
850 } else if ($forum->grade_forum > 0) {
851 $item['gradetype'] = GRADE_TYPE_VALUE;
852 $item['grademax'] = $forum->grade_forum;
853 $item['grademin'] = 0;
854 } else if ($forum->grade_forum < 0) {
855 $item['gradetype'] = GRADE_TYPE_SCALE;
856 $item['scaleid'] = $forum->grade_forum * -1;
857 }
858
859 if ($forumgrades === 'reset') {
860 $item['reset'] = true;
861 $forumgrades = null;
862 }
863 // Itemnumber 1 is the whole forum grade.
864 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, $forumgrades, $item);
353228d8 865}
866
867/**
92b229c5 868 * Delete grade item for given forum.
353228d8 869 *
a153c9f2 870 * @param stdClass $forum Forum object
353228d8 871 */
872function forum_grade_item_delete($forum) {
612607bd 873 global $CFG;
874 require_once($CFG->libdir.'/gradelib.php');
875
92b229c5
AN
876 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, null, ['deleted' => 1]);
877 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, null, ['deleted' => 1]);
caadf009 878}
879
85c9ebb9 880/**
92b229c5 881 * Checks if scale is being used by any instance of forum.
85c9ebb9 882 *
92b229c5 883 * This is used to find out if scale used anywhere.
df1ba0f4 884 *
85c9ebb9 885 * @param $scaleid int
886 * @return boolean True if the scale is used by any forum
887 */
92b229c5 888function forum_scale_used_anywhere(int $scaleid): bool {
4e445355 889 global $DB;
92b229c5
AN
890
891 if (empty($scaleid)) {
85c9ebb9 892 return false;
893 }
92b229c5 894
7b3f43db 895 return $DB->record_exists_select('forum', "scale = ? and assessed > 0", [$scaleid * -1]);
85c9ebb9 896}
897
0a4ac01b 898// SQL FUNCTIONS ///////////////////////////////////////////////////////////
9fa49e22 899
0a4ac01b 900/**
901 * Gets a post with all info ready for forum_print_post
902 * Most of these joins are just to get the forum id
df1ba0f4 903 *
904 * @global object
905 * @global object
90f4745c 906 * @param int $postid
907 * @return mixed array of posts or false
0a4ac01b 908 */
1f48942e 909function forum_get_post_full($postid) {
4e445355 910 global $CFG, $DB;
1f48942e 911
5e72715e 912 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 913 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
a327f25e 914 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 915 FROM {forum_posts} p
916 JOIN {forum_discussions} d ON p.discussion = d.id
917 LEFT JOIN {user} u ON p.userid = u.id
918 WHERE p.id = ?", array($postid));
1f48942e 919}
920
65bcf17b 921/**
922 * Gets all posts in discussion including top parent.
df1ba0f4 923 *
bc4c7337
AN
924 * @param int $discussionid The Discussion to fetch.
925 * @param string $sort The sorting to apply.
926 * @param bool $tracking Whether the user tracks this forum.
927 * @return array The posts in the discussion.
65bcf17b 928 */
bc4c7337 929function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) {
4e445355 930 global $CFG, $DB, $USER;
65bcf17b 931
3c2bf848 932 $tr_sel = "";
933 $tr_join = "";
4e445355 934 $params = array();
3c2bf848 935
90f4745c 936 if ($tracking) {
90f4745c 937 $tr_sel = ", fr.id AS postread";
4e445355 938 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)";
939 $params[] = $USER->id;
90f4745c 940 }
941
5e72715e 942 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 943 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4e445355 944 $params[] = $discussionid;
a327f25e 945 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel
4e445355 946 FROM {forum_posts} p
947 LEFT JOIN {user} u ON p.userid = u.id
90f4745c 948 $tr_join
4e445355 949 WHERE p.discussion = ?
950 ORDER BY $sort", $params)) {
65bcf17b 951 return array();
952 }
953
954 foreach ($posts as $pid=>$p) {
90f4745c 955 if ($tracking) {
956 if (forum_tp_is_post_old($p)) {
6b7de0bb 957 $posts[$pid]->postread = true;
90f4745c 958 }
959 }
65bcf17b 960 if (!$p->parent) {
961 continue;
962 }
963 if (!isset($posts[$p->parent])) {
964 continue; // parent does not exist??
965 }
966 if (!isset($posts[$p->parent]->children)) {
967 $posts[$p->parent]->children = array();
968 }
969 $posts[$p->parent]->children[$pid] =& $posts[$pid];
970 }
971
bfa7bece
AN
972 // Start with the last child of the first post.
973 $post = &$posts[reset($posts)->id];
974
975 $lastpost = false;
976 while (!$lastpost) {
977 if (!isset($post->children)) {
978 $post->lastpost = true;
979 $lastpost = true;
980 } else {
981 // Go to the last child of this post.
982 $post = &$posts[end($post->children)->id];
983 }
984 }
985
65bcf17b 986 return $posts;
987}
988
42fb3c85 989/**
990 * An array of forum objects that the user is allowed to read/search through.
df1ba0f4 991 *
992 * @global object
993 * @global object
994 * @global object
995 * @param int $userid
996 * @param int $courseid if 0, we look for forums throughout the whole site.
42fb3c85 997 * @return array of forum objects, or false if no matches
998 * Forum objects have the following attributes:
999 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups,
1000 * viewhiddentimedposts
1001 */
1002function forum_get_readable_forums($userid, $courseid=0) {
2b63df96 1003
4e445355 1004 global $CFG, $DB, $USER;
6b7de0bb 1005 require_once($CFG->dirroot.'/course/lib.php');
2b63df96 1006
4e445355 1007 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) {
12e57b92 1008 print_error('notinstalled', 'forum');
42fb3c85 1009 }
2b63df96 1010
42fb3c85 1011 if ($courseid) {
4e445355 1012 $courses = $DB->get_records('course', array('id' => $courseid));
42fb3c85 1013 } else {
65bcf17b 1014 // If no course is specified, then the user can see SITE + his courses.
4e445355 1015 $courses1 = $DB->get_records('course', array('id' => SITEID));
b1d5d015 1016 $courses2 = enrol_get_users_courses($userid, true, array('modinfo'));
6155150c 1017 $courses = array_merge($courses1, $courses2);
42fb3c85 1018 }
1019 if (!$courses) {
6b7de0bb 1020 return array();
42fb3c85 1021 }
1022
1023 $readableforums = array();
2b63df96 1024
6527b5c2 1025 foreach ($courses as $course) {
1026
f20edd52 1027 $modinfo = get_fast_modinfo($course);
2b63df96 1028
6b7de0bb 1029 if (empty($modinfo->instances['forum'])) {
1030 // hmm, no forums?
1031 continue;
1032 }
2b63df96 1033
4e445355 1034 $courseforums = $DB->get_records('forum', array('course' => $course->id));
2b63df96 1035
6b7de0bb 1036 foreach ($modinfo->instances['forum'] as $forumid => $cm) {
1037 if (!$cm->uservisible or !isset($courseforums[$forumid])) {
1038 continue;
1039 }
bf0f06b1 1040 $context = context_module::instance($cm->id);
6b7de0bb 1041 $forum = $courseforums[$forumid];
2e945910
AB
1042 $forum->context = $context;
1043 $forum->cm = $cm;
d50704bf 1044
6b7de0bb 1045 if (!has_capability('mod/forum:viewdiscussion', $context)) {
1046 continue;
1047 }
6527b5c2 1048
6b7de0bb 1049 /// group access
1050 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2c1bbbc5
MG
1051
1052 $forum->onlygroups = $modinfo->get_groups($cm->groupingid);
1053 $forum->onlygroups[] = -1;
6b7de0bb 1054 }
2b63df96 1055
6b7de0bb 1056 /// hidden timed discussions
1057 $forum->viewhiddentimedposts = true;
1058 if (!empty($CFG->forum_enabletimedposts)) {
1059 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) {
1060 $forum->viewhiddentimedposts = false;
1061 }
1062 }
d50704bf 1063
6b7de0bb 1064 /// qanda access
1065 if ($forum->type == 'qanda'
1066 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
2b63df96 1067
6b7de0bb 1068 // We need to check whether the user has posted in the qanda forum.
1069 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions
1070 // the user is allowed to see in this forum.
1071 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) {
1072 foreach ($discussionspostedin as $d) {
1073 $forum->onlydiscussions[] = $d->id;
d50704bf 1074 }
42fb3c85 1075 }
1076 }
6b7de0bb 1077
1078 $readableforums[$forum->id] = $forum;
42fb3c85 1079 }
6b7de0bb 1080
1081 unset($modinfo);
1082
42fb3c85 1083 } // End foreach $courses
2b63df96 1084
42fb3c85 1085 return $readableforums;
1086}
1087
bbbf2d40 1088/**
1089 * Returns a list of posts found using an array of search terms.
df1ba0f4 1090 *
1091 * @global object
1092 * @global object
1093 * @global object
1094 * @param array $searchterms array of search terms, e.g. word +word -word
1095 * @param int $courseid if 0, we search through the whole site
1096 * @param int $limitfrom
1097 * @param int $limitnum
1098 * @param int &$totalcount
1099 * @param string $extrasql
1100 * @return array|bool Array of posts found or false
42fb3c85 1101 */
0eada7a5 1102function forum_search_posts($searchterms, $courseid, $limitfrom, $limitnum,
42fb3c85 1103 &$totalcount, $extrasql='') {
4e445355 1104 global $CFG, $DB, $USER;
42fb3c85 1105 require_once($CFG->libdir.'/searchlib.php');
1106
1107 $forums = forum_get_readable_forums($USER->id, $courseid);
2b63df96 1108
67875aa1 1109 if (count($forums) == 0) {
6b7de0bb 1110 $totalcount = 0;
67875aa1 1111 return false;
1112 }
42fb3c85 1113
098f4337 1114 $now = floor(time() / 60) * 60; // DB Cache Friendly.
6b7de0bb 1115
1116 $fullaccess = array();
1117 $where = array();
4e445355 1118 $params = array();
6b7de0bb 1119
1120 foreach ($forums as $forumid => $forum) {
1121 $select = array();
1122
1123 if (!$forum->viewhiddentimedposts) {
b1d5d015
PS
1124 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
1125 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now));
42fb3c85 1126 }
6b7de0bb 1127
2e945910
AB
1128 $cm = $forum->cm;
1129 $context = $forum->context;
ad9c22aa 1130
1131 if ($forum->type == 'qanda'
1132 && !has_capability('mod/forum:viewqandawithoutposting', $context)) {
6b7de0bb 1133 if (!empty($forum->onlydiscussions)) {
cf717dc2 1134 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
4e445355 1135 $params = array_merge($params, $discussionid_params);
1136 $select[] = "(d.id $discussionid_sql OR p.parent = 0)";
d50704bf 1137 } else {
6b7de0bb 1138 $select[] = "p.parent = 0";
d50704bf 1139 }
1140 }
6b7de0bb 1141
1142 if (!empty($forum->onlygroups)) {
cf717dc2 1143 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
4e445355 1144 $params = array_merge($params, $groupid_params);
1145 $select[] = "d.groupid $groupid_sql";
42fb3c85 1146 }
6b7de0bb 1147
1148 if ($select) {
1149 $selects = implode(" AND ", $select);
b1d5d015
PS
1150 $where[] = "(d.forum = :forum{$forumid} AND $selects)";
1151 $params['forum'.$forumid] = $forumid;
6b7de0bb 1152 } else {
1153 $fullaccess[] = $forumid;
1154 }
1155 }
1156
1157 if ($fullaccess) {
cf717dc2 1158 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula');
4e445355 1159 $params = array_merge($params, $fullid_params);
1160 $where[] = "(d.forum $fullid_sql)";
42fb3c85 1161 }
42fb3c85 1162
dd223096
P
1163 $favjoin = "";
1164 if (in_array('starredonly:on', $searchterms)) {
1165 $usercontext = context_user::instance($USER->id);
1166 $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1167 list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions',
1168 "favourited", "d.id");
1169
1170 $searchterms = array_values(array_diff($searchterms, array('starredonly:on')));
1171 $params = array_merge($params, $favparams);
1172 $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0";
1173 }
1174
6b7de0bb 1175 $selectdiscussion = "(".implode(" OR ", $where).")";
42fb3c85 1176
42fb3c85 1177 $messagesearch = '';
1178 $searchstring = '';
2b63df96 1179
42fb3c85 1180 // Need to concat these back together for parser to work.
1181 foreach($searchterms as $searchterm){
1182 if ($searchstring != '') {
1183 $searchstring .= ' ';
1184 }
1185 $searchstring .= $searchterm;
1186 }
1187
1188 // We need to allow quoted strings for the search. The quotes *should* be stripped
1189 // by the parser, but this should be examined carefully for security implications.
1190 $searchstring = str_replace("\\\"","\"",$searchstring);
1191 $parser = new search_parser();
1192 $lexer = new search_lexer($parser);
1193
1194 if ($lexer->parse($searchstring)) {
1195 $parsearray = $parser->get_parsed_array();
d2ba493c
AH
1196
1197 $tagjoins = '';
1198 $tagfields = [];
e9c46768 1199 $tagfieldcount = 0;
dd223096
P
1200 if ($parsearray) {
1201 foreach ($parsearray as $token) {
1202 if ($token->getType() == TOKEN_TAGS) {
1203 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) {
1204 // Queries can only have a limited number of joins so set a limit sensible users won't exceed.
1205 if ($tagfieldcount > 10) {
1206 continue;
1207 }
1208 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount
e9c46768
AH
1209 ON p.id = ti_$tagfieldcount.itemid
1210 AND ti_$tagfieldcount.component = 'mod_forum'
1211 AND ti_$tagfieldcount.itemtype = 'forum_posts'";
dd223096
P
1212 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid";
1213 $tagfields[] = "t_$tagfieldcount.rawname";
1214 $tagfieldcount++;
1215 }
d2ba493c
AH
1216 }
1217 }
dd223096
P
1218 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject',
1219 'p.userid', 'u.id', 'u.firstname',
1220 'u.lastname', 'p.modified', 'd.forum',
1221 $tagfields);
1222
1223 $params = ($msparams ? array_merge($params, $msparams) : $params);
d2ba493c 1224 }
42fb3c85 1225 }
1226
d2ba493c
AH
1227 $fromsql = "{forum_posts} p
1228 INNER JOIN {forum_discussions} d ON d.id = p.discussion
dd223096 1229 INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin";
42fb3c85 1230
dd223096
P
1231 $selectsql = ($messagesearch ? $messagesearch . " AND " : "").
1232 " p.discussion = d.id
42fb3c85 1233 AND p.userid = u.id
1234 AND $selectdiscussion
1235 $extrasql";
1236
1237 $countsql = "SELECT COUNT(*)
1238 FROM $fromsql
1239 WHERE $selectsql";
1240
5e72715e 1241 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 1242 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
7f094149 1243 $searchsql = "SELECT p.*,
42fb3c85 1244 d.forum,
a327f25e 1245 $allnames,
42fb3c85 1246 u.email,
8ba59d07 1247 u.picture,
ce7382c9 1248 u.imagealt
42fb3c85 1249 FROM $fromsql
1250 WHERE $selectsql
1251 ORDER BY p.modified DESC";
1252
4e445355 1253 $totalcount = $DB->count_records_sql($countsql, $params);
d50704bf 1254
4e445355 1255 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum);
42fb3c85 1256}
1257
0a4ac01b 1258/**
1259 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 1260 *
1261 * @global object
1262 * @global object
1263 * @uses CONTEXT_MODULE
1264 * @return array
0a4ac01b 1265 */
1f48942e 1266function forum_get_user_posts($forumid, $userid) {
4e445355 1267 global $CFG, $DB;
1f48942e 1268
90f4745c 1269 $timedsql = "";
4e445355 1270 $params = array($forumid, $userid);
1271
90f4745c 1272 if (!empty($CFG->forum_enabletimedposts)) {
1273 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 1274 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 1275 $now = time();
4e445355 1276 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1277 $params[] = $now;
1278 $params[] = $now;
6b7de0bb 1279 }
90f4745c 1280 }
1281
5e72715e 1282 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 1283 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
a327f25e 1284 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt
4e445355 1285 FROM {forum} f
1286 JOIN {forum_discussions} d ON d.forum = f.id
1287 JOIN {forum_posts} p ON p.discussion = d.id
1288 JOIN {user} u ON u.id = p.userid
1289 WHERE f.id = ?
1290 AND p.userid = ?
90f4745c 1291 $timedsql
4e445355 1292 ORDER BY p.modified ASC", $params);
1f48942e 1293}
1294
90f4745c 1295/**
1296 * Get all the discussions user participated in
df1ba0f4 1297 *
1298 * @global object
1299 * @global object
1300 * @uses CONTEXT_MODULE
90f4745c 1301 * @param int $forumid
1302 * @param int $userid
df1ba0f4 1303 * @return array Array or false
90f4745c 1304 */
1305function forum_get_user_involved_discussions($forumid, $userid) {
4e445355 1306 global $CFG, $DB;
90f4745c 1307
1308 $timedsql = "";
4e445355 1309 $params = array($forumid, $userid);
90f4745c 1310 if (!empty($CFG->forum_enabletimedposts)) {
1311 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 1312 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 1313 $now = time();
4e445355 1314 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1315 $params[] = $now;
1316 $params[] = $now;
6b7de0bb 1317 }
90f4745c 1318 }
1319
4e445355 1320 return $DB->get_records_sql("SELECT DISTINCT d.*
1321 FROM {forum} f
1322 JOIN {forum_discussions} d ON d.forum = f.id
1323 JOIN {forum_posts} p ON p.discussion = d.id
1324 WHERE f.id = ?
1325 AND p.userid = ?
1326 $timedsql", $params);
90f4745c 1327}
1328
1329/**
1330 * Get all the posts for a user in a forum suitable for forum_print_post
df1ba0f4 1331 *
1332 * @global object
1333 * @global object
90f4745c 1334 * @param int $forumid
1335 * @param int $userid
1336 * @return array of counts or false
1337 */
1338function forum_count_user_posts($forumid, $userid) {
4e445355 1339 global $CFG, $DB;
90f4745c 1340
1341 $timedsql = "";
4e445355 1342 $params = array($forumid, $userid);
90f4745c 1343 if (!empty($CFG->forum_enabletimedposts)) {
1344 $cm = get_coursemodule_from_instance('forum', $forumid);
bf0f06b1 1345 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) {
90f4745c 1346 $now = time();
4e445355 1347 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))";
1348 $params[] = $now;
1349 $params[] = $now;
6b7de0bb 1350 }
90f4745c 1351 }
1352
4e445355 1353 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost
1354 FROM {forum} f
1355 JOIN {forum_discussions} d ON d.forum = f.id
1356 JOIN {forum_posts} p ON p.discussion = d.id
1357 JOIN {user} u ON u.id = p.userid
1358 WHERE f.id = ?
1359 AND p.userid = ?
1360 $timedsql", $params);
90f4745c 1361}
1362
0a4ac01b 1363/**
1364 * Given a log entry, return the forum post details for it.
df1ba0f4 1365 *
1366 * @global object
1367 * @global object
1368 * @param object $log
1369 * @return array|null
0a4ac01b 1370 */
1f48942e 1371function forum_get_post_from_log($log) {
4e445355 1372 global $CFG, $DB;
1f48942e 1373
5e72715e 1374 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 1375 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1f48942e 1376 if ($log->action == "add post") {
1377
a327f25e 1378 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 1379 FROM {forum_discussions} d,
1380 {forum_posts} p,
1381 {forum} f,
1382 {user} u
1383 WHERE p.id = ?
65b0e537 1384 AND d.id = p.discussion
1385 AND p.userid = u.id
8f7dc7f1 1386 AND u.deleted <> '1'
4e445355 1387 AND f.id = d.forum", array($log->info));
1f48942e 1388
1389
1390 } else if ($log->action == "add discussion") {
1391
a327f25e 1392 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture
4e445355 1393 FROM {forum_discussions} d,
1394 {forum_posts} p,
1395 {forum} f,
1396 {user} u
1397 WHERE d.id = ?
65b0e537 1398 AND d.firstpost = p.id
1399 AND p.userid = u.id
8f7dc7f1 1400 AND u.deleted <> '1'
4e445355 1401 AND f.id = d.forum", array($log->info));
1f48942e 1402 }
1403 return NULL;
1404}
1405
0a4ac01b 1406/**
1407 * Given a discussion id, return the first post from the discussion
df1ba0f4 1408 *
1409 * @global object
1410 * @global object
1411 * @param int $dicsussionid
1412 * @return array
0a4ac01b 1413 */
d05956ac 1414function forum_get_firstpost_from_discussion($discussionid) {
4e445355 1415 global $CFG, $DB;
d05956ac 1416
4e445355 1417 return $DB->get_record_sql("SELECT p.*
1418 FROM {forum_discussions} d,
1419 {forum_posts} p
1420 WHERE d.id = ?
1421 AND d.firstpost = p.id ", array($discussionid));
d05956ac 1422}
1423
0a4ac01b 1424/**
90f4745c 1425 * Returns an array of counts of replies to each discussion
df1ba0f4 1426 *
bc4c7337
AN
1427 * @param int $forumid
1428 * @param string $forumsort
1429 * @param int $limit
1430 * @param int $page
1431 * @param int $perpage
1432 * @param boolean $canseeprivatereplies Whether the current user can see private replies.
1433 * @return array
0a4ac01b 1434 */
bc4c7337
AN
1435function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0,
1436 $canseeprivatereplies = false) {
1437 global $CFG, $DB, $USER;
1f48942e 1438
90f4745c 1439 if ($limit > 0) {
1440 $limitfrom = 0;
1441 $limitnum = $limit;
1442 } else if ($page != -1) {
1443 $limitfrom = $page*$perpage;
1444 $limitnum = $perpage;
1445 } else {
1446 $limitfrom = 0;
1447 $limitnum = 0;
1448 }
1449
1450 if ($forumsort == "") {
1451 $orderby = "";
1452 $groupby = "";
1453
1454 } else {
1455 $orderby = "ORDER BY $forumsort";
1456 $groupby = ", ".strtolower($forumsort);
1457 $groupby = str_replace('desc', '', $groupby);
1458 $groupby = str_replace('asc', '', $groupby);
1459 }
1460
bc4c7337
AN
1461 $params = ['forumid' => $forumid];
1462
1463 if (!$canseeprivatereplies) {
1464 $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)';
1465 $params['currentuser1'] = $USER->id;
1466 $params['currentuser2'] = $USER->id;
1467 } else {
1468 $privatewhere = '';
1469 }
1470
bfeb10b7 1471 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") {
1472 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid
4e445355 1473 FROM {forum_posts} p
1474 JOIN {forum_discussions} d ON p.discussion = d.id
bc4c7337
AN
1475 WHERE p.parent > 0 AND d.forum = :forumid
1476 $privatewhere
bfeb10b7 1477 GROUP BY p.discussion";
bc4c7337 1478 return $DB->get_records_sql($sql, $params);
bfeb10b7 1479
90f4745c 1480 } else {
bfeb10b7 1481 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid
4e445355 1482 FROM {forum_posts} p
1483 JOIN {forum_discussions} d ON p.discussion = d.id
bc4c7337
AN
1484 WHERE d.forum = :forumid
1485 $privatewhere
38ec3fb0 1486 GROUP BY p.discussion $groupby $orderby";
bc4c7337 1487 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
90f4745c 1488 }
1489}
1490
df1ba0f4 1491/**
1492 * @global object
1493 * @global object
1494 * @global object
1495 * @staticvar array $cache
1496 * @param object $forum
1497 * @param object $cm
1498 * @param object $course
1499 * @return mixed
1500 */
90f4745c 1501function forum_count_discussions($forum, $cm, $course) {
4e445355 1502 global $CFG, $DB, $USER;
90f4745c 1503
1504 static $cache = array();
1505
098f4337 1506 $now = floor(time() / 60) * 60; // DB Cache Friendly.
90f4745c 1507
4e445355 1508 $params = array($course->id);
1509
90f4745c 1510 if (!isset($cache[$course->id])) {
1511 if (!empty($CFG->forum_enabletimedposts)) {
4e445355 1512 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)";
1513 $params[] = $now;
1514 $params[] = $now;
90f4745c 1515 } else {
1516 $timedsql = "";
1517 }
1518
1519 $sql = "SELECT f.id, COUNT(d.id) as dcount
4e445355 1520 FROM {forum} f
1521 JOIN {forum_discussions} d ON d.forum = f.id
1522 WHERE f.course = ?
90f4745c 1523 $timedsql
1524 GROUP BY f.id";
a48e8c4b 1525
4e445355 1526 if ($counts = $DB->get_records_sql($sql, $params)) {
90f4745c 1527 foreach ($counts as $count) {
1528 $counts[$count->id] = $count->dcount;
1529 }
1530 $cache[$course->id] = $counts;
1531 } else {
1532 $cache[$course->id] = array();
1533 }
a48e8c4b 1534 }
90f4745c 1535
1536 if (empty($cache[$course->id][$forum->id])) {
1537 return 0;
a48e8c4b 1538 }
90f4745c 1539
1540 $groupmode = groups_get_activity_groupmode($cm, $course);
1541
1542 if ($groupmode != SEPARATEGROUPS) {
1543 return $cache[$course->id][$forum->id];
1f48942e 1544 }
90f4745c 1545
bf0f06b1 1546 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) {
90f4745c 1547 return $cache[$course->id][$forum->id];
1548 }
1549
1550 require_once($CFG->dirroot.'/course/lib.php');
1551
f20edd52 1552 $modinfo = get_fast_modinfo($course);
90f4745c 1553
2c1bbbc5 1554 $mygroups = $modinfo->get_groups($cm->groupingid);
90f4745c 1555
1556 // add all groups posts
2c1bbbc5 1557 $mygroups[-1] = -1;
4e445355 1558
1559 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups);
1560 $params[] = $forum->id;
90f4745c 1561
1562 if (!empty($CFG->forum_enabletimedposts)) {
1563 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)";
4e445355 1564 $params[] = $now;
1565 $params[] = $now;
90f4745c 1566 } else {
1567 $timedsql = "";
1568 }
1569
1570 $sql = "SELECT COUNT(d.id)
4e445355 1571 FROM {forum_discussions} d
342650a7 1572 WHERE d.groupid $mygroups_sql AND d.forum = ?
90f4745c 1573 $timedsql";
1574
4e445355 1575 return $DB->get_field_sql($sql, $params);
1f48942e 1576}
1577
0a4ac01b 1578/**
1579 * Get all discussions in a forum
df1ba0f4 1580 *
1581 * @global object
1582 * @global object
1583 * @global object
1584 * @uses CONTEXT_MODULE
1585 * @uses VISIBLEGROUPS
1586 * @param object $cm
1587 * @param string $forumsort
1588 * @param bool $fullpost
1589 * @param int $unused
1590 * @param int $limit
1591 * @param bool $userlastmodified
1592 * @param int $page
1593 * @param int $perpage
4f3a2d21
JL
1594 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
1595 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
65b2669d 1596 * @param int $updatedsince retrieve only discussions updated since the given time
df1ba0f4 1597 * @return array
0a4ac01b 1598 */
1e366657 1599function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1,
02a73d76 1600 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1,
65b2669d 1601 $updatedsince = 0) {
4e445355 1602 global $CFG, $DB, $USER;
0fcac008 1603
3d284127 1604 $timelimit = '';
1605
098f4337 1606 $now = floor(time() / 60) * 60;
4e445355 1607 $params = array($cm->instance);
90f4745c 1608
bf0f06b1 1609 $modcontext = context_module::instance($cm->id);
2b63df96 1610
4436a63b 1611 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions
1612 return array();
1613 }
1614
1615 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts
2b63df96 1616
0468976c 1617 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 1618 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
1619 $params[] = $now;
1620 $params[] = $now;
90f4745c 1621 if (isloggedin()) {
4e445355 1622 $timelimit .= " OR d.userid = ?";
1623 $params[] = $USER->id;
3d284127 1624 }
90f4745c 1625 $timelimit .= ")";
fbc21e82 1626 }
fbc21e82 1627 }
1f48942e 1628
90f4745c 1629 if ($limit > 0) {
1630 $limitfrom = 0;
1631 $limitnum = $limit;
1632 } else if ($page != -1) {
1633 $limitfrom = $page*$perpage;
1634 $limitnum = $perpage;
1635 } else {
1636 $limitfrom = 0;
1637 $limitnum = 0;
90ec387a 1638 }
8f0cd6ef 1639
90f4745c 1640 $groupmode = groups_get_activity_groupmode($cm);
353228d8 1641
fffa8b35 1642 if ($groupmode) {
4f3a2d21 1643
fffa8b35 1644 if (empty($modcontext)) {
bf0f06b1 1645 $modcontext = context_module::instance($cm->id);
fffa8b35 1646 }
1647
4f3a2d21
JL
1648 // Special case, we received a groupid to override currentgroup.
1649 if ($groupid > 0) {
1650 $course = get_course($cm->course);
1651 if (!groups_group_visible($groupid, $course, $cm)) {
1652 // User doesn't belong to this group, return nothing.
1653 return array();
1654 }
1655 $currentgroup = $groupid;
1656 } else if ($groupid === -1) {
1657 $currentgroup = groups_get_activity_group($cm);
1658 } else {
1659 // Get discussions for all groups current user can see.
1660 $currentgroup = null;
1661 }
1662
fffa8b35 1663 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1664 if ($currentgroup) {
4e445355 1665 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1666 $params[] = $currentgroup;
fffa8b35 1667 } else {
1668 $groupselect = "";
1669 }
1670
1671 } else {
4f3a2d21
JL
1672 // Separate groups.
1673
1674 // Get discussions for all groups current user can see.
1675 if ($currentgroup === null) {
1676 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
1677 if (empty($mygroups)) {
1678 $groupselect = "AND d.groupid = -1";
1679 } else {
1680 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
1681 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)";
1682 $params = array_merge($params, $inparamsgroups);
1683 }
1684 } else if ($currentgroup) {
4e445355 1685 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
1686 $params[] = $currentgroup;
fffa8b35 1687 } else {
1688 $groupselect = "AND d.groupid = -1";
1689 }
1690 }
353228d8 1691 } else {
02509fe6 1692 $groupselect = "";
1693 }
29507631 1694 if (empty($forumsort)) {
1e366657 1695 $forumsort = forum_get_default_sort_order();
29507631 1696 }
2ab968e9 1697 if (empty($fullpost)) {
94df729b 1698 $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created";
2ab968e9 1699 } else {
1700 $postdata = "p.*";
1701 }
9197e147 1702
5e72715e 1703 $userfieldsapi = \core_user\fields::for_name();
558cc1b8 1704
13597d01 1705 if (empty($userlastmodified)) { // We don't need to know this
fffa8b35 1706 $umfields = "";
1707 $umtable = "";
13597d01 1708 } else {
558cc1b8 1709 $umfields = $userfieldsapi->get_sql('um', false, 'um')->selects . ', um.email AS umemail, um.picture AS umpicture,
d85bedf7 1710 um.imagealt AS umimagealt';
4e445355 1711 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
90f4745c 1712 }
1713
65b2669d
JL
1714 $updatedsincesql = '';
1715 if (!empty($updatedsince)) {
1716 $updatedsincesql = 'AND d.timemodified > ?';
1717 $params[] = $updatedsince;
1718 }
2893812e 1719
8666dfec 1720 $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," .
bdb4a87d 1721 " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked";
65b2669d 1722
558cc1b8 1723 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
2f6f3397 1724 $sql = "SELECT $postdata, $discussionfields,
424920f8 1725 $allnames, u.email, u.picture, u.imagealt $umfields
4e445355 1726 FROM {forum_discussions} d
1727 JOIN {forum_posts} p ON p.discussion = d.id
1728 JOIN {user} u ON p.userid = u.id
90f4745c 1729 $umtable
4e445355 1730 WHERE d.forum = ? AND p.parent = 0
65b2669d 1731 $timelimit $groupselect $updatedsincesql
5f219cf1 1732 ORDER BY $forumsort, d.id DESC";
65b2669d 1733
4e445355 1734 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
90f4745c 1735}
1736
8d3a5ba1
FM
1737/**
1738 * Gets the neighbours (previous and next) of a discussion.
1739 *
5f219cf1
BK
1740 * The calculation is based on the timemodified when time modified or time created is identical
1741 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion.
8d3a5ba1 1742 *
9e381efd
DM
1743 * For blog-style forums, the calculation is based on the original creation time of the
1744 * blog post.
1745 *
8d3a5ba1
FM
1746 * Please note that this does not check whether or not the discussion passed is accessible
1747 * by the user, it simply uses it as a reference to find the neighbours. On the other hand,
1748 * the returned neighbours are checked and are accessible to the current user.
1749 *
1750 * @param object $cm The CM record.
1751 * @param object $discussion The discussion record.
9e381efd 1752 * @param object $forum The forum instance record.
8d3a5ba1
FM
1753 * @return array That always contains the keys 'prev' and 'next'. When there is a result
1754 * they contain the record with minimal information such as 'id' and 'name'.
1755 * When the neighbour is not found the value is false.
1756 */
9e381efd 1757function forum_get_discussion_neighbours($cm, $discussion, $forum) {
8d3a5ba1
FM
1758 global $CFG, $DB, $USER;
1759
9e381efd 1760 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) {
8d3a5ba1
FM
1761 throw new coding_exception('Discussion is not part of the same forum.');
1762 }
1763
1764 $neighbours = array('prev' => false, 'next' => false);
098f4337 1765 $now = floor(time() / 60) * 60;
8d3a5ba1
FM
1766 $params = array();
1767
1768 $modcontext = context_module::instance($cm->id);
1769 $groupmode = groups_get_activity_groupmode($cm);
1770 $currentgroup = groups_get_activity_group($cm);
1771
1772 // Users must fulfill timed posts.
1773 $timelimit = '';
1774 if (!empty($CFG->forum_enabletimedposts)) {
1775 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
1776 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))';
1777 $params['tltimestart'] = $now;
1778 $params['tltimeend'] = $now;
1779 if (isloggedin()) {
1780 $timelimit .= ' OR d.userid = :tluserid';
1781 $params['tluserid'] = $USER->id;
1782 }
1783 $timelimit .= ')';
1784 }
1785 }
1786
1787 // Limiting to posts accessible according to groups.
1788 $groupselect = '';
1789 if ($groupmode) {
1790 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) {
1791 if ($currentgroup) {
1792 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1793 $params['groupid'] = $currentgroup;
1794 }
1795 } else {
1796 if ($currentgroup) {
1797 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)';
1798 $params['groupid'] = $currentgroup;
1799 } else {
1800 $groupselect = 'AND d.groupid = -1';
1801 }
1802 }
1803 }
1804
5f219cf1
BK
1805 $params['forumid'] = $cm->instance;
1806 $params['discid1'] = $discussion->id;
1807 $params['discid2'] = $discussion->id;
1808 $params['discid3'] = $discussion->id;
1809 $params['discid4'] = $discussion->id;
1810 $params['disctimecompare1'] = $discussion->timemodified;
1811 $params['disctimecompare2'] = $discussion->timemodified;
1812 $params['pinnedstate1'] = (int) $discussion->pinned;
1813 $params['pinnedstate2'] = (int) $discussion->pinned;
1814 $params['pinnedstate3'] = (int) $discussion->pinned;
1815 $params['pinnedstate4'] = (int) $discussion->pinned;
9e381efd 1816
5f219cf1
BK
1817 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend
1818 FROM {forum_discussions} d
1819 JOIN {forum_posts} p ON d.firstpost = p.id
1820 WHERE d.forum = :forumid
1821 AND d.id <> :discid1
1822 $timelimit
1823 $groupselect";
1824 $comparefield = "d.timemodified";
1825 $comparevalue = ":disctimecompare1";
1826 $comparevalue2 = ":disctimecompare2";
1827 if (!empty($CFG->forum_enabletimedposts)) {
1828 // Here we need to take into account the release time (timestart)
1829 // if one is set, of the neighbouring posts and compare it to the
1830 // timestart or timemodified of *this* post depending on if the
1831 // release date of this post is in the future or not.
1832 // This stops discussions that appear later because of the
1833 // timestart value from being buried under discussions that were
1834 // made afterwards.
1835 $comparefield = "CASE WHEN d.timemodified < d.timestart
1836 THEN d.timestart ELSE d.timemodified END";
1837 if ($discussion->timemodified < $discussion->timestart) {
1838 // Normally we would just use the timemodified for sorting
1839 // discussion posts. However, when timed discussions are enabled,
1840 // then posts need to be sorted base on the later of timemodified
1841 // or the release date of the post (timestart).
1842 $params['disctimecompare1'] = $discussion->timestart;
1843 $params['disctimecompare2'] = $discussion->timestart;
1844 }
1845 }
1846 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false);
1847 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false);
9e381efd 1848
5f219cf1
BK
1849 if ($forum->type === 'blog') {
1850 $subselect = "SELECT pp.created
1851 FROM {forum_discussions} dd
1852 JOIN {forum_posts} pp ON dd.firstpost = pp.id ";
8d3a5ba1 1853
5f219cf1
BK
1854 $subselectwhere1 = " WHERE dd.id = :discid3";
1855 $subselectwhere2 = " WHERE dd.id = :discid4";
8d3a5ba1 1856
5f219cf1 1857 $comparefield = "p.created";
9e381efd 1858
5f219cf1
BK
1859 $sub1 = $subselect.$subselectwhere1;
1860 $comparevalue = "($sub1)";
9e381efd 1861
5f219cf1
BK
1862 $sub2 = $subselect.$subselectwhere2;
1863 $comparevalue2 = "($sub2)";
8d3a5ba1 1864
5f219cf1
BK
1865 $orderbydesc = "d.pinned, p.created DESC";
1866 $orderbyasc = "d.pinned, p.created ASC";
1867 }
1e366657 1868
5f219cf1
BK
1869 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned)
1870 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2)
1871 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2))
1872 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC";
9e381efd 1873
5f219cf1
BK
1874 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned)
1875 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2)
1876 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2))
1877 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC";
8d3a5ba1 1878
5f219cf1
BK
1879 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE);
1880 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE);
8d3a5ba1
FM
1881 return $neighbours;
1882}
1883
1e366657
AO
1884/**
1885 * Get the sql to use in the ORDER BY clause for forum discussions.
1886 *
1887 * This has the ordering take timed discussion windows into account.
1888 *
1889 * @param bool $desc True for DESC, False for ASC.
1890 * @param string $compare The field in the SQL to compare to normally sort by.
1891 * @param string $prefix The prefix being used for the discussion table.
5f219cf1 1892 * @param bool $pinned sort pinned posts to the top
1e366657
AO
1893 * @return string
1894 */
5f219cf1 1895function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) {
1e366657
AO
1896 global $CFG;
1897
1898 if (!empty($prefix)) {
1899 $prefix .= '.';
1900 }
1901
1902 $dir = $desc ? 'DESC' : 'ASC';
1903
5f219cf1
BK
1904 if ($pinned == true) {
1905 $pinned = "{$prefix}pinned DESC,";
1906 } else {
1907 $pinned = '';
1908 }
1909
1e366657
AO
1910 $sort = "{$prefix}timemodified";
1911 if (!empty($CFG->forum_enabletimedposts)) {
1912 $sort = "CASE WHEN {$compare} < {$prefix}timestart
1913 THEN {$prefix}timestart
1914 ELSE {$compare}
1915 END";
1916 }
5f219cf1 1917 return "$pinned $sort $dir";
1e366657
AO
1918}
1919
df1ba0f4 1920/**
1921 *
1922 * @global object
1923 * @global object
1924 * @global object
1925 * @uses CONTEXT_MODULE
1926 * @uses VISIBLEGROUPS
1927 * @param object $cm
1928 * @return array
1929 */
bfeb10b7 1930function forum_get_discussions_unread($cm) {
4e445355 1931 global $CFG, $DB, $USER;
90f4745c 1932
098f4337 1933 $now = floor(time() / 60) * 60;
ee151230 1934 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60);
35716b86 1935
ee151230 1936 $params = array();
90f4745c 1937 $groupmode = groups_get_activity_groupmode($cm);
1938 $currentgroup = groups_get_activity_group($cm);
1939
1940 if ($groupmode) {
bf0f06b1 1941 $modcontext = context_module::instance($cm->id);
90f4745c 1942
1943 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
1944 if ($currentgroup) {
ee151230
AD
1945 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1946 $params['currentgroup'] = $currentgroup;
90f4745c 1947 } else {
1948 $groupselect = "";
1949 }
1950
1951 } else {
ee151230 1952 //separate groups without access all
90f4745c 1953 if ($currentgroup) {
ee151230
AD
1954 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)";
1955 $params['currentgroup'] = $currentgroup;
90f4745c 1956 } else {
1957 $groupselect = "AND d.groupid = -1";
1958 }
1959 }
1960 } else {
1961 $groupselect = "";
13597d01 1962 }
1963
90f4745c 1964 if (!empty($CFG->forum_enabletimedposts)) {
ee151230
AD
1965 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)";
1966 $params['now1'] = $now;
1967 $params['now2'] = $now;
90f4745c 1968 } else {
1969 $timedsql = "";
1970 }
1971
1972 $sql = "SELECT d.id, COUNT(p.id) AS unread
4e445355 1973 FROM {forum_discussions} d
1974 JOIN {forum_posts} p ON p.discussion = d.id
1975 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id)
90f4745c 1976 WHERE d.forum = {$cm->instance}
ee151230 1977 AND p.modified >= :cutoffdate AND r.id is NULL
90f4745c 1978 $groupselect
4e445355 1979 $timedsql
bfeb10b7 1980 GROUP BY d.id";
ee151230
AD
1981 $params['cutoffdate'] = $cutoffdate;
1982
4e445355 1983 if ($unreads = $DB->get_records_sql($sql, $params)) {
90f4745c 1984 foreach ($unreads as $unread) {
1985 $unreads[$unread->id] = $unread->unread;
1986 }
1987 return $unreads;
1988 } else {
1989 return array();
1990 }
1f48942e 1991}
1992
df1ba0f4 1993/**
1994 * @global object
1995 * @global object
1996 * @global object
1997 * @uses CONEXT_MODULE
1998 * @uses VISIBLEGROUPS
1999 * @param object $cm
2000 * @return array
2001 */
90f4745c 2002function forum_get_discussions_count($cm) {
4e445355 2003 global $CFG, $DB, $USER;
90f4745c 2004
098f4337 2005 $now = floor(time() / 60) * 60;
4e445355 2006 $params = array($cm->instance);
90f4745c 2007 $groupmode = groups_get_activity_groupmode($cm);
2008 $currentgroup = groups_get_activity_group($cm);
2009
2010 if ($groupmode) {
bf0f06b1 2011 $modcontext = context_module::instance($cm->id);
90f4745c 2012
2013 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
2014 if ($currentgroup) {
4e445355 2015 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2016 $params[] = $currentgroup;
90f4745c 2017 } else {
2018 $groupselect = "";
2019 }
2020
2021 } else {
2022 //seprate groups without access all
2023 if ($currentgroup) {
4e445355 2024 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
2025 $params[] = $currentgroup;
90f4745c 2026 } else {
2027 $groupselect = "AND d.groupid = -1";
2028 }
2029 }
2030 } else {
2031 $groupselect = "";
2032 }
2033
90f4745c 2034 $timelimit = "";
2035
2036 if (!empty($CFG->forum_enabletimedposts)) {
2037
bf0f06b1 2038 $modcontext = context_module::instance($cm->id);
90f4745c 2039
2040 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
4e445355 2041 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
2042 $params[] = $now;
2043 $params[] = $now;
90f4745c 2044 if (isloggedin()) {
4e445355 2045 $timelimit .= " OR d.userid = ?";
2046 $params[] = $USER->id;
90f4745c 2047 }
2048 $timelimit .= ")";
2049 }
2050 }
2051
2052 $sql = "SELECT COUNT(d.id)
4e445355 2053 FROM {forum_discussions} d
2054 JOIN {forum_posts} p ON p.discussion = d.id
2055 WHERE d.forum = ? AND p.parent = 0
2056 $groupselect $timelimit";
90f4745c 2057
4e445355 2058 return $DB->get_field_sql($sql, $params);
90f4745c 2059}
1f48942e 2060
2061
0a4ac01b 2062// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 2063
2064
df1ba0f4 2065/**
2066 * @global object
2067 * @global object
2068 * @param int $courseid
2069 * @param string $type
2070 */
11b0c469 2071function forum_get_course_forum($courseid, $type) {
2072// How to set up special 1-per-course forums
c112bc60 2073 global $CFG, $DB, $OUTPUT, $USER;
a6fcdf98 2074
4e445355 2075 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) {
65b0e537 2076 // There should always only be ONE, but with the right combination of
29cbd93a 2077 // errors there might be more. In this case, just return the oldest one (lowest ID).
2078 foreach ($forums as $forum) {
2079 return $forum; // ie the first one
11b0c469 2080 }
8daaf761 2081 }
e6874d9f 2082
8daaf761 2083 // Doesn't exist, so create one now.
b85b25eb 2084 $forum = new stdClass();
8daaf761 2085 $forum->course = $courseid;
2086 $forum->type = "$type";
c112bc60
ARN
2087 if (!empty($USER->htmleditor)) {
2088 $forum->introformat = $USER->htmleditor;
2089 }
8daaf761 2090 switch ($forum->type) {
2091 case "news":
294ce987 2092 $forum->name = get_string("namenews", "forum");
2093 $forum->intro = get_string("intronews", "forum");
490476a1 2094 $forum->introformat = FORMAT_HTML;
906fef94 2095 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 2096 $forum->assessed = 0;
709f0ec8 2097 if ($courseid == SITEID) {
2098 $forum->name = get_string("sitenews");
2099 $forum->forcesubscribe = 0;
8f0cd6ef 2100 }
8daaf761 2101 break;
2102 case "social":
294ce987 2103 $forum->name = get_string("namesocial", "forum");
2104 $forum->intro = get_string("introsocial", "forum");
490476a1 2105 $forum->introformat = FORMAT_HTML;
8daaf761 2106 $forum->assessed = 0;
2107 $forum->forcesubscribe = 0;
2108 break;
1c7b8b93
NC
2109 case "blog":
2110 $forum->name = get_string('blogforum', 'forum');
2111 $forum->intro = get_string('introblog', 'forum');
490476a1 2112 $forum->introformat = FORMAT_HTML;
1c7b8b93
NC
2113 $forum->assessed = 0;
2114 $forum->forcesubscribe = 0;
2115 break;
8daaf761 2116 default:
9146b979 2117 echo $OUTPUT->notification("That forum type doesn't exist!");
8daaf761 2118 return false;
2119 break;
2120 }
2121
2122 $forum->timemodified = time();
4e445355 2123 $forum->id = $DB->insert_record("forum", $forum);
8daaf761 2124
4e445355 2125 if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
9146b979 2126 echo $OUTPUT->notification("Could not find forum module!!");
e1b5643f 2127 return false;
82aa0e8d 2128 }
39790bd8 2129 $mod = new stdClass();
e1b5643f 2130 $mod->course = $courseid;
2131 $mod->module = $module->id;
2132 $mod->instance = $forum->id;
2133 $mod->section = 0;
722e6ba9
MG
2134 include_once("$CFG->dirroot/course/lib.php");
2135 if (! $mod->coursemodule = add_course_module($mod) ) {
11cd754e 2136 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
e1b5643f 2137 return false;
2138 }
722e6ba9 2139 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0);
4e445355 2140 return $DB->get_record("forum", array("id" => "$forum->id"));
82aa0e8d 2141}
2142
d251b259
AD
2143/**
2144 * Return rating related permissions
2b04c41c 2145 *
d251b259
AD
2146 * @param string $options the context id
2147 * @return array an associative array of the user's rating permissions
2148 */
2b04c41c 2149function forum_rating_permissions($contextid, $component, $ratingarea) {
d197ea43 2150 $context = context::instance_by_id($contextid, MUST_EXIST);
2b04c41c
SH
2151 if ($component != 'mod_forum' || $ratingarea != 'post') {
2152 // We don't know about this component/ratingarea so just return null to get the
2153 // default restrictive permissions.
d251b259 2154 return null;
d251b259 2155 }
2b04c41c
SH
2156 return array(
2157 'view' => has_capability('mod/forum:viewrating', $context),
2158 'viewany' => has_capability('mod/forum:viewanyrating', $context),
2159 'viewall' => has_capability('mod/forum:viewallratings', $context),
2160 'rate' => has_capability('mod/forum:rate', $context)
2161 );
d251b259
AD
2162}
2163
aeafd436 2164/**
2c2ff8d5
AD
2165 * Validates a submitted rating
2166 * @param array $params submitted data
2167 * context => object the context in which the rated items exists [required]
2b04c41c
SH
2168 * component => The component for this module - should always be mod_forum [required]
2169 * ratingarea => object the context in which the rated items exists [required]
db4754e9 2170 *
2c2ff8d5
AD
2171 * itemid => int the ID of the object being rated [required]
2172 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
2173 * rating => int the submitted rating [required]
2174 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
2175 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
778361c3 2176 * @return boolean true if the rating is valid. Will throw rating_exception if not
aeafd436 2177 */
778361c3 2178function forum_rating_validate($params) {
2c2ff8d5
AD
2179 global $DB, $USER;
2180
2b04c41c
SH
2181 // Check the component is mod_forum
2182 if ($params['component'] != 'mod_forum') {
2183 throw new rating_exception('invalidcomponent');
2c2ff8d5
AD
2184 }
2185
2b04c41c
SH
2186 // Check the ratingarea is post (the only rating area in forum)
2187 if ($params['ratingarea'] != 'post') {
2188 throw new rating_exception('invalidratingarea');
2c2ff8d5
AD
2189 }
2190
2b04c41c
SH
2191 // Check the rateduserid is not the current user .. you can't rate your own posts
2192 if ($params['rateduserid'] == $USER->id) {
778361c3
AD
2193 throw new rating_exception('nopermissiontorate');
2194 }
2195
2b04c41c
SH
2196 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post
2197 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST);
2198 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2199 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
74df2951 2200 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2b04c41c 2201 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
bf0f06b1 2202 $context = context_module::instance($cm->id);
2b04c41c
SH
2203
2204 // Make sure the context provided is the context of the forum
2205 if ($context->id != $params['context']->id) {
2206 throw new rating_exception('invalidcontext');
2207 }
f2e72593 2208
2b04c41c
SH
2209 if ($forum->scale != $params['scaleid']) {
2210 //the scale being submitted doesnt match the one in the database
2211 throw new rating_exception('invalidscaleid');
2c2ff8d5
AD
2212 }
2213
2b04c41c
SH
2214 // check the item we're rating was created in the assessable time window
2215 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) {
2216 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) {
2217 throw new rating_exception('notavailable');
2218 }
2219 }
f2e72593 2220
6ac149dc 2221 //check that the submitted rating is valid for the scale
5693d56c
EL
2222
2223 // lower limit
2224 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
6ac149dc 2225 throw new rating_exception('invalidnum');
5693d56c
EL
2226 }
2227
2228 // upper limit
c4cee99c 2229 if ($forum->scale < 0) {
6ac149dc 2230 //its a custom scale
2b04c41c 2231 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale));
6ac149dc
AD
2232 if ($scalerecord) {
2233 $scalearray = explode(',', $scalerecord->scale);
2234 if ($params['rating'] > count($scalearray)) {
2235 throw new rating_exception('invalidnum');
2236 }
2237 } else {
2238 throw new rating_exception('invalidscaleid');
2239 }
2b04c41c 2240 } else if ($params['rating'] > $forum->scale) {
6ac149dc
AD
2241 //if its numeric and submitted rating is above maximum
2242 throw new rating_exception('invalidnum');
2243 }
2244
2c2ff8d5 2245 // Make sure groups allow this user to see the item they're rating
2b04c41c
SH
2246 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
2247 if (!groups_group_exists($discussion->groupid)) { // Can't find group
778361c3 2248 throw new rating_exception('cannotfindgroup');//something is wrong
2c2ff8d5
AD
2249 }
2250
2b04c41c 2251 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2c2ff8d5 2252 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
778361c3 2253 throw new rating_exception('notmemberofgroup');
2c2ff8d5
AD
2254 }
2255 }
2256
2b04c41c
SH
2257 // perform some final capability checks
2258 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
778361c3 2259 throw new rating_exception('nopermissiontorate');
2c2ff8d5
AD
2260 }
2261
2262 return true;
aeafd436
AD
2263}
2264
731c2712
AA
2265/**
2266 * Can the current user see ratings for a given itemid?
2267 *
2268 * @param array $params submitted data
2269 * contextid => int contextid [required]
2270 * component => The component for this module - should always be mod_forum [required]
2271 * ratingarea => object the context in which the rated items exists [required]
2272 * itemid => int the ID of the object being rated [required]
2273 * scaleid => int scale id [optional]
2274 * @return bool
2275 * @throws coding_exception
2276 * @throws rating_exception
2277 */
2278function mod_forum_rating_can_see_item_ratings($params) {
2279 global $DB, $USER;
2280
2281 // Check the component is mod_forum.
2282 if (!isset($params['component']) || $params['component'] != 'mod_forum') {
2283 throw new rating_exception('invalidcomponent');
2284 }
2285
2286 // Check the ratingarea is post (the only rating area in forum).
2287 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') {
2288 throw new rating_exception('invalidratingarea');
2289 }
2290
2291 if (!isset($params['itemid'])) {
2292 throw new rating_exception('invaliditemid');
2293 }
2294
2295 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST);
2296 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST);
2297 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
2298 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
2299 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST);
2300
2301 // Perform some final capability checks.
2302 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) {
2303 return false;
2304 }
3e95e09b 2305
731c2712
AA
2306 return true;
2307}
42fb3c85 2308
eaf50aef 2309/**
0a4ac01b 2310 * This function prints the overview of a discussion in the forum listing.
2311 * It needs some discussion information and some post information, these
2312 * happen to be combined for efficiency in the $post parameter by the function
2313 * that calls this one: forum_print_latest_discussions()
2314 *
df1ba0f4 2315 * @global object
2316 * @global object
0a4ac01b 2317 * @param object $post The post object (passed by reference for speed).
2318 * @param object $forum The forum object.
2319 * @param int $group Current group.
2320 * @param string $datestring Format to use for the dates.
2321 * @param boolean $cantrack Is tracking enabled for this forum.
2322 * @param boolean $forumtracked Is the user tracking this forum.
2323 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course
05f1455b 2324 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum
0a4ac01b 2325 */
05f1455b
AO
2326function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "",
2327 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null,
2328 $canviewhiddentimedposts = false) {
43921b8a 2329
05f1455b 2330 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE;
3335f6fb 2331
f51e8d7e 2332 static $rowcount;
5733262d 2333 static $strmarkalldread;
f51e8d7e 2334
2c894bb9 2335 if (empty($modcontext)) {
2336 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
12e57b92 2337 print_error('invalidcoursemodule');
2c894bb9 2338 }
bf0f06b1 2339 $modcontext = context_module::instance($cm->id);
951e1073 2340 }
951e1073 2341
f51e8d7e 2342 if (!isset($rowcount)) {
2343 $rowcount = 0;
5733262d 2344 $strmarkalldread = get_string('markalldread', 'forum');
f51e8d7e 2345 } else {
2346 $rowcount = ($rowcount + 1) % 2;
2347 }
2348
17dc3f3c 2349 $post->subject = format_string($post->subject,true);
436a7cae 2350
26cee437 2351 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
05f1455b
AO
2352 $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend);
2353 $timedoutsidewindow = '';
2354 if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) {
2355 $timedoutsidewindow = ' dimmed_text';
2356 }
2357
f51e8d7e 2358 echo "\n\n";
05f1455b 2359 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">';
3335f6fb 2360
87b007b4
CF
2361 $topicclass = 'topic starter';
2362 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2363 $topicclass .= ' pinned';
2364 }
2365 echo '<td class="'.$topicclass.'">';
5f219cf1
BK
2366 if (FORUM_DISCUSSION_PINNED == $post->pinned) {
2367 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum');
2368 }
05f1455b
AO
2369 $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts;
2370 if ($timeddiscussion && $canalwaysseetimedpost) {
2371 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow));
2372 }
2373
f51e8d7e 2374 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
29507631 2375 echo "</td>\n";
2376
2377 // Picture
39790bd8 2378 $postuser = new stdClass();
5e72715e 2379 $postuserfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
5b1944bb 2380 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields);
e351bed5 2381 $postuser->id = $post->userid;
0433d36d 2382 echo '<td class="author">';
b1a74e40 2383 echo '<div class="media">';
5db1ce53 2384 echo '<span class="float-left">';
812dbaf7 2385 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course));
0433d36d 2386 echo '</span>';
29507631 2387 // User name
b1a74e40 2388 echo '<div class="media-body">';
26cee437 2389 $fullname = fullname($postuser, $canviewfullnames);
f51e8d7e 2390 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
b1a74e40
BB
2391 echo '</div>';
2392 echo '</div>';
29507631 2393 echo "</td>\n";
2394
3a68fbbb 2395 // Group picture
425b4f1a 2396 if ($group !== -1) { // Groups are active - group is a group data object or NULL
f51e8d7e 2397 echo '<td class="picture group">';
3aed37ee 2398 if (!empty($group->picture)) {
800fa051
DM
2399 if ($canviewparticipants && $COURSE->groupmode) {
2400 $picturelink = true;
2401 } else {
2402 $picturelink = false;
2403 }
2404 print_group_picture($group, $forum->course, false, false, $picturelink);
3a68fbbb 2405 } else if (isset($group->id)) {
c980dd12 2406 if ($canviewparticipants && $COURSE->groupmode) {
18d6ef01 2407 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
2408 } else {
2409 echo $group->name;
2410 }
3a68fbbb 2411 }
2412 echo "</td>\n";
2413 }
2414
f0da6b85 2415 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies
f51e8d7e 2416 echo '<td class="replies">';
2417 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2418 echo $post->replies.'</a>';
a796d0b8 2419 echo "</td>\n";
e3ff14ca 2420
eaf50aef 2421 if ($cantrack) {
f51e8d7e 2422 echo '<td class="replies">';
eaf50aef 2423 if ($forumtracked) {
2424 if ($post->unread > 0) {
2425 echo '<span class="unread">';
2426 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2427 echo $post->unread;
2428 echo '</a>';
c39748f4 2429 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2e19ca18
RW
2430 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;return=/mod/forum/view.php&amp;sesskey=' .
2431 sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>';
eaf50aef 2432 echo '</span>';
2433 } else {
2434 echo '<span class="read">';
eaf50aef 2435 echo $post->unread;
eaf50aef 2436 echo '</span>';
2437 }
f51e8d7e 2438 } else {
343af274 2439 echo '<span class="read">';
eaf50aef 2440 echo '-';
343af274 2441 echo '</span>';
3a68fbbb 2442 }
f37da850 2443 echo "</td>\n";
2444 }
a796d0b8 2445 }
3335f6fb 2446
f51e8d7e 2447 echo '<td class="lastpost">';
014fe0ad 2448 $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified;
8f2e8060 2449 $parenturl = '';
39790bd8 2450 $usermodified = new stdClass();
e351bed5
AG
2451 $usermodified->id = $post->usermodified;
2452 $usermodified = username_load_fields_from_object($usermodified, $post, 'um');
8f2e8060 2453
cbebd40d
DM
2454 // In QA forums we check that the user can view participants.
2455 if ($forum->type !== 'qanda' || $canviewparticipants) {
b53b69c1 2456 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
26cee437 2457 fullname($usermodified, $canviewfullnames).'</a><br />';
8f2e8060 2458 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
b53b69c1 2459 }
8f2e8060 2460
ac00b904 2461 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
1bf3a76a 2462 userdate_htmltime($usedate, $datestring).'</a>';
29507631 2463 echo "</td>\n";
2464
ddb4a31d
AN
2465 // is_guest should be used here as this also checks whether the user is a guest in the current course.
2466 // Guests and visitors cannot subscribe - only enrolled users.
2467 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) {
ebfb73db
AN
2468 // Discussion subscription.
2469 if (\mod_forum\subscriptions::is_subscribable($forum)) {
2470 echo '<td class="discussionsubscription">';
2471 echo forum_get_discussion_subscription_icon($forum, $post->discussion);
2472 echo '</td>';
2473 }
2474 }
2475
f51e8d7e 2476 echo "</tr>\n\n";
3335f6fb 2477
3335f6fb 2478}
2479
ebfb73db
AN
2480/**
2481 * Return the markup for the discussion subscription toggling icon.
2482 *
2483 * @param stdClass $forum The forum object.
2484 * @param int $discussionid The discussion to create an icon for.
2485 * @return string The generated markup.
2486 */
517e1782 2487function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) {
ebfb73db
AN
2488 global $USER, $OUTPUT, $PAGE;
2489
2490 if ($returnurl === null && $PAGE->url) {
2491 $returnurl = $PAGE->url->out();
2492 }
2493
2494 $o = '';
2495 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid);
2496 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array(
2497 'sesskey' => sesskey(),
2498 'id' => $forum->id,
2499 'd' => $discussionid,
2500 'returnurl' => $returnurl,
2501 ));
a35ce611
AN
2502
2503 if ($includetext) {
2504 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum');
2505 }
2506
ebfb73db 2507 if ($subscriptionstatus) {
a35ce611
AN
2508 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum');
2509 if ($includetext) {
2510 $output .= get_string('subscribed', 'mod_forum');
2511 }
2512
2513 return html_writer::link($subscriptionlink, $output, array(
ebfb73db 2514 'title' => get_string('clicktounsubscribe', 'forum'),
1a9e5cb2 2515 'class' => 'discussiontoggle btn btn-link',
ebfb73db
AN
2516 'data-forumid' => $forum->id,
2517 'data-discussionid' => $discussionid,
79b4fb12 2518 'data-includetext' => $includetext,
a35ce611
AN
2519 ));
2520
ebfb73db 2521 } else {
a35ce611
AN
2522 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum');
2523 if ($includetext) {
2524 $output .= get_string('notsubscribed', 'mod_forum');
2525 }
2526
2527 return html_writer::link($subscriptionlink, $output, array(
ebfb73db 2528 'title' => get_string('clicktosubscribe', 'forum'),
1a9e5cb2 2529 'class' => 'discussiontoggle btn btn-link',
ebfb73db
AN
2530 'data-forumid' => $forum->id,
2531 'data-discussionid' => $discussionid,
79b4fb12 2532 'data-includetext' => $includetext,
a35ce611 2533 ));
ebfb73db 2534 }
ebfb73db
AN
2535}
2536
548453ec
AN
2537/**
2538 * Return a pair of spans containing classes to allow the subscribe and
2539 * unsubscribe icons to be pre-loaded by a browser.
2540 *
2541 * @return string The generated markup
2542 */
2543function forum_get_discussion_subscription_icon_preloaders() {
2544 $o = '';
2545 $o .= html_writer::span('&nbsp;', 'preload-subscribe');
2546 $o .= html_writer::span('&nbsp;', 'preload-unsubscribe');
2547 return $o;
2548}
2549
83da3d28 2550/**
2551 * Print the drop down that allows the user to select how they want to have
2552 * the discussion displayed.
df1ba0f4 2553 *
2554 * @param int $id forum id if $forumtype is 'single',
83da3d28 2555 * discussion id for any other forum type
df1ba0f4 2556 * @param mixed $mode forum layout mode
2557 * @param string $forumtype optional
83da3d28 2558 */
2559function forum_print_mode_form($id, $mode, $forumtype='') {
9fc666e5 2560 global $OUTPUT;
667e5fd9 2561 $useexperimentalui = get_user_preferences('forum_useexperimentalui', false);
83da3d28 2562 if ($forumtype == 'single') {
667e5fd9
RW
2563 $select = new single_select(
2564 new moodle_url("/mod/forum/view.php",
2565 array('f' => $id)),
2566 'mode',
2567 forum_get_layout_modes($useexperimentalui),
2568 $mode,
2569 null,
2570 "mode"
2571 );
d1881bec 2572 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
f8dab966 2573 $select->class = "forummode";
8295918f 2574 } else {
667e5fd9
RW
2575 $select = new single_select(
2576 new moodle_url("/mod/forum/discuss.php",
2577 array('d' => $id)),
2578 'mode',
2579 forum_get_layout_modes($useexperimentalui),
2580 $mode,
2581 null,
2582 "mode"
2583 );
d1881bec 2584 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide'));
83da3d28 2585 }
f8dab966 2586 echo $OUTPUT->render($select);
501cdbd8 2587}
2588
0a4ac01b 2589/**
df1ba0f4 2590 * @global object
2591 * @param object $course
2592 * @param string $search
2593 * @return string
0a4ac01b 2594 */
6f1cc8d6 2595function forum_search_form($course, $search='') {
66bb9ead
FM
2596 global $CFG, $PAGE;
2597 $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search);
2598 $output = $PAGE->get_renderer('mod_forum');
2599 return $output->render($forumsearch);
501cdbd8 2600}
2601
2602
0a4ac01b 2603/**
df1ba0f4 2604 * @global object
2605 * @global object
0a4ac01b 2606 */
11b0c469 2607function forum_set_return() {
607809b3 2608 global $CFG, $SESSION;
501cdbd8 2609
28e1e8b9 2610 if (! isset($SESSION->fromdiscussion)) {
dcee0b94 2611 $referer = get_local_referer(false);
28e1e8b9 2612 // If the referer is NOT a login screen then save it.
48d38fad 2613 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
b2687a05 2614 $SESSION->fromdiscussion = $referer;
28e1e8b9 2615 }
501cdbd8 2616 }
2617}
2618
2619
0a4ac01b 2620/**
df1ba0f4 2621 * @global object
3d8d8a8c 2622 * @param string|\moodle_url $default
df1ba0f4 2623 * @return string
0a4ac01b 2624 */
11b0c469 2625function forum_go_back_to($default) {
501cdbd8 2626 global $SESSION;
2627
9c9f7d77 2628 if (!empty($SESSION->fromdiscussion)) {
501cdbd8 2629 $returnto = $SESSION->fromdiscussion;
2630 unset($SESSION->fromdiscussion);
2631 return $returnto;
2632 } else {
2633 return $default;
2634 }
2635}
2636
0a4ac01b 2637/**
0faf6791 2638 * Given a discussion object that is being moved to $forumto,
2639 * this function checks all posts in that discussion
2640 * for attachments, and if any are found, these are
2641 * moved to the new forum directory.
2642 *
df1ba0f4 2643 * @global object
2644 * @param object $discussion
0faf6791 2645 * @param int $forumfrom source forum id
2646 * @param int $forumto target forum id
2647 * @return bool success
0a4ac01b 2648 */
0faf6791 2649function forum_move_attachments($discussion, $forumfrom, $forumto) {
2650 global $DB;
65bcf17b 2651
0faf6791 2652 $fs = get_file_storage();
7f6689e4 2653
0faf6791 2654 $newcm = get_coursemodule_from_instance('forum', $forumto);
2655 $oldcm = get_coursemodule_from_instance('forum', $forumfrom);
7f6689e4 2656
bf0f06b1
AA
2657 $newcontext = context_module::instance($newcm->id);
2658 $oldcontext = context_module::instance($oldcm->id);
7f6689e4 2659
0faf6791 2660 // loop through all posts, better not use attachment flag ;-)
1f0e7702 2661 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) {
0faf6791 2662 foreach ($posts as $post) {
d2af1014
TH
2663 $fs->move_area_files_to_new_context($oldcontext->id,
2664 $newcontext->id, 'mod_forum', 'post', $post->id);
2665 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id,
2666 $newcontext->id, 'mod_forum', 'attachment', $post->id);
2667 if ($attachmentsmoved > 0 && $post->attachment != '1') {
2668 // Weird - let's fix it
2669 $post->attachment = '1';
2670 $DB->update_record('forum_posts', $post);
2671 } else if ($attachmentsmoved == 0 && $post->attachment != '') {
2672 // Weird - let's fix it
2673 $post->attachment = '';
2674 $DB->update_record('forum_posts', $post);
7f6689e4 2675 }
2676 }
7f6689e4 2677 }
0faf6791 2678
2679 return true;
7f6689e4 2680}
2681
0a4ac01b 2682/**
0faf6791 2683 * Returns attachments as formated text/html optionally with separate images
df1ba0f4 2684 *
2685 * @global object
2686 * @global object
2687 * @global object
0faf6791 2688 * @param object $post
2689 * @param object $cm
df1ba0f4 2690 * @param string $type html/text/separateimages
0faf6791 2691 * @return mixed string or array of (html text withouth images and image HTML)
0a4ac01b 2692 */
0faf6791 2693function forum_print_attachments($post, $cm, $type) {
d436d197 2694 global $CFG, $DB, $USER, $OUTPUT;
cc2b7ea5 2695
0faf6791 2696 if (empty($post->attachment)) {
2697 return $type !== 'separateimages' ? '' : array('', '');
cc2b7ea5 2698 }
cc2b7ea5 2699
0faf6791 2700 if (!in_array($type, array('separateimages', 'html', 'text'))) {
2701 return $type !== 'separateimages' ? '' : array('', '');
2702 }
7f6689e4 2703
bf0f06b1 2704 if (!$context = context_module::instance($cm->id)) {
0faf6791 2705 return $type !== 'separateimages' ? '' : array('', '');
2706 }
2707 $strattachment = get_string('attachment', 'forum');
7f6689e4 2708
0faf6791 2709 $fs = get_file_storage();
7f6689e4 2710
0faf6791 2711 $imagereturn = '';
2712 $output = '';
72d497d4 2713
b8d3c3f7 2714 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context)));
7f6689e4 2715
b8d3c3f7 2716 if ($canexport) {
6708a1f5 2717 require_once($CFG->libdir.'/portfoliolib.php');
b8d3c3f7
SH
2718 }
2719
cc8bd704
AN
2720 // We retrieve all files according to the time that they were created. In the case that several files were uploaded
2721 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename.
2722 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false);
b8d3c3f7
SH
2723 if ($files) {
2724 if ($canexport) {
6708a1f5 2725 $button = new portfolio_add_button();
b8d3c3f7
SH
2726 }
2727 foreach ($files as $file) {
2728 $filename = $file->get_filename();
2729 $mimetype = $file->get_mimetype();
559276b1 2730 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon'));
b8d3c3f7
SH
2731 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename);
2732
2733 if ($type == 'html') {
2734 $output .= "<a href=\"$path\">$iconimage</a> ";
2735 $output .= "<a href=\"$path\">".s($filename)."</a>";
2736 if ($canexport) {
37743241 2737 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
b8d3c3f7
SH
2738 $button->set_format_by_file($file);
2739 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2740 }
2741 $output .= "<br />";
6708a1f5 2742
b8d3c3f7
SH
2743 } else if ($type == 'text') {
2744 $output .= "$strattachment ".s($filename).":\n$path\n";
2745
2746 } else { //'returnimages'
2747 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
2748 // Image attachments don't get printed as links
2749 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />";
2750 if ($canexport) {
37743241 2751 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
b8d3c3f7
SH
2752 $button->set_format_by_file($file);
2753 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
2754 }
2755 } else {
0faf6791 2756 $output .= "<a href=\"$path\">$iconimage</a> ";
b8d3c3f7 2757 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context));
f98b13a6 2758 if ($canexport) {
37743241 2759 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum');
887160c7 2760 $button->set_format_by_file($file);
0d06b6fd 2761 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
10ae55f9 2762 }
b8d3c3f7 2763 $output .= '<br />';
7f6689e4 2764 }
2765 }
103e7cba
KG
2766
2767 if (!empty($CFG->enableplagiarism)) {
2768 require_once($CFG->libdir.'/plagiarismlib.php');
2769 $output .= plagiarism_get_links(array('userid' => $post->userid,
2770 'file' => $file,
2771 'cmid' => $cm->id,
334bee5f
CC
2772 'course' => $cm->course,
2773 'forum' => $cm->instance));
103e7cba
KG
2774 $output .= '<br />';
2775 }
7f6689e4 2776 }
2777 }
72d497d4 2778
0faf6791 2779 if ($type !== 'separateimages') {
7f6689e4 2780 return $output;
0faf6791 2781
2782 } else {
2783 return array($output, $imagereturn);
2784 }
2785}
2786
9a1c0751
DM
2787////////////////////////////////////////////////////////////////////////////////
2788// File API //
2789////////////////////////////////////////////////////////////////////////////////
2790
d6f7cbfd 2791/**
2792 * Lists all browsable file areas
df1ba0f4 2793 *
d2b7803e
DC
2794 * @package mod_forum
2795 * @category files
2796 * @param stdClass $course course object
2797 * @param stdClass $cm course module object
2798 * @param stdClass $context context object
df1ba0f4 2799 * @return array
d6f7cbfd 2800 */
2801function forum_get_file_areas($course, $cm, $context) {
9a1c0751
DM
2802 return array(
2803 'attachment' => get_string('areaattachment', 'mod_forum'),
2804 'post' => get_string('areapost', 'mod_forum'),
2805 );
d6f7cbfd 2806}
2807
beb18068
MG
2808/**
2809 * File browsing support for forum module.
2810 *
d2b7803e
DC
2811 * @package mod_forum
2812 * @category files
2813 * @param stdClass $browser file browser object
2814 * @param stdClass $areas file areas
2815 * @param stdClass $course course object
2816 * @param stdClass $cm course module
2817 * @param stdClass $context context module
2818 * @param string $filearea file area
2819 * @param int $itemid item ID
2820 * @param string $filepath file path
2821 * @param string $filename file name
2822 * @return file_info instance or null if not found
beb18068
MG
2823 */
2824function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
35ca63c1 2825 global $CFG, $DB, $USER;
beb18068
MG
2826
2827 if ($context->contextlevel != CONTEXT_MODULE) {
2828 return null;
2829 }
2830
9a1c0751
DM
2831 // filearea must contain a real area
2832 if (!isset($areas[$filearea])) {
2833 return null;
2834 }
2835
9a1c0751
DM
2836 // Note that forum_user_can_see_post() additionally allows access for parent roles
2837 // and it explicitly checks qanda forum type, too. One day, when we stop requiring
2838 // course:managefiles, we will need to extend this.
2839 if (!has_capability('mod/forum:viewdiscussion', $context)) {
beb18068
MG
2840 return null;
2841 }
2842
9a1c0751
DM
2843 if (is_null($itemid)) {
2844 require_once($CFG->dirroot.'/mod/forum/locallib.php');
2845 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2846 }
2847
406f8dd8
MG
2848 static $cached = array();
2849 // $cached will store last retrieved post, discussion and forum. To make sure that the cache
2850 // is cleared between unit tests we check if this is the same session
2851 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) {
2852 $cached = array('sesskey' => sesskey());
2853 }
2854
2855 if (isset($cached['post']) && $cached['post']->id == $itemid) {
2856 $post = $cached['post'];
2857 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) {
2858 $cached['post'] = $post;
2859 } else {
beb18068
MG
2860 return null;
2861 }
2862
406f8dd8
MG
2863 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) {
2864 $discussion = $cached['discussion'];
2865 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) {
2866 $cached['discussion'] = $discussion;
2867 } else {
beb18068
MG
2868 return null;
2869 }
2870
406f8dd8
MG
2871 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) {
2872 $forum = $cached['forum'];
2873 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) {
2874 $cached['forum'] = $forum;
2875 } else {
beb18068
MG
2876 return null;
2877 }
2878
2879 $fs = get_file_storage();
2880 $filepath = is_null($filepath) ? '/' : $filepath;
2881 $filename = is_null($filename) ? '.' : $filename;
2882 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) {
2883 return null;
2884 }
2885
35ca63c1
AG
2886 // Checks to see if the user can manage files or is the owner.
2887 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2888 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2889 return null;
2890 }
beb18068 2891 // Make sure groups allow this user to see this file
406f8dd8 2892 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) {
b75ec104 2893 $groupmode = groups_get_activity_groupmode($cm, $course);
406f8dd8
MG
2894 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) {
2895 return null;
beb18068
MG
2896 }
2897 }
2898
2899 // Make sure we're allowed to see it...
2900 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
2901 return null;
2902 }
2903
2904 $urlbase = $CFG->wwwroot.'/pluginfile.php';
9a1c0751 2905 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
beb18068
MG
2906}
2907
0faf6791 2908/**
2909 * Serves the forum attachments. Implements needed access control ;-)
df1ba0f4 2910 *
d2b7803e
DC
2911 * @package mod_forum
2912 * @category files
2913 * @param stdClass $course course object
2914 * @param stdClass $cm course module object
2915 * @param stdClass $context context object
2916 * @param string $filearea file area
2917 * @param array $args extra arguments
2918 * @param bool $forcedownload whether or not force download
261cbbac 2919 * @param array $options additional options affecting the file serving
86900a93 2920 * @return bool false if file not found, does not return if found - justsend the file
0faf6791 2921 */
261cbbac 2922function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
0faf6791 2923 global $CFG, $DB;
2924
64f93798 2925 if ($context->contextlevel != CONTEXT_MODULE) {
7e55d513 2926 return false;
2927 }
2928
64f93798
PS
2929 require_course_login($course, true, $cm);
2930
9a1c0751
DM
2931 $areas = forum_get_file_areas($course, $cm, $context);
2932
2933 // filearea must contain a real area
2934 if (!isset($areas[$filearea])) {
0faf6791 2935 return false;
2936 }
2937
2938 $postid = (int)array_shift($args);
2939
2940 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) {
2941 return false;
7f6689e4 2942 }
72d497d4 2943
0faf6791 2944 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) {
2945 return false;
2946 }
2947
64f93798 2948 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) {
0faf6791 2949 return false;
2950 }
2951
2952 $fs = get_file_storage();
64f93798
PS
2953 $relativepath = implode('/', $args);
2954 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath";
0faf6791 2955 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
2956 return false;
2957 }
2958
2959 // Make sure groups allow this user to see this file
b75ec104
DM
2960 if ($discussion->groupid > 0) {
2961 $groupmode = groups_get_activity_groupmode($cm, $course);
2962 if ($groupmode == SEPARATEGROUPS) {
2963 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
2964 return false;
2965 }
0faf6791 2966 }
2967 }
2968
2969 // Make sure we're allowed to see it...
1d797cac 2970 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
0faf6791 2971 return false;
2972 }
2973
0faf6791 2974 // finally send the file
261cbbac 2975 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
7f6689e4 2976}
0faf6791 2977
db290a6e 2978/**
e3ff14ca 2979 * If successful, this function returns the name of the file
df1ba0f4 2980 *
2981 * @global object
2982 * @param object $post is a full post record, including course and forum
2983 * @param object $forum
2984 * @param object $cm
2985 * @param mixed $mform
a9a0cb69 2986 * @param string $unused
df1ba0f4 2987 * @return bool
e3ff14ca 2988 */
a9a0cb69 2989function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) {
12fab708 2990 global $DB;
7f6689e4 2991
dbf4d660 2992 if (empty($mform)) {
2993 return false;
2994 }
7f6689e4 2995
6606c00f
MD
2996 if (empty($post->attachments)) {
2997 return true; // Nothing to do
2998 }
2999
bf0f06b1 3000 $context = context_module::instance($cm->id);
0faf6791 3001
edc0c493 3002 $info = file_get_draft_area_info($post->attachments);
12fab708 3003 $present = ($info['filecount']>0) ? '1' : '';
61a339e5
MG
3004 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id,
3005 mod_forum_post_form::attachment_options($forum));
0faf6791 3006
12fab708 3007 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id));
274e2947 3008
12fab708 3009 return true;
927ce887 3010}
3011
3012/**
3013 * Add a new post in an existing discussion.
df1ba0f4 3014 *
2e48384d
AN
3015 * @param stdClass $post The post data
3016 * @param mixed $mform The submitted form
3017 * @param string $unused
df1ba0f4 3018 * @return int
0a4ac01b 3019 */
91223df6 3020function forum_add_new_post($post, $mform, $unused = null) {
2e48384d 3021 global $USER, $DB;
e3ff14ca 3022
4e445355 3023 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3024 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
0faf6791 3025 $cm = get_coursemodule_from_instance('forum', $forum->id);
bf0f06b1 3026 $context = context_module::instance($cm->id);
bc4c7337
AN
3027 $privatereplyto = 0;
3028
3029 // Check whether private replies should be enabled for this post.
3030 if ($post->parent) {
3031 $parent = $DB->get_record('forum_posts', array('id' => $post->parent));
3032
3033 if (!empty($parent->privatereplyto)) {
3034 throw new \coding_exception('It should not be possible to reply to a private reply');
3035 }
3036
3037 if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) {
3038 $privatereplyto = $parent->userid;
3039 }
3040 }
b9973acc 3041
3042 $post->created = $post->modified = time();
8076010d 3043 $post->mailed = FORUM_MAILED_PENDING;
b9973acc 3044 $post->userid = $USER->id;
bc4c7337 3045 $post->privatereplyto = $privatereplyto;
7f6689e4 3046 $post->attachment = "";
cd5be9a5
MG
3047 if (!isset($post->totalscore)) {
3048 $post->totalscore = 0;
3049 }
3050 if (!isset($post->mailnow)) {
3051 $post->mailnow = 0;
3052 }
7f6689e4 3053
d21d6baa 3054 \mod_forum\local\entities\post::add_message_counts($post);
a8f3a651 3055 $post->id = $DB->insert_record("forum_posts", $post);
61a339e5 3056 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id,
5e95223e 3057 mod_forum_post_form::editor_options($context, null), $post->message);
e58357bf 3058 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id));
91223df6 3059 forum_add_attachment($post, $forum, $cm, $mform);
29507631 3060
3061 // Update discussion modified date
4e445355 3062 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion));
3063 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion));
65b0e537 3064
90f4745c 3065 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
6c635746 3066 forum_tp_mark_post_read($post->userid, $post);
f37da850 3067 }
3068
34c8585d
MG
3069 if (isset($post->tags)) {
3070 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags);
3071 }
3072
103e7cba
KG
3073 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3074 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post');
3075
7f6689e4 3076 return $post->id;
501cdbd8 3077}
3078
0a063e6d
JL
3079/**
3080 * Trigger post updated event.
3081 *
3082 * @param object $post forum post object
3083 * @param object $discussion discussion object
3084 * @param object $context forum context object
3085 * @param object $forum forum object
3086 * @since Moodle 3.8
3087 * @return void
3088 */
3089function forum_trigger_post_updated_event($post, $discussion, $context, $forum) {
3090 global $USER;
3091
3092 $params = array(
3093 'context' => $context,
3094 'objectid' => $post->id,
3095 'other' => array(
3096 'discussionid' => $discussion->id,
3097 'forumid' => $forum->id,
3098 'forumtype' => $forum->type,
3099 )
3100 );
3101
3102 if ($USER->id !== $post->userid) {
3103 $params['relateduserid'] = $post->userid;
3104 }
3105
3106 $event = \mod_forum\event\post_updated::create($params);
3107 $event->add_record_snapshot('forum_discussions', $discussion);
3108 $event->trigger();
3109}
3110
0a4ac01b 3111/**
2e48384d 3112 * Update a post.
df1ba0f4 3113 *
6528ec35 3114 * @param stdClass $newpost The post to update
2e48384d
AN
3115 * @param mixed $mform The submitted form
3116 * @param string $unused
3117 * @return bool
0a4ac01b 3118 */
6528ec35
AN
3119function forum_update_post($newpost, $mform, $unused = null) {
3120 global $DB, $USER;
a56f0d60 3121
6528ec35 3122 $post = $DB->get_record('forum_posts', array('id' => $newpost->id));
0faf6791 3123 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
3124 $forum = $DB->get_record('forum', array('id' => $discussion->forum));
3125 $cm = get_coursemodule_from_instance('forum', $forum->id);
bf0f06b1 3126 $context = context_module::instance($cm->id);
90f4745c 3127
6528ec35
AN
3128 // Allowed modifiable fields.
3129 $modifiablefields = [
3130 'subject',
3131 'message',
3132 'messageformat',
3133 'messagetrust',
3134 'timestart',
3135 'timeend',
3136 'pinned',
1af801be 3137 'attachments',
6528ec35
AN
3138 ];
3139 foreach ($modifiablefields as $field) {
3140 if (isset($newpost->{$field})) {
3141 $post->{$field} = $newpost->{$field};
3142 }
3143 }
ffe11640 3144 $post->modified = time();
0936de64 3145
dd97c328 3146 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too
0faf6791 3147 $discussion->name = $post->subject;
3148 $discussion->timestart = $post->timestart;
3149 $discussion->timeend = $post->timeend;
5f219cf1
BK
3150
3151 if (isset($post->pinned)) {
3152 $discussion->pinned = $post->pinned;
3153 }
dd97c328 3154 }
6528ec35 3155 $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id,
5e95223e 3156 mod_forum_post_form::editor_options($context, $post->id), $post->message);
d21d6baa 3157 \mod_forum\local\entities\post::add_message_counts($post);
6528ec35 3158 $DB->update_record('forum_posts', $post);
014fe0ad 3159 // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post.
9d749339 3160 $DB->update_record('forum_discussions', $discussion);
29507631 3161
2e48384d 3162 forum_add_attachment($post, $forum, $cm, $mform);
29507631 3163
0a063e6d
JL
3164 if ($forum->type == 'single' && $post->parent == '0') {
3165 // Updating first post of single discussion type -> updating forum intro.
3166 $forum->intro = $post->message;
3167 $forum->timemodified = time();
3168 $DB->update_record("forum", $forum);
3169 }
3170
34c8585d
MG
3171 if (isset($newpost->tags)) {
3172 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags);
3173 }
3174
90f4745c 3175 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
6c635746 3176 forum_tp_mark_post_read($USER->id, $post);
f37da850 3177 }
3178
103e7cba
KG
3179 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection)
3180 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post');
3181
0faf6791 3182 return true;
501cdbd8 3183}
3184
0a4