Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

   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   * Data generator.
  19   *
  20   * @package    core
  21   * @category   test
  22   * @copyright  2012 Petr Skoda {@link http://skodak.org}
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  /**
  29   * Data generator class for unit tests and other tools that need to create fake test sites.
  30   *
  31   * @package    core
  32   * @category   test
  33   * @copyright  2012 Petr Skoda {@link http://skodak.org}
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class testing_data_generator {
  37      /** @var int The number of grade categories created */
  38      protected $gradecategorycounter = 0;
  39      /** @var int The number of grade items created */
  40      protected $gradeitemcounter = 0;
  41      /** @var int The number of grade outcomes created */
  42      protected $gradeoutcomecounter = 0;
  43      protected $usercounter = 0;
  44      protected $categorycount = 0;
  45      protected $cohortcount = 0;
  46      protected $coursecount = 0;
  47      protected $scalecount = 0;
  48      protected $groupcount = 0;
  49      protected $groupingcount = 0;
  50      protected $rolecount = 0;
  51      protected $tagcount = 0;
  52  
  53      /** @var array list of plugin generators */
  54      protected $generators = array();
  55  
  56      /** @var array lis of common last names */
  57      public $lastnames = array(
  58          'Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Miller', 'Davis', 'García', 'Rodríguez', 'Wilson',
  59          'Müller', 'Schmidt', 'Schneider', 'Fischer', 'Meyer', 'Weber', 'Schulz', 'Wagner', 'Becker', 'Hoffmann',
  60          'Novák', 'Svoboda', 'Novotný', 'Dvořák', 'Černý', 'Procházková', 'Kučerová', 'Veselá', 'Horáková', 'Němcová',
  61          'Смирнов', 'Иванов', 'Кузнецов', 'Соколов', 'Попов', 'Лебедева', 'Козлова', 'Новикова', 'Морозова', 'Петрова',
  62          '王', '李', '张', '刘', '陈', '楊', '黃', '趙', '吳', '周',
  63          '佐藤', '鈴木', '高橋', '田中', '渡辺', '伊藤', '山本', '中村', '小林', '斎藤',
  64      );
  65  
  66      /** @var array lis of common first names */
  67      public $firstnames = array(
  68          'Jacob', 'Ethan', 'Michael', 'Jayden', 'William', 'Isabella', 'Sophia', 'Emma', 'Olivia', 'Ava',
  69          'Lukas', 'Leon', 'Luca', 'Timm', 'Paul', 'Leonie', 'Leah', 'Lena', 'Hanna', 'Laura',
  70          'Jakub', 'Jan', 'Tomáš', 'Lukáš', 'Matěj', 'Tereza', 'Eliška', 'Anna', 'Adéla', 'Karolína',
  71          'Даниил', 'Максим', 'Артем', 'Иван', 'Александр', 'София', 'Анастасия', 'Дарья', 'Мария', 'Полина',
  72          '伟', '伟', '芳', '伟', '秀英', '秀英', '娜', '秀英', '伟', '敏',
  73          '翔', '大翔', '拓海', '翔太', '颯太', '陽菜', 'さくら', '美咲', '葵', '美羽',
  74      );
  75  
  76      public $loremipsum = <<<EOD
  77  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla non arcu lacinia neque faucibus fringilla. Vivamus porttitor turpis ac leo. Integer in sapien. Nullam eget nisl. Aliquam erat volutpat. Cras elementum. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Integer malesuada. Nullam lectus justo, vulputate eget mollis sed, tempor sed magna. Mauris elementum mauris vitae tortor. Aliquam erat volutpat.
  78  Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Pellentesque ipsum. Cras pede libero, dapibus nec, pretium sit amet, tempor quis. Aliquam ante. Proin in tellus sit amet nibh dignissim sagittis. Vivamus porttitor turpis ac leo. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Aliquam erat volutpat. Nulla est.
  79  Vivamus luctus egestas leo. Aenean fermentum risus id tortor. Mauris dictum facilisis augue. Aliquam erat volutpat. Aliquam ornare wisi eu metus. Aliquam id dolor. Duis condimentum augue id magna semper rutrum. Donec iaculis gravida nulla. Pellentesque ipsum. Etiam dictum tincidunt diam. Quisque tincidunt scelerisque libero. Etiam egestas wisi a erat.
  80  Integer lacinia. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris tincidunt sem sed arcu. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam id dolor. Maecenas sollicitudin. Et harum quidem rerum facilis est et expedita distinctio. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Nullam dapibus fermentum ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Pellentesque sapien. Duis risus. Mauris elementum mauris vitae tortor. Suspendisse nisl. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim.
  81  In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Maecenas lorem. Etiam posuere lacus quis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Nam sed tellus id magna elementum tincidunt. Suspendisse nisl. Vivamus luctus egestas leo. Nulla non arcu lacinia neque faucibus fringilla. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Etiam dictum tincidunt diam. Etiam commodo dui eget wisi. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Duis ante orci, molestie vitae vehicula venenatis, tincidunt ac pede. Pellentesque sapien.
  82  EOD;
  83  
  84      /**
  85       * To be called from data reset code only,
  86       * do not use in tests.
  87       * @return void
  88       */
  89      public function reset() {
  90          $this->gradecategorycounter = 0;
  91          $this->gradeitemcounter = 0;
  92          $this->gradeoutcomecounter = 0;
  93          $this->usercounter = 0;
  94          $this->categorycount = 0;
  95          $this->cohortcount = 0;
  96          $this->coursecount = 0;
  97          $this->scalecount = 0;
  98          $this->groupcount = 0;
  99          $this->groupingcount = 0;
 100          $this->rolecount = 0;
 101          $this->tagcount = 0;
 102  
 103          foreach ($this->generators as $generator) {
 104              $generator->reset();
 105          }
 106      }
 107  
 108      /**
 109       * Return generator for given plugin or component.
 110       * @param string $component the component name, e.g. 'mod_forum' or 'core_question'.
 111       * @return component_generator_base or rather an instance of the appropriate subclass.
 112       */
 113      public function get_plugin_generator($component) {
 114          // Note: This global is included so that generator have access to it.
 115          // CFG is widely used in require statements.
 116          global $CFG;
 117          list($type, $plugin) = core_component::normalize_component($component);
 118          $cleancomponent = $type . '_' . $plugin;
 119          if ($cleancomponent != $component) {
 120              debugging("Please specify the component you want a generator for as " .
 121                      "{$cleancomponent}, not {$component}.", DEBUG_DEVELOPER);
 122              $component = $cleancomponent;
 123          }
 124  
 125          if (isset($this->generators[$component])) {
 126              return $this->generators[$component];
 127          }
 128  
 129          $dir = core_component::get_component_directory($component);
 130          $lib = $dir . '/tests/generator/lib.php';
 131          if (!$dir || !is_readable($lib)) {
 132              $this->generators[$component] = $this->get_default_plugin_generator($component);
 133  
 134              return $this->generators[$component];
 135          }
 136  
 137          include_once($lib);
 138          $classname = $component . '_generator';
 139  
 140          if (class_exists($classname)) {
 141              $this->generators[$component] = new $classname($this);
 142          } else {
 143              $this->generators[$component] = $this->get_default_plugin_generator($component, $classname);
 144          }
 145  
 146          return $this->generators[$component];
 147      }
 148  
 149      /**
 150       * Create a test user
 151       * @param array|stdClass $record
 152       * @param array $options
 153       * @return stdClass user record
 154       */
 155      public function create_user($record=null, array $options=null) {
 156          global $DB, $CFG;
 157          require_once($CFG->dirroot.'/user/lib.php');
 158  
 159          $this->usercounter++;
 160          $i = $this->usercounter;
 161  
 162          $record = (array)$record;
 163  
 164          if (!isset($record['auth'])) {
 165              $record['auth'] = 'manual';
 166          }
 167  
 168          if (!isset($record['firstname']) and !isset($record['lastname'])) {
 169              $country = rand(0, 5);
 170              $firstname = rand(0, 4);
 171              $lastname = rand(0, 4);
 172              $female = rand(0, 1);
 173              $record['firstname'] = $this->firstnames[($country*10) + $firstname + ($female*5)];
 174              $record['lastname'] = $this->lastnames[($country*10) + $lastname + ($female*5)];
 175  
 176          } else if (!isset($record['firstname'])) {
 177              $record['firstname'] = 'Firstname'.$i;
 178  
 179          } else if (!isset($record['lastname'])) {
 180              $record['lastname'] = 'Lastname'.$i;
 181          }
 182  
 183          if (!isset($record['firstnamephonetic'])) {
 184              $firstnamephonetic = rand(0, 59);
 185              $record['firstnamephonetic'] = $this->firstnames[$firstnamephonetic];
 186          }
 187  
 188          if (!isset($record['lastnamephonetic'])) {
 189              $lastnamephonetic = rand(0, 59);
 190              $record['lastnamephonetic'] = $this->lastnames[$lastnamephonetic];
 191          }
 192  
 193          if (!isset($record['middlename'])) {
 194              $middlename = rand(0, 59);
 195              $record['middlename'] = $this->firstnames[$middlename];
 196          }
 197  
 198          if (!isset($record['alternatename'])) {
 199              $alternatename = rand(0, 59);
 200              $record['alternatename'] = $this->firstnames[$alternatename];
 201          }
 202  
 203          if (!isset($record['idnumber'])) {
 204              $record['idnumber'] = '';
 205          }
 206  
 207          if (!isset($record['mnethostid'])) {
 208              $record['mnethostid'] = $CFG->mnet_localhost_id;
 209          }
 210  
 211          if (!isset($record['username'])) {
 212              $record['username'] = 'username'.$i;
 213              $j = 2;
 214              while ($DB->record_exists('user', array('username'=>$record['username'], 'mnethostid'=>$record['mnethostid']))) {
 215                  $record['username'] = 'username'.$i.'_'.$j;
 216                  $j++;
 217              }
 218          }
 219  
 220          if (isset($record['password'])) {
 221              $record['password'] = hash_internal_user_password($record['password']);
 222          }
 223  
 224          if (!isset($record['email'])) {
 225              $record['email'] = $record['username'].'@example.com';
 226          }
 227  
 228          if (!isset($record['confirmed'])) {
 229              $record['confirmed'] = 1;
 230          }
 231  
 232          if (!isset($record['lastip'])) {
 233              $record['lastip'] = '0.0.0.0';
 234          }
 235  
 236          $tobedeleted = !empty($record['deleted']);
 237          unset($record['deleted']);
 238  
 239          $userid = user_create_user($record, false, false);
 240  
 241          if ($extrafields = array_intersect_key($record, ['password' => 1, 'timecreated' => 1])) {
 242              $DB->update_record('user', ['id' => $userid] + $extrafields);
 243          }
 244  
 245          if (!$tobedeleted) {
 246              // All new not deleted users must have a favourite self-conversation.
 247              $selfconversation = \core_message\api::create_conversation(
 248                  \core_message\api::MESSAGE_CONVERSATION_TYPE_SELF,
 249                  [$userid]
 250              );
 251              \core_message\api::set_favourite_conversation($selfconversation->id, $userid);
 252  
 253              // Save custom profile fields data.
 254              $hasprofilefields = array_filter($record, function($key){
 255                  return strpos($key, 'profile_field_') === 0;
 256              }, ARRAY_FILTER_USE_KEY);
 257              if ($hasprofilefields) {
 258                  require_once($CFG->dirroot.'/user/profile/lib.php');
 259                  $usernew = (object)(['id' => $userid] + $record);
 260                  profile_save_data($usernew);
 261              }
 262          }
 263  
 264          $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
 265  
 266          if (!$tobedeleted && isset($record['interests'])) {
 267              require_once($CFG->dirroot . '/user/editlib.php');
 268              if (!is_array($record['interests'])) {
 269                  $record['interests'] = preg_split('/\s*,\s*/', trim($record['interests']), -1, PREG_SPLIT_NO_EMPTY);
 270              }
 271              useredit_update_interests($user, $record['interests']);
 272          }
 273  
 274          \core\event\user_created::create_from_userid($userid)->trigger();
 275  
 276          if ($tobedeleted) {
 277              delete_user($user);
 278              $user = $DB->get_record('user', array('id' => $userid));
 279          }
 280          return $user;
 281      }
 282  
 283      /**
 284       * Create a test course category
 285       * @param array|stdClass $record
 286       * @param array $options
 287       * @return core_course_category course category record
 288       */
 289      public function create_category($record=null, array $options=null) {
 290          $this->categorycount++;
 291          $i = $this->categorycount;
 292  
 293          $record = (array)$record;
 294  
 295          if (!isset($record['name'])) {
 296              $record['name'] = 'Course category '.$i;
 297          }
 298  
 299          if (!isset($record['description'])) {
 300              $record['description'] = "Test course category $i\n$this->loremipsum";
 301          }
 302  
 303          if (!isset($record['idnumber'])) {
 304              $record['idnumber'] = '';
 305          }
 306  
 307          return core_course_category::create($record);
 308      }
 309  
 310      /**
 311       * Create test cohort.
 312       * @param array|stdClass $record
 313       * @param array $options
 314       * @return stdClass cohort record
 315       */
 316      public function create_cohort($record=null, array $options=null) {
 317          global $DB, $CFG;
 318          require_once("$CFG->dirroot/cohort/lib.php");
 319  
 320          $this->cohortcount++;
 321          $i = $this->cohortcount;
 322  
 323          $record = (array)$record;
 324  
 325          if (!isset($record['contextid'])) {
 326              $record['contextid'] = context_system::instance()->id;
 327          }
 328  
 329          if (!isset($record['name'])) {
 330              $record['name'] = 'Cohort '.$i;
 331          }
 332  
 333          if (!isset($record['idnumber'])) {
 334              $record['idnumber'] = '';
 335          }
 336  
 337          if (!isset($record['description'])) {
 338              $record['description'] = "Description for '{$record['name']}' \n$this->loremipsum";
 339          }
 340  
 341          if (!isset($record['descriptionformat'])) {
 342              $record['descriptionformat'] = FORMAT_MOODLE;
 343          }
 344  
 345          if (!isset($record['visible'])) {
 346              $record['visible'] = 1;
 347          }
 348  
 349          if (!isset($record['component'])) {
 350              $record['component'] = '';
 351          }
 352  
 353          $id = cohort_add_cohort((object)$record);
 354  
 355          return $DB->get_record('cohort', array('id'=>$id), '*', MUST_EXIST);
 356      }
 357  
 358      /**
 359       * Create a test course
 360       * @param array|stdClass $record
 361       * @param array $options with keys:
 362       *      'createsections'=>bool precreate all sections
 363       * @return stdClass course record
 364       */
 365      public function create_course($record=null, array $options=null) {
 366          global $DB, $CFG;
 367          require_once("$CFG->dirroot/course/lib.php");
 368  
 369          $this->coursecount++;
 370          $i = $this->coursecount;
 371  
 372          $record = (array)$record;
 373  
 374          if (!isset($record['fullname'])) {
 375              $record['fullname'] = 'Test course '.$i;
 376          }
 377  
 378          if (!isset($record['shortname'])) {
 379              $record['shortname'] = 'tc_'.$i;
 380          }
 381  
 382          if (!isset($record['idnumber'])) {
 383              $record['idnumber'] = '';
 384          }
 385  
 386          if (!isset($record['format'])) {
 387              $record['format'] = 'topics';
 388          }
 389  
 390          if (!isset($record['newsitems'])) {
 391              $record['newsitems'] = 0;
 392          }
 393  
 394          if (!isset($record['numsections'])) {
 395              $record['numsections'] = 5;
 396          }
 397  
 398          if (!isset($record['summary'])) {
 399              $record['summary'] = "Test course $i\n$this->loremipsum";
 400          }
 401  
 402          if (!isset($record['summaryformat'])) {
 403              $record['summaryformat'] = FORMAT_MOODLE;
 404          }
 405  
 406          if (!isset($record['category'])) {
 407              $record['category'] = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
 408          }
 409  
 410          if (!isset($record['startdate'])) {
 411              $record['startdate'] = usergetmidnight(time());
 412          }
 413  
 414          if (isset($record['tags']) && !is_array($record['tags'])) {
 415              $record['tags'] = preg_split('/\s*,\s*/', trim($record['tags']), -1, PREG_SPLIT_NO_EMPTY);
 416          }
 417  
 418          if (!empty($options['createsections']) && empty($record['numsections'])) {
 419              // Since Moodle 3.3 function create_course() automatically creates sections if numsections is specified.
 420              // For BC if 'createsections' is given but 'numsections' is not, assume the default value from config.
 421              $record['numsections'] = get_config('moodlecourse', 'numsections');
 422          }
 423  
 424          if (!empty($record['customfields'])) {
 425              foreach ($record['customfields'] as $field) {
 426                  $record['customfield_'.$field['shortname']] = $field['value'];
 427              }
 428          }
 429  
 430          $course = create_course((object)$record);
 431          context_course::instance($course->id);
 432  
 433          return $course;
 434      }
 435  
 436      /**
 437       * Create course section if does not exist yet
 438       * @param array|stdClass $record must contain 'course' and 'section' attributes
 439       * @param array|null $options
 440       * @return stdClass
 441       * @throws coding_exception
 442       */
 443      public function create_course_section($record = null, array $options = null) {
 444          global $DB;
 445  
 446          $record = (array)$record;
 447  
 448          if (empty($record['course'])) {
 449              throw new coding_exception('course must be present in testing_data_generator::create_course_section() $record');
 450          }
 451  
 452          if (!isset($record['section'])) {
 453              throw new coding_exception('section must be present in testing_data_generator::create_course_section() $record');
 454          }
 455  
 456          course_create_sections_if_missing($record['course'], $record['section']);
 457          return get_fast_modinfo($record['course'])->get_section_info($record['section']);
 458      }
 459  
 460      /**
 461       * Create a test block.
 462       *
 463       * The $record passed in becomes the basis for the new row added to the
 464       * block_instances table. You only need to supply the values of interest.
 465       * Any missing values have sensible defaults filled in, and ->blockname will be set based on $blockname.
 466       *
 467       * The $options array provides additional data, not directly related to what
 468       * will be inserted in the block_instance table, which may affect the block
 469       * that is created. The meanings of any data passed here depends on the particular
 470       * type of block being created.
 471       *
 472       * @param string $blockname the type of block to create. E.g. 'html'.
 473       * @param array|stdClass $record forms the basis for the entry to be inserted in the block_instances table.
 474       * @param array $options further, block-specific options to control how the block is created.
 475       * @return stdClass new block_instance record.
 476       */
 477      public function create_block($blockname, $record=null, array $options=array()) {
 478          $generator = $this->get_plugin_generator('block_'.$blockname);
 479          return $generator->create_instance($record, $options);
 480      }
 481  
 482      /**
 483       * Create a test activity module.
 484       *
 485       * The $record should contain the same data that you would call from
 486       * ->get_data() when the mod_[type]_mod_form is submitted, except that you
 487       * only need to supply values of interest. The only required value is
 488       * 'course'. Any missing values will have a sensible default supplied.
 489       *
 490       * The $options array provides additional data, not directly related to what
 491       * would come back from the module edit settings form, which may affect the activity
 492       * that is created. The meanings of any data passed here depends on the particular
 493       * type of activity being created.
 494       *
 495       * @param string $modulename the type of activity to create. E.g. 'forum' or 'quiz'.
 496       * @param array|stdClass $record data, as if from the module edit settings form.
 497       * @param array $options additional data that may affect how the module is created.
 498       * @return stdClass activity record new new record that was just inserted in the table
 499       *      like 'forum' or 'quiz', with a ->cmid field added.
 500       */
 501      public function create_module($modulename, $record=null, array $options=null) {
 502          $generator = $this->get_plugin_generator('mod_'.$modulename);
 503          return $generator->create_instance($record, $options);
 504      }
 505  
 506      /**
 507       * Create a test group for the specified course
 508       *
 509       * $record should be either an array or a stdClass containing infomation about the group to create.
 510       * At the very least it needs to contain courseid.
 511       * Default values are added for name, description, and descriptionformat if they are not present.
 512       *
 513       * This function calls groups_create_group() to create the group within the database.
 514       * @see groups_create_group
 515       * @param array|stdClass $record
 516       * @return stdClass group record
 517       */
 518      public function create_group($record) {
 519          global $DB, $CFG;
 520  
 521          require_once($CFG->dirroot . '/group/lib.php');
 522  
 523          $this->groupcount++;
 524          $i = str_pad($this->groupcount, 4, '0', STR_PAD_LEFT);
 525  
 526          $record = (array)$record;
 527  
 528          if (empty($record['courseid'])) {
 529              throw new coding_exception('courseid must be present in testing_data_generator::create_group() $record');
 530          }
 531  
 532          if (!isset($record['name'])) {
 533              $record['name'] = 'group-' . $i;
 534          }
 535  
 536          if (!isset($record['description'])) {
 537              $record['description'] = "Test Group $i\n{$this->loremipsum}";
 538          }
 539  
 540          if (!isset($record['descriptionformat'])) {
 541              $record['descriptionformat'] = FORMAT_MOODLE;
 542          }
 543  
 544          $id = groups_create_group((object)$record);
 545  
 546          // Allow tests to set group pictures.
 547          if (!empty($record['picturepath'])) {
 548              require_once($CFG->dirroot . '/lib/gdlib.php');
 549              $grouppicture = process_new_icon(\context_course::instance($record['courseid']), 'group', 'icon', $id,
 550                  $record['picturepath']);
 551  
 552              $DB->set_field('groups', 'picture', $grouppicture, ['id' => $id]);
 553  
 554              // Invalidate the group data as we've updated the group record.
 555              cache_helper::invalidate_by_definition('core', 'groupdata', array(), [$record['courseid']]);
 556          }
 557  
 558          return $DB->get_record('groups', array('id'=>$id));
 559      }
 560  
 561      /**
 562       * Create a test group member
 563       * @param array|stdClass $record
 564       * @throws coding_exception
 565       * @return boolean
 566       */
 567      public function create_group_member($record) {
 568          global $DB, $CFG;
 569  
 570          require_once($CFG->dirroot . '/group/lib.php');
 571  
 572          $record = (array)$record;
 573  
 574          if (empty($record['userid'])) {
 575              throw new coding_exception('user must be present in testing_util::create_group_member() $record');
 576          }
 577  
 578          if (!isset($record['groupid'])) {
 579              throw new coding_exception('group must be present in testing_util::create_group_member() $record');
 580          }
 581  
 582          if (!isset($record['component'])) {
 583              $record['component'] = null;
 584          }
 585          if (!isset($record['itemid'])) {
 586              $record['itemid'] = 0;
 587          }
 588  
 589          return groups_add_member($record['groupid'], $record['userid'], $record['component'], $record['itemid']);
 590      }
 591  
 592      /**
 593       * Create a test grouping for the specified course
 594       *
 595       * $record should be either an array or a stdClass containing infomation about the grouping to create.
 596       * At the very least it needs to contain courseid.
 597       * Default values are added for name, description, and descriptionformat if they are not present.
 598       *
 599       * This function calls groups_create_grouping() to create the grouping within the database.
 600       * @see groups_create_grouping
 601       * @param array|stdClass $record
 602       * @return stdClass grouping record
 603       */
 604      public function create_grouping($record) {
 605          global $DB, $CFG;
 606  
 607          require_once($CFG->dirroot . '/group/lib.php');
 608  
 609          $this->groupingcount++;
 610          $i = $this->groupingcount;
 611  
 612          $record = (array)$record;
 613  
 614          if (empty($record['courseid'])) {
 615              throw new coding_exception('courseid must be present in testing_data_generator::create_grouping() $record');
 616          }
 617  
 618          if (!isset($record['name'])) {
 619              $record['name'] = 'grouping-' . $i;
 620          }
 621  
 622          if (!isset($record['description'])) {
 623              $record['description'] = "Test Grouping $i\n{$this->loremipsum}";
 624          }
 625  
 626          if (!isset($record['descriptionformat'])) {
 627              $record['descriptionformat'] = FORMAT_MOODLE;
 628          }
 629  
 630          $id = groups_create_grouping((object)$record);
 631  
 632          return $DB->get_record('groupings', array('id'=>$id));
 633      }
 634  
 635      /**
 636       * Create a test grouping group
 637       * @param array|stdClass $record
 638       * @throws coding_exception
 639       * @return boolean
 640       */
 641      public function create_grouping_group($record) {
 642          global $DB, $CFG;
 643  
 644          require_once($CFG->dirroot . '/group/lib.php');
 645  
 646          $record = (array)$record;
 647  
 648          if (empty($record['groupingid'])) {
 649              throw new coding_exception('grouping must be present in testing::create_grouping_group() $record');
 650          }
 651  
 652          if (!isset($record['groupid'])) {
 653              throw new coding_exception('group must be present in testing_util::create_grouping_group() $record');
 654          }
 655  
 656          return groups_assign_grouping($record['groupingid'], $record['groupid']);
 657      }
 658  
 659      /**
 660       * Create an instance of a repository.
 661       *
 662       * @param string type of repository to create an instance for.
 663       * @param array|stdClass $record data to use to up set the instance.
 664       * @param array $options options
 665       * @return stdClass repository instance record
 666       * @since Moodle 2.5.1
 667       */
 668      public function create_repository($type, $record=null, array $options = null) {
 669          $generator = $this->get_plugin_generator('repository_'.$type);
 670          return $generator->create_instance($record, $options);
 671      }
 672  
 673      /**
 674       * Create an instance of a repository.
 675       *
 676       * @param string type of repository to create an instance for.
 677       * @param array|stdClass $record data to use to up set the instance.
 678       * @param array $options options
 679       * @return repository_type object
 680       * @since Moodle 2.5.1
 681       */
 682      public function create_repository_type($type, $record=null, array $options = null) {
 683          $generator = $this->get_plugin_generator('repository_'.$type);
 684          return $generator->create_type($record, $options);
 685      }
 686  
 687  
 688      /**
 689       * Create a test scale
 690       * @param array|stdClass $record
 691       * @param array $options
 692       * @return stdClass block instance record
 693       */
 694      public function create_scale($record=null, array $options=null) {
 695          global $DB;
 696  
 697          $this->scalecount++;
 698          $i = $this->scalecount;
 699  
 700          $record = (array)$record;
 701  
 702          if (!isset($record['name'])) {
 703              $record['name'] = 'Test scale '.$i;
 704          }
 705  
 706          if (!isset($record['scale'])) {
 707              $record['scale'] = 'A,B,C,D,F';
 708          }
 709  
 710          if (!isset($record['courseid'])) {
 711              $record['courseid'] = 0;
 712          }
 713  
 714          if (!isset($record['userid'])) {
 715              $record['userid'] = 0;
 716          }
 717  
 718          if (!isset($record['description'])) {
 719              $record['description'] = 'Test scale description '.$i;
 720          }
 721  
 722          if (!isset($record['descriptionformat'])) {
 723              $record['descriptionformat'] = FORMAT_MOODLE;
 724          }
 725  
 726          $record['timemodified'] = time();
 727  
 728          if (isset($record['id'])) {
 729              $DB->import_record('scale', $record);
 730              $DB->get_manager()->reset_sequence('scale');
 731              $id = $record['id'];
 732          } else {
 733              $id = $DB->insert_record('scale', $record);
 734          }
 735  
 736          return $DB->get_record('scale', array('id'=>$id), '*', MUST_EXIST);
 737      }
 738  
 739      /**
 740       * Creates a new role in the system.
 741       *
 742       * You can fill $record with the role 'name',
 743       * 'shortname', 'description' and 'archetype'.
 744       *
 745       * If an archetype is specified it's capabilities,
 746       * context where the role can be assigned and
 747       * all other properties are copied from the archetype;
 748       * if no archetype is specified it will create an
 749       * empty role.
 750       *
 751       * @param array|stdClass $record
 752       * @return int The new role id
 753       */
 754      public function create_role($record=null) {
 755          global $DB;
 756  
 757          $this->rolecount++;
 758          $i = $this->rolecount;
 759  
 760          $record = (array)$record;
 761  
 762          if (empty($record['shortname'])) {
 763              $record['shortname'] = 'role-' . $i;
 764          }
 765  
 766          if (empty($record['name'])) {
 767              $record['name'] = 'Test role ' . $i;
 768          }
 769  
 770          if (empty($record['description'])) {
 771              $record['description'] = 'Test role ' . $i . ' description';
 772          }
 773  
 774          if (empty($record['archetype'])) {
 775              $record['archetype'] = '';
 776          } else {
 777              $archetypes = get_role_archetypes();
 778              if (empty($archetypes[$record['archetype']])) {
 779                  throw new coding_exception('\'role\' requires the field \'archetype\' to specify a ' .
 780                      'valid archetype shortname (editingteacher, student...)');
 781              }
 782          }
 783  
 784          // Creates the role.
 785          if (!$newroleid = create_role($record['name'], $record['shortname'], $record['description'], $record['archetype'])) {
 786              throw new coding_exception('There was an error creating \'' . $record['shortname'] . '\' role');
 787          }
 788  
 789          // If no archetype was specified we allow it to be added to all contexts,
 790          // otherwise we allow it in the archetype contexts.
 791          if (!$record['archetype']) {
 792              $contextlevels = [];
 793              $usefallback = true;
 794              foreach (context_helper::get_all_levels() as $level => $title) {
 795                  if (array_key_exists($title, $record)) {
 796                      $usefallback = false;
 797                      if (!empty($record[$title])) {
 798                          $contextlevels[] = $level;
 799                      }
 800                  }
 801              }
 802  
 803              if ($usefallback) {
 804                  $contextlevels = array_keys(context_helper::get_all_levels());
 805              }
 806          } else {
 807              // Copying from the archetype default rol.
 808              $archetyperoleid = $DB->get_field(
 809                  'role',
 810                  'id',
 811                  array('shortname' => $record['archetype'], 'archetype' => $record['archetype'])
 812              );
 813              $contextlevels = get_role_contextlevels($archetyperoleid);
 814          }
 815          set_role_contextlevels($newroleid, $contextlevels);
 816  
 817          if ($record['archetype']) {
 818              // We copy all the roles the archetype can assign, override, switch to and view.
 819              if ($record['archetype']) {
 820                  $types = array('assign', 'override', 'switch', 'view');
 821                  foreach ($types as $type) {
 822                      $rolestocopy = get_default_role_archetype_allows($type, $record['archetype']);
 823                      foreach ($rolestocopy as $tocopy) {
 824                          $functionname = "core_role_set_{$type}_allowed";
 825                          $functionname($newroleid, $tocopy);
 826                      }
 827                  }
 828              }
 829  
 830              // Copying the archetype capabilities.
 831              $sourcerole = $DB->get_record('role', array('id' => $archetyperoleid));
 832              role_cap_duplicate($sourcerole, $newroleid);
 833          }
 834  
 835          $allcapabilities = get_all_capabilities();
 836          $foundcapabilities = array_intersect(array_keys($allcapabilities), array_keys($record));
 837          $systemcontext = \context_system::instance();
 838  
 839          $allpermissions = [
 840              'inherit' => CAP_INHERIT,
 841              'allow' => CAP_ALLOW,
 842              'prevent' => CAP_PREVENT,
 843              'prohibit' => CAP_PROHIBIT,
 844          ];
 845  
 846          foreach ($foundcapabilities as $capability) {
 847              $permission = $record[$capability];
 848              if (!array_key_exists($permission, $allpermissions)) {
 849                  throw new \coding_exception("Unknown capability permissions '{$permission}'");
 850              }
 851              assign_capability(
 852                  $capability,
 853                  $allpermissions[$permission],
 854                  $newroleid,
 855                  $systemcontext->id,
 856                  true
 857              );
 858          }
 859  
 860          return $newroleid;
 861      }
 862  
 863      /**
 864       * Set role capabilities for the specified role.
 865       *
 866       * @param int $roleid The Role to set capabilities for
 867       * @param array $rolecapabilities The list of capability =>permission to set for this role
 868       * @param null|context $context The context to apply this capability to
 869       */
 870      public function create_role_capability(int $roleid, array $rolecapabilities, context $context = null): void {
 871          // Map the capabilities into human-readable names.
 872          $allpermissions = [
 873              'inherit' => CAP_INHERIT,
 874              'allow' => CAP_ALLOW,
 875              'prevent' => CAP_PREVENT,
 876              'prohibit' => CAP_PROHIBIT,
 877          ];
 878  
 879          // Fetch all capabilities to check that they exist.
 880          $allcapabilities = get_all_capabilities();
 881          foreach ($rolecapabilities as $capability => $permission) {
 882              if ($permission === '') {
 883                  // Allow items to be skipped.
 884                  continue;
 885              }
 886  
 887              if (!array_key_exists($capability, $allcapabilities)) {
 888                  throw new \coding_exception("Unknown capability '{$capability}'");
 889              }
 890  
 891              if (!array_key_exists($permission, $allpermissions)) {
 892                  throw new \coding_exception("Unknown capability permissions '{$permission}'");
 893              }
 894  
 895              assign_capability(
 896                  $capability,
 897                  $allpermissions[$permission],
 898                  $roleid,
 899                  $context->id,
 900                  true
 901              );
 902          }
 903      }
 904  
 905      /**
 906       * Create a tag.
 907       *
 908       * @param array|stdClass $record
 909       * @return stdClass the tag record
 910       */
 911      public function create_tag($record = null) {
 912          global $DB, $USER;
 913  
 914          $this->tagcount++;
 915          $i = $this->tagcount;
 916  
 917          $record = (array) $record;
 918  
 919          if (!isset($record['userid'])) {
 920              $record['userid'] = $USER->id;
 921          }
 922  
 923          if (!isset($record['rawname'])) {
 924              if (isset($record['name'])) {
 925                  $record['rawname'] = $record['name'];
 926              } else {
 927                  $record['rawname'] = 'Tag name ' . $i;
 928              }
 929          }
 930  
 931          // Attribute 'name' should be a lowercase version of 'rawname', if not set.
 932          if (!isset($record['name'])) {
 933              $record['name'] = core_text::strtolower($record['rawname']);
 934          } else {
 935              $record['name'] = core_text::strtolower($record['name']);
 936          }
 937  
 938          if (!isset($record['tagcollid'])) {
 939              $record['tagcollid'] = core_tag_collection::get_default();
 940          }
 941  
 942          if (!isset($record['description'])) {
 943              $record['description'] = 'Tag description';
 944          }
 945  
 946          if (!isset($record['descriptionformat'])) {
 947              $record['descriptionformat'] = FORMAT_MOODLE;
 948          }
 949  
 950          if (!isset($record['flag'])) {
 951              $record['flag'] = 0;
 952          }
 953  
 954          if (!isset($record['timemodified'])) {
 955              $record['timemodified'] = time();
 956          }
 957  
 958          $id = $DB->insert_record('tag', $record);
 959  
 960          return $DB->get_record('tag', array('id' => $id), '*', MUST_EXIST);
 961      }
 962  
 963      /**
 964       * Helper method which combines $defaults with the values specified in $record.
 965       * If $record is an object, it is converted to an array.
 966       * Then, for each key that is in $defaults, but not in $record, the value
 967       * from $defaults is copied.
 968       * @param array $defaults the default value for each field with
 969       * @param array|stdClass $record
 970       * @return array updated $record.
 971       */
 972      public function combine_defaults_and_record(array $defaults, $record) {
 973          $record = (array) $record;
 974  
 975          foreach ($defaults as $key => $defaults) {
 976              if (!array_key_exists($key, $record)) {
 977                  $record[$key] = $defaults;
 978              }
 979          }
 980          return $record;
 981      }
 982  
 983      /**
 984       * Simplified enrolment of user to course using default options.
 985       *
 986       * It is strongly recommended to use only this method for 'manual' and 'self' plugins only!!!
 987       *
 988       * @param int $userid
 989       * @param int $courseid
 990       * @param int|string $roleidorshortname optional role id or role shortname, use only with manual plugin
 991       * @param string $enrol name of enrol plugin,
 992       *     there must be exactly one instance in course,
 993       *     it must support enrol_user() method.
 994       * @param int $timestart (optional) 0 means unknown
 995       * @param int $timeend (optional) 0 means forever
 996       * @param int $status (optional) default to ENROL_USER_ACTIVE for new enrolments
 997       * @return bool success
 998       */
 999      public function enrol_user($userid, $courseid, $roleidorshortname = null, $enrol = 'manual',
1000              $timestart = 0, $timeend = 0, $status = null) {
1001          global $DB;
1002  
1003          // If role is specified by shortname, convert it into an id.
1004          if (!is_numeric($roleidorshortname) && is_string($roleidorshortname)) {
1005              $roleid = $DB->get_field('role', 'id', array('shortname' => $roleidorshortname), MUST_EXIST);
1006          } else {
1007              $roleid = $roleidorshortname;
1008          }
1009  
1010          if (!$plugin = enrol_get_plugin($enrol)) {
1011              return false;
1012          }
1013  
1014          $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'enrol'=>$enrol));
1015          if (count($instances) != 1) {
1016              return false;
1017          }
1018          $instance = reset($instances);
1019  
1020          if (is_null($roleid) and $instance->roleid) {
1021              $roleid = $instance->roleid;
1022          }
1023  
1024          $plugin->enrol_user($instance, $userid, $roleid, $timestart, $timeend, $status);
1025          return true;
1026      }
1027  
1028      /**
1029       * Assigns the specified role to a user in the context.
1030       *
1031       * @param int $roleid
1032       * @param int $userid
1033       * @param int $contextid Defaults to the system context
1034       * @return int new/existing id of the assignment
1035       */
1036      public function role_assign($roleid, $userid, $contextid = false) {
1037  
1038          // Default to the system context.
1039          if (!$contextid) {
1040              $context = context_system::instance();
1041              $contextid = $context->id;
1042          }
1043  
1044          if (empty($roleid)) {
1045              throw new coding_exception('roleid must be present in testing_data_generator::role_assign() arguments');
1046          }
1047  
1048          if (empty($userid)) {
1049              throw new coding_exception('userid must be present in testing_data_generator::role_assign() arguments');
1050          }
1051  
1052          return role_assign($roleid, $userid, $contextid);
1053      }
1054  
1055      /**
1056       * Create a grade_category.
1057       *
1058       * @param array|stdClass $record
1059       * @return stdClass the grade category record
1060       */
1061      public function create_grade_category($record = null) {
1062          global $CFG;
1063  
1064          $this->gradecategorycounter++;
1065  
1066          $record = (array)$record;
1067  
1068          if (empty($record['courseid'])) {
1069              throw new coding_exception('courseid must be present in testing::create_grade_category() $record');
1070          }
1071  
1072          if (!isset($record['fullname'])) {
1073              $record['fullname'] = 'Grade category ' . $this->gradecategorycounter;
1074          }
1075  
1076          // For gradelib classes.
1077          require_once($CFG->libdir . '/gradelib.php');
1078          // Create new grading category in this course.
1079          $gradecategory = new grade_category(array('courseid' => $record['courseid']), false);
1080          $gradecategory->apply_default_settings();
1081          grade_category::set_properties($gradecategory, $record);
1082          $gradecategory->apply_forced_settings();
1083          $gradecategory->insert();
1084  
1085          // This creates a default grade item for the category
1086          $gradeitem = $gradecategory->load_grade_item();
1087  
1088          $gradecategory->update_from_db();
1089          return $gradecategory->get_record_data();
1090      }
1091  
1092      /**
1093       * Create a grade_grade.
1094       *
1095       * @param array $record
1096       * @return grade_grade the grade record
1097       */
1098      public function create_grade_grade(?array $record = null): grade_grade {
1099          global $DB, $USER;
1100  
1101          $item = $DB->get_record('grade_items', ['id' => $record['itemid']]);
1102          $userid = $record['userid'] ?? $USER->id;
1103  
1104          unset($record['itemid']);
1105          unset($record['userid']);
1106  
1107          if ($item->itemtype === 'mod') {
1108              $cm = get_coursemodule_from_instance($item->itemmodule, $item->iteminstance);
1109              $module = new $item->itemmodule(context_module::instance($cm->id), $cm, false);
1110              $record['attemptnumber'] = $record['attemptnumber'] ?? 0;
1111  
1112              $module->save_grade($userid, (object) $record);
1113  
1114              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1115          } else {
1116              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1117              $record['rawgrade'] = $record['rawgrade'] ?? $record['grade'] ?? null;
1118              $record['finalgrade'] = $record['finalgrade'] ?? $record['grade'] ?? null;
1119  
1120              unset($record['grade']);
1121  
1122              if ($grade) {
1123                  $fields = $grade->required_fields + array_keys($grade->optional_fields);
1124  
1125                  foreach ($fields as $field) {
1126                      $grade->{$field} = $record[$field] ?? $grade->{$field};
1127                  }
1128  
1129                  $grade->update();
1130              } else {
1131                  $record['userid'] = $userid;
1132                  $record['itemid'] = $item->id;
1133  
1134                  $grade = new grade_grade($record, false);
1135  
1136                  $grade->insert();
1137              }
1138          }
1139  
1140          return $grade;
1141      }
1142  
1143      /**
1144       * Create a grade_item.
1145       *
1146       * @param array|stdClass $record
1147       * @return stdClass the grade item record
1148       */
1149      public function create_grade_item($record = null) {
1150          global $CFG;
1151          require_once("$CFG->libdir/gradelib.php");
1152  
1153          $this->gradeitemcounter++;
1154  
1155          if (!isset($record['itemtype'])) {
1156              $record['itemtype'] = 'manual';
1157          }
1158  
1159          if (!isset($record['itemname'])) {
1160              $record['itemname'] = 'Grade item ' . $this->gradeitemcounter;
1161          }
1162  
1163          if (isset($record['outcomeid'])) {
1164              $outcome = new grade_outcome(array('id' => $record['outcomeid']));
1165              $record['scaleid'] = $outcome->scaleid;
1166          }
1167          if (isset($record['scaleid'])) {
1168              $record['gradetype'] = GRADE_TYPE_SCALE;
1169          } else if (!isset($record['gradetype'])) {
1170              $record['gradetype'] = GRADE_TYPE_VALUE;
1171          }
1172  
1173          // Create new grade item in this course.
1174          $gradeitem = new grade_item($record, false);
1175          $gradeitem->insert();
1176  
1177          $gradeitem->update_from_db();
1178          return $gradeitem->get_record_data();
1179      }
1180  
1181      /**
1182       * Create a grade_outcome.
1183       *
1184       * @param array|stdClass $record
1185       * @return stdClass the grade outcome record
1186       */
1187      public function create_grade_outcome($record = null) {
1188          global $CFG;
1189  
1190          $this->gradeoutcomecounter++;
1191          $i = $this->gradeoutcomecounter;
1192  
1193          if (!isset($record['fullname'])) {
1194              $record['fullname'] = 'Grade outcome ' . $i;
1195          }
1196  
1197          // For gradelib classes.
1198          require_once($CFG->libdir . '/gradelib.php');
1199          // Create new grading outcome in this course.
1200          $gradeoutcome = new grade_outcome($record, false);
1201          $gradeoutcome->insert();
1202  
1203          $gradeoutcome->update_from_db();
1204          return $gradeoutcome->get_record_data();
1205      }
1206  
1207      /**
1208       * Helper function used to create an LTI tool.
1209       *
1210       * @param array $data
1211       * @return stdClass the tool
1212       */
1213      public function create_lti_tool($data = array()) {
1214          global $DB;
1215  
1216          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1217          $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1218  
1219          // Create a course if no course id was specified.
1220          if (empty($data->courseid)) {
1221              $course = $this->create_course();
1222              $data->courseid = $course->id;
1223          } else {
1224              $course = get_course($data->courseid);
1225          }
1226  
1227          if (!empty($data->cmid)) {
1228              $data->contextid = context_module::instance($data->cmid)->id;
1229          } else {
1230              $data->contextid = context_course::instance($data->courseid)->id;
1231          }
1232  
1233          // Set it to enabled if no status was specified.
1234          if (!isset($data->status)) {
1235              $data->status = ENROL_INSTANCE_ENABLED;
1236          }
1237  
1238          // Add some extra necessary fields to the data.
1239          $data->name = 'Test LTI';
1240          $data->roleinstructor = $studentrole->id;
1241          $data->rolelearner = $teacherrole->id;
1242  
1243          // Get the enrol LTI plugin.
1244          $enrolplugin = enrol_get_plugin('lti');
1245          $instanceid = $enrolplugin->add_instance($course, (array) $data);
1246  
1247          // Get the tool associated with this instance.
1248          return $DB->get_record('enrol_lti_tools', array('enrolid' => $instanceid));
1249      }
1250  
1251      /**
1252       * Helper function used to create an event.
1253       *
1254       * @param   array   $data
1255       * @return  stdClass
1256       */
1257      public function create_event($data = []) {
1258          global $CFG;
1259  
1260          require_once($CFG->dirroot . '/calendar/lib.php');
1261          $record = new \stdClass();
1262          $record->name = 'event name';
1263          $record->repeat = 0;
1264          $record->repeats = 0;
1265          $record->timestart = time();
1266          $record->timeduration = 0;
1267          $record->timesort = 0;
1268          $record->eventtype = 'user';
1269          $record->courseid = 0;
1270          $record->categoryid = 0;
1271  
1272          foreach ($data as $key => $value) {
1273              $record->$key = $value;
1274          }
1275  
1276          switch ($record->eventtype) {
1277              case 'user':
1278                  unset($record->categoryid);
1279                  unset($record->courseid);
1280                  unset($record->groupid);
1281                  break;
1282              case 'group':
1283                  unset($record->categoryid);
1284                  break;
1285              case 'course':
1286                  unset($record->categoryid);
1287                  unset($record->groupid);
1288                  break;
1289              case 'category':
1290                  unset($record->courseid);
1291                  unset($record->groupid);
1292                  break;
1293              case 'site':
1294                  unset($record->categoryid);
1295                  unset($record->courseid);
1296                  unset($record->groupid);
1297                  break;
1298          }
1299  
1300          $event = new calendar_event($record);
1301          $event->create($record);
1302  
1303          return $event->properties();
1304      }
1305  
1306      /**
1307       * Create a new course custom field category with the given name.
1308       *
1309       * @param   array $data Array with data['name'] of category
1310       * @return  \core_customfield\category_controller   The created category
1311       */
1312      public function create_custom_field_category($data) : \core_customfield\category_controller {
1313          return $this->get_plugin_generator('core_customfield')->create_category($data);
1314      }
1315  
1316      /**
1317       * Create a new custom field
1318       *
1319       * @param   array $data Array with 'name', 'shortname' and 'type' of the field
1320       * @return  \core_customfield\field_controller   The created field
1321       */
1322      public function create_custom_field($data) : \core_customfield\field_controller {
1323          global $DB;
1324          if (empty($data['categoryid']) && !empty($data['category'])) {
1325              $data['categoryid'] = $DB->get_field('customfield_category', 'id', ['name' => $data['category']]);
1326              unset($data['category']);
1327          }
1328          return $this->get_plugin_generator('core_customfield')->create_field($data);
1329      }
1330  
1331      /**
1332       * Create a new category for custom profile fields.
1333       *
1334       * @param array $data Array with 'name' and optionally 'sortorder'
1335       * @return \stdClass New category object
1336       */
1337      public function create_custom_profile_field_category(array $data): \stdClass {
1338          global $DB;
1339  
1340          // Pick next sortorder if not defined.
1341          if (!array_key_exists('sortorder', $data)) {
1342              $data['sortorder'] = (int)$DB->get_field_sql('SELECT MAX(sortorder) FROM {user_info_category}') + 1;
1343          }
1344  
1345          $category = (object)[
1346              'name' => $data['name'],
1347              'sortorder' => $data['sortorder']
1348          ];
1349          $category->id = $DB->insert_record('user_info_category', $category);
1350  
1351          return $category;
1352      }
1353  
1354      /**
1355       * Creates a new custom profile field.
1356       *
1357       * Optional fields are:
1358       *
1359       * categoryid (or use 'category' to specify by name). If you don't specify
1360       * either, it will add the field to a 'Testing' category, which will be created for you if
1361       * necessary.
1362       *
1363       * sortorder (if you don't specify this, it will pick the next one in the category).
1364       *
1365       * all the other database fields (if you don't specify this, it will pick sensible defaults
1366       * based on the data type).
1367       *
1368       * @param array $data Array with 'datatype', 'shortname', and 'name'
1369       * @return \stdClass Database object from the user_info_field table
1370       */
1371      public function create_custom_profile_field(array $data): \stdClass {
1372          global $DB, $CFG;
1373          require_once($CFG->dirroot . '/user/profile/lib.php');
1374  
1375          // Set up category if necessary.
1376          if (!array_key_exists('categoryid', $data)) {
1377              if (array_key_exists('category', $data)) {
1378                  $data['categoryid'] = $DB->get_field('user_info_category', 'id',
1379                          ['name' => $data['category']], MUST_EXIST);
1380              } else {
1381                  // Make up a 'Testing' category or use existing.
1382                  $data['categoryid'] = $DB->get_field('user_info_category', 'id', ['name' => 'Testing']);
1383                  if (!$data['categoryid']) {
1384                      $created = $this->create_custom_profile_field_category(['name' => 'Testing']);
1385                      $data['categoryid'] = $created->id;
1386                  }
1387              }
1388          }
1389  
1390          // Pick sort order if necessary.
1391          if (!array_key_exists('sortorder', $data)) {
1392              $data['sortorder'] = (int)$DB->get_field_sql(
1393                      'SELECT MAX(sortorder) FROM {user_info_field} WHERE categoryid = ?',
1394                      [$data['categoryid']]) + 1;
1395          }
1396  
1397          if ($data['datatype'] === 'menu' && isset($data['param1'])) {
1398              // Convert new lines to the proper character.
1399              $data['param1'] = str_replace('\n', "\n", $data['param1']);
1400          }
1401  
1402          // Defaults for other values.
1403          $defaults = [
1404              'description' => '',
1405              'descriptionformat' => 0,
1406              'required' => 0,
1407              'locked' => 0,
1408              'visible' => PROFILE_VISIBLE_ALL,
1409              'forceunique' => 0,
1410              'signup' => 0,
1411              'defaultdata' => '',
1412              'defaultdataformat' => 0,
1413              'param1' => '',
1414              'param2' => '',
1415              'param3' => '',
1416              'param4' => '',
1417              'param5' => ''
1418          ];
1419  
1420          // Type-specific defaults for other values.
1421          $typedefaults = [
1422              'text' => [
1423                  'param1' => 30,
1424                  'param2' => 2048
1425              ],
1426              'menu' => [
1427                  'param1' => "Yes\nNo",
1428                  'defaultdata' => 'No'
1429              ],
1430              'datetime' => [
1431                  'param1' => '2010',
1432                  'param2' => '2015',
1433                  'param3' => 1
1434              ],
1435              'checkbox' => [
1436                  'defaultdata' => 0
1437              ]
1438          ];
1439          foreach ($typedefaults[$data['datatype']] ?? [] as $field => $value) {
1440              $defaults[$field] = $value;
1441          }
1442  
1443          foreach ($defaults as $field => $value) {
1444              if (!array_key_exists($field, $data)) {
1445                  $data[$field] = $value;
1446              }
1447          }
1448  
1449          $data['id'] = $DB->insert_record('user_info_field', $data);
1450          return (object)$data;
1451      }
1452  
1453      /**
1454       * Create a new user, and enrol them in the specified course as the supplied role.
1455       *
1456       * @param   \stdClass   $course The course to enrol in
1457       * @param   string      $role The role to give within the course
1458       * @param   \stdClass   $userparams User parameters
1459       * @return  \stdClass   The created user
1460       */
1461      public function create_and_enrol($course, $role = 'student', $userparams = null, $enrol = 'manual',
1462              $timestart = 0, $timeend = 0, $status = null) {
1463          global $DB;
1464  
1465          $user = $this->create_user($userparams);
1466          $roleid = $DB->get_field('role', 'id', ['shortname' => $role ]);
1467  
1468          $this->enrol_user($user->id, $course->id, $roleid, $enrol, $timestart, $timeend, $status);
1469  
1470          return $user;
1471      }
1472  
1473      /**
1474       * Create a new last access record for a given user in a course.
1475       *
1476       * @param   \stdClass   $user The user
1477       * @param   \stdClass   $course The course the user accessed
1478       * @param   int         $timestamp The timestamp for when the user last accessed the course
1479       * @return  \stdClass   The user_lastaccess record
1480       */
1481      public function create_user_course_lastaccess(\stdClass $user, \stdClass $course, int $timestamp): \stdClass {
1482          global $DB;
1483  
1484          $record = [
1485              'userid' => $user->id,
1486              'courseid' => $course->id,
1487              'timeaccess' => $timestamp,
1488          ];
1489  
1490          $recordid = $DB->insert_record('user_lastaccess', $record);
1491  
1492          return $DB->get_record('user_lastaccess', ['id' => $recordid], '*', MUST_EXIST);
1493      }
1494  
1495      /**
1496       * Gets a default generator for a given component.
1497       *
1498       * @param string $component The component name, e.g. 'mod_forum' or 'core_question'.
1499       * @param string $classname The name of the class missing from the generators file.
1500       * @return component_generator_base The generator.
1501       */
1502      protected function get_default_plugin_generator(string $component, ?string $classname = null) {
1503          [$type, $plugin] = core_component::normalize_component($component);
1504  
1505          switch ($type) {
1506              case 'block':
1507                  return new default_block_generator($this, $plugin);
1508          }
1509  
1510          if (is_null($classname)) {
1511              throw new coding_exception("Component {$component} does not support " .
1512                  "generators yet. Missing tests/generator/lib.php.");
1513          }
1514  
1515          throw new coding_exception("Component {$component} does not support " .
1516              "data generators yet. Class {$classname} not found.");
1517      }
1518  
1519  }