See Release Notes
Long Term Support Release
Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]
1 <?php 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 /** 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 21 */ 22 23 defined('MOODLE_INTERNAL') || die(); 24 25 /** Include required files */ 26 require_once (__DIR__ . '/deprecatedlib.php'); 27 require_once($CFG->libdir.'/filelib.php'); 28 29 /// CONSTANTS /////////////////////////////////////////////////////////// 30 31 define('FORUM_MODE_FLATOLDEST', 1); 32 define('FORUM_MODE_FLATNEWEST', -1); 33 define('FORUM_MODE_THREADED', 2); 34 define('FORUM_MODE_NESTED', 3); 35 define('FORUM_MODE_NESTED_V2', 4); 36 37 define('FORUM_CHOOSESUBSCRIBE', 0); 38 define('FORUM_FORCESUBSCRIBE', 1); 39 define('FORUM_INITIALSUBSCRIBE', 2); 40 define('FORUM_DISALLOWSUBSCRIBE',3); 41 42 /** 43 * FORUM_TRACKING_OFF - Tracking is not available for this forum. 44 */ 45 define('FORUM_TRACKING_OFF', 0); 46 47 /** 48 * FORUM_TRACKING_OPTIONAL - Tracking is based on user preference. 49 */ 50 define('FORUM_TRACKING_OPTIONAL', 1); 51 52 /** 53 * FORUM_TRACKING_FORCED - Tracking is on, regardless of user setting. 54 * Treated as FORUM_TRACKING_OPTIONAL if $CFG->forum_allowforcedreadtracking is off. 55 */ 56 define('FORUM_TRACKING_FORCED', 2); 57 58 define('FORUM_MAILED_PENDING', 0); 59 define('FORUM_MAILED_SUCCESS', 1); 60 define('FORUM_MAILED_ERROR', 2); 61 62 if (!defined('FORUM_CRON_USER_CACHE')) { 63 /** Defines how many full user records are cached in forum cron. */ 64 define('FORUM_CRON_USER_CACHE', 5000); 65 } 66 67 /** 68 * FORUM_POSTS_ALL_USER_GROUPS - All the posts in groups where the user is enrolled. 69 */ 70 define('FORUM_POSTS_ALL_USER_GROUPS', -2); 71 72 define('FORUM_DISCUSSION_PINNED', 1); 73 define('FORUM_DISCUSSION_UNPINNED', 0); 74 75 /// STANDARD FUNCTIONS /////////////////////////////////////////////////////////// 76 77 /** 78 * Given an object containing all the necessary data, 79 * (defined by the form in mod_form.php) this function 80 * will create a new instance and return the id number 81 * of the new instance. 82 * 83 * @param stdClass $forum add forum instance 84 * @param mod_forum_mod_form $mform 85 * @return int intance id 86 */ 87 function forum_add_instance($forum, $mform = null) { 88 global $CFG, $DB; 89 90 require_once($CFG->dirroot.'/mod/forum/locallib.php'); 91 92 $forum->timemodified = time(); 93 94 if (empty($forum->assessed)) { 95 $forum->assessed = 0; 96 } 97 98 if (empty($forum->ratingtime) or empty($forum->assessed)) { 99 $forum->assesstimestart = 0; 100 $forum->assesstimefinish = 0; 101 } 102 103 $forum->id = $DB->insert_record('forum', $forum); 104 $modcontext = context_module::instance($forum->coursemodule); 105 106 if ($forum->type == 'single') { // Create related discussion. 107 $discussion = new stdClass(); 108 $discussion->course = $forum->course; 109 $discussion->forum = $forum->id; 110 $discussion->name = $forum->name; 111 $discussion->assessed = $forum->assessed; 112 $discussion->message = $forum->intro; 113 $discussion->messageformat = $forum->introformat; 114 $discussion->messagetrust = trusttext_trusted(context_course::instance($forum->course)); 115 $discussion->mailnow = false; 116 $discussion->groupid = -1; 117 118 $message = ''; 119 120 $discussion->id = forum_add_discussion($discussion, null, $message); 121 122 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) { 123 // Ugly hack - we need to copy the files somehow. 124 $discussion = $DB->get_record('forum_discussions', array('id'=>$discussion->id), '*', MUST_EXIST); 125 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST); 126 127 $options = array('subdirs'=>true); // Use the same options as intro field! 128 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message); 129 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id)); 130 } 131 } 132 133 forum_update_calendar($forum, $forum->coursemodule); 134 forum_grade_item_update($forum); 135 136 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null; 137 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected); 138 139 return $forum->id; 140 } 141 142 /** 143 * Handle changes following the creation of a forum instance. 144 * This function is typically called by the course_module_created observer. 145 * 146 * @param object $context the forum context 147 * @param stdClass $forum The forum object 148 * @return void 149 */ 150 function forum_instance_created($context, $forum) { 151 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) { 152 $users = \mod_forum\subscriptions::get_potential_subscribers($context, 0, 'u.id, u.email'); 153 foreach ($users as $user) { 154 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $context); 155 } 156 } 157 } 158 159 /** 160 * Given an object containing all the necessary data, 161 * (defined by the form in mod_form.php) this function 162 * will update an existing instance with new data. 163 * 164 * @global object 165 * @param object $forum forum instance (with magic quotes) 166 * @return bool success 167 */ 168 function forum_update_instance($forum, $mform) { 169 global $CFG, $DB, $OUTPUT, $USER; 170 171 require_once($CFG->dirroot.'/mod/forum/locallib.php'); 172 173 $forum->timemodified = time(); 174 $forum->id = $forum->instance; 175 176 if (empty($forum->assessed)) { 177 $forum->assessed = 0; 178 } 179 180 if (empty($forum->ratingtime) or empty($forum->assessed)) { 181 $forum->assesstimestart = 0; 182 $forum->assesstimefinish = 0; 183 } 184 185 $oldforum = $DB->get_record('forum', array('id'=>$forum->id)); 186 187 // MDL-3942 - if the aggregation type or scale (i.e. max grade) changes then recalculate the grades for the entire forum 188 // if scale changes - do we need to recheck the ratings, if ratings higher than scale how do we want to respond? 189 // for count and sum aggregation types the grade we check to make sure they do not exceed the scale (i.e. max score) when calculating the grade 190 $updategrades = false; 191 192 if ($oldforum->assessed <> $forum->assessed) { 193 // Whether this forum is rated. 194 $updategrades = true; 195 } 196 197 if ($oldforum->scale <> $forum->scale) { 198 // The scale currently in use. 199 $updategrades = true; 200 } 201 202 if (empty($oldforum->grade_forum) || $oldforum->grade_forum <> $forum->grade_forum) { 203 // The whole forum grading. 204 $updategrades = true; 205 } 206 207 if ($updategrades) { 208 forum_update_grades($forum); // Recalculate grades for the forum. 209 } 210 211 if ($forum->type == 'single') { // Update related discussion and post. 212 $discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id), 'timemodified ASC'); 213 if (!empty($discussions)) { 214 if (count($discussions) > 1) { 215 echo $OUTPUT->notification(get_string('warnformorepost', 'forum')); 216 } 217 $discussion = array_pop($discussions); 218 } else { 219 // try to recover by creating initial discussion - MDL-16262 220 $discussion = new stdClass(); 221 $discussion->course = $forum->course; 222 $discussion->forum = $forum->id; 223 $discussion->name = $forum->name; 224 $discussion->assessed = $forum->assessed; 225 $discussion->message = $forum->intro; 226 $discussion->messageformat = $forum->introformat; 227 $discussion->messagetrust = true; 228 $discussion->mailnow = false; 229 $discussion->groupid = -1; 230 231 $message = ''; 232 233 forum_add_discussion($discussion, null, $message); 234 235 if (! $discussion = $DB->get_record('forum_discussions', array('forum'=>$forum->id))) { 236 print_error('cannotadd', 'forum'); 237 } 238 } 239 if (! $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost))) { 240 print_error('cannotfindfirstpost', 'forum'); 241 } 242 243 $cm = get_coursemodule_from_instance('forum', $forum->id); 244 $modcontext = context_module::instance($cm->id, MUST_EXIST); 245 246 $post = $DB->get_record('forum_posts', array('id'=>$discussion->firstpost), '*', MUST_EXIST); 247 $post->subject = $forum->name; 248 $post->message = $forum->intro; 249 $post->messageformat = $forum->introformat; 250 $post->messagetrust = trusttext_trusted($modcontext); 251 $post->modified = $forum->timemodified; 252 $post->userid = $USER->id; // MDL-18599, so that current teacher can take ownership of activities. 253 254 if ($mform and $draftid = file_get_submitted_draft_itemid('introeditor')) { 255 // Ugly hack - we need to copy the files somehow. 256 $options = array('subdirs'=>true); // Use the same options as intro field! 257 $post->message = file_save_draft_area_files($draftid, $modcontext->id, 'mod_forum', 'post', $post->id, $options, $post->message); 258 } 259 260 \mod_forum\local\entities\post::add_message_counts($post); 261 $DB->update_record('forum_posts', $post); 262 $discussion->name = $forum->name; 263 $DB->update_record('forum_discussions', $discussion); 264 } 265 266 $DB->update_record('forum', $forum); 267 268 $modcontext = context_module::instance($forum->coursemodule); 269 if (($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) && ($oldforum->forcesubscribe <> $forum->forcesubscribe)) { 270 $users = \mod_forum\subscriptions::get_potential_subscribers($modcontext, 0, 'u.id, u.email', ''); 271 foreach ($users as $user) { 272 \mod_forum\subscriptions::subscribe_user($user->id, $forum, $modcontext); 273 } 274 } 275 276 forum_update_calendar($forum, $forum->coursemodule); 277 forum_grade_item_update($forum); 278 279 $completiontimeexpected = !empty($forum->completionexpected) ? $forum->completionexpected : null; 280 \core_completion\api::update_completion_date_event($forum->coursemodule, 'forum', $forum->id, $completiontimeexpected); 281 282 return true; 283 } 284 285 286 /** 287 * Given an ID of an instance of this module, 288 * this function will permanently delete the instance 289 * and any data that depends on it. 290 * 291 * @global object 292 * @param int $id forum instance id 293 * @return bool success 294 */ 295 function forum_delete_instance($id) { 296 global $DB; 297 298 if (!$forum = $DB->get_record('forum', array('id'=>$id))) { 299 return false; 300 } 301 if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) { 302 return false; 303 } 304 if (!$course = $DB->get_record('course', array('id'=>$cm->course))) { 305 return false; 306 } 307 308 $context = context_module::instance($cm->id); 309 310 // now get rid of all files 311 $fs = get_file_storage(); 312 $fs->delete_area_files($context->id); 313 314 $result = true; 315 316 \core_completion\api::update_completion_date_event($cm->id, 'forum', $forum->id, null); 317 318 // Delete digest and subscription preferences. 319 $DB->delete_records('forum_digests', array('forum' => $forum->id)); 320 $DB->delete_records('forum_subscriptions', array('forum'=>$forum->id)); 321 $DB->delete_records('forum_discussion_subs', array('forum' => $forum->id)); 322 323 if ($discussions = $DB->get_records('forum_discussions', array('forum'=>$forum->id))) { 324 foreach ($discussions as $discussion) { 325 if (!forum_delete_discussion($discussion, true, $course, $cm, $forum)) { 326 $result = false; 327 } 328 } 329 } 330 331 forum_tp_delete_read_records(-1, -1, -1, $forum->id); 332 333 forum_grade_item_delete($forum); 334 335 // We must delete the module record after we delete the grade item. 336 if (!$DB->delete_records('forum', array('id'=>$forum->id))) { 337 $result = false; 338 } 339 340 return $result; 341 } 342 343 344 /** 345 * Indicates API features that the forum supports. 346 * 347 * @uses FEATURE_GROUPS 348 * @uses FEATURE_GROUPINGS 349 * @uses FEATURE_MOD_INTRO 350 * @uses FEATURE_COMPLETION_TRACKS_VIEWS 351 * @uses FEATURE_COMPLETION_HAS_RULES 352 * @uses FEATURE_GRADE_HAS_GRADE 353 * @uses FEATURE_GRADE_OUTCOMES 354 * @param string $feature 355 * @return mixed True if yes (some features may use other values) 356 */ 357 function forum_supports($feature) { 358 switch($feature) { 359 case FEATURE_GROUPS: return true; 360 case FEATURE_GROUPINGS: return true; 361 case FEATURE_MOD_INTRO: return true; 362 case FEATURE_COMPLETION_TRACKS_VIEWS: return true; 363 case FEATURE_COMPLETION_HAS_RULES: return true; 364 case FEATURE_GRADE_HAS_GRADE: return true; 365 case FEATURE_GRADE_OUTCOMES: return true; 366 case FEATURE_RATE: return true; 367 case FEATURE_BACKUP_MOODLE2: return true; 368 case FEATURE_SHOW_DESCRIPTION: return true; 369 case FEATURE_PLAGIARISM: return true; 370 case FEATURE_ADVANCED_GRADING: return true; 371 372 default: return null; 373 } 374 } 375 376 /** 377 * Obtains the automatic completion state for this forum based on any conditions 378 * in forum settings. 379 * 380 * @global object 381 * @global object 382 * @param object $course Course 383 * @param object $cm Course-module 384 * @param int $userid User ID 385 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions) 386 * @return bool True if completed, false if not. (If no conditions, then return 387 * value depends on comparison type) 388 */ 389 function forum_get_completion_state($course,$cm,$userid,$type) { 390 global $CFG,$DB; 391 392 // Get forum details 393 if (!($forum=$DB->get_record('forum',array('id'=>$cm->instance)))) { 394 throw new Exception("Can't find forum {$cm->instance}"); 395 } 396 397 $result=$type; // Default return value 398 399 $postcountparams=array('userid'=>$userid,'forumid'=>$forum->id); 400 $postcountsql=" 401 SELECT 402 COUNT(1) 403 FROM 404 {forum_posts} fp 405 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id 406 WHERE 407 fp.userid=:userid AND fd.forum=:forumid"; 408 409 if ($forum->completiondiscussions) { 410 $value = $forum->completiondiscussions <= 411 $DB->count_records('forum_discussions',array('forum'=>$forum->id,'userid'=>$userid)); 412 if ($type == COMPLETION_AND) { 413 $result = $result && $value; 414 } else { 415 $result = $result || $value; 416 } 417 } 418 if ($forum->completionreplies) { 419 $value = $forum->completionreplies <= 420 $DB->get_field_sql( $postcountsql.' AND fp.parent<>0',$postcountparams); 421 if ($type==COMPLETION_AND) { 422 $result = $result && $value; 423 } else { 424 $result = $result || $value; 425 } 426 } 427 if ($forum->completionposts) { 428 $value = $forum->completionposts <= $DB->get_field_sql($postcountsql,$postcountparams); 429 if ($type == COMPLETION_AND) { 430 $result = $result && $value; 431 } else { 432 $result = $result || $value; 433 } 434 } 435 436 return $result; 437 } 438 439 /** 440 * Create a message-id string to use in the custom headers of forum notification emails 441 * 442 * message-id is used by email clients to identify emails and to nest conversations 443 * 444 * @param int $postid The ID of the forum post we are notifying the user about 445 * @param int $usertoid The ID of the user being notified 446 * @return string A unique message-id 447 */ 448 function forum_get_email_message_id($postid, $usertoid) { 449 return generate_email_messageid(hash('sha256', $postid . 'to' . $usertoid)); 450 } 451 452 /** 453 * 454 * @param object $course 455 * @param object $user 456 * @param object $mod TODO this is not used in this function, refactor 457 * @param object $forum 458 * @return object A standard object with 2 variables: info (number of posts for this user) and time (last modified) 459 */ 460 function forum_user_outline($course, $user, $mod, $forum) { 461 global $CFG; 462 require_once("$CFG->libdir/gradelib.php"); 463 464 $gradeinfo = ''; 465 $gradetime = 0; 466 467 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id); 468 if (!empty($grades->items[0]->grades)) { 469 // Item 0 is the rating. 470 $grade = reset($grades->items[0]->grades); 471 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user)); 472 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 473 $gradeinfo .= get_string('gradeforrating', 'forum', $grade) . html_writer::empty_tag('br'); 474 } else { 475 $gradeinfo .= get_string('gradeforratinghidden', 'forum') . html_writer::empty_tag('br'); 476 } 477 } 478 479 // Item 1 is the whole-forum grade. 480 if (!empty($grades->items[1]->grades)) { 481 $grade = reset($grades->items[1]->grades); 482 $gradetime = max($gradetime, grade_get_date_for_user_grade($grade, $user)); 483 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 484 $gradeinfo .= get_string('gradeforwholeforum', 'forum', $grade) . html_writer::empty_tag('br'); 485 } else { 486 $gradeinfo .= get_string('gradeforwholeforumhidden', 'forum') . html_writer::empty_tag('br'); 487 } 488 } 489 490 $count = forum_count_user_posts($forum->id, $user->id); 491 if ($count && $count->postcount > 0) { 492 $info = get_string("numposts", "forum", $count->postcount); 493 $time = $count->lastpost; 494 495 if ($gradeinfo) { 496 $info .= ', ' . $gradeinfo; 497 $time = max($time, $gradetime); 498 } 499 500 return (object) [ 501 'info' => $info, 502 'time' => $time, 503 ]; 504 } else if ($gradeinfo) { 505 return (object) [ 506 'info' => $gradeinfo, 507 'time' => $gradetime, 508 ]; 509 } 510 511 return null; 512 } 513 514 515 /** 516 * @global object 517 * @global object 518 * @param object $coure 519 * @param object $user 520 * @param object $mod 521 * @param object $forum 522 */ 523 function forum_user_complete($course, $user, $mod, $forum) { 524 global $CFG, $USER; 525 require_once("$CFG->libdir/gradelib.php"); 526 527 $getgradeinfo = function($grades, string $type) use ($course): string { 528 global $OUTPUT; 529 530 if (empty($grades)) { 531 return ''; 532 } 533 534 $result = ''; 535 $grade = reset($grades); 536 if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) { 537 $result .= $OUTPUT->container(get_string("gradefor{$type}", "forum", $grade)); 538 if ($grade->str_feedback) { 539 $result .= $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback); 540 } 541 } else { 542 $result .= $OUTPUT->container(get_string("gradefor{$type}hidden", "forum")); 543 } 544 545 return $result; 546 }; 547 548 $grades = grade_get_grades($course->id, 'mod', 'forum', $forum->id, $user->id); 549 550 // Item 0 is the rating. 551 if (!empty($grades->items[0]->grades)) { 552 echo $getgradeinfo($grades->items[0]->grades, 'rating'); 553 } 554 555 // Item 1 is the whole-forum grade. 556 if (!empty($grades->items[1]->grades)) { 557 echo $getgradeinfo($grades->items[1]->grades, 'wholeforum'); 558 } 559 560 if ($posts = forum_get_user_posts($forum->id, $user->id)) { 561 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { 562 print_error('invalidcoursemodule'); 563 } 564 $context = context_module::instance($cm->id); 565 $discussions = forum_get_user_involved_discussions($forum->id, $user->id); 566 $posts = array_filter($posts, function($post) use ($discussions) { 567 return isset($discussions[$post->discussion]); 568 }); 569 $entityfactory = mod_forum\local\container::get_entity_factory(); 570 $rendererfactory = mod_forum\local\container::get_renderer_factory(); 571 $postrenderer = $rendererfactory->get_posts_renderer(); 572 573 echo $postrenderer->render( 574 $USER, 575 [$forum->id => $entityfactory->get_forum_from_stdclass($forum, $context, $cm, $course)], 576 array_map(function($discussion) use ($entityfactory) { 577 return $entityfactory->get_discussion_from_stdclass($discussion); 578 }, $discussions), 579 array_map(function($post) use ($entityfactory) { 580 return $entityfactory->get_post_from_stdclass($post); 581 }, $posts) 582 ); 583 } else { 584 echo "<p>".get_string("noposts", "forum")."</p>"; 585 } 586 } 587 588 /** 589 * @deprecated since Moodle 3.3, when the block_course_overview block was removed. 590 */ 591 function forum_filter_user_groups_discussions() { 592 throw new coding_exception('forum_filter_user_groups_discussions() can not be used any more and is obsolete.'); 593 } 594 595 /** 596 * Returns whether the discussion group is visible by the current user or not. 597 * 598 * @since Moodle 2.8, 2.7.1, 2.6.4 599 * @param cm_info $cm The discussion course module 600 * @param int $discussiongroupid The discussion groupid 601 * @return bool 602 */ 603 function forum_is_user_group_discussion(cm_info $cm, $discussiongroupid) { 604 605 if ($discussiongroupid == -1 || $cm->effectivegroupmode != SEPARATEGROUPS) { 606 return true; 607 } 608 609 if (isguestuser()) { 610 return false; 611 } 612 613 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id)) || 614 in_array($discussiongroupid, $cm->get_modinfo()->get_groups($cm->groupingid))) { 615 return true; 616 } 617 618 return false; 619 } 620 621 /** 622 * @deprecated since Moodle 3.3, when the block_course_overview block was removed. 623 */ 624 function forum_print_overview() { 625 throw new coding_exception('forum_print_overview() can not be used any more and is obsolete.'); 626 } 627 628 /** 629 * Given a course and a date, prints a summary of all the new 630 * messages posted in the course since that date 631 * 632 * @global object 633 * @global object 634 * @global object 635 * @uses CONTEXT_MODULE 636 * @uses VISIBLEGROUPS 637 * @param object $course 638 * @param bool $viewfullnames capability 639 * @param int $timestart 640 * @return bool success 641 */ 642 function forum_print_recent_activity($course, $viewfullnames, $timestart) { 643 global $USER, $DB, $OUTPUT; 644 645 // do not use log table if possible, it may be huge and is expensive to join with other tables 646 647 $allnamefields = user_picture::fields('u', null, 'duserid'); 648 if (!$posts = $DB->get_records_sql("SELECT p.*, 649 f.course, f.type AS forumtype, f.name AS forumname, f.intro, f.introformat, f.duedate, 650 f.cutoffdate, f.assessed AS forumassessed, f.assesstimestart, f.assesstimefinish, 651 f.scale, f.grade_forum, f.maxbytes, f.maxattachments, f.forcesubscribe, 652 f.trackingtype, f.rsstype, f.rssarticles, f.timemodified, f.warnafter, f.blockafter, 653 f.blockperiod, f.completiondiscussions, f.completionreplies, f.completionposts, 654 f.displaywordcount, f.lockdiscussionafter, f.grade_forum_notify, 655 d.name AS discussionname, d.firstpost, d.userid AS discussionstarter, 656 d.assessed AS discussionassessed, d.timemodified, d.usermodified, d.forum, d.groupid, 657 d.timestart, d.timeend, d.pinned, d.timelocked, 658 $allnamefields 659 FROM {forum_posts} p 660 JOIN {forum_discussions} d ON d.id = p.discussion 661 JOIN {forum} f ON f.id = d.forum 662 JOIN {user} u ON u.id = p.userid 663 WHERE p.created > ? AND f.course = ? AND p.deleted <> 1 664 ORDER BY p.id ASC", array($timestart, $course->id))) { // order by initial posting date 665 return false; 666 } 667 668 $modinfo = get_fast_modinfo($course); 669 670 $strftimerecent = get_string('strftimerecent'); 671 672 $managerfactory = mod_forum\local\container::get_manager_factory(); 673 $entityfactory = mod_forum\local\container::get_entity_factory(); 674 675 $discussions = []; 676 $capmanagers = []; 677 $printposts = []; 678 foreach ($posts as $post) { 679 if (!isset($modinfo->instances['forum'][$post->forum])) { 680 // not visible 681 continue; 682 } 683 $cm = $modinfo->instances['forum'][$post->forum]; 684 if (!$cm->uservisible) { 685 continue; 686 } 687 688 // Get the discussion. Cache if not yet available. 689 if (!isset($discussions[$post->discussion])) { 690 // Build the discussion record object from the post data. 691 $discussionrecord = (object)[ 692 'id' => $post->discussion, 693 'course' => $post->course, 694 'forum' => $post->forum, 695 'name' => $post->discussionname, 696 'firstpost' => $post->firstpost, 697 'userid' => $post->discussionstarter, 698 'groupid' => $post->groupid, 699 'assessed' => $post->discussionassessed, 700 'timemodified' => $post->timemodified, 701 'usermodified' => $post->usermodified, 702 'timestart' => $post->timestart, 703 'timeend' => $post->timeend, 704 'pinned' => $post->pinned, 705 'timelocked' => $post->timelocked 706 ]; 707 // Build the discussion entity from the factory and cache it. 708 $discussions[$post->discussion] = $entityfactory->get_discussion_from_stdclass($discussionrecord); 709 } 710 $discussionentity = $discussions[$post->discussion]; 711 712 // Get the capability manager. Cache if not yet available. 713 if (!isset($capmanagers[$post->forum])) { 714 $context = context_module::instance($cm->id); 715 $coursemodule = $cm->get_course_module_record(); 716 // Build the forum record object from the post data. 717 $forumrecord = (object)[ 718 'id' => $post->forum, 719 'course' => $post->course, 720 'type' => $post->forumtype, 721 'name' => $post->forumname, 722 'intro' => $post->intro, 723 'introformat' => $post->introformat, 724 'duedate' => $post->duedate, 725 'cutoffdate' => $post->cutoffdate, 726 'assessed' => $post->forumassessed, 727 'assesstimestart' => $post->assesstimestart, 728 'assesstimefinish' => $post->assesstimefinish, 729 'scale' => $post->scale, 730 'grade_forum' => $post->grade_forum, 731 'maxbytes' => $post->maxbytes, 732 'maxattachments' => $post->maxattachments, 733 'forcesubscribe' => $post->forcesubscribe, 734 'trackingtype' => $post->trackingtype, 735 'rsstype' => $post->rsstype, 736 'rssarticles' => $post->rssarticles, 737 'timemodified' => $post->timemodified, 738 'warnafter' => $post->warnafter, 739 'blockafter' => $post->blockafter, 740 'blockperiod' => $post->blockperiod, 741 'completiondiscussions' => $post->completiondiscussions, 742 'completionreplies' => $post->completionreplies, 743 'completionposts' => $post->completionposts, 744 'displaywordcount' => $post->displaywordcount, 745 'lockdiscussionafter' => $post->lockdiscussionafter, 746 'grade_forum_notify' => $post->grade_forum_notify 747 ]; 748 // Build the forum entity from the factory. 749 $forumentity = $entityfactory->get_forum_from_stdclass($forumrecord, $context, $coursemodule, $course); 750 // Get the capability manager of this forum and cache it. 751 $capmanagers[$post->forum] = $managerfactory->get_capability_manager($forumentity); 752 } 753 $capabilitymanager = $capmanagers[$post->forum]; 754 755 // Get the post entity. 756 $postentity = $entityfactory->get_post_from_stdclass($post); 757 758 // Check if the user can view the post. 759 if ($capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) { 760 $printposts[] = $post; 761 } 762 } 763 unset($posts); 764 765 if (!$printposts) { 766 return false; 767 } 768 769 echo $OUTPUT->heading(get_string('newforumposts', 'forum') . ':', 6); 770 $list = html_writer::start_tag('ul', ['class' => 'unlist']); 771 772 foreach ($printposts as $post) { 773 $subjectclass = empty($post->parent) ? ' bold' : ''; 774 $authorhidden = forum_is_author_hidden($post, (object) ['type' => $post->forumtype]); 775 776 $list .= html_writer::start_tag('li'); 777 $list .= html_writer::start_div('head'); 778 $list .= html_writer::div(userdate_htmltime($post->modified, $strftimerecent), 'date'); 779 if (!$authorhidden) { 780 $list .= html_writer::div(fullname($post, $viewfullnames), 'name'); 781 } 782 $list .= html_writer::end_div(); // Head. 783 784 $list .= html_writer::start_div('info' . $subjectclass); 785 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $post->discussion]); 786 if (!empty($post->parent)) { 787 $discussionurl->param('parent', $post->parent); 788 $discussionurl->set_anchor('p'. $post->id); 789 } 790 $post->subject = break_up_long_words(format_string($post->subject, true)); 791 $list .= html_writer::link($discussionurl, $post->subject, ['rel' => 'bookmark']); 792 $list .= html_writer::end_div(); // Info. 793 $list .= html_writer::end_tag('li'); 794 } 795 796 $list .= html_writer::end_tag('ul'); 797 echo $list; 798 799 return true; 800 } 801 802 /** 803 * Update activity grades. 804 * 805 * @param object $forum 806 * @param int $userid specific user only, 0 means all 807 */ 808 function forum_update_grades($forum, $userid = 0): void { 809 global $CFG, $DB; 810 require_once($CFG->libdir.'/gradelib.php'); 811 812 $ratings = null; 813 if ($forum->assessed) { 814 require_once($CFG->dirroot.'/rating/lib.php'); 815 816 $cm = get_coursemodule_from_instance('forum', $forum->id); 817 818 $rm = new rating_manager(); 819 $ratings = $rm->get_user_grades((object) [ 820 'component' => 'mod_forum', 821 'ratingarea' => 'post', 822 'contextid' => \context_module::instance($cm->id)->id, 823 824 'modulename' => 'forum', 825 'moduleid ' => $forum->id, 826 'userid' => $userid, 827 'aggregationmethod' => $forum->assessed, 828 'scaleid' => $forum->scale, 829 'itemtable' => 'forum_posts', 830 'itemtableusercolumn' => 'userid', 831 ]); 832 } 833 834 $forumgrades = null; 835 if ($forum->grade_forum) { 836 $sql = <<<EOF 837 SELECT 838 g.userid, 839 0 as datesubmitted, 840 g.grade as rawgrade, 841 g.timemodified as dategraded 842 FROM {forum} f 843 JOIN {forum_grades} g ON g.forum = f.id 844 WHERE f.id = :forumid 845 EOF; 846 847 $params = [ 848 'forumid' => $forum->id, 849 ]; 850 851 if ($userid) { 852 $sql .= " AND g.userid = :userid"; 853 $params['userid'] = $userid; 854 } 855 856 $forumgrades = []; 857 if ($grades = $DB->get_recordset_sql($sql, $params)) { 858 foreach ($grades as $userid => $grade) { 859 if ($grade->rawgrade != -1) { 860 $forumgrades[$userid] = $grade; 861 } 862 } 863 $grades->close(); 864 } 865 } 866 867 forum_grade_item_update($forum, $ratings, $forumgrades); 868 } 869 870 /** 871 * Create/update grade items for given forum. 872 * 873 * @param stdClass $forum Forum object with extra cmidnumber 874 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook 875 */ 876 function forum_grade_item_update($forum, $ratings = null, $forumgrades = null): void { 877 global $CFG; 878 require_once("{$CFG->libdir}/gradelib.php"); 879 880 // Update the rating. 881 $item = [ 882 'itemname' => get_string('gradeitemnameforrating', 'forum', $forum), 883 'idnumber' => $forum->cmidnumber, 884 ]; 885 886 if (!$forum->assessed || $forum->scale == 0) { 887 $item['gradetype'] = GRADE_TYPE_NONE; 888 } else if ($forum->scale > 0) { 889 $item['gradetype'] = GRADE_TYPE_VALUE; 890 $item['grademax'] = $forum->scale; 891 $item['grademin'] = 0; 892 } else if ($forum->scale < 0) { 893 $item['gradetype'] = GRADE_TYPE_SCALE; 894 $item['scaleid'] = -$forum->scale; 895 } 896 897 if ($ratings === 'reset') { 898 $item['reset'] = true; 899 $ratings = null; 900 } 901 // Itemnumber 0 is the rating. 902 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, $ratings, $item); 903 904 // Whole forum grade. 905 $item = [ 906 'itemname' => get_string('gradeitemnameforwholeforum', 'forum', $forum), 907 // Note: We do not need to store the idnumber here. 908 ]; 909 910 if (!$forum->grade_forum) { 911 $item['gradetype'] = GRADE_TYPE_NONE; 912 } else if ($forum->grade_forum > 0) { 913 $item['gradetype'] = GRADE_TYPE_VALUE; 914 $item['grademax'] = $forum->grade_forum; 915 $item['grademin'] = 0; 916 } else if ($forum->grade_forum < 0) { 917 $item['gradetype'] = GRADE_TYPE_SCALE; 918 $item['scaleid'] = $forum->grade_forum * -1; 919 } 920 921 if ($forumgrades === 'reset') { 922 $item['reset'] = true; 923 $forumgrades = null; 924 } 925 // Itemnumber 1 is the whole forum grade. 926 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, $forumgrades, $item); 927 } 928 929 /** 930 * Delete grade item for given forum. 931 * 932 * @param stdClass $forum Forum object 933 */ 934 function forum_grade_item_delete($forum) { 935 global $CFG; 936 require_once($CFG->libdir.'/gradelib.php'); 937 938 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 0, null, ['deleted' => 1]); 939 grade_update('mod/forum', $forum->course, 'mod', 'forum', $forum->id, 1, null, ['deleted' => 1]); 940 } 941 942 /** 943 * Checks if scale is being used by any instance of forum. 944 * 945 * This is used to find out if scale used anywhere. 946 * 947 * @param $scaleid int 948 * @return boolean True if the scale is used by any forum 949 */ 950 function forum_scale_used_anywhere(int $scaleid): bool { 951 global $DB; 952 953 if (empty($scaleid)) { 954 return false; 955 } 956 957 return $DB->record_exists_select('forum', "scale = ? and assessed > 0", [$scaleid * -1]); 958 } 959 960 // SQL FUNCTIONS /////////////////////////////////////////////////////////// 961 962 /** 963 * Gets a post with all info ready for forum_print_post 964 * Most of these joins are just to get the forum id 965 * 966 * @global object 967 * @global object 968 * @param int $postid 969 * @return mixed array of posts or false 970 */ 971 function forum_get_post_full($postid) { 972 global $CFG, $DB; 973 974 $allnames = get_all_user_name_fields(true, 'u'); 975 return $DB->get_record_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt 976 FROM {forum_posts} p 977 JOIN {forum_discussions} d ON p.discussion = d.id 978 LEFT JOIN {user} u ON p.userid = u.id 979 WHERE p.id = ?", array($postid)); 980 } 981 982 /** 983 * Gets all posts in discussion including top parent. 984 * 985 * @param int $discussionid The Discussion to fetch. 986 * @param string $sort The sorting to apply. 987 * @param bool $tracking Whether the user tracks this forum. 988 * @return array The posts in the discussion. 989 */ 990 function forum_get_all_discussion_posts($discussionid, $sort, $tracking = false) { 991 global $CFG, $DB, $USER; 992 993 $tr_sel = ""; 994 $tr_join = ""; 995 $params = array(); 996 997 if ($tracking) { 998 $tr_sel = ", fr.id AS postread"; 999 $tr_join = "LEFT JOIN {forum_read} fr ON (fr.postid = p.id AND fr.userid = ?)"; 1000 $params[] = $USER->id; 1001 } 1002 1003 $allnames = get_all_user_name_fields(true, 'u'); 1004 $params[] = $discussionid; 1005 if (!$posts = $DB->get_records_sql("SELECT p.*, $allnames, u.email, u.picture, u.imagealt $tr_sel 1006 FROM {forum_posts} p 1007 LEFT JOIN {user} u ON p.userid = u.id 1008 $tr_join 1009 WHERE p.discussion = ? 1010 ORDER BY $sort", $params)) { 1011 return array(); 1012 } 1013 1014 foreach ($posts as $pid=>$p) { 1015 if ($tracking) { 1016 if (forum_tp_is_post_old($p)) { 1017 $posts[$pid]->postread = true; 1018 } 1019 } 1020 if (!$p->parent) { 1021 continue; 1022 } 1023 if (!isset($posts[$p->parent])) { 1024 continue; // parent does not exist?? 1025 } 1026 if (!isset($posts[$p->parent]->children)) { 1027 $posts[$p->parent]->children = array(); 1028 } 1029 $posts[$p->parent]->children[$pid] =& $posts[$pid]; 1030 } 1031 1032 // Start with the last child of the first post. 1033 $post = &$posts[reset($posts)->id]; 1034 1035 $lastpost = false; 1036 while (!$lastpost) { 1037 if (!isset($post->children)) { 1038 $post->lastpost = true; 1039 $lastpost = true; 1040 } else { 1041 // Go to the last child of this post. 1042 $post = &$posts[end($post->children)->id]; 1043 } 1044 } 1045 1046 return $posts; 1047 } 1048 1049 /** 1050 * An array of forum objects that the user is allowed to read/search through. 1051 * 1052 * @global object 1053 * @global object 1054 * @global object 1055 * @param int $userid 1056 * @param int $courseid if 0, we look for forums throughout the whole site. 1057 * @return array of forum objects, or false if no matches 1058 * Forum objects have the following attributes: 1059 * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups, 1060 * viewhiddentimedposts 1061 */ 1062 function forum_get_readable_forums($userid, $courseid=0) { 1063 1064 global $CFG, $DB, $USER; 1065 require_once($CFG->dirroot.'/course/lib.php'); 1066 1067 if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) { 1068 print_error('notinstalled', 'forum'); 1069 } 1070 1071 if ($courseid) { 1072 $courses = $DB->get_records('course', array('id' => $courseid)); 1073 } else { 1074 // If no course is specified, then the user can see SITE + his courses. 1075 $courses1 = $DB->get_records('course', array('id' => SITEID)); 1076 $courses2 = enrol_get_users_courses($userid, true, array('modinfo')); 1077 $courses = array_merge($courses1, $courses2); 1078 } 1079 if (!$courses) { 1080 return array(); 1081 } 1082 1083 $readableforums = array(); 1084 1085 foreach ($courses as $course) { 1086 1087 $modinfo = get_fast_modinfo($course); 1088 1089 if (empty($modinfo->instances['forum'])) { 1090 // hmm, no forums? 1091 continue; 1092 } 1093 1094 $courseforums = $DB->get_records('forum', array('course' => $course->id)); 1095 1096 foreach ($modinfo->instances['forum'] as $forumid => $cm) { 1097 if (!$cm->uservisible or !isset($courseforums[$forumid])) { 1098 continue; 1099 } 1100 $context = context_module::instance($cm->id); 1101 $forum = $courseforums[$forumid]; 1102 $forum->context = $context; 1103 $forum->cm = $cm; 1104 1105 if (!has_capability('mod/forum:viewdiscussion', $context)) { 1106 continue; 1107 } 1108 1109 /// group access 1110 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { 1111 1112 $forum->onlygroups = $modinfo->get_groups($cm->groupingid); 1113 $forum->onlygroups[] = -1; 1114 } 1115 1116 /// hidden timed discussions 1117 $forum->viewhiddentimedposts = true; 1118 if (!empty($CFG->forum_enabletimedposts)) { 1119 if (!has_capability('mod/forum:viewhiddentimedposts', $context)) { 1120 $forum->viewhiddentimedposts = false; 1121 } 1122 } 1123 1124 /// qanda access 1125 if ($forum->type == 'qanda' 1126 && !has_capability('mod/forum:viewqandawithoutposting', $context)) { 1127 1128 // We need to check whether the user has posted in the qanda forum. 1129 $forum->onlydiscussions = array(); // Holds discussion ids for the discussions 1130 // the user is allowed to see in this forum. 1131 if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) { 1132 foreach ($discussionspostedin as $d) { 1133 $forum->onlydiscussions[] = $d->id; 1134 } 1135 } 1136 } 1137 1138 $readableforums[$forum->id] = $forum; 1139 } 1140 1141 unset($modinfo); 1142 1143 } // End foreach $courses 1144 1145 return $readableforums; 1146 } 1147 1148 /** 1149 * Returns a list of posts found using an array of search terms. 1150 * 1151 * @global object 1152 * @global object 1153 * @global object 1154 * @param array $searchterms array of search terms, e.g. word +word -word 1155 * @param int $courseid if 0, we search through the whole site 1156 * @param int $limitfrom 1157 * @param int $limitnum 1158 * @param int &$totalcount 1159 * @param string $extrasql 1160 * @return array|bool Array of posts found or false 1161 */ 1162 function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=50, 1163 &$totalcount, $extrasql='') { 1164 global $CFG, $DB, $USER; 1165 require_once($CFG->libdir.'/searchlib.php'); 1166 1167 $forums = forum_get_readable_forums($USER->id, $courseid); 1168 1169 if (count($forums) == 0) { 1170 $totalcount = 0; 1171 return false; 1172 } 1173 1174 $now = floor(time() / 60) * 60; // DB Cache Friendly. 1175 1176 $fullaccess = array(); 1177 $where = array(); 1178 $params = array(); 1179 1180 foreach ($forums as $forumid => $forum) { 1181 $select = array(); 1182 1183 if (!$forum->viewhiddentimedposts) { 1184 $select[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))"; 1185 $params = array_merge($params, array('userid'.$forumid=>$USER->id, 'timestart'.$forumid=>$now, 'timeend'.$forumid=>$now)); 1186 } 1187 1188 $cm = $forum->cm; 1189 $context = $forum->context; 1190 1191 if ($forum->type == 'qanda' 1192 && !has_capability('mod/forum:viewqandawithoutposting', $context)) { 1193 if (!empty($forum->onlydiscussions)) { 1194 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forum->onlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_'); 1195 $params = array_merge($params, $discussionid_params); 1196 $select[] = "(d.id $discussionid_sql OR p.parent = 0)"; 1197 } else { 1198 $select[] = "p.parent = 0"; 1199 } 1200 } 1201 1202 if (!empty($forum->onlygroups)) { 1203 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($forum->onlygroups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_'); 1204 $params = array_merge($params, $groupid_params); 1205 $select[] = "d.groupid $groupid_sql"; 1206 } 1207 1208 if ($select) { 1209 $selects = implode(" AND ", $select); 1210 $where[] = "(d.forum = :forum{$forumid} AND $selects)"; 1211 $params['forum'.$forumid] = $forumid; 1212 } else { 1213 $fullaccess[] = $forumid; 1214 } 1215 } 1216 1217 if ($fullaccess) { 1218 list($fullid_sql, $fullid_params) = $DB->get_in_or_equal($fullaccess, SQL_PARAMS_NAMED, 'fula'); 1219 $params = array_merge($params, $fullid_params); 1220 $where[] = "(d.forum $fullid_sql)"; 1221 } 1222 1223 $favjoin = ""; 1224 if (in_array('starredonly:on', $searchterms)) { 1225 $usercontext = context_user::instance($USER->id); 1226 $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext); 1227 list($favjoin, $favparams) = $ufservice->get_join_sql_by_type('mod_forum', 'discussions', 1228 "favourited", "d.id"); 1229 1230 $searchterms = array_values(array_diff($searchterms, array('starredonly:on'))); 1231 $params = array_merge($params, $favparams); 1232 $extrasql .= " AND favourited.itemid IS NOT NULL AND favourited.itemid != 0"; 1233 } 1234 1235 $selectdiscussion = "(".implode(" OR ", $where).")"; 1236 1237 $messagesearch = ''; 1238 $searchstring = ''; 1239 1240 // Need to concat these back together for parser to work. 1241 foreach($searchterms as $searchterm){ 1242 if ($searchstring != '') { 1243 $searchstring .= ' '; 1244 } 1245 $searchstring .= $searchterm; 1246 } 1247 1248 // We need to allow quoted strings for the search. The quotes *should* be stripped 1249 // by the parser, but this should be examined carefully for security implications. 1250 $searchstring = str_replace("\\\"","\"",$searchstring); 1251 $parser = new search_parser(); 1252 $lexer = new search_lexer($parser); 1253 1254 if ($lexer->parse($searchstring)) { 1255 $parsearray = $parser->get_parsed_array(); 1256 1257 $tagjoins = ''; 1258 $tagfields = []; 1259 $tagfieldcount = 0; 1260 if ($parsearray) { 1261 foreach ($parsearray as $token) { 1262 if ($token->getType() == TOKEN_TAGS) { 1263 for ($i = 0; $i <= substr_count($token->getValue(), ','); $i++) { 1264 // Queries can only have a limited number of joins so set a limit sensible users won't exceed. 1265 if ($tagfieldcount > 10) { 1266 continue; 1267 } 1268 $tagjoins .= " LEFT JOIN {tag_instance} ti_$tagfieldcount 1269 ON p.id = ti_$tagfieldcount.itemid 1270 AND ti_$tagfieldcount.component = 'mod_forum' 1271 AND ti_$tagfieldcount.itemtype = 'forum_posts'"; 1272 $tagjoins .= " LEFT JOIN {tag} t_$tagfieldcount ON t_$tagfieldcount.id = ti_$tagfieldcount.tagid"; 1273 $tagfields[] = "t_$tagfieldcount.rawname"; 1274 $tagfieldcount++; 1275 } 1276 } 1277 } 1278 list($messagesearch, $msparams) = search_generate_SQL($parsearray, 'p.message', 'p.subject', 1279 'p.userid', 'u.id', 'u.firstname', 1280 'u.lastname', 'p.modified', 'd.forum', 1281 $tagfields); 1282 1283 $params = ($msparams ? array_merge($params, $msparams) : $params); 1284 } 1285 } 1286 1287 $fromsql = "{forum_posts} p 1288 INNER JOIN {forum_discussions} d ON d.id = p.discussion 1289 INNER JOIN {user} u ON u.id = p.userid $tagjoins $favjoin"; 1290 1291 $selectsql = ($messagesearch ? $messagesearch . " AND " : ""). 1292 " p.discussion = d.id 1293 AND p.userid = u.id 1294 AND $selectdiscussion 1295 $extrasql"; 1296 1297 $countsql = "SELECT COUNT(*) 1298 FROM $fromsql 1299 WHERE $selectsql"; 1300 1301 $allnames = get_all_user_name_fields(true, 'u'); 1302 $searchsql = "SELECT p.*, 1303 d.forum, 1304 $allnames, 1305 u.email, 1306 u.picture, 1307 u.imagealt 1308 FROM $fromsql 1309 WHERE $selectsql 1310 ORDER BY p.modified DESC"; 1311 1312 $totalcount = $DB->count_records_sql($countsql, $params); 1313 1314 return $DB->get_records_sql($searchsql, $params, $limitfrom, $limitnum); 1315 } 1316 1317 /** 1318 * Get all the posts for a user in a forum suitable for forum_print_post 1319 * 1320 * @global object 1321 * @global object 1322 * @uses CONTEXT_MODULE 1323 * @return array 1324 */ 1325 function forum_get_user_posts($forumid, $userid) { 1326 global $CFG, $DB; 1327 1328 $timedsql = ""; 1329 $params = array($forumid, $userid); 1330 1331 if (!empty($CFG->forum_enabletimedposts)) { 1332 $cm = get_coursemodule_from_instance('forum', $forumid); 1333 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) { 1334 $now = time(); 1335 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))"; 1336 $params[] = $now; 1337 $params[] = $now; 1338 } 1339 } 1340 1341 $allnames = get_all_user_name_fields(true, 'u'); 1342 return $DB->get_records_sql("SELECT p.*, d.forum, $allnames, u.email, u.picture, u.imagealt 1343 FROM {forum} f 1344 JOIN {forum_discussions} d ON d.forum = f.id 1345 JOIN {forum_posts} p ON p.discussion = d.id 1346 JOIN {user} u ON u.id = p.userid 1347 WHERE f.id = ? 1348 AND p.userid = ? 1349 $timedsql 1350 ORDER BY p.modified ASC", $params); 1351 } 1352 1353 /** 1354 * Get all the discussions user participated in 1355 * 1356 * @global object 1357 * @global object 1358 * @uses CONTEXT_MODULE 1359 * @param int $forumid 1360 * @param int $userid 1361 * @return array Array or false 1362 */ 1363 function forum_get_user_involved_discussions($forumid, $userid) { 1364 global $CFG, $DB; 1365 1366 $timedsql = ""; 1367 $params = array($forumid, $userid); 1368 if (!empty($CFG->forum_enabletimedposts)) { 1369 $cm = get_coursemodule_from_instance('forum', $forumid); 1370 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) { 1371 $now = time(); 1372 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))"; 1373 $params[] = $now; 1374 $params[] = $now; 1375 } 1376 } 1377 1378 return $DB->get_records_sql("SELECT DISTINCT d.* 1379 FROM {forum} f 1380 JOIN {forum_discussions} d ON d.forum = f.id 1381 JOIN {forum_posts} p ON p.discussion = d.id 1382 WHERE f.id = ? 1383 AND p.userid = ? 1384 $timedsql", $params); 1385 } 1386 1387 /** 1388 * Get all the posts for a user in a forum suitable for forum_print_post 1389 * 1390 * @global object 1391 * @global object 1392 * @param int $forumid 1393 * @param int $userid 1394 * @return array of counts or false 1395 */ 1396 function forum_count_user_posts($forumid, $userid) { 1397 global $CFG, $DB; 1398 1399 $timedsql = ""; 1400 $params = array($forumid, $userid); 1401 if (!empty($CFG->forum_enabletimedposts)) { 1402 $cm = get_coursemodule_from_instance('forum', $forumid); 1403 if (!has_capability('mod/forum:viewhiddentimedposts' , context_module::instance($cm->id))) { 1404 $now = time(); 1405 $timedsql = "AND (d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?))"; 1406 $params[] = $now; 1407 $params[] = $now; 1408 } 1409 } 1410 1411 return $DB->get_record_sql("SELECT COUNT(p.id) AS postcount, MAX(p.modified) AS lastpost 1412 FROM {forum} f 1413 JOIN {forum_discussions} d ON d.forum = f.id 1414 JOIN {forum_posts} p ON p.discussion = d.id 1415 JOIN {user} u ON u.id = p.userid 1416 WHERE f.id = ? 1417 AND p.userid = ? 1418 $timedsql", $params); 1419 } 1420 1421 /** 1422 * Given a log entry, return the forum post details for it. 1423 * 1424 * @global object 1425 * @global object 1426 * @param object $log 1427 * @return array|null 1428 */ 1429 function forum_get_post_from_log($log) { 1430 global $CFG, $DB; 1431 1432 $allnames = get_all_user_name_fields(true, 'u'); 1433 if ($log->action == "add post") { 1434 1435 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture 1436 FROM {forum_discussions} d, 1437 {forum_posts} p, 1438 {forum} f, 1439 {user} u 1440 WHERE p.id = ? 1441 AND d.id = p.discussion 1442 AND p.userid = u.id 1443 AND u.deleted <> '1' 1444 AND f.id = d.forum", array($log->info)); 1445 1446 1447 } else if ($log->action == "add discussion") { 1448 1449 return $DB->get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, $allnames, u.email, u.picture 1450 FROM {forum_discussions} d, 1451 {forum_posts} p, 1452 {forum} f, 1453 {user} u 1454 WHERE d.id = ? 1455 AND d.firstpost = p.id 1456 AND p.userid = u.id 1457 AND u.deleted <> '1' 1458 AND f.id = d.forum", array($log->info)); 1459 } 1460 return NULL; 1461 } 1462 1463 /** 1464 * Given a discussion id, return the first post from the discussion 1465 * 1466 * @global object 1467 * @global object 1468 * @param int $dicsussionid 1469 * @return array 1470 */ 1471 function forum_get_firstpost_from_discussion($discussionid) { 1472 global $CFG, $DB; 1473 1474 return $DB->get_record_sql("SELECT p.* 1475 FROM {forum_discussions} d, 1476 {forum_posts} p 1477 WHERE d.id = ? 1478 AND d.firstpost = p.id ", array($discussionid)); 1479 } 1480 1481 /** 1482 * Returns an array of counts of replies to each discussion 1483 * 1484 * @param int $forumid 1485 * @param string $forumsort 1486 * @param int $limit 1487 * @param int $page 1488 * @param int $perpage 1489 * @param boolean $canseeprivatereplies Whether the current user can see private replies. 1490 * @return array 1491 */ 1492 function forum_count_discussion_replies($forumid, $forumsort = "", $limit = -1, $page = -1, $perpage = 0, 1493 $canseeprivatereplies = false) { 1494 global $CFG, $DB, $USER; 1495 1496 if ($limit > 0) { 1497 $limitfrom = 0; 1498 $limitnum = $limit; 1499 } else if ($page != -1) { 1500 $limitfrom = $page*$perpage; 1501 $limitnum = $perpage; 1502 } else { 1503 $limitfrom = 0; 1504 $limitnum = 0; 1505 } 1506 1507 if ($forumsort == "") { 1508 $orderby = ""; 1509 $groupby = ""; 1510 1511 } else { 1512 $orderby = "ORDER BY $forumsort"; 1513 $groupby = ", ".strtolower($forumsort); 1514 $groupby = str_replace('desc', '', $groupby); 1515 $groupby = str_replace('asc', '', $groupby); 1516 } 1517 1518 $params = ['forumid' => $forumid]; 1519 1520 if (!$canseeprivatereplies) { 1521 $privatewhere = ' AND (p.privatereplyto = :currentuser1 OR p.userid = :currentuser2 OR p.privatereplyto = 0)'; 1522 $params['currentuser1'] = $USER->id; 1523 $params['currentuser2'] = $USER->id; 1524 } else { 1525 $privatewhere = ''; 1526 } 1527 1528 if (($limitfrom == 0 and $limitnum == 0) or $forumsort == "") { 1529 $sql = "SELECT p.discussion, COUNT(p.id) AS replies, MAX(p.id) AS lastpostid 1530 FROM {forum_posts} p 1531 JOIN {forum_discussions} d ON p.discussion = d.id 1532 WHERE p.parent > 0 AND d.forum = :forumid 1533 $privatewhere 1534 GROUP BY p.discussion"; 1535 return $DB->get_records_sql($sql, $params); 1536 1537 } else { 1538 $sql = "SELECT p.discussion, (COUNT(p.id) - 1) AS replies, MAX(p.id) AS lastpostid 1539 FROM {forum_posts} p 1540 JOIN {forum_discussions} d ON p.discussion = d.id 1541 WHERE d.forum = :forumid 1542 $privatewhere 1543 GROUP BY p.discussion $groupby $orderby"; 1544 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum); 1545 } 1546 } 1547 1548 /** 1549 * @global object 1550 * @global object 1551 * @global object 1552 * @staticvar array $cache 1553 * @param object $forum 1554 * @param object $cm 1555 * @param object $course 1556 * @return mixed 1557 */ 1558 function forum_count_discussions($forum, $cm, $course) { 1559 global $CFG, $DB, $USER; 1560 1561 static $cache = array(); 1562 1563 $now = floor(time() / 60) * 60; // DB Cache Friendly. 1564 1565 $params = array($course->id); 1566 1567 if (!isset($cache[$course->id])) { 1568 if (!empty($CFG->forum_enabletimedposts)) { 1569 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)"; 1570 $params[] = $now; 1571 $params[] = $now; 1572 } else { 1573 $timedsql = ""; 1574 } 1575 1576 $sql = "SELECT f.id, COUNT(d.id) as dcount 1577 FROM {forum} f 1578 JOIN {forum_discussions} d ON d.forum = f.id 1579 WHERE f.course = ? 1580 $timedsql 1581 GROUP BY f.id"; 1582 1583 if ($counts = $DB->get_records_sql($sql, $params)) { 1584 foreach ($counts as $count) { 1585 $counts[$count->id] = $count->dcount; 1586 } 1587 $cache[$course->id] = $counts; 1588 } else { 1589 $cache[$course->id] = array(); 1590 } 1591 } 1592 1593 if (empty($cache[$course->id][$forum->id])) { 1594 return 0; 1595 } 1596 1597 $groupmode = groups_get_activity_groupmode($cm, $course); 1598 1599 if ($groupmode != SEPARATEGROUPS) { 1600 return $cache[$course->id][$forum->id]; 1601 } 1602 1603 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) { 1604 return $cache[$course->id][$forum->id]; 1605 } 1606 1607 require_once($CFG->dirroot.'/course/lib.php'); 1608 1609 $modinfo = get_fast_modinfo($course); 1610 1611 $mygroups = $modinfo->get_groups($cm->groupingid); 1612 1613 // add all groups posts 1614 $mygroups[-1] = -1; 1615 1616 list($mygroups_sql, $params) = $DB->get_in_or_equal($mygroups); 1617 $params[] = $forum->id; 1618 1619 if (!empty($CFG->forum_enabletimedposts)) { 1620 $timedsql = "AND d.timestart < $now AND (d.timeend = 0 OR d.timeend > $now)"; 1621 $params[] = $now; 1622 $params[] = $now; 1623 } else { 1624 $timedsql = ""; 1625 } 1626 1627 $sql = "SELECT COUNT(d.id) 1628 FROM {forum_discussions} d 1629 WHERE d.groupid $mygroups_sql AND d.forum = ? 1630 $timedsql"; 1631 1632 return $DB->get_field_sql($sql, $params); 1633 } 1634 1635 /** 1636 * Get all discussions in a forum 1637 * 1638 * @global object 1639 * @global object 1640 * @global object 1641 * @uses CONTEXT_MODULE 1642 * @uses VISIBLEGROUPS 1643 * @param object $cm 1644 * @param string $forumsort 1645 * @param bool $fullpost 1646 * @param int $unused 1647 * @param int $limit 1648 * @param bool $userlastmodified 1649 * @param int $page 1650 * @param int $perpage 1651 * @param int $groupid if groups enabled, get discussions for this group overriding the current group. 1652 * Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups 1653 * @param int $updatedsince retrieve only discussions updated since the given time 1654 * @return array 1655 */ 1656 function forum_get_discussions($cm, $forumsort="", $fullpost=true, $unused=-1, $limit=-1, 1657 $userlastmodified=false, $page=-1, $perpage=0, $groupid = -1, 1658 $updatedsince = 0) { 1659 global $CFG, $DB, $USER; 1660 1661 $timelimit = ''; 1662 1663 $now = floor(time() / 60) * 60; 1664 $params = array($cm->instance); 1665 1666 $modcontext = context_module::instance($cm->id); 1667 1668 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) { /// User must have perms to view discussions 1669 return array(); 1670 } 1671 1672 if (!empty($CFG->forum_enabletimedposts)) { /// Users must fulfill timed posts 1673 1674 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) { 1675 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))"; 1676 $params[] = $now; 1677 $params[] = $now; 1678 if (isloggedin()) { 1679 $timelimit .= " OR d.userid = ?"; 1680 $params[] = $USER->id; 1681 } 1682 $timelimit .= ")"; 1683 } 1684 } 1685 1686 if ($limit > 0) { 1687 $limitfrom = 0; 1688 $limitnum = $limit; 1689 } else if ($page != -1) { 1690 $limitfrom = $page*$perpage; 1691 $limitnum = $perpage; 1692 } else { 1693 $limitfrom = 0; 1694 $limitnum = 0; 1695 } 1696 1697 $groupmode = groups_get_activity_groupmode($cm); 1698 1699 if ($groupmode) { 1700 1701 if (empty($modcontext)) { 1702 $modcontext = context_module::instance($cm->id); 1703 } 1704 1705 // Special case, we received a groupid to override currentgroup. 1706 if ($groupid > 0) { 1707 $course = get_course($cm->course); 1708 if (!groups_group_visible($groupid, $course, $cm)) { 1709 // User doesn't belong to this group, return nothing. 1710 return array(); 1711 } 1712 $currentgroup = $groupid; 1713 } else if ($groupid === -1) { 1714 $currentgroup = groups_get_activity_group($cm); 1715 } else { 1716 // Get discussions for all groups current user can see. 1717 $currentgroup = null; 1718 } 1719 1720 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) { 1721 if ($currentgroup) { 1722 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)"; 1723 $params[] = $currentgroup; 1724 } else { 1725 $groupselect = ""; 1726 } 1727 1728 } else { 1729 // Separate groups. 1730 1731 // Get discussions for all groups current user can see. 1732 if ($currentgroup === null) { 1733 $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id')); 1734 if (empty($mygroups)) { 1735 $groupselect = "AND d.groupid = -1"; 1736 } else { 1737 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups); 1738 $groupselect = "AND (d.groupid = -1 OR d.groupid $insqlgroups)"; 1739 $params = array_merge($params, $inparamsgroups); 1740 } 1741 } else if ($currentgroup) { 1742 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)"; 1743 $params[] = $currentgroup; 1744 } else { 1745 $groupselect = "AND d.groupid = -1"; 1746 } 1747 } 1748 } else { 1749 $groupselect = ""; 1750 } 1751 if (empty($forumsort)) { 1752 $forumsort = forum_get_default_sort_order(); 1753 } 1754 if (empty($fullpost)) { 1755 $postdata = "p.id, p.subject, p.modified, p.discussion, p.userid, p.created"; 1756 } else { 1757 $postdata = "p.*"; 1758 } 1759 1760 if (empty($userlastmodified)) { // We don't need to know this 1761 $umfields = ""; 1762 $umtable = ""; 1763 } else { 1764 $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture, 1765 um.imagealt AS umimagealt'; 1766 $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)"; 1767 } 1768 1769 $updatedsincesql = ''; 1770 if (!empty($updatedsince)) { 1771 $updatedsincesql = 'AND d.timemodified > ?'; 1772 $params[] = $updatedsince; 1773 } 1774 1775 $discussionfields = "d.id as discussionid, d.course, d.forum, d.name, d.firstpost, d.groupid, d.assessed," . 1776 " d.timemodified, d.usermodified, d.timestart, d.timeend, d.pinned, d.timelocked"; 1777 1778 $allnames = get_all_user_name_fields(true, 'u'); 1779 $sql = "SELECT $postdata, $discussionfields, 1780 $allnames, u.email, u.picture, u.imagealt $umfields 1781 FROM {forum_discussions} d 1782 JOIN {forum_posts} p ON p.discussion = d.id 1783 JOIN {user} u ON p.userid = u.id 1784 $umtable 1785 WHERE d.forum = ? AND p.parent = 0 1786 $timelimit $groupselect $updatedsincesql 1787 ORDER BY $forumsort, d.id DESC"; 1788 1789 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum); 1790 } 1791 1792 /** 1793 * Gets the neighbours (previous and next) of a discussion. 1794 * 1795 * The calculation is based on the timemodified when time modified or time created is identical 1796 * It will revert to using the ID to sort consistently. This is better tha skipping a discussion. 1797 * 1798 * For blog-style forums, the calculation is based on the original creation time of the 1799 * blog post. 1800 * 1801 * Please note that this does not check whether or not the discussion passed is accessible 1802 * by the user, it simply uses it as a reference to find the neighbours. On the other hand, 1803 * the returned neighbours are checked and are accessible to the current user. 1804 * 1805 * @param object $cm The CM record. 1806 * @param object $discussion The discussion record. 1807 * @param object $forum The forum instance record. 1808 * @return array That always contains the keys 'prev' and 'next'. When there is a result 1809 * they contain the record with minimal information such as 'id' and 'name'. 1810 * When the neighbour is not found the value is false. 1811 */ 1812 function forum_get_discussion_neighbours($cm, $discussion, $forum) { 1813 global $CFG, $DB, $USER; 1814 1815 if ($cm->instance != $discussion->forum or $discussion->forum != $forum->id or $forum->id != $cm->instance) { 1816 throw new coding_exception('Discussion is not part of the same forum.'); 1817 } 1818 1819 $neighbours = array('prev' => false, 'next' => false); 1820 $now = floor(time() / 60) * 60; 1821 $params = array(); 1822 1823 $modcontext = context_module::instance($cm->id); 1824 $groupmode = groups_get_activity_groupmode($cm); 1825 $currentgroup = groups_get_activity_group($cm); 1826 1827 // Users must fulfill timed posts. 1828 $timelimit = ''; 1829 if (!empty($CFG->forum_enabletimedposts)) { 1830 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) { 1831 $timelimit = ' AND ((d.timestart <= :tltimestart AND (d.timeend = 0 OR d.timeend > :tltimeend))'; 1832 $params['tltimestart'] = $now; 1833 $params['tltimeend'] = $now; 1834 if (isloggedin()) { 1835 $timelimit .= ' OR d.userid = :tluserid'; 1836 $params['tluserid'] = $USER->id; 1837 } 1838 $timelimit .= ')'; 1839 } 1840 } 1841 1842 // Limiting to posts accessible according to groups. 1843 $groupselect = ''; 1844 if ($groupmode) { 1845 if ($groupmode == VISIBLEGROUPS || has_capability('moodle/site:accessallgroups', $modcontext)) { 1846 if ($currentgroup) { 1847 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)'; 1848 $params['groupid'] = $currentgroup; 1849 } 1850 } else { 1851 if ($currentgroup) { 1852 $groupselect = 'AND (d.groupid = :groupid OR d.groupid = -1)'; 1853 $params['groupid'] = $currentgroup; 1854 } else { 1855 $groupselect = 'AND d.groupid = -1'; 1856 } 1857 } 1858 } 1859 1860 $params['forumid'] = $cm->instance; 1861 $params['discid1'] = $discussion->id; 1862 $params['discid2'] = $discussion->id; 1863 $params['discid3'] = $discussion->id; 1864 $params['discid4'] = $discussion->id; 1865 $params['disctimecompare1'] = $discussion->timemodified; 1866 $params['disctimecompare2'] = $discussion->timemodified; 1867 $params['pinnedstate1'] = (int) $discussion->pinned; 1868 $params['pinnedstate2'] = (int) $discussion->pinned; 1869 $params['pinnedstate3'] = (int) $discussion->pinned; 1870 $params['pinnedstate4'] = (int) $discussion->pinned; 1871 1872 $sql = "SELECT d.id, d.name, d.timemodified, d.groupid, d.timestart, d.timeend 1873 FROM {forum_discussions} d 1874 JOIN {forum_posts} p ON d.firstpost = p.id 1875 WHERE d.forum = :forumid 1876 AND d.id <> :discid1 1877 $timelimit 1878 $groupselect"; 1879 $comparefield = "d.timemodified"; 1880 $comparevalue = ":disctimecompare1"; 1881 $comparevalue2 = ":disctimecompare2"; 1882 if (!empty($CFG->forum_enabletimedposts)) { 1883 // Here we need to take into account the release time (timestart) 1884 // if one is set, of the neighbouring posts and compare it to the 1885 // timestart or timemodified of *this* post depending on if the 1886 // release date of this post is in the future or not. 1887 // This stops discussions that appear later because of the 1888 // timestart value from being buried under discussions that were 1889 // made afterwards. 1890 $comparefield = "CASE WHEN d.timemodified < d.timestart 1891 THEN d.timestart ELSE d.timemodified END"; 1892 if ($discussion->timemodified < $discussion->timestart) { 1893 // Normally we would just use the timemodified for sorting 1894 // discussion posts. However, when timed discussions are enabled, 1895 // then posts need to be sorted base on the later of timemodified 1896 // or the release date of the post (timestart). 1897 $params['disctimecompare1'] = $discussion->timestart; 1898 $params['disctimecompare2'] = $discussion->timestart; 1899 } 1900 } 1901 $orderbydesc = forum_get_default_sort_order(true, $comparefield, 'd', false); 1902 $orderbyasc = forum_get_default_sort_order(false, $comparefield, 'd', false); 1903 1904 if ($forum->type === 'blog') { 1905 $subselect = "SELECT pp.created 1906 FROM {forum_discussions} dd 1907 JOIN {forum_posts} pp ON dd.firstpost = pp.id "; 1908 1909 $subselectwhere1 = " WHERE dd.id = :discid3"; 1910 $subselectwhere2 = " WHERE dd.id = :discid4"; 1911 1912 $comparefield = "p.created"; 1913 1914 $sub1 = $subselect.$subselectwhere1; 1915 $comparevalue = "($sub1)"; 1916 1917 $sub2 = $subselect.$subselectwhere2; 1918 $comparevalue2 = "($sub2)"; 1919 1920 $orderbydesc = "d.pinned, p.created DESC"; 1921 $orderbyasc = "d.pinned, p.created ASC"; 1922 } 1923 1924 $prevsql = $sql . " AND ( (($comparefield < $comparevalue) AND :pinnedstate1 = d.pinned) 1925 OR ($comparefield = $comparevalue2 AND (d.pinned = 0 OR d.pinned = :pinnedstate4) AND d.id < :discid2) 1926 OR (d.pinned = 0 AND d.pinned <> :pinnedstate2)) 1927 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbydesc, d.id DESC"; 1928 1929 $nextsql = $sql . " AND ( (($comparefield > $comparevalue) AND :pinnedstate1 = d.pinned) 1930 OR ($comparefield = $comparevalue2 AND (d.pinned = 1 OR d.pinned = :pinnedstate4) AND d.id > :discid2) 1931 OR (d.pinned = 1 AND d.pinned <> :pinnedstate2)) 1932 ORDER BY CASE WHEN d.pinned = :pinnedstate3 THEN 1 ELSE 0 END DESC, $orderbyasc, d.id ASC"; 1933 1934 $neighbours['prev'] = $DB->get_record_sql($prevsql, $params, IGNORE_MULTIPLE); 1935 $neighbours['next'] = $DB->get_record_sql($nextsql, $params, IGNORE_MULTIPLE); 1936 return $neighbours; 1937 } 1938 1939 /** 1940 * Get the sql to use in the ORDER BY clause for forum discussions. 1941 * 1942 * This has the ordering take timed discussion windows into account. 1943 * 1944 * @param bool $desc True for DESC, False for ASC. 1945 * @param string $compare The field in the SQL to compare to normally sort by. 1946 * @param string $prefix The prefix being used for the discussion table. 1947 * @param bool $pinned sort pinned posts to the top 1948 * @return string 1949 */ 1950 function forum_get_default_sort_order($desc = true, $compare = 'd.timemodified', $prefix = 'd', $pinned = true) { 1951 global $CFG; 1952 1953 if (!empty($prefix)) { 1954 $prefix .= '.'; 1955 } 1956 1957 $dir = $desc ? 'DESC' : 'ASC'; 1958 1959 if ($pinned == true) { 1960 $pinned = "{$prefix}pinned DESC,"; 1961 } else { 1962 $pinned = ''; 1963 } 1964 1965 $sort = "{$prefix}timemodified"; 1966 if (!empty($CFG->forum_enabletimedposts)) { 1967 $sort = "CASE WHEN {$compare} < {$prefix}timestart 1968 THEN {$prefix}timestart 1969 ELSE {$compare} 1970 END"; 1971 } 1972 return "$pinned $sort $dir"; 1973 } 1974 1975 /** 1976 * 1977 * @global object 1978 * @global object 1979 * @global object 1980 * @uses CONTEXT_MODULE 1981 * @uses VISIBLEGROUPS 1982 * @param object $cm 1983 * @return array 1984 */ 1985 function forum_get_discussions_unread($cm) { 1986 global $CFG, $DB, $USER; 1987 1988 $now = floor(time() / 60) * 60; 1989 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60); 1990 1991 $params = array(); 1992 $groupmode = groups_get_activity_groupmode($cm); 1993 $currentgroup = groups_get_activity_group($cm); 1994 1995 if ($groupmode) { 1996 $modcontext = context_module::instance($cm->id); 1997 1998 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) { 1999 if ($currentgroup) { 2000 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)"; 2001 $params['currentgroup'] = $currentgroup; 2002 } else { 2003 $groupselect = ""; 2004 } 2005 2006 } else { 2007 //separate groups without access all 2008 if ($currentgroup) { 2009 $groupselect = "AND (d.groupid = :currentgroup OR d.groupid = -1)"; 2010 $params['currentgroup'] = $currentgroup; 2011 } else { 2012 $groupselect = "AND d.groupid = -1"; 2013 } 2014 } 2015 } else { 2016 $groupselect = ""; 2017 } 2018 2019 if (!empty($CFG->forum_enabletimedposts)) { 2020 $timedsql = "AND d.timestart < :now1 AND (d.timeend = 0 OR d.timeend > :now2)"; 2021 $params['now1'] = $now; 2022 $params['now2'] = $now; 2023 } else { 2024 $timedsql = ""; 2025 } 2026 2027 $sql = "SELECT d.id, COUNT(p.id) AS unread 2028 FROM {forum_discussions} d 2029 JOIN {forum_posts} p ON p.discussion = d.id 2030 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = $USER->id) 2031 WHERE d.forum = {$cm->instance} 2032 AND p.modified >= :cutoffdate AND r.id is NULL 2033 $groupselect 2034 $timedsql 2035 GROUP BY d.id"; 2036 $params['cutoffdate'] = $cutoffdate; 2037 2038 if ($unreads = $DB->get_records_sql($sql, $params)) { 2039 foreach ($unreads as $unread) { 2040 $unreads[$unread->id] = $unread->unread; 2041 } 2042 return $unreads; 2043 } else { 2044 return array(); 2045 } 2046 } 2047 2048 /** 2049 * @global object 2050 * @global object 2051 * @global object 2052 * @uses CONEXT_MODULE 2053 * @uses VISIBLEGROUPS 2054 * @param object $cm 2055 * @return array 2056 */ 2057 function forum_get_discussions_count($cm) { 2058 global $CFG, $DB, $USER; 2059 2060 $now = floor(time() / 60) * 60; 2061 $params = array($cm->instance); 2062 $groupmode = groups_get_activity_groupmode($cm); 2063 $currentgroup = groups_get_activity_group($cm); 2064 2065 if ($groupmode) { 2066 $modcontext = context_module::instance($cm->id); 2067 2068 if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) { 2069 if ($currentgroup) { 2070 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)"; 2071 $params[] = $currentgroup; 2072 } else { 2073 $groupselect = ""; 2074 } 2075 2076 } else { 2077 //seprate groups without access all 2078 if ($currentgroup) { 2079 $groupselect = "AND (d.groupid = ? OR d.groupid = -1)"; 2080 $params[] = $currentgroup; 2081 } else { 2082 $groupselect = "AND d.groupid = -1"; 2083 } 2084 } 2085 } else { 2086 $groupselect = ""; 2087 } 2088 2089 $timelimit = ""; 2090 2091 if (!empty($CFG->forum_enabletimedposts)) { 2092 2093 $modcontext = context_module::instance($cm->id); 2094 2095 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) { 2096 $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))"; 2097 $params[] = $now; 2098 $params[] = $now; 2099 if (isloggedin()) { 2100 $timelimit .= " OR d.userid = ?"; 2101 $params[] = $USER->id; 2102 } 2103 $timelimit .= ")"; 2104 } 2105 } 2106 2107 $sql = "SELECT COUNT(d.id) 2108 FROM {forum_discussions} d 2109 JOIN {forum_posts} p ON p.discussion = d.id 2110 WHERE d.forum = ? AND p.parent = 0 2111 $groupselect $timelimit"; 2112 2113 return $DB->get_field_sql($sql, $params); 2114 } 2115 2116 2117 // OTHER FUNCTIONS /////////////////////////////////////////////////////////// 2118 2119 2120 /** 2121 * @global object 2122 * @global object 2123 * @param int $courseid 2124 * @param string $type 2125 */ 2126 function forum_get_course_forum($courseid, $type) { 2127 // How to set up special 1-per-course forums 2128 global $CFG, $DB, $OUTPUT, $USER; 2129 2130 if ($forums = $DB->get_records_select("forum", "course = ? AND type = ?", array($courseid, $type), "id ASC")) { 2131 // There should always only be ONE, but with the right combination of 2132 // errors there might be more. In this case, just return the oldest one (lowest ID). 2133 foreach ($forums as $forum) { 2134 return $forum; // ie the first one 2135 } 2136 } 2137 2138 // Doesn't exist, so create one now. 2139 $forum = new stdClass(); 2140 $forum->course = $courseid; 2141 $forum->type = "$type"; 2142 if (!empty($USER->htmleditor)) { 2143 $forum->introformat = $USER->htmleditor; 2144 } 2145 switch ($forum->type) { 2146 case "news": 2147 $forum->name = get_string("namenews", "forum"); 2148 $forum->intro = get_string("intronews", "forum"); 2149 $forum->introformat = FORMAT_HTML; 2150 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE; 2151 $forum->assessed = 0; 2152 if ($courseid == SITEID) { 2153 $forum->name = get_string("sitenews"); 2154 $forum->forcesubscribe = 0; 2155 } 2156 break; 2157 case "social": 2158 $forum->name = get_string("namesocial", "forum"); 2159 $forum->intro = get_string("introsocial", "forum"); 2160 $forum->introformat = FORMAT_HTML; 2161 $forum->assessed = 0; 2162 $forum->forcesubscribe = 0; 2163 break; 2164 case "blog": 2165 $forum->name = get_string('blogforum', 'forum'); 2166 $forum->intro = get_string('introblog', 'forum'); 2167 $forum->introformat = FORMAT_HTML; 2168 $forum->assessed = 0; 2169 $forum->forcesubscribe = 0; 2170 break; 2171 default: 2172 echo $OUTPUT->notification("That forum type doesn't exist!"); 2173 return false; 2174 break; 2175 } 2176 2177 $forum->timemodified = time(); 2178 $forum->id = $DB->insert_record("forum", $forum); 2179 2180 if (! $module = $DB->get_record("modules", array("name" => "forum"))) { 2181 echo $OUTPUT->notification("Could not find forum module!!"); 2182 return false; 2183 } 2184 $mod = new stdClass(); 2185 $mod->course = $courseid; 2186 $mod->module = $module->id; 2187 $mod->instance = $forum->id; 2188 $mod->section = 0; 2189 include_once("$CFG->dirroot/course/lib.php"); 2190 if (! $mod->coursemodule = add_course_module($mod) ) { 2191 echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'"); 2192 return false; 2193 } 2194 $sectionid = course_add_cm_to_section($courseid, $mod->coursemodule, 0); 2195 return $DB->get_record("forum", array("id" => "$forum->id")); 2196 } 2197 2198 /** 2199 * Return rating related permissions 2200 * 2201 * @param string $options the context id 2202 * @return array an associative array of the user's rating permissions 2203 */ 2204 function forum_rating_permissions($contextid, $component, $ratingarea) { 2205 $context = context::instance_by_id($contextid, MUST_EXIST); 2206 if ($component != 'mod_forum' || $ratingarea != 'post') { 2207 // We don't know about this component/ratingarea so just return null to get the 2208 // default restrictive permissions. 2209 return null; 2210 } 2211 return array( 2212 'view' => has_capability('mod/forum:viewrating', $context), 2213 'viewany' => has_capability('mod/forum:viewanyrating', $context), 2214 'viewall' => has_capability('mod/forum:viewallratings', $context), 2215 'rate' => has_capability('mod/forum:rate', $context) 2216 ); 2217 } 2218 2219 /** 2220 * Validates a submitted rating 2221 * @param array $params submitted data 2222 * context => object the context in which the rated items exists [required] 2223 * component => The component for this module - should always be mod_forum [required] 2224 * ratingarea => object the context in which the rated items exists [required] 2225 * 2226 * itemid => int the ID of the object being rated [required] 2227 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required] 2228 * rating => int the submitted rating [required] 2229 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required] 2230 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required] 2231 * @return boolean true if the rating is valid. Will throw rating_exception if not 2232 */ 2233 function forum_rating_validate($params) { 2234 global $DB, $USER; 2235 2236 // Check the component is mod_forum 2237 if ($params['component'] != 'mod_forum') { 2238 throw new rating_exception('invalidcomponent'); 2239 } 2240 2241 // Check the ratingarea is post (the only rating area in forum) 2242 if ($params['ratingarea'] != 'post') { 2243 throw new rating_exception('invalidratingarea'); 2244 } 2245 2246 // Check the rateduserid is not the current user .. you can't rate your own posts 2247 if ($params['rateduserid'] == $USER->id) { 2248 throw new rating_exception('nopermissiontorate'); 2249 } 2250 2251 // Fetch all the related records ... we need to do this anyway to call forum_user_can_see_post 2252 $post = $DB->get_record('forum_posts', array('id' => $params['itemid'], 'userid' => $params['rateduserid']), '*', MUST_EXIST); 2253 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST); 2254 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST); 2255 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); 2256 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST); 2257 $context = context_module::instance($cm->id); 2258 2259 // Make sure the context provided is the context of the forum 2260 if ($context->id != $params['context']->id) { 2261 throw new rating_exception('invalidcontext'); 2262 } 2263 2264 if ($forum->scale != $params['scaleid']) { 2265 //the scale being submitted doesnt match the one in the database 2266 throw new rating_exception('invalidscaleid'); 2267 } 2268 2269 // check the item we're rating was created in the assessable time window 2270 if (!empty($forum->assesstimestart) && !empty($forum->assesstimefinish)) { 2271 if ($post->created < $forum->assesstimestart || $post->created > $forum->assesstimefinish) { 2272 throw new rating_exception('notavailable'); 2273 } 2274 } 2275 2276 //check that the submitted rating is valid for the scale 2277 2278 // lower limit 2279 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) { 2280 throw new rating_exception('invalidnum'); 2281 } 2282 2283 // upper limit 2284 if ($forum->scale < 0) { 2285 //its a custom scale 2286 $scalerecord = $DB->get_record('scale', array('id' => -$forum->scale)); 2287 if ($scalerecord) { 2288 $scalearray = explode(',', $scalerecord->scale); 2289 if ($params['rating'] > count($scalearray)) { 2290 throw new rating_exception('invalidnum'); 2291 } 2292 } else { 2293 throw new rating_exception('invalidscaleid'); 2294 } 2295 } else if ($params['rating'] > $forum->scale) { 2296 //if its numeric and submitted rating is above maximum 2297 throw new rating_exception('invalidnum'); 2298 } 2299 2300 // Make sure groups allow this user to see the item they're rating 2301 if ($discussion->groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used 2302 if (!groups_group_exists($discussion->groupid)) { // Can't find group 2303 throw new rating_exception('cannotfindgroup');//something is wrong 2304 } 2305 2306 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) { 2307 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS 2308 throw new rating_exception('notmemberofgroup'); 2309 } 2310 } 2311 2312 // perform some final capability checks 2313 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) { 2314 throw new rating_exception('nopermissiontorate'); 2315 } 2316 2317 return true; 2318 } 2319 2320 /** 2321 * Can the current user see ratings for a given itemid? 2322 * 2323 * @param array $params submitted data 2324 * contextid => int contextid [required] 2325 * component => The component for this module - should always be mod_forum [required] 2326 * ratingarea => object the context in which the rated items exists [required] 2327 * itemid => int the ID of the object being rated [required] 2328 * scaleid => int scale id [optional] 2329 * @return bool 2330 * @throws coding_exception 2331 * @throws rating_exception 2332 */ 2333 function mod_forum_rating_can_see_item_ratings($params) { 2334 global $DB, $USER; 2335 2336 // Check the component is mod_forum. 2337 if (!isset($params['component']) || $params['component'] != 'mod_forum') { 2338 throw new rating_exception('invalidcomponent'); 2339 } 2340 2341 // Check the ratingarea is post (the only rating area in forum). 2342 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'post') { 2343 throw new rating_exception('invalidratingarea'); 2344 } 2345 2346 if (!isset($params['itemid'])) { 2347 throw new rating_exception('invaliditemid'); 2348 } 2349 2350 $post = $DB->get_record('forum_posts', array('id' => $params['itemid']), '*', MUST_EXIST); 2351 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion), '*', MUST_EXIST); 2352 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST); 2353 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); 2354 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id , false, MUST_EXIST); 2355 2356 // Perform some final capability checks. 2357 if (!forum_user_can_see_post($forum, $discussion, $post, $USER, $cm)) { 2358 return false; 2359 } 2360 2361 return true; 2362 } 2363 2364 /** 2365 * This function prints the overview of a discussion in the forum listing. 2366 * It needs some discussion information and some post information, these 2367 * happen to be combined for efficiency in the $post parameter by the function 2368 * that calls this one: forum_print_latest_discussions() 2369 * 2370 * @global object 2371 * @global object 2372 * @param object $post The post object (passed by reference for speed). 2373 * @param object $forum The forum object. 2374 * @param int $group Current group. 2375 * @param string $datestring Format to use for the dates. 2376 * @param boolean $cantrack Is tracking enabled for this forum. 2377 * @param boolean $forumtracked Is the user tracking this forum. 2378 * @param boolean $canviewparticipants True if user has the viewparticipants permission for this course 2379 * @param boolean $canviewhiddentimedposts True if user has the viewhiddentimedposts permission for this forum 2380 */ 2381 function forum_print_discussion_header(&$post, $forum, $group = -1, $datestring = "", 2382 $cantrack = true, $forumtracked = true, $canviewparticipants = true, $modcontext = null, 2383 $canviewhiddentimedposts = false) { 2384 2385 global $COURSE, $USER, $CFG, $OUTPUT, $PAGE; 2386 2387 static $rowcount; 2388 static $strmarkalldread; 2389 2390 if (empty($modcontext)) { 2391 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) { 2392 print_error('invalidcoursemodule'); 2393 } 2394 $modcontext = context_module::instance($cm->id); 2395 } 2396 2397 if (!isset($rowcount)) { 2398 $rowcount = 0; 2399 $strmarkalldread = get_string('markalldread', 'forum'); 2400 } else { 2401 $rowcount = ($rowcount + 1) % 2; 2402 } 2403 2404 $post->subject = format_string($post->subject,true); 2405 2406 $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext); 2407 $timeddiscussion = !empty($CFG->forum_enabletimedposts) && ($post->timestart || $post->timeend); 2408 $timedoutsidewindow = ''; 2409 if ($timeddiscussion && ($post->timestart > time() || ($post->timeend != 0 && $post->timeend < time()))) { 2410 $timedoutsidewindow = ' dimmed_text'; 2411 } 2412 2413 echo "\n\n"; 2414 echo '<tr class="discussion r'.$rowcount.$timedoutsidewindow.'">'; 2415 2416 $topicclass = 'topic starter'; 2417 if (FORUM_DISCUSSION_PINNED == $post->pinned) { 2418 $topicclass .= ' pinned'; 2419 } 2420 echo '<td class="'.$topicclass.'">'; 2421 if (FORUM_DISCUSSION_PINNED == $post->pinned) { 2422 echo $OUTPUT->pix_icon('i/pinned', get_string('discussionpinned', 'forum'), 'mod_forum'); 2423 } 2424 $canalwaysseetimedpost = $USER->id == $post->userid || $canviewhiddentimedposts; 2425 if ($timeddiscussion && $canalwaysseetimedpost) { 2426 echo $PAGE->get_renderer('mod_forum')->timed_discussion_tooltip($post, empty($timedoutsidewindow)); 2427 } 2428 2429 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>'; 2430 echo "</td>\n"; 2431 2432 // Picture 2433 $postuser = new stdClass(); 2434 $postuserfields = explode(',', user_picture::fields()); 2435 $postuser = username_load_fields_from_object($postuser, $post, null, $postuserfields); 2436 $postuser->id = $post->userid; 2437 echo '<td class="author">'; 2438 echo '<div class="media">'; 2439 echo '<span class="float-left">'; 2440 echo $OUTPUT->user_picture($postuser, array('courseid'=>$forum->course)); 2441 echo '</span>'; 2442 // User name 2443 echo '<div class="media-body">'; 2444 $fullname = fullname($postuser, $canviewfullnames); 2445 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&course='.$forum->course.'">'.$fullname.'</a>'; 2446 echo '</div>'; 2447 echo '</div>'; 2448 echo "</td>\n"; 2449 2450 // Group picture 2451 if ($group !== -1) { // Groups are active - group is a group data object or NULL 2452 echo '<td class="picture group">'; 2453 if (!empty($group->picture) and empty($group->hidepicture)) { 2454 if ($canviewparticipants && $COURSE->groupmode) { 2455 $picturelink = true; 2456 } else { 2457 $picturelink = false; 2458 } 2459 print_group_picture($group, $forum->course, false, false, $picturelink); 2460 } else if (isset($group->id)) { 2461 if ($canviewparticipants && $COURSE->groupmode) { 2462 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&group='.$group->id.'">'.$group->name.'</a>'; 2463 } else { 2464 echo $group->name; 2465 } 2466 } 2467 echo "</td>\n"; 2468 } 2469 2470 if (has_capability('mod/forum:viewdiscussion', $modcontext)) { // Show the column with replies 2471 echo '<td class="replies">'; 2472 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'; 2473 echo $post->replies.'</a>'; 2474 echo "</td>\n"; 2475 2476 if ($cantrack) { 2477 echo '<td class="replies">'; 2478 if ($forumtracked) { 2479 if ($post->unread > 0) { 2480 echo '<span class="unread">'; 2481 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">'; 2482 echo $post->unread; 2483 echo '</a>'; 2484 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='. 2485 $forum->id.'&d='.$post->discussion.'&mark=read&return=/mod/forum/view.php&sesskey=' . 2486 sesskey() . '">' . $OUTPUT->pix_icon('t/markasread', $strmarkalldread) . '</a>'; 2487 echo '</span>'; 2488 } else { 2489 echo '<span class="read">'; 2490 echo $post->unread; 2491 echo '</span>'; 2492 } 2493 } else { 2494 echo '<span class="read">'; 2495 echo '-'; 2496 echo '</span>'; 2497 } 2498 echo "</td>\n"; 2499 } 2500 } 2501 2502 echo '<td class="lastpost">'; 2503 $usedate = (empty($post->timemodified)) ? $post->created : $post->timemodified; 2504 $parenturl = ''; 2505 $usermodified = new stdClass(); 2506 $usermodified->id = $post->usermodified; 2507 $usermodified = username_load_fields_from_object($usermodified, $post, 'um'); 2508 2509 // In QA forums we check that the user can view participants. 2510 if ($forum->type !== 'qanda' || $canviewparticipants) { 2511 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&course='.$forum->course.'">'. 2512 fullname($usermodified, $canviewfullnames).'</a><br />'; 2513 $parenturl = (empty($post->lastpostid)) ? '' : '&parent='.$post->lastpostid; 2514 } 2515 2516 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'. 2517 userdate_htmltime($usedate, $datestring).'</a>'; 2518 echo "</td>\n"; 2519 2520 // is_guest should be used here as this also checks whether the user is a guest in the current course. 2521 // Guests and visitors cannot subscribe - only enrolled users. 2522 if ((!is_guest($modcontext, $USER) && isloggedin()) && has_capability('mod/forum:viewdiscussion', $modcontext)) { 2523 // Discussion subscription. 2524 if (\mod_forum\subscriptions::is_subscribable($forum)) { 2525 echo '<td class="discussionsubscription">'; 2526 echo forum_get_discussion_subscription_icon($forum, $post->discussion); 2527 echo '</td>'; 2528 } 2529 } 2530 2531 echo "</tr>\n\n"; 2532 2533 } 2534 2535 /** 2536 * Return the markup for the discussion subscription toggling icon. 2537 * 2538 * @param stdClass $forum The forum object. 2539 * @param int $discussionid The discussion to create an icon for. 2540 * @return string The generated markup. 2541 */ 2542 function forum_get_discussion_subscription_icon($forum, $discussionid, $returnurl = null, $includetext = false) { 2543 global $USER, $OUTPUT, $PAGE; 2544 2545 if ($returnurl === null && $PAGE->url) { 2546 $returnurl = $PAGE->url->out(); 2547 } 2548 2549 $o = ''; 2550 $subscriptionstatus = \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussionid); 2551 $subscriptionlink = new moodle_url('/mod/forum/subscribe.php', array( 2552 'sesskey' => sesskey(), 2553 'id' => $forum->id, 2554 'd' => $discussionid, 2555 'returnurl' => $returnurl, 2556 )); 2557 2558 if ($includetext) { 2559 $o .= $subscriptionstatus ? get_string('subscribed', 'mod_forum') : get_string('notsubscribed', 'mod_forum'); 2560 } 2561 2562 if ($subscriptionstatus) { 2563 $output = $OUTPUT->pix_icon('t/subscribed', get_string('clicktounsubscribe', 'forum'), 'mod_forum'); 2564 if ($includetext) { 2565 $output .= get_string('subscribed', 'mod_forum'); 2566 } 2567 2568 return html_writer::link($subscriptionlink, $output, array( 2569 'title' => get_string('clicktounsubscribe', 'forum'), 2570 'class' => 'discussiontoggle btn btn-link', 2571 'data-forumid' => $forum->id, 2572 'data-discussionid' => $discussionid, 2573 'data-includetext' => $includetext, 2574 )); 2575 2576 } else { 2577 $output = $OUTPUT->pix_icon('t/unsubscribed', get_string('clicktosubscribe', 'forum'), 'mod_forum'); 2578 if ($includetext) { 2579 $output .= get_string('notsubscribed', 'mod_forum'); 2580 } 2581 2582 return html_writer::link($subscriptionlink, $output, array( 2583 'title' => get_string('clicktosubscribe', 'forum'), 2584 'class' => 'discussiontoggle btn btn-link', 2585 'data-forumid' => $forum->id, 2586 'data-discussionid' => $discussionid, 2587 'data-includetext' => $includetext, 2588 )); 2589 } 2590 } 2591 2592 /** 2593 * Return a pair of spans containing classes to allow the subscribe and 2594 * unsubscribe icons to be pre-loaded by a browser. 2595 * 2596 * @return string The generated markup 2597 */ 2598 function forum_get_discussion_subscription_icon_preloaders() { 2599 $o = ''; 2600 $o .= html_writer::span(' ', 'preload-subscribe'); 2601 $o .= html_writer::span(' ', 'preload-unsubscribe'); 2602 return $o; 2603 } 2604 2605 /** 2606 * Print the drop down that allows the user to select how they want to have 2607 * the discussion displayed. 2608 * 2609 * @param int $id forum id if $forumtype is 'single', 2610 * discussion id for any other forum type 2611 * @param mixed $mode forum layout mode 2612 * @param string $forumtype optional 2613 */ 2614 function forum_print_mode_form($id, $mode, $forumtype='') { 2615 global $OUTPUT; 2616 $useexperimentalui = get_user_preferences('forum_useexperimentalui', false); 2617 if ($forumtype == 'single') { 2618 $select = new single_select( 2619 new moodle_url("/mod/forum/view.php", 2620 array('f' => $id)), 2621 'mode', 2622 forum_get_layout_modes($useexperimentalui), 2623 $mode, 2624 null, 2625 "mode" 2626 ); 2627 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide')); 2628 $select->class = "forummode"; 2629 } else { 2630 $select = new single_select( 2631 new moodle_url("/mod/forum/discuss.php", 2632 array('d' => $id)), 2633 'mode', 2634 forum_get_layout_modes($useexperimentalui), 2635 $mode, 2636 null, 2637 "mode" 2638 ); 2639 $select->set_label(get_string('displaymode', 'forum'), array('class' => 'accesshide')); 2640 } 2641 echo $OUTPUT->render($select); 2642 } 2643 2644 /** 2645 * @global object 2646 * @param object $course 2647 * @param string $search 2648 * @return string 2649 */ 2650 function forum_search_form($course, $search='') { 2651 global $CFG, $PAGE; 2652 $forumsearch = new \mod_forum\output\quick_search_form($course->id, $search); 2653 $output = $PAGE->get_renderer('mod_forum'); 2654 return $output->render($forumsearch); 2655 } 2656 2657 2658 /** 2659 * @global object 2660 * @global object 2661 */ 2662 function forum_set_return() { 2663 global $CFG, $SESSION; 2664 2665 if (! isset($SESSION->fromdiscussion)) { 2666 $referer = get_local_referer(false); 2667 // If the referer is NOT a login screen then save it. 2668 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) { 2669 $SESSION->fromdiscussion = $referer; 2670 } 2671 } 2672 } 2673 2674 2675 /** 2676 * @global object 2677 * @param string|\moodle_url $default 2678 * @return string 2679 */ 2680 function forum_go_back_to($default) { 2681 global $SESSION; 2682 2683 if (!empty($SESSION->fromdiscussion)) { 2684 $returnto = $SESSION->fromdiscussion; 2685 unset($SESSION->fromdiscussion); 2686 return $returnto; 2687 } else { 2688 return $default; 2689 } 2690 } 2691 2692 /** 2693 * Given a discussion object that is being moved to $forumto, 2694 * this function checks all posts in that discussion 2695 * for attachments, and if any are found, these are 2696 * moved to the new forum directory. 2697 * 2698 * @global object 2699 * @param object $discussion 2700 * @param int $forumfrom source forum id 2701 * @param int $forumto target forum id 2702 * @return bool success 2703 */ 2704 function forum_move_attachments($discussion, $forumfrom, $forumto) { 2705 global $DB; 2706 2707 $fs = get_file_storage(); 2708 2709 $newcm = get_coursemodule_from_instance('forum', $forumto); 2710 $oldcm = get_coursemodule_from_instance('forum', $forumfrom); 2711 2712 $newcontext = context_module::instance($newcm->id); 2713 $oldcontext = context_module::instance($oldcm->id); 2714 2715 // loop through all posts, better not use attachment flag ;-) 2716 if ($posts = $DB->get_records('forum_posts', array('discussion'=>$discussion->id), '', 'id, attachment')) { 2717 foreach ($posts as $post) { 2718 $fs->move_area_files_to_new_context($oldcontext->id, 2719 $newcontext->id, 'mod_forum', 'post', $post->id); 2720 $attachmentsmoved = $fs->move_area_files_to_new_context($oldcontext->id, 2721 $newcontext->id, 'mod_forum', 'attachment', $post->id); 2722 if ($attachmentsmoved > 0 && $post->attachment != '1') { 2723 // Weird - let's fix it 2724 $post->attachment = '1'; 2725 $DB->update_record('forum_posts', $post); 2726 } else if ($attachmentsmoved == 0 && $post->attachment != '') { 2727 // Weird - let's fix it 2728 $post->attachment = ''; 2729 $DB->update_record('forum_posts', $post); 2730 } 2731 } 2732 } 2733 2734 return true; 2735 } 2736 2737 /** 2738 * Returns attachments as formated text/html optionally with separate images 2739 * 2740 * @global object 2741 * @global object 2742 * @global object 2743 * @param object $post 2744 * @param object $cm 2745 * @param string $type html/text/separateimages 2746 * @return mixed string or array of (html text withouth images and image HTML) 2747 */ 2748 function forum_print_attachments($post, $cm, $type) { 2749 global $CFG, $DB, $USER, $OUTPUT; 2750 2751 if (empty($post->attachment)) { 2752 return $type !== 'separateimages' ? '' : array('', ''); 2753 } 2754 2755 if (!in_array($type, array('separateimages', 'html', 'text'))) { 2756 return $type !== 'separateimages' ? '' : array('', ''); 2757 } 2758 2759 if (!$context = context_module::instance($cm->id)) { 2760 return $type !== 'separateimages' ? '' : array('', ''); 2761 } 2762 $strattachment = get_string('attachment', 'forum'); 2763 2764 $fs = get_file_storage(); 2765 2766 $imagereturn = ''; 2767 $output = ''; 2768 2769 $canexport = !empty($CFG->enableportfolios) && (has_capability('mod/forum:exportpost', $context) || ($post->userid == $USER->id && has_capability('mod/forum:exportownpost', $context))); 2770 2771 if ($canexport) { 2772 require_once($CFG->libdir.'/portfoliolib.php'); 2773 } 2774 2775 // We retrieve all files according to the time that they were created. In the case that several files were uploaded 2776 // at the sametime (e.g. in the case of drag/drop upload) we revert to using the filename. 2777 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "filename", false); 2778 if ($files) { 2779 if ($canexport) { 2780 $button = new portfolio_add_button(); 2781 } 2782 foreach ($files as $file) { 2783 $filename = $file->get_filename(); 2784 $mimetype = $file->get_mimetype(); 2785 $iconimage = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')); 2786 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$context->id.'/mod_forum/attachment/'.$post->id.'/'.$filename); 2787 2788 if ($type == 'html') { 2789 $output .= "<a href=\"$path\">$iconimage</a> "; 2790 $output .= "<a href=\"$path\">".s($filename)."</a>"; 2791 if ($canexport) { 2792 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum'); 2793 $button->set_format_by_file($file); 2794 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK); 2795 } 2796 $output .= "<br />"; 2797 2798 } else if ($type == 'text') { 2799 $output .= "$strattachment ".s($filename).":\n$path\n"; 2800 2801 } else { //'returnimages' 2802 if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) { 2803 // Image attachments don't get printed as links 2804 $imagereturn .= "<br /><img src=\"$path\" alt=\"\" />"; 2805 if ($canexport) { 2806 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum'); 2807 $button->set_format_by_file($file); 2808 $imagereturn .= $button->to_html(PORTFOLIO_ADD_ICON_LINK); 2809 } 2810 } else { 2811 $output .= "<a href=\"$path\">$iconimage</a> "; 2812 $output .= format_text("<a href=\"$path\">".s($filename)."</a>", FORMAT_HTML, array('context'=>$context)); 2813 if ($canexport) { 2814 $button->set_callback_options('forum_portfolio_caller', array('postid' => $post->id, 'attachment' => $file->get_id()), 'mod_forum'); 2815 $button->set_format_by_file($file); 2816 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK); 2817 } 2818 $output .= '<br />'; 2819 } 2820 } 2821 2822 if (!empty($CFG->enableplagiarism)) { 2823 require_once($CFG->libdir.'/plagiarismlib.php'); 2824 $output .= plagiarism_get_links(array('userid' => $post->userid, 2825 'file' => $file, 2826 'cmid' => $cm->id, 2827 'course' => $cm->course, 2828 'forum' => $cm->instance)); 2829 $output .= '<br />'; 2830 } 2831 } 2832 } 2833 2834 if ($type !== 'separateimages') { 2835 return $output; 2836 2837 } else { 2838 return array($output, $imagereturn); 2839 } 2840 } 2841 2842 //////////////////////////////////////////////////////////////////////////////// 2843 // File API // 2844 //////////////////////////////////////////////////////////////////////////////// 2845 2846 /** 2847 * Lists all browsable file areas 2848 * 2849 * @package mod_forum 2850 * @category files 2851 * @param stdClass $course course object 2852 * @param stdClass $cm course module object 2853 * @param stdClass $context context object 2854 * @return array 2855 */ 2856 function forum_get_file_areas($course, $cm, $context) { 2857 return array( 2858 'attachment' => get_string('areaattachment', 'mod_forum'), 2859 'post' => get_string('areapost', 'mod_forum'), 2860 ); 2861 } 2862 2863 /** 2864 * File browsing support for forum module. 2865 * 2866 * @package mod_forum 2867 * @category files 2868 * @param stdClass $browser file browser object 2869 * @param stdClass $areas file areas 2870 * @param stdClass $course course object 2871 * @param stdClass $cm course module 2872 * @param stdClass $context context module 2873 * @param string $filearea file area 2874 * @param int $itemid item ID 2875 * @param string $filepath file path 2876 * @param string $filename file name 2877 * @return file_info instance or null if not found 2878 */ 2879 function forum_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { 2880 global $CFG, $DB, $USER; 2881 2882 if ($context->contextlevel != CONTEXT_MODULE) { 2883 return null; 2884 } 2885 2886 // filearea must contain a real area 2887 if (!isset($areas[$filearea])) { 2888 return null; 2889 } 2890 2891 // Note that forum_user_can_see_post() additionally allows access for parent roles 2892 // and it explicitly checks qanda forum type, too. One day, when we stop requiring 2893 // course:managefiles, we will need to extend this. 2894 if (!has_capability('mod/forum:viewdiscussion', $context)) { 2895 return null; 2896 } 2897 2898 if (is_null($itemid)) { 2899 require_once($CFG->dirroot.'/mod/forum/locallib.php'); 2900 return new forum_file_info_container($browser, $course, $cm, $context, $areas, $filearea); 2901 } 2902 2903 static $cached = array(); 2904 // $cached will store last retrieved post, discussion and forum. To make sure that the cache 2905 // is cleared between unit tests we check if this is the same session 2906 if (!isset($cached['sesskey']) || $cached['sesskey'] != sesskey()) { 2907 $cached = array('sesskey' => sesskey()); 2908 } 2909 2910 if (isset($cached['post']) && $cached['post']->id == $itemid) { 2911 $post = $cached['post']; 2912 } else if ($post = $DB->get_record('forum_posts', array('id' => $itemid))) { 2913 $cached['post'] = $post; 2914 } else { 2915 return null; 2916 } 2917 2918 if (isset($cached['discussion']) && $cached['discussion']->id == $post->discussion) { 2919 $discussion = $cached['discussion']; 2920 } else if ($discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion))) { 2921 $cached['discussion'] = $discussion; 2922 } else { 2923 return null; 2924 } 2925 2926 if (isset($cached['forum']) && $cached['forum']->id == $cm->instance) { 2927 $forum = $cached['forum']; 2928 } else if ($forum = $DB->get_record('forum', array('id' => $cm->instance))) { 2929 $cached['forum'] = $forum; 2930 } else { 2931 return null; 2932 } 2933 2934 $fs = get_file_storage(); 2935 $filepath = is_null($filepath) ? '/' : $filepath; 2936 $filename = is_null($filename) ? '.' : $filename; 2937 if (!($storedfile = $fs->get_file($context->id, 'mod_forum', $filearea, $itemid, $filepath, $filename))) { 2938 return null; 2939 } 2940 2941 // Checks to see if the user can manage files or is the owner. 2942 // TODO MDL-33805 - Do not use userid here and move the capability check above. 2943 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) { 2944 return null; 2945 } 2946 // Make sure groups allow this user to see this file 2947 if ($discussion->groupid > 0 && !has_capability('moodle/site:accessallgroups', $context)) { 2948 $groupmode = groups_get_activity_groupmode($cm, $course); 2949 if ($groupmode == SEPARATEGROUPS && !groups_is_member($discussion->groupid)) { 2950 return null; 2951 } 2952 } 2953 2954 // Make sure we're allowed to see it... 2955 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) { 2956 return null; 2957 } 2958 2959 $urlbase = $CFG->wwwroot.'/pluginfile.php'; 2960 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false); 2961 } 2962 2963 /** 2964 * Serves the forum attachments. Implements needed access control ;-) 2965 * 2966 * @package mod_forum 2967 * @category files 2968 * @param stdClass $course course object 2969 * @param stdClass $cm course module object 2970 * @param stdClass $context context object 2971 * @param string $filearea file area 2972 * @param array $args extra arguments 2973 * @param bool $forcedownload whether or not force download 2974 * @param array $options additional options affecting the file serving 2975 * @return bool false if file not found, does not return if found - justsend the file 2976 */ 2977 function forum_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) { 2978 global $CFG, $DB; 2979 2980 if ($context->contextlevel != CONTEXT_MODULE) { 2981 return false; 2982 } 2983 2984 require_course_login($course, true, $cm); 2985 2986 $areas = forum_get_file_areas($course, $cm, $context); 2987 2988 // filearea must contain a real area 2989 if (!isset($areas[$filearea])) { 2990 return false; 2991 } 2992 2993 $postid = (int)array_shift($args); 2994 2995 if (!$post = $DB->get_record('forum_posts', array('id'=>$postid))) { 2996 return false; 2997 } 2998 2999 if (!$discussion = $DB->get_record('forum_discussions', array('id'=>$post->discussion))) { 3000 return false; 3001 } 3002 3003 if (!$forum = $DB->get_record('forum', array('id'=>$cm->instance))) { 3004 return false; 3005 } 3006 3007 $fs = get_file_storage(); 3008 $relativepath = implode('/', $args); 3009 $fullpath = "/$context->id/mod_forum/$filearea/$postid/$relativepath"; 3010 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { 3011 return false; 3012 } 3013 3014 // Make sure groups allow this user to see this file 3015 if ($discussion->groupid > 0) { 3016 $groupmode = groups_get_activity_groupmode($cm, $course); 3017 if ($groupmode == SEPARATEGROUPS) { 3018 if (!groups_is_member($discussion->groupid) and !has_capability('moodle/site:accessallgroups', $context)) { 3019 return false; 3020 } 3021 } 3022 } 3023 3024 // Make sure we're allowed to see it... 3025 if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) { 3026 return false; 3027 } 3028 3029 // finally send the file 3030 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security! 3031 } 3032 3033 /** 3034 * If successful, this function returns the name of the file 3035 * 3036 * @global object 3037 * @param object $post is a full post record, including course and forum 3038 * @param object $forum 3039 * @param object $cm 3040 * @param mixed $mform 3041 * @param string $unused 3042 * @return bool 3043 */ 3044 function forum_add_attachment($post, $forum, $cm, $mform=null, $unused=null) { 3045 global $DB; 3046 3047 if (empty($mform)) { 3048 return false; 3049 } 3050 3051 if (empty($post->attachments)) { 3052 return true; // Nothing to do 3053 } 3054 3055 $context = context_module::instance($cm->id); 3056 3057 $info = file_get_draft_area_info($post->attachments); 3058 $present = ($info['filecount']>0) ? '1' : ''; 3059 file_save_draft_area_files($post->attachments, $context->id, 'mod_forum', 'attachment', $post->id, 3060 mod_forum_post_form::attachment_options($forum)); 3061 3062 $DB->set_field('forum_posts', 'attachment', $present, array('id'=>$post->id)); 3063 3064 return true; 3065 } 3066 3067 /** 3068 * Add a new post in an existing discussion. 3069 * 3070 * @param stdClass $post The post data 3071 * @param mixed $mform The submitted form 3072 * @param string $unused 3073 * @return int 3074 */ 3075 function forum_add_new_post($post, $mform, $unused = null) { 3076 global $USER, $DB; 3077 3078 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion)); 3079 $forum = $DB->get_record('forum', array('id' => $discussion->forum)); 3080 $cm = get_coursemodule_from_instance('forum', $forum->id); 3081 $context = context_module::instance($cm->id); 3082 $privatereplyto = 0; 3083 3084 // Check whether private replies should be enabled for this post. 3085 if ($post->parent) { 3086 $parent = $DB->get_record('forum_posts', array('id' => $post->parent)); 3087 3088 if (!empty($parent->privatereplyto)) { 3089 throw new \coding_exception('It should not be possible to reply to a private reply'); 3090 } 3091 3092 if (!empty($post->isprivatereply) && forum_user_can_reply_privately($context, $parent)) { 3093 $privatereplyto = $parent->userid; 3094 } 3095 } 3096 3097 $post->created = $post->modified = time(); 3098 $post->mailed = FORUM_MAILED_PENDING; 3099 $post->userid = $USER->id; 3100 $post->privatereplyto = $privatereplyto; 3101 $post->attachment = ""; 3102 if (!isset($post->totalscore)) { 3103 $post->totalscore = 0; 3104 } 3105 if (!isset($post->mailnow)) { 3106 $post->mailnow = 0; 3107 } 3108 3109 \mod_forum\local\entities\post::add_message_counts($post); 3110 $post->id = $DB->insert_record("forum_posts", $post); 3111 $post->message = file_save_draft_area_files($post->itemid, $context->id, 'mod_forum', 'post', $post->id, 3112 mod_forum_post_form::editor_options($context, null), $post->message); 3113 $DB->set_field('forum_posts', 'message', $post->message, array('id'=>$post->id)); 3114 forum_add_attachment($post, $forum, $cm, $mform); 3115 3116 // Update discussion modified date 3117 $DB->set_field("forum_discussions", "timemodified", $post->modified, array("id" => $post->discussion)); 3118 $DB->set_field("forum_discussions", "usermodified", $post->userid, array("id" => $post->discussion)); 3119 3120 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) { 3121 forum_tp_mark_post_read($post->userid, $post); 3122 } 3123 3124 if (isset($post->tags)) { 3125 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $post->tags); 3126 } 3127 3128 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection) 3129 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_new_post'); 3130 3131 return $post->id; 3132 } 3133 3134 /** 3135 * Trigger post updated event. 3136 * 3137 * @param object $post forum post object 3138 * @param object $discussion discussion object 3139 * @param object $context forum context object 3140 * @param object $forum forum object 3141 * @since Moodle 3.8 3142 * @return void 3143 */ 3144 function forum_trigger_post_updated_event($post, $discussion, $context, $forum) { 3145 global $USER; 3146 3147 $params = array( 3148 'context' => $context, 3149 'objectid' => $post->id, 3150 'other' => array( 3151 'discussionid' => $discussion->id, 3152 'forumid' => $forum->id, 3153 'forumtype' => $forum->type, 3154 ) 3155 ); 3156 3157 if ($USER->id !== $post->userid) { 3158 $params['relateduserid'] = $post->userid; 3159 } 3160 3161 $event = \mod_forum\event\post_updated::create($params); 3162 $event->add_record_snapshot('forum_discussions', $discussion); 3163 $event->trigger(); 3164 } 3165 3166 /** 3167 * Update a post. 3168 * 3169 * @param stdClass $newpost The post to update 3170 * @param mixed $mform The submitted form 3171 * @param string $unused 3172 * @return bool 3173 */ 3174 function forum_update_post($newpost, $mform, $unused = null) { 3175 global $DB, $USER; 3176 3177 $post = $DB->get_record('forum_posts', array('id' => $newpost->id)); 3178 $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion)); 3179 $forum = $DB->get_record('forum', array('id' => $discussion->forum)); 3180 $cm = get_coursemodule_from_instance('forum', $forum->id); 3181 $context = context_module::instance($cm->id); 3182 3183 // Allowed modifiable fields. 3184 $modifiablefields = [ 3185 'subject', 3186 'message', 3187 'messageformat', 3188 'messagetrust', 3189 'timestart', 3190 'timeend', 3191 'pinned', 3192 'attachments', 3193 ]; 3194 foreach ($modifiablefields as $field) { 3195 if (isset($newpost->{$field})) { 3196 $post->{$field} = $newpost->{$field}; 3197 } 3198 } 3199 $post->modified = time(); 3200 3201 if (!$post->parent) { // Post is a discussion starter - update discussion title and times too 3202 $discussion->name = $post->subject; 3203 $discussion->timestart = $post->timestart; 3204 $discussion->timeend = $post->timeend; 3205 3206 if (isset($post->pinned)) { 3207 $discussion->pinned = $post->pinned; 3208 } 3209 } 3210 $post->message = file_save_draft_area_files($newpost->itemid, $context->id, 'mod_forum', 'post', $post->id, 3211 mod_forum_post_form::editor_options($context, $post->id), $post->message); 3212 \mod_forum\local\entities\post::add_message_counts($post); 3213 $DB->update_record('forum_posts', $post); 3214 // Note: Discussion modified time/user are intentionally not updated, to enable them to track the latest new post. 3215 $DB->update_record('forum_discussions', $discussion); 3216 3217 forum_add_attachment($post, $forum, $cm, $mform); 3218 3219 if ($forum->type == 'single' && $post->parent == '0') { 3220 // Updating first post of single discussion type -> updating forum intro. 3221 $forum->intro = $post->message; 3222 $forum->timemodified = time(); 3223 $DB->update_record("forum", $forum); 3224 } 3225 3226 if (isset($newpost->tags)) { 3227 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, $context, $newpost->tags); 3228 } 3229 3230 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) { 3231 forum_tp_mark_post_read($USER->id, $post); 3232 } 3233 3234 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection) 3235 forum_trigger_content_uploaded_event($post, $cm, 'forum_update_post'); 3236 3237 return true; 3238 } 3239 3240 /** 3241 * Given an object containing all the necessary data, 3242 * create a new discussion and return the id 3243 * 3244 * @param object $post 3245 * @param mixed $mform 3246 * @param string $unused 3247 * @param int $userid 3248 * @return object 3249 */ 3250 function forum_add_discussion($discussion, $mform=null, $unused=null, $userid=null) { 3251 global $USER, $CFG, $DB; 3252 3253 $timenow = isset($discussion->timenow) ? $discussion->timenow : time(); 3254 3255 if (is_null($userid)) { 3256 $userid = $USER->id; 3257 } 3258 3259 // The first post is stored as a real post, and linked 3260 // to from the discuss entry. 3261 3262 $forum = $DB->get_record('forum', array('id'=>$discussion->forum)); 3263 $cm = get_coursemodule_from_instance('forum', $forum->id); 3264 3265 $post = new stdClass(); 3266 $post->discussion = 0; 3267 $post->parent = 0; 3268 $post->privatereplyto = 0; 3269 $post->userid = $userid; 3270 $post->created = $timenow; 3271 $post->modified = $timenow; 3272 $post->mailed = FORUM_MAILED_PENDING; 3273 $post->subject = $discussion->name; 3274 $post->message = $discussion->message; 3275 $post->messageformat = $discussion->messageformat; 3276 $post->messagetrust = $discussion->messagetrust; 3277 $post->attachments = isset($discussion->attachments) ? $discussion->attachments : null; 3278 $post->forum = $forum->id; // speedup 3279 $post->course = $forum->course; // speedup 3280 $post->mailnow = $discussion->mailnow; 3281 3282 \mod_forum\local\entities\post::add_message_counts($post); 3283 $post->id = $DB->insert_record("forum_posts", $post); 3284 3285 // TODO: Fix the calling code so that there always is a $cm when this function is called 3286 if (!empty($cm->id) && !empty($discussion->itemid)) { // In "single simple discussions" this may not exist yet 3287 $context = context_module::instance($cm->id); 3288 $text = file_save_draft_area_files($discussion->itemid, $context->id, 'mod_forum', 'post', $post->id, 3289 mod_forum_post_form::editor_options($context, null), $post->message); 3290 $DB->set_field('forum_posts', 'message', $text, array('id'=>$post->id)); 3291 } 3292 3293 // Now do the main entry for the discussion, linking to this first post 3294 3295 $discussion->firstpost = $post->id; 3296 $discussion->timemodified = $timenow; 3297 $discussion->usermodified = $post->userid; 3298 $discussion->userid = $userid; 3299 $discussion->assessed = 0; 3300 3301 $post->discussion = $DB->insert_record("forum_discussions", $discussion); 3302 3303 // Finally, set the pointer on the post. 3304 $DB->set_field("forum_posts", "discussion", $post->discussion, array("id"=>$post->id)); 3305 3306 if (!empty($cm->id)) { 3307 forum_add_attachment($post, $forum, $cm, $mform, $unused); 3308 } 3309 3310 if (isset($discussion->tags)) { 3311 core_tag_tag::set_item_tags('mod_forum', 'forum_posts', $post->id, context_module::instance($cm->id), $discussion->tags); 3312 } 3313 3314 if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) { 3315 forum_tp_mark_post_read($post->userid, $post); 3316 } 3317 3318 // Let Moodle know that assessable content is uploaded (eg for plagiarism detection) 3319 if (!empty($cm->id)) { 3320 forum_trigger_content_uploaded_event($post, $cm, 'forum_add_discussion'); 3321 } 3322 3323 return $post->discussion; 3324 } 3325 3326 3327 /** 3328 * Deletes a discussion and handles all associated cleanup. 3329 * 3330 * @global object 3331 * @param object $discussion Discussion to delete 3332 * @param bool $fulldelete True when deleting entire forum 3333 * @param object $course Course 3334 * @param object $cm Course-module 3335 * @param object $forum Forum 3336 * @return bool 3337 */ 3338 function forum_delete_discussion($discussion, $fulldelete, $course, $cm, $forum) { 3339 global $DB, $CFG; 3340 require_once($CFG->libdir.'/completionlib.php'); 3341 3342 $result = true; 3343 3344 if ($posts = $DB->get_records("forum_posts", array("discussion" => $discussion->id))) { 3345 foreach ($posts as $post) { 3346 $post->course = $discussion->course; 3347 $post->forum = $discussion->forum; 3348 if (!forum_delete_post($post, 'ignore', $course, $cm, $forum, $fulldelete)) { 3349 $result = false; 3350 } 3351 } 3352 } 3353 3354 forum_tp_delete_read_records(-1, -1, $discussion->id); 3355 3356 // Discussion subscriptions must be removed before discussions because of key constraints. 3357 $DB->delete_records('forum_discussion_subs', array('discussion' => $discussion->id)); 3358 if (!$DB->delete_records("forum_discussions", array("id" => $discussion->id))) { 3359 $result = false; 3360 } 3361 3362 // Update completion state if we are tracking completion based on number of posts 3363 // But don't bother when deleting whole thing 3364 if (!$fulldelete) { 3365 $completion = new completion_info($course); 3366 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && 3367 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) { 3368 $completion->update_state($cm, COMPLETION_INCOMPLETE, $discussion->userid); 3369 } 3370 } 3371 3372 $params = array( 3373 'objectid' => $discussion->id, 3374 'context' => context_module::instance($cm->id), 3375 'other' => array( 3376 'forumid' => $forum->id, 3377 ) 3378 ); 3379 $event = \mod_forum\event\discussion_deleted::create($params); 3380 $event->add_record_snapshot('forum_discussions', $discussion); 3381 $event->trigger(); 3382 3383 return $result; 3384 } 3385 3386 3387 /** 3388 * Deletes a single forum post. 3389 * 3390 * @global object 3391 * @param object $post Forum post object 3392 * @param mixed $children Whether to delete children. If false, returns false 3393 * if there are any children (without deleting the post). If true, 3394 * recursively deletes all children. If set to special value 'ignore', deletes 3395 * post regardless of children (this is for use only when deleting all posts 3396 * in a disussion). 3397 * @param object $course Course 3398 * @param object $cm Course-module 3399 * @param object $forum Forum 3400 * @param bool $skipcompletion True to skip updating completion state if it 3401 * would otherwise be updated, i.e. when deleting entire forum anyway. 3402 * @return bool 3403 */ 3404 function forum_delete_post($post, $children, $course, $cm, $forum, $skipcompletion=false) { 3405 global $DB, $CFG, $USER; 3406 require_once($CFG->libdir.'/completionlib.php'); 3407 3408 $context = context_module::instance($cm->id); 3409 3410 if ($children !== 'ignore' && ($childposts = $DB->get_records('forum_posts', array('parent'=>$post->id)))) { 3411 if ($children) { 3412 foreach ($childposts as $childpost) { 3413 forum_delete_post($childpost, true, $course, $cm, $forum, $skipcompletion); 3414 } 3415 } else { 3416 return false; 3417 } 3418 } 3419 3420 // Delete ratings. 3421 require_once($CFG->dirroot.'/rating/lib.php'); 3422 $delopt = new stdClass; 3423 $delopt->contextid = $context->id; 3424 $delopt->component = 'mod_forum'; 3425 $delopt->ratingarea = 'post'; 3426 $delopt->itemid = $post->id; 3427 $rm = new rating_manager(); 3428 $rm->delete_ratings($delopt); 3429 3430 // Delete attachments. 3431 $fs = get_file_storage(); 3432 $fs->delete_area_files($context->id, 'mod_forum', 'attachment', $post->id); 3433 $fs->delete_area_files($context->id, 'mod_forum', 'post', $post->id); 3434 3435 // Delete cached RSS feeds. 3436 if (!empty($CFG->enablerssfeeds)) { 3437 require_once($CFG->dirroot.'/mod/forum/rsslib.php'); 3438 forum_rss_delete_file($forum); 3439 } 3440 3441 if ($DB->delete_records("forum_posts", array("id" => $post->id))) { 3442 3443 forum_tp_delete_read_records(-1, $post->id); 3444 3445 // Just in case we are deleting the last post 3446 forum_discussion_update_last_post($post->discussion); 3447 3448 // Update completion state if we are tracking completion based on number of posts 3449 // But don't bother when deleting whole thing 3450 3451 if (!$skipcompletion) { 3452 $completion = new completion_info($course); 3453 if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && 3454 ($forum->completiondiscussions || $forum->completionreplies || $forum->completionposts)) { 3455 $completion->update_state($cm, COMPLETION_INCOMPLETE, $post->userid); 3456 } 3457 } 3458 3459 $params = array( 3460 'context' => $context, 3461 'objectid' => $post->id, 3462 'other' => array( 3463 'discussionid' => $post->discussion, 3464 'forumid' => $forum->id, 3465 'forumtype' => $forum->type, 3466 ) 3467 ); 3468 $post->deleted = 1; 3469 if ($post->userid !== $USER->id) { 3470 $params['relateduserid'] = $post->userid; 3471 } 3472 $event = \mod_forum\event\post_deleted::create($params); 3473 $event->add_record_snapshot('forum_posts', $post); 3474 $event->trigger(); 3475 3476 return true; 3477 } 3478 return false; 3479 } 3480 3481 /** 3482 * Sends post content to plagiarism plugin 3483 * @param object $post Forum post object 3484 * @param object $cm Course-module 3485 * @param string $name 3486 * @return bool 3487 */ 3488 function forum_trigger_content_uploaded_event($post, $cm, $name) { 3489 $context = context_module::instance($cm->id); 3490 $fs = get_file_storage(); 3491 $files = $fs->get_area_files($context->id, 'mod_forum', 'attachment', $post->id, "timemodified", false); 3492 $params = array( 3493 'context' => $context, 3494 'objectid' => $post->id, 3495 'other' => array( 3496 'content' => $post->message, 3497 'pathnamehashes' => array_keys($files), 3498 'discussionid' => $post->discussion, 3499 'triggeredfrom' => $name, 3500 ) 3501 ); 3502 $event = \mod_forum\event\assessable_uploaded::create($params); 3503 $event->trigger(); 3504 return true; 3505 } 3506 3507 /** 3508 * Given a new post, subscribes or unsubscribes as appropriate. 3509 * Returns some text which describes what happened. 3510 * 3511 * @param object $fromform The submitted form 3512 * @param stdClass $forum The forum record 3513 * @param stdClass $discussion The forum discussion record 3514 * @return string 3515 */ 3516 function forum_post_subscription($fromform, $forum, $discussion) { 3517 global $USER; 3518 3519 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) { 3520 return ""; 3521 } else if (\mod_forum\subscriptions::subscription_disabled($forum)) { 3522 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum); 3523 if ($subscribed && !has_capability('moodle/course:manageactivities', context_course::instance($forum->course), $USER->id)) { 3524 // This user should not be subscribed to the forum. 3525 \mod_forum\subscriptions::unsubscribe_user($USER->id, $forum); 3526 } 3527 return ""; 3528 } 3529 3530 $info = new stdClass(); 3531 $info->name = fullname($USER); 3532 $info->discussion = format_string($discussion->name); 3533 $info->forum = format_string($forum->name); 3534 3535 if (isset($fromform->discussionsubscribe) && $fromform->discussionsubscribe) { 3536 if ($result = \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion)) { 3537 return html_writer::tag('p', get_string('discussionnowsubscribed', 'forum', $info)); 3538 } 3539 } else { 3540 if ($result = \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion)) { 3541 return html_writer::tag('p', get_string('discussionnownotsubscribed', 'forum', $info)); 3542 } 3543 } 3544 3545 return ''; 3546 } 3547 3548 /** 3549 * Generate and return the subscribe or unsubscribe link for a forum. 3550 * 3551 * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe. 3552 * @param object $context the context object for this forum. 3553 * @param array $messages text used for the link in its various states 3554 * (subscribed, unsubscribed, forcesubscribed or cantsubscribe). 3555 * Any strings not passed in are taken from the $defaultmessages array 3556 * at the top of the function. 3557 * @param bool $cantaccessagroup 3558 * @param bool $unused1 3559 * @param bool $backtoindex 3560 * @param array $unused2 3561 * @return string 3562 */ 3563 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $unused1 = true, 3564 $backtoindex = false, $unused2 = null) { 3565 global $CFG, $USER, $PAGE, $OUTPUT; 3566 $defaultmessages = array( 3567 'subscribed' => get_string('unsubscribe', 'forum'), 3568 'unsubscribed' => get_string('subscribe', 'forum'), 3569 'cantaccessgroup' => get_string('no'), 3570 'forcesubscribed' => get_string('everyoneissubscribed', 'forum'), 3571 'cantsubscribe' => get_string('disallowsubscribe','forum') 3572 ); 3573 $messages = $messages + $defaultmessages; 3574 3575 if (\mod_forum\subscriptions::is_forcesubscribed($forum)) { 3576 return $messages['forcesubscribed']; 3577 } else if (\mod_forum\subscriptions::subscription_disabled($forum) && 3578 !has_capability('mod/forum:managesubscriptions', $context)) { 3579 return $messages['cantsubscribe']; 3580 } else if ($cantaccessagroup) { 3581 return $messages['cantaccessgroup']; 3582 } else { 3583 if (!is_enrolled($context, $USER, '', true)) { 3584 return ''; 3585 } 3586 3587 $subscribed = \mod_forum\subscriptions::is_subscribed($USER->id, $forum); 3588 if ($subscribed) { 3589 $linktext = $messages['subscribed']; 3590 $linktitle = get_string('subscribestop', 'forum'); 3591 } else { 3592 $linktext = $messages['unsubscribed']; 3593 $linktitle = get_string('subscribestart', 'forum'); 3594 } 3595 3596 $options = array(); 3597 if ($backtoindex) { 3598 $backtoindexlink = '&backtoindex=1'; 3599 $options['backtoindex'] = 1; 3600 } else { 3601 $backtoindexlink = ''; 3602 } 3603 3604 $options['id'] = $forum->id; 3605 $options['sesskey'] = sesskey(); 3606 $url = new moodle_url('/mod/forum/subscribe.php', $options); 3607 return $OUTPUT->single_button($url, $linktext, 'get', array('title' => $linktitle)); 3608 } 3609 } 3610 3611 /** 3612 * Returns true if user created new discussion already. 3613 * 3614 * @param int $forumid The forum to check for postings 3615 * @param int $userid The user to check for postings 3616 * @param int $groupid The group to restrict the check to 3617 * @return bool 3618 */ 3619 function forum_user_has_posted_discussion($forumid, $userid, $groupid = null) { 3620 global $CFG, $DB; 3621 3622 $sql = "SELECT 'x' 3623 FROM {forum_discussions} d, {forum_posts} p 3624 WHERE d.forum = ? AND p.discussion = d.id AND p.parent = 0 AND p.userid = ?"; 3625 3626 $params = [$forumid, $userid]; 3627 3628 if ($groupid) { 3629 $sql .= " AND d.groupid = ?"; 3630 $params[] = $groupid; 3631 } 3632 3633 return $DB->record_exists_sql($sql, $params); 3634 } 3635 3636 /** 3637 * @global object 3638 * @global object 3639 * @param int $forumid 3640 * @param int $userid 3641 * @return array 3642 */ 3643 function forum_discussions_user_has_posted_in($forumid, $userid) { 3644 global $CFG, $DB; 3645 3646 $haspostedsql = "SELECT d.id AS id, 3647 d.* 3648 FROM {forum_posts} p, 3649 {forum_discussions} d 3650 WHERE p.discussion = d.id 3651 AND d.forum = ? 3652 AND p.userid = ?"; 3653 3654 return $DB->get_records_sql($haspostedsql, array($forumid, $userid)); 3655 } 3656 3657 /** 3658 * @global object 3659 * @global object 3660 * @param int $forumid 3661 * @param int $did 3662 * @param int $userid 3663 * @return bool 3664 */ 3665 function forum_user_has_posted($forumid, $did, $userid) { 3666 global $DB; 3667 3668 if (empty($did)) { 3669 // posted in any forum discussion? 3670 $sql = "SELECT 'x' 3671 FROM {forum_posts} p 3672 JOIN {forum_discussions} d ON d.id = p.discussion 3673 WHERE p.userid = :userid AND d.forum = :forumid"; 3674 return $DB->record_exists_sql($sql, array('forumid'=>$forumid,'userid'=>$userid)); 3675 } else { 3676 return $DB->record_exists('forum_posts', array('discussion'=>$did,'userid'=>$userid)); 3677 } 3678 } 3679 3680 /** 3681 * Returns creation time of the first user's post in given discussion 3682 * @global object $DB 3683 * @param int $did Discussion id 3684 * @param int $userid User id 3685 * @return int|bool post creation time stamp or return false 3686 */ 3687 function forum_get_user_posted_time($did, $userid) { 3688 global $DB; 3689 3690 $posttime = $DB->get_field('forum_posts', 'MIN(created)', array('userid'=>$userid, 'discussion'=>$did)); 3691 if (empty($posttime)) { 3692 return false; 3693 } 3694 return $posttime; 3695 } 3696 3697 /** 3698 * @global object 3699 * @param object $forum 3700 * @param object $currentgroup 3701 * @param int $unused 3702 * @param object $cm 3703 * @param object $context 3704 * @return bool 3705 */ 3706 function forum_user_can_post_discussion($forum, $currentgroup=null, $unused=-1, $cm=NULL, $context=NULL) { 3707 // $forum is an object 3708 global $USER; 3709 3710 // shortcut - guest and not-logged-in users can not post 3711 if (isguestuser() or !isloggedin()) { 3712 return false; 3713 } 3714 3715 if (!$cm) { 3716 debugging('missing cm', DEBUG_DEVELOPER); 3717 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) { 3718 print_error('invalidcoursemodule'); 3719 } 3720 } 3721 3722 if (!$context) { 3723 $context = context_module::instance($cm->id); 3724 } 3725 3726 if (forum_is_cutoff_date_reached($forum)) { 3727 if (!has_capability('mod/forum:canoverridecutoff', $context)) { 3728 return false; 3729 } 3730 } 3731 3732 if ($currentgroup === null) { 3733 $currentgroup = groups_get_activity_group($cm); 3734 } 3735 3736 $groupmode = groups_get_activity_groupmode($cm); 3737 3738 if ($forum->type == 'news') { 3739 $capname = 'mod/forum:addnews'; 3740 } else if ($forum->type == 'qanda') { 3741 $capname = 'mod/forum:addquestion'; 3742 } else { 3743 $capname = 'mod/forum:startdiscussion'; 3744 } 3745 3746 if (!has_capability($capname, $context)) { 3747 return false; 3748 } 3749 3750 if ($forum->type == 'single') { 3751 return false; 3752 } 3753 3754 if ($forum->type == 'eachuser') { 3755 if (forum_user_has_posted_discussion($forum->id, $USER->id, $currentgroup)) { 3756 return false; 3757 } 3758 } 3759 3760 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) { 3761 return true; 3762 } 3763 3764 if ($currentgroup) { 3765 return groups_is_member($currentgroup); 3766 } else { 3767 // no group membership and no accessallgroups means no new discussions 3768 // reverted to 1.7 behaviour in 1.9+, buggy in 1.8.0-1.9.0 3769 return false; 3770 } 3771 } 3772 3773 /** 3774 * This function checks whether the user can reply to posts in a forum 3775 * discussion. Use forum_user_can_post_discussion() to check whether the user 3776 * can start discussions. 3777 * 3778 * @global object 3779 * @global object 3780 * @uses DEBUG_DEVELOPER 3781 * @uses CONTEXT_MODULE 3782 * @uses VISIBLEGROUPS 3783 * @param object $forum forum object 3784 * @param object $discussion 3785 * @param object $user 3786 * @param object $cm 3787 * @param object $course 3788 * @param object $context 3789 * @return bool 3790 */ 3791 function forum_user_can_post($forum, $discussion, $user=NULL, $cm=NULL, $course=NULL, $context=NULL) { 3792 global $USER, $DB; 3793 if (empty($user)) { 3794 $user = $USER; 3795 } 3796 3797 // shortcut - guest and not-logged-in users can not post 3798 if (isguestuser($user) or empty($user->id)) { 3799 return false; 3800 } 3801 3802 if (!isset($discussion->groupid)) { 3803 debugging('incorrect discussion parameter', DEBUG_DEVELOPER); 3804 return false; 3805 } 3806 3807 if (!$cm) { 3808 debugging('missing cm', DEBUG_DEVELOPER); 3809 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) { 3810 print_error('invalidcoursemodule'); 3811 } 3812 } 3813 3814 if (!$course) { 3815 debugging('missing course', DEBUG_DEVELOPER); 3816 if (!$course = $DB->get_record('course', array('id' => $forum->course))) { 3817 print_error('invalidcourseid'); 3818 } 3819 } 3820 3821 if (!$context) { 3822 $context = context_module::instance($cm->id); 3823 } 3824 3825 if (forum_is_cutoff_date_reached($forum)) { 3826 if (!has_capability('mod/forum:canoverridecutoff', $context)) { 3827 return false; 3828 } 3829 } 3830 3831 // Check whether the discussion is locked. 3832 if (forum_discussion_is_locked($forum, $discussion)) { 3833 if (!has_capability('mod/forum:canoverridediscussionlock', $context)) { 3834 return false; 3835 } 3836 } 3837 3838 // normal users with temporary guest access can not post, suspended users can not post either 3839 if (!is_viewing($context, $user->id) and !is_enrolled($context, $user->id, '', true)) { 3840 return false; 3841 } 3842 3843 if ($forum->type == 'news') { 3844 $capname = 'mod/forum:replynews'; 3845 } else { 3846 $capname = 'mod/forum:replypost'; 3847 } 3848 3849 if (!has_capability($capname, $context, $user->id)) { 3850 return false; 3851 } 3852 3853 if (!$groupmode = groups_get_activity_groupmode($cm, $course)) { 3854 return true; 3855 } 3856 3857 if (has_capability('moodle/site:accessallgroups', $context)) { 3858 return true; 3859 } 3860 3861 if ($groupmode == VISIBLEGROUPS) { 3862 if ($discussion->groupid == -1) { 3863 // allow students to reply to all participants discussions - this was not possible in Moodle <1.8 3864 return true; 3865 } 3866 return groups_is_member($discussion->groupid); 3867 3868 } else { 3869 //separate groups 3870 if ($discussion->groupid == -1) { 3871 return false; 3872 } 3873 return groups_is_member($discussion->groupid); 3874 } 3875 } 3876 3877 /** 3878 * Check to ensure a user can view a timed discussion. 3879 * 3880 * @param object $discussion 3881 * @param object $user 3882 * @param object $context 3883 * @return boolean returns true if they can view post, false otherwise 3884 */ 3885 function forum_user_can_see_timed_discussion($discussion, $user, $context) { 3886 global $CFG; 3887 3888 // Check that the user can view a discussion that is normally hidden due to access times. 3889 if (!empty($CFG->forum_enabletimedposts)) { 3890 $time = time(); 3891 if (($discussion->timestart != 0 && $discussion->timestart > $time) 3892 || ($discussion->timeend != 0 && $discussion->timeend < $time)) { 3893 if (!has_capability('mod/forum:viewhiddentimedposts', $context, $user->id)) { 3894 return false; 3895 } 3896 } 3897 } 3898 3899 return true; 3900 } 3901 3902 /** 3903 * Check to ensure a user can view a group discussion. 3904 * 3905 * @param object $discussion 3906 * @param object $cm 3907 * @param object $context 3908 * @return boolean returns true if they can view post, false otherwise 3909 */ 3910 function forum_user_can_see_group_discussion($discussion, $cm, $context) { 3911 3912 // If it's a grouped discussion, make sure the user is a member. 3913 if ($discussion->groupid > 0) { 3914 $groupmode = groups_get_activity_groupmode($cm); 3915 if ($groupmode == SEPARATEGROUPS) { 3916 return groups_is_member($discussion->groupid) || has_capability('moodle/site:accessallgroups', $context); 3917 } 3918 } 3919 3920 return true; 3921 } 3922 3923 /** 3924 * @global object 3925 * @global object 3926 * @uses DEBUG_DEVELOPER 3927 * @param object $forum 3928 * @param object $discussion 3929 * @param object $context 3930 * @param object $user 3931 * @return bool 3932 */ 3933 function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL) { 3934 global $USER, $DB; 3935 3936 if (empty($user) || empty($user->id)) { 3937 $user = $USER; 3938 } 3939 3940 // retrieve objects (yuk) 3941 if (is_numeric($forum)) { 3942 debugging('missing full forum', DEBUG_DEVELOPER); 3943 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) { 3944 return false; 3945 } 3946 } 3947 if (is_numeric($discussion)) { 3948 debugging('missing full discussion', DEBUG_DEVELOPER); 3949 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) { 3950 return false; 3951 } 3952 } 3953 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) { 3954 print_error('invalidcoursemodule'); 3955 } 3956 3957 if (!has_capability('mod/forum:viewdiscussion', $context)) { 3958 return false; 3959 } 3960 3961 if (!forum_user_can_see_timed_discussion($discussion, $user, $context)) { 3962 return false; 3963 } 3964 3965 if (!forum_user_can_see_group_discussion($discussion, $cm, $context)) { 3966 return false; 3967 } 3968 3969 return true; 3970 } 3971 3972 /** 3973 * Check whether a user can see the specified post. 3974 * 3975 * @param \stdClass $forum The forum to chcek 3976 * @param \stdClass $discussion The discussion the post is in 3977 * @param \stdClass $post The post in question 3978 * @param \stdClass $user The user to test - if not specified, the current user is checked. 3979 * @param \stdClass $cm The Course Module that the forum is in (required). 3980 * @param bool $checkdeleted Whether to check the deleted flag on the post. 3981 * @return bool 3982 */ 3983 function forum_user_can_see_post($forum, $discussion, $post, $user = null, $cm = null, $checkdeleted = true) { 3984 global $CFG, $USER, $DB; 3985 3986 // retrieve objects (yuk) 3987 if (is_numeric($forum)) { 3988 debugging('missing full forum', DEBUG_DEVELOPER); 3989 if (!$forum = $DB->get_record('forum',array('id'=>$forum))) { 3990 return false; 3991 } 3992 } 3993 3994 if (is_numeric($discussion)) { 3995 debugging('missing full discussion', DEBUG_DEVELOPER); 3996 if (!$discussion = $DB->get_record('forum_discussions',array('id'=>$discussion))) { 3997 return false; 3998 } 3999 } 4000 if (is_numeric($post)) { 4001 debugging('missing full post', DEBUG_DEVELOPER); 4002 if (!$post = $DB->get_record('forum_posts',array('id'=>$post))) { 4003 return false; 4004 } 4005 } 4006 4007 if (!isset($post->id) && isset($post->parent)) { 4008 $post->id = $post->parent; 4009 } 4010 4011 if ($checkdeleted && !empty($post->deleted)) { 4012 return false; 4013 } 4014 4015 if (!$cm) { 4016 debugging('missing cm', DEBUG_DEVELOPER); 4017 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) { 4018 print_error('invalidcoursemodule'); 4019 } 4020 } 4021 4022 // Context used throughout function. 4023 $modcontext = context_module::instance($cm->id); 4024 4025 if (empty($user) || empty($user->id)) { 4026 $user = $USER; 4027 } 4028 4029 $canviewdiscussion = (isset($cm->cache) && !empty($cm->cache->caps['mod/forum:viewdiscussion'])) 4030 || has_capability('mod/forum:viewdiscussion', $modcontext, $user->id); 4031 if (!$canviewdiscussion && !has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), context_user::instance($post->userid))) { 4032 return false; 4033 } 4034 4035 if (!forum_post_is_visible_privately($post, $cm)) { 4036 return false; 4037 } 4038 4039 if (isset($cm->uservisible)) { 4040 if (!$cm->uservisible) { 4041 return false; 4042 } 4043 } else { 4044 if (!\core_availability\info_module::is_user_visible($cm, $user->id, false)) { 4045 return false; 4046 } 4047 } 4048 4049 if (!forum_user_can_see_timed_discussion($discussion, $user, $modcontext)) { 4050 return false; 4051 } 4052 4053 if (!forum_user_can_see_group_discussion($discussion, $cm, $modcontext)) { 4054 return false; 4055 } 4056 4057 if ($forum->type == 'qanda') { 4058 if (has_capability('mod/forum:viewqandawithoutposting', $modcontext, $user->id) || $post->userid == $user->id 4059 || (isset($discussion->firstpost) && $discussion->firstpost == $post->id)) { 4060 return true; 4061 } 4062 $firstpost = forum_get_firstpost_from_discussion($discussion->id); 4063 if ($firstpost->userid == $user->id) { 4064 return true; 4065 } 4066 $userfirstpost = forum_get_user_posted_time($discussion->id, $user->id); 4067 return (($userfirstpost !== false && (time() - $userfirstpost >= $CFG->maxeditingtime))); 4068 } 4069 return true; 4070 } 4071 4072 /** 4073 * Returns all forum posts since a given time in specified forum. 4074 * 4075 * @todo Document this functions args 4076 * @global object 4077 * @global object 4078 * @global object 4079 * @global object 4080 */ 4081 function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) { 4082 global $CFG, $COURSE, $USER, $DB; 4083 4084 if ($COURSE->id == $courseid) { 4085 $course = $COURSE; 4086 } else { 4087 $course = $DB->get_record('course', array('id' => $courseid)); 4088 } 4089 4090 $modinfo = get_fast_modinfo($course); 4091 4092 $cm = $modinfo->cms[$cmid]; 4093 $params = array($timestart, $cm->instance); 4094 4095 if ($userid) { 4096 $userselect = "AND u.id = ?"; 4097 $params[] = $userid; 4098 } else { 4099 $userselect = ""; 4100 } 4101 4102 if ($groupid) { 4103 $groupselect = "AND d.groupid = ?"; 4104 $params[] = $groupid; 4105 } else { 4106 $groupselect = ""; 4107 } 4108 4109 $allnames = get_all_user_name_fields(true, 'u'); 4110 if (!$posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid, 4111 d.timestart, d.timeend, d.userid AS duserid, 4112 $allnames, u.email, u.picture, u.imagealt, u.email 4113 FROM {forum_posts} p 4114 JOIN {forum_discussions} d ON d.id = p.discussion 4115 JOIN {forum} f ON f.id = d.forum 4116 JOIN {user} u ON u.id = p.userid 4117 WHERE p.created > ? AND f.id = ? 4118 $userselect $groupselect 4119 ORDER BY p.id ASC", $params)) { // order by initial posting date 4120 return; 4121 } 4122 4123 $groupmode = groups_get_activity_groupmode($cm, $course); 4124 $cm_context = context_module::instance($cm->id); 4125 $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context); 4126 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context); 4127 4128 $printposts = array(); 4129 foreach ($posts as $post) { 4130 4131 if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid 4132 and (($post->timestart > 0 and $post->timestart > time()) or ($post->timeend > 0 and $post->timeend < time()))) { 4133 if (!$viewhiddentimed) { 4134 continue; 4135 } 4136 } 4137 4138 if ($groupmode) { 4139 if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) { 4140 // oki (Open discussions have groupid -1) 4141 } else { 4142 // separate mode 4143 if (isguestuser()) { 4144 // shortcut 4145 continue; 4146 } 4147 4148 if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) { 4149 continue; 4150 } 4151 } 4152 } 4153 4154 $printposts[] = $post; 4155 } 4156 4157 if (!$printposts) { 4158 return; 4159 } 4160 4161 $aname = format_string($cm->name,true); 4162 4163 foreach ($printposts as $post) { 4164 $tmpactivity = new stdClass(); 4165 4166 $tmpactivity->type = 'forum'; 4167 $tmpactivity->cmid = $cm->id; 4168 $tmpactivity->name = $aname; 4169 $tmpactivity->sectionnum = $cm->sectionnum; 4170 $tmpactivity->timestamp = $post->modified; 4171 4172 $tmpactivity->content = new stdClass(); 4173 $tmpactivity->content->id = $post->id; 4174 $tmpactivity->content->discussion = $post->discussion; 4175 $tmpactivity->content->subject = format_string($post->subject); 4176 $tmpactivity->content->parent = $post->parent; 4177 $tmpactivity->content->forumtype = $post->forumtype; 4178 4179 $tmpactivity->user = new stdClass(); 4180 $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email'); 4181 $additionalfields = explode(',', user_picture::fields()); 4182 $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields); 4183 $tmpactivity->user->id = $post->userid; 4184 4185 $activities[$index++] = $tmpactivity; 4186 } 4187 4188 return; 4189 } 4190 4191 /** 4192 * Outputs the forum post indicated by $activity. 4193 * 4194 * @param object $activity the activity object the forum resides in 4195 * @param int $courseid the id of the course the forum resides in 4196 * @param bool $detail not used, but required for compatibilty with other modules 4197 * @param int $modnames not used, but required for compatibilty with other modules 4198 * @param bool $viewfullnames not used, but required for compatibilty with other modules 4199 */ 4200 function forum_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) { 4201 global $OUTPUT; 4202 4203 $content = $activity->content; 4204 if ($content->parent) { 4205 $class = 'reply'; 4206 } else { 4207 $class = 'discussion'; 4208 } 4209 4210 $tableoptions = [ 4211 'border' => '0', 4212 'cellpadding' => '3', 4213 'cellspacing' => '0', 4214 'class' => 'forum-recent' 4215 ]; 4216 $output = html_writer::start_tag('table', $tableoptions); 4217 $output .= html_writer::start_tag('tr'); 4218 4219 $post = (object) ['parent' => $content->parent]; 4220 $forum = (object) ['type' => $content->forumtype]; 4221 $authorhidden = forum_is_author_hidden($post, $forum); 4222 4223 // Show user picture if author should not be hidden. 4224 if (!$authorhidden) { 4225 $pictureoptions = [ 4226 'courseid' => $courseid, 4227 'link' => $authorhidden, 4228 'alttext' => $authorhidden, 4229 ]; 4230 $picture = $OUTPUT->user_picture($activity->user, $pictureoptions); 4231 $output .= html_writer::tag('td', $picture, ['class' => 'userpicture', 'valign' => 'top']); 4232 } 4233 4234 // Discussion title and author. 4235 $output .= html_writer::start_tag('td', ['class' => $class]); 4236 if ($content->parent) { 4237 $class = 'title'; 4238 } else { 4239 // Bold the title of new discussions so they stand out. 4240 $class = 'title bold'; 4241 } 4242 4243 $output .= html_writer::start_div($class); 4244 if ($detail) { 4245 $aname = s($activity->name); 4246 $output .= $OUTPUT->image_icon('icon', $aname, $activity->type); 4247 } 4248 $discussionurl = new moodle_url('/mod/forum/discuss.php', ['d' => $content->discussion]); 4249 $discussionurl->set_anchor('p' . $activity->content->id); 4250 $output .= html_writer::link($discussionurl, $content->subject); 4251 $output .= html_writer::end_div(); 4252 4253 $timestamp = userdate_htmltime($activity->timestamp); 4254 if ($authorhidden) { 4255 $authornamedate = $timestamp; 4256 } else { 4257 $fullname = fullname($activity->user, $viewfullnames); 4258 $userurl = new moodle_url('/user/view.php'); 4259 $userurl->params(['id' => $activity->user->id, 'course' => $courseid]); 4260 $by = new stdClass(); 4261 $by->name = html_writer::link($userurl, $fullname); 4262 $by->date = $timestamp; 4263 $authornamedate = get_string('bynameondate', 'forum', $by); 4264 } 4265 $output .= html_writer::div($authornamedate, 'user'); 4266 $output .= html_writer::end_tag('td'); 4267 $output .= html_writer::end_tag('tr'); 4268 $output .= html_writer::end_tag('table'); 4269 4270 echo $output; 4271 } 4272 4273 /** 4274 * recursively sets the discussion field to $discussionid on $postid and all its children 4275 * used when pruning a post 4276 * 4277 * @global object 4278 * @param int $postid 4279 * @param int $discussionid 4280 * @return bool 4281 */ 4282 function forum_change_discussionid($postid, $discussionid) { 4283 global $DB; 4284 $DB->set_field('forum_posts', 'discussion', $discussionid, array('id' => $postid)); 4285 if ($posts = $DB->get_records('forum_posts', array('parent' => $postid))) { 4286 foreach ($posts as $post) { 4287 forum_change_discussionid($post->id, $discussionid); 4288 } 4289 } 4290 return true; 4291 } 4292 4293 /** 4294 * Prints the editing button on subscribers page 4295 * 4296 * @global object 4297 * @global object 4298 * @param int $courseid 4299 * @param int $forumid 4300 * @return string 4301 */ 4302 function forum_update_subscriptions_button($courseid, $forumid) { 4303 global $CFG, $USER; 4304 4305 if (!empty($USER->subscriptionsediting)) { 4306 $string = get_string('managesubscriptionsoff', 'forum'); 4307 $edit = "off"; 4308 } else { 4309 $string = get_string('managesubscriptionson', 'forum'); 4310 $edit = "on"; 4311 } 4312 4313 $subscribers = html_writer::start_tag('form', array('action' => $CFG->wwwroot . '/mod/forum/subscribers.php', 4314 'method' => 'get', 'class' => 'form-inline')); 4315 $subscribers .= html_writer::empty_tag('input', array('type' => 'submit', 'value' => $string, 4316 'class' => 'btn btn-secondary')); 4317 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'id', 'value' => $forumid)); 4318 $subscribers .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'edit', 'value' => $edit)); 4319 $subscribers .= html_writer::end_tag('form'); 4320 4321 return $subscribers; 4322 } 4323 4324 // Functions to do with read tracking. 4325 4326 /** 4327 * Mark posts as read. 4328 * 4329 * @global object 4330 * @global object 4331 * @param object $user object 4332 * @param array $postids array of post ids 4333 * @return boolean success 4334 */ 4335 function forum_tp_mark_posts_read($user, $postids) { 4336 global $CFG, $DB; 4337 4338 if (!forum_tp_can_track_forums(false, $user)) { 4339 return true; 4340 } 4341 4342 $status = true; 4343 4344 $now = time(); 4345 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600); 4346 4347 if (empty($postids)) { 4348 return true; 4349 4350 } else if (count($postids) > 200) { 4351 while ($part = array_splice($postids, 0, 200)) { 4352 $status = forum_tp_mark_posts_read($user, $part) && $status; 4353 } 4354 return $status; 4355 } 4356 4357 list($usql, $postidparams) = $DB->get_in_or_equal($postids, SQL_PARAMS_NAMED, 'postid'); 4358 4359 $insertparams = array( 4360 'userid1' => $user->id, 4361 'userid2' => $user->id, 4362 'userid3' => $user->id, 4363 'firstread' => $now, 4364 'lastread' => $now, 4365 'cutoffdate' => $cutoffdate, 4366 ); 4367 $params = array_merge($postidparams, $insertparams); 4368 4369 if ($CFG->forum_allowforcedreadtracking) { 4370 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED." 4371 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL))"; 4372 } else { 4373 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.") 4374 AND tf.id IS NULL)"; 4375 } 4376 4377 // First insert any new entries. 4378 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread) 4379 4380 SELECT :userid1, p.id, p.discussion, d.forum, :firstread, :lastread 4381 FROM {forum_posts} p 4382 JOIN {forum_discussions} d ON d.id = p.discussion 4383 JOIN {forum} f ON f.id = d.forum 4384 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = :userid2 AND tf.forumid = f.id) 4385 LEFT JOIN {forum_read} fr ON ( 4386 fr.userid = :userid3 4387 AND fr.postid = p.id 4388 AND fr.discussionid = d.id 4389 AND fr.forumid = f.id 4390 ) 4391 WHERE p.id $usql 4392 AND p.modified >= :cutoffdate 4393 $trackingsql 4394 AND fr.id IS NULL"; 4395 4396 $status = $DB->execute($sql, $params) && $status; 4397 4398 // Then update all records. 4399 $updateparams = array( 4400 'userid' => $user->id, 4401 'lastread' => $now, 4402 ); 4403 $params = array_merge($postidparams, $updateparams); 4404 $status = $DB->set_field_select('forum_read', 'lastread', $now, ' 4405 userid = :userid 4406 AND lastread <> :lastread 4407 AND postid ' . $usql, 4408 $params) && $status; 4409 4410 return $status; 4411 } 4412 4413 /** 4414 * Mark post as read. 4415 * @global object 4416 * @global object 4417 * @param int $userid 4418 * @param int $postid 4419 */ 4420 function forum_tp_add_read_record($userid, $postid) { 4421 global $CFG, $DB; 4422 4423 $now = time(); 4424 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 3600); 4425 4426 if (!$DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $postid))) { 4427 $sql = "INSERT INTO {forum_read} (userid, postid, discussionid, forumid, firstread, lastread) 4428 4429 SELECT ?, p.id, p.discussion, d.forum, ?, ? 4430 FROM {forum_posts} p 4431 JOIN {forum_discussions} d ON d.id = p.discussion 4432 WHERE p.id = ? AND p.modified >= ?"; 4433 return $DB->execute($sql, array($userid, $now, $now, $postid, $cutoffdate)); 4434 4435 } else { 4436 $sql = "UPDATE {forum_read} 4437 SET lastread = ? 4438 WHERE userid = ? AND postid = ?"; 4439 return $DB->execute($sql, array($now, $userid, $userid)); 4440 } 4441 } 4442 4443 /** 4444 * If its an old post, do nothing. If the record exists, the maintenance will clear it up later. 4445 * 4446 * @param int $userid The ID of the user to mark posts read for. 4447 * @param object $post The post record for the post to mark as read. 4448 * @param mixed $unused 4449 * @return bool 4450 */ 4451 function forum_tp_mark_post_read($userid, $post, $unused = null) { 4452 if (!forum_tp_is_post_old($post)) { 4453 return forum_tp_add_read_record($userid, $post->id); 4454 } else { 4455 return true; 4456 } 4457 } 4458 4459 /** 4460 * Marks a whole forum as read, for a given user 4461 * 4462 * @global object 4463 * @global object 4464 * @param object $user 4465 * @param int $forumid 4466 * @param int|bool $groupid 4467 * @return bool 4468 */ 4469 function forum_tp_mark_forum_read($user, $forumid, $groupid=false) { 4470 global $CFG, $DB; 4471 4472 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60); 4473 4474 $groupsel = ""; 4475 $params = array($user->id, $forumid, $cutoffdate); 4476 4477 if ($groupid !== false) { 4478 $groupsel = " AND (d.groupid = ? OR d.groupid = -1)"; 4479 $params[] = $groupid; 4480 } 4481 4482 $sql = "SELECT p.id 4483 FROM {forum_posts} p 4484 LEFT JOIN {forum_discussions} d ON d.id = p.discussion 4485 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?) 4486 WHERE d.forum = ? 4487 AND p.modified >= ? AND r.id is NULL 4488 $groupsel"; 4489 4490 if ($posts = $DB->get_records_sql($sql, $params)) { 4491 $postids = array_keys($posts); 4492 return forum_tp_mark_posts_read($user, $postids); 4493 } 4494 4495 return true; 4496 } 4497 4498 /** 4499 * Marks a whole discussion as read, for a given user 4500 * 4501 * @global object 4502 * @global object 4503 * @param object $user 4504 * @param int $discussionid 4505 * @return bool 4506 */ 4507 function forum_tp_mark_discussion_read($user, $discussionid) { 4508 global $CFG, $DB; 4509 4510 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60); 4511 4512 $sql = "SELECT p.id 4513 FROM {forum_posts} p 4514 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?) 4515 WHERE p.discussion = ? 4516 AND p.modified >= ? AND r.id is NULL"; 4517 4518 if ($posts = $DB->get_records_sql($sql, array($user->id, $discussionid, $cutoffdate))) { 4519 $postids = array_keys($posts); 4520 return forum_tp_mark_posts_read($user, $postids); 4521 } 4522 4523 return true; 4524 } 4525 4526 /** 4527 * @global object 4528 * @param int $userid 4529 * @param object $post 4530 */ 4531 function forum_tp_is_post_read($userid, $post) { 4532 global $DB; 4533 return (forum_tp_is_post_old($post) || 4534 $DB->record_exists('forum_read', array('userid' => $userid, 'postid' => $post->id))); 4535 } 4536 4537 /** 4538 * @global object 4539 * @param object $post 4540 * @param int $time Defautls to time() 4541 */ 4542 function forum_tp_is_post_old($post, $time=null) { 4543 global $CFG; 4544 4545 if (is_null($time)) { 4546 $time = time(); 4547 } 4548 return ($post->modified < ($time - ($CFG->forum_oldpostdays * 24 * 3600))); 4549 } 4550 4551 /** 4552 * Returns the count of records for the provided user and course. 4553 * Please note that group access is ignored! 4554 * 4555 * @global object 4556 * @global object 4557 * @param int $userid 4558 * @param int $courseid 4559 * @return array 4560 */ 4561 function forum_tp_get_course_unread_posts($userid, $courseid) { 4562 global $CFG, $DB; 4563 4564 $now = floor(time() / 60) * 60; // DB cache friendliness. 4565 $cutoffdate = $now - ($CFG->forum_oldpostdays * 24 * 60 * 60); 4566 $params = array($userid, $userid, $courseid, $cutoffdate, $userid); 4567 4568 if (!empty($CFG->forum_enabletimedposts)) { 4569 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)"; 4570 $params[] = $now; 4571 $params[] = $now; 4572 } else { 4573 $timedsql = ""; 4574 } 4575 4576 if ($CFG->forum_allowforcedreadtracking) { 4577 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_FORCED." 4578 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND tf.id IS NULL 4579 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1))"; 4580 } else { 4581 $trackingsql = "AND ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.") 4582 AND tf.id IS NULL 4583 AND (SELECT trackforums FROM {user} WHERE id = ?) = 1)"; 4584 } 4585 4586 $sql = "SELECT f.id, COUNT(p.id) AS unread 4587 FROM {forum_posts} p 4588 JOIN {forum_discussions} d ON d.id = p.discussion 4589 JOIN {forum} f ON f.id = d.forum 4590 JOIN {course} c ON c.id = f.course 4591 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?) 4592 LEFT JOIN {forum_track_prefs} tf ON (tf.userid = ? AND tf.forumid = f.id) 4593 WHERE f.course = ? 4594 AND p.modified >= ? AND r.id is NULL 4595 $trackingsql 4596 $timedsql 4597 GROUP BY f.id"; 4598 4599 if ($return = $DB->get_records_sql($sql, $params)) { 4600 return $return; 4601 } 4602 4603 return array(); 4604 } 4605 4606 /** 4607 * Returns the count of records for the provided user and forum and [optionally] group. 4608 * 4609 * @global object 4610 * @global object 4611 * @global object 4612 * @param object $cm 4613 * @param object $course 4614 * @param bool $resetreadcache optional, true to reset the function static $readcache var 4615 * @return int 4616 */ 4617 function forum_tp_count_forum_unread_posts($cm, $course, $resetreadcache = false) { 4618 global $CFG, $USER, $DB; 4619 4620 static $readcache = array(); 4621 4622 if ($resetreadcache) { 4623 $readcache = array(); 4624 } 4625 4626 $forumid = $cm->instance; 4627 4628 if (!isset($readcache[$course->id])) { 4629 $readcache[$course->id] = array(); 4630 if ($counts = forum_tp_get_course_unread_posts($USER->id, $course->id)) { 4631 foreach ($counts as $count) { 4632 $readcache[$course->id][$count->id] = $count->unread; 4633 } 4634 } 4635 } 4636 4637 if (empty($readcache[$course->id][$forumid])) { 4638 // no need to check group mode ;-) 4639 return 0; 4640 } 4641 4642 $groupmode = groups_get_activity_groupmode($cm, $course); 4643 4644 if ($groupmode != SEPARATEGROUPS) { 4645 return $readcache[$course->id][$forumid]; 4646 } 4647 4648 if (has_capability('moodle/site:accessallgroups', context_module::instance($cm->id))) { 4649 return $readcache[$course->id][$forumid]; 4650 } 4651 4652 require_once($CFG->dirroot.'/course/lib.php'); 4653 4654 $modinfo = get_fast_modinfo($course); 4655 4656 $mygroups = $modinfo->get_groups($cm->groupingid); 4657 4658 // add all groups posts 4659 $mygroups[-1] = -1; 4660 4661 list ($groups_sql, $groups_params) = $DB->get_in_or_equal($mygroups); 4662 4663 $now = floor(time() / 60) * 60; // DB Cache friendliness. 4664 $cutoffdate = $now - ($CFG->forum_oldpostdays*24*60*60); 4665 $params = array($USER->id, $forumid, $cutoffdate); 4666 4667 if (!empty($CFG->forum_enabletimedposts)) { 4668 $timedsql = "AND d.timestart < ? AND (d.timeend = 0 OR d.timeend > ?)"; 4669 $params[] = $now; 4670 $params[] = $now; 4671 } else { 4672 $timedsql = ""; 4673 } 4674 4675 $params = array_merge($params, $groups_params); 4676 4677 $sql = "SELECT COUNT(p.id) 4678 FROM {forum_posts} p 4679 JOIN {forum_discussions} d ON p.discussion = d.id 4680 LEFT JOIN {forum_read} r ON (r.postid = p.id AND r.userid = ?) 4681 WHERE d.forum = ? 4682 AND p.modified >= ? AND r.id is NULL 4683 $timedsql 4684 AND d.groupid $groups_sql"; 4685 4686 return $DB->get_field_sql($sql, $params); 4687 } 4688 4689 /** 4690 * Deletes read records for the specified index. At least one parameter must be specified. 4691 * 4692 * @global object 4693 * @param int $userid 4694 * @param int $postid 4695 * @param int $discussionid 4696 * @param int $forumid 4697 * @return bool 4698 */ 4699 function forum_tp_delete_read_records($userid=-1, $postid=-1, $discussionid=-1, $forumid=-1) { 4700 global $DB; 4701 $params = array(); 4702 4703 $select = ''; 4704 if ($userid > -1) { 4705 if ($select != '') $select .= ' AND '; 4706 $select .= 'userid = ?'; 4707 $params[] = $userid; 4708 } 4709 if ($postid > -1) { 4710 if ($select != '') $select .= ' AND '; 4711 $select .= 'postid = ?'; 4712 $params[] = $postid; 4713 } 4714 if ($discussionid > -1) { 4715 if ($select != '') $select .= ' AND '; 4716 $select .= 'discussionid = ?'; 4717 $params[] = $discussionid; 4718 } 4719 if ($forumid > -1) { 4720 if ($select != '') $select .= ' AND '; 4721 $select .= 'forumid = ?'; 4722 $params[] = $forumid; 4723 } 4724 if ($select == '') { 4725 return false; 4726 } 4727 else { 4728 return $DB->delete_records_select('forum_read', $select, $params); 4729 } 4730 } 4731 /** 4732 * Get a list of forums not tracked by the user. 4733 * 4734 * @global object 4735 * @global object 4736 * @param int $userid The id of the user to use. 4737 * @param int $courseid The id of the course being checked. 4738 * @return mixed An array indexed by forum id, or false. 4739 */ 4740 function forum_tp_get_untracked_forums($userid, $courseid) { 4741 global $CFG, $DB; 4742 4743 if ($CFG->forum_allowforcedreadtracking) { 4744 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF." 4745 OR (f.trackingtype = ".FORUM_TRACKING_OPTIONAL." AND (ft.id IS NOT NULL 4746 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))"; 4747 } else { 4748 $trackingsql = "AND (f.trackingtype = ".FORUM_TRACKING_OFF." 4749 OR ((f.trackingtype = ".FORUM_TRACKING_OPTIONAL." OR f.trackingtype = ".FORUM_TRACKING_FORCED.") 4750 AND (ft.id IS NOT NULL 4751 OR (SELECT trackforums FROM {user} WHERE id = ?) = 0)))"; 4752 } 4753 4754 $sql = "SELECT f.id 4755 FROM {forum} f 4756 LEFT JOIN {forum_track_prefs} ft ON (ft.forumid = f.id AND ft.userid = ?) 4757 WHERE f.course = ? 4758 $trackingsql"; 4759 4760 if ($forums = $DB->get_records_sql($sql, array($userid, $courseid, $userid))) { 4761 foreach ($forums as $forum) { 4762 $forums[$forum->id] = $forum; 4763 } 4764 return $forums; 4765 4766 } else { 4767 return array(); 4768 } 4769 } 4770 4771 /** 4772 * Determine if a user can track forums and optionally a particular forum. 4773 * Checks the site settings, the user settings and the forum settings (if 4774 * requested). 4775 * 4776 * @global object 4777 * @global object 4778 * @global object 4779 * @param mixed $forum The forum object to test, or the int id (optional). 4780 * @param mixed $userid The user object to check for (optional). 4781 * @return boolean 4782 */ 4783 function forum_tp_can_track_forums($forum=false, $user=false) { 4784 global $USER, $CFG, $DB; 4785 4786 // if possible, avoid expensive 4787 // queries 4788 if (empty($CFG->forum_trackreadposts)) { 4789 return false; 4790 } 4791 4792 if ($user === false) { 4793 $user = $USER; 4794 } 4795 4796 if (isguestuser($user) or empty($user->id)) { 4797 return false; 4798 } 4799 4800 if ($forum === false) { 4801 if ($CFG->forum_allowforcedreadtracking) { 4802 // Since we can force tracking, assume yes without a specific forum. 4803 return true; 4804 } else { 4805 return (bool)$user->trackforums; 4806 } 4807 } 4808 4809 // Work toward always passing an object... 4810 if (is_numeric($forum)) { 4811 debugging('Better use proper forum object.', DEBUG_DEVELOPER); 4812 $forum = $DB->get_record('forum', array('id' => $forum), '', 'id,trackingtype'); 4813 } 4814 4815 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL); 4816 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED); 4817 4818 if ($CFG->forum_allowforcedreadtracking) { 4819 // If we allow forcing, then forced forums takes procidence over user setting. 4820 return ($forumforced || ($forumallows && (!empty($user->trackforums) && (bool)$user->trackforums))); 4821 } else { 4822 // If we don't allow forcing, user setting trumps. 4823 return ($forumforced || $forumallows) && !empty($user->trackforums); 4824 } 4825 } 4826 4827 /** 4828 * Tells whether a specific forum is tracked by the user. A user can optionally 4829 * be specified. If not specified, the current user is assumed. 4830 * 4831 * @global object 4832 * @global object 4833 * @global object 4834 * @param mixed $forum If int, the id of the forum being checked; if object, the forum object 4835 * @param int $userid The id of the user being checked (optional). 4836 * @return boolean 4837 */ 4838 function forum_tp_is_tracked($forum, $user=false) { 4839 global $USER, $CFG, $DB; 4840 4841 if ($user === false) { 4842 $user = $USER; 4843 } 4844 4845 if (isguestuser($user) or empty($user->id)) { 4846 return false; 4847 } 4848 4849 $cache = cache::make('mod_forum', 'forum_is_tracked'); 4850 $forumid = is_numeric($forum) ? $forum : $forum->id; 4851 $key = $forumid . '_' . $user->id; 4852 if ($cachedvalue = $cache->get($key)) { 4853 return $cachedvalue == 'tracked'; 4854 } 4855 4856 // Work toward always passing an object... 4857 if (is_numeric($forum)) { 4858 debugging('Better use proper forum object.', DEBUG_DEVELOPER); 4859 $forum = $DB->get_record('forum', array('id' => $forum)); 4860 } 4861 4862 if (!forum_tp_can_track_forums($forum, $user)) { 4863 return false; 4864 } 4865 4866 $forumallows = ($forum->trackingtype == FORUM_TRACKING_OPTIONAL); 4867 $forumforced = ($forum->trackingtype == FORUM_TRACKING_FORCED); 4868 $userpref = $DB->get_record('forum_track_prefs', array('userid' => $user->id, 'forumid' => $forum->id)); 4869 4870 if ($CFG->forum_allowforcedreadtracking) { 4871 $istracked = $forumforced || ($forumallows && $userpref === false); 4872 } else { 4873 $istracked = ($forumallows || $forumforced) && $userpref === false; 4874 } 4875 4876 // We have to store a string here because the cache API returns false 4877 // when it can't find the key which would be confused with our legitimate 4878 // false value. *sigh*. 4879 $cache->set($key, $istracked ? 'tracked' : 'not'); 4880 4881 return $istracked; 4882 } 4883 4884 /** 4885 * @global object 4886 * @global object 4887 * @param int $forumid 4888 * @param int $userid 4889 */ 4890 function forum_tp_start_tracking($forumid, $userid=false) { 4891 global $USER, $DB; 4892 4893 if ($userid === false) { 4894 $userid = $USER->id; 4895 } 4896 4897 return $DB->delete_records('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid)); 4898 } 4899 4900 /** 4901 * @global object 4902 * @global object 4903 * @param int $forumid 4904 * @param int $userid 4905 */ 4906 function forum_tp_stop_tracking($forumid, $userid=false) { 4907 global $USER, $DB; 4908 4909 if ($userid === false) { 4910 $userid = $USER->id; 4911 } 4912 4913 if (!$DB->record_exists('forum_track_prefs', array('userid' => $userid, 'forumid' => $forumid))) { 4914 $track_prefs = new stdClass(); 4915 $track_prefs->userid = $userid; 4916 $track_prefs->forumid = $forumid; 4917 $DB->insert_record('forum_track_prefs', $track_prefs); 4918 } 4919 4920 return forum_tp_delete_read_records($userid, -1, -1, $forumid); 4921 } 4922 4923 4924 /** 4925 * Clean old records from the forum_read table. 4926 * @global object 4927 * @global object 4928 * @return void 4929 */ 4930 function forum_tp_clean_read_records() { 4931 global $CFG, $DB; 4932 4933 if (!isset($CFG->forum_oldpostdays)) { 4934 return; 4935 } 4936 // Look for records older than the cutoffdate that are still in the forum_read table. 4937 $cutoffdate = time() - ($CFG->forum_oldpostdays*24*60*60); 4938 4939 //first get the oldest tracking present - we need tis to speedup the next delete query 4940 $sql = "SELECT MIN(fp.modified) AS first 4941 FROM {forum_posts} fp 4942 JOIN {forum_read} fr ON fr.postid=fp.id"; 4943 if (!$first = $DB->get_field_sql($sql)) { 4944 // nothing to delete; 4945 return; 4946 } 4947 4948 // now delete old tracking info 4949 $sql = "DELETE 4950 FROM {forum_read} 4951 WHERE postid IN (SELECT fp.id 4952 FROM {forum_posts} fp 4953 WHERE fp.modified >= ? AND fp.modified < ?)"; 4954 $DB->execute($sql, array($first, $cutoffdate)); 4955 } 4956 4957 /** 4958 * Sets the last post for a given discussion 4959 * 4960 * @global object 4961 * @global object 4962 * @param into $discussionid 4963 * @return bool|int 4964 **/ 4965 function forum_discussion_update_last_post($discussionid) { 4966 global $CFG, $DB; 4967 4968 // Check the given discussion exists 4969 if (!$DB->record_exists('forum_discussions', array('id' => $discussionid))) { 4970 return false; 4971 } 4972 4973 // Use SQL to find the last post for this discussion 4974 $sql = "SELECT id, userid, modified 4975 FROM {forum_posts} 4976 WHERE discussion=? 4977 ORDER BY modified DESC"; 4978 4979 // Lets go find the last post 4980 if (($lastposts = $DB->get_records_sql($sql, array($discussionid), 0, 1))) { 4981 $lastpost = reset($lastposts); 4982 $discussionobject = new stdClass(); 4983 $discussionobject->id = $discussionid; 4984 $discussionobject->usermodified = $lastpost->userid; 4985 $discussionobject->timemodified = $lastpost->modified; 4986 $DB->update_record('forum_discussions', $discussionobject); 4987 return $lastpost->id; 4988 } 4989 4990 // To get here either we couldn't find a post for the discussion (weird) 4991 // or we couldn't update the discussion record (weird x2) 4992 return false; 4993 } 4994 4995 4996 /** 4997 * List the actions that correspond to a view of this module. 4998 * This is used by the participation report. 4999 * 5000 * Note: This is not used by new logging system. Event with 5001 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will 5002 * be considered as view action. 5003 * 5004 * @return array 5005 */ 5006 function forum_get_view_actions() { 5007 return array('view discussion', 'search', 'forum', 'forums', 'subscribers', 'view forum'); 5008 } 5009 5010 /** 5011 * List the options for forum subscription modes. 5012 * This is used by the settings page and by the mod_form page. 5013 * 5014 * @return array 5015 */ 5016 function forum_get_subscriptionmode_options() { 5017 $options = array(); 5018 $options[FORUM_CHOOSESUBSCRIBE] = get_string('subscriptionoptional', 'forum'); 5019 $options[FORUM_FORCESUBSCRIBE] = get_string('subscriptionforced', 'forum'); 5020 $options[FORUM_INITIALSUBSCRIBE] = get_string('subscriptionauto', 'forum'); 5021 $options[FORUM_DISALLOWSUBSCRIBE] = get_string('subscriptiondisabled', 'forum'); 5022 return $options; 5023 } 5024 5025 /** 5026 * List the actions that correspond to a post of this module. 5027 * This is used by the participation report. 5028 * 5029 * Note: This is not used by new logging system. Event with 5030 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING 5031 * will be considered as post action. 5032 * 5033 * @return array 5034 */ 5035 function forum_get_post_actions() { 5036 return array('add discussion','add post','delete discussion','delete post','move discussion','prune post','update post'); 5037 } 5038 5039 /** 5040 * Returns a warning object if a user has reached the number of posts equal to 5041 * the warning/blocking setting, or false if there is no warning to show. 5042 * 5043 * @param int|stdClass $forum the forum id or the forum object 5044 * @param stdClass $cm the course module 5045 * @return stdClass|bool returns an object with the warning information, else 5046 * returns false if no warning is required. 5047 */ 5048 function forum_check_throttling($forum, $cm = null) { 5049 global $CFG, $DB, $USER; 5050 5051 if (is_numeric($forum)) { 5052 $forum = $DB->get_record('forum', array('id' => $forum), '*', MUST_EXIST); 5053 } 5054 5055 if (!is_object($forum)) { 5056 return false; // This is broken. 5057 } 5058 5059 if (!$cm) { 5060 $cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course, false, MUST_EXIST); 5061 } 5062 5063 if (empty($forum->blockafter)) { 5064 return false; 5065 } 5066 5067 if (empty($forum->blockperiod)) { 5068 return false; 5069 } 5070 5071 $modcontext = context_module::instance($cm->id); 5072 if (has_capability('mod/forum:postwithoutthrottling', $modcontext)) { 5073 return false; 5074 } 5075 5076 // Get the number of posts in the last period we care about. 5077 $timenow = time(); 5078 $timeafter = $timenow - $forum->blockperiod; 5079 $numposts = $DB->count_records_sql('SELECT COUNT(p.id) FROM {forum_posts} p 5080 JOIN {forum_discussions} d 5081 ON p.discussion = d.id WHERE d.forum = ? 5082 AND p.userid = ? AND p.created > ?', array($forum->id, $USER->id, $timeafter)); 5083 5084 $a = new stdClass(); 5085 $a->blockafter = $forum->blockafter; 5086 $a->numposts = $numposts; 5087 $a->blockperiod = get_string('secondstotime'.$forum->blockperiod); 5088 5089 if ($forum->blockafter <= $numposts) { 5090 $warning = new stdClass(); 5091 $warning->canpost = false; 5092 $warning->errorcode = 'forumblockingtoomanyposts'; 5093 $warning->module = 'error'; 5094 $warning->additional = $a; 5095 $warning->link = $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id; 5096 5097 return $warning; 5098 } 5099 5100 if ($forum->warnafter <= $numposts) { 5101 $warning = new stdClass(); 5102 $warning->canpost = true; 5103 $warning->errorcode = 'forumblockingalmosttoomanyposts'; 5104 $warning->module = 'forum'; 5105 $warning->additional = $a; 5106 $warning->link = null; 5107 5108 return $warning; 5109 } 5110 } 5111 5112 /** 5113 * Throws an error if the user is no longer allowed to post due to having reached 5114 * or exceeded the number of posts specified in 'Post threshold for blocking' 5115 * setting. 5116 * 5117 * @since Moodle 2.5 5118 * @param stdClass $thresholdwarning the warning information returned 5119 * from the function forum_check_throttling. 5120 */ 5121 function forum_check_blocking_threshold($thresholdwarning) { 5122 if (!empty($thresholdwarning) && !$thresholdwarning->canpost) { 5123 print_error($thresholdwarning->errorcode, 5124 $thresholdwarning->module, 5125 $thresholdwarning->link, 5126 $thresholdwarning->additional); 5127 } 5128 } 5129 5130 5131 /** 5132 * Removes all grades from gradebook 5133 * 5134 * @global object 5135 * @global object 5136 * @param int $courseid 5137 * @param string $type optional 5138 */ 5139 function forum_reset_gradebook($courseid, $type='') { 5140 global $CFG, $DB; 5141 5142 $wheresql = ''; 5143 $params = array($courseid); 5144 if ($type) { 5145 $wheresql = "AND f.type=?"; 5146 $params[] = $type; 5147 } 5148 5149 $sql = "SELECT f.*, cm.idnumber as cmidnumber, f.course as courseid 5150 FROM {forum} f, {course_modules} cm, {modules} m 5151 WHERE m.name='forum' AND m.id=cm.module AND cm.instance=f.id AND f.course=? $wheresql"; 5152 5153 if ($forums = $DB->get_records_sql($sql, $params)) { 5154 foreach ($forums as $forum) { 5155 forum_grade_item_update($forum, 'reset', 'reset'); 5156 } 5157 } 5158 } 5159 5160 /** 5161 * This function is used by the reset_course_userdata function in moodlelib. 5162 * This function will remove all posts from the specified forum 5163 * and clean up any related data. 5164 * 5165 * @global object 5166 * @global object 5167 * @param $data the data submitted from the reset course. 5168 * @return array status array 5169 */ 5170 function forum_reset_userdata($data) { 5171 global $CFG, $DB; 5172 require_once($CFG->dirroot.'/rating/lib.php'); 5173 5174 $componentstr = get_string('modulenameplural', 'forum'); 5175 $status = array(); 5176 5177 $params = array($data->courseid); 5178 5179 $removeposts = false; 5180 $typesql = ""; 5181 if (!empty($data->reset_forum_all)) { 5182 $removeposts = true; 5183 $typesstr = get_string('resetforumsall', 'forum'); 5184 $types = array(); 5185 } else if (!empty($data->reset_forum_types)){ 5186 $removeposts = true; 5187 $types = array(); 5188 $sqltypes = array(); 5189 $forum_types_all = forum_get_forum_types_all(); 5190 foreach ($data->reset_forum_types as $type) { 5191 if (!array_key_exists($type, $forum_types_all)) { 5192 continue; 5193 } 5194 $types[] = $forum_types_all[$type]; 5195 $sqltypes[] = $type; 5196 } 5197 if (!empty($sqltypes)) { 5198 list($typesql, $typeparams) = $DB->get_in_or_equal($sqltypes); 5199 $typesql = " AND f.type " . $typesql; 5200 $params = array_merge($params, $typeparams); 5201 } 5202 $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types); 5203 } 5204 $alldiscussionssql = "SELECT fd.id 5205 FROM {forum_discussions} fd, {forum} f 5206 WHERE f.course=? AND f.id=fd.forum"; 5207 5208 $allforumssql = "SELECT f.id 5209 FROM {forum} f 5210 WHERE f.course=?"; 5211 5212 $allpostssql = "SELECT fp.id 5213 FROM {forum_posts} fp, {forum_discussions} fd, {forum} f 5214 WHERE f.course=? AND f.id=fd.forum AND fd.id=fp.discussion"; 5215 5216 $forumssql = $forums = $rm = null; 5217 5218 // Check if we need to get additional data. 5219 if ($removeposts || !empty($data->reset_forum_ratings) || !empty($data->reset_forum_tags)) { 5220 // Set this up if we have to remove ratings. 5221 $rm = new rating_manager(); 5222 $ratingdeloptions = new stdClass; 5223 $ratingdeloptions->component = 'mod_forum'; 5224 $ratingdeloptions->ratingarea = 'post'; 5225 5226 // Get the forums for actions that require it. 5227 $forumssql = "$allforumssql $typesql"; 5228 $forums = $DB->get_records_sql($forumssql, $params); 5229 } 5230 5231 if ($removeposts) { 5232 $discussionssql = "$alldiscussionssql $typesql"; 5233 $postssql = "$allpostssql $typesql"; 5234 5235 // now get rid of all attachments 5236 $fs = get_file_storage(); 5237 if ($forums) { 5238 foreach ($forums as $forumid=>$unused) { 5239 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) { 5240 continue; 5241 } 5242 $context = context_module::instance($cm->id); 5243 $fs->delete_area_files($context->id, 'mod_forum', 'attachment'); 5244 $fs->delete_area_files($context->id, 'mod_forum', 'post'); 5245 5246 //remove ratings 5247 $ratingdeloptions->contextid = $context->id; 5248 $rm->delete_ratings($ratingdeloptions); 5249 5250 core_tag_tag::delete_instances('mod_forum', null, $context->id); 5251 } 5252 } 5253 5254 // first delete all read flags 5255 $DB->delete_records_select('forum_read', "forumid IN ($forumssql)", $params); 5256 5257 // remove tracking prefs 5258 $DB->delete_records_select('forum_track_prefs', "forumid IN ($forumssql)", $params); 5259 5260 // remove posts from queue 5261 $DB->delete_records_select('forum_queue', "discussionid IN ($discussionssql)", $params); 5262 5263 // all posts - initial posts must be kept in single simple discussion forums 5264 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql) AND parent <> 0", $params); // first all children 5265 $DB->delete_records_select('forum_posts', "discussion IN ($discussionssql AND f.type <> 'single') AND parent = 0", $params); // now the initial posts for non single simple 5266 5267 // finally all discussions except single simple forums 5268 $DB->delete_records_select('forum_discussions', "forum IN ($forumssql AND f.type <> 'single')", $params); 5269 5270 // remove all grades from gradebook 5271 if (empty($data->reset_gradebook_grades)) { 5272 if (empty($types)) { 5273 forum_reset_gradebook($data->courseid); 5274 } else { 5275 foreach ($types as $type) { 5276 forum_reset_gradebook($data->courseid, $type); 5277 } 5278 } 5279 } 5280 5281 $status[] = array('component'=>$componentstr, 'item'=>$typesstr, 'error'=>false); 5282 } 5283 5284 // remove all ratings in this course's forums 5285 if (!empty($data->reset_forum_ratings)) { 5286 if ($forums) { 5287 foreach ($forums as $forumid=>$unused) { 5288 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) { 5289 continue; 5290 } 5291 $context = context_module::instance($cm->id); 5292 5293 //remove ratings 5294 $ratingdeloptions->contextid = $context->id; 5295 $rm->delete_ratings($ratingdeloptions); 5296 } 5297 } 5298 5299 // remove all grades from gradebook 5300 if (empty($data->reset_gradebook_grades)) { 5301 forum_reset_gradebook($data->courseid); 5302 } 5303 } 5304 5305 // Remove all the tags. 5306 if (!empty($data->reset_forum_tags)) { 5307 if ($forums) { 5308 foreach ($forums as $forumid => $unused) { 5309 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) { 5310 continue; 5311 } 5312 5313 $context = context_module::instance($cm->id); 5314 core_tag_tag::delete_instances('mod_forum', null, $context->id); 5315 } 5316 } 5317 5318 $status[] = array('component' => $componentstr, 'item' => get_string('tagsdeleted', 'forum'), 'error' => false); 5319 } 5320 5321 // remove all digest settings unconditionally - even for users still enrolled in course. 5322 if (!empty($data->reset_forum_digests)) { 5323 $DB->delete_records_select('forum_digests', "forum IN ($allforumssql)", $params); 5324 $status[] = array('component' => $componentstr, 'item' => get_string('resetdigests', 'forum'), 'error' => false); 5325 } 5326 5327 // remove all subscriptions unconditionally - even for users still enrolled in course 5328 if (!empty($data->reset_forum_subscriptions)) { 5329 $DB->delete_records_select('forum_subscriptions', "forum IN ($allforumssql)", $params); 5330 $DB->delete_records_select('forum_discussion_subs', "forum IN ($allforumssql)", $params); 5331 $status[] = array('component' => $componentstr, 'item' => get_string('resetsubscriptions', 'forum'), 'error' => false); 5332 } 5333 5334 // remove all tracking prefs unconditionally - even for users still enrolled in course 5335 if (!empty($data->reset_forum_track_prefs)) { 5336 $DB->delete_records_select('forum_track_prefs', "forumid IN ($allforumssql)", $params); 5337 $status[] = array('component'=>$componentstr, 'item'=>get_string('resettrackprefs','forum'), 'error'=>false); 5338 } 5339 5340 /// updating dates - shift may be negative too 5341 if ($data->timeshift) { 5342 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset. 5343 // See MDL-9367. 5344 shift_course_mod_dates('forum', array('assesstimestart', 'assesstimefinish'), $data->timeshift, $data->courseid); 5345 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false); 5346 } 5347 5348 return $status; 5349 } 5350 5351 /** 5352 * Called by course/reset.php 5353 * 5354 * @param $mform form passed by reference 5355 */ 5356 function forum_reset_course_form_definition(&$mform) { 5357 $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum')); 5358 5359 $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum')); 5360 5361 $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple')); 5362 $mform->setAdvanced('reset_forum_types'); 5363 $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked'); 5364 5365 $mform->addElement('checkbox', 'reset_forum_digests', get_string('resetdigests','forum')); 5366 $mform->setAdvanced('reset_forum_digests'); 5367 5368 $mform->addElement('checkbox', 'reset_forum_subscriptions', get_string('resetsubscriptions','forum')); 5369 $mform->setAdvanced('reset_forum_subscriptions'); 5370 5371 $mform->addElement('checkbox', 'reset_forum_track_prefs', get_string('resettrackprefs','forum')); 5372 $mform->setAdvanced('reset_forum_track_prefs'); 5373 $mform->disabledIf('reset_forum_track_prefs', 'reset_forum_all', 'checked'); 5374 5375 $mform->addElement('checkbox', 'reset_forum_ratings', get_string('deleteallratings')); 5376 $mform->disabledIf('reset_forum_ratings', 'reset_forum_all', 'checked'); 5377 5378 $mform->addElement('checkbox', 'reset_forum_tags', get_string('removeallforumtags', 'forum')); 5379 $mform->disabledIf('reset_forum_tags', 'reset_forum_all', 'checked'); 5380 } 5381 5382 /** 5383 * Course reset form defaults. 5384 * @return array 5385 */ 5386 function forum_reset_course_form_defaults($course) { 5387 return array('reset_forum_all'=>1, 'reset_forum_digests' => 0, 'reset_forum_subscriptions'=>0, 'reset_forum_track_prefs'=>0, 'reset_forum_ratings'=>1); 5388 } 5389 5390 /** 5391 * Returns array of forum layout modes 5392 * 5393 * @param bool $useexperimentalui use experimental layout modes or not 5394 * @return array 5395 */ 5396 function forum_get_layout_modes(bool $useexperimentalui = false) { 5397 $modes = [ 5398 FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'), 5399 FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'), 5400 FORUM_MODE_THREADED => get_string('modethreaded', 'forum') 5401 ]; 5402 5403 if ($useexperimentalui) { 5404 $modes[FORUM_MODE_NESTED_V2] = get_string('modenestedv2', 'forum'); 5405 } else { 5406 $modes[FORUM_MODE_NESTED] = get_string('modenested', 'forum'); 5407 } 5408 5409 return $modes; 5410 } 5411 5412 /** 5413 * Returns array of forum types chooseable on the forum editing form 5414 * 5415 * @return array 5416 */ 5417 function forum_get_forum_types() { 5418 return array ('general' => get_string('generalforum', 'forum'), 5419 'eachuser' => get_string('eachuserforum', 'forum'), 5420 'single' => get_string('singleforum', 'forum'), 5421 'qanda' => get_string('qandaforum', 'forum'), 5422 'blog' => get_string('blogforum', 'forum')); 5423 } 5424 5425 /** 5426 * Returns array of all forum layout modes 5427 * 5428 * @return array 5429 */ 5430 function forum_get_forum_types_all() { 5431 return array ('news' => get_string('namenews','forum'), 5432 'social' => get_string('namesocial','forum'), 5433 'general' => get_string('generalforum', 'forum'), 5434 'eachuser' => get_string('eachuserforum', 'forum'), 5435 'single' => get_string('singleforum', 'forum'), 5436 'qanda' => get_string('qandaforum', 'forum'), 5437 'blog' => get_string('blogforum', 'forum')); 5438 } 5439 5440 /** 5441 * Returns all other caps used in module 5442 * 5443 * @return array 5444 */ 5445 function forum_get_extra_capabilities() { 5446 return ['moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate']; 5447 } 5448 5449 /** 5450 * Adds module specific settings to the settings block 5451 * 5452 * @param settings_navigation $settings The settings navigation object 5453 * @param navigation_node $forumnode The node to add module settings to 5454 */ 5455 function forum_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $forumnode) { 5456 global $USER, $PAGE, $CFG, $DB, $OUTPUT; 5457 5458 if (empty($PAGE->cm->context)) { 5459 $PAGE->cm->context = context_module::instance($PAGE->cm->instance); 5460 } 5461 5462 $vaultfactory = mod_forum\local\container::get_vault_factory(); 5463 $managerfactory = mod_forum\local\container::get_manager_factory(); 5464 $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory(); 5465 $forumvault = $vaultfactory->get_forum_vault(); 5466 $forumentity = $forumvault->get_from_id($PAGE->cm->instance); 5467 $forumobject = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forumentity); 5468 5469 $params = $PAGE->url->params(); 5470 if (!empty($params['d'])) { 5471 $discussionid = $params['d']; 5472 } 5473 5474 // Display all forum reports user has access to. 5475 if (isloggedin() && !isguestuser()) { 5476 $reportnames = array_keys(core_component::get_plugin_list('forumreport')); 5477 5478 foreach ($reportnames as $reportname) { 5479 if (has_capability("forumreport/{$reportname}:view", $PAGE->cm->context)) { 5480 $reportlinkparams = [ 5481 'courseid' => $forumobject->course, 5482 'forumid' => $forumobject->id, 5483 ]; 5484 $reportlink = new moodle_url("/mod/forum/report/{$reportname}/index.php", $reportlinkparams); 5485 $forumnode->add(get_string('nodetitle', "forumreport_{$reportname}"), $reportlink, navigation_node::TYPE_CONTAINER); 5486 } 5487 } 5488 } 5489 5490 // For some actions you need to be enrolled, being admin is not enough sometimes here. 5491 $enrolled = is_enrolled($PAGE->cm->context, $USER, '', false); 5492 $activeenrolled = is_enrolled($PAGE->cm->context, $USER, '', true); 5493 5494 $canmanage = has_capability('mod/forum:managesubscriptions', $PAGE->cm->context); 5495 $subscriptionmode = \mod_forum\subscriptions::get_subscription_mode($forumobject); 5496 $cansubscribe = $activeenrolled && !\mod_forum\subscriptions::is_forcesubscribed($forumobject) && 5497 (!\mod_forum\subscriptions::subscription_disabled($forumobject) || $canmanage); 5498 5499 if ($canmanage) { 5500 $mode = $forumnode->add(get_string('subscriptionmode', 'forum'), null, navigation_node::TYPE_CONTAINER); 5501 $mode->add_class('subscriptionmode'); 5502 5503 $allowchoice = $mode->add(get_string('subscriptionoptional', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_CHOOSESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING); 5504 $forceforever = $mode->add(get_string("subscriptionforced", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_FORCESUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING); 5505 $forceinitially = $mode->add(get_string("subscriptionauto", "forum"), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_INITIALSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING); 5506 $disallowchoice = $mode->add(get_string('subscriptiondisabled', 'forum'), new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'mode'=>FORUM_DISALLOWSUBSCRIBE, 'sesskey'=>sesskey())), navigation_node::TYPE_SETTING); 5507 5508 switch ($subscriptionmode) { 5509 case FORUM_CHOOSESUBSCRIBE : // 0 5510 $allowchoice->action = null; 5511 $allowchoice->add_class('activesetting'); 5512 $allowchoice->icon = new pix_icon('t/selected', '', 'mod_forum'); 5513 break; 5514 case FORUM_FORCESUBSCRIBE : // 1 5515 $forceforever->action = null; 5516 $forceforever->add_class('activesetting'); 5517 $forceforever->icon = new pix_icon('t/selected', '', 'mod_forum'); 5518 break; 5519 case FORUM_INITIALSUBSCRIBE : // 2 5520 $forceinitially->action = null; 5521 $forceinitially->add_class('activesetting'); 5522 $forceinitially->icon = new pix_icon('t/selected', '', 'mod_forum'); 5523 break; 5524 case FORUM_DISALLOWSUBSCRIBE : // 3 5525 $disallowchoice->action = null; 5526 $disallowchoice->add_class('activesetting'); 5527 $disallowchoice->icon = new pix_icon('t/selected', '', 'mod_forum'); 5528 break; 5529 } 5530 5531 } else if ($activeenrolled) { 5532 5533 switch ($subscriptionmode) { 5534 case FORUM_CHOOSESUBSCRIBE : // 0 5535 $notenode = $forumnode->add(get_string('subscriptionoptional', 'forum')); 5536 break; 5537 case FORUM_FORCESUBSCRIBE : // 1 5538 $notenode = $forumnode->add(get_string('subscriptionforced', 'forum')); 5539 break; 5540 case FORUM_INITIALSUBSCRIBE : // 2 5541 $notenode = $forumnode->add(get_string('subscriptionauto', 'forum')); 5542 break; 5543 case FORUM_DISALLOWSUBSCRIBE : // 3 5544 $notenode = $forumnode->add(get_string('subscriptiondisabled', 'forum')); 5545 break; 5546 } 5547 } 5548 5549 if ($cansubscribe) { 5550 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, null, $PAGE->cm)) { 5551 $linktext = get_string('unsubscribe', 'forum'); 5552 } else { 5553 $linktext = get_string('subscribe', 'forum'); 5554 } 5555 $url = new moodle_url('/mod/forum/subscribe.php', array('id'=>$forumobject->id, 'sesskey'=>sesskey())); 5556 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING); 5557 5558 if (isset($discussionid)) { 5559 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forumobject, $discussionid, $PAGE->cm)) { 5560 $linktext = get_string('unsubscribediscussion', 'forum'); 5561 } else { 5562 $linktext = get_string('subscribediscussion', 'forum'); 5563 } 5564 $url = new moodle_url('/mod/forum/subscribe.php', array( 5565 'id' => $forumobject->id, 5566 'sesskey' => sesskey(), 5567 'd' => $discussionid, 5568 'returnurl' => $PAGE->url->out(), 5569 )); 5570 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING); 5571 } 5572 } 5573 5574 if (has_capability('mod/forum:viewsubscribers', $PAGE->cm->context)){ 5575 $url = new moodle_url('/mod/forum/subscribers.php', array('id'=>$forumobject->id)); 5576 $forumnode->add(get_string('showsubscribers', 'forum'), $url, navigation_node::TYPE_SETTING); 5577 } 5578 5579 if ($enrolled && forum_tp_can_track_forums($forumobject)) { // keep tracking info for users with suspended enrolments 5580 if ($forumobject->trackingtype == FORUM_TRACKING_OPTIONAL 5581 || ((!$CFG->forum_allowforcedreadtracking) && $forumobject->trackingtype == FORUM_TRACKING_FORCED)) { 5582 if (forum_tp_is_tracked($forumobject)) { 5583 $linktext = get_string('notrackforum', 'forum'); 5584 } else { 5585 $linktext = get_string('trackforum', 'forum'); 5586 } 5587 $url = new moodle_url('/mod/forum/settracking.php', array( 5588 'id' => $forumobject->id, 5589 'sesskey' => sesskey(), 5590 )); 5591 $forumnode->add($linktext, $url, navigation_node::TYPE_SETTING); 5592 } 5593 } 5594 5595 if (!isloggedin() && $PAGE->course->id == SITEID) { 5596 $userid = guest_user()->id; 5597 } else { 5598 $userid = $USER->id; 5599 } 5600 5601 $hascourseaccess = ($PAGE->course->id == SITEID) || can_access_course($PAGE->course, $userid); 5602 $enablerssfeeds = !empty($CFG->enablerssfeeds) && !empty($CFG->forum_enablerssfeeds); 5603 5604 if ($enablerssfeeds && $forumobject->rsstype && $forumobject->rssarticles && $hascourseaccess) { 5605 5606 if (!function_exists('rss_get_url')) { 5607 require_once("$CFG->libdir/rsslib.php"); 5608 } 5609 5610 if ($forumobject->rsstype == 1) { 5611 $string = get_string('rsssubscriberssdiscussions','forum'); 5612 } else { 5613 $string = get_string('rsssubscriberssposts','forum'); 5614 } 5615 5616 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $userid, "mod_forum", $forumobject->id)); 5617 $forumnode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', '')); 5618 } 5619 5620 $capabilitymanager = $managerfactory->get_capability_manager($forumentity); 5621 if ($capabilitymanager->can_export_forum($USER)) { 5622 $url = new moodle_url('/mod/forum/export.php', ['id' => $forumobject->id]); 5623 $forumnode->add(get_string('export', 'mod_forum'), $url, navigation_node::TYPE_SETTING); 5624 } 5625 } 5626 5627 /** 5628 * Adds information about unread messages, that is only required for the course view page (and 5629 * similar), to the course-module object. 5630 * @param cm_info $cm Course-module object 5631 */ 5632 function forum_cm_info_view(cm_info $cm) { 5633 global $CFG; 5634 5635 if (forum_tp_can_track_forums()) { 5636 if ($unread = forum_tp_count_forum_unread_posts($cm, $cm->get_course())) { 5637 $out = '<span class="unread"> <a href="' . $cm->url . '#unread">'; 5638 if ($unread == 1) { 5639 $out .= get_string('unreadpostsone', 'forum'); 5640 } else { 5641 $out .= get_string('unreadpostsnumber', 'forum', $unread); 5642 } 5643 $out .= '</a></span>'; 5644 $cm->set_after_link($out); 5645 } 5646 } 5647 } 5648 5649 /** 5650 * Return a list of page types 5651 * @param string $pagetype current page type 5652 * @param stdClass $parentcontext Block's parent context 5653 * @param stdClass $currentcontext Current context of block 5654 */ 5655 function forum_page_type_list($pagetype, $parentcontext, $currentcontext) { 5656 $forum_pagetype = array( 5657 'mod-forum-*'=>get_string('page-mod-forum-x', 'forum'), 5658 'mod-forum-view'=>get_string('page-mod-forum-view', 'forum'), 5659 'mod-forum-discuss'=>get_string('page-mod-forum-discuss', 'forum') 5660 ); 5661 return $forum_pagetype; 5662 } 5663 5664 /** 5665 * Gets all of the courses where the provided user has posted in a forum. 5666 * 5667 * @global moodle_database $DB The database connection 5668 * @param stdClass $user The user who's posts we are looking for 5669 * @param bool $discussionsonly If true only look for discussions started by the user 5670 * @param bool $includecontexts If set to trye contexts for the courses will be preloaded 5671 * @param int $limitfrom The offset of records to return 5672 * @param int $limitnum The number of records to return 5673 * @return array An array of courses 5674 */ 5675 function forum_get_courses_user_posted_in($user, $discussionsonly = false, $includecontexts = true, $limitfrom = null, $limitnum = null) { 5676 global $DB; 5677 5678 // If we are only after discussions we need only look at the forum_discussions 5679 // table and join to the userid there. If we are looking for posts then we need 5680 // to join to the forum_posts table. 5681 if (!$discussionsonly) { 5682 $subquery = "(SELECT DISTINCT fd.course 5683 FROM {forum_discussions} fd 5684 JOIN {forum_posts} fp ON fp.discussion = fd.id 5685 WHERE fp.userid = :userid )"; 5686 } else { 5687 $subquery= "(SELECT DISTINCT fd.course 5688 FROM {forum_discussions} fd 5689 WHERE fd.userid = :userid )"; 5690 } 5691 5692 $params = array('userid' => $user->id); 5693 5694 // Join to the context table so that we can preload contexts if required. 5695 if ($includecontexts) { 5696 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx'); 5697 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)"; 5698 $params['contextlevel'] = CONTEXT_COURSE; 5699 } else { 5700 $ctxselect = ''; 5701 $ctxjoin = ''; 5702 } 5703 5704 // Now we need to get all of the courses to search. 5705 // All courses where the user has posted within a forum will be returned. 5706 $sql = "SELECT c.* $ctxselect 5707 FROM {course} c 5708 $ctxjoin 5709 WHERE c.id IN ($subquery)"; 5710 $courses = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum); 5711 if ($includecontexts) { 5712 array_map('context_helper::preload_from_record', $courses); 5713 } 5714 return $courses; 5715 } 5716 5717 /** 5718 * Gets all of the forums a user has posted in for one or more courses. 5719 * 5720 * @global moodle_database $DB 5721 * @param stdClass $user 5722 * @param array $courseids An array of courseids to search or if not provided 5723 * all courses the user has posted within 5724 * @param bool $discussionsonly If true then only forums where the user has started 5725 * a discussion will be returned. 5726 * @param int $limitfrom The offset of records to return 5727 * @param int $limitnum The number of records to return 5728 * @return array An array of forums the user has posted within in the provided courses 5729 */ 5730 function forum_get_forums_user_posted_in($user, array $courseids = null, $discussionsonly = false, $limitfrom = null, $limitnum = null) { 5731 global $DB; 5732 5733 if (!is_null($courseids)) { 5734 list($coursewhere, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'courseid'); 5735 $coursewhere = ' AND f.course '.$coursewhere; 5736 } else { 5737 $coursewhere = ''; 5738 $params = array(); 5739 } 5740 $params['userid'] = $user->id; 5741 $params['forum'] = 'forum'; 5742 5743 if ($discussionsonly) { 5744 $join = 'JOIN {forum_discussions} ff ON ff.forum = f.id'; 5745 } else { 5746 $join = 'JOIN {forum_discussions} fd ON fd.forum = f.id 5747 JOIN {forum_posts} ff ON ff.discussion = fd.id'; 5748 } 5749 5750 $sql = "SELECT f.*, cm.id AS cmid 5751 FROM {forum} f 5752 JOIN {course_modules} cm ON cm.instance = f.id 5753 JOIN {modules} m ON m.id = cm.module 5754 JOIN ( 5755 SELECT f.id 5756 FROM {forum} f 5757 {$join} 5758 WHERE ff.userid = :userid 5759 GROUP BY f.id 5760 ) j ON j.id = f.id 5761 WHERE m.name = :forum 5762 {$coursewhere}"; 5763 5764 $courseforums = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum); 5765 return $courseforums; 5766 } 5767 5768 /** 5769 * Returns posts made by the selected user in the requested courses. 5770 * 5771 * This method can be used to return all of the posts made by the requested user 5772 * within the given courses. 5773 * For each course the access of the current user and requested user is checked 5774 * and then for each post access to the post and forum is checked as well. 5775 * 5776 * This function is safe to use with usercapabilities. 5777 * 5778 * @global moodle_database $DB 5779 * @param stdClass $user The user whose posts we want to get 5780 * @param array $courses The courses to search 5781 * @param bool $musthaveaccess If set to true errors will be thrown if the user 5782 * cannot access one or more of the courses to search 5783 * @param bool $discussionsonly If set to true only discussion starting posts 5784 * will be returned. 5785 * @param int $limitfrom The offset of records to return 5786 * @param int $limitnum The number of records to return 5787 * @return stdClass An object the following properties 5788 * ->totalcount: the total number of posts made by the requested user 5789 * that the current user can see. 5790 * ->courses: An array of courses the current user can see that the 5791 * requested user has posted in. 5792 * ->forums: An array of forums relating to the posts returned in the 5793 * property below. 5794 * ->posts: An array containing the posts to show for this request. 5795 */ 5796 function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) { 5797 global $DB, $USER, $CFG; 5798 5799 $return = new stdClass; 5800 $return->totalcount = 0; // The total number of posts that the current user is able to view 5801 $return->courses = array(); // The courses the current user can access 5802 $return->forums = array(); // The forums that the current user can access that contain posts 5803 $return->posts = array(); // The posts to display 5804 5805 // First up a small sanity check. If there are no courses to check we can 5806 // return immediately, there is obviously nothing to search. 5807 if (empty($courses)) { 5808 return $return; 5809 } 5810 5811 // A couple of quick setups 5812 $isloggedin = isloggedin(); 5813 $isguestuser = $isloggedin && isguestuser(); 5814 $iscurrentuser = $isloggedin && $USER->id == $user->id; 5815 5816 // Checkout whether or not the current user has capabilities over the requested 5817 // user and if so they have the capabilities required to view the requested 5818 // users content. 5819 $usercontext = context_user::instance($user->id, MUST_EXIST); 5820 $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id)); 5821 $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext); 5822 5823 // Before we actually search each course we need to check the user's access to the 5824 // course. If the user doesn't have the appropraite access then we either throw an 5825 // error if a particular course was requested or we just skip over the course. 5826 foreach ($courses as $course) { 5827 $coursecontext = context_course::instance($course->id, MUST_EXIST); 5828 if ($iscurrentuser || $hascapsonuser) { 5829 // If it is the current user, or the current user has capabilities to the 5830 // requested user then all we need to do is check the requested users 5831 // current access to the course. 5832 // Note: There is no need to check group access or anything of the like 5833 // as either the current user is the requested user, or has granted 5834 // capabilities on the requested user. Either way they can see what the 5835 // requested user posted, although its VERY unlikely in the `parent` situation 5836 // that the current user will be able to view the posts in context. 5837 if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) { 5838 // Need to have full access to a course to see the rest of own info 5839 if ($musthaveaccess) { 5840 print_error('errorenrolmentrequired', 'forum'); 5841 } 5842 continue; 5843 } 5844 } else { 5845 // Check whether the current user is enrolled or has access to view the course 5846 // if they don't we immediately have a problem. 5847 if (!can_access_course($course)) { 5848 if ($musthaveaccess) { 5849 print_error('errorenrolmentrequired', 'forum'); 5850 } 5851 continue; 5852 } 5853 5854 // If groups are in use and enforced throughout the course then make sure 5855 // we can meet in at least one course level group. 5856 // Note that we check if either the current user or the requested user have 5857 // the capability to access all groups. This is because with that capability 5858 // a user in group A could post in the group B forum. Grrrr. 5859 if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce 5860 && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) { 5861 // If its the guest user to bad... the guest user cannot access groups 5862 if (!$isloggedin or $isguestuser) { 5863 // do not use require_login() here because we might have already used require_login($course) 5864 if ($musthaveaccess) { 5865 redirect(get_login_url()); 5866 } 5867 continue; 5868 } 5869 // Get the groups of the current user 5870 $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name')); 5871 // Get the groups the requested user is a member of 5872 $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name')); 5873 // Check whether they are members of the same group. If they are great. 5874 $intersect = array_intersect($mygroups, $usergroups); 5875 if (empty($intersect)) { 5876 // But they're not... if it was a specific course throw an error otherwise 5877 // just skip this course so that it is not searched. 5878 if ($musthaveaccess) { 5879 print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id"); 5880 } 5881 continue; 5882 } 5883 } 5884 } 5885 // Woo hoo we got this far which means the current user can search this 5886 // this course for the requested user. Although this is only the course accessibility 5887 // handling that is complete, the forum accessibility tests are yet to come. 5888 $return->courses[$course->id] = $course; 5889 } 5890 // No longer beed $courses array - lose it not it may be big 5891 unset($courses); 5892 5893 // Make sure that we have some courses to search 5894 if (empty($return->courses)) { 5895 // If we don't have any courses to search then the reality is that the current 5896 // user doesn't have access to any courses is which the requested user has posted. 5897 // Although we do know at this point that the requested user has posts. 5898 if ($musthaveaccess) { 5899 print_error('permissiondenied'); 5900 } else { 5901 return $return; 5902 } 5903 } 5904 5905 // Next step: Collect all of the forums that we will want to search. 5906 // It is important to note that this step isn't actually about searching, it is 5907 // about determining which forums we can search by testing accessibility. 5908 $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly); 5909 5910 // Will be used to build the where conditions for the search 5911 $forumsearchwhere = array(); 5912 // Will be used to store the where condition params for the search 5913 $forumsearchparams = array(); 5914 // Will record forums where the user can freely access everything 5915 $forumsearchfullaccess = array(); 5916 // DB caching friendly 5917 $now = floor(time() / 60) * 60; 5918 // For each course to search we want to find the forums the user has posted in 5919 // and providing the current user can access the forum create a search condition 5920 // for the forum to get the requested users posts. 5921 foreach ($return->courses as $course) { 5922 // Now we need to get the forums 5923 $modinfo = get_fast_modinfo($course); 5924 if (empty($modinfo->instances['forum'])) { 5925 // hmmm, no forums? well at least its easy... skip! 5926 continue; 5927 } 5928 // Iterate 5929 foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) { 5930 if (!$cm->uservisible or !isset($forums[$forumid])) { 5931 continue; 5932 } 5933 // Get the forum in question 5934 $forum = $forums[$forumid]; 5935 5936 // This is needed for functionality later on in the forum code. It is converted to an object 5937 // because the cm_info is readonly from 2.6. This is a dirty hack because some other parts of the 5938 // code were expecting an writeable object. See {@link forum_print_post()}. 5939 $forum->cm = new stdClass(); 5940 foreach ($cm as $key => $value) { 5941 $forum->cm->$key = $value; 5942 } 5943 5944 // Check that either the current user can view the forum, or that the 5945 // current user has capabilities over the requested user and the requested 5946 // user can view the discussion 5947 if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) { 5948 continue; 5949 } 5950 5951 // This will contain forum specific where clauses 5952 $forumsearchselect = array(); 5953 if (!$iscurrentuser && !$hascapsonuser) { 5954 // Make sure we check group access 5955 if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) { 5956 $groups = $modinfo->get_groups($cm->groupingid); 5957 $groups[] = -1; 5958 list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_'); 5959 $forumsearchparams = array_merge($forumsearchparams, $groupid_params); 5960 $forumsearchselect[] = "d.groupid $groupid_sql"; 5961 } 5962 5963 // hidden timed discussions 5964 if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) { 5965 $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))"; 5966 $forumsearchparams['userid'.$forumid] = $user->id; 5967 $forumsearchparams['timestart'.$forumid] = $now; 5968 $forumsearchparams['timeend'.$forumid] = $now; 5969 } 5970 5971 // qanda access 5972 if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) { 5973 // We need to check whether the user has posted in the qanda forum. 5974 $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id); 5975 if (!empty($discussionspostedin)) { 5976 $forumonlydiscussions = array(); // Holds discussion ids for the discussions the user is allowed to see in this forum. 5977 foreach ($discussionspostedin as $d) { 5978 $forumonlydiscussions[] = $d->id; 5979 } 5980 list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_'); 5981 $forumsearchparams = array_merge($forumsearchparams, $discussionid_params); 5982 $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)"; 5983 } else { 5984 $forumsearchselect[] = "p.parent = 0"; 5985 } 5986 5987 } 5988 5989 if (count($forumsearchselect) > 0) { 5990 $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")"; 5991 $forumsearchparams['forum'.$forumid] = $forumid; 5992 } else { 5993 $forumsearchfullaccess[] = $forumid; 5994 } 5995 } else { 5996 // The current user/parent can see all of their own posts 5997 $forumsearchfullaccess[] = $forumid; 5998 } 5999 } 6000 } 6001 6002 // If we dont have any search conditions, and we don't have any forums where 6003 // the user has full access then we just return the default. 6004 if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) { 6005 return $return; 6006 } 6007 6008 // Prepare a where condition for the full access forums. 6009 if (count($forumsearchfullaccess) > 0) { 6010 list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula'); 6011 $forumsearchparams = array_merge($forumsearchparams, $fullidparams); 6012 $forumsearchwhere[] = "(d.forum $fullidsql)"; 6013 } 6014 6015 // Prepare SQL to both count and search. 6016 // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break 6017 // oracle and mssql. 6018 $userfields = user_picture::fields('u', null, 'useridx'); 6019 $countsql = 'SELECT COUNT(*) '; 6020 $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' '; 6021 $wheresql = implode(" OR ", $forumsearchwhere); 6022 6023 if ($discussionsonly) { 6024 if ($wheresql == '') { 6025 $wheresql = 'p.parent = 0'; 6026 } else { 6027 $wheresql = 'p.parent = 0 AND ('.$wheresql.')'; 6028 } 6029 } 6030 6031 $sql = "FROM {forum_posts} p 6032 JOIN {forum_discussions} d ON d.id = p.discussion 6033 JOIN {user} u ON u.id = p.userid 6034 WHERE ($wheresql) 6035 AND p.userid = :userid "; 6036 $orderby = "ORDER BY p.modified DESC"; 6037 $forumsearchparams['userid'] = $user->id; 6038 6039 // Set the total number posts made by the requested user that the current user can see 6040 $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams); 6041 // Set the collection of posts that has been requested 6042 $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum); 6043 6044 // We need to build an array of forums for which posts will be displayed. 6045 // We do this here to save the caller needing to retrieve them themselves before 6046 // printing these forums posts. Given we have the forums already there is 6047 // practically no overhead here. 6048 foreach ($return->posts as $post) { 6049 if (!array_key_exists($post->forum, $return->forums)) { 6050 $return->forums[$post->forum] = $forums[$post->forum]; 6051 } 6052 } 6053 6054 return $return; 6055 } 6056 6057 /** 6058 * Set the per-forum maildigest option for the specified user. 6059 * 6060 * @param stdClass $forum The forum to set the option for. 6061 * @param int $maildigest The maildigest option. 6062 * @param stdClass $user The user object. This defaults to the global $USER object. 6063 * @throws invalid_digest_setting thrown if an invalid maildigest option is provided. 6064 */ 6065 function forum_set_user_maildigest($forum, $maildigest, $user = null) { 6066 global $DB, $USER; 6067 6068 if (is_number($forum)) { 6069 $forum = $DB->get_record('forum', array('id' => $forum)); 6070 } 6071 6072 if ($user === null) { 6073 $user = $USER; 6074 } 6075 6076 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); 6077 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST); 6078 $context = context_module::instance($cm->id); 6079 6080 // User must be allowed to see this forum. 6081 require_capability('mod/forum:viewdiscussion', $context, $user->id); 6082 6083 // Validate the maildigest setting. 6084 $digestoptions = forum_get_user_digest_options($user); 6085 6086 if (!isset($digestoptions[$maildigest])) { 6087 throw new moodle_exception('invaliddigestsetting', 'mod_forum'); 6088 } 6089 6090 // Attempt to retrieve any existing forum digest record. 6091 $subscription = $DB->get_record('forum_digests', array( 6092 'userid' => $user->id, 6093 'forum' => $forum->id, 6094 )); 6095 6096 // Create or Update the existing maildigest setting. 6097 if ($subscription) { 6098 if ($maildigest == -1) { 6099 $DB->delete_records('forum_digests', array('forum' => $forum->id, 'userid' => $user->id)); 6100 } else if ($maildigest !== $subscription->maildigest) { 6101 // Only update the maildigest setting if it's changed. 6102 6103 $subscription->maildigest = $maildigest; 6104 $DB->update_record('forum_digests', $subscription); 6105 } 6106 } else { 6107 if ($maildigest != -1) { 6108 // Only insert the maildigest setting if it's non-default. 6109 6110 $subscription = new stdClass(); 6111 $subscription->forum = $forum->id; 6112 $subscription->userid = $user->id; 6113 $subscription->maildigest = $maildigest; 6114 $subscription->id = $DB->insert_record('forum_digests', $subscription); 6115 } 6116 } 6117 } 6118 6119 /** 6120 * Determine the maildigest setting for the specified user against the 6121 * specified forum. 6122 * 6123 * @param Array $digests An array of forums and user digest settings. 6124 * @param stdClass $user The user object containing the id and maildigest default. 6125 * @param int $forumid The ID of the forum to check. 6126 * @return int The calculated maildigest setting for this user and forum. 6127 */ 6128 function forum_get_user_maildigest_bulk($digests, $user, $forumid) { 6129 if (isset($digests[$forumid]) && isset($digests[$forumid][$user->id])) { 6130 $maildigest = $digests[$forumid][$user->id]; 6131 if ($maildigest === -1) { 6132 $maildigest = $user->maildigest; 6133 } 6134 } else { 6135 $maildigest = $user->maildigest; 6136 } 6137 return $maildigest; 6138 } 6139 6140 /** 6141 * Retrieve the list of available user digest options. 6142 * 6143 * @param stdClass $user The user object. This defaults to the global $USER object. 6144 * @return array The mapping of values to digest options. 6145 */ 6146 function forum_get_user_digest_options($user = null) { 6147 global $USER; 6148 6149 // Revert to the global user object. 6150 if ($user === null) { 6151 $user = $USER; 6152 } 6153 6154 $digestoptions = array(); 6155 $digestoptions['0'] = get_string('emaildigestoffshort', 'mod_forum'); 6156 $digestoptions['1'] = get_string('emaildigestcompleteshort', 'mod_forum'); 6157 $digestoptions['2'] = get_string('emaildigestsubjectsshort', 'mod_forum'); 6158 6159 // We need to add the default digest option at the end - it relies on 6160 // the contents of the existing values. 6161 $digestoptions['-1'] = get_string('emaildigestdefault', 'mod_forum', 6162 $digestoptions[$user->maildigest]); 6163 6164 // Resort the options to be in a sensible order. 6165 ksort($digestoptions); 6166 6167 return $digestoptions; 6168 } 6169 6170 /** 6171 * Determine the current context if one was not already specified. 6172 * 6173 * If a context of type context_module is specified, it is immediately 6174 * returned and not checked. 6175 * 6176 * @param int $forumid The ID of the forum 6177 * @param context_module $context The current context. 6178 * @return context_module The context determined 6179 */ 6180 function forum_get_context($forumid, $context = null) { 6181 global $PAGE; 6182 6183 if (!$context || !($context instanceof context_module)) { 6184 // Find out forum context. First try to take current page context to save on DB query. 6185 if ($PAGE->cm && $PAGE->cm->modname === 'forum' && $PAGE->cm->instance == $forumid 6186 && $PAGE->context->contextlevel == CONTEXT_MODULE && $PAGE->context->instanceid == $PAGE->cm->id) { 6187 $context = $PAGE->context; 6188 } else { 6189 $cm = get_coursemodule_from_instance('forum', $forumid); 6190 $context = \context_module::instance($cm->id); 6191 } 6192 } 6193 6194 return $context; 6195 } 6196 6197 /** 6198 * Mark the activity completed (if required) and trigger the course_module_viewed event. 6199 * 6200 * @param stdClass $forum forum object 6201 * @param stdClass $course course object 6202 * @param stdClass $cm course module object 6203 * @param stdClass $context context object 6204 * @since Moodle 2.9 6205 */ 6206 function forum_view($forum, $course, $cm, $context) { 6207 6208 // Completion. 6209 $completion = new completion_info($course); 6210 $completion->set_module_viewed($cm); 6211 6212 // Trigger course_module_viewed event. 6213 6214 $params = array( 6215 'context' => $context, 6216 'objectid' => $forum->id 6217 ); 6218 6219 $event = \mod_forum\event\course_module_viewed::create($params); 6220 $event->add_record_snapshot('course_modules', $cm); 6221 $event->add_record_snapshot('course', $course); 6222 $event->add_record_snapshot('forum', $forum); 6223 $event->trigger(); 6224 } 6225 6226 /** 6227 * Trigger the discussion viewed event 6228 * 6229 * @param stdClass $modcontext module context object 6230 * @param stdClass $forum forum object 6231 * @param stdClass $discussion discussion object 6232 * @since Moodle 2.9 6233 */ 6234 function forum_discussion_view($modcontext, $forum, $discussion) { 6235 $params = array( 6236 'context' => $modcontext, 6237 'objectid' => $discussion->id, 6238 ); 6239 6240 $event = \mod_forum\event\discussion_viewed::create($params); 6241 $event->add_record_snapshot('forum_discussions', $discussion); 6242 $event->add_record_snapshot('forum', $forum); 6243 $event->trigger(); 6244 } 6245 6246 /** 6247 * Set the discussion to pinned and trigger the discussion pinned event 6248 * 6249 * @param stdClass $modcontext module context object 6250 * @param stdClass $forum forum object 6251 * @param stdClass $discussion discussion object 6252 * @since Moodle 3.1 6253 */ 6254 function forum_discussion_pin($modcontext, $forum, $discussion) { 6255 global $DB; 6256 6257 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_PINNED, array('id' => $discussion->id)); 6258 6259 $params = array( 6260 'context' => $modcontext, 6261 'objectid' => $discussion->id, 6262 'other' => array('forumid' => $forum->id) 6263 ); 6264 6265 $event = \mod_forum\event\discussion_pinned::create($params); 6266 $event->add_record_snapshot('forum_discussions', $discussion); 6267 $event->trigger(); 6268 } 6269 6270 /** 6271 * Set discussion to unpinned and trigger the discussion unpin event 6272 * 6273 * @param stdClass $modcontext module context object 6274 * @param stdClass $forum forum object 6275 * @param stdClass $discussion discussion object 6276 * @since Moodle 3.1 6277 */ 6278 function forum_discussion_unpin($modcontext, $forum, $discussion) { 6279 global $DB; 6280 6281 $DB->set_field('forum_discussions', 'pinned', FORUM_DISCUSSION_UNPINNED, array('id' => $discussion->id)); 6282 6283 $params = array( 6284 'context' => $modcontext, 6285 'objectid' => $discussion->id, 6286 'other' => array('forumid' => $forum->id) 6287 ); 6288 6289 $event = \mod_forum\event\discussion_unpinned::create($params); 6290 $event->add_record_snapshot('forum_discussions', $discussion); 6291 $event->trigger(); 6292 } 6293 6294 /** 6295 * Add nodes to myprofile page. 6296 * 6297 * @param \core_user\output\myprofile\tree $tree Tree object 6298 * @param stdClass $user user object 6299 * @param bool $iscurrentuser 6300 * @param stdClass $course Course object 6301 * 6302 * @return bool 6303 */ 6304 function mod_forum_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) { 6305 if (isguestuser($user)) { 6306 // The guest user cannot post, so it is not possible to view any posts. 6307 // May as well just bail aggressively here. 6308 return false; 6309 } 6310 $postsurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id)); 6311 if (!empty($course)) { 6312 $postsurl->param('course', $course->id); 6313 } 6314 $string = get_string('forumposts', 'mod_forum'); 6315 $node = new core_user\output\myprofile\node('miscellaneous', 'forumposts', $string, null, $postsurl); 6316 $tree->add_node($node); 6317 6318 $discussionssurl = new moodle_url('/mod/forum/user.php', array('id' => $user->id, 'mode' => 'discussions')); 6319 if (!empty($course)) { 6320 $discussionssurl->param('course', $course->id); 6321 } 6322 $string = get_string('myprofileotherdis', 'mod_forum'); 6323 $node = new core_user\output\myprofile\node('miscellaneous', 'forumdiscussions', $string, null, 6324 $discussionssurl); 6325 $tree->add_node($node); 6326 6327 return true; 6328 } 6329 6330 /** 6331 * Checks whether the author's name and picture for a given post should be hidden or not. 6332 * 6333 * @param object $post The forum post. 6334 * @param object $forum The forum object. 6335 * @return bool 6336 * @throws coding_exception 6337 */ 6338 function forum_is_author_hidden($post, $forum) { 6339 if (!isset($post->parent)) { 6340 throw new coding_exception('$post->parent must be set.'); 6341 } 6342 if (!isset($forum->type)) { 6343 throw new coding_exception('$forum->type must be set.'); 6344 } 6345 if ($forum->type === 'single' && empty($post->parent)) { 6346 return true; 6347 } 6348 return false; 6349 } 6350 6351 /** 6352 * Manage inplace editable saves. 6353 * 6354 * @param string $itemtype The type of item. 6355 * @param int $itemid The ID of the item. 6356 * @param mixed $newvalue The new value 6357 * @return string 6358 */ 6359 function mod_forum_inplace_editable($itemtype, $itemid, $newvalue) { 6360 global $DB, $PAGE; 6361 6362 if ($itemtype === 'digestoptions') { 6363 // The itemid is the forumid. 6364 $forum = $DB->get_record('forum', array('id' => $itemid), '*', MUST_EXIST); 6365 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST); 6366 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST); 6367 $context = context_module::instance($cm->id); 6368 6369 $PAGE->set_context($context); 6370 require_login($course, false, $cm); 6371 forum_set_user_maildigest($forum, $newvalue); 6372 6373 $renderer = $PAGE->get_renderer('mod_forum'); 6374 return $renderer->render_digest_options($forum, $newvalue); 6375 } 6376 } 6377 6378 /** 6379 * Determine whether the specified forum's cutoff date is reached. 6380 * 6381 * @param stdClass $forum The forum 6382 * @return bool 6383 */ 6384 function forum_is_cutoff_date_reached($forum) { 6385 $entityfactory = \mod_forum\local\container::get_entity_factory(); 6386 $coursemoduleinfo = get_fast_modinfo($forum->course); 6387 $cminfo = $coursemoduleinfo->instances['forum'][$forum->id]; 6388 $forumentity = $entityfactory->get_forum_from_stdclass( 6389 $forum, 6390 context_module::instance($cminfo->id), 6391 $cminfo->get_course_module_record(), 6392 $cminfo->get_course() 6393 ); 6394 6395 return $forumentity->is_cutoff_date_reached(); 6396 } 6397 6398 /** 6399 * Determine whether the specified forum's due date is reached. 6400 * 6401 * @param stdClass $forum The forum 6402 * @return bool 6403 */ 6404 function forum_is_due_date_reached($forum) { 6405 $entityfactory = \mod_forum\local\container::get_entity_factory(); 6406 $coursemoduleinfo = get_fast_modinfo($forum->course); 6407 $cminfo = $coursemoduleinfo->instances['forum'][$forum->id]; 6408 $forumentity = $entityfactory->get_forum_from_stdclass( 6409 $forum, 6410 context_module::instance($cminfo->id), 6411 $cminfo->get_course_module_record(), 6412 $cminfo->get_course() 6413 ); 6414 6415 return $forumentity->is_due_date_reached(); 6416 } 6417 6418 /** 6419 * Determine whether the specified discussion is time-locked. 6420 * 6421 * @param stdClass $forum The forum that the discussion belongs to 6422 * @param stdClass $discussion The discussion to test 6423 * @return bool 6424 */ 6425 function forum_discussion_is_locked($forum, $discussion) { 6426 $entityfactory = \mod_forum\local\container::get_entity_factory(); 6427 $coursemoduleinfo = get_fast_modinfo($forum->course); 6428 $cminfo = $coursemoduleinfo->instances['forum'][$forum->id]; 6429 $forumentity = $entityfactory->get_forum_from_stdclass( 6430 $forum, 6431 context_module::instance($cminfo->id), 6432 $cminfo->get_course_module_record(), 6433 $cminfo->get_course() 6434 ); 6435 $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion); 6436 6437 return $forumentity->is_discussion_locked($discussionentity); 6438 } 6439 6440 /** 6441 * Check if the module has any update that affects the current user since a given time. 6442 * 6443 * @param cm_info $cm course module data 6444 * @param int $from the time to check updates from 6445 * @param array $filter if we need to check only specific updates 6446 * @return stdClass an object with the different type of areas indicating if they were updated or not 6447 * @since Moodle 3.2 6448 */ 6449 function forum_check_updates_since(cm_info $cm, $from, $filter = array()) { 6450 6451 $context = $cm->context; 6452 $updates = new stdClass(); 6453 if (!has_capability('mod/forum:viewdiscussion', $context)) { 6454 return $updates; 6455 } 6456 6457 $updates = course_check_module_updates_since($cm, $from, array(), $filter); 6458 6459 // Check if there are new discussions in the forum. 6460 $updates->discussions = (object) array('updated' => false); 6461 $discussions = forum_get_discussions($cm, '', false, -1, -1, true, -1, 0, FORUM_POSTS_ALL_USER_GROUPS, $from); 6462 if (!empty($discussions)) { 6463 $updates->discussions->updated = true; 6464 $updates->discussions->itemids = array_keys($discussions); 6465 } 6466 6467 return $updates; 6468 } 6469 6470 /** 6471 * Check if the user can create attachments in a forum. 6472 * @param stdClass $forum forum object 6473 * @param stdClass $context context object 6474 * @return bool true if the user can create attachments, false otherwise 6475 * @since Moodle 3.3 6476 */ 6477 function forum_can_create_attachment($forum, $context) { 6478 // If maxbytes == 1 it means no attachments at all. 6479 if (empty($forum->maxattachments) || $forum->maxbytes == 1 || 6480 !has_capability('mod/forum:createattachment', $context)) { 6481 return false; 6482 } 6483 return true; 6484 } 6485 6486 /** 6487 * Get icon mapping for font-awesome. 6488 * 6489 * @return array 6490 */ 6491 function mod_forum_get_fontawesome_icon_map() { 6492 return [ 6493 'mod_forum:i/pinned' => 'fa-map-pin', 6494 'mod_forum:t/selected' => 'fa-check', 6495 'mod_forum:t/subscribed' => 'fa-envelope-o', 6496 'mod_forum:t/unsubscribed' => 'fa-envelope-open-o', 6497 'mod_forum:t/star' => 'fa-star', 6498 ]; 6499 } 6500 6501 /** 6502 * Callback function that determines whether an action event should be showing its item count 6503 * based on the event type and the item count. 6504 * 6505 * @param calendar_event $event The calendar event. 6506 * @param int $itemcount The item count associated with the action event. 6507 * @return bool 6508 */ 6509 function mod_forum_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) { 6510 // Always show item count for forums if item count is greater than 1. 6511 // If only one action is required than it is obvious and we don't show it for other modules. 6512 return $itemcount > 1; 6513 } 6514 6515 /** 6516 * This function receives a calendar event and returns the action associated with it, or null if there is none. 6517 * 6518 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event 6519 * is not displayed on the block. 6520 * 6521 * @param calendar_event $event 6522 * @param \core_calendar\action_factory $factory 6523 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default). 6524 * @return \core_calendar\local\event\entities\action_interface|null 6525 */ 6526 function mod_forum_core_calendar_provide_event_action(calendar_event $event, 6527 \core_calendar\action_factory $factory, 6528 int $userid = 0) { 6529 global $DB, $USER; 6530 6531 if (!$userid) { 6532 $userid = $USER->id; 6533 } 6534 6535 $cm = get_fast_modinfo($event->courseid, $userid)->instances['forum'][$event->instance]; 6536 6537 if (!$cm->uservisible) { 6538 // The module is not visible to the user for any reason. 6539 return null; 6540 } 6541 6542 $context = context_module::instance($cm->id); 6543 6544 if (!has_capability('mod/forum:viewdiscussion', $context, $userid)) { 6545 return null; 6546 } 6547 6548 $completion = new \completion_info($cm->get_course()); 6549 6550 $completiondata = $completion->get_data($cm, false, $userid); 6551 6552 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) { 6553 return null; 6554 } 6555 6556 // Get action itemcount. 6557 $itemcount = 0; 6558 $forum = $DB->get_record('forum', array('id' => $cm->instance)); 6559 $postcountsql = " 6560 SELECT 6561 COUNT(1) 6562 FROM 6563 {forum_posts} fp 6564 INNER JOIN {forum_discussions} fd ON fp.discussion=fd.id 6565 WHERE 6566 fp.userid=:userid AND fd.forum=:forumid"; 6567 $postcountparams = array('userid' => $userid, 'forumid' => $forum->id); 6568 6569 if ($forum->completiondiscussions) { 6570 $count = $DB->count_records('forum_discussions', array('forum' => $forum->id, 'userid' => $userid)); 6571 $itemcount += ($forum->completiondiscussions >= $count) ? ($forum->completiondiscussions - $count) : 0; 6572 } 6573 6574 if ($forum->completionreplies) { 6575 $count = $DB->get_field_sql( $postcountsql.' AND fp.parent<>0', $postcountparams); 6576 $itemcount += ($forum->completionreplies >= $count) ? ($forum->completionreplies - $count) : 0; 6577 } 6578 6579 if ($forum->completionposts) { 6580 $count = $DB->get_field_sql($postcountsql, $postcountparams); 6581 $itemcount += ($forum->completionposts >= $count) ? ($forum->completionposts - $count) : 0; 6582 } 6583 6584 // Well there is always atleast one actionable item (view forum, etc). 6585 $itemcount = $itemcount > 0 ? $itemcount : 1; 6586 6587 return $factory->create_instance( 6588 get_string('view'), 6589 new \moodle_url('/mod/forum/view.php', ['id' => $cm->id]), 6590 $itemcount, 6591 true 6592 ); 6593 } 6594 6595 /** 6596 * Add a get_coursemodule_info function in case any forum type wants to add 'extra' information 6597 * for the course (see resource). 6598 * 6599 * Given a course_module object, this function returns any "extra" information that may be needed 6600 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php. 6601 * 6602 * @param stdClass $coursemodule The coursemodule object (record). 6603 * @return cached_cm_info An object on information that the courses 6604 * will know about (most noticeably, an icon). 6605 */ 6606 function forum_get_coursemodule_info($coursemodule) { 6607 global $DB; 6608 6609 $dbparams = ['id' => $coursemodule->instance]; 6610 $fields = 'id, name, intro, introformat, completionposts, completiondiscussions, completionreplies'; 6611 if (!$forum = $DB->get_record('forum', $dbparams, $fields)) { 6612 return false; 6613 } 6614 6615 $result = new cached_cm_info(); 6616 $result->name = $forum->name; 6617 6618 if ($coursemodule->showdescription) { 6619 // Convert intro to html. Do not filter cached version, filters run at display time. 6620 $result->content = format_module_intro('forum', $forum, $coursemodule->id, false); 6621 } 6622 6623 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'. 6624 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) { 6625 $result->customdata['customcompletionrules']['completiondiscussions'] = $forum->completiondiscussions; 6626 $result->customdata['customcompletionrules']['completionreplies'] = $forum->completionreplies; 6627 $result->customdata['customcompletionrules']['completionposts'] = $forum->completionposts; 6628 } 6629 6630 return $result; 6631 } 6632 6633 /** 6634 * Callback which returns human-readable strings describing the active completion custom rules for the module instance. 6635 * 6636 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules'] 6637 * @return array $descriptions the array of descriptions for the custom rules. 6638 */ 6639 function mod_forum_get_completion_active_rule_descriptions($cm) { 6640 // Values will be present in cm_info, and we assume these are up to date. 6641 if (empty($cm->customdata['customcompletionrules']) 6642 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) { 6643 return []; 6644 } 6645 6646 $descriptions = []; 6647 foreach ($cm->customdata['customcompletionrules'] as $key => $val) { 6648 switch ($key) { 6649 case 'completiondiscussions': 6650 if (!empty($val)) { 6651 $descriptions[] = get_string('completiondiscussionsdesc', 'forum', $val); 6652 } 6653 break; 6654 case 'completionreplies': 6655 if (!empty($val)) { 6656 $descriptions[] = get_string('completionrepliesdesc', 'forum', $val); 6657 } 6658 break; 6659 case 'completionposts': 6660 if (!empty($val)) { 6661 $descriptions[] = get_string('completionpostsdesc', 'forum', $val); 6662 } 6663 break; 6664 default: 6665 break; 6666 } 6667 } 6668 return $descriptions; 6669 } 6670 6671 /** 6672 * Check whether the forum post is a private reply visible to this user. 6673 * 6674 * @param stdClass $post The post to check. 6675 * @param cm_info $cm The context module instance. 6676 * @return bool Whether the post is visible in terms of private reply configuration. 6677 */ 6678 function forum_post_is_visible_privately($post, $cm) { 6679 global $USER; 6680 6681 if (!empty($post->privatereplyto)) { 6682 // Allow the user to see the private reply if: 6683 // * they hold the permission; 6684 // * they are the author; or 6685 // * they are the intended recipient. 6686 $cansee = false; 6687 $cansee = $cansee || ($post->userid == $USER->id); 6688 $cansee = $cansee || ($post->privatereplyto == $USER->id); 6689 $cansee = $cansee || has_capability('mod/forum:readprivatereplies', context_module::instance($cm->id)); 6690 return $cansee; 6691 } 6692 6693 return true; 6694 } 6695 6696 /** 6697 * Check whether the user can reply privately to the parent post. 6698 * 6699 * @param \context_module $context 6700 * @param \stdClass $parent 6701 * @return bool 6702 */ 6703 function forum_user_can_reply_privately(\context_module $context, \stdClass $parent) : bool { 6704 if ($parent->privatereplyto) { 6705 // You cannot reply privately to a post which is, itself, a private reply. 6706 return false; 6707 } 6708 6709 return has_capability('mod/forum:postprivatereply', $context); 6710 } 6711 6712 /** 6713 * This function calculates the minimum and maximum cutoff values for the timestart of 6714 * the given event. 6715 * 6716 * It will return an array with two values, the first being the minimum cutoff value and 6717 * the second being the maximum cutoff value. Either or both values can be null, which 6718 * indicates there is no minimum or maximum, respectively. 6719 * 6720 * If a cutoff is required then the function must return an array containing the cutoff 6721 * timestamp and error string to display to the user if the cutoff value is violated. 6722 * 6723 * A minimum and maximum cutoff return value will look like: 6724 * [ 6725 * [1505704373, 'The date must be after this date'], 6726 * [1506741172, 'The date must be before this date'] 6727 * ] 6728 * 6729 * @param calendar_event $event The calendar event to get the time range for 6730 * @param stdClass $forum The module instance to get the range from 6731 * @return array Returns an array with min and max date. 6732 */ 6733 function mod_forum_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $forum) { 6734 global $CFG; 6735 6736 require_once($CFG->dirroot . '/mod/forum/locallib.php'); 6737 6738 $mindate = null; 6739 $maxdate = null; 6740 6741 if ($event->eventtype == FORUM_EVENT_TYPE_DUE) { 6742 if (!empty($forum->cutoffdate)) { 6743 $maxdate = [ 6744 $forum->cutoffdate, 6745 get_string('cutoffdatevalidation', 'forum'), 6746 ]; 6747 } 6748 } 6749 6750 return [$mindate, $maxdate]; 6751 } 6752 6753 /** 6754 * This function will update the forum module according to the 6755 * event that has been modified. 6756 * 6757 * It will set the timeclose value of the forum instance 6758 * according to the type of event provided. 6759 * 6760 * @throws \moodle_exception 6761 * @param \calendar_event $event 6762 * @param stdClass $forum The module instance to get the range from 6763 */ 6764 function mod_forum_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $forum) { 6765 global $CFG, $DB; 6766 6767 require_once($CFG->dirroot . '/mod/forum/locallib.php'); 6768 6769 if ($event->eventtype != FORUM_EVENT_TYPE_DUE) { 6770 return; 6771 } 6772 6773 $courseid = $event->courseid; 6774 $modulename = $event->modulename; 6775 $instanceid = $event->instance; 6776 6777 // Something weird going on. The event is for a different module so 6778 // we should ignore it. 6779 if ($modulename != 'forum') { 6780 return; 6781 } 6782 6783 if ($forum->id != $instanceid) { 6784 return; 6785 } 6786 6787 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid]; 6788 $context = context_module::instance($coursemodule->id); 6789 6790 // The user does not have the capability to modify this activity. 6791 if (!has_capability('moodle/course:manageactivities', $context)) { 6792 return; 6793 } 6794 6795 if ($event->eventtype == FORUM_EVENT_TYPE_DUE) { 6796 if ($forum->duedate != $event->timestart) { 6797 $forum->duedate = $event->timestart; 6798 $forum->timemodified = time(); 6799 // Persist the instance changes. 6800 $DB->update_record('forum', $forum); 6801 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context); 6802 $event->trigger(); 6803 } 6804 } 6805 } 6806 6807 /** 6808 * Fetch the data used to display the discussions on the current page. 6809 * 6810 * @param \mod_forum\local\entities\forum $forum The forum entity 6811 * @param stdClass $user The user to render for 6812 * @param int[]|null $groupid The group to render 6813 * @param int|null $sortorder The sort order to use when selecting the discussions in the list 6814 * @param int|null $pageno The zero-indexed page number to use 6815 * @param int|null $pagesize The number of discussions to show on the page 6816 * @return array The data to use for display 6817 */ 6818 function mod_forum_get_discussion_summaries(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid, ?int $sortorder, 6819 ?int $pageno = 0, ?int $pagesize = 0) { 6820 6821 $vaultfactory = mod_forum\local\container::get_vault_factory(); 6822 $discussionvault = $vaultfactory->get_discussions_in_forum_vault(); 6823 $managerfactory = mod_forum\local\container::get_manager_factory(); 6824 $capabilitymanager = $managerfactory->get_capability_manager($forum); 6825 6826 $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid); 6827 6828 if (null === $groupids) { 6829 return $discussions = $discussionvault->get_from_forum_id( 6830 $forum->get_id(), 6831 $capabilitymanager->can_view_hidden_posts($user), 6832 $user->id, 6833 $sortorder, 6834 $pagesize, 6835 $pageno * $pagesize); 6836 } else { 6837 return $discussions = $discussionvault->get_from_forum_id_and_group_id( 6838 $forum->get_id(), 6839 $groupids, 6840 $capabilitymanager->can_view_hidden_posts($user), 6841 $user->id, 6842 $sortorder, 6843 $pagesize, 6844 $pageno * $pagesize); 6845 } 6846 } 6847 6848 /** 6849 * Get a count of all discussions in a forum. 6850 * 6851 * @param \mod_forum\local\entities\forum $forum The forum entity 6852 * @param stdClass $user The user to render for 6853 * @param int $groupid The group to render 6854 * @return int The number of discussions in a forum 6855 */ 6856 function mod_forum_count_all_discussions(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) { 6857 6858 $managerfactory = mod_forum\local\container::get_manager_factory(); 6859 $capabilitymanager = $managerfactory->get_capability_manager($forum); 6860 $vaultfactory = mod_forum\local\container::get_vault_factory(); 6861 $discussionvault = $vaultfactory->get_discussions_in_forum_vault(); 6862 6863 $groupids = mod_forum_get_groups_from_groupid($forum, $user, $groupid); 6864 6865 if (null === $groupids) { 6866 return $discussionvault->get_total_discussion_count_from_forum_id( 6867 $forum->get_id(), 6868 $capabilitymanager->can_view_hidden_posts($user), 6869 $user->id); 6870 } else { 6871 return $discussionvault->get_total_discussion_count_from_forum_id_and_group_id( 6872 $forum->get_id(), 6873 $groupids, 6874 $capabilitymanager->can_view_hidden_posts($user), 6875 $user->id); 6876 } 6877 } 6878 6879 /** 6880 * Get the list of groups to show based on the current user and requested groupid. 6881 * 6882 * @param \mod_forum\local\entities\forum $forum The forum entity 6883 * @param stdClass $user The user viewing 6884 * @param int $groupid The groupid requested 6885 * @return array The list of groups to show 6886 */ 6887 function mod_forum_get_groups_from_groupid(\mod_forum\local\entities\forum $forum, stdClass $user, ?int $groupid) : ?array { 6888 6889 $effectivegroupmode = $forum->get_effective_group_mode(); 6890 if (empty($effectivegroupmode)) { 6891 // This forum is not in a group mode. Show all posts always. 6892 return null; 6893 } 6894 6895 if (null == $groupid) { 6896 $managerfactory = mod_forum\local\container::get_manager_factory(); 6897 $capabilitymanager = $managerfactory->get_capability_manager($forum); 6898 // No group was specified. 6899 $showallgroups = (VISIBLEGROUPS == $effectivegroupmode); 6900 $showallgroups = $showallgroups || $capabilitymanager->can_access_all_groups($user); 6901 if ($showallgroups) { 6902 // Return null to show all groups. 6903 return null; 6904 } else { 6905 // No group was specified. Only show the users current groups. 6906 return array_keys( 6907 groups_get_all_groups( 6908 $forum->get_course_id(), 6909 $user->id, 6910 $forum->get_course_module_record()->groupingid 6911 ) 6912 ); 6913 } 6914 } else { 6915 // A group was specified. Just show that group. 6916 return [$groupid]; 6917 } 6918 } 6919 6920 /** 6921 * Return a list of all the user preferences used by mod_forum. 6922 * 6923 * @return array 6924 */ 6925 function mod_forum_user_preferences() { 6926 $vaultfactory = \mod_forum\local\container::get_vault_factory(); 6927 $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault(); 6928 6929 $preferences = array(); 6930 $preferences['forum_discussionlistsortorder'] = array( 6931 'null' => NULL_NOT_ALLOWED, 6932 'default' => $discussionlistvault::SORTORDER_LASTPOST_DESC, 6933 'type' => PARAM_INT, 6934 'choices' => array( 6935 $discussionlistvault::SORTORDER_LASTPOST_DESC, 6936 $discussionlistvault::SORTORDER_LASTPOST_ASC, 6937 $discussionlistvault::SORTORDER_CREATED_DESC, 6938 $discussionlistvault::SORTORDER_CREATED_ASC, 6939 $discussionlistvault::SORTORDER_REPLIES_DESC, 6940 $discussionlistvault::SORTORDER_REPLIES_ASC 6941 ) 6942 ); 6943 $preferences['forum_useexperimentalui'] = [ 6944 'null' => NULL_NOT_ALLOWED, 6945 'default' => false, 6946 'type' => PARAM_BOOL 6947 ]; 6948 6949 return $preferences; 6950 } 6951 6952 /** 6953 * Lists all gradable areas for the advanced grading methods gramework. 6954 * 6955 * @return array('string'=>'string') An array with area names as keys and descriptions as values 6956 */ 6957 function forum_grading_areas_list() { 6958 return [ 6959 'forum' => get_string('grade_forum_header', 'forum'), 6960 ]; 6961 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body