MDL-65033 mod_forum: Fix up the 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
039c81f0
JL
595 foreach ($alldiscussions as $discussion) {
596
7c51b40a 597 // This function checks for qanda forums.
039c81f0
JL
598 // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
599 $discussionrec = clone $discussion;
600 $discussionrec->id = $discussion->discussion;
601 if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
7c51b40a
JL
602 $warning = array();
603 // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
604 $warning['item'] = 'post';
605 $warning['itemid'] = $discussion->id;
606 $warning['warningcode'] = '1';
607 $warning['message'] = 'You can\'t see this discussion';
608 $warnings[] = $warning;
609 continue;
610 }
611
612 $discussion->numunread = 0;
613 if ($cantrack && $forumtracked) {
614 if (isset($unreads[$discussion->discussion])) {
615 $discussion->numunread = (int) $unreads[$discussion->discussion];
616 }
617 }
618
619 $discussion->numreplies = 0;
620 if (!empty($replies[$discussion->discussion])) {
621 $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
622 }
623
55bb8189
JL
624 $discussion->name = external_format_string($discussion->name, $modcontext->id);
625 $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
7c51b40a
JL
626 // Rewrite embedded images URLs.
627 list($discussion->message, $discussion->messageformat) =
628 external_format_text($discussion->message, $discussion->messageformat,
629 $modcontext->id, 'mod_forum', 'post', $discussion->id);
630
631 // List attachments.
632 if (!empty($discussion->attachment)) {
14590070
JL
633 $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
634 $discussion->id);
7c51b40a 635 }
c8743f62
JL
636 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
637 if (!empty($messageinlinefiles)) {
638 $discussion->messageinlinefiles = $messageinlinefiles;
639 }
7c51b40a 640
565cccfa
P
641 $discussion->locked = forum_discussion_is_locked($forum, $discussion);
642 $discussion->canlock = $canlock;
0f3bbfd4
AN
643 $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
644
30861fbd
JL
645 if (forum_is_author_hidden($discussion, $forum)) {
646 $discussion->userid = null;
647 $discussion->userfullname = null;
648 $discussion->userpictureurl = null;
649
650 $discussion->usermodified = null;
651 $discussion->usermodifiedfullname = null;
652 $discussion->usermodifiedpictureurl = null;
653 } else {
654 $picturefields = explode(',', user_picture::fields());
655
656 // Load user objects from the results of the query.
657 $user = new stdclass();
658 $user->id = $discussion->userid;
659 $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
660 // Preserve the id, it can be modified by username_load_fields_from_object.
661 $user->id = $discussion->userid;
662 $discussion->userfullname = fullname($user, $canviewfullname);
663
664 $userpicture = new user_picture($user);
665 $userpicture->size = 1; // Size f1.
666 $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
667
668 $usermodified = new stdclass();
669 $usermodified->id = $discussion->usermodified;
670 $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
671 // Preserve the id (it can be overwritten due to the prefixed $picturefields).
672 $usermodified->id = $discussion->usermodified;
673 $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
674
675 $userpicture = new user_picture($usermodified);
676 $userpicture->size = 1; // Size f1.
677 $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
678 }
679
039c81f0 680 $discussions[] = $discussion;
7c51b40a
JL
681 }
682 }
683
684 $result = array();
685 $result['discussions'] = $discussions;
686 $result['warnings'] = $warnings;
687 return $result;
688
689 }
690
691 /**
692 * Describes the get_forum_discussions_paginated return value.
693 *
694 * @return external_single_structure
695 * @since Moodle 2.8
696 */
697 public static function get_forum_discussions_paginated_returns() {
698 return new external_single_structure(
699 array(
700 'discussions' => new external_multiple_structure(
701 new external_single_structure(
702 array(
703 'id' => new external_value(PARAM_INT, 'Post id'),
704 'name' => new external_value(PARAM_TEXT, 'Discussion name'),
705 'groupid' => new external_value(PARAM_INT, 'Group id'),
706 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
707 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
708 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
709 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
710 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
711 'parent' => new external_value(PARAM_INT, 'Parent id'),
712 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
713 'created' => new external_value(PARAM_INT, 'Creation time'),
714 'modified' => new external_value(PARAM_INT, 'Time modified'),
715 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
716 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
717 'message' => new external_value(PARAM_RAW, 'The post message'),
718 'messageformat' => new external_format_value('message'),
719 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
c8743f62 720 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
7c51b40a 721 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
14590070 722 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
7c51b40a
JL
723 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
724 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
725 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
726 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
727 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
728 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
729 'numreplies' => new external_value(PARAM_TEXT, 'The number of replies in the discussion'),
5f219cf1 730 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
0f3bbfd4
AN
731 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
732 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
733 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
565cccfa 734 'canlock' => new external_value(PARAM_BOOL, 'Can the user lock the discussion'),
7c51b40a
JL
735 ), 'post'
736 )
737 ),
738 'warnings' => new external_warnings()
739 )
740 );
741 }
742
4a1e44a1
JL
743 /**
744 * Returns description of method parameters
745 *
746 * @return external_function_parameters
747 * @since Moodle 2.9
748 */
749 public static function view_forum_parameters() {
750 return new external_function_parameters(
751 array(
752 'forumid' => new external_value(PARAM_INT, 'forum instance id')
753 )
754 );
755 }
756
757 /**
1c2b7882 758 * Trigger the course module viewed event and update the module completion status.
4a1e44a1
JL
759 *
760 * @param int $forumid the forum instance id
761 * @return array of warnings and status result
762 * @since Moodle 2.9
763 * @throws moodle_exception
764 */
765 public static function view_forum($forumid) {
766 global $DB, $CFG;
767 require_once($CFG->dirroot . "/mod/forum/lib.php");
768
769 $params = self::validate_parameters(self::view_forum_parameters(),
770 array(
771 'forumid' => $forumid
772 ));
773 $warnings = array();
774
775 // Request and permission validation.
ca7e2fc2 776 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
4a1e44a1
JL
777 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
778
779 $context = context_module::instance($cm->id);
780 self::validate_context($context);
781
ea2fa324
JL
782 require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
783
4a1e44a1
JL
784 // Call the forum/lib API.
785 forum_view($forum, $course, $cm, $context);
786
787 $result = array();
788 $result['status'] = true;
789 $result['warnings'] = $warnings;
790 return $result;
791 }
792
793 /**
794 * Returns description of method result value
795 *
796 * @return external_description
797 * @since Moodle 2.9
798 */
799 public static function view_forum_returns() {
800 return new external_single_structure(
801 array(
802 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
803 'warnings' => new external_warnings()
804 )
805 );
806 }
807
a3c315dd
JL
808 /**
809 * Returns description of method parameters
810 *
811 * @return external_function_parameters
812 * @since Moodle 2.9
813 */
814 public static function view_forum_discussion_parameters() {
815 return new external_function_parameters(
816 array(
817 'discussionid' => new external_value(PARAM_INT, 'discussion id')
818 )
819 );
820 }
821
822 /**
1c2b7882 823 * Trigger the discussion viewed event.
a3c315dd
JL
824 *
825 * @param int $discussionid the discussion id
826 * @return array of warnings and status result
827 * @since Moodle 2.9
828 * @throws moodle_exception
829 */
830 public static function view_forum_discussion($discussionid) {
db3c9ff8 831 global $DB, $CFG, $USER;
a3c315dd
JL
832 require_once($CFG->dirroot . "/mod/forum/lib.php");
833
834 $params = self::validate_parameters(self::view_forum_discussion_parameters(),
835 array(
836 'discussionid' => $discussionid
837 ));
838 $warnings = array();
839
840 $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
841 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
842 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
843
844 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
845 $modcontext = context_module::instance($cm->id);
846 self::validate_context($modcontext);
847
ea2fa324
JL
848 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
849
a3c315dd
JL
850 // Call the forum/lib API.
851 forum_discussion_view($modcontext, $forum, $discussion);
852
db3c9ff8
PFO
853 // Mark as read if required.
854 if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
855 forum_tp_mark_discussion_read($USER, $discussion->id);
856 }
857
a3c315dd
JL
858 $result = array();
859 $result['status'] = true;
860 $result['warnings'] = $warnings;
861 return $result;
862 }
863
864 /**
865 * Returns description of method result value
866 *
867 * @return external_description
868 * @since Moodle 2.9
869 */
870 public static function view_forum_discussion_returns() {
871 return new external_single_structure(
872 array(
873 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
874 'warnings' => new external_warnings()
875 )
876 );
877 }
878
50a20317
JL
879 /**
880 * Returns description of method parameters
881 *
882 * @return external_function_parameters
883 * @since Moodle 3.0
884 */
885 public static function add_discussion_post_parameters() {
886 return new external_function_parameters(
887 array(
888 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
889 (can be the initial discussion post'),
890 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
891 'message' => new external_value(PARAM_RAW, 'new post message (only html format allowed)'),
892 'options' => new external_multiple_structure (
893 new external_single_structure(
894 array(
895 'name' => new external_value(PARAM_ALPHANUM,
896 'The allowed keys (value format) are:
897 discussionsubscribe (bool); subscribe to the discussion?, default to true
bc4c7337 898 private (bool); make this reply private to the author of the parent post, default to false.
48143990 899 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 900 attachmentsid (int); the draft file area id for attachments
50a20317
JL
901 '),
902 'value' => new external_value(PARAM_RAW, 'the value of the option,
903 this param is validated in the external function.'
904 )
905 )
906 ), 'Options', VALUE_DEFAULT, array())
907 )
908 );
909 }
910
911 /**
912 * Create new posts into an existing discussion.
913 *
914 * @param int $postid the post id we are going to reply to
915 * @param string $subject new post subject
916 * @param string $message new post message (only html format allowed)
917 * @param array $options optional settings
918 * @return array of warnings and the new post id
919 * @since Moodle 3.0
920 * @throws moodle_exception
921 */
922 public static function add_discussion_post($postid, $subject, $message, $options = array()) {
a0c9b6af 923 global $CFG, $USER;
50a20317
JL
924 require_once($CFG->dirroot . "/mod/forum/lib.php");
925
9b4f09ba
P
926 // Get all the factories that are required.
927 $vaultfactory = mod_forum\local\container::get_vault_factory();
928 $entityfactory = mod_forum\local\container::get_entity_factory();
929 $datamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
930 $managerfactory = mod_forum\local\container::get_manager_factory();
931 $discussionvault = $vaultfactory->get_discussion_vault();
932 $forumvault = $vaultfactory->get_forum_vault();
933 $discussiondatamapper = $datamapperfactory->get_discussion_data_mapper();
934 $forumdatamapper = $datamapperfactory->get_forum_data_mapper();
935
50a20317 936 $params = self::validate_parameters(self::add_discussion_post_parameters(),
609a1073
JL
937 array(
938 'postid' => $postid,
939 'subject' => $subject,
940 'message' => $message,
941 'options' => $options
942 )
943 );
bc4c7337 944
609a1073
JL
945 $warnings = array();
946
947 if (!$parent = forum_get_post_full($params['postid'])) {
948 throw new moodle_exception('invalidparentpostid', 'forum');
949 }
950
9b4f09ba 951 if (!$discussion = $discussionvault->get_from_id($parent->discussion)) {
609a1073
JL
952 throw new moodle_exception('notpartofdiscussion', 'forum');
953 }
954
955 // Request and permission validation.
9b4f09ba
P
956 $forum = $forumvault->get_from_id($discussion->get_forum_id());
957 $capabilitymanager = $managerfactory->get_capability_manager($forum);
958 $course = $forum->get_course_record();
959 $cm = $forum->get_course_module_record();
609a1073 960
9b4f09ba
P
961 $discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
962 $forumrecord = $forumdatamapper->to_legacy_object($forum);
609a1073
JL
963 $context = context_module::instance($cm->id);
964 self::validate_context($context);
965
50a20317
JL
966 // Validate options.
967 $options = array(
41182118 968 'discussionsubscribe' => true,
bc4c7337 969 'private' => false,
48143990 970 'inlineattachmentsid' => 0,
e881c4f5 971 'attachmentsid' => null
50a20317
JL
972 );
973 foreach ($params['options'] as $option) {
974 $name = trim($option['name']);
975 switch ($name) {
976 case 'discussionsubscribe':
977 $value = clean_param($option['value'], PARAM_BOOL);
978 break;
bc4c7337
AN
979 case 'private':
980 $value = clean_param($option['value'], PARAM_BOOL);
981 break;
48143990 982 case 'inlineattachmentsid':
41182118
BK
983 $value = clean_param($option['value'], PARAM_INT);
984 break;
e881c4f5
BK
985 case 'attachmentsid':
986 $value = clean_param($option['value'], PARAM_INT);
609a1073
JL
987 // Ensure that the user has permissions to create attachments.
988 if (!has_capability('mod/forum:createattachment', $context)) {
989 $value = 0;
990 }
e881c4f5 991 break;
50a20317
JL
992 default:
993 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
994 }
995 $options[$name] = $value;
996 }
997
9b4f09ba 998 if (!$capabilitymanager->can_post_in_discussion($USER, $discussion)) {
50a20317
JL
999 throw new moodle_exception('nopostforum', 'forum');
1000 }
1001
9b4f09ba 1002 $thresholdwarning = forum_check_throttling($forumrecord, $cm);
50a20317
JL
1003 forum_check_blocking_threshold($thresholdwarning);
1004
1005 // Create the post.
1006 $post = new stdClass();
9b4f09ba 1007 $post->discussion = $discussion->get_id();
50a20317
JL
1008 $post->parent = $parent->id;
1009 $post->subject = $params['subject'];
1010 $post->message = $params['message'];
1011 $post->messageformat = FORMAT_HTML; // Force formatting for now.
1012 $post->messagetrust = trusttext_trusted($context);
48143990 1013 $post->itemid = $options['inlineattachmentsid'];
3e95e09b 1014 $post->attachments = $options['attachmentsid'];
bc4c7337 1015 $post->isprivatereply = $options['private'];
3e95e09b 1016 $post->deleted = 0;
e881c4f5
BK
1017 $fakemform = $post->attachments;
1018 if ($postid = forum_add_new_post($post, $fakemform)) {
50a20317
JL
1019
1020 $post->id = $postid;
1021
1022 // Trigger events and completion.
1023 $params = array(
1024 'context' => $context,
1025 'objectid' => $post->id,
1026 'other' => array(
9b4f09ba
P
1027 'discussionid' => $discussion->get_id(),
1028 'forumid' => $forum->get_id(),
1029 'forumtype' => $forum->get_type(),
50a20317
JL
1030 )
1031 );
1032 $event = \mod_forum\event\post_created::create($params);
1033 $event->add_record_snapshot('forum_posts', $post);
9b4f09ba 1034 $event->add_record_snapshot('forum_discussions', $discussionrecord);
50a20317
JL
1035 $event->trigger();
1036
1037 // Update completion state.
1038 $completion = new completion_info($course);
1039 if ($completion->is_enabled($cm) &&
9b4f09ba 1040 ($forum->get_completion_replies() || $forum->get_completion_posts())) {
50a20317
JL
1041 $completion->update_state($cm, COMPLETION_COMPLETE);
1042 }
1043
1044 $settings = new stdClass();
1045 $settings->discussionsubscribe = $options['discussionsubscribe'];
9b4f09ba 1046 forum_post_subscription($settings, $forumrecord, $discussionrecord);
50a20317
JL
1047 } else {
1048 throw new moodle_exception('couldnotadd', 'forum');
1049 }
1050
9b4f09ba
P
1051 $builderfactory = \mod_forum\local\container::get_builder_factory();
1052 $exportedpostsbuilder = $builderfactory->get_exported_posts_builder();
1053 $postentity = $entityfactory->get_post_from_stdClass($post);
1054 $exportedposts = $exportedpostsbuilder->build($USER, [$forum], [$discussion], [$postentity]);
1055 $exportedpost = $exportedposts[0];
1056
a0c9b6af
P
1057 $message = [];
1058 $message[] = [
1059 'type' => 'success',
1060 'message' => get_string("postaddedsuccess", "forum")
1061 ];
1062
1063 $message[] = [
1064 'type' => 'success',
1065 'message' => get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime))
1066 ];
1067
50a20317
JL
1068 $result = array();
1069 $result['postid'] = $postid;
1070 $result['warnings'] = $warnings;
9b4f09ba 1071 $result['post'] = $exportedpost;
a0c9b6af 1072 $result['messages'] = $message;
50a20317
JL
1073 return $result;
1074 }
1075
1076 /**
1077 * Returns description of method result value
1078 *
1079 * @return external_description
1080 * @since Moodle 3.0
1081 */
1082 public static function add_discussion_post_returns() {
1083 return new external_single_structure(
1084 array(
1085 'postid' => new external_value(PARAM_INT, 'new post id'),
9b4f09ba 1086 'warnings' => new external_warnings(),
a0c9b6af
P
1087 'post' => post_exporter::get_read_structure(),
1088 'messages' => new external_multiple_structure(
1089 new external_single_structure(
1090 array(
1091 'type' => new external_value(PARAM_TEXT, "The classification to be used in the client side", VALUE_REQUIRED),
1092 'message' => new external_value(PARAM_TEXT,'untranslated english message to explain the warning', VALUE_REQUIRED)
1093 ), 'Messages'), 'list of warnings', VALUE_OPTIONAL
1094 ),
1095 //'alertmessage' => new external_value(PARAM_RAW, 'Success message to be displayed to the user.'),
50a20317
JL
1096 )
1097 );
1098 }
1099
99bda8a7
P
1100 public static function toggle_favourite_state($forumid, $discussionid, $targetstate) {
1101 global $DB, $PAGE, $USER;
1102
1103 $params = self::validate_parameters(self::toggle_favourite_state_parameters(), [
1104 'forumid' => $forumid,
1105 'discussionid' => $discussionid,
1106 'targetstate' => $targetstate
1107 ]);
1108
1109 $vaultfactory = mod_forum\local\container::get_vault_factory();
1110 $forumvault = $vaultfactory->get_forum_vault();
1111 $forum = $forumvault->get_from_id($params['forumid']);
1112 $forumcontext = $forum->get_context();
1113 $usercontext = context_user::instance($USER->id);
1114
1115 self::validate_context($forumcontext);
1116
1117 $managerfactory = mod_forum\local\container::get_manager_factory();
1118 $capabilitymanager = $managerfactory->get_capability_manager($forum);
1119
1120 // Get the discussion vault and the corresponding discussion entity.
1121 $discussionvault = $vaultfactory->get_discussion_vault();
1122 $discussion = $discussionvault->get_from_id($params['discussionid']);
1123
1124 // Does the user have the ability to favourite the discussion?
1125 if (!$capabilitymanager->can_favourite_discussion($USER, $discussion)) {
1126 throw new moodle_exception('cannotfavourite', 'forum');
1127 }
1128
1129 $ufservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
1130 $isfavourited = $ufservice->favourite_exists('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1131
1132 $favouritefunction = $targetstate ? 'create_favourite' : 'delete_favourite';
1133 if ($isfavourited != (bool) $params['targetstate']) {
1134 $ufservice->{$favouritefunction}('mod_forum', 'discussions', $discussion->get_id(), $forumcontext);
1135 }
1136
1137 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1138 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1139 return $exporter->export($PAGE->get_renderer('mod_forum'));
1140 }
1141
1142 /**
1143 * Returns description of method result value
1144 *
1145 * @return external_description
1146 * @since Moodle 3.0
1147 */
1148 public static function toggle_favourite_state_returns() {
1149 return discussion_exporter::get_read_structure();
1150 }
1151
897ac0de 1152 public static function toggle_favourite_state_parameters() {
99bda8a7
P
1153 return new external_function_parameters(
1154 [
1155 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1156 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1157 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1158 ]
1159 );
1160 }
1161
7ab43ac8
JL
1162 /**
1163 * Returns description of method parameters
1164 *
1165 * @return external_function_parameters
1166 * @since Moodle 3.0
1167 */
1168 public static function add_discussion_parameters() {
1169 return new external_function_parameters(
1170 array(
7267daa8
AN
1171 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1172 'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
1173 'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
aa9059b9 1174 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
7ab43ac8
JL
1175 'options' => new external_multiple_structure (
1176 new external_single_structure(
1177 array(
1178 'name' => new external_value(PARAM_ALPHANUM,
1179 'The allowed keys (value format) are:
1180 discussionsubscribe (bool); subscribe to the discussion?, default to true
5f219cf1 1181 discussionpinned (bool); is the discussion pinned, default to false
48143990 1182 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 1183 attachmentsid (int); the draft file area id for attachments
7ab43ac8 1184 '),
7267daa8
AN
1185 'value' => new external_value(PARAM_RAW, 'The value of the option,
1186 This param is validated in the external function.'
7ab43ac8
JL
1187 )
1188 )
1189 ), 'Options', VALUE_DEFAULT, array())
1190 )
1191 );
1192 }
1193
1194 /**
1195 * Add a new discussion into an existing forum.
1196 *
1197 * @param int $forumid the forum instance id
1198 * @param string $subject new discussion subject
1199 * @param string $message new discussion message (only html format allowed)
1200 * @param int $groupid the user course group
1201 * @param array $options optional settings
1202 * @return array of warnings and the new discussion id
1203 * @since Moodle 3.0
1204 * @throws moodle_exception
1205 */
aa9059b9 1206 public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
7ab43ac8
JL
1207 global $DB, $CFG;
1208 require_once($CFG->dirroot . "/mod/forum/lib.php");
1209
1210 $params = self::validate_parameters(self::add_discussion_parameters(),
1211 array(
1212 'forumid' => $forumid,
1213 'subject' => $subject,
1214 'message' => $message,
1215 'groupid' => $groupid,
1216 'options' => $options
1217 ));
609a1073
JL
1218
1219 $warnings = array();
1220
1221 // Request and permission validation.
1222 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1223 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1224
1225 $context = context_module::instance($cm->id);
1226 self::validate_context($context);
1227
7ab43ac8
JL
1228 // Validate options.
1229 $options = array(
5f219cf1 1230 'discussionsubscribe' => true,
41182118 1231 'discussionpinned' => false,
48143990 1232 'inlineattachmentsid' => 0,
e881c4f5 1233 'attachmentsid' => null
7ab43ac8
JL
1234 );
1235 foreach ($params['options'] as $option) {
1236 $name = trim($option['name']);
1237 switch ($name) {
1238 case 'discussionsubscribe':
1239 $value = clean_param($option['value'], PARAM_BOOL);
1240 break;
5f219cf1
BK
1241 case 'discussionpinned':
1242 $value = clean_param($option['value'], PARAM_BOOL);
1243 break;
48143990 1244 case 'inlineattachmentsid':
41182118
BK
1245 $value = clean_param($option['value'], PARAM_INT);
1246 break;
e881c4f5
BK
1247 case 'attachmentsid':
1248 $value = clean_param($option['value'], PARAM_INT);
609a1073
JL
1249 // Ensure that the user has permissions to create attachments.
1250 if (!has_capability('mod/forum:createattachment', $context)) {
1251 $value = 0;
1252 }
e881c4f5 1253 break;
7ab43ac8
JL
1254 default:
1255 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
1256 }
1257 $options[$name] = $value;
1258 }
1259
7ab43ac8
JL
1260 // Normalize group.
1261 if (!groups_get_activity_groupmode($cm)) {
1262 // Groups not supported, force to -1.
1263 $groupid = -1;
1264 } else {
1265 // Check if we receive the default or and empty value for groupid,
1266 // in this case, get the group for the user in the activity.
aa9059b9 1267 if (empty($params['groupid'])) {
7ab43ac8
JL
1268 $groupid = groups_get_activity_group($cm);
1269 } else {
1270 // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
1271 $groupid = $params['groupid'];
1272 }
1273 }
1274
1275 if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
1276 throw new moodle_exception('cannotcreatediscussion', 'forum');
1277 }
1278
1279 $thresholdwarning = forum_check_throttling($forum, $cm);
1280 forum_check_blocking_threshold($thresholdwarning);
1281
1282 // Create the discussion.
1283 $discussion = new stdClass();
1284 $discussion->course = $course->id;
1285 $discussion->forum = $forum->id;
1286 $discussion->message = $params['message'];
1287 $discussion->messageformat = FORMAT_HTML; // Force formatting for now.
1288 $discussion->messagetrust = trusttext_trusted($context);
48143990 1289 $discussion->itemid = $options['inlineattachmentsid'];
7ab43ac8
JL
1290 $discussion->groupid = $groupid;
1291 $discussion->mailnow = 0;
1292 $discussion->subject = $params['subject'];
1293 $discussion->name = $discussion->subject;
1294 $discussion->timestart = 0;
1295 $discussion->timeend = 0;
2893812e 1296 $discussion->timelocked = 0;
e881c4f5
BK
1297 $discussion->attachments = $options['attachmentsid'];
1298
5f219cf1
BK
1299 if (has_capability('mod/forum:pindiscussions', $context) && $options['discussionpinned']) {
1300 $discussion->pinned = FORUM_DISCUSSION_PINNED;
1301 } else {
1302 $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
1303 }
e881c4f5
BK
1304 $fakemform = $options['attachmentsid'];
1305 if ($discussionid = forum_add_discussion($discussion, $fakemform)) {
7ab43ac8
JL
1306
1307 $discussion->id = $discussionid;
1308
1309 // Trigger events and completion.
1310
1311 $params = array(
1312 'context' => $context,
1313 'objectid' => $discussion->id,
1314 'other' => array(
1315 'forumid' => $forum->id,
1316 )
1317 );
1318 $event = \mod_forum\event\discussion_created::create($params);
1319 $event->add_record_snapshot('forum_discussions', $discussion);
1320 $event->trigger();
1321
1322 $completion = new completion_info($course);
1323 if ($completion->is_enabled($cm) &&
1324 ($forum->completiondiscussions || $forum->completionposts)) {
1325 $completion->update_state($cm, COMPLETION_COMPLETE);
1326 }
1327
1328 $settings = new stdClass();
1329 $settings->discussionsubscribe = $options['discussionsubscribe'];
1330 forum_post_subscription($settings, $forum, $discussion);
1331 } else {
1332 throw new moodle_exception('couldnotadd', 'forum');
1333 }
1334
1335 $result = array();
1336 $result['discussionid'] = $discussionid;
1337 $result['warnings'] = $warnings;
1338 return $result;
1339 }
1340
1341 /**
1342 * Returns description of method result value
1343 *
1344 * @return external_description
1345 * @since Moodle 3.0
1346 */
1347 public static function add_discussion_returns() {
1348 return new external_single_structure(
1349 array(
7267daa8 1350 'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
7ab43ac8
JL
1351 'warnings' => new external_warnings()
1352 )
1353 );
1354 }
1355
04cd8ae3
JL
1356 /**
1357 * Returns description of method parameters
1358 *
1359 * @return external_function_parameters
1360 * @since Moodle 3.1
1361 */
1362 public static function can_add_discussion_parameters() {
1363 return new external_function_parameters(
1364 array(
1365 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1366 'groupid' => new external_value(PARAM_INT, 'The group to check, default to active group.
1367 Use -1 to check if the user can post in all the groups.', VALUE_DEFAULT, null)
1368 )
1369 );
1370 }
1371
1372 /**
1373 * Check if the current user can add discussions in the given forum (and optionally for the given group).
1374 *
1375 * @param int $forumid the forum instance id
1376 * @param int $groupid the group to check, default to active group. Use -1 to check if the user can post in all the groups.
1377 * @return array of warnings and the status (true if the user can add discussions)
1378 * @since Moodle 3.1
1379 * @throws moodle_exception
1380 */
1381 public static function can_add_discussion($forumid, $groupid = null) {
1382 global $DB, $CFG;
1383 require_once($CFG->dirroot . "/mod/forum/lib.php");
1384
1385 $params = self::validate_parameters(self::can_add_discussion_parameters(),
1386 array(
1387 'forumid' => $forumid,
1388 'groupid' => $groupid,
1389 ));
1390 $warnings = array();
1391
1392 // Request and permission validation.
1393 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1394 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1395
1396 $context = context_module::instance($cm->id);
1397 self::validate_context($context);
1398
1399 $status = forum_user_can_post_discussion($forum, $params['groupid'], -1, $cm, $context);
1400
1401 $result = array();
1402 $result['status'] = $status;
581e75bf
JL
1403 $result['canpindiscussions'] = has_capability('mod/forum:pindiscussions', $context);
1404 $result['cancreateattachment'] = forum_can_create_attachment($forum, $context);
04cd8ae3
JL
1405 $result['warnings'] = $warnings;
1406 return $result;
1407 }
1408
1409 /**
1410 * Returns description of method result value
1411 *
1412 * @return external_description
1413 * @since Moodle 3.1
1414 */
1415 public static function can_add_discussion_returns() {
1416 return new external_single_structure(
1417 array(
1418 'status' => new external_value(PARAM_BOOL, 'True if the user can add discussions, false otherwise.'),
581e75bf
JL
1419 'canpindiscussions' => new external_value(PARAM_BOOL, 'True if the user can pin discussions, false otherwise.',
1420 VALUE_OPTIONAL),
1421 'cancreateattachment' => new external_value(PARAM_BOOL, 'True if the user can add attachments, false otherwise.',
1422 VALUE_OPTIONAL),
04cd8ae3
JL
1423 'warnings' => new external_warnings()
1424 )
1425 );
1426 }
1427
4daa0d08
JL
1428 /**
1429 * Describes the parameters for get_forum_access_information.
1430 *
1431 * @return external_external_function_parameters
1432 * @since Moodle 3.7
1433 */
1434 public static function get_forum_access_information_parameters() {
1435 return new external_function_parameters (
1436 array(
1437 'forumid' => new external_value(PARAM_INT, 'Forum instance id.')
1438 )
1439 );
1440 }
1441
1442 /**
1443 * Return access information for a given forum.
1444 *
1445 * @param int $forumid forum instance id
1446 * @return array of warnings and the access information
1447 * @since Moodle 3.7
1448 * @throws moodle_exception
1449 */
1450 public static function get_forum_access_information($forumid) {
1451 global $DB;
1452
1453 $params = self::validate_parameters(self::get_forum_access_information_parameters(), array('forumid' => $forumid));
1454
1455 // Request and permission validation.
1456 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1457 $cm = get_coursemodule_from_instance('forum', $forum->id);
1458
1459 $context = context_module::instance($cm->id);
1460 self::validate_context($context);
1461
1462 $result = array();
1463 // Return all the available capabilities.
1464 $capabilities = load_capability_def('mod_forum');
1465 foreach ($capabilities as $capname => $capdata) {
1466 // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1467 $field = 'can' . str_replace('mod/forum:', '', $capname);
1468 $result[$field] = has_capability($capname, $context);
1469 }
1470
1471 $result['warnings'] = array();
1472 return $result;
1473 }
1474
1475 /**
1476 * Describes the get_forum_access_information return value.
1477 *
1478 * @return external_single_structure
1479 * @since Moodle 3.7
1480 */
1481 public static function get_forum_access_information_returns() {
1482
1483 $structure = array(
1484 'warnings' => new external_warnings()
1485 );
1486
1487 $capabilities = load_capability_def('mod_forum');
1488 foreach ($capabilities as $capname => $capdata) {
1489 // Get fields like cansubmit so it is consistent with the access_information function implemented in other modules.
1490 $field = 'can' . str_replace('mod/forum:', '', $capname);
1491 $structure[$field] = new external_value(PARAM_BOOL, 'Whether the user has the capability ' . $capname . ' allowed.',
1492 VALUE_OPTIONAL);
1493 }
1494
1495 return new external_single_structure($structure);
1496 }
2646e9d6
RW
1497
1498 /**
1499 * Set the subscription state.
1500 *
1501 * @param int $forumid
1502 * @param int $discussionid
1503 * @param bool $targetstate
1504 * @return \stdClass
1505 */
1506 public static function set_subscription_state($forumid, $discussionid, $targetstate) {
f30f46db 1507 global $PAGE, $USER;
2646e9d6
RW
1508
1509 $params = self::validate_parameters(self::set_subscription_state_parameters(), [
1510 'forumid' => $forumid,
1511 'discussionid' => $discussionid,
1512 'targetstate' => $targetstate
1513 ]);
1514
1515 $vaultfactory = mod_forum\local\container::get_vault_factory();
1516 $forumvault = $vaultfactory->get_forum_vault();
1517 $forum = $forumvault->get_from_id($params['forumid']);
2646e9d6 1518 $coursemodule = $forum->get_course_module_record();
96a49734 1519 $context = $forum->get_context();
2646e9d6 1520
96a49734 1521 self::validate_context($context);
2646e9d6 1522
2646e9d6
RW
1523 $discussionvault = $vaultfactory->get_discussion_vault();
1524 $discussion = $discussionvault->get_from_id($params['discussionid']);
1525 $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
1526
1527 $forumrecord = $legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
1528 $discussionrecord = $legacydatamapperfactory->get_discussion_data_mapper()->to_legacy_object($discussion);
1529
1530 if (!\mod_forum\subscriptions::is_subscribable($forumrecord)) {
1531 // Nothing to do. We won't actually output any content here though.
1532 throw new \moodle_exception('cannotsubscribe', 'mod_forum');
1533 }
1534
1535 $issubscribed = \mod_forum\subscriptions::is_subscribed(
1536 $USER->id,
1537 $forumrecord,
1538 $discussion->get_id(),
1539 $coursemodule
1540 );
1541
1542 // If the current state doesn't equal the desired state then update the current
1543 // state to the desired state.
1544 if ($issubscribed != (bool) $params['targetstate']) {
1545 if ($params['targetstate']) {
1546 \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussionrecord, $context);
1547 } else {
1548 \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussionrecord, $context);
1549 }
1550 }
1551
1552 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1553 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1554 return $exporter->export($PAGE->get_renderer('mod_forum'));
1555 }
1556
1557 /**
1558 * Returns description of method parameters.
1559 *
1560 * @return external_function_parameters
1561 */
1562 public static function set_subscription_state_parameters() {
1563 return new external_function_parameters(
1564 [
1565 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1566 'discussionid' => new external_value(PARAM_INT, 'The discussion to subscribe or unsubscribe'),
1567 'targetstate' => new external_value(PARAM_BOOL, 'The target state')
1568 ]
1569 );
1570 }
1571
1572 /**
1573 * Returns description of method result value.
1574 *
1575 * @return external_description
1576 */
1577 public static function set_subscription_state_returns() {
1578 return \mod_forum\local\exporters\discussion::get_read_structure();
1579 }
2893812e 1580
2893812e
P
1581 /**
1582 * Set the lock state.
1583 *
1584 * @param int $forumid
1585 * @param int $discussionid
1586 * @param string $targetstate
1587 * @return \stdClass
1588 */
1589 public static function set_lock_state($forumid, $discussionid, $targetstate) {
1590 global $DB, $PAGE, $USER;
1591
1592 $params = self::validate_parameters(self::set_lock_state_parameters(), [
1593 'forumid' => $forumid,
1594 'discussionid' => $discussionid,
1595 'targetstate' => $targetstate
1596 ]);
1597
1598 $vaultfactory = mod_forum\local\container::get_vault_factory();
1599 $forumvault = $vaultfactory->get_forum_vault();
1600 $forum = $forumvault->get_from_id($params['forumid']);
2893812e
P
1601
1602 $managerfactory = mod_forum\local\container::get_manager_factory();
1603 $capabilitymanager = $managerfactory->get_capability_manager($forum);
bdb4a87d
P
1604 if (!$capabilitymanager->can_manage_forum($USER)) {
1605 throw new moodle_exception('errorcannotlock', 'forum');
1606 }
1607
1608 // If the targetstate(currentstate) is not 0 then it should be set to the current time.
1609 $lockedvalue = $targetstate ? 0 : time();
1610 self::validate_context($forum->get_context());
1611
2893812e
P
1612 $discussionvault = $vaultfactory->get_discussion_vault();
1613 $discussion = $discussionvault->get_from_id($params['discussionid']);
2893812e 1614
c475fe41 1615 // If the current state doesn't equal the desired state then update the current.
2893812e 1616 // state to the desired state.
bdb4a87d
P
1617 $discussion->toggle_locked_state($lockedvalue);
1618 $response = $discussionvault->update_discussion($discussion);
1619 $discussion = !$response ? $response : $discussion;
2893812e
P
1620
1621 $exporterfactory = mod_forum\local\container::get_exporter_factory();
1622 $exporter = $exporterfactory->get_discussion_exporter($USER, $forum, $discussion);
1623 return $exporter->export($PAGE->get_renderer('mod_forum'));
1624 }
1625
1626 /**
1627 * Returns description of method parameters.
1628 *
1629 * @return external_function_parameters
1630 */
1631 public static function set_lock_state_parameters() {
1632 return new external_function_parameters(
1633 [
1634 'forumid' => new external_value(PARAM_INT, 'Forum that the discussion is in'),
1635 'discussionid' => new external_value(PARAM_INT, 'The discussion to lock / unlock'),
1636 'targetstate' => new external_value(PARAM_INT, 'The timestamp for the lock state')
1637 ]
1638 );
1639 }
1640
1641 /**
1642 * Returns description of method result value.
1643 *
1644 * @return external_description
1645 */
1646 public static function set_lock_state_returns() {
bdb4a87d
P
1647 return new external_single_structure([
1648 'id' => new external_value(PARAM_INT, 'The discussion we are locking.'),
1649 'locked' => new external_value(PARAM_BOOL, 'The locked state of the discussion.'),
1650 'times' => new external_single_structure([
1651 'locked' => new external_value(PARAM_INT, 'The locked time of the discussion.'),
1652 ])
1653 ]);
2893812e 1654 }
2b9fe87d 1655}