Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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