Search moodle.org's
Developer Documentation

See Release Notes

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

Differences Between: [Versions 311 and 402] [Versions 400 and 402] [Versions 401 and 402]

   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  namespace core_grades\external;
  18  
  19  use core_external\external_api;
  20  use core_external\external_function_parameters;
  21  use core_external\external_multiple_structure;
  22  use core_external\external_single_structure;
  23  use core_external\external_value;
  24  use core_external\external_warnings;
  25  
  26  defined('MOODLE_INTERNAL') || die;
  27  
  28  require_once("$CFG->libdir/gradelib.php");
  29  require_once("$CFG->dirroot/grade/edit/tree/lib.php");
  30  
  31  /**
  32   * Create gradecategories webservice.
  33   *
  34   * @package    core_grades
  35   * @copyright  2021 Peter Burnett <peterburnett@catalyst-au.net>
  36   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   * @since      Moodle 3.11
  38   */
  39  class create_gradecategories extends external_api {
  40      /**
  41       * Returns description of method parameters
  42       *
  43       * @return external_function_parameters
  44       * @since Moodle 3.11
  45       */
  46      public static function execute_parameters(): external_function_parameters {
  47          return new external_function_parameters(
  48              [
  49                  'courseid' => new external_value(PARAM_INT, 'id of course', VALUE_REQUIRED),
  50                  'categories' => new external_multiple_structure(
  51                      new external_single_structure([
  52                          'fullname' => new external_value(PARAM_TEXT, 'fullname of category', VALUE_REQUIRED),
  53                          'options' => new external_single_structure([
  54                              'aggregation' => new external_value(PARAM_INT, 'aggregation method', VALUE_OPTIONAL),
  55                              'aggregateonlygraded' => new external_value(PARAM_BOOL, 'exclude empty grades', VALUE_OPTIONAL),
  56                              'aggregateoutcomes' => new external_value(PARAM_BOOL, 'aggregate outcomes', VALUE_OPTIONAL),
  57                              'droplow' => new external_value(PARAM_INT, 'drop low grades', VALUE_OPTIONAL),
  58                              'itemname' => new external_value(PARAM_TEXT, 'the category total name', VALUE_OPTIONAL),
  59                              'iteminfo' => new external_value(PARAM_TEXT, 'the category iteminfo', VALUE_OPTIONAL),
  60                              'idnumber' => new external_value(PARAM_TEXT, 'the category idnumber', VALUE_OPTIONAL),
  61                              'gradetype' => new external_value(PARAM_INT, 'the grade type', VALUE_OPTIONAL),
  62                              'grademax' => new external_value(PARAM_INT, 'the grade max', VALUE_OPTIONAL),
  63                              'grademin' => new external_value(PARAM_INT, 'the grade min', VALUE_OPTIONAL),
  64                              'gradepass' => new external_value(PARAM_INT, 'the grade to pass', VALUE_OPTIONAL),
  65                              'display' => new external_value(PARAM_INT, 'the display type', VALUE_OPTIONAL),
  66                              'decimals' => new external_value(PARAM_INT, 'the decimal count', VALUE_OPTIONAL),
  67                              'hiddenuntil' => new external_value(PARAM_INT, 'grades hidden until', VALUE_OPTIONAL),
  68                              'locktime' => new external_value(PARAM_INT, 'lock grades after', VALUE_OPTIONAL),
  69                              'weightoverride' => new external_value(PARAM_BOOL, 'weight adjusted', VALUE_OPTIONAL),
  70                              'aggregationcoef2' => new external_value(PARAM_RAW, 'weight coefficient', VALUE_OPTIONAL),
  71                              'parentcategoryid' => new external_value(PARAM_INT, 'The parent category id', VALUE_OPTIONAL),
  72                              'parentcategoryidnumber' => new external_value(PARAM_TEXT,
  73                                  'the parent category idnumber', VALUE_OPTIONAL),
  74                          ], 'optional category data', VALUE_DEFAULT, []),
  75                      ], 'Category to create', VALUE_REQUIRED)
  76                  , 'Categories to create', VALUE_REQUIRED)
  77              ]
  78          );
  79      }
  80  
  81      /**
  82       * Creates gradecategories inside of the specified course.
  83       *
  84       * @param int $courseid the courseid to create the gradecategory in.
  85       * @param array $categories the categories to create.
  86       * @return array array of created categoryids and warnings.
  87       * @since Moodle 3.11
  88       */
  89      public static function execute(int $courseid, array $categories): array {
  90          $params = self::validate_parameters(self::execute_parameters(),
  91              ['courseid' => $courseid, 'categories' => $categories]);
  92  
  93          // Now params are validated, update the references.
  94          $courseid = $params['courseid'];
  95          $categories = $params['categories'];
  96  
  97          // Check that the context and permissions are OK.
  98          $context = \context_course::instance($courseid);
  99          self::validate_context($context);
 100          require_capability('moodle/grade:manage', $context);
 101  
 102          return self::create_gradecategories_from_data($courseid, $categories);
 103      }
 104  
 105      /**
 106       * Returns description of method result value
 107       *
 108       * @return external_single_structure
 109       * @since Moodle 3.11
 110       */
 111      public static function execute_returns(): external_single_structure {
 112          return new external_single_structure([
 113              'categoryids' => new external_multiple_structure(
 114                  new external_value(PARAM_INT, 'created cateogry ID')
 115              ),
 116              'warnings' => new external_warnings(),
 117          ]);
 118      }
 119  
 120      /**
 121       * Takes an array of categories and creates the inside the category tree for the supplied courseid.
 122       *
 123       * @param int $courseid the courseid to create the categories inside of.
 124       * @param array $categories the categories to create.
 125       * @return array array of results and warnings.
 126       */
 127      public static function create_gradecategories_from_data(int $courseid, array $categories): array {
 128          global $CFG, $DB;
 129  
 130          $defaultparentcat = \grade_category::fetch_course_category($courseid);
 131          // Setup default data so WS call needs to contain only data to set.
 132          // This is not done in the Parameters, so that the array of options can be optional.
 133          $defaultdata = [
 134              'aggregation' => grade_get_setting($courseid, 'aggregation', $CFG->grade_aggregation, true),
 135              'aggregateonlygraded' => 1,
 136              'aggregateoutcomes' => 0,
 137              'droplow' => 0,
 138              'grade_item_itemname' => '',
 139              'grade_item_iteminfo' => '',
 140              'grade_item_idnumber' => '',
 141              'grade_item_gradetype' => GRADE_TYPE_VALUE,
 142              'grade_item_grademax' => 100,
 143              'grade_item_grademin' => 1,
 144              'grade_item_gradepass' => 1,
 145              'grade_item_display' => GRADE_DISPLAY_TYPE_DEFAULT,
 146              // Hack. This must be -2 to use the default setting.
 147              'grade_item_decimals' => -2,
 148              'grade_item_hiddenuntil' => 0,
 149              'grade_item_locktime' => 0,
 150              'grade_item_weightoverride' => 0,
 151              'grade_item_aggregationcoef2' => 0,
 152              'parentcategory' => $defaultparentcat->id
 153          ];
 154  
 155          // Most of the data items need boilerplate prepended. These are the exceptions.
 156          $ignorekeys = [
 157              'aggregation',
 158              'aggregateonlygraded',
 159              'aggregateoutcomes',
 160              'droplow',
 161              'parentcategoryid',
 162              'parentcategoryidnumber'
 163          ];
 164  
 165          $createdcats = [];
 166          foreach ($categories as $category) {
 167              // Setup default data so WS call needs to contain only data to set.
 168              // This is not done in the Parameters, so that the array of options can be optional.
 169              $data = $defaultdata;
 170              $data['fullname'] = $category['fullname'];
 171  
 172              foreach ($category['options'] as $key => $value) {
 173                  if (!in_array($key, $ignorekeys)) {
 174                      $fullkey = 'grade_item_' . $key;
 175                      $data[$fullkey] = $value;
 176                  } else {
 177                      $data[$key] = $value;
 178                  }
 179              }
 180  
 181              // Handle parent category special case.
 182              // This figures the parent category id from the provided id OR idnumber.
 183              if (array_key_exists('parentcategoryid', $category['options']) && $parentcat = $DB->get_record('grade_categories',
 184                      ['id' => $category['options']['parentcategoryid'], 'courseid' => $courseid])) {
 185                  $data['parentcategory'] = $parentcat->id;
 186              } else if (array_key_exists('parentcategoryidnumber', $category['options']) &&
 187                      $parentcatgradeitem = $DB->get_record('grade_items', [
 188                          'itemtype' => 'category',
 189                          'courseid' => $courseid,
 190                          'idnumber' => $category['options']['parentcategoryidnumber']
 191                      ], '*', IGNORE_MULTIPLE)) {
 192                  if ($parentcat = $DB->get_record('grade_categories',
 193                          ['courseid' => $courseid, 'id' => $parentcatgradeitem->iteminstance])) {
 194                      $data['parentcategory'] = $parentcat->id;
 195                  }
 196              }
 197  
 198              // Create new gradecategory item.
 199              $gradecategory = new \grade_category(['courseid' => $courseid], false);
 200              $gradecategory->apply_default_settings();
 201              $gradecategory->apply_forced_settings();
 202  
 203              // Data Validation.
 204              if (array_key_exists('grade_item_gradetype', $data) and $data['grade_item_gradetype'] == GRADE_TYPE_SCALE) {
 205                  if (empty($data['grade_item_scaleid'])) {
 206                      $warnings[] = ['item' => 'scaleid', 'warningcode' => 'invalidscale',
 207                          'message' => get_string('missingscale', 'grades')];
 208                  }
 209              }
 210              if (array_key_exists('grade_item_grademin', $data) and array_key_exists('grade_item_grademax', $data)) {
 211                  if (($data['grade_item_grademax'] != 0 OR $data['grade_item_grademin'] != 0) AND
 212                      ($data['grade_item_grademax'] == $data['grade_item_grademin'] OR
 213                      $data['grade_item_grademax'] < $data['grade_item_grademin'])) {
 214                      $warnings[] = ['item' => 'grademax', 'warningcode' => 'invalidgrade',
 215                          'message' => get_string('incorrectminmax', 'grades')];
 216                  }
 217              }
 218  
 219              if (!empty($warnings)) {
 220                  return ['categoryids' => [], 'warnings' => $warnings];
 221              }
 222  
 223              // Now call the update function with data. Transactioned so the gradebook isn't broken on bad data.
 224              // This is done per-category so that children can correctly discover the parent categories.
 225              try {
 226                  $transaction = $DB->start_delegated_transaction();
 227                  \grade_edit_tree::update_gradecategory($gradecategory, (object) $data);
 228                  $transaction->allow_commit();
 229                  $createdcats[] = $gradecategory->id;
 230              } catch (\Exception $e) {
 231                  // If the submitted data was broken for any reason.
 232                  $warnings['database'] = $e->getMessage();
 233                  $transaction->rollback($e);
 234                  return ['warnings' => $warnings];
 235              }
 236          }
 237  
 238          return['categoryids' => $createdcats, 'warnings' => []];
 239      }
 240  }