Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 400 and 402] [Versions 400 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  defined('MOODLE_INTERNAL') || die();
  28  
  29  require_once("$CFG->libdir/externallib.php");
  30  require_once("$CFG->dirroot/comment/lib.php");
  31  
  32  /**
  33   * External comment API functions
  34   *
  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
  40   */
  41  class core_comment_external extends external_api {
  42      /**
  43       * Returns description of method parameters
  44       *
  45       * @return external_function_parameters
  46       * @since Moodle 2.9
  47       */
  48      public static function get_comments_parameters() {
  49  
  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'),
  59              )
  60          );
  61      }
  62  
  63      /**
  64       * Return a list of comments
  65       *
  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
  75       */
  76      public static function get_comments($contextlevel, $instanceid, $component, $itemid, $area = '', $page = 0,
  77              $sortdirection = 'DESC') {
  78          global $CFG;
  79  
  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,
  89          );
  90          $params = self::validate_parameters(self::get_comments_parameters(), $arrayparams);
  91  
  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));
  97          }
  98  
  99          $context = self::get_context_from_params($params);
 100          self::validate_context($context);
 101  
 102          require_capability('moodle/comment:view', $context);
 103  
 104          $args = new stdClass;
 105          $args->context   = $context;
 106          $args->area      = $params['area'];
 107          $args->itemid    = $params['itemid'];
 108          $args->component = $params['component'];
 109  
 110          $commentobject = new comment($args);
 111          $comments = $commentobject->get_comments($params['page'], $sortdirection);
 112  
 113          // False means no permissions to see comments.
 114          if ($comments === false) {
 115              throw new moodle_exception('nopermissions', 'error', '', 'view comments');
 116          }
 117          $options = array('blanktarget' => true);
 118  
 119          foreach ($comments as $key => $comment) {
 120  
 121                  list($comments[$key]->content, $comments[$key]->format) = external_format_text($comment->content,
 122                                                                                                   $comment->format,
 123                                                                                                   $context->id,
 124                                                                                                   $params['component'],
 125                                                                                                   '',
 126                                                                                                   0,
 127                                                                                                   $options);
 128          }
 129  
 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
 136          );
 137          return $results;
 138      }
 139  
 140      /**
 141       * Returns description of method result value
 142       *
 143       * @return external_description
 144       * @since Moodle 2.9
 145       */
 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'
 151                  ),
 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()
 156              )
 157          );
 158      }
 159  
 160      /**
 161       * Helper to get the structure of a single comment.
 162       *
 163       * @return external_single_structure the comment structure.
 164       */
 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'
 180          );
 181      }
 182  
 183      /**
 184       * Returns description of method parameters for the add_comments method.
 185       *
 186       * @return external_function_parameters
 187       * @since Moodle 3.8
 188       */
 189      public static function add_comments_parameters() {
 190          return new external_function_parameters(
 191              [
 192                  'comments' => new external_multiple_structure(
 193                      new external_single_structure(
 194                          [
 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, ''),
 201                          ]
 202                      )
 203                  )
 204              ]
 205          );
 206      }
 207  
 208      /**
 209       * Add a comment or comments.
 210       *
 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
 215       */
 216      public static function add_comments($comments) {
 217          global $CFG, $SITE;
 218  
 219          if (empty($CFG->usecomments)) {
 220              throw new comment_exception('commentsnotenabled', 'moodle');
 221          }
 222  
 223          $params = self::validate_parameters(self::add_comments_parameters(), ['comments' => $comments]);
 224  
 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);
 229  
 230              list($context, $course, $cm) = get_context_info_array($context->id);
 231              if ($context->id == SYSCONTEXTID) {
 232                  $course = $SITE;
 233              }
 234  
 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'];
 243  
 244              $manager = new comment($args);
 245              if (!$manager->can_post()) {
 246                  throw new comment_exception('nopermissiontocomment');
 247              }
 248  
 249              $params['comments'][$index]['preparedcomment'] = $manager;
 250          }
 251  
 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;
 259          }
 260  
 261          return $results;
 262      }
 263  
 264      /**
 265       * Returns description of method result value for the add_comments method.
 266       *
 267       * @return external_description
 268       * @since Moodle 3.8
 269       */
 270      public static function add_comments_returns() {
 271          return new external_multiple_structure(
 272              self::get_comment_structure()
 273          );
 274      }
 275  
 276      /**
 277       * Returns description of method parameters for the delete_comments() method.
 278       *
 279       * @return external_function_parameters
 280       * @since Moodle 3.8
 281       */
 282      public static function delete_comments_parameters() {
 283          return new external_function_parameters(
 284              [
 285                  'comments' => new external_multiple_structure(
 286                      new external_value(PARAM_INT, 'id of the comment', VALUE_DEFAULT, 0)
 287                  )
 288              ]
 289          );
 290      }
 291  
 292      /**
 293       * Deletes a comment or comments.
 294       *
 295       * @param array $comments array of comment ids to be deleted
 296       * @return array
 297       * @throws comment_exception
 298       * @since Moodle 3.8
 299       */
 300      public static function delete_comments(array $comments) {
 301          global $CFG, $DB, $USER, $SITE;
 302  
 303          if (empty($CFG->usecomments)) {
 304              throw new comment_exception('commentsnotenabled', 'moodle');
 305          }
 306  
 307          $params = self::validate_parameters(self::delete_comments_parameters(), ['comments' => $comments]);
 308          $commentids = $params['comments'];
 309  
 310          list($insql, $inparams) = $DB->get_in_or_equal($commentids);
 311          $commentrecords = $DB->get_records_select('comments', "id {$insql}", $inparams);
 312  
 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");
 318          }
 319  
 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;
 327              }
 328              self::validate_context($context);
 329  
 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);
 339  
 340              if (!$manager->can_delete($commentrecord)) {
 341                  throw new comment_exception('nopermissiontodelentry');
 342              }
 343  
 344              // User is allowed to delete it, so store the comment object, for use below in final deletion.
 345              $comments[$commentrecord->id] = $manager;
 346          }
 347  
 348          // All comments can be deleted by the user. Make it so.
 349          foreach ($comments as $commentid => $comment) {
 350              $comment->delete($commentid);
 351          }
 352  
 353          return [];
 354      }
 355  
 356      /**
 357       * Returns description of method result value for the delete_comments() method.
 358       *
 359       * @return external_description
 360       * @since Moodle 3.8
 361       */
 362      public static function delete_comments_returns() {
 363          return new external_warnings();
 364      }
 365  }