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