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