Merge branch 'MDL-69005' of https://github.com/paulholden/moodle
[moodle.git] / comment / classes / external.php
blob41a8b4108bc702174b72da9403db6e564d05dcd1
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * External comment API
20 * @package core_comment
21 * @category external
22 * @copyright Costantino Cito <ccito@cvaconsulting.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since Moodle 2.9
27 defined('MOODLE_INTERNAL') || die();
29 require_once("$CFG->libdir/externallib.php");
30 require_once("$CFG->dirroot/comment/lib.php");
32 /**
33 * External comment API functions
35 * @package core_comment
36 * @category external
37 * @copyright Costantino Cito <ccito@cvaconsulting.com>
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 * @since Moodle 2.9
41 class core_comment_external extends external_api {
42 /**
43 * Returns description of method parameters
45 * @return external_function_parameters
46 * @since Moodle 2.9
48 public static function get_comments_parameters() {
50 return new external_function_parameters(
51 array(
52 'contextlevel' => new external_value(PARAM_ALPHA, 'contextlevel system, course, user...'),
53 'instanceid' => new external_value(PARAM_INT, 'the Instance id of item associated with the context level'),
54 'component' => new external_value(PARAM_COMPONENT, 'component'),
55 'itemid' => new external_value(PARAM_INT, 'associated id'),
56 'area' => new external_value(PARAM_AREA, 'string comment area', VALUE_DEFAULT, ''),
57 'page' => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
58 'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
63 /**
64 * Return a list of comments
66 * @param string $contextlevel ('system, course, user', etc..)
67 * @param int $instanceid
68 * @param string $component the name of the component
69 * @param int $itemid the item id
70 * @param string $area comment area
71 * @param int $page page number
72 * @param string $sortdirection sort direction
73 * @return array of comments and warnings
74 * @since Moodle 2.9
76 public static function get_comments($contextlevel, $instanceid, $component, $itemid, $area = '', $page = 0,
77 $sortdirection = 'DESC') {
78 global $CFG;
80 $warnings = array();
81 $arrayparams = array(
82 'contextlevel' => $contextlevel,
83 'instanceid' => $instanceid,
84 'component' => $component,
85 'itemid' => $itemid,
86 'area' => $area,
87 'page' => $page,
88 'sortdirection' => $sortdirection,
90 $params = self::validate_parameters(self::get_comments_parameters(), $arrayparams);
92 $sortdirection = strtoupper($params['sortdirection']);
93 $directionallowedvalues = array('ASC', 'DESC');
94 if (!in_array($sortdirection, $directionallowedvalues)) {
95 throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
96 'allowed values are: ' . implode(',', $directionallowedvalues));
99 $context = self::get_context_from_params($params);
100 self::validate_context($context);
102 require_capability('moodle/comment:view', $context);
104 $args = new stdClass;
105 $args->context = $context;
106 $args->area = $params['area'];
107 $args->itemid = $params['itemid'];
108 $args->component = $params['component'];
110 $commentobject = new comment($args);
111 $comments = $commentobject->get_comments($params['page'], $sortdirection);
113 // False means no permissions to see comments.
114 if ($comments === false) {
115 throw new moodle_exception('nopermissions', 'error', '', 'view comments');
117 $options = array('blanktarget' => true);
119 foreach ($comments as $key => $comment) {
121 list($comments[$key]->content, $comments[$key]->format) = external_format_text($comment->content,
122 $comment->format,
123 $context->id,
124 $params['component'],
127 $options);
130 $results = array(
131 'comments' => $comments,
132 'count' => $commentobject->count(),
133 'perpage' => (!empty($CFG->commentsperpage)) ? $CFG->commentsperpage : 15,
134 'canpost' => $commentobject->can_post(),
135 'warnings' => $warnings
137 return $results;
141 * Returns description of method result value
143 * @return external_description
144 * @since Moodle 2.9
146 public static function get_comments_returns() {
147 return new external_single_structure(
148 array(
149 'comments' => new external_multiple_structure(
150 self::get_comment_structure(), 'List of comments'
152 'count' => new external_value(PARAM_INT, 'Total number of comments.', VALUE_OPTIONAL),
153 'perpage' => new external_value(PARAM_INT, 'Number of comments per page.', VALUE_OPTIONAL),
154 'canpost' => new external_value(PARAM_BOOL, 'Whether the user can post in this comment area.', VALUE_OPTIONAL),
155 'warnings' => new external_warnings()
161 * Helper to get the structure of a single comment.
163 * @return external_single_structure the comment structure.
165 protected static function get_comment_structure() {
166 return new external_single_structure(
167 array(
168 'id' => new external_value(PARAM_INT, 'Comment ID'),
169 'content' => new external_value(PARAM_RAW, 'The content text formatted'),
170 'format' => new external_format_value('content'),
171 'timecreated' => new external_value(PARAM_INT, 'Time created (timestamp)'),
172 'strftimeformat' => new external_value(PARAM_NOTAGS, 'Time format'),
173 'profileurl' => new external_value(PARAM_URL, 'URL profile'),
174 'fullname' => new external_value(PARAM_NOTAGS, 'fullname'),
175 'time' => new external_value(PARAM_NOTAGS, 'Time in human format'),
176 'avatar' => new external_value(PARAM_RAW, 'HTML user picture'),
177 'userid' => new external_value(PARAM_INT, 'User ID'),
178 'delete' => new external_value(PARAM_BOOL, 'Permission to delete=true/false', VALUE_OPTIONAL)
179 ), 'comment'
184 * Returns description of method parameters for the add_comments method.
186 * @return external_function_parameters
187 * @since Moodle 3.8
189 public static function add_comments_parameters() {
190 return new external_function_parameters(
192 'comments' => new external_multiple_structure(
193 new external_single_structure(
195 'contextlevel' => new external_value(PARAM_ALPHA, 'contextlevel system, course, user...'),
196 'instanceid' => new external_value(PARAM_INT, 'the id of item associated with the contextlevel'),
197 'component' => new external_value(PARAM_COMPONENT, 'component'),
198 'content' => new external_value(PARAM_RAW, 'component'),
199 'itemid' => new external_value(PARAM_INT, 'associated id'),
200 'area' => new external_value(PARAM_AREA, 'string comment area', VALUE_DEFAULT, ''),
209 * Add a comment or comments.
211 * @param array $comments the array of comments to create.
212 * @return array the array containing those comments created.
213 * @throws comment_exception
214 * @since Moodle 3.8
216 public static function add_comments($comments) {
217 global $CFG, $SITE;
219 if (empty($CFG->usecomments)) {
220 throw new comment_exception('commentsnotenabled', 'moodle');
223 $params = self::validate_parameters(self::add_comments_parameters(), ['comments' => $comments]);
225 // Validate every intended comment before creating anything, storing the validated comment for use below.
226 foreach ($params['comments'] as $index => $comment) {
227 $context = self::get_context_from_params($comment);
228 self::validate_context($context);
230 list($context, $course, $cm) = get_context_info_array($context->id);
231 if ($context->id == SYSCONTEXTID) {
232 $course = $SITE;
235 // Initialising comment object.
236 $args = new stdClass();
237 $args->context = $context;
238 $args->course = $course;
239 $args->cm = $cm;
240 $args->component = $comment['component'];
241 $args->itemid = $comment['itemid'];
242 $args->area = $comment['area'];
244 $manager = new comment($args);
245 if (!$manager->can_post()) {
246 throw new comment_exception('nopermissiontocomment');
249 $params['comments'][$index]['preparedcomment'] = $manager;
252 // Create the comments.
253 $results = [];
254 foreach ($params['comments'] as $comment) {
255 $manager = $comment['preparedcomment'];
256 $newcomment = $manager->add($comment['content']);
257 $newcomment->delete = true; // USER created the comment, so they can delete it.
258 $results[] = $newcomment;
261 return $results;
265 * Returns description of method result value for the add_comments method.
267 * @return external_description
268 * @since Moodle 3.8
270 public static function add_comments_returns() {
271 return new external_multiple_structure(
272 self::get_comment_structure()
277 * Returns description of method parameters for the delete_comments() method.
279 * @return external_function_parameters
280 * @since Moodle 3.8
282 public static function delete_comments_parameters() {
283 return new external_function_parameters(
285 'comments' => new external_multiple_structure(
286 new external_value(PARAM_INT, 'id of the comment', VALUE_DEFAULT, 0)
293 * Deletes a comment or comments.
295 * @param array $comments array of comment ids to be deleted
296 * @return array
297 * @throws comment_exception
298 * @since Moodle 3.8
300 public static function delete_comments(array $comments) {
301 global $CFG, $DB, $USER, $SITE;
303 if (empty($CFG->usecomments)) {
304 throw new comment_exception('commentsnotenabled', 'moodle');
307 $params = self::validate_parameters(self::delete_comments_parameters(), ['comments' => $comments]);
308 $commentids = $params['comments'];
310 list($insql, $inparams) = $DB->get_in_or_equal($commentids);
311 $commentrecords = $DB->get_records_select('comments', "id {$insql}", $inparams);
313 // If one or more of the records could not be found, report this and fail early.
314 if (count($commentrecords) != count($comments)) {
315 $invalidcomments = array_diff($commentids, array_column($commentrecords, 'id'));
316 $invalidcommentsstr = implode(',', $invalidcomments);
317 throw new comment_exception("One or more comments could not be found by id: $invalidcommentsstr");
320 // Make sure we can delete every one of the comments before actually doing so.
321 $comments = []; // Holds the comment objects, for later deletion.
322 foreach ($commentrecords as $commentrecord) {
323 // Validate the context.
324 list($context, $course, $cm) = get_context_info_array($commentrecord->contextid);
325 if ($context->id == SYSCONTEXTID) {
326 $course = $SITE;
328 self::validate_context($context);
330 // Make sure the user is allowed to delete the comment.
331 $args = new stdClass;
332 $args->context = $context;
333 $args->course = $course;
334 $args->cm = $cm;
335 $args->component = $commentrecord->component;
336 $args->itemid = $commentrecord->itemid;
337 $args->area = $commentrecord->commentarea;
338 $manager = new comment($args);
340 if ($commentrecord->userid != $USER->id && !$manager->can_delete($commentrecord->id)) {
341 throw new comment_exception('nopermissiontodelentry');
344 // User is allowed to delete it, so store the comment object, for use below in final deletion.
345 $comments[$commentrecord->id] = $manager;
348 // All comments can be deleted by the user. Make it so.
349 foreach ($comments as $commentid => $comment) {
350 $comment->delete($commentid);
353 return [];
357 * Returns description of method result value for the delete_comments() method.
359 * @return external_description
360 * @since Moodle 3.8
362 public static function delete_comments_returns() {
363 return new external_warnings();