MDL-65071 forum: Add unit tests
[moodle.git] / mod / forum / externallib.php
CommitLineData
2b9fe87d
MN
1<?php
2
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/>.
17
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 */
25
26defined('MOODLE_INTERNAL') || die;
27
28require_once("$CFG->libdir/externallib.php");
29
9b4f09ba 30use mod_forum\local\exporters\post as post_exporter;
99bda8a7 31use mod_forum\local\exporters\discussion as discussion_exporter;
9b4f09ba 32
2b9fe87d
MN
33class mod_forum_external extends external_api {
34
35 /**
a9a0cb69 36 * Describes the parameters for get_forum.
2b9fe87d 37 *
9db43c73 38 * @return external_function_parameters
2b9fe87d
MN
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',
a69c9abd 45 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of Course IDs', VALUE_DEFAULT, array()),
2b9fe87d
MN
46 )
47 );
48 }
49
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()) {
c8f1d8a0 60 global $CFG;
2b9fe87d
MN
61
62 require_once($CFG->dirroot . "/mod/forum/lib.php");
63
a9a0cb69
MN
64 $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids));
65
583b02e4 66 $courses = array();
a9a0cb69 67 if (empty($params['courseids'])) {
583b02e4
FM
68 $courses = enrol_get_my_courses();
69 $params['courseids'] = array_keys($courses);
2b9fe87d
MN
70 }
71
72 // Array to store the forums to return.
73 $arrforums = array();
ea5b910b 74 $warnings = array();
2b9fe87d 75
0c246ae5 76 // Ensure there are courseids to loop through.
ea5b910b
JL
77 if (!empty($params['courseids'])) {
78
583b02e4 79 list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses);
c8f1d8a0
JL
80
81 // Get the forums in this course. This function checks users visibility permissions.
ea5b910b
JL
82 $forums = get_all_instances_in_courses("forum", $courses);
83 foreach ($forums as $forum) {
84
85 $course = $courses[$forum->course];
86 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
87 $context = context_module::instance($cm->id);
88
89 // Skip forums we are not allowed to see discussions.
90 if (!has_capability('mod/forum:viewdiscussion', $context)) {
91 continue;
2b9fe87d 92 }
ea5b910b 93
5b587c75 94 $forum->name = external_format_string($forum->name, $context->id);
ea5b910b
JL
95 // Format the intro before being returning using the format setting.
96 list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat,
d33c67bc 97 $context->id, 'mod_forum', 'intro', null);
7ef49bd3 98 $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false);
ea5b910b
JL
99 // Discussions count. This function does static request cache.
100 $forum->numdiscussions = forum_count_discussions($forum, $cm, $course);
101 $forum->cmid = $forum->coursemodule;
102 $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context);
4669389d 103 $forum->istracked = forum_tp_is_tracked($forum);
2256bb74
JL
104 if ($forum->istracked) {
105 $forum->unreadpostscount = forum_tp_count_forum_unread_posts($cm, $course);
106 }
ea5b910b
JL
107
108 // Add the forum to the array to return.
109 $arrforums[$forum->id] = $forum;
2b9fe87d
MN
110 }
111 }
112
113 return $arrforums;
114 }
115
116 /**
a9a0cb69 117 * Describes the get_forum return value.
2b9fe87d
MN
118 *
119 * @return external_single_structure
120 * @since Moodle 2.5
121 */
0f3bbfd4 122 public static function get_forums_by_courses_returns() {
2b9fe87d
MN
123 return new external_multiple_structure(
124 new external_single_structure(
125 array(
126 'id' => new external_value(PARAM_INT, 'Forum id'),
5b587c75 127 'course' => new external_value(PARAM_INT, 'Course id'),
2b9fe87d 128 'type' => new external_value(PARAM_TEXT, 'The forum type'),
5b587c75 129 'name' => new external_value(PARAM_RAW, 'Forum name'),
2b9fe87d
MN
130 'intro' => new external_value(PARAM_RAW, 'The forum intro'),
131 'introformat' => new external_format_value('intro'),
7ef49bd3 132 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
99bcb318
SR
133 'duedate' => new external_value(PARAM_INT, 'duedate for the user', VALUE_OPTIONAL),
134 'cutoffdate' => new external_value(PARAM_INT, 'cutoffdate for the user', VALUE_OPTIONAL),
2b9fe87d
MN
135 'assessed' => new external_value(PARAM_INT, 'Aggregate type'),
136 'assesstimestart' => new external_value(PARAM_INT, 'Assess start time'),
137 'assesstimefinish' => new external_value(PARAM_INT, 'Assess finish time'),
138 'scale' => new external_value(PARAM_INT, 'Scale'),
139 'maxbytes' => new external_value(PARAM_INT, 'Maximum attachment size'),
140 'maxattachments' => new external_value(PARAM_INT, 'Maximum number of attachments'),
141 'forcesubscribe' => new external_value(PARAM_INT, 'Force users to subscribe'),
142 'trackingtype' => new external_value(PARAM_INT, 'Subscription mode'),
143 'rsstype' => new external_value(PARAM_INT, 'RSS feed for this activity'),
144 'rssarticles' => new external_value(PARAM_INT, 'Number of RSS recent articles'),
145 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
146 'warnafter' => new external_value(PARAM_INT, 'Post threshold for warning'),
147 'blockafter' => new external_value(PARAM_INT, 'Post threshold for blocking'),
148 'blockperiod' => new external_value(PARAM_INT, 'Time period for blocking'),
149 'completiondiscussions' => new external_value(PARAM_INT, 'Student must create discussions'),
150 'completionreplies' => new external_value(PARAM_INT, 'Student must post replies'),
151 'completionposts' => new external_value(PARAM_INT, 'Student must post discussions or replies'),
7ea6ada3 152 'cmid' => new external_value(PARAM_INT, 'Course module id'),
ea5b910b
JL
153 'numdiscussions' => new external_value(PARAM_INT, 'Number of discussions in the forum', VALUE_OPTIONAL),
154 'cancreatediscussions' => new external_value(PARAM_BOOL, 'If the user can create discussions', VALUE_OPTIONAL),
0f3bbfd4 155 'lockdiscussionafter' => new external_value(PARAM_INT, 'After what period a discussion is locked', VALUE_OPTIONAL),
4669389d 156 'istracked' => new external_value(PARAM_BOOL, 'If the user is tracking the forum', VALUE_OPTIONAL),
2256bb74
JL
157 'unreadpostscount' => new external_value(PARAM_INT, 'The number of unread posts for tracked forums',
158 VALUE_OPTIONAL),
2b9fe87d
MN
159 ), 'forum'
160 )
161 );
162 }
a9a0cb69 163
bc4c7337
AN
164 /**
165 * Get the forum posts in the specified discussion.
166 *
167 * @param int $discussionid
168 * @param string $sortby
169 * @param string $sortdirection
170 * @return array
171 */
172 public static function get_discussion_posts(int $discussionid, ?string $sortby, ?string $sortdirection) {
173 global $USER;
174 // Validate the parameter.
175 $params = self::validate_parameters(self::get_discussion_posts_parameters(), [
176 'discussionid' => $discussionid,
177 'sortby' => $sortby,
178 'sortdirection' => $sortdirection,
179 ]);
180 $warnings = [];
181
182 $vaultfactory = mod_forum\local\container::get_vault_factory();
183
184 $discussionvault = $vaultfactory->get_discussion_vault();
185 $discussion = $discussionvault->get_from_id($params['discussionid']);
186
187 $forumvault = $vaultfactory->get_forum_vault();
188 $forum = $forumvault->get_from_id($discussion->get_forum_id());
189
190 $sortby = $params['sortby'];
191 $sortdirection = $params['sortdirection'];
192 $sortallowedvalues = ['id', 'created', 'modified'];
193 $directionallowedvalues = ['ASC', 'DESC'];
194
195 if (!in_array(strtolower($sortby), $sortallowedvalues)) {
196 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
197 'allowed values are: ' . implode(', ', $sortallowedvalues));
198 }
199
200 $sortdirection = strtoupper($sortdirection);
201 if (!in_array($sortdirection, $directionallowedvalues)) {
202 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
203 'allowed values are: ' . implode(',', $directionallowedvalues));
204 }
205
206 $managerfactory = mod_forum\local\container::get_manager_factory();
207 $capabilitymanager = $managerfactory->get_capability_manager($forum);
208
209 $postvault = $vaultfactory->get_post_vault();
210 $posts = $postvault->get_from_discussion_id(
211 $USER,
212 $discussion->get_id(),
213 $capabilitymanager->can_view_any_private_reply($USER),
214 "{$sortby} {$sortdirection}"
215 );
216
217 $builderfactory = mod_forum\local\container::get_builder_factory();
218 $postbuilder = $builderfactory->get_exported_posts_builder();
219
220 $legacydatamapper = mod_forum\local\container::get_legacy_data_mapper_factory();
221
222 return [
223 'posts' => $postbuilder->build($USER, [$forum], [$discussion], $posts),
224 'ratinginfo' => \core_rating\external\util::get_rating_info(
225 $legacydatamapper->get_forum_data_mapper()->to_legacy_object($forum),
226 $forum->get_context(),
227 'mod_forum',
228 'post',
229 $legacydatamapper->get_post_data_mapper()->to_legacy_objects($posts)
230 ),
231 'warnings' => $warnings,
232 ];
233 }
234
235 /**
236 * Describe the post parameters.
237 *
238 * @return external_function_parameters
239 */
240 public static function get_discussion_posts_parameters() {
241 return new external_function_parameters ([
242 'discussionid' => new external_value(PARAM_INT, 'The ID of the discussion from which to fetch posts.', VALUE_REQUIRED),
243 'sortby' => new external_value(PARAM_ALPHA, 'Sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
244 'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
245 ]);
246 }
247
248 /**
249 * Describe the post return format.
250 *
251 * @return external_single_structure
252 */
253 public static function get_discussion_posts_returns() {
254 return new external_single_structure([
255 'posts' => new external_multiple_structure(\mod_forum\local\exporters\post::get_read_structure()),
256 'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
257 'warnings' => new external_warnings()
258 ]);
259 }
260
e2ede426
JL
261 /**
262 * Describes the parameters for get_forum_discussion_posts.
263 *
9db43c73 264 * @return external_function_parameters
e2ede426
JL
265 * @since Moodle 2.7
266 */
267 public static function get_forum_discussion_posts_parameters() {
268 return new external_function_parameters (
269 array(
270 'discussionid' => new external_value(PARAM_INT, 'discussion ID', VALUE_REQUIRED),
271 'sortby' => new external_value(PARAM_ALPHA,
272 'sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
273 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
274 )
275 );
276 }
277
278 /**
279 * Returns a list of forum posts for a discussion
280 *
281 * @param int $discussionid the post ids
282 * @param string $sortby sort by this element (id, created or modified)
283 * @param string $sortdirection sort direction: ASC or DESC
284 *
285 * @return array the forum post details
286 * @since Moodle 2.7
8245daba 287 * @todo MDL-65252 This will be removed in Moodle 4.1
e2ede426 288 */
fb8840d2 289 public static function get_forum_discussion_posts($discussionid, $sortby = "created", $sortdirection = "DESC") {
d85bedf7 290 global $CFG, $DB, $USER, $PAGE;
e2ede426 291
b1aa7dfa 292 $posts = array();
e2ede426
JL
293 $warnings = array();
294
295 // Validate the parameter.
296 $params = self::validate_parameters(self::get_forum_discussion_posts_parameters(),
297 array(
298 'discussionid' => $discussionid,
299 'sortby' => $sortby,
300 'sortdirection' => $sortdirection));
301
302 // Compact/extract functions are not recommended.
303 $discussionid = $params['discussionid'];
304 $sortby = $params['sortby'];
305 $sortdirection = $params['sortdirection'];
306
307 $sortallowedvalues = array('id', 'created', 'modified');
308 if (!in_array($sortby, $sortallowedvalues)) {
309 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
310 'allowed values are: ' . implode(',', $sortallowedvalues));
311 }
312
313 $sortdirection = strtoupper($sortdirection);
314 $directionallowedvalues = array('ASC', 'DESC');
315 if (!in_array($sortdirection, $directionallowedvalues)) {
316 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
317 'allowed values are: ' . implode(',', $directionallowedvalues));
318 }
319
320 $discussion = $DB->get_record('forum_discussions', array('id' => $discussionid), '*', MUST_EXIST);
321 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
322 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
323 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
324
325 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
326 $modcontext = context_module::instance($cm->id);
327 self::validate_context($modcontext);
328
329 // This require must be here, see mod/forum/discuss.php.
330 require_once($CFG->dirroot . "/mod/forum/lib.php");
331
332 // Check they have the view forum capability.
333 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
334
335 if (! $post = forum_get_post_full($discussion->firstpost)) {
336 throw new moodle_exception('notexists', 'forum');
337 }
338
339 // This function check groups, qanda, timed discussions, etc.
340 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
341 throw new moodle_exception('noviewdiscussionspermission', 'forum');
342 }
343
344 $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
345
346 // We will add this field in the response.
347 $canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
348
349 $forumtracked = forum_tp_is_tracked($forum);
350
351 $sort = 'p.' . $sortby . ' ' . $sortdirection;
b1aa7dfa 352 $allposts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
e2ede426 353
b1aa7dfa 354 foreach ($allposts as $post) {
3e95e09b 355 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm, false)) {
e2ede426
JL
356 $warning = array();
357 $warning['item'] = 'post';
358 $warning['itemid'] = $post->id;
359 $warning['warningcode'] = '1';
360 $warning['message'] = 'You can\'t see this post';
361 $warnings[] = $warning;
362 continue;
363 }
364
365 // Function forum_get_all_discussion_posts adds postread field.
f47eeafd
JL
366 // Note that the value returned can be a boolean or an integer. The WS expects a boolean.
367 if (empty($post->postread)) {
b1aa7dfa 368 $post->postread = false;
f47eeafd 369 } else {
b1aa7dfa 370 $post->postread = true;
e2ede426 371 }
f47eeafd 372
bc4c7337
AN
373 $post->isprivatereply = !empty($post->privatereplyto);
374
b1aa7dfa
JL
375 $post->canreply = $canreply;
376 if (!empty($post->children)) {
377 $post->children = array_keys($post->children);
fb8840d2 378 } else {
b1aa7dfa 379 $post->children = array();
e2ede426
JL
380 }
381
3e95e09b
AN
382 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
383 // The post is available, but has been marked as deleted.
384 // It will still be available but filled with a placeholder.
385 $post->userid = null;
386 $post->userfullname = null;
387 $post->userpictureurl = null;
388
389 $post->subject = get_string('privacy:request:delete:post:subject', 'mod_forum');
390 $post->message = get_string('privacy:request:delete:post:message', 'mod_forum');
391
392 $post->deleted = true;
393 $posts[] = $post;
394
395 continue;
396 }
397 $post->deleted = false;
398
30861fbd
JL
399 if (forum_is_author_hidden($post, $forum)) {
400 $post->userid = null;
401 $post->userfullname = null;
402 $post->userpictureurl = null;
403 } else {
404 $user = new stdclass();
405 $user->id = $post->userid;
406 $user = username_load_fields_from_object($user, $post, null, array('picture', 'imagealt', 'email'));
407 $post->userfullname = fullname($user, $canviewfullname);
81f810dc 408
30861fbd
JL
409 $userpicture = new user_picture($user);
410 $userpicture->size = 1; // Size f1.
411 $post->userpictureurl = $userpicture->get_url($PAGE)->out(false);
412 }
14ebc396 413
55bb8189 414 $post->subject = external_format_string($post->subject, $modcontext->id);
48fb0250
JL
415 // Rewrite embedded images URLs.
416 list($post->message, $post->messageformat) =
417 external_format_text($post->message, $post->messageformat, $modcontext->id, 'mod_forum', 'post', $post->id);
418
419 // List attachments.
420 if (!empty($post->attachment)) {
14590070 421 $post->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $post->id);
48fb0250 422 }
c8743f62
JL
423 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $post->id);
424 if (!empty($messageinlinefiles)) {
425 $post->messageinlinefiles = $messageinlinefiles;
426 }
6c344ff2
JL
427 // Post tags.
428 $post->tags = \core_tag\external\util::get_item_tags('mod_forum', 'forum_posts', $post->id);
e2ede426 429
b1aa7dfa 430 $posts[] = $post;
e2ede426
JL
431 }
432
433 $result = array();
434 $result['posts'] = $posts;
b7ce46df 435 $result['ratinginfo'] = \core_rating\external\util::get_rating_info($forum, $modcontext, 'mod_forum', 'post', $posts);
e2ede426
JL
436 $result['warnings'] = $warnings;
437 return $result;
438 }
439
440 /**
441 * Describes the get_forum_discussion_posts return value.
442 *
443 * @return external_single_structure
444 * @since Moodle 2.7
445 */
446 public static function get_forum_discussion_posts_returns() {
447 return new external_single_structure(
448 array(
449 'posts' => new external_multiple_structure(
450 new external_single_structure(
451 array(
452 'id' => new external_value(PARAM_INT, 'Post id'),
453 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
454 'parent' => new external_value(PARAM_INT, 'Parent id'),
455 'userid' => new external_value(PARAM_INT, 'User id'),
456 'created' => new external_value(PARAM_INT, 'Creation time'),
457 'modified' => new external_value(PARAM_INT, 'Time modified'),
458 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
459 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
460 'message' => new external_value(PARAM_RAW, 'The post message'),
48fb0250 461 'messageformat' => new external_format_value('message'),
e2ede426 462 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
c8743f62 463 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
48fb0250 464 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
14590070 465 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
e2ede426
JL
466 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
467 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
468 'children' => new external_multiple_structure(new external_value(PARAM_INT, 'children post id')),
469 'canreply' => new external_value(PARAM_BOOL, 'The user can reply to posts?'),
470 'postread' => new external_value(PARAM_BOOL, 'The post was read'),
694bf0c7 471 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
3e95e09b
AN
472 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.', VALUE_OPTIONAL),
473 'deleted' => new external_value(PARAM_BOOL, 'This post has been removed.'),
bc4c7337 474 'isprivatereply' => new external_value(PARAM_BOOL, 'The post is a private reply'),
6c344ff2
JL
475 'tags' => new external_multiple_structure(
476 \core_tag\external\tag_item_exporter::get_read_structure(), 'Tags', VALUE_OPTIONAL
477 ),
e2ede426
JL
478 ), 'post'
479 )
480 ),
b7ce46df 481 'ratinginfo' => \core_rating\external\util::external_ratings_structure(),
e2ede426
JL
482 'warnings' => new external_warnings()
483 )
484 );
485 }
486
bc4c7337
AN
487 /**
488 * Mark the get_forum_discussion_posts web service as deprecated.
489 *
490 * @return bool
491 */
492 public static function get_forum_discussion_posts_is_deprecated() {
493 return true;
494 }
495
7c51b40a
JL
496 /**
497 * Describes the parameters for get_forum_discussions_paginated.
498 *
9db43c73 499 * @return external_function_parameters
7c51b40a
JL
500 * @since Moodle 2.8
501 */
502 public static function get_forum_discussions_paginated_parameters() {
503 return new external_function_parameters (
504 array(
505 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
506 'sortby' => new external_value(PARAM_ALPHA,
507 'sort by this element: id, timemodified, timestart or timeend', VALUE_DEFAULT, 'timemodified'),
508 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
509 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
510 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
511 )
512 );
513 }
514
515 /**
516 * Returns a list of forum discussions optionally sorted and paginated.
517 *
518 * @param int $forumid the forum instance id
519 * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
520 * @param string $sortdirection sort direction: ASC or DESC
521 * @param int $page page number
522 * @param int $perpage items per page
523 *
524 * @return array the forum discussion details including warnings
525 * @since Moodle 2.8
526 */
527 public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC',
528 $page = -1, $perpage = 0) {
d85bedf7 529 global $CFG, $DB, $USER, $PAGE;
7c51b40a
JL
530
531 require_once($CFG->dirroot . "/mod/forum/lib.php");
532
533 $warnings = array();
039c81f0 534 $discussions = array();
7c51b40a
JL
535
536 $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(),
537 array(
538 'forumid' => $forumid,
539 'sortby' => $sortby,
540 'sortdirection' => $sortdirection,
541 'page' => $page,
542 'perpage' => $perpage
543 )
544 );
545
546 // Compact/extract functions are not recommended.
547 $forumid = $params['forumid'];
548 $sortby = $params['sortby'];
549 $sortdirection = $params['sortdirection'];
550 $page = $params['page'];
551 $perpage = $params['perpage'];
552
553 $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
554 if (!in_array($sortby, $sortallowedvalues)) {
555 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
556 'allowed values are: ' . implode(',', $sortallowedvalues));
557 }
558
559 $sortdirection = strtoupper($sortdirection);
560 $directionallowedvalues = array('ASC', 'DESC');
561 if (!in_array($sortdirection, $directionallowedvalues)) {
562 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
563 'allowed values are: ' . implode(',', $directionallowedvalues));
564 }
565
566 $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
567 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
568 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
569
570 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
571 $modcontext = context_module::instance($cm->id);
572 self::validate_context($modcontext);
573
574 // Check they have the view forum capability.
575 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
576
5f219cf1 577 $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
4f3a2d21 578 $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
7c51b40a 579
039c81f0 580 if ($alldiscussions) {
7c51b40a
JL
581 $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
582
583 // Get the unreads array, this takes a forum id and returns data for all discussions.
584 $unreads = array();
585 if ($cantrack = forum_tp_can_track_forums($forum)) {
586 if ($forumtracked = forum_tp_is_tracked($forum)) {
587 $unreads = forum_get_discussions_unread($cm);
588 }
589 }
590 // The forum function returns the replies for all the discussions in a given forum.
bc4c7337 591 $canseeprivatereplies = has_capability('mod/forum:readprivatereplies', $modcontext);
565cccfa 592 $canlock = has_capability('moodle/course:manageactivities', $modcontext, $USER);
bc4c7337 593 $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage, $canseeprivatereplies);
7c51b40a 594
d3cac88d
P
595 if (isloggedin()) {
596 $usercontext = context_user::instance($USER->id);
597 $ufservice = core_favourites\service_factory::get_service_for_user_context($usercontext);
598 }
279128bb 599 $canfavourite = has_capability('mod/forum:cantogglefavourite', $modcontext, $USER);
039c81f0
JL
600 foreach ($alldiscussions as $discussion) {
601
7c51b40a 602 // This function checks for qanda forums.
039c81f0
JL
603 // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
604 $discussionrec = clone $discussion;
605 $discussionrec->id = $discussion->discussion;
606 if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
7c51b40a
JL
607 $warning = array();
608 // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
609 $warning['item'] = 'post';
610 $warning['itemid'] = $discussion->id;
611 $warning['warningcode'] = '1';
612 $warning['message'] = 'You can\'t see this discussion';
613 $warnings[] = $warning;
614 continue;
615 }
616
617 $discussion->numunread = 0;
618 if ($cantrack && $forumtracked) {
619 if (isset($unreads[$discussion->discussion])) {
620 $discussion->numunread = (int) $unreads[$discussion->discussion];
621 }
622 }
623
624 $discussion->numreplies = 0;
625 if (!empty($replies[$discussion->discussion])) {
626 $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
627 }
628
55bb8189
JL
629 $discussion->name = external_format_string($discussion->name, $modcontext->id);
630 $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
7c51b40a
JL
631 // Rewrite embedded images URLs.
632 list($discussion->message, $discussion->messageformat) =
633 external_format_text($discussion->message, $discussion->messageformat,
634 $modcontext->id, 'mod_forum', 'post', $discussion->id);
635
636 // List attachments.
637 if (!empty($discussion->attachment)) {
14590070
JL
638 $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
639 $discussion->id);
7c51b40a 640 }
c8743f62
JL
641 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
642 if (!empty($messageinlinefiles)) {
643 $discussion->messageinlinefiles = $messageinlinefiles;
644 }
7c51b40a 645
565cccfa
P
646 $discussion->locked = forum_discussion_is_locked($forum, $discussion);
647 $discussion->canlock = $canlock;
d3cac88d
P
648 $discussion->starred = !empty($ufservice) ? $ufservice->favourite_exists('mod_forum', 'discussions',
649 $discussionrec->id, $modcontext) : false;
0f3bbfd4 650 $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
279128bb 651 $discussion->canfavourite = $canfavourite;
0f3bbfd4 652
30861fbd
JL
653 if (forum_is_author_hidden($discussion, $forum)) {
654 $discussion->userid = null;
655 $discussion->userfullname = null;
656 $discussion->userpictureurl = null;
657
658 $discussion->usermodified = null;
659 $discussion->usermodifiedfullname = null;
660 $discussion->usermodifiedpictureurl = null;
661 } else {
662 $picturefields = explode(',', user_picture::fields());
663
664 // Load user objects from the results of the query.
665 $user = new stdclass();
666 $user->id = $discussion->userid;
667 $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
668 // Preserve the id, it can be modified by username_load_fields_from_object.
669 $user->id = $discussion->userid;
670 $discussion->userfullname = fullname($user, $canviewfullname);
671
672 $userpicture = new user_picture($user);
673 $userpicture->size = 1; // Size f1.
674 $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
675
676 $usermodified = new stdclass();
677 $usermodified->id = $discussion->usermodified;
678 $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
679 // Preserve the id (it can be overwritten due to the prefixed $picturefields).
680 $usermodified->id = $discussion->usermodified;
681 $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
682
683 $userpicture = new user_picture($usermodified);
684 $userpicture->size = 1; // Size f1.
685 $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
686 }
687
039c81f0 688 $discussions[] = $discussion;
7c51b40a
JL
689 }
690 }
691
692 $result = array();
693 $result['discussions'] = $discussions;
694 $result['warnings'] = $warnings;
695 return $result;
696
697 }
698
699 /**
700 * Describes the get_forum_discussions_paginated return value.
701 *
702 * @return external_single_structure
703 * @since Moodle 2.8
704 */
705 public static function get_forum_discussions_paginated_returns() {
706 return new external_single_structure(
707 array(
708 'discussions' => new external_multiple_structure(
709 new external_single_structure(
710 array(
711 'id' => new external_value(PARAM_INT, 'Post id'),
712 'name' => new external_value(PARAM_TEXT, 'Discussion name'),
713 'groupid' => new external_value(PARAM_INT, 'Group id'),
714 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
715 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
716 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
717 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
718 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
719 'parent' => new external_value(PARAM_INT, 'Parent id'),
720 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
721 'created' => new external_value(PARAM_INT, 'Creation time'),
722 'modified' => new external_value(PARAM_INT, 'Time modified'),
723 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
724 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
725 'message' => new external_value(PARAM_RAW, 'The post message'),
726 'messageformat' => new external_format_value('message'),
727 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
c8743f62 728 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
7c51b40a 729 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
14590070 730 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
7c51b40a
JL
731 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
732 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
733 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
734 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
735 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
736 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
737 'numreplies' => new external_value(PARAM_TEXT, 'The number of replies in the discussion'),
5f219cf1 738 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
0f3bbfd4
AN
739 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
740 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
279128bb 741 'starred' => new external_value(PARAM_BOOL, 'Is the discussion starred'),
0f3bbfd4 742 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
565cccfa 743 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
279128bb 744 'canfavourite' => new external_value(PARAM_BOOL, 'Can the user star the discussion'),
7c51b40a
JL
745 ), 'post'
746 )
747 ),
748 'warnings' => new external_warnings()
749 )
750 );
751 }
752
4a1e44a1
JL
753 /**
754 * Returns description of method parameters
755 *
756 * @return external_function_parameters
757 * @since Moodle 2.9
758 */
759 public static function view_forum_parameters() {
760 return new external_function_parameters(
761 array(
762 'forumid' => new external_value(PARAM_INT, 'forum instance id')
763 )
764 );
765 }
766
767 /**
1c2b7882 768 * Trigger the course module viewed event and update the module completion status.
4a1e44a1
JL
769 *
770 * @param int $forumid the forum instance id
771 * @return array of warnings and status result
772 * @since Moodle 2.9
773 * @throws moodle_exception
774 */
775 public static function view_forum($forumid) {
776 global $DB, $CFG;
777 require_once($CFG->dirroot . "/mod/forum/lib.php");
778
779 $params = self::validate_parameters(self::view_forum_parameters(),
780 array(
781 'forumid' => $forumid
782 ));
783 $warnings = array();
784
785 // Request and permission validation.
ca7e2fc2 786 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
4a1e44a1
JL
787 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
788
789 $context = context_module::instance($cm->id);
790 self::validate_context($context);
791
ea2fa324
JL
792 require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
793
4a1e44a1
JL
794 // Call the forum/lib API.
795 forum_view($forum, $course, $cm, $context);
796
797 $result = array();
798 $result['status'] = true;
799 $result['warnings'] = $warnings;
800 return $result;
801 }
802
803 /**
804 * Returns description of method result value
805 *
806 * @return external_description
807 * @since Moodle 2.9
808 */
809 public static function view_forum_returns() {
810 return new external_single_structure(
811 array(
812 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
813 'warnings' => new external_warnings()
814 )
815 );
816 }
817
a3c315dd
JL
818 /**
819 * Returns description of method parameters
820 *
821 * @return external_function_parameters
822 * @since Moodle 2.9
823 */
824 public static function view_forum_discussion_parameters() {
825 return new external_function_parameters(
826 array(
827 'discussionid' => new external_value(PARAM_INT, 'discussion id')
828 )
829 );
830 }
831
832 /**
1c2b7882 833 * Trigger the discussion viewed event.
a3c315dd
JL
834 *
835 * @param int $discussionid the discussion id
836 * @return array of warnings and status result
837 * @since Moodle 2.9
838 * @throws moodle_exception
839 */
840 public static function view_forum_discussion($discussionid) {
db3c9ff8 841 global $DB, $CFG, $USER;
a3c315dd
JL
842 require_once($CFG->dirroot . "/mod/forum/lib.php");
843
844 $params = self::validate_parameters(self::view_forum_discussion_parameters(),
845 array(
846 'discussionid' => $discussionid
847 ));
848 $warnings = array();
849
850 $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
851 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
852 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
853
854 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
855 $modcontext = context_module::instance($cm->id);
856 self::validate_context($modcontext);
857
ea2fa324
JL
858 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
859
a3c315dd
JL
860 // Call the forum/lib API.
861 forum_discussion_view($modcontext, $forum, $discussion);
862
db3c9ff8
PFO
863 // Mark as read if required.
864 if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
865 forum_tp_mark_discussion_read($USER, $discussion->id);
866 }
867
a3c315dd
JL
868 $result = array();
869 $result['status'] = true;
870 $result['warnings'] = $warnings;
871 return $result;
872 }
873
874 /**
875 * Returns description of method result value
876 *
877 * @return external_description
878 * @since Moodle 2.9
879 */
880 public static function view_forum_discussion_returns() {
881 return new external_single_structure(
882 array(
883 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
884 'warnings' => new external_warnings()
885 )
886 );
887 }
888
50a20317
JL
889 /**
890 * Returns description of method parameters
891 *
892 * @return external_function_parameters
893 * @since Moodle 3.0
894 */
895 public static function add_discussion_post_parameters() {
896 return new external_function_parameters(
897 array(
898 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
899 (can be the initial discussion post'),
900 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
901 'message' => new external_value(PARAM_RAW, 'new post message (only html format allowed)'),
902 'options' => new external_multiple_structure (
903 new external_single_structure(
904 array(
905 'name' => new external_value(PARAM_ALPHANUM,
906 'The allowed keys (value format) are:
907 discussionsubscribe (bool); subscribe to the discussion?, default to true
bc4c7337 908 private (bool); make this reply private to the author of the parent post, default to false.
48143990 909 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 910 attachmentsid (int); the draft file area id for attachments
50a20317
JL
911 '),
912 'value' => new external_value(PARAM_RAW, 'the value of the option,
913 this param is validated in the external function.'
914 )
915 )
916 ), 'Options', VALUE_DEFAULT, array())
917 )
918 );
919 }
920
921 /**
922 * Create new posts into an existing discussion.
923 *
924 * @param int $postid the post id we are going to reply to
925 * @param string $subject new post subject
926 * @param string $message new post message (only html format allowed)
927 * @param array $options optional settings
928 * @return array of warnings and the new post id
929 * @since Moodle 3.0
930 * @throws moodle_exception
931 */
932 public static function add_discussion_post($postid, $subject, $message, $options = array()) {
a0c9b6af 933 global $CFG, $USER;
50a20317
JL
934 require_once($CFG->dirroot . "/mod/forum/lib.php");
935
9b4f09ba
P
936 // Get all the factories that are required.
937 $vaultfactory = mod_forum\local\container::get_vault_factory();
938 $entityfactory = mod_forum\local\container::get_entity_factory();
939 $datamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
940 $managerfactory = mod_forum\local\container::get_manager_factory();
941 $discussionvault = $vaultfactory->get_discussion_vault();
942 $forumvault = $vaultfactory->get_forum_vault();
943 $discussiondatamapper = $datamapperfactory->get_discussion_data_mapper();
944 $forumdatamapper = $datamapperfactory->get_forum_data_mapper();
945
50a20317 946 $params = self::validate_parameters(self::add_discussion_post_parameters(),
609a1073
JL
947 array(
948 'postid' => $postid,
949 'subject' => $subject,
950 'message' => $message,
951 'options' => $options
952 )
953 );
bc4c7337 954
609a1073
JL
955 $warnings = array();
956
957 if (!$parent = forum_get_post_full($params['postid'])) {
958 throw new moodle_exception('invalidparentpostid', 'forum');
959 }
960
9b4f09ba 961 if (!$discussion = $discussionvault->get_from_id($parent->discussion)) {
609a1073
JL
962 throw new moodle_exception('notpartofdiscussion', 'forum');
963 }
964
965 // Request and permission validation.
9b4f09ba
P
966 $forum = $forumvault->get_from_id($discussion->get_forum_id());
967 $capabilitymanager = $managerfactory->get_capability_manager($forum);
968 $course = $forum->get_course_record();
969 $cm = $forum->get_course_module_record();
609a1073 970
9b4f09ba
P
971 $discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
972 $forumrecord = $forumdatamapper->to_legacy_object($forum);
609a1073
JL
973 $context = context_module::instance($cm->id);
974 self::validate_context($context);
975
50a20317
JL
976 // Validate options.
977 $options = array(
41182118 978 'discussionsubscribe' => true,
bc4c7337 979 'private' => false,
48143990 980 'inlineattachmentsid' => 0,
e881c4f5 981 'attachmentsid' => null
50a20317
JL
982 );
983 foreach ($params['options'] as $option) {
984 $name = trim($option['name']);
985 switch ($name) {
986 case 'discussionsubscribe':
987 $value = clean_param($option['value'], PARAM_BOOL);
988 break;
bc4c7337
AN
989 case 'private':
990 $value = clean_param($option['value'], PARAM_BOOL);
991 break;
48143990 992 case 'inlineattachmentsid':
41182118
BK
993 $value = clean_param($option['value'], PARAM_INT);
994 break;
e881c4f5
BK
995 case 'attachmentsid':
996 $value = clean_param($option['value'], PARAM_INT);
609a1073
JL
997 // Ensure that the user has permissions to create attachments.
998 if (!has_capability('mod/forum:createattachment', $context)) {
999 $value = 0;
1000 }
e881c4f5 1001 break;
50a20317
JL
1002 default:
1003 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1004 }
1005 $options[$name] = $value;
1006 }
1007
9b4f09ba 1008 if (!$capabilitymanager->can_post_in_discussion($USER, $discussion)) {
50a20317
JL
1009 throw new moodle_exception('nopostforum', 'forum');
1010 }
1011
9b4f09ba 1012 $thresholdwarning = forum_check_throttling($forumrecord, $cm);
50a20317
JL
1013 forum_check_blocking_threshold($thresholdwarning);
1014
1015 // Create the post.
1016 $post = new stdClass();
9b4f09ba 1017 $post->discussion = $discussion->get_id();
50a20317
JL
1018 $post->parent = $parent->id;
1019 $post->subject = $params['subject'];
1020 $post->message = $params['message'];
1021 $post->messageformat = FORMAT_HTML; // Force formatting for now.
1022 $post->messagetrust = trusttext_trusted($context);
48143990 1023 $post->itemid = $options['inlineattachmentsid'];
3e95e09b 1024 $post->attachments = $options['attachmentsid'];
bc4c7337 1025 $post->isprivatereply = $options['private'];
3e95e09b 1026 $post->deleted = 0;
e881c4f5
BK
1027 $fakemform = $post->attachments;
1028 if ($postid = forum_add_new_post($post, $fakemform)) {
50a20317
JL
1029
1030 $post->id = $postid;
1031
1032 // Trigger events and completion.
1033 $params = array(
1034 'context' => $context,
1035 'objectid' => $post->id,
1036 'other' => array(
9b4f09ba
P
1037 'discussionid' => $discussion->get_id(),
1038 'forumid' => $forum->get_id(),
1039 'forumtype' => $forum->get_type(),
50a20317
JL
1040 )
1041 );
1042 $event = \mod_forum\event\post_created::create($params);
1043 $event->add_record_snapshot('forum_posts', $post);
9b4f09ba 1044 $event->add_record_snapshot('forum_discussions', $discussionrecord);
50a20317
JL
1045 $event->trigger();
1046
1047 // Update completion state.
1048 $completion = new completion_info($course);
1049 if ($completion->is_enabled($cm) &&
9b4f09ba 1050 ($forum->get_completion_replies() || $forum->get_completion_posts())) {
50a20317
JL
1051 $completion->update_state($cm, COMPLETION_COMPLETE);
1052 }
1053
1054 $settings = new stdClass();
1055 $settings->discussionsubscribe = $options['discussionsubscribe'];
9b4f09ba 1056 forum_post_subscription($settings, $forumrecord, $discussionrecord);
50a20317
JL
1057 } else {
1058 throw new moodle_exception('couldnotadd', 'forum');
1059 }
1060
9b4f09ba
P
1061 $builderfactory = \mod_forum\local\container::get_builder_factory();
1062 $exportedpostsbuilder = $builderfactory->get_exported_posts_builder();
1063 $postentity = $entityfactory->get_post_from_stdClass($post);
1064 $exportedposts = $exportedpostsbuilder->build($USER, [$forum], [$discussion], [$postentity]);
1065 $exportedpost = $exportedposts[0];
1066
a0c9b6af
P
1067 $message = [];
1068 $message[] = [
1069 'type' => 'success',
1070 'message' => get_string("postaddedsuccess", "forum")
1071 ];
1072
1073 $message[] = [
1074 'type' => 'success',
1075 'message' => get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime))
1076 ];
1077
50a20317
JL
1078 $result = array();
1079 $result['postid'] = $postid;
1080 $result['warnings'] = $warnings;
9b4f09ba 1081 $result['post'] = $exportedpost;
a0c9b6af 1082 $result['messages'] = $message;
50a20317
JL
1083 return $result;
1084 }
1085
1086 /**
1087 * Returns description of method result value
1088 *
1089 * @return external_description
1090 * @since Moodle 3.0
1091 */
1092 public static function add_discussion_post_returns() {
1093 return new external_single_structure(
1094 array(
1095 'postid' => new external_value(PARAM_INT, 'new post id'),
9b4f09ba 1096 'warnings' => new external_warnings(),
a0c9b6af
P
1097 'post' => post_exporter::get_read_structure(),
1098 'messages' => new external_multiple_structure(
1099 new external_single_structure(
1100 array(
1101 'type' => new external_value(PARAM_TEXT, "The classification to be used in the client side", VALUE_REQUIRED),
1102 'message' => new external_value(PARAM_TEXT,'untranslated english message to explain the warning', VALUE_REQUIRED)
1103 ), 'Messages'), 'list of warnings', VALUE_OPTIONAL
1104 ),
1105 //'alertmessage' => new external_value(PARAM_RAW, 'Success message to be displayed to the user.'),
50a20317
JL
1106 )
1107 );
1108 }
1109
309e8698
P
1110 /**
1111 * Toggle the favouriting value for the discussion provided
1112 *
309e8698
P
1113 * @param int $discussionid The discussion we need to favourite
1114 * @param bool $targetstate The state of the favourite value
1115 * @return array The exported discussion
1116 */
8885cd57 1117 public static function toggle_favourite_state($discussionid, $targetstate) {
99bda8a7
P
1118 global $DB, $PAGE, $USER;
1119
1120 $params = self::validate_parameters(self::toggle_favourite_state_parameters(), [
99bda8a7
P
1121 'discussionid' => $discussionid,
1122 'targetstate' => $targetstate
1123 ]);
1124
1125 $vaultfactory = mod_forum\local\container::get_vault_factory();
8885cd57
P
1126 // Get the discussion vault and the corresponding discussion entity.
1127 $discussionvault = $vaultfactory->get_discussion_vault();
1128 $discussion = $discussionvault->get_from_id($params['discussionid']);
1129
99bda8a7 1130 $forumvault = $vaultfactory->get_forum_vault();
8885cd57 1131 $forum = $forumvault->get_from_id($discussion->get_forum_id());
99bda8a7 1132 $forumcontext = $forum->get_context();
99bda8a7
P
1133 self::validate_context($forumcontext);
1134
1135 $managerfactory = mod_forum\local\container::get_manager_factory();
1136 $capabilitymanager = $managerfactory->get_capability_manager($forum);
1137
99bda8a7
P
1138 // Does the user have the ability to favourite the discussion?
1139 if (!$capabilitymanager->can_favourite_discussion($USER, $discussion)) {
1140 throw new moodle_exception('cannotfavourite', 'forum');
1141 }
d3cac88d 1142 $usercontext = context_user::instance($USER->id);
99bda8a7
P
1143 $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1144 $isfavourited = $ufservice->favourite_exists('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1145
1146 $favouritefunction = $targetstate ? 'create_favourite' : 'delete_favourite';
1147 if ($isfavourited != (bool) $params['targetstate']) {
1148 $ufservice->{$favouritefunction}('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1149 }
1150
1151 $exporterfactory = mod_forum\local\container::get_exporter_factory();
13cd05ac
P
1152 $builder = mod_forum\local\container::get_builder_factory()->get_exported_discussion_builder();
1153 $favourited = ($builder->is_favourited($discussion, $forumcontext, $USER) ? [$discussion->get_id()] : []);
1154 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion, [], $favourited);
99bda8a7
P
1155 return $exporter->export($PAGE->get_renderer('mod_forum'));
1156 }
1157
1158 /**
1159 * Returns description of method result value
1160 *
1161 * @return external_description
1162 * @since Moodle 3.0
1163 */
1164 public static function toggle_favourite_state_returns() {
1165 return discussion_exporter::get_read_structure();
1166 }
1167
309e8698
P
1168 /**
1169 * Defines the parameters for the toggle_favourite_state method
1170 *
1171 * @return external_function_parameters
1172 */
897ac0de 1173 public static function toggle_favourite_state_parameters() {
99bda8a7
P
1174 return new external_function_parameters(
1175 [
99bda8a7
P
1176 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1177 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1178 ]
1179 );
1180 }
1181
7ab43ac8
JL
1182 /**
1183 * Returns description of method parameters
1184 *
1185 * @return external_function_parameters
1186 * @since Moodle 3.0
1187 */
1188 public static function add_discussion_parameters() {
1189 return new external_function_parameters(
1190 array(
7267daa8
AN
1191 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1192 'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
1193 'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
aa9059b9 1194 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
7ab43ac8
JL
1195 'options' => new external_multiple_structure (
1196 new external_single_structure(
1197 array(
1198 'name' => new external_value(PARAM_ALPHANUM,
1199 'The allowed keys (value format) are:
1200 discussionsubscribe (bool); subscribe to the discussion?, default to true
5f219cf1 1201 discussionpinned (bool); is the discussion pinned, default to false
48143990 1202 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 1203 attachmentsid (int); the draft file area id for attachments
7ab43ac8 1204 '),
7267daa8
AN
1205 'value' => new external_value(PARAM_RAW, 'The value of the option,
1206 This param is validated in the external function.'
7ab43ac8
JL
1207 )
1208 )
1209 ), 'Options', VALUE_DEFAULT, array())
1210 )
1211 );
1212 }
1213
1214 /**
1215 * Add a new discussion into an existing forum.
1216 *
1217 * @param int $forumid the forum instance id
1218 * @param string $subject new discussion subject
1219 * @param string $message new discussion message (only html format allowed)
1220 * @param int $groupid the user course group
1221 * @param array $options optional settings
1222 * @return array of warnings and the new discussion id
1223 * @since Moodle 3.0
1224 * @throws moodle_exception
1225 */
aa9059b9 1226 public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
7ab43ac8
JL
1227 global $DB, $CFG;
1228 require_once($CFG->dirroot . "/mod/forum/lib.php");
1229
1230 $params = self::validate_parameters(self::add_discussion_parameters(),
1231 array(
1232 'forumid' => $forumid,
1233 'subject' => $subject,
1234 'message' => $message,
1235 'groupid' => $groupid,
1236 'options' => $options
1237 ));
609a1073
JL
1238
1239 $warnings = array();
1240
1241 // Request and permission validation.
1242 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1243 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1244
1245 $context = context_module::instance($cm->id);
1246 self::validate_context($context);
1247
7ab43ac8
JL
1248 // Validate options.
1249 $options = array(
5f219cf1 1250 'discussionsubscribe' => true,
41182118 1251 'discussionpinned' => false,
48143990 1252 'inlineattachmentsid' => 0,
e881c4f5 1253 'attachmentsid' => null
7ab43ac8
JL
1254 );
1255 foreach ($params['options'] as $option) {
1256 $name = trim($option['name']);
1257 switch ($name) {
1258 case 'discussionsubscribe':
1259 $value = clean_param($option['value'], PARAM_BOOL);
1260 break;
5f219cf1
BK
1261 case 'discussionpinned':
1262 $value = clean_param($option['value'], PARAM_BOOL);
1263 break;
48143990 1264 case 'inlineattachmentsid':
41182118
BK
1265 $value = clean_param($option['value'], PARAM_INT);
1266 break;
e881c4f5
BK
1267 case 'attachmentsid':
1268 $value = clean_param($option['value'], PARAM_INT);
609a1073
JL
1269 // Ensure that the user has permissions to create attachments.
1270 if (!has_capability('mod/forum:createattachment', $context)) {
1271 $value = 0;
1272 }
e881c4f5 1273 break;
7ab43ac8
JL
1274 default:
1275 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1276 }
1277 $options[$name] = $value;
1278 }
1279
7ab43ac8
JL
1280 // Normalize group.
1281 if (!groups_get_activity_groupmode($cm)) {
1282 // Groups not supported, force to -1.
1283 $groupid = -1;
1284 } else {
1285 // Check if we receive the default or and empty value for groupid,
1286 // in this case, get the group for the user in the activity.
aa9059b9 1287 if (empty($params['groupid'])) {
7ab43ac8
JL
1288 $groupid = groups_get_activity_group($cm);
1289 } else {
1290 // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
1291 $groupid = $params['groupid'];
1292 }
1293 }
1294
1295 if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
1296 throw new moodle_exception('cannotcreatediscussion', 'forum');
1297 }
1298
1299 $thresholdwarning = forum_check_throttling($forum, $cm);
1300 forum_check_blocking_threshold($thresholdwarning);
1301
1302 // Create the discussion.
1303 $discussion = new stdClass();
1304 $discussion->course = $course->id;
1305 $discussion->forum = $forum->id;
1306 $discussion->message = $params['message'];
1307 $discussion->messageformat = FORMAT_HTML; // Force formatting for now.
1308 $discussion->messagetrust = trusttext_trusted($context);
48143990 1309 $discussion->itemid = $options['inlineattachmentsid'];
7ab43ac8
JL
1310 $discussion->groupid = $groupid;
1311 $discussion->mailnow = 0;
1312 $discussion->subject = $params['subject'];
1313 $discussion->name = $discussion->subject;
1314 $discussion->timestart = 0;
1315 $discussion->timeend = 0;
2893812e 1316 $discussion->timelocked = 0;
e881c4f5
BK
1317 $discussion->attachments = $options['attachmentsid'];
1318
5f219cf1
BK
1319 if (has_capability('mod/forum:pindiscussions', $context) && $options['discussionpinned']) {
1320 $discussion->pinned = FORUM_DISCUSSION_PINNED;
1321 } else {
1322 $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
1323 }
e881c4f5
BK
1324 $fakemform = $options['attachmentsid'];
1325 if ($discussionid = forum_add_discussion($discussion, $fakemform)) {
7ab43ac8
JL
1326
1327 $discussion->id = $discussionid;
1328
1329 // Trigger events and completion.
1330
1331 $params = array(
1332 'context' => $context,
1333 'objectid' => $discussion->id,
1334 'other' => array(
1335 'forumid' => $forum->id,
1336 )
1337 );
1338 $event = \mod_forum\event\discussion_created::create($params);
1339 $event->add_record_snapshot('forum_discussions', $discussion);
1340 $event->trigger();
1341
1342 $completion = new completion_info($course);
1343 if ($completion->is_enabled($cm) &&
1344 ($forum->completiondiscussions || $forum->completionposts)) {
1345 $completion->update_state($cm, COMPLETION_COMPLETE);
1346 }
1347
1348 $settings = new stdClass();
1349 $settings->discussionsubscribe = $options['discussionsubscribe'];
1350 forum_post_subscription($settings, $forum, $discussion);
1351 } else {
1352 throw new moodle_exception('couldnotadd', 'forum');
1353 }
1354
1355 $result = array();
1356 $result['discussionid'] = $discussionid;
1357 $result['warnings'] = $warnings;
1358 return $result;
1359 }
1360
1361 /**
1362 * Returns description of method result value
1363 *
1364 * @return external_description
1365 * @since Moodle 3.0
1366 */
1367 public static function add_discussion_returns() {
1368 return new external_single_structure(
1369 array(
7267daa8 1370 'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
7ab43ac8
JL
1371 'warnings' => new external_warnings()
1372 )
1373 );
1374 }
1375
04cd8ae3
JL
1376 /**
1377 * Returns description of method parameters
1378 *
1379 * @return external_function_parameters
1380 * @since Moodle 3.1
1381 */
1382 public static function can_add_discussion_parameters() {
1383 return new external_function_parameters(
1384 array(
1385 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1386 'groupid' => new external_value(PARAM_INT, 'The group to check, default to active group.
1387 Use -1 to check if the user can post in all the groups.', VALUE_DEFAULT, null)
1388 )
1389 );
1390 }
1391
1392 /**
1393 * Check if the current user can add discussions in the given forum (and optionally for the given group).
1394 *
1395 * @param int $forumid the forum instance id
1396 * @param int $groupid the group to check, default to active group. Use -1 to check if the user can post in all the groups.
1397 * @return array of warnings and the status (true if the user can add discussions)
1398 * @since Moodle 3.1
1399 * @throws moodle_exception
1400 */
1401 public static function can_add_discussion($forumid, $groupid = null) {
1402 global $DB, $CFG;
1403 require_once($CFG->dirroot . "/mod/forum/lib.php");
1404
1405 $params = self::validate_parameters(self::can_add_discussion_parameters(),
1406 array(
1407 'forumid' => $forumid,
1408 'groupid' => $groupid,
1409 ));
1410 $warnings = array();
1411
1412 // Request and permission validation.
1413 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1414 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1415
1416 $context = context_module::instance($cm->id);
1417 self::validate_context($context);
1418
1419 $status = forum_user_can_post_discussion($forum, $params['groupid'], -1, $cm, $context);
1420
1421 $result = array();
1422 $result['status'] = $status;
581e75bf
JL
1423 $result['canpindiscussions'] = has_capability('mod/forum:pindiscussions', $context);
1424 $result['cancreateattachment'] = forum_can_create_attachment($forum, $context);
04cd8ae3
JL
1425 $result['warnings'] = $warnings;
1426 return $result;
1427 }
1428
1429 /**
1430 * Returns description of method result value
1431 *
1432 * @return external_description
1433 * @since Moodle 3.1
1434 */
1435 public static function can_add_discussion_returns() {
1436 return new external_single_structure(
1437 array(
1438 'status' => new external_value(PARAM_BOOL, 'True if the user can add discussions, false otherwise.'),
581e75bf
JL
1439 'canpindiscussions' => new external_value(PARAM_BOOL, 'True if the user can pin discussions, false otherwise.',
1440 VALUE_OPTIONAL),
1441 'cancreateattachment' => new external_value(PARAM_BOOL, 'True if the user can add attachments, false otherwise.',
1442 VALUE_OPTIONAL),
04cd8ae3
JL
1443 'warnings' => new external_warnings()
1444 )
1445 );
1446 }
1447
4daa0d08
JL
1448 /**
1449 * Describes the parameters for get_forum_access_information.
1450 *
1451 * @return external_external_function_parameters
1452 * @since Moodle 3.7
1453 */
1454 public static function get_forum_access_information_parameters() {
1455 return new external_function_parameters (
1456 array(
1457 'forumid' => new external_value(PARAM_INT, 'Forum instance id.')
1458 )
1459 );
1460 }
1461
1462 /**
1463 * Return access information for a given forum.
1464 *
1465 * @param int $forumid forum instance id
1466 * @return array of warnings and the access information
1467 * @since Moodle 3.7
1468 * @throws moodle_exception
1469 */
1470 public static function get_forum_access_information($forumid) {
1471 global $DB;
1472
1473 $params = self::validate_parameters(self::get_forum_access_information_parameters(), array('forumid' => $forumid));
1474
1475 // Request and permission validation.
1476 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1477 $cm = get_coursemodule_from_instance('forum', $forum->id);
1478
1479 $context = context_module::instance($cm->id);
1480 self::validate_context($context);
1481
1482 $result = array();
1483 // Return all the available capabilities.
1484 $capabilities = load_capability_def('mod_forum');
1485 foreach ($capabilities as $capname => $capdata) {
1486 // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1487 $field = 'can' . str_replace('mod/forum:', '', $capname);
1488 $result[$field] = has_capability($capname, $context);
1489 }
1490
1491 $result['warnings'] = array();
1492 return $result;
1493 }
1494
1495 /**
1496 * Describes the get_forum_access_information return value.
1497 *
1498 * @return external_single_structure
1499 * @since Moodle 3.7
1500 */
1501 public static function get_forum_access_information_returns() {
1502
1503 $structure = array(
1504 'warnings' => new external_warnings()
1505 );
1506
1507 $capabilities = load_capability_def('mod_forum');
1508 foreach ($capabilities as $capname => $capdata) {
1509 // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1510 $field = 'can' . str_replace('mod/forum:', '', $capname);
1511 $structure[$field] = new external_value(PARAM_BOOL, 'Whether the user has the capability ' . $capname . ' allowed.',
1512 VALUE_OPTIONAL);
1513 }
1514
1515 return new external_single_structure($structure);
1516 }
2646e9d6
RW
1517
1518 /**
1519 * Set the subscription state.
1520 *
1521 * @param int $forumid
1522 * @param int $discussionid
1523 * @param bool $targetstate
1524 * @return \stdClass
1525 */
1526 public static function set_subscription_state($forumid, $discussionid, $targetstate) {
f30f46db 1527 global $PAGE, $USER;
2646e9d6
RW
1528
1529 $params = self::validate_parameters(self::set_subscription_state_parameters(), [
1530 'forumid' => $forumid,
1531 'discussionid' => $discussionid,
1532 'targetstate' => $targetstate
1533 ]);
1534
1535 $vaultfactory = mod_forum\local\container::get_vault_factory();
1536 $forumvault = $vaultfactory->get_forum_vault();
1537 $forum = $forumvault->get_from_id($params['forumid']);
2646e9d6 1538 $coursemodule = $forum->get_course_module_record();
96a49734 1539 $context = $forum->get_context();
2646e9d6 1540
96a49734 1541 self::validate_context($context);
2646e9d6 1542
2646e9d6
RW
1543 $discussionvault = $vaultfactory->get_discussion_vault();
1544 $discussion = $discussionvault->get_from_id($params['discussionid']);
1545 $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1546
1547 $forumrecord = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
1548 $discussionrecord = $legacydatamapperfactory->get_discussion_data_mapper()->to_legacy_object($discussion);
1549
1550 if (!\mod_forum\subscriptions::is_subscribable($forumrecord)) {
1551 // Nothing to do. We won't actually output any content here though.
1552 throw new \moodle_exception('cannotsubscribe', 'mod_forum');
1553 }
1554
1555 $issubscribed = \mod_forum\subscriptions::is_subscribed(
1556 $USER->id,
1557 $forumrecord,
1558 $discussion->get_id(),
1559 $coursemodule
1560 );
1561
1562 // If the current state doesn't equal the desired state then update the current
1563 // state to the desired state.
1564 if ($issubscribed != (bool) $params['targetstate']) {
1565 if ($params['targetstate']) {
1566 \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussionrecord, $context);
1567 } else {
1568 \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussionrecord, $context);
1569 }
1570 }
1571
1572 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1573 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1574 return $exporter->export($PAGE->get_renderer('mod_forum'));
1575 }
1576
1577 /**
1578 * Returns description of method parameters.
1579 *
1580 * @return external_function_parameters
1581 */
1582 public static function set_subscription_state_parameters() {
1583 return new external_function_parameters(
1584 [
1585 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1586 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1587 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1588 ]
1589 );
1590 }
1591
1592 /**
1593 * Returns description of method result value.
1594 *
1595 * @return external_description
1596 */
1597 public static function set_subscription_state_returns() {
8885cd57 1598 return discussion_exporter::get_read_structure();
2646e9d6 1599 }
2893812e 1600
2893812e
P
1601 /**
1602 * Set the lock state.
1603 *
1604 * @param int $forumid
1605 * @param int $discussionid
1606 * @param string $targetstate
1607 * @return \stdClass
1608 */
1609 public static function set_lock_state($forumid, $discussionid, $targetstate) {
1610 global $DB, $PAGE, $USER;
1611
1612 $params = self::validate_parameters(self::set_lock_state_parameters(), [
1613 'forumid' => $forumid,
1614 'discussionid' => $discussionid,
1615 'targetstate' => $targetstate
1616 ]);
1617
1618 $vaultfactory = mod_forum\local\container::get_vault_factory();
1619 $forumvault = $vaultfactory->get_forum_vault();
1620 $forum = $forumvault->get_from_id($params['forumid']);
2893812e
P
1621
1622 $managerfactory = mod_forum\local\container::get_manager_factory();
1623 $capabilitymanager = $managerfactory->get_capability_manager($forum);
bdb4a87d
P
1624 if (!$capabilitymanager->can_manage_forum($USER)) {
1625 throw new moodle_exception('errorcannotlock', 'forum');
1626 }
1627
1628 // If the targetstate(currentstate) is not 0 then it should be set to the current time.
1629 $lockedvalue = $targetstate ? 0 : time();
1630 self::validate_context($forum->get_context());
1631
2893812e
P
1632 $discussionvault = $vaultfactory->get_discussion_vault();
1633 $discussion = $discussionvault->get_from_id($params['discussionid']);
2893812e 1634
c475fe41 1635 // If the current state doesn't equal the desired state then update the current.
2893812e 1636 // state to the desired state.
bdb4a87d
P
1637 $discussion->toggle_locked_state($lockedvalue);
1638 $response = $discussionvault->update_discussion($discussion);
1639 $discussion = !$response ? $response : $discussion;
a7260536 1640 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1641 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1642 return $exporter->export($PAGE->get_renderer('mod_forum'));
1643 }
1644
cda9da99
P
1645 /**
1646 * Returns description of method parameters.
1647 *
1648 * @return external_function_parameters
1649 */
1650 public static function set_lock_state_parameters() {
1651 return new external_function_parameters(
1652 [
1653 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1654 'discussionid' => new external_value(PARAM_INT, 'The discussion to lock / unlock'),
1655 'targetstate' => new external_value(PARAM_INT, 'The timestamp for the lock state')
1656 ]
1657 );
1658 }
1659
1660 /**
1661 * Returns description of method result value.
1662 *
1663 * @return external_description
1664 */
1665 public static function set_lock_state_returns() {
1666 return new external_single_structure([
1667 'id' => new external_value(PARAM_INT, 'The discussion we are locking.'),
1668 'locked' => new external_value(PARAM_BOOL, 'The locked state of the discussion.'),
1669 'times' => new external_single_structure([
1670 'locked' => new external_value(PARAM_INT, 'The locked time of the discussion.'),
1671 ])
1672 ]);
1673 }
1674
a7260536 1675 /**
1676 * Set the pin state.
1677 *
a7260536 1678 * @param int $discussionid
1679 * @param bool $targetstate
1680 * @return \stdClass
1681 */
8885cd57 1682 public static function set_pin_state($discussionid, $targetstate) {
a7260536 1683 global $PAGE, $USER;
1684 $params = self::validate_parameters(self::set_pin_state_parameters(), [
a7260536 1685 'discussionid' => $discussionid,
1686 'targetstate' => $targetstate,
1687 ]);
1688 $vaultfactory = mod_forum\local\container::get_vault_factory();
309e8698 1689 $managerfactory = mod_forum\local\container::get_manager_factory();
a7260536 1690 $forumvault = $vaultfactory->get_forum_vault();
1691 $discussionvault = $vaultfactory->get_discussion_vault();
8885cd57
P
1692 $discussion = $discussionvault->get_from_id($params['discussionid']);
1693 $forum = $forumvault->get_from_id($discussion->get_forum_id());
309e8698 1694 $capabilitymanager = $managerfactory->get_capability_manager($forum);
a7260536 1695
1696 self::validate_context($forum->get_context());
24962ee1
P
1697
1698 $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
309e8698 1699 if (!$capabilitymanager->can_pin_discussions($USER)) {
a7260536 1700 // Nothing to do. We won't actually output any content here though.
309e8698 1701 throw new \moodle_exception('cannotpindiscussions', 'mod_forum');
a7260536 1702 }
1703
a7260536 1704 $discussion->set_pinned($targetstate);
cda9da99 1705 $discussionvault->update_discussion($discussion);
2893812e
P
1706
1707 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1708 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1709 return $exporter->export($PAGE->get_renderer('mod_forum'));
1710 }
1711
a7260536 1712 /**
1713 * Returns description of method parameters.
1714 *
1715 * @return external_function_parameters
1716 */
1717 public static function set_pin_state_parameters() {
1718 return new external_function_parameters(
1719 [
309e8698
P
1720 'discussionid' => new external_value(PARAM_INT, 'The discussion to pin or unpin', VALUE_REQUIRED,
1721 null, NULL_NOT_ALLOWED),
1722 'targetstate' => new external_value(PARAM_INT, 'The target state', VALUE_REQUIRED,
1723 null, NULL_NOT_ALLOWED),
a7260536 1724 ]
1725 );
1726 }
1727
a7260536 1728 /**
1729 * Returns description of method result value.
1730 *
1731 * @return external_single_structure
1732 */
1733 public static function set_pin_state_returns() {
8885cd57 1734 return discussion_exporter::get_read_structure();
a7260536 1735 }
2b9fe87d 1736}