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