MDL-65025 forum: Fix text formatting (check messagetrust) in WS
[moodle.git] / mod / forum / externallib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * External forum API
20  *
21  * @package    mod_forum
22  * @copyright  2012 Mark Nelson <markn@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die;
28 require_once("$CFG->libdir/externallib.php");
30 use mod_forum\local\exporters\post as post_exporter;
31 use mod_forum\local\exporters\discussion as discussion_exporter;
33 class mod_forum_external extends external_api {
35     /**
36      * Describes the parameters for get_forum.
37      *
38      * @return external_function_parameters
39      * @since Moodle 2.5
40      */
41     public static function get_forums_by_courses_parameters() {
42         return new external_function_parameters (
43             array(
44                 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID',
45                         VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of Course IDs', VALUE_DEFAULT, array()),
46             )
47         );
48     }
50     /**
51      * Returns a list of forums in a provided list of courses,
52      * if no list is provided all forums that the user can view
53      * will be returned.
54      *
55      * @param array $courseids the course ids
56      * @return array the forum details
57      * @since Moodle 2.5
58      */
59     public static function get_forums_by_courses($courseids = array()) {
60         global $CFG;
62         require_once($CFG->dirroot . "/mod/forum/lib.php");
64         $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids));
66         $courses = array();
67         if (empty($params['courseids'])) {
68             $courses = enrol_get_my_courses();
69             $params['courseids'] = array_keys($courses);
70         }
72         // Array to store the forums to return.
73         $arrforums = array();
74         $warnings = array();
76         // Ensure there are courseids to loop through.
77         if (!empty($params['courseids'])) {
79             list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses);
81             // Get the forums in this course. This function checks users visibility permissions.
82             $forums = get_all_instances_in_courses("forum", $courses);
83             foreach ($forums as $forum) {
85                 $course = $courses[$forum->course];
86                 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
87                 $context = context_module::instance($cm->id);
89                 // Skip forums we are not allowed to see discussions.
90                 if (!has_capability('mod/forum:viewdiscussion', $context)) {
91                     continue;
92                 }
94                 $forum->name = external_format_string($forum->name, $context->id);
95                 // Format the intro before being returning using the format setting.
96                 list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat,
97                                                                                 $context->id, 'mod_forum', 'intro', null);
98                 $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false);
99                 // Discussions count. This function does static request cache.
100                 $forum->numdiscussions = forum_count_discussions($forum, $cm, $course);
101                 $forum->cmid = $forum->coursemodule;
102                 $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context);
103                 $forum->istracked = forum_tp_is_tracked($forum);
104                 if ($forum->istracked) {
105                     $forum->unreadpostscount = forum_tp_count_forum_unread_posts($cm, $course);
106                 }
108                 // Add the forum to the array to return.
109                 $arrforums[$forum->id] = $forum;
110             }
111         }
113         return $arrforums;
114     }
116     /**
117      * Describes the get_forum return value.
118      *
119      * @return external_single_structure
120      * @since Moodle 2.5
121      */
122     public static function get_forums_by_courses_returns() {
123         return new external_multiple_structure(
124             new external_single_structure(
125                 array(
126                     'id' => new external_value(PARAM_INT, 'Forum id'),
127                     'course' => new external_value(PARAM_INT, 'Course id'),
128                     'type' => new external_value(PARAM_TEXT, 'The forum type'),
129                     'name' => new external_value(PARAM_RAW, 'Forum name'),
130                     'intro' => new external_value(PARAM_RAW, 'The forum intro'),
131                     'introformat' => new external_format_value('intro'),
132                     'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
133                     'duedate' => new external_value(PARAM_INT, 'duedate for the user', VALUE_OPTIONAL),
134                     'cutoffdate' => new external_value(PARAM_INT, 'cutoffdate for the user', VALUE_OPTIONAL),
135                     'assessed' => new external_value(PARAM_INT, 'Aggregate type'),
136                     'assesstimestart' => new external_value(PARAM_INT, 'Assess start time'),
137                     'assesstimefinish' => new external_value(PARAM_INT, 'Assess finish time'),
138                     'scale' => new external_value(PARAM_INT, 'Scale'),
139                     'maxbytes' => new external_value(PARAM_INT, 'Maximum attachment size'),
140                     'maxattachments' => new external_value(PARAM_INT, 'Maximum number of attachments'),
141                     'forcesubscribe' => new external_value(PARAM_INT, 'Force users to subscribe'),
142                     'trackingtype' => new external_value(PARAM_INT, 'Subscription mode'),
143                     'rsstype' => new external_value(PARAM_INT, 'RSS feed for this activity'),
144                     'rssarticles' => new external_value(PARAM_INT, 'Number of RSS recent articles'),
145                     'timemodified' => new external_value(PARAM_INT, 'Time modified'),
146                     'warnafter' => new external_value(PARAM_INT, 'Post threshold for warning'),
147                     'blockafter' => new external_value(PARAM_INT, 'Post threshold for blocking'),
148                     'blockperiod' => new external_value(PARAM_INT, 'Time period for blocking'),
149                     'completiondiscussions' => new external_value(PARAM_INT, 'Student must create discussions'),
150                     'completionreplies' => new external_value(PARAM_INT, 'Student must post replies'),
151                     'completionposts' => new external_value(PARAM_INT, 'Student must post discussions or replies'),
152                     'cmid' => new external_value(PARAM_INT, 'Course module id'),
153                     'numdiscussions' => new external_value(PARAM_INT, 'Number of discussions in the forum', VALUE_OPTIONAL),
154                     'cancreatediscussions' => new external_value(PARAM_BOOL, 'If the user can create discussions', VALUE_OPTIONAL),
155                     'lockdiscussionafter' => new external_value(PARAM_INT, 'After what period a discussion is locked', VALUE_OPTIONAL),
156                     'istracked' => new external_value(PARAM_BOOL, 'If the user is tracking the forum', VALUE_OPTIONAL),
157                     'unreadpostscount' => new external_value(PARAM_INT, 'The number of unread posts for tracked forums',
158                         VALUE_OPTIONAL),
159                 ), 'forum'
160             )
161         );
162     }
164     /**
165      * Get the forum posts in the specified discussion.
166      *
167      * @param   int $discussionid
168      * @param   string $sortby
169      * @param   string $sortdirection
170      * @return  array
171      */
172     public static function get_discussion_posts(int $discussionid, ?string $sortby, ?string $sortdirection) {
173         global $USER;
174         // Validate the parameter.
175         $params = self::validate_parameters(self::get_discussion_posts_parameters(), [
176                 'discussionid' => $discussionid,
177                 'sortby' => $sortby,
178                 'sortdirection' => $sortdirection,
179             ]);
180         $warnings = [];
182         $vaultfactory = mod_forum\local\container::get_vault_factory();
184         $discussionvault = $vaultfactory->get_discussion_vault();
185         $discussion = $discussionvault->get_from_id($params['discussionid']);
187         $forumvault = $vaultfactory->get_forum_vault();
188         $forum = $forumvault->get_from_id($discussion->get_forum_id());
190         $sortby = $params['sortby'];
191         $sortdirection = $params['sortdirection'];
192         $sortallowedvalues = ['id', 'created', 'modified'];
193         $directionallowedvalues = ['ASC', 'DESC'];
195         if (!in_array(strtolower($sortby), $sortallowedvalues)) {
196             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
197                 'allowed values are: ' . implode(', ', $sortallowedvalues));
198         }
200         $sortdirection = strtoupper($sortdirection);
201         if (!in_array($sortdirection, $directionallowedvalues)) {
202             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
203                 'allowed values are: ' . implode(',', $directionallowedvalues));
204         }
206         $managerfactory = mod_forum\local\container::get_manager_factory();
207         $capabilitymanager = $managerfactory->get_capability_manager($forum);
209         $postvault = $vaultfactory->get_post_vault();
210         $posts = $postvault->get_from_discussion_id(
211                 $USER,
212                 $discussion->get_id(),
213                 $capabilitymanager->can_view_any_private_reply($USER),
214                 "{$sortby} {$sortdirection}"
215             );
217         $builderfactory = mod_forum\local\container::get_builder_factory();
218         $postbuilder = $builderfactory->get_exported_posts_builder();
220         $legacydatamapper = mod_forum\local\container::get_legacy_data_mapper_factory();
222         return [
223             'posts' => $postbuilder->build($USER, [$forum], [$discussion], $posts),
224             'ratinginfo' => \core_rating\external\util::get_rating_info(
225                 $legacydatamapper->get_forum_data_mapper()->to_legacy_object($forum),
226                 $forum->get_context(),
227                 'mod_forum',
228                 'post',
229                 $legacydatamapper->get_post_data_mapper()->to_legacy_objects($posts)
230             ),
231             'warnings' => $warnings,
232         ];
233     }
235     /**
236      * Describe the post parameters.
237      *
238      * @return external_function_parameters
239      */
240     public static function get_discussion_posts_parameters() {
241         return new external_function_parameters ([
242             'discussionid' => new external_value(PARAM_INT, 'The ID of the discussion from which to fetch posts.', VALUE_REQUIRED),
243             'sortby' => new external_value(PARAM_ALPHA, 'Sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
244             'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
245         ]);
246     }
248     /**
249      * Describe the post return format.
250      *
251      * @return external_single_structure
252      */
253     public static function get_discussion_posts_returns() {
254         return new external_single_structure([
255             'posts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
256             'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
257             'warnings' => new external_warnings()
258         ]);
259     }
261     /**
262      * Describes the parameters for get_forum_discussion_posts.
263      *
264      * @return external_function_parameters
265      * @since Moodle 2.7
266      */
267     public static function get_forum_discussion_posts_parameters() {
268         return new external_function_parameters (
269             array(
270                 'discussionid' => new external_value(PARAM_INT, 'discussion ID', VALUE_REQUIRED),
271                 'sortby' => new external_value(PARAM_ALPHA,
272                     'sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
273                 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
274             )
275         );
276     }
278     /**
279      * Returns a list of forum posts for a discussion
280      *
281      * @param int $discussionid the post ids
282      * @param string $sortby sort by this element (id, created or modified)
283      * @param string $sortdirection sort direction: ASC or DESC
284      *
285      * @return array the forum post details
286      * @since Moodle 2.7
287      * @todo MDL-65252 This will be removed in Moodle 4.1
288      */
289     public static function get_forum_discussion_posts($discussionid, $sortby = "created", $sortdirection = "DESC") {
290         global $CFG, $DB, $USER, $PAGE;
292         $posts = array();
293         $warnings = array();
295         // Validate the parameter.
296         $params = self::validate_parameters(self::get_forum_discussion_posts_parameters(),
297             array(
298                 'discussionid' => $discussionid,
299                 'sortby' => $sortby,
300                 'sortdirection' => $sortdirection));
302         // Compact/extract functions are not recommended.
303         $discussionid   = $params['discussionid'];
304         $sortby         = $params['sortby'];
305         $sortdirection  = $params['sortdirection'];
307         $sortallowedvalues = array('id', 'created', 'modified');
308         if (!in_array($sortby, $sortallowedvalues)) {
309             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
310                 'allowed values are: ' . implode(',', $sortallowedvalues));
311         }
313         $sortdirection = strtoupper($sortdirection);
314         $directionallowedvalues = array('ASC', 'DESC');
315         if (!in_array($sortdirection, $directionallowedvalues)) {
316             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
317                 'allowed values are: ' . implode(',', $directionallowedvalues));
318         }
320         $discussion = $DB->get_record('forum_discussions', array('id' => $discussionid), '*', MUST_EXIST);
321         $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
322         $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
323         $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
325         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
326         $modcontext = context_module::instance($cm->id);
327         self::validate_context($modcontext);
329         // This require must be here, see mod/forum/discuss.php.
330         require_once($CFG->dirroot . "/mod/forum/lib.php");
332         // Check they have the view forum capability.
333         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
335         if (! $post = forum_get_post_full($discussion->firstpost)) {
336             throw new moodle_exception('notexists', 'forum');
337         }
339         // This function check groups, qanda, timed discussions, etc.
340         if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
341             throw new moodle_exception('noviewdiscussionspermission', 'forum');
342         }
344         $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
346         // We will add this field in the response.
347         $canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
349         $forumtracked = forum_tp_is_tracked($forum);
351         $sort = 'p.' . $sortby . ' ' . $sortdirection;
352         $allposts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
354         foreach ($allposts as $post) {
355             if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm, false)) {
356                 $warning = array();
357                 $warning['item'] = 'post';
358                 $warning['itemid'] = $post->id;
359                 $warning['warningcode'] = '1';
360                 $warning['message'] = 'You can\'t see this post';
361                 $warnings[] = $warning;
362                 continue;
363             }
365             // Function forum_get_all_discussion_posts adds postread field.
366             // Note that the value returned can be a boolean or an integer. The WS expects a boolean.
367             if (empty($post->postread)) {
368                 $post->postread = false;
369             } else {
370                 $post->postread = true;
371             }
373             $post->isprivatereply = !empty($post->privatereplyto);
375             $post->canreply = $canreply;
376             if (!empty($post->children)) {
377                 $post->children = array_keys($post->children);
378             } else {
379                 $post->children = array();
380             }
382             if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
383                 // The post is available, but has been marked as deleted.
384                 // It will still be available but filled with a placeholder.
385                 $post->userid = null;
386                 $post->userfullname = null;
387                 $post->userpictureurl = null;
389                 $post->subject = get_string('privacy:request:delete:post:subject', 'mod_forum');
390                 $post->message = get_string('privacy:request:delete:post:message', 'mod_forum');
392                 $post->deleted = true;
393                 $posts[] = $post;
395                 continue;
396             }
397             $post->deleted = false;
399             if (forum_is_author_hidden($post, $forum)) {
400                 $post->userid = null;
401                 $post->userfullname = null;
402                 $post->userpictureurl = null;
403             } else {
404                 $user = new stdclass();
405                 $user->id = $post->userid;
406                 $user = username_load_fields_from_object($user, $post, null, array('picture', 'imagealt', 'email'));
407                 $post->userfullname = fullname($user, $canviewfullname);
409                 $userpicture = new user_picture($user);
410                 $userpicture->size = 1; // Size f1.
411                 $post->userpictureurl = $userpicture->get_url($PAGE)->out(false);
412             }
414             $post->subject = external_format_string($post->subject, $modcontext->id);
415             // Rewrite embedded images URLs.
416             $options = array('trusted' => $post->messagetrust);
417             list($post->message, $post->messageformat) =
418                 external_format_text($post->message, $post->messageformat, $modcontext->id, 'mod_forum', 'post', $post->id,
419                     $options);
421             // List attachments.
422             if (!empty($post->attachment)) {
423                 $post->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $post->id);
424             }
425             $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $post->id);
426             if (!empty($messageinlinefiles)) {
427                 $post->messageinlinefiles = $messageinlinefiles;
428             }
429             // Post tags.
430             $post->tags = \core_tag\external\util::get_item_tags('mod_forum', 'forum_posts', $post->id);
432             $posts[] = $post;
433         }
435         $result = array();
436         $result['posts'] = $posts;
437         $result['ratinginfo'] = \core_rating\external\util::get_rating_info($forum, $modcontext, 'mod_forum', 'post', $posts);
438         $result['warnings'] = $warnings;
439         return $result;
440     }
442     /**
443      * Describes the get_forum_discussion_posts return value.
444      *
445      * @return external_single_structure
446      * @since Moodle 2.7
447      */
448     public static function get_forum_discussion_posts_returns() {
449         return new external_single_structure(
450             array(
451                 'posts' => new external_multiple_structure(
452                         new external_single_structure(
453                             array(
454                                 'id' => new external_value(PARAM_INT, 'Post id'),
455                                 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
456                                 'parent' => new external_value(PARAM_INT, 'Parent id'),
457                                 'userid' => new external_value(PARAM_INT, 'User id'),
458                                 'created' => new external_value(PARAM_INT, 'Creation time'),
459                                 'modified' => new external_value(PARAM_INT, 'Time modified'),
460                                 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
461                                 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
462                                 'message' => new external_value(PARAM_RAW, 'The post message'),
463                                 'messageformat' => new external_format_value('message'),
464                                 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
465                                 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
466                                 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
467                                 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
468                                 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
469                                 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
470                                 'children' => new external_multiple_structure(new external_value(PARAM_INT, 'children post id')),
471                                 'canreply' => new external_value(PARAM_BOOL, 'The user can reply to posts?'),
472                                 'postread' => new external_value(PARAM_BOOL, 'The post was read'),
473                                 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
474                                 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.', VALUE_OPTIONAL),
475                                 'deleted' => new external_value(PARAM_BOOL, 'This post has been removed.'),
476                                 'isprivatereply' => new external_value(PARAM_BOOL, 'The post is a private reply'),
477                                 'tags' => new external_multiple_structure(
478                                     \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags', VALUE_OPTIONAL
479                                 ),
480                             ), 'post'
481                         )
482                     ),
483                 'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
484                 'warnings' => new external_warnings()
485             )
486         );
487     }
489     /**
490      * Mark the get_forum_discussion_posts web service as deprecated.
491      *
492      * @return  bool
493      */
494     public static function get_forum_discussion_posts_is_deprecated() {
495         return true;
496     }
498     /**
499      * Describes the parameters for get_forum_discussions_paginated.
500      *
501      * @deprecated since 3.7
502      * @return external_function_parameters
503      * @since Moodle 2.8
504      */
505     public static function get_forum_discussions_paginated_parameters() {
506         return new external_function_parameters (
507             array(
508                 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
509                 'sortby' => new external_value(PARAM_ALPHA,
510                     'sort by this element: id, timemodified, timestart or timeend', VALUE_DEFAULT, 'timemodified'),
511                 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
512                 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
513                 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
514             )
515         );
516     }
518     /**
519      * Returns a list of forum discussions optionally sorted and paginated.
520      *
521      * @deprecated since 3.7
522      * @param int $forumid the forum instance id
523      * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
524      * @param string $sortdirection sort direction: ASC or DESC
525      * @param int $page page number
526      * @param int $perpage items per page
527      *
528      * @return array the forum discussion details including warnings
529      * @since Moodle 2.8
530      */
531     public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC',
532             $page = -1, $perpage = 0) {
533         global $CFG, $DB, $USER, $PAGE;
535         require_once($CFG->dirroot . "/mod/forum/lib.php");
537         $warnings = array();
538         $discussions = array();
540         $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(),
541             array(
542                 'forumid' => $forumid,
543                 'sortby' => $sortby,
544                 'sortdirection' => $sortdirection,
545                 'page' => $page,
546                 'perpage' => $perpage
547             )
548         );
550         // Compact/extract functions are not recommended.
551         $forumid        = $params['forumid'];
552         $sortby         = $params['sortby'];
553         $sortdirection  = $params['sortdirection'];
554         $page           = $params['page'];
555         $perpage        = $params['perpage'];
557         $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
558         if (!in_array($sortby, $sortallowedvalues)) {
559             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
560                 'allowed values are: ' . implode(',', $sortallowedvalues));
561         }
563         $sortdirection = strtoupper($sortdirection);
564         $directionallowedvalues = array('ASC', 'DESC');
565         if (!in_array($sortdirection, $directionallowedvalues)) {
566             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
567                 'allowed values are: ' . implode(',', $directionallowedvalues));
568         }
570         $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
571         $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
572         $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
574         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
575         $modcontext = context_module::instance($cm->id);
576         self::validate_context($modcontext);
578         // Check they have the view forum capability.
579         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
581         $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
582         $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
584         if ($alldiscussions) {
585             $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
587             // Get the unreads array, this takes a forum id and returns data for all discussions.
588             $unreads = array();
589             if ($cantrack = forum_tp_can_track_forums($forum)) {
590                 if ($forumtracked = forum_tp_is_tracked($forum)) {
591                     $unreads = forum_get_discussions_unread($cm);
592                 }
593             }
594             // The forum function returns the replies for all the discussions in a given forum.
595             $canseeprivatereplies = has_capability('mod/forum:readprivatereplies', $modcontext);
596             $canlock = has_capability('moodle/course:manageactivities', $modcontext, $USER);
597             $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage, $canseeprivatereplies);
599             foreach ($alldiscussions as $discussion) {
601                 // This function checks for qanda forums.
602                 // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
603                 $discussionrec = clone $discussion;
604                 $discussionrec->id = $discussion->discussion;
605                 if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
606                     $warning = array();
607                     // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
608                     $warning['item'] = 'post';
609                     $warning['itemid'] = $discussion->id;
610                     $warning['warningcode'] = '1';
611                     $warning['message'] = 'You can\'t see this discussion';
612                     $warnings[] = $warning;
613                     continue;
614                 }
616                 $discussion->numunread = 0;
617                 if ($cantrack && $forumtracked) {
618                     if (isset($unreads[$discussion->discussion])) {
619                         $discussion->numunread = (int) $unreads[$discussion->discussion];
620                     }
621                 }
623                 $discussion->numreplies = 0;
624                 if (!empty($replies[$discussion->discussion])) {
625                     $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
626                 }
628                 $discussion->name = external_format_string($discussion->name, $modcontext->id);
629                 $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
630                 // Rewrite embedded images URLs.
631                 $options = array('trusted' => $discussion->messagetrust);
632                 list($discussion->message, $discussion->messageformat) =
633                     external_format_text($discussion->message, $discussion->messageformat,
634                                             $modcontext->id, 'mod_forum', 'post', $discussion->id, $options);
636                 // List attachments.
637                 if (!empty($discussion->attachment)) {
638                     $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
639                                                                                 $discussion->id);
640                 }
641                 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
642                 if (!empty($messageinlinefiles)) {
643                     $discussion->messageinlinefiles = $messageinlinefiles;
644                 }
646                 $discussion->locked = forum_discussion_is_locked($forum, $discussion);
647                 $discussion->canlock = $canlock;
648                 $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
650                 if (forum_is_author_hidden($discussion, $forum)) {
651                     $discussion->userid = null;
652                     $discussion->userfullname = null;
653                     $discussion->userpictureurl = null;
655                     $discussion->usermodified = null;
656                     $discussion->usermodifiedfullname = null;
657                     $discussion->usermodifiedpictureurl = null;
658                 } else {
659                     $picturefields = explode(',', user_picture::fields());
661                     // Load user objects from the results of the query.
662                     $user = new stdclass();
663                     $user->id = $discussion->userid;
664                     $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
665                     // Preserve the id, it can be modified by username_load_fields_from_object.
666                     $user->id = $discussion->userid;
667                     $discussion->userfullname = fullname($user, $canviewfullname);
669                     $userpicture = new user_picture($user);
670                     $userpicture->size = 1; // Size f1.
671                     $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
673                     $usermodified = new stdclass();
674                     $usermodified->id = $discussion->usermodified;
675                     $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
676                     // Preserve the id (it can be overwritten due to the prefixed $picturefields).
677                     $usermodified->id = $discussion->usermodified;
678                     $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
680                     $userpicture = new user_picture($usermodified);
681                     $userpicture->size = 1; // Size f1.
682                     $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
683                 }
685                 $discussions[] = $discussion;
686             }
687         }
689         $result = array();
690         $result['discussions'] = $discussions;
691         $result['warnings'] = $warnings;
692         return $result;
694     }
696     /**
697      * Describes the get_forum_discussions_paginated return value.
698      *
699      * @deprecated since 3.7
700      * @return external_single_structure
701      * @since Moodle 2.8
702      */
703     public static function get_forum_discussions_paginated_returns() {
704         return new external_single_structure(
705             array(
706                 'discussions' => new external_multiple_structure(
707                         new external_single_structure(
708                             array(
709                                 'id' => new external_value(PARAM_INT, 'Post id'),
710                                 'name' => new external_value(PARAM_TEXT, 'Discussion name'),
711                                 'groupid' => new external_value(PARAM_INT, 'Group id'),
712                                 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
713                                 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
714                                 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
715                                 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
716                                 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
717                                 'parent' => new external_value(PARAM_INT, 'Parent id'),
718                                 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
719                                 'created' => new external_value(PARAM_INT, 'Creation time'),
720                                 'modified' => new external_value(PARAM_INT, 'Time modified'),
721                                 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
722                                 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
723                                 'message' => new external_value(PARAM_RAW, 'The post message'),
724                                 'messageformat' => new external_format_value('message'),
725                                 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
726                                 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
727                                 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
728                                 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
729                                 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
730                                 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
731                                 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
732                                 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
733                                 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
734                                 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
735                                 'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
736                                 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
737                                 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
738                                 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
739                                 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
740                                 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
741                             ), 'post'
742                         )
743                     ),
744                 'warnings' => new external_warnings()
745             )
746         );
747     }
749     /**
750      * Describes the parameters for get_forum_discussions.
751      *
752      * @return external_function_parameters
753      * @since Moodle 3.7
754      */
755     public static function get_forum_discussions_parameters() {
756         return new external_function_parameters (
757             array(
758                 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
759                 'sortorder' => new external_value(PARAM_INT,
760                     'sort by this element: numreplies, , created or timemodified', VALUE_DEFAULT, -1),
761                 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
762                 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
763                 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0),
764             )
765         );
766     }
768     /**
769      * Returns a list of forum discussions optionally sorted and paginated.
770      *
771      * @param int $forumid the forum instance id
772      * @param int $sortorder The sort order
773      * @param int $page page number
774      * @param int $perpage items per page
775      * @param int $groupid the user course group
776      *
777      *
778      * @return array the forum discussion details including warnings
779      * @since Moodle 3.7
780      */
781     public static function get_forum_discussions(int $forumid, ?int $sortorder = -1, ?int $page = -1,
782             ?int $perpage = 0, ?int $groupid = 0) {
784         global $CFG, $DB, $USER;
786         require_once($CFG->dirroot . "/mod/forum/lib.php");
788         $warnings = array();
789         $discussions = array();
791         $params = self::validate_parameters(self::get_forum_discussions_parameters(),
792             array(
793                 'forumid' => $forumid,
794                 'sortorder' => $sortorder,
795                 'page' => $page,
796                 'perpage' => $perpage,
797                 'groupid' => $groupid
798             )
799         );
801         // Compact/extract functions are not recommended.
802         $forumid        = $params['forumid'];
803         $sortorder      = $params['sortorder'];
804         $page           = $params['page'];
805         $perpage        = $params['perpage'];
806         $groupid        = $params['groupid'];
808         $vaultfactory = \mod_forum\local\container::get_vault_factory();
809         $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
811         $sortallowedvalues = array(
812             $discussionlistvault::SORTORDER_LASTPOST_DESC,
813             $discussionlistvault::SORTORDER_LASTPOST_ASC,
814             $discussionlistvault::SORTORDER_CREATED_DESC,
815             $discussionlistvault::SORTORDER_CREATED_ASC,
816             $discussionlistvault::SORTORDER_REPLIES_DESC,
817             $discussionlistvault::SORTORDER_REPLIES_ASC
818         );
820         // If sortorder not defined set a default one.
821         if ($sortorder == -1) {
822             $sortorder = $discussionlistvault::SORTORDER_LASTPOST_DESC;
823         }
825         if (!in_array($sortorder, $sortallowedvalues)) {
826             throw new invalid_parameter_exception('Invalid value for sortorder parameter (value: ' . $sortorder . '),' .
827                 ' allowed values are: ' . implode(',', $sortallowedvalues));
828         }
830         $managerfactory = \mod_forum\local\container::get_manager_factory();
831         $urlfactory = \mod_forum\local\container::get_url_factory();
832         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
834         $forumvault = $vaultfactory->get_forum_vault();
835         $forum = $forumvault->get_from_id($forumid);
836         if (!$forum) {
837             throw new \moodle_exception("Unable to find forum with id {$forumid}");
838         }
839         $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
840         $forumrecord = $forumdatamapper->to_legacy_object($forum);
842         $capabilitymanager = $managerfactory->get_capability_manager($forum);
844         $course = $DB->get_record('course', array('id' => $forum->get_course_id()), '*', MUST_EXIST);
845         $cm = get_coursemodule_from_instance('forum', $forum->get_id(), $course->id, false, MUST_EXIST);
847         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
848         $modcontext = context_module::instance($cm->id);
849         self::validate_context($modcontext);
851         $canseeanyprivatereply = $capabilitymanager->can_view_any_private_reply($USER);
853         // Check they have the view forum capability.
854         if (!$capabilitymanager->can_view_discussions($USER)) {
855             throw new moodle_exception('noviewdiscussionspermission', 'forum');
856         }
858         $alldiscussions = mod_forum_get_discussion_summaries($forum, $USER, $groupid, $sortorder, $page, $perpage);
860         if ($alldiscussions) {
861             $discussionids = array_keys($alldiscussions);
863             $postvault = $vaultfactory->get_post_vault();
864             $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
865             // Return the reply count for each discussion in a given forum.
866             $replies = $postvault->get_reply_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
867             // Return the first post for each discussion in a given forum.
868             $firstposts = $postvault->get_first_post_for_discussion_ids($discussionids);
870             // Get the unreads array, this takes a forum id and returns data for all discussions.
871             $unreads = array();
872             if ($cantrack = forum_tp_can_track_forums($forumrecord)) {
873                 if ($forumtracked = forum_tp_is_tracked($forumrecord)) {
874                     $unreads = $postvault->get_unread_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
875                 }
876             }
878             $canlock = $capabilitymanager->can_manage_forum($USER);
880             $usercontext = context_user::instance($USER->id);
881             $ufservice = core_favourites\service_factory::get_service_for_user_context($usercontext);
883             $canfavourite = has_capability('mod/forum:cantogglefavourite', $modcontext, $USER);
885             foreach ($alldiscussions as $discussionsummary) {
886                 $discussion = $discussionsummary->get_discussion();
887                 $firstpostauthor = $discussionsummary->get_first_post_author();
888                 $latestpostauthor = $discussionsummary->get_latest_post_author();
890                 // This function checks for qanda forums.
891                 $canviewdiscussion = $capabilitymanager->can_view_discussion($USER, $discussion);
892                 if (!$canviewdiscussion) {
893                     $warning = array();
894                     // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
895                     $warning['item'] = 'post';
896                     $warning['itemid'] = $discussion->get_id();
897                     $warning['warningcode'] = '1';
898                     $warning['message'] = 'You can\'t see this discussion';
899                     $warnings[] = $warning;
900                     continue;
901                 }
903                 $firstpost = $firstposts[$discussion->get_first_post_id()];
904                 $discussionobject = $postdatamapper->to_legacy_object($firstpost);
905                 // Fix up the types for these properties.
906                 $discussionobject->mailed = $discussionobject->mailed ? 1 : 0;
907                 $discussionobject->messagetrust = $discussionobject->messagetrust ? 1 : 0;
908                 $discussionobject->mailnow = $discussionobject->mailnow ? 1 : 0;
909                 $discussionobject->groupid = $discussion->get_group_id();
910                 $discussionobject->timemodified = $discussion->get_time_modified();
911                 $discussionobject->usermodified = $discussion->get_user_modified();
912                 $discussionobject->timestart = $discussion->get_time_start();
913                 $discussionobject->timeend = $discussion->get_time_end();
914                 $discussionobject->pinned = $discussion->is_pinned();
916                 $discussionobject->numunread = 0;
917                 if ($cantrack && $forumtracked) {
918                     if (isset($unreads[$discussion->get_id()])) {
919                         $discussionobject->numunread = (int) $unreads[$discussion->get_id()];
920                     }
921                 }
923                 $discussionobject->numreplies = 0;
924                 if (!empty($replies[$discussion->get_id()])) {
925                     $discussionobject->numreplies = (int) $replies[$discussion->get_id()];
926                 }
928                 $discussionobject->name = external_format_string($discussion->get_name(), $modcontext->id);
929                 $discussionobject->subject = external_format_string($discussionobject->subject, $modcontext->id);
930                 // Rewrite embedded images URLs.
931                 $options = array('trusted' => $discussionobject->messagetrust);
932                 list($discussionobject->message, $discussionobject->messageformat) =
933                     external_format_text($discussionobject->message, $discussionobject->messageformat,
934                         $modcontext->id, 'mod_forum', 'post', $discussionobject->id, $options);
936                 // List attachments.
937                 if (!empty($discussionobject->attachment)) {
938                     $discussionobject->attachments = external_util::get_area_files($modcontext->id, 'mod_forum',
939                         'attachment', $discussionobject->id);
940                 }
941                 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post',
942                     $discussionobject->id);
943                 if (!empty($messageinlinefiles)) {
944                     $discussionobject->messageinlinefiles = $messageinlinefiles;
945                 }
947                 $discussionobject->locked = $forum->is_discussion_locked($discussion);
948                 $discussionobject->canlock = $canlock;
949                 $discussionobject->starred = !empty($ufservice) ? $ufservice->favourite_exists('mod_forum', 'discussions',
950                     $discussion->get_id(), $modcontext) : false;
951                 $discussionobject->canreply = $capabilitymanager->can_post_in_discussion($USER, $discussion);
952                 $discussionobject->canfavourite = $canfavourite;
954                 if (forum_is_author_hidden($discussionobject, $forumrecord)) {
955                     $discussionobject->userid = null;
956                     $discussionobject->userfullname = null;
957                     $discussionobject->userpictureurl = null;
959                     $discussionobject->usermodified = null;
960                     $discussionobject->usermodifiedfullname = null;
961                     $discussionobject->usermodifiedpictureurl = null;
963                 } else {
964                     $discussionobject->userfullname = $firstpostauthor->get_full_name();
965                     $discussionobject->userpictureurl = $urlfactory->get_author_profile_image_url($firstpostauthor, null, 2)
966                         ->out(false);
968                     $discussionobject->usermodifiedfullname = $latestpostauthor->get_full_name();
969                     $discussionobject->usermodifiedpictureurl = $urlfactory->get_author_profile_image_url(
970                         $latestpostauthor, null, 2)->out(false);
971                 }
973                 $discussions[] = (array) $discussionobject;
974             }
975         }
976         $result = array();
977         $result['discussions'] = $discussions;
978         $result['warnings'] = $warnings;
980         return $result;
981     }
983     /**
984      * Describes the get_forum_discussions return value.
985      *
986      * @return external_single_structure
987      * @since Moodle 3.7
988      */
989     public static function get_forum_discussions_returns() {
990         return new external_single_structure(
991             array(
992                 'discussions' => new external_multiple_structure(
993                     new external_single_structure(
994                         array(
995                             'id' => new external_value(PARAM_INT, 'Post id'),
996                             'name' => new external_value(PARAM_TEXT, 'Discussion name'),
997                             'groupid' => new external_value(PARAM_INT, 'Group id'),
998                             'timemodified' => new external_value(PARAM_INT, 'Time modified'),
999                             'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
1000                             'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
1001                             'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
1002                             'discussion' => new external_value(PARAM_INT, 'Discussion id'),
1003                             'parent' => new external_value(PARAM_INT, 'Parent id'),
1004                             'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
1005                             'created' => new external_value(PARAM_INT, 'Creation time'),
1006                             'modified' => new external_value(PARAM_INT, 'Time modified'),
1007                             'mailed' => new external_value(PARAM_INT, 'Mailed?'),
1008                             'subject' => new external_value(PARAM_TEXT, 'The post subject'),
1009                             'message' => new external_value(PARAM_RAW, 'The post message'),
1010                             'messageformat' => new external_format_value('message'),
1011                             'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
1012                             'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
1013                             'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
1014                             'attachments' => new external_files('attachments', VALUE_OPTIONAL),
1015                             'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
1016                             'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
1017                             'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
1018                             'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
1019                             'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
1020                             'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
1021                             'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
1022                             'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
1023                             'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
1024                             'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
1025                             'starred' => new external_value(PARAM_BOOL, 'Is the discussion starred'),
1026                             'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
1027                             'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
1028                             'canfavourite' => new external_value(PARAM_BOOL, 'Can the user star the discussion'),
1029                         ), 'post'
1030                     )
1031                 ),
1032                 'warnings' => new external_warnings()
1033             )
1034         );
1035     }
1037     /**
1038      * Returns description of method parameters
1039      *
1040      * @return external_function_parameters
1041      * @since Moodle 2.9
1042      */
1043     public static function view_forum_parameters() {
1044         return new external_function_parameters(
1045             array(
1046                 'forumid' => new external_value(PARAM_INT, 'forum instance id')
1047             )
1048         );
1049     }
1051     /**
1052      * Trigger the course module viewed event and update the module completion status.
1053      *
1054      * @param int $forumid the forum instance id
1055      * @return array of warnings and status result
1056      * @since Moodle 2.9
1057      * @throws moodle_exception
1058      */
1059     public static function view_forum($forumid) {
1060         global $DB, $CFG;
1061         require_once($CFG->dirroot . "/mod/forum/lib.php");
1063         $params = self::validate_parameters(self::view_forum_parameters(),
1064                                             array(
1065                                                 'forumid' => $forumid
1066                                             ));
1067         $warnings = array();
1069         // Request and permission validation.
1070         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1071         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1073         $context = context_module::instance($cm->id);
1074         self::validate_context($context);
1076         require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
1078         // Call the forum/lib API.
1079         forum_view($forum, $course, $cm, $context);
1081         $result = array();
1082         $result['status'] = true;
1083         $result['warnings'] = $warnings;
1084         return $result;
1085     }
1087     /**
1088      * Returns description of method result value
1089      *
1090      * @return external_description
1091      * @since Moodle 2.9
1092      */
1093     public static function view_forum_returns() {
1094         return new external_single_structure(
1095             array(
1096                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1097                 'warnings' => new external_warnings()
1098             )
1099         );
1100     }
1102     /**
1103      * Returns description of method parameters
1104      *
1105      * @return external_function_parameters
1106      * @since Moodle 2.9
1107      */
1108     public static function view_forum_discussion_parameters() {
1109         return new external_function_parameters(
1110             array(
1111                 'discussionid' => new external_value(PARAM_INT, 'discussion id')
1112             )
1113         );
1114     }
1116     /**
1117      * Trigger the discussion viewed event.
1118      *
1119      * @param int $discussionid the discussion id
1120      * @return array of warnings and status result
1121      * @since Moodle 2.9
1122      * @throws moodle_exception
1123      */
1124     public static function view_forum_discussion($discussionid) {
1125         global $DB, $CFG, $USER;
1126         require_once($CFG->dirroot . "/mod/forum/lib.php");
1128         $params = self::validate_parameters(self::view_forum_discussion_parameters(),
1129                                             array(
1130                                                 'discussionid' => $discussionid
1131                                             ));
1132         $warnings = array();
1134         $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
1135         $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
1136         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1138         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
1139         $modcontext = context_module::instance($cm->id);
1140         self::validate_context($modcontext);
1142         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
1144         // Call the forum/lib API.
1145         forum_discussion_view($modcontext, $forum, $discussion);
1147         // Mark as read if required.
1148         if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
1149             forum_tp_mark_discussion_read($USER, $discussion->id);
1150         }
1152         $result = array();
1153         $result['status'] = true;
1154         $result['warnings'] = $warnings;
1155         return $result;
1156     }
1158     /**
1159      * Returns description of method result value
1160      *
1161      * @return external_description
1162      * @since Moodle 2.9
1163      */
1164     public static function view_forum_discussion_returns() {
1165         return new external_single_structure(
1166             array(
1167                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1168                 'warnings' => new external_warnings()
1169             )
1170         );
1171     }
1173     /**
1174      * Returns description of method parameters
1175      *
1176      * @return external_function_parameters
1177      * @since Moodle 3.0
1178      */
1179     public static function add_discussion_post_parameters() {
1180         return new external_function_parameters(
1181             array(
1182                 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
1183                                                 (can be the initial discussion post'),
1184                 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
1185                 'message' => new external_value(PARAM_RAW, 'new post message (html assumed if messageformat is not provided)'),
1186                 'options' => new external_multiple_structure (
1187                     new external_single_structure(
1188                         array(
1189                             'name' => new external_value(PARAM_ALPHANUM,
1190                                         'The allowed keys (value format) are:
1191                                         discussionsubscribe (bool); subscribe to the discussion?, default to true
1192                                         private (bool); make this reply private to the author of the parent post, default to false.
1193                                         inlineattachmentsid              (int); the draft file area id for inline attachments
1194                                         attachmentsid       (int); the draft file area id for attachments
1195                                         topreferredformat (bool); convert the message & messageformat to FORMAT_HTML, defaults to false
1196                             '),
1197                             'value' => new external_value(PARAM_RAW, 'the value of the option,
1198                                                             this param is validated in the external function.'
1199                         )
1200                     )
1201                 ), 'Options', VALUE_DEFAULT, array()),
1202                 'messageformat' => new external_format_value('message', VALUE_DEFAULT)
1203             )
1204         );
1205     }
1207     /**
1208      * Create new posts into an existing discussion.
1209      *
1210      * @param int $postid the post id we are going to reply to
1211      * @param string $subject new post subject
1212      * @param string $message new post message (html assumed if messageformat is not provided)
1213      * @param array $options optional settings
1214      * @param string $messageformat The format of the message, defaults to FORMAT_HTML for BC
1215      * @return array of warnings and the new post id
1216      * @since Moodle 3.0
1217      * @throws moodle_exception
1218      */
1219     public static function add_discussion_post($postid, $subject, $message, $options = array(), $messageformat = FORMAT_HTML) {
1220         global $CFG, $USER;
1221         require_once($CFG->dirroot . "/mod/forum/lib.php");
1223         // Get all the factories that are required.
1224         $vaultfactory = mod_forum\local\container::get_vault_factory();
1225         $entityfactory = mod_forum\local\container::get_entity_factory();
1226         $datamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1227         $managerfactory = mod_forum\local\container::get_manager_factory();
1228         $discussionvault = $vaultfactory->get_discussion_vault();
1229         $forumvault = $vaultfactory->get_forum_vault();
1230         $discussiondatamapper = $datamapperfactory->get_discussion_data_mapper();
1231         $forumdatamapper = $datamapperfactory->get_forum_data_mapper();
1233         $params = self::validate_parameters(self::add_discussion_post_parameters(),
1234             array(
1235                 'postid' => $postid,
1236                 'subject' => $subject,
1237                 'message' => $message,
1238                 'options' => $options,
1239                 'messageformat' => $messageformat,
1240             )
1241         );
1243         $warnings = array();
1245         if (!$parent = forum_get_post_full($params['postid'])) {
1246             throw new moodle_exception('invalidparentpostid', 'forum');
1247         }
1249         if (!$discussion = $discussionvault->get_from_id($parent->discussion)) {
1250             throw new moodle_exception('notpartofdiscussion', 'forum');
1251         }
1253         // Request and permission validation.
1254         $forum = $forumvault->get_from_id($discussion->get_forum_id());
1255         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1256         $course = $forum->get_course_record();
1257         $cm = $forum->get_course_module_record();
1259         $discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
1260         $forumrecord = $forumdatamapper->to_legacy_object($forum);
1261         $context = context_module::instance($cm->id);
1262         self::validate_context($context);
1264         $coursecontext = \context_course::instance($forum->get_course_id());
1265         $discussionsubscribe = \mod_forum\subscriptions::get_user_default_subscription($forumrecord, $coursecontext,
1266             $cm, null);
1268         // Validate options.
1269         $options = array(
1270             'discussionsubscribe' => $discussionsubscribe,
1271             'private'             => false,
1272             'inlineattachmentsid' => 0,
1273             'attachmentsid' => null,
1274             'topreferredformat'   => false
1275         );
1276         foreach ($params['options'] as $option) {
1277             $name = trim($option['name']);
1278             switch ($name) {
1279                 case 'discussionsubscribe':
1280                     $value = clean_param($option['value'], PARAM_BOOL);
1281                     break;
1282                 case 'private':
1283                     $value = clean_param($option['value'], PARAM_BOOL);
1284                     break;
1285                 case 'inlineattachmentsid':
1286                     $value = clean_param($option['value'], PARAM_INT);
1287                     break;
1288                 case 'attachmentsid':
1289                     $value = clean_param($option['value'], PARAM_INT);
1290                     // Ensure that the user has permissions to create attachments.
1291                     if (!has_capability('mod/forum:createattachment', $context)) {
1292                         $value = 0;
1293                     }
1294                     break;
1295                 case 'topreferredformat':
1296                     $value = clean_param($option['value'], PARAM_BOOL);
1297                     break;
1298                 default:
1299                     throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1300             }
1301             $options[$name] = $value;
1302         }
1304         if (!$capabilitymanager->can_post_in_discussion($USER, $discussion)) {
1305             throw new moodle_exception('nopostforum', 'forum');
1306         }
1308         $thresholdwarning = forum_check_throttling($forumrecord, $cm);
1309         forum_check_blocking_threshold($thresholdwarning);
1311         // If we want to force a conversion to the preferred format, let's do it now.
1312         if ($options['topreferredformat']) {
1313             // We always are going to honor the preferred format. We are creating a new post.
1314             $preferredformat = editors_get_preferred_format();
1315             // If the post is not HTML and the preferred format is HTML, convert to it.
1316             if ($params['messageformat'] != FORMAT_HTML and $preferredformat == FORMAT_HTML) {
1317                 $params['message'] = format_text($params['message'], $params['messageformat'], ['context' => $context]);
1318             }
1319             $params['messageformat'] = $preferredformat;
1320         }
1322         // Create the post.
1323         $post = new stdClass();
1324         $post->discussion = $discussion->get_id();
1325         $post->parent = $parent->id;
1326         $post->subject = $params['subject'];
1327         $post->message = $params['message'];
1328         $post->messageformat = $params['messageformat'];
1329         $post->messagetrust = trusttext_trusted($context);
1330         $post->itemid = $options['inlineattachmentsid'];
1331         $post->attachments = $options['attachmentsid'];
1332         $post->isprivatereply = $options['private'];
1333         $post->deleted = 0;
1334         $fakemform = $post->attachments;
1335         if ($postid = forum_add_new_post($post, $fakemform)) {
1337             $post->id = $postid;
1339             // Trigger events and completion.
1340             $params = array(
1341                 'context' => $context,
1342                 'objectid' => $post->id,
1343                 'other' => array(
1344                     'discussionid' => $discussion->get_id(),
1345                     'forumid' => $forum->get_id(),
1346                     'forumtype' => $forum->get_type(),
1347                 )
1348             );
1349             $event = \mod_forum\event\post_created::create($params);
1350             $event->add_record_snapshot('forum_posts', $post);
1351             $event->add_record_snapshot('forum_discussions', $discussionrecord);
1352             $event->trigger();
1354             // Update completion state.
1355             $completion = new completion_info($course);
1356             if ($completion->is_enabled($cm) &&
1357                     ($forum->get_completion_replies() || $forum->get_completion_posts())) {
1358                 $completion->update_state($cm, COMPLETION_COMPLETE);
1359             }
1361             if ($options['discussionsubscribe']) {
1362                 $settings = new stdClass();
1363                 $settings->discussionsubscribe = $options['discussionsubscribe'];
1364                 forum_post_subscription($settings, $forumrecord, $discussionrecord);
1365             }
1366         } else {
1367             throw new moodle_exception('couldnotadd', 'forum');
1368         }
1370         $builderfactory = \mod_forum\local\container::get_builder_factory();
1371         $exportedpostsbuilder = $builderfactory->get_exported_posts_builder();
1372         $postentity = $entityfactory->get_post_from_stdClass($post);
1373         $exportedposts = $exportedpostsbuilder->build($USER, [$forum], [$discussion], [$postentity]);
1374         $exportedpost = $exportedposts[0];
1376         $message = [];
1377         $message[] = [
1378             'type' => 'success',
1379             'message' => get_string("postaddedsuccess", "forum")
1380         ];
1382         $message[] = [
1383             'type' => 'success',
1384             'message' => get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime))
1385         ];
1387         $result = array();
1388         $result['postid'] = $postid;
1389         $result['warnings'] = $warnings;
1390         $result['post'] = $exportedpost;
1391         $result['messages'] = $message;
1392         return $result;
1393     }
1395     /**
1396      * Returns description of method result value
1397      *
1398      * @return external_description
1399      * @since Moodle 3.0
1400      */
1401     public static function add_discussion_post_returns() {
1402         return new external_single_structure(
1403             array(
1404                 'postid' => new external_value(PARAM_INT, 'new post id'),
1405                 'warnings' => new external_warnings(),
1406                 'post' => post_exporter::get_read_structure(),
1407                 'messages' => new external_multiple_structure(
1408                     new external_single_structure(
1409                         array(
1410                             'type' => new external_value(PARAM_TEXT, "The classification to be used in the client side", VALUE_REQUIRED),
1411                             'message' => new external_value(PARAM_TEXT,'untranslated english message to explain the warning', VALUE_REQUIRED)
1412                         ), 'Messages'), 'list of warnings', VALUE_OPTIONAL
1413                 ),
1414                 //'alertmessage' => new external_value(PARAM_RAW, 'Success message to be displayed to the user.'),
1415             )
1416         );
1417     }
1419     /**
1420      * Toggle the favouriting value for the discussion provided
1421      *
1422      * @param int $discussionid The discussion we need to favourite
1423      * @param bool $targetstate The state of the favourite value
1424      * @return array The exported discussion
1425      */
1426     public static function toggle_favourite_state($discussionid, $targetstate) {
1427         global $DB, $PAGE, $USER;
1429         $params = self::validate_parameters(self::toggle_favourite_state_parameters(), [
1430             'discussionid' => $discussionid,
1431             'targetstate' => $targetstate
1432         ]);
1434         $vaultfactory = mod_forum\local\container::get_vault_factory();
1435         // Get the discussion vault and the corresponding discussion entity.
1436         $discussionvault = $vaultfactory->get_discussion_vault();
1437         $discussion = $discussionvault->get_from_id($params['discussionid']);
1439         $forumvault = $vaultfactory->get_forum_vault();
1440         $forum = $forumvault->get_from_id($discussion->get_forum_id());
1441         $forumcontext = $forum->get_context();
1442         self::validate_context($forumcontext);
1444         $managerfactory = mod_forum\local\container::get_manager_factory();
1445         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1447         // Does the user have the ability to favourite the discussion?
1448         if (!$capabilitymanager->can_favourite_discussion($USER)) {
1449             throw new moodle_exception('cannotfavourite', 'forum');
1450         }
1451         $usercontext = context_user::instance($USER->id);
1452         $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1453         $isfavourited = $ufservice->favourite_exists('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1455         $favouritefunction = $targetstate ? 'create_favourite' : 'delete_favourite';
1456         if ($isfavourited != (bool) $params['targetstate']) {
1457             $ufservice->{$favouritefunction}('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1458         }
1460         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1461         $builder = mod_forum\local\container::get_builder_factory()->get_exported_discussion_builder();
1462         $favourited = ($builder->is_favourited($discussion, $forumcontext, $USER) ? [$discussion->get_id()] : []);
1463         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion, [], $favourited);
1464         return $exporter->export($PAGE->get_renderer('mod_forum'));
1465     }
1467     /**
1468      * Returns description of method result value
1469      *
1470      * @return external_description
1471      * @since Moodle 3.0
1472      */
1473     public static function toggle_favourite_state_returns() {
1474         return discussion_exporter::get_read_structure();
1475     }
1477     /**
1478      * Defines the parameters for the toggle_favourite_state method
1479      *
1480      * @return external_function_parameters
1481      */
1482     public static function toggle_favourite_state_parameters() {
1483         return new external_function_parameters(
1484             [
1485                 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1486                 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1487             ]
1488         );
1489     }
1491     /**
1492      * Returns description of method parameters
1493      *
1494      * @return external_function_parameters
1495      * @since Moodle 3.0
1496      */
1497     public static function add_discussion_parameters() {
1498         return new external_function_parameters(
1499             array(
1500                 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1501                 'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
1502                 'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
1503                 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
1504                 'options' => new external_multiple_structure (
1505                     new external_single_structure(
1506                         array(
1507                             'name' => new external_value(PARAM_ALPHANUM,
1508                                         'The allowed keys (value format) are:
1509                                         discussionsubscribe (bool); subscribe to the discussion?, default to true
1510                                         discussionpinned    (bool); is the discussion pinned, default to false
1511                                         inlineattachmentsid              (int); the draft file area id for inline attachments
1512                                         attachmentsid       (int); the draft file area id for attachments
1513                             '),
1514                             'value' => new external_value(PARAM_RAW, 'The value of the option,
1515                                                             This param is validated in the external function.'
1516                         )
1517                     )
1518                 ), 'Options', VALUE_DEFAULT, array())
1519             )
1520         );
1521     }
1523     /**
1524      * Add a new discussion into an existing forum.
1525      *
1526      * @param int $forumid the forum instance id
1527      * @param string $subject new discussion subject
1528      * @param string $message new discussion message (only html format allowed)
1529      * @param int $groupid the user course group
1530      * @param array $options optional settings
1531      * @return array of warnings and the new discussion id
1532      * @since Moodle 3.0
1533      * @throws moodle_exception
1534      */
1535     public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
1536         global $DB, $CFG;
1537         require_once($CFG->dirroot . "/mod/forum/lib.php");
1539         $params = self::validate_parameters(self::add_discussion_parameters(),
1540                                             array(
1541                                                 'forumid' => $forumid,
1542                                                 'subject' => $subject,
1543                                                 'message' => $message,
1544                                                 'groupid' => $groupid,
1545                                                 'options' => $options
1546                                             ));
1548         $warnings = array();
1550         // Request and permission validation.
1551         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1552         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1554         $context = context_module::instance($cm->id);
1555         self::validate_context($context);
1557         // Validate options.
1558         $options = array(
1559             'discussionsubscribe' => true,
1560             'discussionpinned' => false,
1561             'inlineattachmentsid' => 0,
1562             'attachmentsid' => null
1563         );
1564         foreach ($params['options'] as $option) {
1565             $name = trim($option['name']);
1566             switch ($name) {
1567                 case 'discussionsubscribe':
1568                     $value = clean_param($option['value'], PARAM_BOOL);
1569                     break;
1570                 case 'discussionpinned':
1571                     $value = clean_param($option['value'], PARAM_BOOL);
1572                     break;
1573                 case 'inlineattachmentsid':
1574                     $value = clean_param($option['value'], PARAM_INT);
1575                     break;
1576                 case 'attachmentsid':
1577                     $value = clean_param($option['value'], PARAM_INT);
1578                     // Ensure that the user has permissions to create attachments.
1579                     if (!has_capability('mod/forum:createattachment', $context)) {
1580                         $value = 0;
1581                     }
1582                     break;
1583                 default:
1584                     throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1585             }
1586             $options[$name] = $value;
1587         }
1589         // Normalize group.
1590         if (!groups_get_activity_groupmode($cm)) {
1591             // Groups not supported, force to -1.
1592             $groupid = -1;
1593         } else {
1594             // Check if we receive the default or and empty value for groupid,
1595             // in this case, get the group for the user in the activity.
1596             if (empty($params['groupid'])) {
1597                 $groupid = groups_get_activity_group($cm);
1598             } else {
1599                 // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
1600                 $groupid = $params['groupid'];
1601             }
1602         }
1604         if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
1605             throw new moodle_exception('cannotcreatediscussion', 'forum');
1606         }
1608         $thresholdwarning = forum_check_throttling($forum, $cm);
1609         forum_check_blocking_threshold($thresholdwarning);
1611         // Create the discussion.
1612         $discussion = new stdClass();
1613         $discussion->course = $course->id;
1614         $discussion->forum = $forum->id;
1615         $discussion->message = $params['message'];
1616         $discussion->messageformat = FORMAT_HTML;   // Force formatting for now.
1617         $discussion->messagetrust = trusttext_trusted($context);
1618         $discussion->itemid = $options['inlineattachmentsid'];
1619         $discussion->groupid = $groupid;
1620         $discussion->mailnow = 0;
1621         $discussion->subject = $params['subject'];
1622         $discussion->name = $discussion->subject;
1623         $discussion->timestart = 0;
1624         $discussion->timeend = 0;
1625         $discussion->timelocked = 0;
1626         $discussion->attachments = $options['attachmentsid'];
1628         if (has_capability('mod/forum:pindiscussions', $context) && $options['discussionpinned']) {
1629             $discussion->pinned = FORUM_DISCUSSION_PINNED;
1630         } else {
1631             $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
1632         }
1633         $fakemform = $options['attachmentsid'];
1634         if ($discussionid = forum_add_discussion($discussion, $fakemform)) {
1636             $discussion->id = $discussionid;
1638             // Trigger events and completion.
1640             $params = array(
1641                 'context' => $context,
1642                 'objectid' => $discussion->id,
1643                 'other' => array(
1644                     'forumid' => $forum->id,
1645                 )
1646             );
1647             $event = \mod_forum\event\discussion_created::create($params);
1648             $event->add_record_snapshot('forum_discussions', $discussion);
1649             $event->trigger();
1651             $completion = new completion_info($course);
1652             if ($completion->is_enabled($cm) &&
1653                     ($forum->completiondiscussions || $forum->completionposts)) {
1654                 $completion->update_state($cm, COMPLETION_COMPLETE);
1655             }
1657             $settings = new stdClass();
1658             $settings->discussionsubscribe = $options['discussionsubscribe'];
1659             forum_post_subscription($settings, $forum, $discussion);
1660         } else {
1661             throw new moodle_exception('couldnotadd', 'forum');
1662         }
1664         $result = array();
1665         $result['discussionid'] = $discussionid;
1666         $result['warnings'] = $warnings;
1667         return $result;
1668     }
1670     /**
1671      * Returns description of method result value
1672      *
1673      * @return external_description
1674      * @since Moodle 3.0
1675      */
1676     public static function add_discussion_returns() {
1677         return new external_single_structure(
1678             array(
1679                 'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
1680                 'warnings' => new external_warnings()
1681             )
1682         );
1683     }
1685     /**
1686      * Returns description of method parameters
1687      *
1688      * @return external_function_parameters
1689      * @since Moodle 3.1
1690      */
1691     public static function can_add_discussion_parameters() {
1692         return new external_function_parameters(
1693             array(
1694                 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1695                 'groupid' => new external_value(PARAM_INT, 'The group to check, default to active group.
1696                                                 Use -1 to check if the user can post in all the groups.', VALUE_DEFAULT, null)
1697             )
1698         );
1699     }
1701     /**
1702      * Check if the current user can add discussions in the given forum (and optionally for the given group).
1703      *
1704      * @param int $forumid the forum instance id
1705      * @param int $groupid the group to check, default to active group. Use -1 to check if the user can post in all the groups.
1706      * @return array of warnings and the status (true if the user can add discussions)
1707      * @since Moodle 3.1
1708      * @throws moodle_exception
1709      */
1710     public static function can_add_discussion($forumid, $groupid = null) {
1711         global $DB, $CFG;
1712         require_once($CFG->dirroot . "/mod/forum/lib.php");
1714         $params = self::validate_parameters(self::can_add_discussion_parameters(),
1715                                             array(
1716                                                 'forumid' => $forumid,
1717                                                 'groupid' => $groupid,
1718                                             ));
1719         $warnings = array();
1721         // Request and permission validation.
1722         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1723         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1725         $context = context_module::instance($cm->id);
1726         self::validate_context($context);
1728         $status = forum_user_can_post_discussion($forum, $params['groupid'], -1, $cm, $context);
1730         $result = array();
1731         $result['status'] = $status;
1732         $result['canpindiscussions'] = has_capability('mod/forum:pindiscussions', $context);
1733         $result['cancreateattachment'] = forum_can_create_attachment($forum, $context);
1734         $result['warnings'] = $warnings;
1735         return $result;
1736     }
1738     /**
1739      * Returns description of method result value
1740      *
1741      * @return external_description
1742      * @since Moodle 3.1
1743      */
1744     public static function can_add_discussion_returns() {
1745         return new external_single_structure(
1746             array(
1747                 'status' => new external_value(PARAM_BOOL, 'True if the user can add discussions, false otherwise.'),
1748                 'canpindiscussions' => new external_value(PARAM_BOOL, 'True if the user can pin discussions, false otherwise.',
1749                     VALUE_OPTIONAL),
1750                 'cancreateattachment' => new external_value(PARAM_BOOL, 'True if the user can add attachments, false otherwise.',
1751                     VALUE_OPTIONAL),
1752                 'warnings' => new external_warnings()
1753             )
1754         );
1755     }
1757     /**
1758      * Describes the parameters for get_forum_access_information.
1759      *
1760      * @return external_external_function_parameters
1761      * @since Moodle 3.7
1762      */
1763     public static function get_forum_access_information_parameters() {
1764         return new external_function_parameters (
1765             array(
1766                 'forumid' => new external_value(PARAM_INT, 'Forum instance id.')
1767             )
1768         );
1769     }
1771     /**
1772      * Return access information for a given forum.
1773      *
1774      * @param int $forumid forum instance id
1775      * @return array of warnings and the access information
1776      * @since Moodle 3.7
1777      * @throws  moodle_exception
1778      */
1779     public static function get_forum_access_information($forumid) {
1780         global $DB;
1782         $params = self::validate_parameters(self::get_forum_access_information_parameters(), array('forumid' => $forumid));
1784         // Request and permission validation.
1785         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1786         $cm = get_coursemodule_from_instance('forum', $forum->id);
1788         $context = context_module::instance($cm->id);
1789         self::validate_context($context);
1791         $result = array();
1792         // Return all the available capabilities.
1793         $capabilities = load_capability_def('mod_forum');
1794         foreach ($capabilities as $capname => $capdata) {
1795             // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1796             $field = 'can' . str_replace('mod/forum:', '', $capname);
1797             $result[$field] = has_capability($capname, $context);
1798         }
1800         $result['warnings'] = array();
1801         return $result;
1802     }
1804     /**
1805      * Describes the get_forum_access_information return value.
1806      *
1807      * @return external_single_structure
1808      * @since Moodle 3.7
1809      */
1810     public static function get_forum_access_information_returns() {
1812         $structure = array(
1813             'warnings' => new external_warnings()
1814         );
1816         $capabilities = load_capability_def('mod_forum');
1817         foreach ($capabilities as $capname => $capdata) {
1818             // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1819             $field = 'can' . str_replace('mod/forum:', '', $capname);
1820             $structure[$field] = new external_value(PARAM_BOOL, 'Whether the user has the capability ' . $capname . ' allowed.',
1821                 VALUE_OPTIONAL);
1822         }
1824         return new external_single_structure($structure);
1825     }
1827     /**
1828      * Set the subscription state.
1829      *
1830      * @param   int     $forumid
1831      * @param   int     $discussionid
1832      * @param   bool    $targetstate
1833      * @return  \stdClass
1834      */
1835     public static function set_subscription_state($forumid, $discussionid, $targetstate) {
1836         global $PAGE, $USER;
1838         $params = self::validate_parameters(self::set_subscription_state_parameters(), [
1839             'forumid' => $forumid,
1840             'discussionid' => $discussionid,
1841             'targetstate' => $targetstate
1842         ]);
1844         $vaultfactory = mod_forum\local\container::get_vault_factory();
1845         $forumvault = $vaultfactory->get_forum_vault();
1846         $forum = $forumvault->get_from_id($params['forumid']);
1847         $coursemodule = $forum->get_course_module_record();
1848         $context = $forum->get_context();
1850         self::validate_context($context);
1852         $discussionvault = $vaultfactory->get_discussion_vault();
1853         $discussion = $discussionvault->get_from_id($params['discussionid']);
1854         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1856         $forumrecord = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
1857         $discussionrecord = $legacydatamapperfactory->get_discussion_data_mapper()->to_legacy_object($discussion);
1859         if (!\mod_forum\subscriptions::is_subscribable($forumrecord)) {
1860             // Nothing to do. We won't actually output any content here though.
1861             throw new \moodle_exception('cannotsubscribe', 'mod_forum');
1862         }
1864         $issubscribed = \mod_forum\subscriptions::is_subscribed(
1865             $USER->id,
1866             $forumrecord,
1867             $discussion->get_id(),
1868             $coursemodule
1869         );
1871         // If the current state doesn't equal the desired state then update the current
1872         // state to the desired state.
1873         if ($issubscribed != (bool) $params['targetstate']) {
1874             if ($params['targetstate']) {
1875                 \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussionrecord, $context);
1876             } else {
1877                 \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussionrecord, $context);
1878             }
1879         }
1881         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1882         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1883         return $exporter->export($PAGE->get_renderer('mod_forum'));
1884     }
1886     /**
1887      * Returns description of method parameters.
1888      *
1889      * @return external_function_parameters
1890      */
1891     public static function set_subscription_state_parameters() {
1892         return new external_function_parameters(
1893             [
1894                 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1895                 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1896                 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1897             ]
1898         );
1899     }
1901     /**
1902      * Returns description of method result value.
1903      *
1904      * @return external_description
1905      */
1906     public static function set_subscription_state_returns() {
1907         return discussion_exporter::get_read_structure();
1908     }
1910     /**
1911      * Set the lock state.
1912      *
1913      * @param   int     $forumid
1914      * @param   int     $discussionid
1915      * @param   string    $targetstate
1916      * @return  \stdClass
1917      */
1918     public static function set_lock_state($forumid, $discussionid, $targetstate) {
1919         global $DB, $PAGE, $USER;
1921         $params = self::validate_parameters(self::set_lock_state_parameters(), [
1922             'forumid' => $forumid,
1923             'discussionid' => $discussionid,
1924             'targetstate' => $targetstate
1925         ]);
1927         $vaultfactory = mod_forum\local\container::get_vault_factory();
1928         $forumvault = $vaultfactory->get_forum_vault();
1929         $forum = $forumvault->get_from_id($params['forumid']);
1931         $managerfactory = mod_forum\local\container::get_manager_factory();
1932         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1933         if (!$capabilitymanager->can_manage_forum($USER)) {
1934             throw new moodle_exception('errorcannotlock', 'forum');
1935         }
1937         // If the targetstate(currentstate) is not 0 then it should be set to the current time.
1938         $lockedvalue = $targetstate ? 0 : time();
1939         self::validate_context($forum->get_context());
1941         $discussionvault = $vaultfactory->get_discussion_vault();
1942         $discussion = $discussionvault->get_from_id($params['discussionid']);
1944         // If the current state doesn't equal the desired state then update the current.
1945         // state to the desired state.
1946         $discussion->toggle_locked_state($lockedvalue);
1947         $response = $discussionvault->update_discussion($discussion);
1948         $discussion = !$response ? $response : $discussion;
1949         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1950         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1951         return $exporter->export($PAGE->get_renderer('mod_forum'));
1952     }
1954     /**
1955      * Returns description of method parameters.
1956      *
1957      * @return external_function_parameters
1958      */
1959     public static function set_lock_state_parameters() {
1960         return new external_function_parameters(
1961             [
1962                 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1963                 'discussionid' => new external_value(PARAM_INT, 'The discussion to lock / unlock'),
1964                 'targetstate' => new external_value(PARAM_INT, 'The timestamp for the lock state')
1965             ]
1966         );
1967     }
1969     /**
1970      * Returns description of method result value.
1971      *
1972      * @return external_description
1973      */
1974     public static function set_lock_state_returns() {
1975         return new external_single_structure([
1976             'id' => new external_value(PARAM_INT, 'The discussion we are locking.'),
1977             'locked' => new external_value(PARAM_BOOL, 'The locked state of the discussion.'),
1978             'times' => new external_single_structure([
1979                 'locked' => new external_value(PARAM_INT, 'The locked time of the discussion.'),
1980             ])
1981         ]);
1982     }
1984     /**
1985      * Set the pin state.
1986      *
1987      * @param   int     $discussionid
1988      * @param   bool    $targetstate
1989      * @return  \stdClass
1990      */
1991     public static function set_pin_state($discussionid, $targetstate) {
1992         global $PAGE, $USER;
1993         $params = self::validate_parameters(self::set_pin_state_parameters(), [
1994             'discussionid' => $discussionid,
1995             'targetstate' => $targetstate,
1996         ]);
1997         $vaultfactory = mod_forum\local\container::get_vault_factory();
1998         $managerfactory = mod_forum\local\container::get_manager_factory();
1999         $forumvault = $vaultfactory->get_forum_vault();
2000         $discussionvault = $vaultfactory->get_discussion_vault();
2001         $discussion = $discussionvault->get_from_id($params['discussionid']);
2002         $forum = $forumvault->get_from_id($discussion->get_forum_id());
2003         $capabilitymanager = $managerfactory->get_capability_manager($forum);
2005         self::validate_context($forum->get_context());
2007         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
2008         if (!$capabilitymanager->can_pin_discussions($USER)) {
2009             // Nothing to do. We won't actually output any content here though.
2010             throw new \moodle_exception('cannotpindiscussions', 'mod_forum');
2011         }
2013         $discussion->set_pinned($targetstate);
2014         $discussionvault->update_discussion($discussion);
2016         $exporterfactory = mod_forum\local\container::get_exporter_factory();
2017         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
2018         return $exporter->export($PAGE->get_renderer('mod_forum'));
2019     }
2021     /**
2022      * Returns description of method parameters.
2023      *
2024      * @return external_function_parameters
2025      */
2026     public static function set_pin_state_parameters() {
2027         return new external_function_parameters(
2028             [
2029                 'discussionid' => new external_value(PARAM_INT, 'The discussion to pin or unpin', VALUE_REQUIRED,
2030                     null, NULL_NOT_ALLOWED),
2031                 'targetstate' => new external_value(PARAM_INT, 'The target state', VALUE_REQUIRED,
2032                     null, NULL_NOT_ALLOWED),
2033             ]
2034         );
2035     }
2037     /**
2038      * Returns description of method result value.
2039      *
2040      * @return external_single_structure
2041      */
2042     public static function set_pin_state_returns() {
2043         return discussion_exporter::get_read_structure();
2044     }