Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403]

   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.
  13  //
  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/>.
  16  
  17  /**
  18   * External comment API
  19   *
  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
  25   */
  26  
  27  use core_external\external_api;
  28  use core_external\external_format_value;
  29  use core_external\external_function_parameters;
  30  use core_external\external_multiple_structure;
  31  use core_external\external_single_structure;
  32  use core_external\external_value;
  33  use core_external\external_warnings;
  34  
  35  defined('MOODLE_INTERNAL') || die();
  36  
  37  require_once("$CFG->dirroot/comment/lib.php");
  38  
  39  /**
  40   * External comment API functions
  41   *
  42   * @package    core_comment
  43   * @category   external
  44   * @copyright  Costantino Cito <ccito@cvaconsulting.com>
  45   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46   * @since      Moodle 2.9
  47   */
  48  class core_comment_external extends external_api {
  49      /**
  50       * Returns description of method parameters
  51       *
  52       * @return external_function_parameters
  53       * @since Moodle 2.9
  54       */
  55      public static function get_comments_parameters() {
  56  
  57          return new external_function_parameters(
  58              array(
  59                  'contextlevel'  => new external_value(PARAM_ALPHA, 'contextlevel system, course, user...'),
  60                  'instanceid'    => new external_value(PARAM_INT, 'the Instance id of item associated with the context level'),
  61                  'component'     => new external_value(PARAM_COMPONENT, 'component'),
  62                  'itemid'        => new external_value(PARAM_INT, 'associated id'),
  63                  'area'          => new external_value(PARAM_AREA, 'string comment area', VALUE_DEFAULT, ''),
  64                  'page'          => new external_value(PARAM_INT, 'page number (0 based)', VALUE_DEFAULT, 0),
  65                  'sortdirection' => new external_value(PARAM_ALPHA, 'Sort direction: ASC or DESC', VALUE_DEFAULT, 'DESC'),
  66              )
  67          );
  68      }
  69  
  70      /**
  71       * Return a list of comments
  72       *
  73       * @param string $contextlevel ('system, course, user', etc..)
  74       * @param int $instanceid
  75       * @param string $component the name of the component
  76       * @param int $itemid the item id
  77       * @param string $area comment area
  78       * @param int $page page number
  79       * @param string $sortdirection sort direction
  80       * @return array of comments and warnings
  81       * @since Moodle 2.9
  82       */
  83      public static function get_comments($contextlevel, $instanceid, $component, $itemid, $area = '', $page = 0,
  84              $sortdirection = 'DESC') {
  85          global $CFG;
  86  
  87          $warnings = array();
  88          $arrayparams = array(
  89              'contextlevel'  => $contextlevel,
  90              'instanceid'    => $instanceid,
  91              'component'     => $component,
  92              'itemid'        => $itemid,
  93              'area'          => $area,
  94              'page'          => $page,
  95              'sortdirection' => $sortdirection,
  96          );
  97          $params = self::validate_parameters(self::get_comments_parameters(), $arrayparams);
  98  
  99          $sortdirection = strtoupper($params['sortdirection']);
 100          $directionallowedvalues = array('ASC', 'DESC');
 101          if (!in_array($sortdirection, $directionallowedvalues)) {
 102              throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' .
 103                  'allowed values are: ' . implode(',', $directionallowedvalues));
 104          }
 105  
 106          $context = self::get_context_from_params($params);
 107          self::validate_context($context);
 108  
 109          require_capability('moodle/comment:view', $context);
 110  
 111          $args = new stdClass;
 112          $args->context   = $context;
 113          $args->area      = $params['area'];
 114          $args->itemid    = $params['itemid'];
 115          $args->component = $params['component'];
 116  
 117          $commentobject = new comment($args);
 118          $comments = $commentobject->get_comments($params['page'], $sortdirection);
 119  
 120          // False means no permissions to see comments.
 121          if ($comments === false) {
 122              throw new moodle_exception('nopermissions', 'error', '', 'view comments');
 123          }
 124          $options = array('blanktarget' => true);
 125  
 126          foreach ($comments as $key => $comment) {
 127  
 128                  list($comments[$key]->content, $comments[$key]->format) = \core_external\util::format_text($comment->content,
 129                                                                                                   $comment->format,
 130                                                                                                   $context->id,
 131                                                                                                   $params['component'],
 132                                                                                                   '',
 133                                                                                                   0,
 134                                                                                                   $options);
 135          }
 136  
 137          $results = array(
 138              'comments' => $comments,
 139              'count' => $commentobject->count(),
 140              'perpage' => (!empty($CFG->commentsperpage)) ? $CFG->commentsperpage : 15,
 141              'canpost'  => $commentobject->can_post(),
 142              'warnings' => $warnings
 143          );
 144          return $results;
 145      }
 146  
 147      /**
 148       * Returns description of method result value
 149       *
 150       * @return \core_external\external_description
 151       * @since Moodle 2.9
 152       */
 153      public static function get_comments_returns() {
 154          return new external_single_structure(
 155              array(
 156                  'comments' => new external_multiple_structure(
 157                      self::get_comment_structure(), 'List of comments'
 158                  ),
 159                  'count' => new external_value(PARAM_INT,  'Total number of comments.', VALUE_OPTIONAL),
 160                  'perpage' => new external_value(PARAM_INT,  'Number of comments per page.', VALUE_OPTIONAL),
 161                  'canpost' => new external_value(PARAM_BOOL, 'Whether the user can post in this comment area.', VALUE_OPTIONAL),
 162                  'warnings' => new external_warnings()
 163              )
 164          );
 165      }
 166  
 167      /**
 168       * Helper to get the structure of a single comment.
 169       *
 170       * @return external_single_structure the comment structure.
 171       */
 172      protected static function get_comment_structure() {
 173          return new external_single_structure(
 174              array(
 175                  'id'             => new external_value(PARAM_INT,  'Comment ID'),
 176                  'content'        => new external_value(PARAM_RAW,  'The content text formatted'),
 177                  'format'         => new external_format_value('content'),
 178                  'timecreated'    => new external_value(PARAM_INT,  'Time created (timestamp)'),
 179                  'strftimeformat' => new external_value(PARAM_NOTAGS, 'Time format'),
 180                  'profileurl'     => new external_value(PARAM_URL,  'URL profile'),
 181                  'fullname'       => new external_value(PARAM_NOTAGS, 'fullname'),
 182                  'time'           => new external_value(PARAM_NOTAGS, 'Time in human format'),
 183                  'avatar'         => new external_value(PARAM_RAW,  'HTML user picture'),
 184                  'userid'         => new external_value(PARAM_INT,  'User ID'),
 185                  'delete'         => new external_value(PARAM_BOOL, 'Permission to delete=true/false', VALUE_OPTIONAL)
 186              ), 'comment'
 187          );
 188      }
 189  
 190      /**
 191       * Returns description of method parameters for the add_comments method.
 192       *
 193       * @return external_function_parameters
 194       * @since Moodle 3.8
 195       */
 196      public static function add_comments_parameters() {
 197          return new external_function_parameters(
 198              [
 199                  'comments' => new external_multiple_structure(
 200                      new external_single_structure(
 201                          [
 202                              'contextlevel' => new external_value(PARAM_ALPHA, 'contextlevel system, course, user...'),
 203                              'instanceid'   => new external_value(PARAM_INT, 'the id of item associated with the contextlevel'),
 204                              'component'    => new external_value(PARAM_COMPONENT, 'component'),
 205                              'content'      => new external_value(PARAM_RAW, 'component'),
 206                              'itemid'       => new external_value(PARAM_INT, 'associated id'),
 207                              'area'         => new external_value(PARAM_AREA, 'string comment area', VALUE_DEFAULT, ''),
 208                          ]
 209                      )
 210                  )
 211              ]
 212          );
 213      }
 214  
 215      /**
 216       * Add a comment or comments.
 217       *
 218       * @param array $comments the array of comments to create.
 219       * @return array the array containing those comments created.
 220       * @throws comment_exception
 221       * @since Moodle 3.8
 222       */
 223      public static function add_comments($comments) {
 224          global $CFG, $SITE;
 225  
 226          if (empty($CFG->usecomments)) {
 227              throw new comment_exception('commentsnotenabled', 'moodle');
 228          }
 229  
 230          $params = self::validate_parameters(self::add_comments_parameters(), ['comments' => $comments]);
 231  
 232          // Validate every intended comment before creating anything, storing the validated comment for use below.
 233          foreach ($params['comments'] as $index => $comment) {
 234              $context = self::get_context_from_params($comment);
 235              self::validate_context($context);
 236  
 237              list($context, $course, $cm) = get_context_info_array($context->id);
 238              if ($context->id == SYSCONTEXTID) {
 239                  $course = $SITE;
 240              }
 241  
 242              // Initialising comment object.
 243              $args = new stdClass();
 244              $args->context   = $context;
 245              $args->course    = $course;
 246              $args->cm        = $cm;
 247              $args->component = $comment['component'];
 248              $args->itemid    = $comment['itemid'];
 249              $args->area      = $comment['area'];
 250  
 251              $manager = new comment($args);
 252              if (!$manager->can_post()) {
 253                  throw new comment_exception('nopermissiontocomment');
 254              }
 255  
 256              $params['comments'][$index]['preparedcomment'] = $manager;
 257          }
 258  
 259          // Create the comments.
 260          $results = [];
 261          foreach ($params['comments'] as $comment) {
 262              $manager = $comment['preparedcomment'];
 263              $newcomment = $manager->add($comment['content']);
 264              $newcomment->delete = true; // USER created the comment, so they can delete it.
 265              $results[] = $newcomment;
 266          }
 267  
 268          return $results;
 269      }
 270  
 271      /**
 272       * Returns description of method result value for the add_comments method.
 273       *
 274       * @return \core_external\external_description
 275       * @since Moodle 3.8
 276       */
 277      public static function add_comments_returns() {
 278          return new external_multiple_structure(
 279              self::get_comment_structure()
 280          );
 281      }
 282  
 283      /**
 284       * Returns description of method parameters for the delete_comments() method.
 285       *
 286       * @return external_function_parameters
 287       * @since Moodle 3.8
 288       */
 289      public static function delete_comments_parameters() {
 290          return new external_function_parameters(
 291              [
 292                  'comments' => new external_multiple_structure(
 293                      new external_value(PARAM_INT, 'id of the comment', VALUE_DEFAULT, 0)
 294                  )
 295              ]
 296          );
 297      }
 298  
 299      /**
 300       * Deletes a comment or comments.
 301       *
 302       * @param array $comments array of comment ids to be deleted
 303       * @return array
 304       * @throws comment_exception
 305       * @since Moodle 3.8
 306       */
 307      public static function delete_comments(array $comments) {
 308          global $CFG, $DB, $USER, $SITE;
 309  
 310          if (empty($CFG->usecomments)) {
 311              throw new comment_exception('commentsnotenabled', 'moodle');
 312          }
 313  
 314          $params = self::validate_parameters(self::delete_comments_parameters(), ['comments' => $comments]);
 315          $commentids = $params['comments'];
 316  
 317          list($insql, $inparams) = $DB->get_in_or_equal($commentids);
 318          $commentrecords = $DB->get_records_select('comments', "id {$insql}", $inparams);
 319  
 320          // If one or more of the records could not be found, report this and fail early.
 321          if (count($commentrecords) != count($comments)) {
 322              $invalidcomments = array_diff($commentids, array_column($commentrecords, 'id'));
 323              $invalidcommentsstr = implode(',', $invalidcomments);
 324              throw new comment_exception("One or more comments could not be found by id: $invalidcommentsstr");
 325          }
 326  
 327          // Make sure we can delete every one of the comments before actually doing so.
 328          $comments = []; // Holds the comment objects, for later deletion.
 329          foreach ($commentrecords as $commentrecord) {
 330              // Validate the context.
 331              list($context, $course, $cm) = get_context_info_array($commentrecord->contextid);
 332              if ($context->id == SYSCONTEXTID) {
 333                  $course = $SITE;
 334              }
 335              self::validate_context($context);
 336  
 337              // Make sure the user is allowed to delete the comment.
 338              $args = new stdClass;
 339              $args->context   = $context;
 340              $args->course    = $course;
 341              $args->cm        = $cm;
 342              $args->component = $commentrecord->component;
 343              $args->itemid    = $commentrecord->itemid;
 344              $args->area      = $commentrecord->commentarea;
 345              $manager = new comment($args);
 346  
 347              if (!$manager->can_delete($commentrecord)) {
 348                  throw new comment_exception('nopermissiontodelentry');
 349              }
 350  
 351              // User is allowed to delete it, so store the comment object, for use below in final deletion.
 352              $comments[$commentrecord->id] = $manager;
 353          }
 354  
 355          // All comments can be deleted by the user. Make it so.
 356          foreach ($comments as $commentid => $comment) {
 357              $comment->delete($commentid);
 358          }
 359  
 360          return [];
 361      }
 362  
 363      /**
 364       * Returns description of method result value for the delete_comments() method.
 365       *
 366       * @return \core_external\external_description
 367       * @since Moodle 3.8
 368       */
 369      public static function delete_comments_returns() {
 370          return new external_warnings();
 371      }
 372  }