MDL-66893 mod_forum: update user content region in grader UI
[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                 $options = array('noclean' => true);
97                 list($forum->intro, $forum->introformat) =
98                     external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', null, $options);
99                 $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false);
100                 // Discussions count. This function does static request cache.
101                 $forum->numdiscussions = forum_count_discussions($forum, $cm, $course);
102                 $forum->cmid = $forum->coursemodule;
103                 $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context);
104                 $forum->istracked = forum_tp_is_tracked($forum);
105                 if ($forum->istracked) {
106                     $forum->unreadpostscount = forum_tp_count_forum_unread_posts($cm, $course);
107                 }
109                 // Add the forum to the array to return.
110                 $arrforums[$forum->id] = $forum;
111             }
112         }
114         return $arrforums;
115     }
117     /**
118      * Describes the get_forum return value.
119      *
120      * @return external_single_structure
121      * @since Moodle 2.5
122      */
123     public static function get_forums_by_courses_returns() {
124         return new external_multiple_structure(
125             new external_single_structure(
126                 array(
127                     'id' => new external_value(PARAM_INT, 'Forum id'),
128                     'course' => new external_value(PARAM_INT, 'Course id'),
129                     'type' => new external_value(PARAM_TEXT, 'The forum type'),
130                     'name' => new external_value(PARAM_RAW, 'Forum name'),
131                     'intro' => new external_value(PARAM_RAW, 'The forum intro'),
132                     'introformat' => new external_format_value('intro'),
133                     'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
134                     'duedate' => new external_value(PARAM_INT, 'duedate for the user', VALUE_OPTIONAL),
135                     'cutoffdate' => new external_value(PARAM_INT, 'cutoffdate for the user', VALUE_OPTIONAL),
136                     'assessed' => new external_value(PARAM_INT, 'Aggregate type'),
137                     'assesstimestart' => new external_value(PARAM_INT, 'Assess start time'),
138                     'assesstimefinish' => new external_value(PARAM_INT, 'Assess finish time'),
139                     'scale' => new external_value(PARAM_INT, 'Scale'),
140                     'grade_forum' => new external_value(PARAM_INT, 'Whole forum grade'),
141                     'maxbytes' => new external_value(PARAM_INT, 'Maximum attachment size'),
142                     'maxattachments' => new external_value(PARAM_INT, 'Maximum number of attachments'),
143                     'forcesubscribe' => new external_value(PARAM_INT, 'Force users to subscribe'),
144                     'trackingtype' => new external_value(PARAM_INT, 'Subscription mode'),
145                     'rsstype' => new external_value(PARAM_INT, 'RSS feed for this activity'),
146                     'rssarticles' => new external_value(PARAM_INT, 'Number of RSS recent articles'),
147                     'timemodified' => new external_value(PARAM_INT, 'Time modified'),
148                     'warnafter' => new external_value(PARAM_INT, 'Post threshold for warning'),
149                     'blockafter' => new external_value(PARAM_INT, 'Post threshold for blocking'),
150                     'blockperiod' => new external_value(PARAM_INT, 'Time period for blocking'),
151                     'completiondiscussions' => new external_value(PARAM_INT, 'Student must create discussions'),
152                     'completionreplies' => new external_value(PARAM_INT, 'Student must post replies'),
153                     'completionposts' => new external_value(PARAM_INT, 'Student must post discussions or replies'),
154                     'cmid' => new external_value(PARAM_INT, 'Course module id'),
155                     'numdiscussions' => new external_value(PARAM_INT, 'Number of discussions in the forum', VALUE_OPTIONAL),
156                     'cancreatediscussions' => new external_value(PARAM_BOOL, 'If the user can create discussions', VALUE_OPTIONAL),
157                     'lockdiscussionafter' => new external_value(PARAM_INT, 'After what period a discussion is locked', VALUE_OPTIONAL),
158                     'istracked' => new external_value(PARAM_BOOL, 'If the user is tracking the forum', VALUE_OPTIONAL),
159                     'unreadpostscount' => new external_value(PARAM_INT, 'The number of unread posts for tracked forums',
160                         VALUE_OPTIONAL),
161                 ), 'forum'
162             )
163         );
164     }
166     /**
167      * Get the forum posts in the specified discussion.
168      *
169      * @param   int $discussionid
170      * @param   string $sortby
171      * @param   string $sortdirection
172      * @return  array
173      */
174     public static function get_discussion_posts(int $discussionid, ?string $sortby, ?string $sortdirection) {
175         global $USER;
176         // Validate the parameter.
177         $params = self::validate_parameters(self::get_discussion_posts_parameters(), [
178                 'discussionid' => $discussionid,
179                 'sortby' => $sortby,
180                 'sortdirection' => $sortdirection,
181             ]);
182         $warnings = [];
184         $vaultfactory = mod_forum\local\container::get_vault_factory();
186         $discussionvault = $vaultfactory->get_discussion_vault();
187         $discussion = $discussionvault->get_from_id($params['discussionid']);
189         $forumvault = $vaultfactory->get_forum_vault();
190         $forum = $forumvault->get_from_id($discussion->get_forum_id());
191         $context = $forum->get_context();
192         self::validate_context($context);
194         $sortby = $params['sortby'];
195         $sortdirection = $params['sortdirection'];
196         $sortallowedvalues = ['id', 'created', 'modified'];
197         $directionallowedvalues = ['ASC', 'DESC'];
199         if (!in_array(strtolower($sortby), $sortallowedvalues)) {
200             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
201                 'allowed values are: ' . implode(', ', $sortallowedvalues));
202         }
204         $sortdirection = strtoupper($sortdirection);
205         if (!in_array($sortdirection, $directionallowedvalues)) {
206             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
207                 'allowed values are: ' . implode(',', $directionallowedvalues));
208         }
210         $managerfactory = mod_forum\local\container::get_manager_factory();
211         $capabilitymanager = $managerfactory->get_capability_manager($forum);
213         $postvault = $vaultfactory->get_post_vault();
214         $posts = $postvault->get_from_discussion_id(
215                 $USER,
216                 $discussion->get_id(),
217                 $capabilitymanager->can_view_any_private_reply($USER),
218                 "{$sortby} {$sortdirection}"
219             );
221         $builderfactory = mod_forum\local\container::get_builder_factory();
222         $postbuilder = $builderfactory->get_exported_posts_builder();
224         $legacydatamapper = mod_forum\local\container::get_legacy_data_mapper_factory();
226         return [
227             'posts' => $postbuilder->build($USER, [$forum], [$discussion], $posts),
228             'ratinginfo' => \core_rating\external\util::get_rating_info(
229                 $legacydatamapper->get_forum_data_mapper()->to_legacy_object($forum),
230                 $forum->get_context(),
231                 'mod_forum',
232                 'post',
233                 $legacydatamapper->get_post_data_mapper()->to_legacy_objects($posts)
234             ),
235             'warnings' => $warnings,
236         ];
237     }
239     /**
240      * Describe the post parameters.
241      *
242      * @return external_function_parameters
243      */
244     public static function get_discussion_posts_parameters() {
245         return new external_function_parameters ([
246             'discussionid' => new external_value(PARAM_INT, 'The ID of the discussion from which to fetch posts.', VALUE_REQUIRED),
247             'sortby' => new external_value(PARAM_ALPHA, 'Sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
248             'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
249         ]);
250     }
252     /**
253      * Describe the post return format.
254      *
255      * @return external_single_structure
256      */
257     public static function get_discussion_posts_returns() {
258         return new external_single_structure([
259             'posts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
260             'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
261             'warnings' => new external_warnings()
262         ]);
263     }
265     /**
266      * Describes the parameters for get_forum_discussion_posts.
267      *
268      * @return external_function_parameters
269      * @since Moodle 2.7
270      */
271     public static function get_forum_discussion_posts_parameters() {
272         return new external_function_parameters (
273             array(
274                 'discussionid' => new external_value(PARAM_INT, 'discussion ID', VALUE_REQUIRED),
275                 'sortby' => new external_value(PARAM_ALPHA,
276                     'sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
277                 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
278             )
279         );
280     }
282     /**
283      * Returns a list of forum posts for a discussion
284      *
285      * @param int $discussionid the post ids
286      * @param string $sortby sort by this element (id, created or modified)
287      * @param string $sortdirection sort direction: ASC or DESC
288      *
289      * @return array the forum post details
290      * @since Moodle 2.7
291      * @todo MDL-65252 This will be removed in Moodle 4.1
292      */
293     public static function get_forum_discussion_posts($discussionid, $sortby = "created", $sortdirection = "DESC") {
294         global $CFG, $DB, $USER, $PAGE;
296         $posts = array();
297         $warnings = array();
299         // Validate the parameter.
300         $params = self::validate_parameters(self::get_forum_discussion_posts_parameters(),
301             array(
302                 'discussionid' => $discussionid,
303                 'sortby' => $sortby,
304                 'sortdirection' => $sortdirection));
306         // Compact/extract functions are not recommended.
307         $discussionid   = $params['discussionid'];
308         $sortby         = $params['sortby'];
309         $sortdirection  = $params['sortdirection'];
311         $sortallowedvalues = array('id', 'created', 'modified');
312         if (!in_array($sortby, $sortallowedvalues)) {
313             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
314                 'allowed values are: ' . implode(',', $sortallowedvalues));
315         }
317         $sortdirection = strtoupper($sortdirection);
318         $directionallowedvalues = array('ASC', 'DESC');
319         if (!in_array($sortdirection, $directionallowedvalues)) {
320             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
321                 'allowed values are: ' . implode(',', $directionallowedvalues));
322         }
324         $discussion = $DB->get_record('forum_discussions', array('id' => $discussionid), '*', MUST_EXIST);
325         $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
326         $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
327         $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
329         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
330         $modcontext = context_module::instance($cm->id);
331         self::validate_context($modcontext);
333         // This require must be here, see mod/forum/discuss.php.
334         require_once($CFG->dirroot . "/mod/forum/lib.php");
336         // Check they have the view forum capability.
337         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
339         if (! $post = forum_get_post_full($discussion->firstpost)) {
340             throw new moodle_exception('notexists', 'forum');
341         }
343         // This function check groups, qanda, timed discussions, etc.
344         if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
345             throw new moodle_exception('noviewdiscussionspermission', 'forum');
346         }
348         $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
350         // We will add this field in the response.
351         $canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
353         $forumtracked = forum_tp_is_tracked($forum);
355         $sort = 'p.' . $sortby . ' ' . $sortdirection;
356         $allposts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
358         foreach ($allposts as $post) {
359             if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm, false)) {
360                 $warning = array();
361                 $warning['item'] = 'post';
362                 $warning['itemid'] = $post->id;
363                 $warning['warningcode'] = '1';
364                 $warning['message'] = 'You can\'t see this post';
365                 $warnings[] = $warning;
366                 continue;
367             }
369             // Function forum_get_all_discussion_posts adds postread field.
370             // Note that the value returned can be a boolean or an integer. The WS expects a boolean.
371             if (empty($post->postread)) {
372                 $post->postread = false;
373             } else {
374                 $post->postread = true;
375             }
377             $post->isprivatereply = !empty($post->privatereplyto);
379             $post->canreply = $canreply;
380             if (!empty($post->children)) {
381                 $post->children = array_keys($post->children);
382             } else {
383                 $post->children = array();
384             }
386             if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
387                 // The post is available, but has been marked as deleted.
388                 // It will still be available but filled with a placeholder.
389                 $post->userid = null;
390                 $post->userfullname = null;
391                 $post->userpictureurl = null;
393                 $post->subject = get_string('privacy:request:delete:post:subject', 'mod_forum');
394                 $post->message = get_string('privacy:request:delete:post:message', 'mod_forum');
396                 $post->deleted = true;
397                 $posts[] = $post;
399                 continue;
400             }
401             $post->deleted = false;
403             if (forum_is_author_hidden($post, $forum)) {
404                 $post->userid = null;
405                 $post->userfullname = null;
406                 $post->userpictureurl = null;
407             } else {
408                 $user = new stdclass();
409                 $user->id = $post->userid;
410                 $user = username_load_fields_from_object($user, $post, null, array('picture', 'imagealt', 'email'));
411                 $post->userfullname = fullname($user, $canviewfullname);
413                 $userpicture = new user_picture($user);
414                 $userpicture->size = 1; // Size f1.
415                 $post->userpictureurl = $userpicture->get_url($PAGE)->out(false);
416             }
418             $post->subject = external_format_string($post->subject, $modcontext->id);
419             // Rewrite embedded images URLs.
420             $options = array('trusted' => $post->messagetrust);
421             list($post->message, $post->messageformat) =
422                 external_format_text($post->message, $post->messageformat, $modcontext->id, 'mod_forum', 'post', $post->id,
423                     $options);
425             // List attachments.
426             if (!empty($post->attachment)) {
427                 $post->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $post->id);
428             }
429             $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $post->id);
430             if (!empty($messageinlinefiles)) {
431                 $post->messageinlinefiles = $messageinlinefiles;
432             }
433             // Post tags.
434             $post->tags = \core_tag\external\util::get_item_tags('mod_forum', 'forum_posts', $post->id);
436             $posts[] = $post;
437         }
439         $result = array();
440         $result['posts'] = $posts;
441         $result['ratinginfo'] = \core_rating\external\util::get_rating_info($forum, $modcontext, 'mod_forum', 'post', $posts);
442         $result['warnings'] = $warnings;
443         return $result;
444     }
446     /**
447      * Describes the get_forum_discussion_posts return value.
448      *
449      * @return external_single_structure
450      * @since Moodle 2.7
451      */
452     public static function get_forum_discussion_posts_returns() {
453         return new external_single_structure(
454             array(
455                 'posts' => new external_multiple_structure(
456                         new external_single_structure(
457                             array(
458                                 'id' => new external_value(PARAM_INT, 'Post id'),
459                                 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
460                                 'parent' => new external_value(PARAM_INT, 'Parent id'),
461                                 'userid' => new external_value(PARAM_INT, 'User id'),
462                                 'created' => new external_value(PARAM_INT, 'Creation time'),
463                                 'modified' => new external_value(PARAM_INT, 'Time modified'),
464                                 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
465                                 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
466                                 'message' => new external_value(PARAM_RAW, 'The post message'),
467                                 'messageformat' => new external_format_value('message'),
468                                 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
469                                 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
470                                 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
471                                 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
472                                 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
473                                 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
474                                 'children' => new external_multiple_structure(new external_value(PARAM_INT, 'children post id')),
475                                 'canreply' => new external_value(PARAM_BOOL, 'The user can reply to posts?'),
476                                 'postread' => new external_value(PARAM_BOOL, 'The post was read'),
477                                 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
478                                 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.', VALUE_OPTIONAL),
479                                 'deleted' => new external_value(PARAM_BOOL, 'This post has been removed.'),
480                                 'isprivatereply' => new external_value(PARAM_BOOL, 'The post is a private reply'),
481                                 'tags' => new external_multiple_structure(
482                                     \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags', VALUE_OPTIONAL
483                                 ),
484                             ), 'post'
485                         )
486                     ),
487                 'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
488                 'warnings' => new external_warnings()
489             )
490         );
491     }
493     /**
494      * Mark the get_forum_discussion_posts web service as deprecated.
495      *
496      * @return  bool
497      */
498     public static function get_forum_discussion_posts_is_deprecated() {
499         return true;
500     }
502     /**
503      * Describes the parameters for get_forum_discussions_paginated.
504      *
505      * @deprecated since 3.7
506      * @return external_function_parameters
507      * @since Moodle 2.8
508      */
509     public static function get_forum_discussions_paginated_parameters() {
510         return new external_function_parameters (
511             array(
512                 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
513                 'sortby' => new external_value(PARAM_ALPHA,
514                     'sort by this element: id, timemodified, timestart or timeend', VALUE_DEFAULT, 'timemodified'),
515                 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
516                 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
517                 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
518             )
519         );
520     }
522     /**
523      * Returns a list of forum discussions optionally sorted and paginated.
524      *
525      * @deprecated since 3.7
526      * @param int $forumid the forum instance id
527      * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
528      * @param string $sortdirection sort direction: ASC or DESC
529      * @param int $page page number
530      * @param int $perpage items per page
531      *
532      * @return array the forum discussion details including warnings
533      * @since Moodle 2.8
534      */
535     public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC',
536             $page = -1, $perpage = 0) {
537         global $CFG, $DB, $USER, $PAGE;
539         require_once($CFG->dirroot . "/mod/forum/lib.php");
541         $warnings = array();
542         $discussions = array();
544         $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(),
545             array(
546                 'forumid' => $forumid,
547                 'sortby' => $sortby,
548                 'sortdirection' => $sortdirection,
549                 'page' => $page,
550                 'perpage' => $perpage
551             )
552         );
554         // Compact/extract functions are not recommended.
555         $forumid        = $params['forumid'];
556         $sortby         = $params['sortby'];
557         $sortdirection  = $params['sortdirection'];
558         $page           = $params['page'];
559         $perpage        = $params['perpage'];
561         $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
562         if (!in_array($sortby, $sortallowedvalues)) {
563             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
564                 'allowed values are: ' . implode(',', $sortallowedvalues));
565         }
567         $sortdirection = strtoupper($sortdirection);
568         $directionallowedvalues = array('ASC', 'DESC');
569         if (!in_array($sortdirection, $directionallowedvalues)) {
570             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
571                 'allowed values are: ' . implode(',', $directionallowedvalues));
572         }
574         $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
575         $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
576         $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
578         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
579         $modcontext = context_module::instance($cm->id);
580         self::validate_context($modcontext);
582         // Check they have the view forum capability.
583         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
585         $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
586         $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
588         if ($alldiscussions) {
589             $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
591             // Get the unreads array, this takes a forum id and returns data for all discussions.
592             $unreads = array();
593             if ($cantrack = forum_tp_can_track_forums($forum)) {
594                 if ($forumtracked = forum_tp_is_tracked($forum)) {
595                     $unreads = forum_get_discussions_unread($cm);
596                 }
597             }
598             // The forum function returns the replies for all the discussions in a given forum.
599             $canseeprivatereplies = has_capability('mod/forum:readprivatereplies', $modcontext);
600             $canlock = has_capability('moodle/course:manageactivities', $modcontext, $USER);
601             $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage, $canseeprivatereplies);
603             foreach ($alldiscussions as $discussion) {
605                 // This function checks for qanda forums.
606                 // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
607                 $discussionrec = clone $discussion;
608                 $discussionrec->id = $discussion->discussion;
609                 if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
610                     $warning = array();
611                     // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
612                     $warning['item'] = 'post';
613                     $warning['itemid'] = $discussion->id;
614                     $warning['warningcode'] = '1';
615                     $warning['message'] = 'You can\'t see this discussion';
616                     $warnings[] = $warning;
617                     continue;
618                 }
620                 $discussion->numunread = 0;
621                 if ($cantrack && $forumtracked) {
622                     if (isset($unreads[$discussion->discussion])) {
623                         $discussion->numunread = (int) $unreads[$discussion->discussion];
624                     }
625                 }
627                 $discussion->numreplies = 0;
628                 if (!empty($replies[$discussion->discussion])) {
629                     $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
630                 }
632                 $discussion->name = external_format_string($discussion->name, $modcontext->id);
633                 $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
634                 // Rewrite embedded images URLs.
635                 $options = array('trusted' => $discussion->messagetrust);
636                 list($discussion->message, $discussion->messageformat) =
637                     external_format_text($discussion->message, $discussion->messageformat,
638                                             $modcontext->id, 'mod_forum', 'post', $discussion->id, $options);
640                 // List attachments.
641                 if (!empty($discussion->attachment)) {
642                     $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
643                                                                                 $discussion->id);
644                 }
645                 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
646                 if (!empty($messageinlinefiles)) {
647                     $discussion->messageinlinefiles = $messageinlinefiles;
648                 }
650                 $discussion->locked = forum_discussion_is_locked($forum, $discussion);
651                 $discussion->canlock = $canlock;
652                 $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
654                 if (forum_is_author_hidden($discussion, $forum)) {
655                     $discussion->userid = null;
656                     $discussion->userfullname = null;
657                     $discussion->userpictureurl = null;
659                     $discussion->usermodified = null;
660                     $discussion->usermodifiedfullname = null;
661                     $discussion->usermodifiedpictureurl = null;
662                 } else {
663                     $picturefields = explode(',', user_picture::fields());
665                     // Load user objects from the results of the query.
666                     $user = new stdclass();
667                     $user->id = $discussion->userid;
668                     $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
669                     // Preserve the id, it can be modified by username_load_fields_from_object.
670                     $user->id = $discussion->userid;
671                     $discussion->userfullname = fullname($user, $canviewfullname);
673                     $userpicture = new user_picture($user);
674                     $userpicture->size = 1; // Size f1.
675                     $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
677                     $usermodified = new stdclass();
678                     $usermodified->id = $discussion->usermodified;
679                     $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
680                     // Preserve the id (it can be overwritten due to the prefixed $picturefields).
681                     $usermodified->id = $discussion->usermodified;
682                     $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
684                     $userpicture = new user_picture($usermodified);
685                     $userpicture->size = 1; // Size f1.
686                     $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
687                 }
689                 $discussions[] = $discussion;
690             }
691         }
693         $result = array();
694         $result['discussions'] = $discussions;
695         $result['warnings'] = $warnings;
696         return $result;
698     }
700     /**
701      * Describes the get_forum_discussions_paginated return value.
702      *
703      * @deprecated since 3.7
704      * @return external_single_structure
705      * @since Moodle 2.8
706      */
707     public static function get_forum_discussions_paginated_returns() {
708         return new external_single_structure(
709             array(
710                 'discussions' => new external_multiple_structure(
711                         new external_single_structure(
712                             array(
713                                 'id' => new external_value(PARAM_INT, 'Post id'),
714                                 'name' => new external_value(PARAM_TEXT, 'Discussion name'),
715                                 'groupid' => new external_value(PARAM_INT, 'Group id'),
716                                 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
717                                 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
718                                 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
719                                 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
720                                 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
721                                 'parent' => new external_value(PARAM_INT, 'Parent id'),
722                                 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
723                                 'created' => new external_value(PARAM_INT, 'Creation time'),
724                                 'modified' => new external_value(PARAM_INT, 'Time modified'),
725                                 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
726                                 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
727                                 'message' => new external_value(PARAM_RAW, 'The post message'),
728                                 'messageformat' => new external_format_value('message'),
729                                 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
730                                 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
731                                 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
732                                 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
733                                 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
734                                 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
735                                 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
736                                 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
737                                 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
738                                 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
739                                 'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
740                                 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
741                                 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
742                                 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
743                                 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
744                                 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
745                             ), 'post'
746                         )
747                     ),
748                 'warnings' => new external_warnings()
749             )
750         );
751     }
753     /**
754      * Describes the parameters for get_forum_discussions.
755      *
756      * @return external_function_parameters
757      * @since Moodle 3.7
758      */
759     public static function get_forum_discussions_parameters() {
760         return new external_function_parameters (
761             array(
762                 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
763                 'sortorder' => new external_value(PARAM_INT,
764                     'sort by this element: numreplies, , created or timemodified', VALUE_DEFAULT, -1),
765                 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
766                 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
767                 'groupid' => new external_value(PARAM_INT, 'group id', VALUE_DEFAULT, 0),
768             )
769         );
770     }
772     /**
773      * Returns a list of forum discussions optionally sorted and paginated.
774      *
775      * @param int $forumid the forum instance id
776      * @param int $sortorder The sort order
777      * @param int $page page number
778      * @param int $perpage items per page
779      * @param int $groupid the user course group
780      *
781      *
782      * @return array the forum discussion details including warnings
783      * @since Moodle 3.7
784      */
785     public static function get_forum_discussions(int $forumid, ?int $sortorder = -1, ?int $page = -1,
786             ?int $perpage = 0, ?int $groupid = 0) {
788         global $CFG, $DB, $USER;
790         require_once($CFG->dirroot . "/mod/forum/lib.php");
792         $warnings = array();
793         $discussions = array();
795         $params = self::validate_parameters(self::get_forum_discussions_parameters(),
796             array(
797                 'forumid' => $forumid,
798                 'sortorder' => $sortorder,
799                 'page' => $page,
800                 'perpage' => $perpage,
801                 'groupid' => $groupid
802             )
803         );
805         // Compact/extract functions are not recommended.
806         $forumid        = $params['forumid'];
807         $sortorder      = $params['sortorder'];
808         $page           = $params['page'];
809         $perpage        = $params['perpage'];
810         $groupid        = $params['groupid'];
812         $vaultfactory = \mod_forum\local\container::get_vault_factory();
813         $discussionlistvault = $vaultfactory->get_discussions_in_forum_vault();
815         $sortallowedvalues = array(
816             $discussionlistvault::SORTORDER_LASTPOST_DESC,
817             $discussionlistvault::SORTORDER_LASTPOST_ASC,
818             $discussionlistvault::SORTORDER_CREATED_DESC,
819             $discussionlistvault::SORTORDER_CREATED_ASC,
820             $discussionlistvault::SORTORDER_REPLIES_DESC,
821             $discussionlistvault::SORTORDER_REPLIES_ASC
822         );
824         // If sortorder not defined set a default one.
825         if ($sortorder == -1) {
826             $sortorder = $discussionlistvault::SORTORDER_LASTPOST_DESC;
827         }
829         if (!in_array($sortorder, $sortallowedvalues)) {
830             throw new invalid_parameter_exception('Invalid value for sortorder parameter (value: ' . $sortorder . '),' .
831                 ' allowed values are: ' . implode(',', $sortallowedvalues));
832         }
834         $managerfactory = \mod_forum\local\container::get_manager_factory();
835         $urlfactory = \mod_forum\local\container::get_url_factory();
836         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
838         $forumvault = $vaultfactory->get_forum_vault();
839         $forum = $forumvault->get_from_id($forumid);
840         if (!$forum) {
841             throw new \moodle_exception("Unable to find forum with id {$forumid}");
842         }
843         $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
844         $forumrecord = $forumdatamapper->to_legacy_object($forum);
846         $capabilitymanager = $managerfactory->get_capability_manager($forum);
848         $course = $DB->get_record('course', array('id' => $forum->get_course_id()), '*', MUST_EXIST);
849         $cm = get_coursemodule_from_instance('forum', $forum->get_id(), $course->id, false, MUST_EXIST);
851         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
852         $modcontext = context_module::instance($cm->id);
853         self::validate_context($modcontext);
855         $canseeanyprivatereply = $capabilitymanager->can_view_any_private_reply($USER);
857         // Check they have the view forum capability.
858         if (!$capabilitymanager->can_view_discussions($USER)) {
859             throw new moodle_exception('noviewdiscussionspermission', 'forum');
860         }
862         $alldiscussions = mod_forum_get_discussion_summaries($forum, $USER, $groupid, $sortorder, $page, $perpage);
864         if ($alldiscussions) {
865             $discussionids = array_keys($alldiscussions);
867             $postvault = $vaultfactory->get_post_vault();
868             $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
869             // Return the reply count for each discussion in a given forum.
870             $replies = $postvault->get_reply_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
871             // Return the first post for each discussion in a given forum.
872             $firstposts = $postvault->get_first_post_for_discussion_ids($discussionids);
874             // Get the unreads array, this takes a forum id and returns data for all discussions.
875             $unreads = array();
876             if ($cantrack = forum_tp_can_track_forums($forumrecord)) {
877                 if ($forumtracked = forum_tp_is_tracked($forumrecord)) {
878                     $unreads = $postvault->get_unread_count_for_discussion_ids($USER, $discussionids, $canseeanyprivatereply);
879                 }
880             }
882             $canlock = $capabilitymanager->can_manage_forum($USER);
884             $usercontext = context_user::instance($USER->id);
885             $ufservice = core_favourites\service_factory::get_service_for_user_context($usercontext);
887             $canfavourite = has_capability('mod/forum:cantogglefavourite', $modcontext, $USER);
889             foreach ($alldiscussions as $discussionsummary) {
890                 $discussion = $discussionsummary->get_discussion();
891                 $firstpostauthor = $discussionsummary->get_first_post_author();
892                 $latestpostauthor = $discussionsummary->get_latest_post_author();
894                 // This function checks for qanda forums.
895                 $canviewdiscussion = $capabilitymanager->can_view_discussion($USER, $discussion);
896                 if (!$canviewdiscussion) {
897                     $warning = array();
898                     // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
899                     $warning['item'] = 'post';
900                     $warning['itemid'] = $discussion->get_id();
901                     $warning['warningcode'] = '1';
902                     $warning['message'] = 'You can\'t see this discussion';
903                     $warnings[] = $warning;
904                     continue;
905                 }
907                 $firstpost = $firstposts[$discussion->get_first_post_id()];
908                 $discussionobject = $postdatamapper->to_legacy_object($firstpost);
909                 // Fix up the types for these properties.
910                 $discussionobject->mailed = $discussionobject->mailed ? 1 : 0;
911                 $discussionobject->messagetrust = $discussionobject->messagetrust ? 1 : 0;
912                 $discussionobject->mailnow = $discussionobject->mailnow ? 1 : 0;
913                 $discussionobject->groupid = $discussion->get_group_id();
914                 $discussionobject->timemodified = $discussion->get_time_modified();
915                 $discussionobject->usermodified = $discussion->get_user_modified();
916                 $discussionobject->timestart = $discussion->get_time_start();
917                 $discussionobject->timeend = $discussion->get_time_end();
918                 $discussionobject->pinned = $discussion->is_pinned();
920                 $discussionobject->numunread = 0;
921                 if ($cantrack && $forumtracked) {
922                     if (isset($unreads[$discussion->get_id()])) {
923                         $discussionobject->numunread = (int) $unreads[$discussion->get_id()];
924                     }
925                 }
927                 $discussionobject->numreplies = 0;
928                 if (!empty($replies[$discussion->get_id()])) {
929                     $discussionobject->numreplies = (int) $replies[$discussion->get_id()];
930                 }
932                 $discussionobject->name = external_format_string($discussion->get_name(), $modcontext->id);
933                 $discussionobject->subject = external_format_string($discussionobject->subject, $modcontext->id);
934                 // Rewrite embedded images URLs.
935                 $options = array('trusted' => $discussionobject->messagetrust);
936                 list($discussionobject->message, $discussionobject->messageformat) =
937                     external_format_text($discussionobject->message, $discussionobject->messageformat,
938                         $modcontext->id, 'mod_forum', 'post', $discussionobject->id, $options);
940                 // List attachments.
941                 if (!empty($discussionobject->attachment)) {
942                     $discussionobject->attachments = external_util::get_area_files($modcontext->id, 'mod_forum',
943                         'attachment', $discussionobject->id);
944                 }
945                 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post',
946                     $discussionobject->id);
947                 if (!empty($messageinlinefiles)) {
948                     $discussionobject->messageinlinefiles = $messageinlinefiles;
949                 }
951                 $discussionobject->locked = $forum->is_discussion_locked($discussion);
952                 $discussionobject->canlock = $canlock;
953                 $discussionobject->starred = !empty($ufservice) ? $ufservice->favourite_exists('mod_forum', 'discussions',
954                     $discussion->get_id(), $modcontext) : false;
955                 $discussionobject->canreply = $capabilitymanager->can_post_in_discussion($USER, $discussion);
956                 $discussionobject->canfavourite = $canfavourite;
958                 if (forum_is_author_hidden($discussionobject, $forumrecord)) {
959                     $discussionobject->userid = null;
960                     $discussionobject->userfullname = null;
961                     $discussionobject->userpictureurl = null;
963                     $discussionobject->usermodified = null;
964                     $discussionobject->usermodifiedfullname = null;
965                     $discussionobject->usermodifiedpictureurl = null;
967                 } else {
968                     $discussionobject->userfullname = $firstpostauthor->get_full_name();
969                     $discussionobject->userpictureurl = $urlfactory->get_author_profile_image_url($firstpostauthor, null, 2)
970                         ->out(false);
972                     $discussionobject->usermodifiedfullname = $latestpostauthor->get_full_name();
973                     $discussionobject->usermodifiedpictureurl = $urlfactory->get_author_profile_image_url(
974                         $latestpostauthor, null, 2)->out(false);
975                 }
977                 $discussions[] = (array) $discussionobject;
978             }
979         }
980         $result = array();
981         $result['discussions'] = $discussions;
982         $result['warnings'] = $warnings;
984         return $result;
985     }
987     /**
988      * Describes the get_forum_discussions return value.
989      *
990      * @return external_single_structure
991      * @since Moodle 3.7
992      */
993     public static function get_forum_discussions_returns() {
994         return new external_single_structure(
995             array(
996                 'discussions' => new external_multiple_structure(
997                     new external_single_structure(
998                         array(
999                             'id' => new external_value(PARAM_INT, 'Post id'),
1000                             'name' => new external_value(PARAM_TEXT, 'Discussion name'),
1001                             'groupid' => new external_value(PARAM_INT, 'Group id'),
1002                             'timemodified' => new external_value(PARAM_INT, 'Time modified'),
1003                             'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
1004                             'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
1005                             'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
1006                             'discussion' => new external_value(PARAM_INT, 'Discussion id'),
1007                             'parent' => new external_value(PARAM_INT, 'Parent id'),
1008                             'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
1009                             'created' => new external_value(PARAM_INT, 'Creation time'),
1010                             'modified' => new external_value(PARAM_INT, 'Time modified'),
1011                             'mailed' => new external_value(PARAM_INT, 'Mailed?'),
1012                             'subject' => new external_value(PARAM_TEXT, 'The post subject'),
1013                             'message' => new external_value(PARAM_RAW, 'The post message'),
1014                             'messageformat' => new external_format_value('message'),
1015                             'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
1016                             'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
1017                             'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
1018                             'attachments' => new external_files('attachments', VALUE_OPTIONAL),
1019                             'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
1020                             'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
1021                             'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
1022                             'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
1023                             'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
1024                             'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
1025                             'numreplies' => new external_value(PARAM_INT, 'The number of replies in the discussion'),
1026                             'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
1027                             'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
1028                             'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
1029                             'starred' => new external_value(PARAM_BOOL, 'Is the discussion starred'),
1030                             'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
1031                             'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
1032                             'canfavourite' => new external_value(PARAM_BOOL, 'Can the user star the discussion'),
1033                         ), 'post'
1034                     )
1035                 ),
1036                 'warnings' => new external_warnings()
1037             )
1038         );
1039     }
1041     /**
1042      * Returns description of method parameters
1043      *
1044      * @return external_function_parameters
1045      * @since Moodle 2.9
1046      */
1047     public static function view_forum_parameters() {
1048         return new external_function_parameters(
1049             array(
1050                 'forumid' => new external_value(PARAM_INT, 'forum instance id')
1051             )
1052         );
1053     }
1055     /**
1056      * Trigger the course module viewed event and update the module completion status.
1057      *
1058      * @param int $forumid the forum instance id
1059      * @return array of warnings and status result
1060      * @since Moodle 2.9
1061      * @throws moodle_exception
1062      */
1063     public static function view_forum($forumid) {
1064         global $DB, $CFG;
1065         require_once($CFG->dirroot . "/mod/forum/lib.php");
1067         $params = self::validate_parameters(self::view_forum_parameters(),
1068                                             array(
1069                                                 'forumid' => $forumid
1070                                             ));
1071         $warnings = array();
1073         // Request and permission validation.
1074         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1075         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1077         $context = context_module::instance($cm->id);
1078         self::validate_context($context);
1080         require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
1082         // Call the forum/lib API.
1083         forum_view($forum, $course, $cm, $context);
1085         $result = array();
1086         $result['status'] = true;
1087         $result['warnings'] = $warnings;
1088         return $result;
1089     }
1091     /**
1092      * Returns description of method result value
1093      *
1094      * @return external_description
1095      * @since Moodle 2.9
1096      */
1097     public static function view_forum_returns() {
1098         return new external_single_structure(
1099             array(
1100                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1101                 'warnings' => new external_warnings()
1102             )
1103         );
1104     }
1106     /**
1107      * Returns description of method parameters
1108      *
1109      * @return external_function_parameters
1110      * @since Moodle 2.9
1111      */
1112     public static function view_forum_discussion_parameters() {
1113         return new external_function_parameters(
1114             array(
1115                 'discussionid' => new external_value(PARAM_INT, 'discussion id')
1116             )
1117         );
1118     }
1120     /**
1121      * Trigger the discussion viewed event.
1122      *
1123      * @param int $discussionid the discussion id
1124      * @return array of warnings and status result
1125      * @since Moodle 2.9
1126      * @throws moodle_exception
1127      */
1128     public static function view_forum_discussion($discussionid) {
1129         global $DB, $CFG, $USER;
1130         require_once($CFG->dirroot . "/mod/forum/lib.php");
1132         $params = self::validate_parameters(self::view_forum_discussion_parameters(),
1133                                             array(
1134                                                 'discussionid' => $discussionid
1135                                             ));
1136         $warnings = array();
1138         $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
1139         $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
1140         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1142         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
1143         $modcontext = context_module::instance($cm->id);
1144         self::validate_context($modcontext);
1146         require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
1148         // Call the forum/lib API.
1149         forum_discussion_view($modcontext, $forum, $discussion);
1151         // Mark as read if required.
1152         if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
1153             forum_tp_mark_discussion_read($USER, $discussion->id);
1154         }
1156         $result = array();
1157         $result['status'] = true;
1158         $result['warnings'] = $warnings;
1159         return $result;
1160     }
1162     /**
1163      * Returns description of method result value
1164      *
1165      * @return external_description
1166      * @since Moodle 2.9
1167      */
1168     public static function view_forum_discussion_returns() {
1169         return new external_single_structure(
1170             array(
1171                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
1172                 'warnings' => new external_warnings()
1173             )
1174         );
1175     }
1177     /**
1178      * Returns description of method parameters
1179      *
1180      * @return external_function_parameters
1181      * @since Moodle 3.0
1182      */
1183     public static function add_discussion_post_parameters() {
1184         return new external_function_parameters(
1185             array(
1186                 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
1187                                                 (can be the initial discussion post'),
1188                 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
1189                 'message' => new external_value(PARAM_RAW, 'new post message (html assumed if messageformat is not provided)'),
1190                 'options' => new external_multiple_structure (
1191                     new external_single_structure(
1192                         array(
1193                             'name' => new external_value(PARAM_ALPHANUM,
1194                                         'The allowed keys (value format) are:
1195                                         discussionsubscribe (bool); subscribe to the discussion?, default to true
1196                                         private (bool); make this reply private to the author of the parent post, default to false.
1197                                         inlineattachmentsid              (int); the draft file area id for inline attachments
1198                                         attachmentsid       (int); the draft file area id for attachments
1199                                         topreferredformat (bool); convert the message & messageformat to FORMAT_HTML, defaults to false
1200                             '),
1201                             'value' => new external_value(PARAM_RAW, 'the value of the option,
1202                                                             this param is validated in the external function.'
1203                         )
1204                     )
1205                 ), 'Options', VALUE_DEFAULT, array()),
1206                 'messageformat' => new external_format_value('message', VALUE_DEFAULT)
1207             )
1208         );
1209     }
1211     /**
1212      * Create new posts into an existing discussion.
1213      *
1214      * @param int $postid the post id we are going to reply to
1215      * @param string $subject new post subject
1216      * @param string $message new post message (html assumed if messageformat is not provided)
1217      * @param array $options optional settings
1218      * @param string $messageformat The format of the message, defaults to FORMAT_HTML for BC
1219      * @return array of warnings and the new post id
1220      * @since Moodle 3.0
1221      * @throws moodle_exception
1222      */
1223     public static function add_discussion_post($postid, $subject, $message, $options = array(), $messageformat = FORMAT_HTML) {
1224         global $CFG, $USER;
1225         require_once($CFG->dirroot . "/mod/forum/lib.php");
1227         // Get all the factories that are required.
1228         $vaultfactory = mod_forum\local\container::get_vault_factory();
1229         $entityfactory = mod_forum\local\container::get_entity_factory();
1230         $datamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1231         $managerfactory = mod_forum\local\container::get_manager_factory();
1232         $discussionvault = $vaultfactory->get_discussion_vault();
1233         $forumvault = $vaultfactory->get_forum_vault();
1234         $discussiondatamapper = $datamapperfactory->get_discussion_data_mapper();
1235         $forumdatamapper = $datamapperfactory->get_forum_data_mapper();
1237         $params = self::validate_parameters(self::add_discussion_post_parameters(),
1238             array(
1239                 'postid' => $postid,
1240                 'subject' => $subject,
1241                 'message' => $message,
1242                 'options' => $options,
1243                 'messageformat' => $messageformat,
1244             )
1245         );
1247         $warnings = array();
1249         if (!$parent = forum_get_post_full($params['postid'])) {
1250             throw new moodle_exception('invalidparentpostid', 'forum');
1251         }
1253         if (!$discussion = $discussionvault->get_from_id($parent->discussion)) {
1254             throw new moodle_exception('notpartofdiscussion', 'forum');
1255         }
1257         // Request and permission validation.
1258         $forum = $forumvault->get_from_id($discussion->get_forum_id());
1259         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1260         $course = $forum->get_course_record();
1261         $cm = $forum->get_course_module_record();
1263         $discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
1264         $forumrecord = $forumdatamapper->to_legacy_object($forum);
1265         $context = context_module::instance($cm->id);
1266         self::validate_context($context);
1268         $coursecontext = \context_course::instance($forum->get_course_id());
1269         $discussionsubscribe = \mod_forum\subscriptions::get_user_default_subscription($forumrecord, $coursecontext,
1270             $cm, null);
1272         // Validate options.
1273         $options = array(
1274             'discussionsubscribe' => $discussionsubscribe,
1275             'private'             => false,
1276             'inlineattachmentsid' => 0,
1277             'attachmentsid' => null,
1278             'topreferredformat'   => false
1279         );
1280         foreach ($params['options'] as $option) {
1281             $name = trim($option['name']);
1282             switch ($name) {
1283                 case 'discussionsubscribe':
1284                     $value = clean_param($option['value'], PARAM_BOOL);
1285                     break;
1286                 case 'private':
1287                     $value = clean_param($option['value'], PARAM_BOOL);
1288                     break;
1289                 case 'inlineattachmentsid':
1290                     $value = clean_param($option['value'], PARAM_INT);
1291                     break;
1292                 case 'attachmentsid':
1293                     $value = clean_param($option['value'], PARAM_INT);
1294                     // Ensure that the user has permissions to create attachments.
1295                     if (!has_capability('mod/forum:createattachment', $context)) {
1296                         $value = 0;
1297                     }
1298                     break;
1299                 case 'topreferredformat':
1300                     $value = clean_param($option['value'], PARAM_BOOL);
1301                     break;
1302                 default:
1303                     throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1304             }
1305             $options[$name] = $value;
1306         }
1308         if (!$capabilitymanager->can_post_in_discussion($USER, $discussion)) {
1309             throw new moodle_exception('nopostforum', 'forum');
1310         }
1312         $thresholdwarning = forum_check_throttling($forumrecord, $cm);
1313         forum_check_blocking_threshold($thresholdwarning);
1315         // If we want to force a conversion to the preferred format, let's do it now.
1316         if ($options['topreferredformat']) {
1317             // We always are going to honor the preferred format. We are creating a new post.
1318             $preferredformat = editors_get_preferred_format();
1319             // If the post is not HTML and the preferred format is HTML, convert to it.
1320             if ($params['messageformat'] != FORMAT_HTML and $preferredformat == FORMAT_HTML) {
1321                 $params['message'] = format_text($params['message'], $params['messageformat'], ['context' => $context]);
1322             }
1323             $params['messageformat'] = $preferredformat;
1324         }
1326         // Create the post.
1327         $post = new stdClass();
1328         $post->discussion = $discussion->get_id();
1329         $post->parent = $parent->id;
1330         $post->subject = $params['subject'];
1331         $post->message = $params['message'];
1332         $post->messageformat = $params['messageformat'];
1333         $post->messagetrust = trusttext_trusted($context);
1334         $post->itemid = $options['inlineattachmentsid'];
1335         $post->attachments = $options['attachmentsid'];
1336         $post->isprivatereply = $options['private'];
1337         $post->deleted = 0;
1338         $fakemform = $post->attachments;
1339         if ($postid = forum_add_new_post($post, $fakemform)) {
1341             $post->id = $postid;
1343             // Trigger events and completion.
1344             $params = array(
1345                 'context' => $context,
1346                 'objectid' => $post->id,
1347                 'other' => array(
1348                     'discussionid' => $discussion->get_id(),
1349                     'forumid' => $forum->get_id(),
1350                     'forumtype' => $forum->get_type(),
1351                 )
1352             );
1353             $event = \mod_forum\event\post_created::create($params);
1354             $event->add_record_snapshot('forum_posts', $post);
1355             $event->add_record_snapshot('forum_discussions', $discussionrecord);
1356             $event->trigger();
1358             // Update completion state.
1359             $completion = new completion_info($course);
1360             if ($completion->is_enabled($cm) &&
1361                     ($forum->get_completion_replies() || $forum->get_completion_posts())) {
1362                 $completion->update_state($cm, COMPLETION_COMPLETE);
1363             }
1365             if ($options['discussionsubscribe']) {
1366                 $settings = new stdClass();
1367                 $settings->discussionsubscribe = $options['discussionsubscribe'];
1368                 forum_post_subscription($settings, $forumrecord, $discussionrecord);
1369             }
1370         } else {
1371             throw new moodle_exception('couldnotadd', 'forum');
1372         }
1374         $builderfactory = \mod_forum\local\container::get_builder_factory();
1375         $exportedpostsbuilder = $builderfactory->get_exported_posts_builder();
1376         $postentity = $entityfactory->get_post_from_stdClass($post);
1377         $exportedposts = $exportedpostsbuilder->build($USER, [$forum], [$discussion], [$postentity]);
1378         $exportedpost = $exportedposts[0];
1380         $message = [];
1381         $message[] = [
1382             'type' => 'success',
1383             'message' => get_string("postaddedsuccess", "forum")
1384         ];
1386         $message[] = [
1387             'type' => 'success',
1388             'message' => get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime))
1389         ];
1391         $result = array();
1392         $result['postid'] = $postid;
1393         $result['warnings'] = $warnings;
1394         $result['post'] = $exportedpost;
1395         $result['messages'] = $message;
1396         return $result;
1397     }
1399     /**
1400      * Returns description of method result value
1401      *
1402      * @return external_description
1403      * @since Moodle 3.0
1404      */
1405     public static function add_discussion_post_returns() {
1406         return new external_single_structure(
1407             array(
1408                 'postid' => new external_value(PARAM_INT, 'new post id'),
1409                 'warnings' => new external_warnings(),
1410                 'post' => post_exporter::get_read_structure(),
1411                 'messages' => new external_multiple_structure(
1412                     new external_single_structure(
1413                         array(
1414                             'type' => new external_value(PARAM_TEXT, "The classification to be used in the client side", VALUE_REQUIRED),
1415                             'message' => new external_value(PARAM_TEXT,'untranslated english message to explain the warning', VALUE_REQUIRED)
1416                         ), 'Messages'), 'list of warnings', VALUE_OPTIONAL
1417                 ),
1418                 //'alertmessage' => new external_value(PARAM_RAW, 'Success message to be displayed to the user.'),
1419             )
1420         );
1421     }
1423     /**
1424      * Toggle the favouriting value for the discussion provided
1425      *
1426      * @param int $discussionid The discussion we need to favourite
1427      * @param bool $targetstate The state of the favourite value
1428      * @return array The exported discussion
1429      */
1430     public static function toggle_favourite_state($discussionid, $targetstate) {
1431         global $DB, $PAGE, $USER;
1433         $params = self::validate_parameters(self::toggle_favourite_state_parameters(), [
1434             'discussionid' => $discussionid,
1435             'targetstate' => $targetstate
1436         ]);
1438         $vaultfactory = mod_forum\local\container::get_vault_factory();
1439         // Get the discussion vault and the corresponding discussion entity.
1440         $discussionvault = $vaultfactory->get_discussion_vault();
1441         $discussion = $discussionvault->get_from_id($params['discussionid']);
1443         $forumvault = $vaultfactory->get_forum_vault();
1444         $forum = $forumvault->get_from_id($discussion->get_forum_id());
1445         $forumcontext = $forum->get_context();
1446         self::validate_context($forumcontext);
1448         $managerfactory = mod_forum\local\container::get_manager_factory();
1449         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1451         // Does the user have the ability to favourite the discussion?
1452         if (!$capabilitymanager->can_favourite_discussion($USER)) {
1453             throw new moodle_exception('cannotfavourite', 'forum');
1454         }
1455         $usercontext = context_user::instance($USER->id);
1456         $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1457         $isfavourited = $ufservice->favourite_exists('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1459         $favouritefunction = $targetstate ? 'create_favourite' : 'delete_favourite';
1460         if ($isfavourited != (bool) $params['targetstate']) {
1461             $ufservice->{$favouritefunction}('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1462         }
1464         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1465         $builder = mod_forum\local\container::get_builder_factory()->get_exported_discussion_builder();
1466         $favourited = ($builder->is_favourited($discussion, $forumcontext, $USER) ? [$discussion->get_id()] : []);
1467         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion, [], $favourited);
1468         return $exporter->export($PAGE->get_renderer('mod_forum'));
1469     }
1471     /**
1472      * Returns description of method result value
1473      *
1474      * @return external_description
1475      * @since Moodle 3.0
1476      */
1477     public static function toggle_favourite_state_returns() {
1478         return discussion_exporter::get_read_structure();
1479     }
1481     /**
1482      * Defines the parameters for the toggle_favourite_state method
1483      *
1484      * @return external_function_parameters
1485      */
1486     public static function toggle_favourite_state_parameters() {
1487         return new external_function_parameters(
1488             [
1489                 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1490                 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1491             ]
1492         );
1493     }
1495     /**
1496      * Returns description of method parameters
1497      *
1498      * @return external_function_parameters
1499      * @since Moodle 3.0
1500      */
1501     public static function add_discussion_parameters() {
1502         return new external_function_parameters(
1503             array(
1504                 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1505                 'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
1506                 'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
1507                 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
1508                 'options' => new external_multiple_structure (
1509                     new external_single_structure(
1510                         array(
1511                             'name' => new external_value(PARAM_ALPHANUM,
1512                                         'The allowed keys (value format) are:
1513                                         discussionsubscribe (bool); subscribe to the discussion?, default to true
1514                                         discussionpinned    (bool); is the discussion pinned, default to false
1515                                         inlineattachmentsid              (int); the draft file area id for inline attachments
1516                                         attachmentsid       (int); the draft file area id for attachments
1517                             '),
1518                             'value' => new external_value(PARAM_RAW, 'The value of the option,
1519                                                             This param is validated in the external function.'
1520                         )
1521                     )
1522                 ), 'Options', VALUE_DEFAULT, array())
1523             )
1524         );
1525     }
1527     /**
1528      * Add a new discussion into an existing forum.
1529      *
1530      * @param int $forumid the forum instance id
1531      * @param string $subject new discussion subject
1532      * @param string $message new discussion message (only html format allowed)
1533      * @param int $groupid the user course group
1534      * @param array $options optional settings
1535      * @return array of warnings and the new discussion id
1536      * @since Moodle 3.0
1537      * @throws moodle_exception
1538      */
1539     public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
1540         global $DB, $CFG;
1541         require_once($CFG->dirroot . "/mod/forum/lib.php");
1543         $params = self::validate_parameters(self::add_discussion_parameters(),
1544                                             array(
1545                                                 'forumid' => $forumid,
1546                                                 'subject' => $subject,
1547                                                 'message' => $message,
1548                                                 'groupid' => $groupid,
1549                                                 'options' => $options
1550                                             ));
1552         $warnings = array();
1554         // Request and permission validation.
1555         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1556         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1558         $context = context_module::instance($cm->id);
1559         self::validate_context($context);
1561         // Validate options.
1562         $options = array(
1563             'discussionsubscribe' => true,
1564             'discussionpinned' => false,
1565             'inlineattachmentsid' => 0,
1566             'attachmentsid' => null
1567         );
1568         foreach ($params['options'] as $option) {
1569             $name = trim($option['name']);
1570             switch ($name) {
1571                 case 'discussionsubscribe':
1572                     $value = clean_param($option['value'], PARAM_BOOL);
1573                     break;
1574                 case 'discussionpinned':
1575                     $value = clean_param($option['value'], PARAM_BOOL);
1576                     break;
1577                 case 'inlineattachmentsid':
1578                     $value = clean_param($option['value'], PARAM_INT);
1579                     break;
1580                 case 'attachmentsid':
1581                     $value = clean_param($option['value'], PARAM_INT);
1582                     // Ensure that the user has permissions to create attachments.
1583                     if (!has_capability('mod/forum:createattachment', $context)) {
1584                         $value = 0;
1585                     }
1586                     break;
1587                 default:
1588                     throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1589             }
1590             $options[$name] = $value;
1591         }
1593         // Normalize group.
1594         if (!groups_get_activity_groupmode($cm)) {
1595             // Groups not supported, force to -1.
1596             $groupid = -1;
1597         } else {
1598             // Check if we receive the default or and empty value for groupid,
1599             // in this case, get the group for the user in the activity.
1600             if (empty($params['groupid'])) {
1601                 $groupid = groups_get_activity_group($cm);
1602             } else {
1603                 // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
1604                 $groupid = $params['groupid'];
1605             }
1606         }
1608         if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
1609             throw new moodle_exception('cannotcreatediscussion', 'forum');
1610         }
1612         $thresholdwarning = forum_check_throttling($forum, $cm);
1613         forum_check_blocking_threshold($thresholdwarning);
1615         // Create the discussion.
1616         $discussion = new stdClass();
1617         $discussion->course = $course->id;
1618         $discussion->forum = $forum->id;
1619         $discussion->message = $params['message'];
1620         $discussion->messageformat = FORMAT_HTML;   // Force formatting for now.
1621         $discussion->messagetrust = trusttext_trusted($context);
1622         $discussion->itemid = $options['inlineattachmentsid'];
1623         $discussion->groupid = $groupid;
1624         $discussion->mailnow = 0;
1625         $discussion->subject = $params['subject'];
1626         $discussion->name = $discussion->subject;
1627         $discussion->timestart = 0;
1628         $discussion->timeend = 0;
1629         $discussion->timelocked = 0;
1630         $discussion->attachments = $options['attachmentsid'];
1632         if (has_capability('mod/forum:pindiscussions', $context) && $options['discussionpinned']) {
1633             $discussion->pinned = FORUM_DISCUSSION_PINNED;
1634         } else {
1635             $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
1636         }
1637         $fakemform = $options['attachmentsid'];
1638         if ($discussionid = forum_add_discussion($discussion, $fakemform)) {
1640             $discussion->id = $discussionid;
1642             // Trigger events and completion.
1644             $params = array(
1645                 'context' => $context,
1646                 'objectid' => $discussion->id,
1647                 'other' => array(
1648                     'forumid' => $forum->id,
1649                 )
1650             );
1651             $event = \mod_forum\event\discussion_created::create($params);
1652             $event->add_record_snapshot('forum_discussions', $discussion);
1653             $event->trigger();
1655             $completion = new completion_info($course);
1656             if ($completion->is_enabled($cm) &&
1657                     ($forum->completiondiscussions || $forum->completionposts)) {
1658                 $completion->update_state($cm, COMPLETION_COMPLETE);
1659             }
1661             $settings = new stdClass();
1662             $settings->discussionsubscribe = $options['discussionsubscribe'];
1663             forum_post_subscription($settings, $forum, $discussion);
1664         } else {
1665             throw new moodle_exception('couldnotadd', 'forum');
1666         }
1668         $result = array();
1669         $result['discussionid'] = $discussionid;
1670         $result['warnings'] = $warnings;
1671         return $result;
1672     }
1674     /**
1675      * Returns description of method result value
1676      *
1677      * @return external_description
1678      * @since Moodle 3.0
1679      */
1680     public static function add_discussion_returns() {
1681         return new external_single_structure(
1682             array(
1683                 'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
1684                 'warnings' => new external_warnings()
1685             )
1686         );
1687     }
1689     /**
1690      * Returns description of method parameters
1691      *
1692      * @return external_function_parameters
1693      * @since Moodle 3.1
1694      */
1695     public static function can_add_discussion_parameters() {
1696         return new external_function_parameters(
1697             array(
1698                 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1699                 'groupid' => new external_value(PARAM_INT, 'The group to check, default to active group.
1700                                                 Use -1 to check if the user can post in all the groups.', VALUE_DEFAULT, null)
1701             )
1702         );
1703     }
1705     /**
1706      * Check if the current user can add discussions in the given forum (and optionally for the given group).
1707      *
1708      * @param int $forumid the forum instance id
1709      * @param int $groupid the group to check, default to active group. Use -1 to check if the user can post in all the groups.
1710      * @return array of warnings and the status (true if the user can add discussions)
1711      * @since Moodle 3.1
1712      * @throws moodle_exception
1713      */
1714     public static function can_add_discussion($forumid, $groupid = null) {
1715         global $DB, $CFG;
1716         require_once($CFG->dirroot . "/mod/forum/lib.php");
1718         $params = self::validate_parameters(self::can_add_discussion_parameters(),
1719                                             array(
1720                                                 'forumid' => $forumid,
1721                                                 'groupid' => $groupid,
1722                                             ));
1723         $warnings = array();
1725         // Request and permission validation.
1726         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1727         list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1729         $context = context_module::instance($cm->id);
1730         self::validate_context($context);
1732         $status = forum_user_can_post_discussion($forum, $params['groupid'], -1, $cm, $context);
1734         $result = array();
1735         $result['status'] = $status;
1736         $result['canpindiscussions'] = has_capability('mod/forum:pindiscussions', $context);
1737         $result['cancreateattachment'] = forum_can_create_attachment($forum, $context);
1738         $result['warnings'] = $warnings;
1739         return $result;
1740     }
1742     /**
1743      * Returns description of method result value
1744      *
1745      * @return external_description
1746      * @since Moodle 3.1
1747      */
1748     public static function can_add_discussion_returns() {
1749         return new external_single_structure(
1750             array(
1751                 'status' => new external_value(PARAM_BOOL, 'True if the user can add discussions, false otherwise.'),
1752                 'canpindiscussions' => new external_value(PARAM_BOOL, 'True if the user can pin discussions, false otherwise.',
1753                     VALUE_OPTIONAL),
1754                 'cancreateattachment' => new external_value(PARAM_BOOL, 'True if the user can add attachments, false otherwise.',
1755                     VALUE_OPTIONAL),
1756                 'warnings' => new external_warnings()
1757             )
1758         );
1759     }
1761     /**
1762      * Describes the parameters for get_forum_access_information.
1763      *
1764      * @return external_external_function_parameters
1765      * @since Moodle 3.7
1766      */
1767     public static function get_forum_access_information_parameters() {
1768         return new external_function_parameters (
1769             array(
1770                 'forumid' => new external_value(PARAM_INT, 'Forum instance id.')
1771             )
1772         );
1773     }
1775     /**
1776      * Return access information for a given forum.
1777      *
1778      * @param int $forumid forum instance id
1779      * @return array of warnings and the access information
1780      * @since Moodle 3.7
1781      * @throws  moodle_exception
1782      */
1783     public static function get_forum_access_information($forumid) {
1784         global $DB;
1786         $params = self::validate_parameters(self::get_forum_access_information_parameters(), array('forumid' => $forumid));
1788         // Request and permission validation.
1789         $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1790         $cm = get_coursemodule_from_instance('forum', $forum->id);
1792         $context = context_module::instance($cm->id);
1793         self::validate_context($context);
1795         $result = array();
1796         // Return all the available capabilities.
1797         $capabilities = load_capability_def('mod_forum');
1798         foreach ($capabilities as $capname => $capdata) {
1799             // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1800             $field = 'can' . str_replace('mod/forum:', '', $capname);
1801             $result[$field] = has_capability($capname, $context);
1802         }
1804         $result['warnings'] = array();
1805         return $result;
1806     }
1808     /**
1809      * Describes the get_forum_access_information return value.
1810      *
1811      * @return external_single_structure
1812      * @since Moodle 3.7
1813      */
1814     public static function get_forum_access_information_returns() {
1816         $structure = array(
1817             'warnings' => new external_warnings()
1818         );
1820         $capabilities = load_capability_def('mod_forum');
1821         foreach ($capabilities as $capname => $capdata) {
1822             // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1823             $field = 'can' . str_replace('mod/forum:', '', $capname);
1824             $structure[$field] = new external_value(PARAM_BOOL, 'Whether the user has the capability ' . $capname . ' allowed.',
1825                 VALUE_OPTIONAL);
1826         }
1828         return new external_single_structure($structure);
1829     }
1831     /**
1832      * Set the subscription state.
1833      *
1834      * @param   int     $forumid
1835      * @param   int     $discussionid
1836      * @param   bool    $targetstate
1837      * @return  \stdClass
1838      */
1839     public static function set_subscription_state($forumid, $discussionid, $targetstate) {
1840         global $PAGE, $USER;
1842         $params = self::validate_parameters(self::set_subscription_state_parameters(), [
1843             'forumid' => $forumid,
1844             'discussionid' => $discussionid,
1845             'targetstate' => $targetstate
1846         ]);
1848         $vaultfactory = mod_forum\local\container::get_vault_factory();
1849         $forumvault = $vaultfactory->get_forum_vault();
1850         $forum = $forumvault->get_from_id($params['forumid']);
1851         $coursemodule = $forum->get_course_module_record();
1852         $context = $forum->get_context();
1854         self::validate_context($context);
1856         $discussionvault = $vaultfactory->get_discussion_vault();
1857         $discussion = $discussionvault->get_from_id($params['discussionid']);
1858         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1860         $forumrecord = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
1861         $discussionrecord = $legacydatamapperfactory->get_discussion_data_mapper()->to_legacy_object($discussion);
1863         if (!\mod_forum\subscriptions::is_subscribable($forumrecord)) {
1864             // Nothing to do. We won't actually output any content here though.
1865             throw new \moodle_exception('cannotsubscribe', 'mod_forum');
1866         }
1868         $issubscribed = \mod_forum\subscriptions::is_subscribed(
1869             $USER->id,
1870             $forumrecord,
1871             $discussion->get_id(),
1872             $coursemodule
1873         );
1875         // If the current state doesn't equal the desired state then update the current
1876         // state to the desired state.
1877         if ($issubscribed != (bool) $params['targetstate']) {
1878             if ($params['targetstate']) {
1879                 \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussionrecord, $context);
1880             } else {
1881                 \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussionrecord, $context);
1882             }
1883         }
1885         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1886         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1887         return $exporter->export($PAGE->get_renderer('mod_forum'));
1888     }
1890     /**
1891      * Returns description of method parameters.
1892      *
1893      * @return external_function_parameters
1894      */
1895     public static function set_subscription_state_parameters() {
1896         return new external_function_parameters(
1897             [
1898                 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1899                 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1900                 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1901             ]
1902         );
1903     }
1905     /**
1906      * Returns description of method result value.
1907      *
1908      * @return external_description
1909      */
1910     public static function set_subscription_state_returns() {
1911         return discussion_exporter::get_read_structure();
1912     }
1914     /**
1915      * Set the lock state.
1916      *
1917      * @param   int     $forumid
1918      * @param   int     $discussionid
1919      * @param   string    $targetstate
1920      * @return  \stdClass
1921      */
1922     public static function set_lock_state($forumid, $discussionid, $targetstate) {
1923         global $DB, $PAGE, $USER;
1925         $params = self::validate_parameters(self::set_lock_state_parameters(), [
1926             'forumid' => $forumid,
1927             'discussionid' => $discussionid,
1928             'targetstate' => $targetstate
1929         ]);
1931         $vaultfactory = mod_forum\local\container::get_vault_factory();
1932         $forumvault = $vaultfactory->get_forum_vault();
1933         $forum = $forumvault->get_from_id($params['forumid']);
1935         $managerfactory = mod_forum\local\container::get_manager_factory();
1936         $capabilitymanager = $managerfactory->get_capability_manager($forum);
1937         if (!$capabilitymanager->can_manage_forum($USER)) {
1938             throw new moodle_exception('errorcannotlock', 'forum');
1939         }
1941         // If the targetstate(currentstate) is not 0 then it should be set to the current time.
1942         $lockedvalue = $targetstate ? 0 : time();
1943         self::validate_context($forum->get_context());
1945         $discussionvault = $vaultfactory->get_discussion_vault();
1946         $discussion = $discussionvault->get_from_id($params['discussionid']);
1948         // If the current state doesn't equal the desired state then update the current.
1949         // state to the desired state.
1950         $discussion->toggle_locked_state($lockedvalue);
1951         $response = $discussionvault->update_discussion($discussion);
1952         $discussion = !$response ? $response : $discussion;
1953         $exporterfactory = mod_forum\local\container::get_exporter_factory();
1954         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1955         return $exporter->export($PAGE->get_renderer('mod_forum'));
1956     }
1958     /**
1959      * Returns description of method parameters.
1960      *
1961      * @return external_function_parameters
1962      */
1963     public static function set_lock_state_parameters() {
1964         return new external_function_parameters(
1965             [
1966                 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1967                 'discussionid' => new external_value(PARAM_INT, 'The discussion to lock / unlock'),
1968                 'targetstate' => new external_value(PARAM_INT, 'The timestamp for the lock state')
1969             ]
1970         );
1971     }
1973     /**
1974      * Returns description of method result value.
1975      *
1976      * @return external_description
1977      */
1978     public static function set_lock_state_returns() {
1979         return new external_single_structure([
1980             'id' => new external_value(PARAM_INT, 'The discussion we are locking.'),
1981             'locked' => new external_value(PARAM_BOOL, 'The locked state of the discussion.'),
1982             'times' => new external_single_structure([
1983                 'locked' => new external_value(PARAM_INT, 'The locked time of the discussion.'),
1984             ])
1985         ]);
1986     }
1988     /**
1989      * Set the pin state.
1990      *
1991      * @param   int     $discussionid
1992      * @param   bool    $targetstate
1993      * @return  \stdClass
1994      */
1995     public static function set_pin_state($discussionid, $targetstate) {
1996         global $PAGE, $USER;
1997         $params = self::validate_parameters(self::set_pin_state_parameters(), [
1998             'discussionid' => $discussionid,
1999             'targetstate' => $targetstate,
2000         ]);
2001         $vaultfactory = mod_forum\local\container::get_vault_factory();
2002         $managerfactory = mod_forum\local\container::get_manager_factory();
2003         $forumvault = $vaultfactory->get_forum_vault();
2004         $discussionvault = $vaultfactory->get_discussion_vault();
2005         $discussion = $discussionvault->get_from_id($params['discussionid']);
2006         $forum = $forumvault->get_from_id($discussion->get_forum_id());
2007         $capabilitymanager = $managerfactory->get_capability_manager($forum);
2009         self::validate_context($forum->get_context());
2011         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
2012         if (!$capabilitymanager->can_pin_discussions($USER)) {
2013             // Nothing to do. We won't actually output any content here though.
2014             throw new \moodle_exception('cannotpindiscussions', 'mod_forum');
2015         }
2017         $discussion->set_pinned($targetstate);
2018         $discussionvault->update_discussion($discussion);
2020         $exporterfactory = mod_forum\local\container::get_exporter_factory();
2021         $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
2022         return $exporter->export($PAGE->get_renderer('mod_forum'));
2023     }
2025     /**
2026      * Returns description of method parameters.
2027      *
2028      * @return external_function_parameters
2029      */
2030     public static function set_pin_state_parameters() {
2031         return new external_function_parameters(
2032             [
2033                 'discussionid' => new external_value(PARAM_INT, 'The discussion to pin or unpin', VALUE_REQUIRED,
2034                     null, NULL_NOT_ALLOWED),
2035                 'targetstate' => new external_value(PARAM_INT, 'The target state', VALUE_REQUIRED,
2036                     null, NULL_NOT_ALLOWED),
2037             ]
2038         );
2039     }
2041     /**
2042      * Returns description of method result value.
2043      *
2044      * @return external_single_structure
2045      */
2046     public static function set_pin_state_returns() {
2047         return discussion_exporter::get_read_structure();
2048     }
2050     /**
2051      * Returns description of method parameters
2052      *
2053      * @return external_function_parameters
2054      * @since Moodle 3.8
2055      */
2056     public static function delete_post_parameters() {
2057         return new external_function_parameters(
2058             array(
2059                 'postid' => new external_value(PARAM_INT, 'Post to be deleted. It can be a discussion topic post.'),
2060             )
2061         );
2062     }
2064     /**
2065      * Deletes a post or a discussion completely when the post is the discussion topic.
2066      *
2067      * @param int $postid post to be deleted, it can be a discussion topic post.
2068      * @return array of warnings and the status (true if the post/discussion was deleted)
2069      * @since Moodle 3.8
2070      * @throws moodle_exception
2071      */
2072     public static function delete_post($postid) {
2073         global $USER, $CFG;
2074         require_once($CFG->dirroot . "/mod/forum/lib.php");
2076         $params = self::validate_parameters(self::delete_post_parameters(),
2077             array(
2078                 'postid' => $postid,
2079             )
2080         );
2081         $warnings = array();
2082         $vaultfactory = mod_forum\local\container::get_vault_factory();
2083         $forumvault = $vaultfactory->get_forum_vault();
2084         $discussionvault = $vaultfactory->get_discussion_vault();
2085         $postvault = $vaultfactory->get_post_vault();
2086         $postentity = $postvault->get_from_id($params['postid']);
2088         if (empty($postentity)) {
2089             throw new moodle_exception('invalidpostid', 'forum');
2090         }
2092         $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
2094         if (empty($discussionentity)) {
2095             throw new moodle_exception('notpartofdiscussion', 'forum');
2096         }
2098         $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
2099         if (empty($forumentity)) {
2100             throw new moodle_exception('invalidforumid', 'forum');
2101         }
2103         $context = $forumentity->get_context();
2105         self::validate_context($context);
2107         $managerfactory = mod_forum\local\container::get_manager_factory();
2108         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
2109         $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
2110         $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
2111         $discussiondatamapper = $legacydatamapperfactory->get_discussion_data_mapper();
2112         $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
2114         $replycount = $postvault->get_reply_count_for_post_id_in_discussion_id($USER, $postentity->get_id(),
2115             $discussionentity->get_id(), true);
2116         $hasreplies = $replycount > 0;
2118         $capabilitymanager->validate_delete_post($USER, $discussionentity, $postentity, $hasreplies);
2120         if (!$postentity->has_parent()) {
2121             $status = forum_delete_discussion(
2122                 $discussiondatamapper->to_legacy_object($discussionentity),
2123                 false,
2124                 $forumentity->get_course_record(),
2125                 $forumentity->get_course_module_record(),
2126                 $forumdatamapper->to_legacy_object($forumentity)
2127             );
2128         } else {
2129             $status = forum_delete_post(
2130                 $postdatamapper->to_legacy_object($postentity),
2131                 has_capability('mod/forum:deleteanypost', $context),
2132                 $forumentity->get_course_record(),
2133                 $forumentity->get_course_module_record(),
2134                 $forumdatamapper->to_legacy_object($forumentity)
2135             );
2136         }
2138         $result = array();
2139         $result['status'] = $status;
2140         $result['warnings'] = $warnings;
2141         return $result;
2142     }
2144     /**
2145      * Returns description of method result value
2146      *
2147      * @return external_description
2148      * @since Moodle 3.8
2149      */
2150     public static function delete_post_returns() {
2151         return new external_single_structure(
2152             array(
2153                 'status' => new external_value(PARAM_BOOL, 'True if the post/discussion was deleted, false otherwise.'),
2154                 'warnings' => new external_warnings()
2155             )
2156         );
2157     }
2159     /**
2160      * Get the forum posts in the specified forum instance.
2161      *
2162      * @param   int $userid
2163      * @param   int $cmid
2164      * @param   string $sortby
2165      * @param   string $sortdirection
2166      * @return  array
2167      */
2168     public static function get_discussion_posts_by_userid(int $userid = 0, int $cmid, ?string $sortby, ?string $sortdirection) {
2169         global $USER, $DB;
2170         // Validate the parameter.
2171         $params = self::validate_parameters(self::get_discussion_posts_by_userid_parameters(), [
2172                 'userid' => $userid,
2173                 'cmid' => $cmid,
2174                 'sortby' => $sortby,
2175                 'sortdirection' => $sortdirection,
2176         ]);
2177         $warnings = [];
2179         $user = core_user::get_user($params['userid']);
2181         $vaultfactory = mod_forum\local\container::get_vault_factory();
2183         $forumvault = $vaultfactory->get_forum_vault();
2184         $forum = $forumvault->get_from_course_module_id($params['cmid']);
2186         // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
2187         self::validate_context($forum->get_context());
2189         $sortby = $params['sortby'];
2190         $sortdirection = $params['sortdirection'];
2191         $sortallowedvalues = ['id', 'created', 'modified'];
2192         $directionallowedvalues = ['ASC', 'DESC'];
2194         if (!in_array(strtolower($sortby), $sortallowedvalues)) {
2195             throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
2196                     'allowed values are: ' . implode(', ', $sortallowedvalues));
2197         }
2199         $sortdirection = strtoupper($sortdirection);
2200         if (!in_array($sortdirection, $directionallowedvalues)) {
2201             throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
2202                     'allowed values are: ' . implode(',', $directionallowedvalues));
2203         }
2205         $managerfactory = mod_forum\local\container::get_manager_factory();
2206         $capabilitymanager = $managerfactory->get_capability_manager($forum);
2208         $discussionsummariesvault = $vaultfactory->get_discussions_in_forum_vault();
2209         $discussionsummaries = $discussionsummariesvault->get_from_forum_id(
2210             $forum->get_id(),
2211             true,
2212             null,
2213             $discussionsummariesvault::SORTORDER_CREATED_ASC,
2214             0,
2215             0
2216         );
2218         $postvault = $vaultfactory->get_post_vault();
2220         $builderfactory = mod_forum\local\container::get_builder_factory();
2221         $postbuilder = $builderfactory->get_exported_posts_builder();
2223         $builtdiscussions = [];
2224         foreach ($discussionsummaries as $discussionsummary) {
2225             $discussion = $discussionsummary->get_discussion();
2226             $posts = $postvault->get_posts_in_discussion_for_user_id(
2227                     $discussion->get_id(),
2228                     $user->id,
2229                     $capabilitymanager->can_view_any_private_reply($USER),
2230                     "{$sortby} {$sortdirection}"
2231             );
2232             if (empty($posts)) {
2233                 continue;
2234             }
2236             $parentids = array_filter(array_map(function($post) {
2237                 return $post->has_parent() ? $post->get_parent_id() : null;
2238             }, $posts));
2240             $parentposts = [];
2241             if ($parentids) {
2242                 $parentposts = $postbuilder->build(
2243                     $user,
2244                     [$forum],
2245                     [$discussion],
2246                     $postvault->get_from_ids(array_values($parentids))
2247                 );
2248             }
2250             $discussionauthor = $discussionsummary->get_first_post_author();
2251             $firstpost = $discussionsummary->get_first_post();
2253             $builtdiscussions[] = [
2254                 'name' => $discussion->get_name(),
2255                 'id' => $discussion->get_id(),
2256                 'timecreated' => $firstpost->get_time_created(),
2257                 'authorfullname' => $discussionauthor->get_full_name(),
2258                 'posts' => [
2259                     'userposts' => $postbuilder->build($user, [$forum], [$discussion], $posts),
2260                     'parentposts' => $parentposts,
2261                 ],
2262             ];
2263         }
2265         return [
2266                 'discussions' => $builtdiscussions,
2267                 'warnings' => $warnings,
2268         ];
2269     }
2271     /**
2272      * Describe the post parameters.
2273      *
2274      * @return external_function_parameters
2275      */
2276     public static function get_discussion_posts_by_userid_parameters() {
2277         return new external_function_parameters ([
2278                 'userid' => new external_value(
2279                         PARAM_INT, 'The ID of the user of whom to fetch posts.', VALUE_REQUIRED),
2280                 'cmid' => new external_value(
2281                         PARAM_INT, 'The ID of the module of which to fetch items.', VALUE_REQUIRED),
2282                 'sortby' => new external_value(
2283                         PARAM_ALPHA, 'Sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
2284                 'sortdirection' => new external_value(
2285                         PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
2286         ]);
2287     }
2289     /**
2290      * Describe the post return format.
2291      *
2292      * @return external_single_structure
2293      */
2294     public static function get_discussion_posts_by_userid_returns() {
2295         return new external_single_structure([
2296                 'discussions' => new external_multiple_structure(
2297                     new external_single_structure([
2298                         'name' => new external_value(PARAM_RAW, 'Name of the discussion'),
2299                         'id' => new external_value(PARAM_INT, 'ID of the discussion'),
2300                         'timecreated' => new external_value(PARAM_INT, 'Timestamp of the discussion start'),
2301                         'authorfullname' => new external_value(PARAM_RAW, 'Full name of the user that started the discussion'),
2302                         'posts' => new external_single_structure([
2303                             'userposts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
2304                             'parentposts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
2305                         ]),
2306                     ])),
2307                 'warnings' => new external_warnings(),
2308         ]);
2309     }
2311     /**
2312      * Returns description of method parameters
2313      *
2314      * @return external_function_parameters
2315      * @since Moodle 3.8
2316      */
2317     public static function get_discussion_post_parameters() {
2318         return new external_function_parameters(
2319             array(
2320                 'postid' => new external_value(PARAM_INT, 'Post to fetch.'),
2321             )
2322         );
2323     }
2325     /**
2326      * Get a particular discussion post.
2327      *
2328      * @param int $postid post to fetch
2329      * @return array of post and warnings (if any)
2330      * @since Moodle 3.8
2331      * @throws moodle_exception
2332      */
2333     public static function get_discussion_post($postid) {
2334         global $USER, $CFG;
2336         $params = self::validate_parameters(self::get_discussion_post_parameters(),
2337                                             array(
2338                                                 'postid' => $postid,
2339                                             ));
2340         $warnings = array();
2341         $vaultfactory = mod_forum\local\container::get_vault_factory();
2342         $forumvault = $vaultfactory->get_forum_vault();
2343         $discussionvault = $vaultfactory->get_discussion_vault();
2344         $postvault = $vaultfactory->get_post_vault();
2346         $postentity = $postvault->get_from_id($params['postid']);
2347         if (empty($postentity)) {
2348             throw new moodle_exception('invalidpostid', 'forum');
2349         }
2350         $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
2351         if (empty($discussionentity)) {
2352             throw new moodle_exception('notpartofdiscussion', 'forum');
2353         }
2354         $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
2355         if (empty($forumentity)) {
2356             throw new moodle_exception('invalidforumid', 'forum');
2357         }
2358         self::validate_context($forumentity->get_context());
2360         $managerfactory = mod_forum\local\container::get_manager_factory();
2361         $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
2363         if (!$capabilitymanager->can_view_post($USER, $discussionentity, $postentity)) {
2364             throw new moodle_exception('noviewdiscussionspermission', 'forum');
2365         }
2367         $builderfactory = mod_forum\local\container::get_builder_factory();
2368         $postbuilder = $builderfactory->get_exported_posts_builder();
2369         $posts = $postbuilder->build($USER, [$forumentity], [$discussionentity], [$postentity]);
2370         $post = empty($posts) ? array() : reset($posts);
2372         $result = array();
2373         $result['post'] = $post;
2374         $result['warnings'] = $warnings;
2375         return $result;
2376     }
2378     /**
2379      * Returns description of method result value
2380      *
2381      * @return external_description
2382      * @since Moodle 3.8
2383      */
2384     public static function get_discussion_post_returns() {
2385         return new external_single_structure(
2386             array(
2387                 'post' => \mod_forum\local\exporters\post::get_read_structure(),
2388                 'warnings' => new external_warnings(),
2389             )
2390         );
2391     }
2393     /**
2394      * Returns description of method parameters
2395      *
2396      * @return external_function_parameters
2397      * @since Moodle 3.8
2398      */
2399     public static function prepare_draft_area_for_post_parameters() {
2400         return new external_function_parameters(
2401             array(
2402                 'postid' => new external_value(PARAM_INT, 'Post to prepare the draft area for.'),
2403                 'area' => new external_value(PARAM_ALPHA, 'Area to prepare: attachment or post.'),
2404                 'draftitemid' => new external_value(PARAM_INT, 'The draft item id to use. 0 to generate one.',
2405                     VALUE_DEFAULT, 0),
2406                 'filestokeep' => new external_multiple_structure(
2407                     new external_single_structure(
2408                         array(
2409                             'filename' => new external_value(PARAM_FILE, 'File name.'),
2410                             'filepath' => new external_value(PARAM_PATH, 'File path.'),
2411                         )
2412                     ), 'Only keep these files in the draft file area. Empty for keeping all.', VALUE_DEFAULT, []
2413                 ),
2414             )
2415         );
2416     }
2418     /**
2419      * Prepares a draft area for editing a post.
2420      *
2421      * @param int $postid post to prepare the draft area for
2422      * @param string $area area to prepare attachment or post
2423      * @param int $draftitemid the draft item id to use. 0 to generate a new one.
2424      * @param array $filestokeep only keep these files in the draft file area. Empty for keeping all.
2425      * @return array of files in the area, the area options and the draft item id
2426      * @since Moodle 3.8
2427      * @throws moodle_exception
2428      */
2429     public static function prepare_draft_area_for_post($postid, $area, $draftitemid = 0, $filestokeep = []) {
2430         global $USER;
2432         $params = self::validate_parameters(
2433             self::prepare_draft_area_for_post_parameters(),
2434             array(
2435                 'postid' => $postid,
2436                 'area' => $area,
2437                 'draftitemid' => $draftitemid,
2438                 'filestokeep' => $filestokeep,
2439             )
2440         );
2441         $directionallowedvalues = ['ASC', 'DESC'];
2443         $allowedareas = ['attachment', 'post'];
2444         if (!in_array($params['area'], $allowedareas)) {
2445             throw new invalid_parameter_exception('Invalid value for area parameter
2446                 (value: ' . $params['area'] . '),' . 'allowed values are: ' . implode(', ', $allowedareas));
2447         }
2449         $warnings = array();
2450         $vaultfactory = mod_forum\local\container::get_vault_factory();
2451         $forumvault = $vaultfactory->get_forum_vault();
2452         $discussionvault = $vaultfactory->get_discussion_vault();
2453         $postvault = $vaultfactory->get_post_vault();
2455         $postentity = $postvault->get_from_id($params['postid']);
2456         if (empty($postentity)) {
2457             throw new moodle_exception('invalidpostid', 'forum');
2458         }
2459         $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
2460         if (empty($discussionentity)) {
2461             throw new moodle_exception('notpartofdiscussion', 'forum');
2462         }
2463         $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
2464         if (empty($forumentity)) {
2465             throw new moodle_exception('invalidforumid', 'forum');
2466         }
2468         $context = $forumentity->get_context();
2469         self::validate_context($context);
2471         $managerfactory = mod_forum\local\container::get_manager_factory();
2472         $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
2474         if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
2475             throw new moodle_exception('noviewdiscussionspermission', 'forum');
2476         }
2478         if ($params['area'] == 'attachment') {
2479             $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
2480             $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
2481             $forum = $forumdatamapper->to_legacy_object($forumentity);
2483             $areaoptions = mod_forum_post_form::attachment_options($forum);
2484             $messagetext = null;
2485         } else {
2486             $areaoptions = mod_forum_post_form::editor_options($context, $postentity->get_id());
2487             $messagetext = $postentity->get_message();
2488         }
2490         $draftitemid = empty($params['draftitemid']) ? 0 : $params['draftitemid'];
2491         $messagetext = file_prepare_draft_area($draftitemid, $context->id, 'mod_forum', $params['area'],
2492             $postentity->get_id(), $areaoptions, $messagetext);
2494         // Just get a structure compatible with external API.
2495         array_walk($areaoptions, function(&$item, $key) {
2496             $item = ['name' => $key, 'value' => $item];
2497         });
2499         // Do we need to keep only the given files?
2500         $usercontext = context_user::instance($USER->id);
2501         if (!empty($params['filestokeep'])) {
2502             $fs = get_file_storage();
2504             if ($areafiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid)) {
2505                 $filestokeep = [];
2506                 foreach ($params['filestokeep'] as $ftokeep) {
2507                     $filestokeep[$ftokeep['filepath']][$ftokeep['filename']] = $ftokeep;
2508                 }
2510                 foreach ($areafiles as $file) {
2511                     if ($file->is_directory()) {
2512                         continue;
2513                     }
2514                     if (!isset($filestokeep[$file->get_filepath()][$file->get_filename()])) {
2515                         $file->delete();    // Not in the list to be kept.
2516                     }
2517                 }
2518             }
2519         }
2521         $result = array(
2522             'draftitemid' => $draftitemid,
2523             'files' => external_util::get_area_files($usercontext->id, 'user', 'draft',
2524                 $draftitemid),
2525             'areaoptions' => $areaoptions,
2526             'messagetext' => $messagetext,
2527             'warnings' => $warnings,
2528         );
2529         return $result;
2530     }
2532     /**
2533      * Returns description of method result value
2534      *
2535      * @return external_description
2536      * @since Moodle 3.8
2537      */
2538     public static function prepare_draft_area_for_post_returns() {
2539         return new external_single_structure(
2540             array(
2541                 'draftitemid' => new external_value(PARAM_INT, 'Draft item id for the file area.'),
2542                 'files' => new external_files('Draft area files.', VALUE_OPTIONAL),
2543                 'areaoptions' => new external_multiple_structure(
2544                     new external_single_structure(
2545                         array(
2546                             'name' => new external_value(PARAM_RAW, 'Name of option.'),
2547                             'value' => new external_value(PARAM_RAW, 'Value of option.'),
2548                         )
2549                     ), 'Draft file area options.'
2550                 ),
2551                 'messagetext' => new external_value(PARAM_RAW, 'Message text with URLs rewritten.'),
2552                 'warnings' => new external_warnings(),
2553             )
2554         );
2555     }
2557     /**
2558      * Returns description of method parameters
2559      *
2560      * @return external_function_parameters
2561      * @since Moodle 3.8
2562      */
2563     public static function update_discussion_post_parameters() {
2564         return new external_function_parameters(
2565             [
2566                 'postid' => new external_value(PARAM_INT, 'Post to be updated. It can be a discussion topic post.'),
2567                 'subject' => new external_value(PARAM_TEXT, 'Updated post subject', VALUE_DEFAULT, ''),
2568                 'message' => new external_value(PARAM_RAW, 'Updated post message (HTML assumed if messageformat is not provided)',
2569                     VALUE_DEFAULT, ''),
2570                 'messageformat' => new external_format_value('message', VALUE_DEFAULT),
2571                 'options' => new external_multiple_structure (
2572                     new external_single_structure(
2573                         [
2574                             'name' => new external_value(
2575                                 PARAM_ALPHANUM,
2576                                 'The allowed keys (value format) are:
2577                                 pinned (bool); (only for discussions) whether to pin this discussion or not
2578                                 discussionsubscribe (bool); whether to subscribe to the post or not
2579                                 inlineattachmentsid (int); the draft file area id for inline attachments in the text
2580                                 attachmentsid (int); the draft file area id for attachments'
2581                             ),
2582                             'value' => new external_value(PARAM_RAW, 'The value of the option.')
2583                         ]
2584                     ),
2585                     'Configuration options for the post.',
2586                     VALUE_DEFAULT,
2587                     []
2588                 ),
2589             ]
2590         );
2591     }
2593     /**
2594      * Updates a post or a discussion post topic.
2595      *
2596      * @param int $postid post to be updated, it can be a discussion topic post.
2597      * @param string $subject updated post subject
2598      * @param string $message updated post message (HTML assumed if messageformat is not provided)
2599      * @param int $messageformat The format of the message, defaults to FORMAT_HTML
2600      * @param array $options different configuration options for the post to be updated.
2601      * @return array of warnings and the status (true if the post/discussion was deleted)
2602      * @since Moodle 3.8
2603      * @throws moodle_exception
2604      * @todo support more options: timed posts, groups change and tags.
2605      */
2606     public static function update_discussion_post($postid, $subject = '', $message = '', $messageformat = FORMAT_HTML,
2607             $options = []) {
2608         global $CFG, $USER;
2609         require_once($CFG->dirroot . "/mod/forum/lib.php");
2611         $params = self::validate_parameters(self::add_discussion_post_parameters(),
2612             [
2613                 'postid' => $postid,
2614                 'subject' => $subject,
2615                 'message' => $message,
2616                 'options' => $options,
2617                 'messageformat' => $messageformat,
2618             ]
2619         );
2620         $warnings = [];
2622         // Validate options.
2623         $options = [];
2624         foreach ($params['options'] as $option) {
2625             $name = trim($option['name']);
2626             switch ($name) {
2627                 case 'pinned':
2628                     $value = clean_param($option['value'], PARAM_BOOL);
2629                     break;
2630                 case 'discussionsubscribe':
2631                     $value = clean_param($option['value'], PARAM_BOOL);
2632                     break;
2633                 case 'inlineattachmentsid':
2634                     $value = clean_param($option['value'], PARAM_INT);
2635                     break;
2636                 case 'attachmentsid':
2637                     $value = clean_param($option['value'], PARAM_INT);
2638                     break;
2639                 default:
2640                     throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
2641             }
2642             $options[$name] = $value;
2643         }
2645         $managerfactory = mod_forum\local\container::get_manager_factory();
2646         $vaultfactory = mod_forum\local\container::get_vault_factory();
2647         $forumvault = $vaultfactory->get_forum_vault();
2648         $discussionvault = $vaultfactory->get_discussion_vault();
2649         $postvault = $vaultfactory->get_post_vault();
2650         $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
2651         $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
2652         $discussiondatamapper = $legacydatamapperfactory->get_discussion_data_mapper();
2653         $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
2655         $postentity = $postvault->get_from_id($params['postid']);
2656         if (empty($postentity)) {
2657             throw new moodle_exception('invalidpostid', 'forum');
2658         }
2659         $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
2660         if (empty($discussionentity)) {
2661             throw new moodle_exception('notpartofdiscussion', 'forum');
2662         }
2663         $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
2664         if (empty($forumentity)) {
2665             throw new moodle_exception('invalidforumid', 'forum');
2666         }
2667         $forum = $forumdatamapper->to_legacy_object($forumentity);
2668         $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
2670         $modcontext = $forumentity->get_context();
2671         self::validate_context($modcontext);
2673         if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
2674             throw new moodle_exception('cannotupdatepost', 'forum');
2675         }
2677         // Get the original post.
2678         $updatepost = $postdatamapper->to_legacy_object($postentity);
2679         $updatepost->itemid = IGNORE_FILE_MERGE;
2680         $updatepost->attachments = IGNORE_FILE_MERGE;
2682         // Prepare the post to be updated.
2683         if (!empty($params['subject'])) {
2684             $updatepost->subject = $params['subject'];
2685         }
2687         if (!empty($params['message']) && !empty($params['messageformat'])) {
2688             $updatepost->message       = $params['message'];
2689             $updatepost->messageformat = $params['messageformat'];
2690             $updatepost->messagetrust  = trusttext_trusted($modcontext);
2691             // Clean message text.
2692             $updatepost = trusttext_pre_edit($updatepost, 'message', $modcontext);
2693         }
2695         if (isset($options['discussionsubscribe'])) {
2696             // No need to validate anything here, forum_post_subscription will do.
2697             $updatepost->discussionsubscribe = $options['discussionsubscribe'];
2698         }
2700         // When editing first post/discussion.
2701         if (!$postentity->has_parent()) {
2702             // Defaults for discussion topic posts.
2703             $updatepost->name = $discussionentity->get_name();
2704             $updatepost->timestart = $discussionentity->get_time_start();
2705             $updatepost->timeend = $discussionentity->get_time_end();
2707             if (isset($options['pinned'])) {
2708                 if ($capabilitymanager->can_pin_discussions($USER)) {
2709                     // Can change pinned if we have capability.
2710                     $updatepost->pinned = !empty($options['pinned']) ? FORUM_DISCUSSION_PINNED : FORUM_DISCUSSION_UNPINNED;
2711                 }
2712             }
2713         }
2715         if (isset($options['inlineattachmentsid'])) {
2716             $updatepost->itemid = $options['inlineattachmentsid'];
2717         }
2719         if (isset($options['attachmentsid']) && forum_can_create_attachment($forum, $modcontext)) {
2720             $updatepost->attachments = $options['attachmentsid'];
2721         }
2723         // Update the post.
2724         $fakemform = $updatepost->id;
2725         if (forum_update_post($updatepost, $fakemform)) {
2726             $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
2728             forum_trigger_post_updated_event($updatepost, $discussion, $modcontext, $forum);
2730             forum_post_subscription(
2731                 $updatepost,
2732                 $forum,
2733                 $discussion
2734             );
2735             $status = true;
2736         } else {
2737             $status = false;
2738         }
2740         return [
2741             'status' => $status,
2742             'warnings' => $warnings,
2743         ];
2744     }
2746     /**
2747      * Returns description of method result value
2748      *
2749      * @return external_description
2750      * @since Moodle 3.8
2751      */
2752     public static function update_discussion_post_returns() {
2753         return new external_single_structure(
2754             [
2755                 'status' => new external_value(PARAM_BOOL, 'True if the post/discussion was updated, false otherwise.'),
2756                 'warnings' => new external_warnings()
2757             ]
2758         );
2759     }