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 38 and 311] [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 = array_keys(context_helper::get_all_levels());
 793          } else {
 794              // Copying from the archetype default rol.
 795              $archetyperoleid = $DB->get_field(
 796                  'role',
 797                  'id',
 798                  array('shortname' => $record['archetype'], 'archetype' => $record['archetype'])
 799              );
 800              $contextlevels = get_role_contextlevels($archetyperoleid);
 801          }
 802          set_role_contextlevels($newroleid, $contextlevels);
 803  
 804          if ($record['archetype']) {
 805  
 806              // We copy all the roles the archetype can assign, override, switch to and view.
 807              if ($record['archetype']) {
 808                  $types = array('assign', 'override', 'switch', 'view');
 809                  foreach ($types as $type) {
 810                      $rolestocopy = get_default_role_archetype_allows($type, $record['archetype']);
 811                      foreach ($rolestocopy as $tocopy) {
 812                          $functionname = "core_role_set_{$type}_allowed";
 813                          $functionname($newroleid, $tocopy);
 814                      }
 815                  }
 816              }
 817  
 818              // Copying the archetype capabilities.
 819              $sourcerole = $DB->get_record('role', array('id' => $archetyperoleid));
 820              role_cap_duplicate($sourcerole, $newroleid);
 821          }
 822  
 823          return $newroleid;
 824      }
 825  
 826      /**
 827       * Create a tag.
 828       *
 829       * @param array|stdClass $record
 830       * @return stdClass the tag record
 831       */
 832      public function create_tag($record = null) {
 833          global $DB, $USER;
 834  
 835          $this->tagcount++;
 836          $i = $this->tagcount;
 837  
 838          $record = (array) $record;
 839  
 840          if (!isset($record['userid'])) {
 841              $record['userid'] = $USER->id;
 842          }
 843  
 844          if (!isset($record['rawname'])) {
 845              if (isset($record['name'])) {
 846                  $record['rawname'] = $record['name'];
 847              } else {
 848                  $record['rawname'] = 'Tag name ' . $i;
 849              }
 850          }
 851  
 852          // Attribute 'name' should be a lowercase version of 'rawname', if not set.
 853          if (!isset($record['name'])) {
 854              $record['name'] = core_text::strtolower($record['rawname']);
 855          } else {
 856              $record['name'] = core_text::strtolower($record['name']);
 857          }
 858  
 859          if (!isset($record['tagcollid'])) {
 860              $record['tagcollid'] = core_tag_collection::get_default();
 861          }
 862  
 863          if (!isset($record['description'])) {
 864              $record['description'] = 'Tag description';
 865          }
 866  
 867          if (!isset($record['descriptionformat'])) {
 868              $record['descriptionformat'] = FORMAT_MOODLE;
 869          }
 870  
 871          if (!isset($record['flag'])) {
 872              $record['flag'] = 0;
 873          }
 874  
 875          if (!isset($record['timemodified'])) {
 876              $record['timemodified'] = time();
 877          }
 878  
 879          $id = $DB->insert_record('tag', $record);
 880  
 881          return $DB->get_record('tag', array('id' => $id), '*', MUST_EXIST);
 882      }
 883  
 884      /**
 885       * Helper method which combines $defaults with the values specified in $record.
 886       * If $record is an object, it is converted to an array.
 887       * Then, for each key that is in $defaults, but not in $record, the value
 888       * from $defaults is copied.
 889       * @param array $defaults the default value for each field with
 890       * @param array|stdClass $record
 891       * @return array updated $record.
 892       */
 893      public function combine_defaults_and_record(array $defaults, $record) {
 894          $record = (array) $record;
 895  
 896          foreach ($defaults as $key => $defaults) {
 897              if (!array_key_exists($key, $record)) {
 898                  $record[$key] = $defaults;
 899              }
 900          }
 901          return $record;
 902      }
 903  
 904      /**
 905       * Simplified enrolment of user to course using default options.
 906       *
 907       * It is strongly recommended to use only this method for 'manual' and 'self' plugins only!!!
 908       *
 909       * @param int $userid
 910       * @param int $courseid
 911       * @param int|string $roleidorshortname optional role id or role shortname, use only with manual plugin
 912       * @param string $enrol name of enrol plugin,
 913       *     there must be exactly one instance in course,
 914       *     it must support enrol_user() method.
 915       * @param int $timestart (optional) 0 means unknown
 916       * @param int $timeend (optional) 0 means forever
 917       * @param int $status (optional) default to ENROL_USER_ACTIVE for new enrolments
 918       * @return bool success
 919       */
 920      public function enrol_user($userid, $courseid, $roleidorshortname = null, $enrol = 'manual',
 921              $timestart = 0, $timeend = 0, $status = null) {
 922          global $DB;
 923  
 924          // If role is specified by shortname, convert it into an id.
 925          if (!is_numeric($roleidorshortname) && is_string($roleidorshortname)) {
 926              $roleid = $DB->get_field('role', 'id', array('shortname' => $roleidorshortname), MUST_EXIST);
 927          } else {
 928              $roleid = $roleidorshortname;
 929          }
 930  
 931          if (!$plugin = enrol_get_plugin($enrol)) {
 932              return false;
 933          }
 934  
 935          $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'enrol'=>$enrol));
 936          if (count($instances) != 1) {
 937              return false;
 938          }
 939          $instance = reset($instances);
 940  
 941          if (is_null($roleid) and $instance->roleid) {
 942              $roleid = $instance->roleid;
 943          }
 944  
 945          $plugin->enrol_user($instance, $userid, $roleid, $timestart, $timeend, $status);
 946          return true;
 947      }
 948  
 949      /**
 950       * Assigns the specified role to a user in the context.
 951       *
 952       * @param int $roleid
 953       * @param int $userid
 954       * @param int $contextid Defaults to the system context
 955       * @return int new/existing id of the assignment
 956       */
 957      public function role_assign($roleid, $userid, $contextid = false) {
 958  
 959          // Default to the system context.
 960          if (!$contextid) {
 961              $context = context_system::instance();
 962              $contextid = $context->id;
 963          }
 964  
 965          if (empty($roleid)) {
 966              throw new coding_exception('roleid must be present in testing_data_generator::role_assign() arguments');
 967          }
 968  
 969          if (empty($userid)) {
 970              throw new coding_exception('userid must be present in testing_data_generator::role_assign() arguments');
 971          }
 972  
 973          return role_assign($roleid, $userid, $contextid);
 974      }
 975  
 976      /**
 977       * Create a grade_category.
 978       *
 979       * @param array|stdClass $record
 980       * @return stdClass the grade category record
 981       */
 982      public function create_grade_category($record = null) {
 983          global $CFG;
 984  
 985          $this->gradecategorycounter++;
 986  
 987          $record = (array)$record;
 988  
 989          if (empty($record['courseid'])) {
 990              throw new coding_exception('courseid must be present in testing::create_grade_category() $record');
 991          }
 992  
 993          if (!isset($record['fullname'])) {
 994              $record['fullname'] = 'Grade category ' . $this->gradecategorycounter;
 995          }
 996  
 997          // For gradelib classes.
 998          require_once($CFG->libdir . '/gradelib.php');
 999          // Create new grading category in this course.
1000          $gradecategory = new grade_category(array('courseid' => $record['courseid']), false);
1001          $gradecategory->apply_default_settings();
1002          grade_category::set_properties($gradecategory, $record);
1003          $gradecategory->apply_forced_settings();
1004          $gradecategory->insert();
1005  
1006          // This creates a default grade item for the category
1007          $gradeitem = $gradecategory->load_grade_item();
1008  
1009          $gradecategory->update_from_db();
1010          return $gradecategory->get_record_data();
1011      }
1012  
1013      /**
1014       * Create a grade_grade.
1015       *
1016       * @param array $record
1017       * @return grade_grade the grade record
1018       */
1019      public function create_grade_grade(?array $record = null): grade_grade {
1020          global $DB, $USER;
1021  
1022          $item = $DB->get_record('grade_items', ['id' => $record['itemid']]);
1023          $userid = $record['userid'] ?? $USER->id;
1024  
1025          unset($record['itemid']);
1026          unset($record['userid']);
1027  
1028          if ($item->itemtype === 'mod') {
1029              $cm = get_coursemodule_from_instance($item->itemmodule, $item->iteminstance);
1030              $module = new $item->itemmodule(context_module::instance($cm->id), $cm, false);
1031              $record['attemptnumber'] = $record['attemptnumber'] ?? 0;
1032  
1033              $module->save_grade($userid, (object) $record);
1034  
1035              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1036          } else {
1037              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1038              $record['rawgrade'] = $record['rawgrade'] ?? $record['grade'] ?? null;
1039              $record['finalgrade'] = $record['finalgrade'] ?? $record['grade'] ?? null;
1040  
1041              unset($record['grade']);
1042  
1043              if ($grade) {
1044                  $fields = $grade->required_fields + array_keys($grade->optional_fields);
1045  
1046                  foreach ($fields as $field) {
1047                      $grade->{$field} = $record[$field] ?? $grade->{$field};
1048                  }
1049  
1050                  $grade->update();
1051              } else {
1052                  $record['userid'] = $userid;
1053                  $record['itemid'] = $item->id;
1054  
1055                  $grade = new grade_grade($record, false);
1056  
1057                  $grade->insert();
1058              }
1059          }
1060  
1061          return $grade;
1062      }
1063  
1064      /**
1065       * Create a grade_item.
1066       *
1067       * @param array|stdClass $record
1068       * @return stdClass the grade item record
1069       */
1070      public function create_grade_item($record = null) {
1071          global $CFG;
1072          require_once("$CFG->libdir/gradelib.php");
1073  
1074          $this->gradeitemcounter++;
1075  
1076          if (!isset($record['itemtype'])) {
1077              $record['itemtype'] = 'manual';
1078          }
1079  
1080          if (!isset($record['itemname'])) {
1081              $record['itemname'] = 'Grade item ' . $this->gradeitemcounter;
1082          }
1083  
1084          if (isset($record['outcomeid'])) {
1085              $outcome = new grade_outcome(array('id' => $record['outcomeid']));
1086              $record['scaleid'] = $outcome->scaleid;
1087          }
1088          if (isset($record['scaleid'])) {
1089              $record['gradetype'] = GRADE_TYPE_SCALE;
1090          } else if (!isset($record['gradetype'])) {
1091              $record['gradetype'] = GRADE_TYPE_VALUE;
1092          }
1093  
1094          // Create new grade item in this course.
1095          $gradeitem = new grade_item($record, false);
1096          $gradeitem->insert();
1097  
1098          $gradeitem->update_from_db();
1099          return $gradeitem->get_record_data();
1100      }
1101  
1102      /**
1103       * Create a grade_outcome.
1104       *
1105       * @param array|stdClass $record
1106       * @return stdClass the grade outcome record
1107       */
1108      public function create_grade_outcome($record = null) {
1109          global $CFG;
1110  
1111          $this->gradeoutcomecounter++;
1112          $i = $this->gradeoutcomecounter;
1113  
1114          if (!isset($record['fullname'])) {
1115              $record['fullname'] = 'Grade outcome ' . $i;
1116          }
1117  
1118          // For gradelib classes.
1119          require_once($CFG->libdir . '/gradelib.php');
1120          // Create new grading outcome in this course.
1121          $gradeoutcome = new grade_outcome($record, false);
1122          $gradeoutcome->insert();
1123  
1124          $gradeoutcome->update_from_db();
1125          return $gradeoutcome->get_record_data();
1126      }
1127  
1128      /**
1129       * Helper function used to create an LTI tool.
1130       *
1131       * @param array $data
1132       * @return stdClass the tool
1133       */
1134      public function create_lti_tool($data = array()) {
1135          global $DB;
1136  
1137          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1138          $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1139  
1140          // Create a course if no course id was specified.
1141          if (empty($data->courseid)) {
1142              $course = $this->create_course();
1143              $data->courseid = $course->id;
1144          } else {
1145              $course = get_course($data->courseid);
1146          }
1147  
1148          if (!empty($data->cmid)) {
1149              $data->contextid = context_module::instance($data->cmid)->id;
1150          } else {
1151              $data->contextid = context_course::instance($data->courseid)->id;
1152          }
1153  
1154          // Set it to enabled if no status was specified.
1155          if (!isset($data->status)) {
1156              $data->status = ENROL_INSTANCE_ENABLED;
1157          }
1158  
1159          // Add some extra necessary fields to the data.
1160          $data->name = 'Test LTI';
1161          $data->roleinstructor = $studentrole->id;
1162          $data->rolelearner = $teacherrole->id;
1163  
1164          // Get the enrol LTI plugin.
1165          $enrolplugin = enrol_get_plugin('lti');
1166          $instanceid = $enrolplugin->add_instance($course, (array) $data);
1167  
1168          // Get the tool associated with this instance.
1169          return $DB->get_record('enrol_lti_tools', array('enrolid' => $instanceid));
1170      }
1171  
1172      /**
1173       * Helper function used to create an event.
1174       *
1175       * @param   array   $data
1176       * @return  stdClass
1177       */
1178      public function create_event($data = []) {
1179          global $CFG;
1180  
1181          require_once($CFG->dirroot . '/calendar/lib.php');
1182          $record = new \stdClass();
1183          $record->name = 'event name';
1184          $record->repeat = 0;
1185          $record->repeats = 0;
1186          $record->timestart = time();
1187          $record->timeduration = 0;
1188          $record->timesort = 0;
1189          $record->eventtype = 'user';
1190          $record->courseid = 0;
1191          $record->categoryid = 0;
1192  
1193          foreach ($data as $key => $value) {
1194              $record->$key = $value;
1195          }
1196  
1197          switch ($record->eventtype) {
1198              case 'user':
1199                  unset($record->categoryid);
1200                  unset($record->courseid);
1201                  unset($record->groupid);
1202                  break;
1203              case 'group':
1204                  unset($record->categoryid);
1205                  break;
1206              case 'course':
1207                  unset($record->categoryid);
1208                  unset($record->groupid);
1209                  break;
1210              case 'category':
1211                  unset($record->courseid);
1212                  unset($record->groupid);
1213                  break;
1214              case 'site':
1215                  unset($record->categoryid);
1216                  unset($record->courseid);
1217                  unset($record->groupid);
1218                  break;
1219          }
1220  
1221          $event = new calendar_event($record);
1222          $event->create($record);
1223  
1224          return $event->properties();
1225      }
1226  
1227      /**
1228       * Create a new course custom field category with the given name.
1229       *
1230       * @param   array $data Array with data['name'] of category
1231       * @return  \core_customfield\category_controller   The created category
1232       */
1233      public function create_custom_field_category($data) : \core_customfield\category_controller {
1234          return $this->get_plugin_generator('core_customfield')->create_category($data);
1235      }
1236  
1237      /**
1238       * Create a new custom field
1239       *
1240       * @param   array $data Array with 'name', 'shortname' and 'type' of the field
1241       * @return  \core_customfield\field_controller   The created field
1242       */
1243      public function create_custom_field($data) : \core_customfield\field_controller {
1244          global $DB;
1245          if (empty($data['categoryid']) && !empty($data['category'])) {
1246              $data['categoryid'] = $DB->get_field('customfield_category', 'id', ['name' => $data['category']]);
1247              unset($data['category']);
1248          }
1249          return $this->get_plugin_generator('core_customfield')->create_field($data);
1250      }
1251  
1252      /**
1253       * Create a new category for custom profile fields.
1254       *
1255       * @param array $data Array with 'name' and optionally 'sortorder'
1256       * @return \stdClass New category object
1257       */
1258      public function create_custom_profile_field_category(array $data): \stdClass {
1259          global $DB;
1260  
1261          // Pick next sortorder if not defined.
1262          if (!array_key_exists('sortorder', $data)) {
1263              $data['sortorder'] = (int)$DB->get_field_sql('SELECT MAX(sortorder) FROM {user_info_category}') + 1;
1264          }
1265  
1266          $category = (object)[
1267              'name' => $data['name'],
1268              'sortorder' => $data['sortorder']
1269          ];
1270          $category->id = $DB->insert_record('user_info_category', $category);
1271  
1272          return $category;
1273      }
1274  
1275      /**
1276       * Creates a new custom profile field.
1277       *
1278       * Optional fields are:
1279       *
1280       * categoryid (or use 'category' to specify by name). If you don't specify
1281       * either, it will add the field to a 'Testing' category, which will be created for you if
1282       * necessary.
1283       *
1284       * sortorder (if you don't specify this, it will pick the next one in the category).
1285       *
1286       * all the other database fields (if you don't specify this, it will pick sensible defaults
1287       * based on the data type).
1288       *
1289       * @param array $data Array with 'datatype', 'shortname', and 'name'
1290       * @return \stdClass Database object from the user_info_field table
1291       */
1292      public function create_custom_profile_field(array $data): \stdClass {
1293          global $DB, $CFG;
1294          require_once($CFG->dirroot . '/user/profile/lib.php');
1295  
1296          // Set up category if necessary.
1297          if (!array_key_exists('categoryid', $data)) {
1298              if (array_key_exists('category', $data)) {
1299                  $data['categoryid'] = $DB->get_field('user_info_category', 'id',
1300                          ['name' => $data['category']], MUST_EXIST);
1301              } else {
1302                  // Make up a 'Testing' category or use existing.
1303                  $data['categoryid'] = $DB->get_field('user_info_category', 'id', ['name' => 'Testing']);
1304                  if (!$data['categoryid']) {
1305                      $created = $this->create_custom_profile_field_category(['name' => 'Testing']);
1306                      $data['categoryid'] = $created->id;
1307                  }
1308              }
1309          }
1310  
1311          // Pick sort order if necessary.
1312          if (!array_key_exists('sortorder', $data)) {
1313              $data['sortorder'] = (int)$DB->get_field_sql(
1314                      'SELECT MAX(sortorder) FROM {user_info_field} WHERE categoryid = ?',
1315                      [$data['categoryid']]) + 1;
1316          }
1317  
1318          if ($data['datatype'] === 'menu' && isset($data['param1'])) {
1319              // Convert new lines to the proper character.
1320              $data['param1'] = str_replace('\n', "\n", $data['param1']);
1321          }
1322  
1323          // Defaults for other values.
1324          $defaults = [
1325              'description' => '',
1326              'descriptionformat' => 0,
1327              'required' => 0,
1328              'locked' => 0,
1329              'visible' => PROFILE_VISIBLE_ALL,
1330              'forceunique' => 0,
1331              'signup' => 0,
1332              'defaultdata' => '',
1333              'defaultdataformat' => 0,
1334              'param1' => '',
1335              'param2' => '',
1336              'param3' => '',
1337              'param4' => '',
1338              'param5' => ''
1339          ];
1340  
1341          // Type-specific defaults for other values.
1342          $typedefaults = [
1343              'text' => [
1344                  'param1' => 30,
1345                  'param2' => 2048
1346              ],
1347              'menu' => [
1348                  'param1' => "Yes\nNo",
1349                  'defaultdata' => 'No'
1350              ],
1351              'datetime' => [
1352                  'param1' => '2010',
1353                  'param2' => '2015',
1354                  'param3' => 1
1355              ],
1356              'checkbox' => [
1357                  'defaultdata' => 0
1358              ]
1359          ];
1360          foreach ($typedefaults[$data['datatype']] ?? [] as $field => $value) {
1361              $defaults[$field] = $value;
1362          }
1363  
1364          foreach ($defaults as $field => $value) {
1365              if (!array_key_exists($field, $data)) {
1366                  $data[$field] = $value;
1367              }
1368          }
1369  
1370          $data['id'] = $DB->insert_record('user_info_field', $data);
1371          return (object)$data;
1372      }
1373  
1374      /**
1375       * Create a new user, and enrol them in the specified course as the supplied role.
1376       *
1377       * @param   \stdClass   $course The course to enrol in
1378       * @param   string      $role The role to give within the course
1379       * @param   \stdClass   $userparams User parameters
1380       * @return  \stdClass   The created user
1381       */
1382      public function create_and_enrol($course, $role = 'student', $userparams = null, $enrol = 'manual',
1383              $timestart = 0, $timeend = 0, $status = null) {
1384          global $DB;
1385  
1386          $user = $this->create_user($userparams);
1387          $roleid = $DB->get_field('role', 'id', ['shortname' => $role ]);
1388  
1389          $this->enrol_user($user->id, $course->id, $roleid, $enrol, $timestart, $timeend, $status);
1390  
1391          return $user;
1392      }
1393  
1394      /**
1395       * Create a new last access record for a given user in a course.
1396       *
1397       * @param   \stdClass   $user The user
1398       * @param   \stdClass   $course The course the user accessed
1399       * @param   int         $timestamp The timestamp for when the user last accessed the course
1400       * @return  \stdClass   The user_lastaccess record
1401       */
1402      public function create_user_course_lastaccess(\stdClass $user, \stdClass $course, int $timestamp): \stdClass {
1403          global $DB;
1404  
1405          $record = [
1406              'userid' => $user->id,
1407              'courseid' => $course->id,
1408              'timeaccess' => $timestamp,
1409          ];
1410  
1411          $recordid = $DB->insert_record('user_lastaccess', $record);
1412  
1413          return $DB->get_record('user_lastaccess', ['id' => $recordid], '*', MUST_EXIST);
1414      }
1415  
1416      /**
1417       * Gets a default generator for a given component.
1418       *
1419       * @param string $component The component name, e.g. 'mod_forum' or 'core_question'.
1420       * @param string $classname The name of the class missing from the generators file.
1421       * @return component_generator_base The generator.
1422       */
1423      protected function get_default_plugin_generator(string $component, ?string $classname = null) {
1424          [$type, $plugin] = core_component::normalize_component($component);
1425  
1426          switch ($type) {
1427              case 'block':
1428                  return new default_block_generator($this, $plugin);
1429          }
1430  
1431          if (is_null($classname)) {
1432              throw new coding_exception("Component {$component} does not support " .
1433                  "generators yet. Missing tests/generator/lib.php.");
1434          }
1435  
1436          throw new coding_exception("Component {$component} does not support " .
1437              "data generators yet. Class {$classname} not found.");
1438      }
1439  
1440  }