MDL-57962 forum: Allow creating new discussions with groupid -1
[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
30class mod_forum_external extends external_api {
31
32 /**
a9a0cb69 33 * Describes the parameters for get_forum.
2b9fe87d 34 *
9db43c73 35 * @return external_function_parameters
2b9fe87d
MN
36 * @since Moodle 2.5
37 */
38 public static function get_forums_by_courses_parameters() {
39 return new external_function_parameters (
40 array(
41 'courseids' => new external_multiple_structure(new external_value(PARAM_INT, 'course ID',
a69c9abd 42 VALUE_REQUIRED, '', NULL_NOT_ALLOWED), 'Array of Course IDs', VALUE_DEFAULT, array()),
2b9fe87d
MN
43 )
44 );
45 }
46
47 /**
48 * Returns a list of forums in a provided list of courses,
49 * if no list is provided all forums that the user can view
50 * will be returned.
51 *
52 * @param array $courseids the course ids
53 * @return array the forum details
54 * @since Moodle 2.5
55 */
56 public static function get_forums_by_courses($courseids = array()) {
c8f1d8a0 57 global $CFG;
2b9fe87d
MN
58
59 require_once($CFG->dirroot . "/mod/forum/lib.php");
60
a9a0cb69
MN
61 $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids));
62
583b02e4 63 $courses = array();
a9a0cb69 64 if (empty($params['courseids'])) {
583b02e4
FM
65 $courses = enrol_get_my_courses();
66 $params['courseids'] = array_keys($courses);
2b9fe87d
MN
67 }
68
69 // Array to store the forums to return.
70 $arrforums = array();
ea5b910b 71 $warnings = array();
2b9fe87d 72
0c246ae5 73 // Ensure there are courseids to loop through.
ea5b910b
JL
74 if (!empty($params['courseids'])) {
75
583b02e4 76 list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses);
c8f1d8a0
JL
77
78 // Get the forums in this course. This function checks users visibility permissions.
ea5b910b
JL
79 $forums = get_all_instances_in_courses("forum", $courses);
80 foreach ($forums as $forum) {
81
82 $course = $courses[$forum->course];
83 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id);
84 $context = context_module::instance($cm->id);
85
86 // Skip forums we are not allowed to see discussions.
87 if (!has_capability('mod/forum:viewdiscussion', $context)) {
88 continue;
2b9fe87d 89 }
ea5b910b 90
5b587c75 91 $forum->name = external_format_string($forum->name, $context->id);
ea5b910b
JL
92 // Format the intro before being returning using the format setting.
93 list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat,
d33c67bc 94 $context->id, 'mod_forum', 'intro', null);
7ef49bd3 95 $forum->introfiles = external_util::get_area_files($context->id, 'mod_forum', 'intro', false, false);
ea5b910b
JL
96 // Discussions count. This function does static request cache.
97 $forum->numdiscussions = forum_count_discussions($forum, $cm, $course);
98 $forum->cmid = $forum->coursemodule;
99 $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context);
4669389d 100 $forum->istracked = forum_tp_is_tracked($forum);
ea5b910b
JL
101
102 // Add the forum to the array to return.
103 $arrforums[$forum->id] = $forum;
2b9fe87d
MN
104 }
105 }
106
107 return $arrforums;
108 }
109
110 /**
a9a0cb69 111 * Describes the get_forum return value.
2b9fe87d
MN
112 *
113 * @return external_single_structure
114 * @since Moodle 2.5
115 */
0f3bbfd4 116 public static function get_forums_by_courses_returns() {
2b9fe87d
MN
117 return new external_multiple_structure(
118 new external_single_structure(
119 array(
120 'id' => new external_value(PARAM_INT, 'Forum id'),
5b587c75 121 'course' => new external_value(PARAM_INT, 'Course id'),
2b9fe87d 122 'type' => new external_value(PARAM_TEXT, 'The forum type'),
5b587c75 123 'name' => new external_value(PARAM_RAW, 'Forum name'),
2b9fe87d
MN
124 'intro' => new external_value(PARAM_RAW, 'The forum intro'),
125 'introformat' => new external_format_value('intro'),
7ef49bd3 126 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
2b9fe87d
MN
127 'assessed' => new external_value(PARAM_INT, 'Aggregate type'),
128 'assesstimestart' => new external_value(PARAM_INT, 'Assess start time'),
129 'assesstimefinish' => new external_value(PARAM_INT, 'Assess finish time'),
130 'scale' => new external_value(PARAM_INT, 'Scale'),
131 'maxbytes' => new external_value(PARAM_INT, 'Maximum attachment size'),
132 'maxattachments' => new external_value(PARAM_INT, 'Maximum number of attachments'),
133 'forcesubscribe' => new external_value(PARAM_INT, 'Force users to subscribe'),
134 'trackingtype' => new external_value(PARAM_INT, 'Subscription mode'),
135 'rsstype' => new external_value(PARAM_INT, 'RSS feed for this activity'),
136 'rssarticles' => new external_value(PARAM_INT, 'Number of RSS recent articles'),
137 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
138 'warnafter' => new external_value(PARAM_INT, 'Post threshold for warning'),
139 'blockafter' => new external_value(PARAM_INT, 'Post threshold for blocking'),
140 'blockperiod' => new external_value(PARAM_INT, 'Time period for blocking'),
141 'completiondiscussions' => new external_value(PARAM_INT, 'Student must create discussions'),
142 'completionreplies' => new external_value(PARAM_INT, 'Student must post replies'),
143 'completionposts' => new external_value(PARAM_INT, 'Student must post discussions or replies'),
7ea6ada3 144 'cmid' => new external_value(PARAM_INT, 'Course module id'),
ea5b910b
JL
145 'numdiscussions' => new external_value(PARAM_INT, 'Number of discussions in the forum', VALUE_OPTIONAL),
146 'cancreatediscussions' => new external_value(PARAM_BOOL, 'If the user can create discussions', VALUE_OPTIONAL),
0f3bbfd4 147 'lockdiscussionafter' => new external_value(PARAM_INT, 'After what period a discussion is locked', VALUE_OPTIONAL),
4669389d 148 'istracked' => new external_value(PARAM_BOOL, 'If the user is tracking the forum', VALUE_OPTIONAL),
2b9fe87d
MN
149 ), 'forum'
150 )
151 );
152 }
a9a0cb69 153
e2ede426
JL
154 /**
155 * Describes the parameters for get_forum_discussion_posts.
156 *
9db43c73 157 * @return external_function_parameters
e2ede426
JL
158 * @since Moodle 2.7
159 */
160 public static function get_forum_discussion_posts_parameters() {
161 return new external_function_parameters (
162 array(
163 'discussionid' => new external_value(PARAM_INT, 'discussion ID', VALUE_REQUIRED),
164 'sortby' => new external_value(PARAM_ALPHA,
165 'sort by this element: id, created or modified', VALUE_DEFAULT, 'created'),
166 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC')
167 )
168 );
169 }
170
171 /**
172 * Returns a list of forum posts for a discussion
173 *
174 * @param int $discussionid the post ids
175 * @param string $sortby sort by this element (id, created or modified)
176 * @param string $sortdirection sort direction: ASC or DESC
177 *
178 * @return array the forum post details
179 * @since Moodle 2.7
180 */
fb8840d2 181 public static function get_forum_discussion_posts($discussionid, $sortby = "created", $sortdirection = "DESC") {
d85bedf7 182 global $CFG, $DB, $USER, $PAGE;
e2ede426 183
b1aa7dfa 184 $posts = array();
e2ede426
JL
185 $warnings = array();
186
187 // Validate the parameter.
188 $params = self::validate_parameters(self::get_forum_discussion_posts_parameters(),
189 array(
190 'discussionid' => $discussionid,
191 'sortby' => $sortby,
192 'sortdirection' => $sortdirection));
193
194 // Compact/extract functions are not recommended.
195 $discussionid = $params['discussionid'];
196 $sortby = $params['sortby'];
197 $sortdirection = $params['sortdirection'];
198
199 $sortallowedvalues = array('id', 'created', 'modified');
200 if (!in_array($sortby, $sortallowedvalues)) {
201 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
202 'allowed values are: ' . implode(',', $sortallowedvalues));
203 }
204
205 $sortdirection = strtoupper($sortdirection);
206 $directionallowedvalues = array('ASC', 'DESC');
207 if (!in_array($sortdirection, $directionallowedvalues)) {
208 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
209 'allowed values are: ' . implode(',', $directionallowedvalues));
210 }
211
212 $discussion = $DB->get_record('forum_discussions', array('id' => $discussionid), '*', MUST_EXIST);
213 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
214 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
215 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
216
217 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
218 $modcontext = context_module::instance($cm->id);
219 self::validate_context($modcontext);
220
221 // This require must be here, see mod/forum/discuss.php.
222 require_once($CFG->dirroot . "/mod/forum/lib.php");
223
224 // Check they have the view forum capability.
225 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
226
227 if (! $post = forum_get_post_full($discussion->firstpost)) {
228 throw new moodle_exception('notexists', 'forum');
229 }
230
231 // This function check groups, qanda, timed discussions, etc.
232 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
233 throw new moodle_exception('noviewdiscussionspermission', 'forum');
234 }
235
236 $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
237
238 // We will add this field in the response.
239 $canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
240
241 $forumtracked = forum_tp_is_tracked($forum);
242
243 $sort = 'p.' . $sortby . ' ' . $sortdirection;
b1aa7dfa 244 $allposts = forum_get_all_discussion_posts($discussion->id, $sort, $forumtracked);
e2ede426 245
b1aa7dfa 246 foreach ($allposts as $post) {
e2ede426
JL
247
248 if (!forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
249 $warning = array();
250 $warning['item'] = 'post';
251 $warning['itemid'] = $post->id;
252 $warning['warningcode'] = '1';
253 $warning['message'] = 'You can\'t see this post';
254 $warnings[] = $warning;
255 continue;
256 }
257
258 // Function forum_get_all_discussion_posts adds postread field.
f47eeafd
JL
259 // Note that the value returned can be a boolean or an integer. The WS expects a boolean.
260 if (empty($post->postread)) {
b1aa7dfa 261 $post->postread = false;
f47eeafd 262 } else {
b1aa7dfa 263 $post->postread = true;
e2ede426 264 }
f47eeafd 265
b1aa7dfa
JL
266 $post->canreply = $canreply;
267 if (!empty($post->children)) {
268 $post->children = array_keys($post->children);
fb8840d2 269 } else {
b1aa7dfa 270 $post->children = array();
e2ede426
JL
271 }
272
30861fbd
JL
273 if (forum_is_author_hidden($post, $forum)) {
274 $post->userid = null;
275 $post->userfullname = null;
276 $post->userpictureurl = null;
277 } else {
278 $user = new stdclass();
279 $user->id = $post->userid;
280 $user = username_load_fields_from_object($user, $post, null, array('picture', 'imagealt', 'email'));
281 $post->userfullname = fullname($user, $canviewfullname);
81f810dc 282
30861fbd
JL
283 $userpicture = new user_picture($user);
284 $userpicture->size = 1; // Size f1.
285 $post->userpictureurl = $userpicture->get_url($PAGE)->out(false);
286 }
14ebc396 287
55bb8189 288 $post->subject = external_format_string($post->subject, $modcontext->id);
48fb0250
JL
289 // Rewrite embedded images URLs.
290 list($post->message, $post->messageformat) =
291 external_format_text($post->message, $post->messageformat, $modcontext->id, 'mod_forum', 'post', $post->id);
292
293 // List attachments.
294 if (!empty($post->attachment)) {
14590070 295 $post->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $post->id);
48fb0250 296 }
c8743f62
JL
297 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $post->id);
298 if (!empty($messageinlinefiles)) {
299 $post->messageinlinefiles = $messageinlinefiles;
300 }
e2ede426 301
b1aa7dfa 302 $posts[] = $post;
e2ede426
JL
303 }
304
305 $result = array();
306 $result['posts'] = $posts;
307 $result['warnings'] = $warnings;
308 return $result;
309 }
310
311 /**
312 * Describes the get_forum_discussion_posts return value.
313 *
314 * @return external_single_structure
315 * @since Moodle 2.7
316 */
317 public static function get_forum_discussion_posts_returns() {
318 return new external_single_structure(
319 array(
320 'posts' => new external_multiple_structure(
321 new external_single_structure(
322 array(
323 'id' => new external_value(PARAM_INT, 'Post id'),
324 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
325 'parent' => new external_value(PARAM_INT, 'Parent id'),
326 'userid' => new external_value(PARAM_INT, 'User id'),
327 'created' => new external_value(PARAM_INT, 'Creation time'),
328 'modified' => new external_value(PARAM_INT, 'Time modified'),
329 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
330 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
331 'message' => new external_value(PARAM_RAW, 'The post message'),
48fb0250 332 'messageformat' => new external_format_value('message'),
e2ede426 333 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
c8743f62 334 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
48fb0250 335 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
14590070 336 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
e2ede426
JL
337 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
338 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
339 'children' => new external_multiple_structure(new external_value(PARAM_INT, 'children post id')),
340 'canreply' => new external_value(PARAM_BOOL, 'The user can reply to posts?'),
341 'postread' => new external_value(PARAM_BOOL, 'The post was read'),
694bf0c7
JL
342 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
343 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.', VALUE_OPTIONAL)
e2ede426
JL
344 ), 'post'
345 )
346 ),
347 'warnings' => new external_warnings()
348 )
349 );
350 }
351
7c51b40a
JL
352 /**
353 * Describes the parameters for get_forum_discussions_paginated.
354 *
9db43c73 355 * @return external_function_parameters
7c51b40a
JL
356 * @since Moodle 2.8
357 */
358 public static function get_forum_discussions_paginated_parameters() {
359 return new external_function_parameters (
360 array(
361 'forumid' => new external_value(PARAM_INT, 'forum instance id', VALUE_REQUIRED),
362 'sortby' => new external_value(PARAM_ALPHA,
363 'sort by this element: id, timemodified, timestart or timeend', VALUE_DEFAULT, 'timemodified'),
364 'sortdirection' => new external_value(PARAM_ALPHA, 'sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
365 'page' => new external_value(PARAM_INT, 'current page', VALUE_DEFAULT, -1),
366 'perpage' => new external_value(PARAM_INT, 'items per page', VALUE_DEFAULT, 0),
367 )
368 );
369 }
370
371 /**
372 * Returns a list of forum discussions optionally sorted and paginated.
373 *
374 * @param int $forumid the forum instance id
375 * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
376 * @param string $sortdirection sort direction: ASC or DESC
377 * @param int $page page number
378 * @param int $perpage items per page
379 *
380 * @return array the forum discussion details including warnings
381 * @since Moodle 2.8
382 */
383 public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC',
384 $page = -1, $perpage = 0) {
d85bedf7 385 global $CFG, $DB, $USER, $PAGE;
7c51b40a
JL
386
387 require_once($CFG->dirroot . "/mod/forum/lib.php");
388
389 $warnings = array();
039c81f0 390 $discussions = array();
7c51b40a
JL
391
392 $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(),
393 array(
394 'forumid' => $forumid,
395 'sortby' => $sortby,
396 'sortdirection' => $sortdirection,
397 'page' => $page,
398 'perpage' => $perpage
399 )
400 );
401
402 // Compact/extract functions are not recommended.
403 $forumid = $params['forumid'];
404 $sortby = $params['sortby'];
405 $sortdirection = $params['sortdirection'];
406 $page = $params['page'];
407 $perpage = $params['perpage'];
408
409 $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
410 if (!in_array($sortby, $sortallowedvalues)) {
411 throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' .
412 'allowed values are: ' . implode(',', $sortallowedvalues));
413 }
414
415 $sortdirection = strtoupper($sortdirection);
416 $directionallowedvalues = array('ASC', 'DESC');
417 if (!in_array($sortdirection, $directionallowedvalues)) {
418 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
419 'allowed values are: ' . implode(',', $directionallowedvalues));
420 }
421
422 $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
423 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
424 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
425
426 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
427 $modcontext = context_module::instance($cm->id);
428 self::validate_context($modcontext);
429
430 // Check they have the view forum capability.
431 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
432
5f219cf1 433 $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
4f3a2d21 434 $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
7c51b40a 435
039c81f0 436 if ($alldiscussions) {
7c51b40a
JL
437 $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
438
439 // Get the unreads array, this takes a forum id and returns data for all discussions.
440 $unreads = array();
441 if ($cantrack = forum_tp_can_track_forums($forum)) {
442 if ($forumtracked = forum_tp_is_tracked($forum)) {
443 $unreads = forum_get_discussions_unread($cm);
444 }
445 }
446 // The forum function returns the replies for all the discussions in a given forum.
447 $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage);
448
039c81f0
JL
449 foreach ($alldiscussions as $discussion) {
450
7c51b40a 451 // This function checks for qanda forums.
039c81f0
JL
452 // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
453 $discussionrec = clone $discussion;
454 $discussionrec->id = $discussion->discussion;
455 if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
7c51b40a
JL
456 $warning = array();
457 // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
458 $warning['item'] = 'post';
459 $warning['itemid'] = $discussion->id;
460 $warning['warningcode'] = '1';
461 $warning['message'] = 'You can\'t see this discussion';
462 $warnings[] = $warning;
463 continue;
464 }
465
466 $discussion->numunread = 0;
467 if ($cantrack && $forumtracked) {
468 if (isset($unreads[$discussion->discussion])) {
469 $discussion->numunread = (int) $unreads[$discussion->discussion];
470 }
471 }
472
473 $discussion->numreplies = 0;
474 if (!empty($replies[$discussion->discussion])) {
475 $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
476 }
477
55bb8189
JL
478 $discussion->name = external_format_string($discussion->name, $modcontext->id);
479 $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
7c51b40a
JL
480 // Rewrite embedded images URLs.
481 list($discussion->message, $discussion->messageformat) =
482 external_format_text($discussion->message, $discussion->messageformat,
483 $modcontext->id, 'mod_forum', 'post', $discussion->id);
484
485 // List attachments.
486 if (!empty($discussion->attachment)) {
14590070
JL
487 $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment',
488 $discussion->id);
7c51b40a 489 }
c8743f62
JL
490 $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
491 if (!empty($messageinlinefiles)) {
492 $discussion->messageinlinefiles = $messageinlinefiles;
493 }
7c51b40a 494
0f3bbfd4
AN
495 $discussion->locked = forum_discussion_is_locked($forum, $discussion);
496 $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
497
30861fbd
JL
498 if (forum_is_author_hidden($discussion, $forum)) {
499 $discussion->userid = null;
500 $discussion->userfullname = null;
501 $discussion->userpictureurl = null;
502
503 $discussion->usermodified = null;
504 $discussion->usermodifiedfullname = null;
505 $discussion->usermodifiedpictureurl = null;
506 } else {
507 $picturefields = explode(',', user_picture::fields());
508
509 // Load user objects from the results of the query.
510 $user = new stdclass();
511 $user->id = $discussion->userid;
512 $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
513 // Preserve the id, it can be modified by username_load_fields_from_object.
514 $user->id = $discussion->userid;
515 $discussion->userfullname = fullname($user, $canviewfullname);
516
517 $userpicture = new user_picture($user);
518 $userpicture->size = 1; // Size f1.
519 $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
520
521 $usermodified = new stdclass();
522 $usermodified->id = $discussion->usermodified;
523 $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
524 // Preserve the id (it can be overwritten due to the prefixed $picturefields).
525 $usermodified->id = $discussion->usermodified;
526 $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
527
528 $userpicture = new user_picture($usermodified);
529 $userpicture->size = 1; // Size f1.
530 $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
531 }
532
039c81f0 533 $discussions[] = $discussion;
7c51b40a
JL
534 }
535 }
536
537 $result = array();
538 $result['discussions'] = $discussions;
539 $result['warnings'] = $warnings;
540 return $result;
541
542 }
543
544 /**
545 * Describes the get_forum_discussions_paginated return value.
546 *
547 * @return external_single_structure
548 * @since Moodle 2.8
549 */
550 public static function get_forum_discussions_paginated_returns() {
551 return new external_single_structure(
552 array(
553 'discussions' => new external_multiple_structure(
554 new external_single_structure(
555 array(
556 'id' => new external_value(PARAM_INT, 'Post id'),
557 'name' => new external_value(PARAM_TEXT, 'Discussion name'),
558 'groupid' => new external_value(PARAM_INT, 'Group id'),
559 'timemodified' => new external_value(PARAM_INT, 'Time modified'),
560 'usermodified' => new external_value(PARAM_INT, 'The id of the user who last modified'),
561 'timestart' => new external_value(PARAM_INT, 'Time discussion can start'),
562 'timeend' => new external_value(PARAM_INT, 'Time discussion ends'),
563 'discussion' => new external_value(PARAM_INT, 'Discussion id'),
564 'parent' => new external_value(PARAM_INT, 'Parent id'),
565 'userid' => new external_value(PARAM_INT, 'User who started the discussion id'),
566 'created' => new external_value(PARAM_INT, 'Creation time'),
567 'modified' => new external_value(PARAM_INT, 'Time modified'),
568 'mailed' => new external_value(PARAM_INT, 'Mailed?'),
569 'subject' => new external_value(PARAM_TEXT, 'The post subject'),
570 'message' => new external_value(PARAM_RAW, 'The post message'),
571 'messageformat' => new external_format_value('message'),
572 'messagetrust' => new external_value(PARAM_INT, 'Can we trust?'),
c8743f62 573 'messageinlinefiles' => new external_files('post message inline files', VALUE_OPTIONAL),
7c51b40a 574 'attachment' => new external_value(PARAM_RAW, 'Has attachments?'),
14590070 575 'attachments' => new external_files('attachments', VALUE_OPTIONAL),
7c51b40a
JL
576 'totalscore' => new external_value(PARAM_INT, 'The post message total score'),
577 'mailnow' => new external_value(PARAM_INT, 'Mail now?'),
578 'userfullname' => new external_value(PARAM_TEXT, 'Post author full name'),
579 'usermodifiedfullname' => new external_value(PARAM_TEXT, 'Post modifier full name'),
580 'userpictureurl' => new external_value(PARAM_URL, 'Post author picture.'),
581 'usermodifiedpictureurl' => new external_value(PARAM_URL, 'Post modifier picture.'),
582 'numreplies' => new external_value(PARAM_TEXT, 'The number of replies in the discussion'),
5f219cf1 583 'numunread' => new external_value(PARAM_INT, 'The number of unread discussions.'),
0f3bbfd4
AN
584 'pinned' => new external_value(PARAM_BOOL, 'Is the discussion pinned'),
585 'locked' => new external_value(PARAM_BOOL, 'Is the discussion locked'),
586 'canreply' => new external_value(PARAM_BOOL, 'Can the user reply to the discussion'),
7c51b40a
JL
587 ), 'post'
588 )
589 ),
590 'warnings' => new external_warnings()
591 )
592 );
593 }
594
4a1e44a1
JL
595 /**
596 * Returns description of method parameters
597 *
598 * @return external_function_parameters
599 * @since Moodle 2.9
600 */
601 public static function view_forum_parameters() {
602 return new external_function_parameters(
603 array(
604 'forumid' => new external_value(PARAM_INT, 'forum instance id')
605 )
606 );
607 }
608
609 /**
1c2b7882 610 * Trigger the course module viewed event and update the module completion status.
4a1e44a1
JL
611 *
612 * @param int $forumid the forum instance id
613 * @return array of warnings and status result
614 * @since Moodle 2.9
615 * @throws moodle_exception
616 */
617 public static function view_forum($forumid) {
618 global $DB, $CFG;
619 require_once($CFG->dirroot . "/mod/forum/lib.php");
620
621 $params = self::validate_parameters(self::view_forum_parameters(),
622 array(
623 'forumid' => $forumid
624 ));
625 $warnings = array();
626
627 // Request and permission validation.
ca7e2fc2 628 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
4a1e44a1
JL
629 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
630
631 $context = context_module::instance($cm->id);
632 self::validate_context($context);
633
ea2fa324
JL
634 require_capability('mod/forum:viewdiscussion', $context, null, true, 'noviewdiscussionspermission', 'forum');
635
4a1e44a1
JL
636 // Call the forum/lib API.
637 forum_view($forum, $course, $cm, $context);
638
639 $result = array();
640 $result['status'] = true;
641 $result['warnings'] = $warnings;
642 return $result;
643 }
644
645 /**
646 * Returns description of method result value
647 *
648 * @return external_description
649 * @since Moodle 2.9
650 */
651 public static function view_forum_returns() {
652 return new external_single_structure(
653 array(
654 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
655 'warnings' => new external_warnings()
656 )
657 );
658 }
659
a3c315dd
JL
660 /**
661 * Returns description of method parameters
662 *
663 * @return external_function_parameters
664 * @since Moodle 2.9
665 */
666 public static function view_forum_discussion_parameters() {
667 return new external_function_parameters(
668 array(
669 'discussionid' => new external_value(PARAM_INT, 'discussion id')
670 )
671 );
672 }
673
674 /**
1c2b7882 675 * Trigger the discussion viewed event.
a3c315dd
JL
676 *
677 * @param int $discussionid the discussion id
678 * @return array of warnings and status result
679 * @since Moodle 2.9
680 * @throws moodle_exception
681 */
682 public static function view_forum_discussion($discussionid) {
db3c9ff8 683 global $DB, $CFG, $USER;
a3c315dd
JL
684 require_once($CFG->dirroot . "/mod/forum/lib.php");
685
686 $params = self::validate_parameters(self::view_forum_discussion_parameters(),
687 array(
688 'discussionid' => $discussionid
689 ));
690 $warnings = array();
691
692 $discussion = $DB->get_record('forum_discussions', array('id' => $params['discussionid']), '*', MUST_EXIST);
693 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
694 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
695
696 // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
697 $modcontext = context_module::instance($cm->id);
698 self::validate_context($modcontext);
699
ea2fa324
JL
700 require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
701
a3c315dd
JL
702 // Call the forum/lib API.
703 forum_discussion_view($modcontext, $forum, $discussion);
704
db3c9ff8
PFO
705 // Mark as read if required.
706 if (!$CFG->forum_usermarksread && forum_tp_is_tracked($forum)) {
707 forum_tp_mark_discussion_read($USER, $discussion->id);
708 }
709
a3c315dd
JL
710 $result = array();
711 $result['status'] = true;
712 $result['warnings'] = $warnings;
713 return $result;
714 }
715
716 /**
717 * Returns description of method result value
718 *
719 * @return external_description
720 * @since Moodle 2.9
721 */
722 public static function view_forum_discussion_returns() {
723 return new external_single_structure(
724 array(
725 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
726 'warnings' => new external_warnings()
727 )
728 );
729 }
730
50a20317
JL
731 /**
732 * Returns description of method parameters
733 *
734 * @return external_function_parameters
735 * @since Moodle 3.0
736 */
737 public static function add_discussion_post_parameters() {
738 return new external_function_parameters(
739 array(
740 'postid' => new external_value(PARAM_INT, 'the post id we are going to reply to
741 (can be the initial discussion post'),
742 'subject' => new external_value(PARAM_TEXT, 'new post subject'),
743 'message' => new external_value(PARAM_RAW, 'new post message (only html format allowed)'),
744 'options' => new external_multiple_structure (
745 new external_single_structure(
746 array(
747 'name' => new external_value(PARAM_ALPHANUM,
748 'The allowed keys (value format) are:
749 discussionsubscribe (bool); subscribe to the discussion?, default to true
48143990 750 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 751 attachmentsid (int); the draft file area id for attachments
50a20317
JL
752 '),
753 'value' => new external_value(PARAM_RAW, 'the value of the option,
754 this param is validated in the external function.'
755 )
756 )
757 ), 'Options', VALUE_DEFAULT, array())
758 )
759 );
760 }
761
762 /**
763 * Create new posts into an existing discussion.
764 *
765 * @param int $postid the post id we are going to reply to
766 * @param string $subject new post subject
767 * @param string $message new post message (only html format allowed)
768 * @param array $options optional settings
769 * @return array of warnings and the new post id
770 * @since Moodle 3.0
771 * @throws moodle_exception
772 */
773 public static function add_discussion_post($postid, $subject, $message, $options = array()) {
774 global $DB, $CFG, $USER;
775 require_once($CFG->dirroot . "/mod/forum/lib.php");
776
777 $params = self::validate_parameters(self::add_discussion_post_parameters(),
778 array(
779 'postid' => $postid,
780 'subject' => $subject,
781 'message' => $message,
782 'options' => $options
783 ));
784 // Validate options.
785 $options = array(
41182118 786 'discussionsubscribe' => true,
48143990 787 'inlineattachmentsid' => 0,
e881c4f5 788 'attachmentsid' => null
50a20317
JL
789 );
790 foreach ($params['options'] as $option) {
791 $name = trim($option['name']);
792 switch ($name) {
793 case 'discussionsubscribe':
794 $value = clean_param($option['value'], PARAM_BOOL);
795 break;
48143990 796 case 'inlineattachmentsid':
41182118
BK
797 $value = clean_param($option['value'], PARAM_INT);
798 break;
e881c4f5
BK
799 case 'attachmentsid':
800 $value = clean_param($option['value'], PARAM_INT);
801 break;
50a20317
JL
802 default:
803 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
804 }
805 $options[$name] = $value;
806 }
807
808 $warnings = array();
809
d3d8f81c 810 if (!$parent = forum_get_post_full($params['postid'])) {
50a20317
JL
811 throw new moodle_exception('invalidparentpostid', 'forum');
812 }
813
d3d8f81c 814 if (!$discussion = $DB->get_record("forum_discussions", array("id" => $parent->discussion))) {
50a20317
JL
815 throw new moodle_exception('notpartofdiscussion', 'forum');
816 }
817
818 // Request and permission validation.
819 $forum = $DB->get_record('forum', array('id' => $discussion->forum), '*', MUST_EXIST);
820 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
821
822 $context = context_module::instance($cm->id);
823 self::validate_context($context);
824
825 if (!forum_user_can_post($forum, $discussion, $USER, $cm, $course, $context)) {
826 throw new moodle_exception('nopostforum', 'forum');
827 }
828
829 $thresholdwarning = forum_check_throttling($forum, $cm);
830 forum_check_blocking_threshold($thresholdwarning);
831
832 // Create the post.
833 $post = new stdClass();
834 $post->discussion = $discussion->id;
835 $post->parent = $parent->id;
836 $post->subject = $params['subject'];
837 $post->message = $params['message'];
838 $post->messageformat = FORMAT_HTML; // Force formatting for now.
839 $post->messagetrust = trusttext_trusted($context);
48143990 840 $post->itemid = $options['inlineattachmentsid'];
e881c4f5
BK
841 $post->attachments = $options['attachmentsid'];
842 $fakemform = $post->attachments;
843 if ($postid = forum_add_new_post($post, $fakemform)) {
50a20317
JL
844
845 $post->id = $postid;
846
847 // Trigger events and completion.
848 $params = array(
849 'context' => $context,
850 'objectid' => $post->id,
851 'other' => array(
852 'discussionid' => $discussion->id,
853 'forumid' => $forum->id,
854 'forumtype' => $forum->type,
855 )
856 );
857 $event = \mod_forum\event\post_created::create($params);
858 $event->add_record_snapshot('forum_posts', $post);
859 $event->add_record_snapshot('forum_discussions', $discussion);
860 $event->trigger();
861
862 // Update completion state.
863 $completion = new completion_info($course);
864 if ($completion->is_enabled($cm) &&
865 ($forum->completionreplies || $forum->completionposts)) {
866 $completion->update_state($cm, COMPLETION_COMPLETE);
867 }
868
869 $settings = new stdClass();
870 $settings->discussionsubscribe = $options['discussionsubscribe'];
871 forum_post_subscription($settings, $forum, $discussion);
872 } else {
873 throw new moodle_exception('couldnotadd', 'forum');
874 }
875
876 $result = array();
877 $result['postid'] = $postid;
878 $result['warnings'] = $warnings;
879 return $result;
880 }
881
882 /**
883 * Returns description of method result value
884 *
885 * @return external_description
886 * @since Moodle 3.0
887 */
888 public static function add_discussion_post_returns() {
889 return new external_single_structure(
890 array(
891 'postid' => new external_value(PARAM_INT, 'new post id'),
892 'warnings' => new external_warnings()
893 )
894 );
895 }
896
7ab43ac8
JL
897 /**
898 * Returns description of method parameters
899 *
900 * @return external_function_parameters
901 * @since Moodle 3.0
902 */
903 public static function add_discussion_parameters() {
904 return new external_function_parameters(
905 array(
7267daa8
AN
906 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
907 'subject' => new external_value(PARAM_TEXT, 'New Discussion subject'),
908 'message' => new external_value(PARAM_RAW, 'New Discussion message (only html format allowed)'),
aa9059b9 909 'groupid' => new external_value(PARAM_INT, 'The group, default to 0', VALUE_DEFAULT, 0),
7ab43ac8
JL
910 'options' => new external_multiple_structure (
911 new external_single_structure(
912 array(
913 'name' => new external_value(PARAM_ALPHANUM,
914 'The allowed keys (value format) are:
915 discussionsubscribe (bool); subscribe to the discussion?, default to true
5f219cf1 916 discussionpinned (bool); is the discussion pinned, default to false
48143990 917 inlineattachmentsid (int); the draft file area id for inline attachments
e881c4f5 918 attachmentsid (int); the draft file area id for attachments
7ab43ac8 919 '),
7267daa8
AN
920 'value' => new external_value(PARAM_RAW, 'The value of the option,
921 This param is validated in the external function.'
7ab43ac8
JL
922 )
923 )
924 ), 'Options', VALUE_DEFAULT, array())
925 )
926 );
927 }
928
929 /**
930 * Add a new discussion into an existing forum.
931 *
932 * @param int $forumid the forum instance id
933 * @param string $subject new discussion subject
934 * @param string $message new discussion message (only html format allowed)
935 * @param int $groupid the user course group
936 * @param array $options optional settings
937 * @return array of warnings and the new discussion id
938 * @since Moodle 3.0
939 * @throws moodle_exception
940 */
aa9059b9 941 public static function add_discussion($forumid, $subject, $message, $groupid = 0, $options = array()) {
7ab43ac8
JL
942 global $DB, $CFG;
943 require_once($CFG->dirroot . "/mod/forum/lib.php");
944
945 $params = self::validate_parameters(self::add_discussion_parameters(),
946 array(
947 'forumid' => $forumid,
948 'subject' => $subject,
949 'message' => $message,
950 'groupid' => $groupid,
951 'options' => $options
952 ));
953 // Validate options.
954 $options = array(
5f219cf1 955 'discussionsubscribe' => true,
41182118 956 'discussionpinned' => false,
48143990 957 'inlineattachmentsid' => 0,
e881c4f5 958 'attachmentsid' => null
7ab43ac8
JL
959 );
960 foreach ($params['options'] as $option) {
961 $name = trim($option['name']);
962 switch ($name) {
963 case 'discussionsubscribe':
964 $value = clean_param($option['value'], PARAM_BOOL);
965 break;
5f219cf1
BK
966 case 'discussionpinned':
967 $value = clean_param($option['value'], PARAM_BOOL);
968 break;
48143990 969 case 'inlineattachmentsid':
41182118
BK
970 $value = clean_param($option['value'], PARAM_INT);
971 break;
e881c4f5
BK
972 case 'attachmentsid':
973 $value = clean_param($option['value'], PARAM_INT);
974 break;
7ab43ac8
JL
975 default:
976 throw new moodle_exception('errorinvalidparam', 'webservice', '', $name);
977 }
978 $options[$name] = $value;
979 }
980
981 $warnings = array();
982
983 // Request and permission validation.
984 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
985 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
986
987 $context = context_module::instance($cm->id);
988 self::validate_context($context);
989
990 // Normalize group.
991 if (!groups_get_activity_groupmode($cm)) {
992 // Groups not supported, force to -1.
993 $groupid = -1;
994 } else {
995 // Check if we receive the default or and empty value for groupid,
996 // in this case, get the group for the user in the activity.
aa9059b9 997 if (empty($params['groupid'])) {
7ab43ac8
JL
998 $groupid = groups_get_activity_group($cm);
999 } else {
1000 // Here we rely in the group passed, forum_user_can_post_discussion will validate the group.
1001 $groupid = $params['groupid'];
1002 }
1003 }
1004
1005 if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
1006 throw new moodle_exception('cannotcreatediscussion', 'forum');
1007 }
1008
1009 $thresholdwarning = forum_check_throttling($forum, $cm);
1010 forum_check_blocking_threshold($thresholdwarning);
1011
1012 // Create the discussion.
1013 $discussion = new stdClass();
1014 $discussion->course = $course->id;
1015 $discussion->forum = $forum->id;
1016 $discussion->message = $params['message'];
1017 $discussion->messageformat = FORMAT_HTML; // Force formatting for now.
1018 $discussion->messagetrust = trusttext_trusted($context);
48143990 1019 $discussion->itemid = $options['inlineattachmentsid'];
7ab43ac8
JL
1020 $discussion->groupid = $groupid;
1021 $discussion->mailnow = 0;
1022 $discussion->subject = $params['subject'];
1023 $discussion->name = $discussion->subject;
1024 $discussion->timestart = 0;
1025 $discussion->timeend = 0;
e881c4f5
BK
1026 $discussion->attachments = $options['attachmentsid'];
1027
5f219cf1
BK
1028 if (has_capability('mod/forum:pindiscussions', $context) && $options['discussionpinned']) {
1029 $discussion->pinned = FORUM_DISCUSSION_PINNED;
1030 } else {
1031 $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
1032 }
e881c4f5
BK
1033 $fakemform = $options['attachmentsid'];
1034 if ($discussionid = forum_add_discussion($discussion, $fakemform)) {
7ab43ac8
JL
1035
1036 $discussion->id = $discussionid;
1037
1038 // Trigger events and completion.
1039
1040 $params = array(
1041 'context' => $context,
1042 'objectid' => $discussion->id,
1043 'other' => array(
1044 'forumid' => $forum->id,
1045 )
1046 );
1047 $event = \mod_forum\event\discussion_created::create($params);
1048 $event->add_record_snapshot('forum_discussions', $discussion);
1049 $event->trigger();
1050
1051 $completion = new completion_info($course);
1052 if ($completion->is_enabled($cm) &&
1053 ($forum->completiondiscussions || $forum->completionposts)) {
1054 $completion->update_state($cm, COMPLETION_COMPLETE);
1055 }
1056
1057 $settings = new stdClass();
1058 $settings->discussionsubscribe = $options['discussionsubscribe'];
1059 forum_post_subscription($settings, $forum, $discussion);
1060 } else {
1061 throw new moodle_exception('couldnotadd', 'forum');
1062 }
1063
1064 $result = array();
1065 $result['discussionid'] = $discussionid;
1066 $result['warnings'] = $warnings;
1067 return $result;
1068 }
1069
1070 /**
1071 * Returns description of method result value
1072 *
1073 * @return external_description
1074 * @since Moodle 3.0
1075 */
1076 public static function add_discussion_returns() {
1077 return new external_single_structure(
1078 array(
7267daa8 1079 'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
7ab43ac8
JL
1080 'warnings' => new external_warnings()
1081 )
1082 );
1083 }
1084
04cd8ae3
JL
1085 /**
1086 * Returns description of method parameters
1087 *
1088 * @return external_function_parameters
1089 * @since Moodle 3.1
1090 */
1091 public static function can_add_discussion_parameters() {
1092 return new external_function_parameters(
1093 array(
1094 'forumid' => new external_value(PARAM_INT, 'Forum instance ID'),
1095 'groupid' => new external_value(PARAM_INT, 'The group to check, default to active group.
1096 Use -1 to check if the user can post in all the groups.', VALUE_DEFAULT, null)
1097 )
1098 );
1099 }
1100
1101 /**
1102 * Check if the current user can add discussions in the given forum (and optionally for the given group).
1103 *
1104 * @param int $forumid the forum instance id
1105 * @param int $groupid the group to check, default to active group. Use -1 to check if the user can post in all the groups.
1106 * @return array of warnings and the status (true if the user can add discussions)
1107 * @since Moodle 3.1
1108 * @throws moodle_exception
1109 */
1110 public static function can_add_discussion($forumid, $groupid = null) {
1111 global $DB, $CFG;
1112 require_once($CFG->dirroot . "/mod/forum/lib.php");
1113
1114 $params = self::validate_parameters(self::can_add_discussion_parameters(),
1115 array(
1116 'forumid' => $forumid,
1117 'groupid' => $groupid,
1118 ));
1119 $warnings = array();
1120
1121 // Request and permission validation.
1122 $forum = $DB->get_record('forum', array('id' => $params['forumid']), '*', MUST_EXIST);
1123 list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
1124
1125 $context = context_module::instance($cm->id);
1126 self::validate_context($context);
1127
1128 $status = forum_user_can_post_discussion($forum, $params['groupid'], -1, $cm, $context);
1129
1130 $result = array();
1131 $result['status'] = $status;
1132 $result['warnings'] = $warnings;
1133 return $result;
1134 }
1135
1136 /**
1137 * Returns description of method result value
1138 *
1139 * @return external_description
1140 * @since Moodle 3.1
1141 */
1142 public static function can_add_discussion_returns() {
1143 return new external_single_structure(
1144 array(
1145 'status' => new external_value(PARAM_BOOL, 'True if the user can add discussions, false otherwise.'),
1146 'warnings' => new external_warnings()
1147 )
1148 );
1149 }
1150
2b9fe87d 1151}