Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  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|string $role either an int role id or a string role shortname.
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($role, $userid, $contextid = false) {
1037          global $DB;
1038  
1039          // Default to the system context.
1040          if (!$contextid) {
1041              $context = context_system::instance();
1042              $contextid = $context->id;
1043          }
1044  
1045          if (empty($role)) {
1046              throw new coding_exception('roleid must be present in testing_data_generator::role_assign() arguments');
1047          }
1048          if (!is_number($role)) {
1049              $role = $DB->get_field('role', 'id', ['shortname' => $role], MUST_EXIST);
1050          }
1051  
1052          if (empty($userid)) {
1053              throw new coding_exception('userid must be present in testing_data_generator::role_assign() arguments');
1054          }
1055  
1056          return role_assign($role, $userid, $contextid);
1057      }
1058  
1059      /**
1060       * Create a grade_category.
1061       *
1062       * @param array|stdClass $record
1063       * @return stdClass the grade category record
1064       */
1065      public function create_grade_category($record = null) {
1066          global $CFG;
1067  
1068          $this->gradecategorycounter++;
1069  
1070          $record = (array)$record;
1071  
1072          if (empty($record['courseid'])) {
1073              throw new coding_exception('courseid must be present in testing::create_grade_category() $record');
1074          }
1075  
1076          if (!isset($record['fullname'])) {
1077              $record['fullname'] = 'Grade category ' . $this->gradecategorycounter;
1078          }
1079  
1080          // For gradelib classes.
1081          require_once($CFG->libdir . '/gradelib.php');
1082          // Create new grading category in this course.
1083          $gradecategory = new grade_category(array('courseid' => $record['courseid']), false);
1084          $gradecategory->apply_default_settings();
1085          grade_category::set_properties($gradecategory, $record);
1086          $gradecategory->apply_forced_settings();
1087          $gradecategory->insert();
1088  
1089          // This creates a default grade item for the category
1090          $gradeitem = $gradecategory->load_grade_item();
1091  
1092          $gradecategory->update_from_db();
1093          return $gradecategory->get_record_data();
1094      }
1095  
1096      /**
1097       * Create a grade_grade.
1098       *
1099       * @param array $record
1100       * @return grade_grade the grade record
1101       */
1102      public function create_grade_grade(?array $record = null): grade_grade {
1103          global $DB, $USER;
1104  
1105          $item = $DB->get_record('grade_items', ['id' => $record['itemid']]);
1106          $userid = $record['userid'] ?? $USER->id;
1107  
1108          unset($record['itemid']);
1109          unset($record['userid']);
1110  
1111          if ($item->itemtype === 'mod') {
1112              $cm = get_coursemodule_from_instance($item->itemmodule, $item->iteminstance);
1113              $module = new $item->itemmodule(context_module::instance($cm->id), $cm, false);
1114              $record['attemptnumber'] = $record['attemptnumber'] ?? 0;
1115  
1116              $module->save_grade($userid, (object) $record);
1117  
1118              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1119          } else {
1120              $grade = grade_grade::fetch(['userid' => $userid, 'itemid' => $item->id]);
1121              $record['rawgrade'] = $record['rawgrade'] ?? $record['grade'] ?? null;
1122              $record['finalgrade'] = $record['finalgrade'] ?? $record['grade'] ?? null;
1123  
1124              unset($record['grade']);
1125  
1126              if ($grade) {
1127                  $fields = $grade->required_fields + array_keys($grade->optional_fields);
1128  
1129                  foreach ($fields as $field) {
1130                      $grade->{$field} = $record[$field] ?? $grade->{$field};
1131                  }
1132  
1133                  $grade->update();
1134              } else {
1135                  $record['userid'] = $userid;
1136                  $record['itemid'] = $item->id;
1137  
1138                  $grade = new grade_grade($record, false);
1139  
1140                  $grade->insert();
1141              }
1142          }
1143  
1144          return $grade;
1145      }
1146  
1147      /**
1148       * Create a grade_item.
1149       *
1150       * @param array|stdClass $record
1151       * @return stdClass the grade item record
1152       */
1153      public function create_grade_item($record = null) {
1154          global $CFG;
1155          require_once("$CFG->libdir/gradelib.php");
1156  
1157          $this->gradeitemcounter++;
1158  
1159          if (!isset($record['itemtype'])) {
1160              $record['itemtype'] = 'manual';
1161          }
1162  
1163          if (!isset($record['itemname'])) {
1164              $record['itemname'] = 'Grade item ' . $this->gradeitemcounter;
1165          }
1166  
1167          if (isset($record['outcomeid'])) {
1168              $outcome = new grade_outcome(array('id' => $record['outcomeid']));
1169              $record['scaleid'] = $outcome->scaleid;
1170          }
1171          if (isset($record['scaleid'])) {
1172              $record['gradetype'] = GRADE_TYPE_SCALE;
1173          } else if (!isset($record['gradetype'])) {
1174              $record['gradetype'] = GRADE_TYPE_VALUE;
1175          }
1176  
1177          // Create new grade item in this course.
1178          $gradeitem = new grade_item($record, false);
1179          $gradeitem->insert();
1180  
1181          $gradeitem->update_from_db();
1182          return $gradeitem->get_record_data();
1183      }
1184  
1185      /**
1186       * Create a grade_outcome.
1187       *
1188       * @param array|stdClass $record
1189       * @return stdClass the grade outcome record
1190       */
1191      public function create_grade_outcome($record = null) {
1192          global $CFG;
1193  
1194          $this->gradeoutcomecounter++;
1195          $i = $this->gradeoutcomecounter;
1196  
1197          if (!isset($record['fullname'])) {
1198              $record['fullname'] = 'Grade outcome ' . $i;
1199          }
1200  
1201          // For gradelib classes.
1202          require_once($CFG->libdir . '/gradelib.php');
1203          // Create new grading outcome in this course.
1204          $gradeoutcome = new grade_outcome($record, false);
1205          $gradeoutcome->insert();
1206  
1207          $gradeoutcome->update_from_db();
1208          return $gradeoutcome->get_record_data();
1209      }
1210  
1211      /**
1212       * Helper function used to create an LTI tool.
1213       *
1214       * @param array $data
1215       * @return stdClass the tool
1216       */
1217      public function create_lti_tool($data = array()) {
1218          global $DB;
1219  
1220          $studentrole = $DB->get_record('role', array('shortname' => 'student'));
1221          $teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1222  
1223          // Create a course if no course id was specified.
1224          if (empty($data->courseid)) {
1225              $course = $this->create_course();
1226              $data->courseid = $course->id;
1227          } else {
1228              $course = get_course($data->courseid);
1229          }
1230  
1231          if (!empty($data->cmid)) {
1232              $data->contextid = context_module::instance($data->cmid)->id;
1233          } else {
1234              $data->contextid = context_course::instance($data->courseid)->id;
1235          }
1236  
1237          // Set it to enabled if no status was specified.
1238          if (!isset($data->status)) {
1239              $data->status = ENROL_INSTANCE_ENABLED;
1240          }
1241  
1242          // Default to legacy lti version.
1243          if (empty($data->ltiversion) || !in_array($data->ltiversion, ['LTI-1p0/LTI-2p0', 'LTI-1p3'])) {
1244              $data->ltiversion = 'LTI-1p0/LTI-2p0';
1245          }
1246  
1247          // Add some extra necessary fields to the data.
1248          $data->name = $data->name ?? 'Test LTI';
1249          $data->roleinstructor = $teacherrole->id;
1250          $data->rolelearner = $studentrole->id;
1251  
1252          // Get the enrol LTI plugin.
1253          $enrolplugin = enrol_get_plugin('lti');
1254          $instanceid = $enrolplugin->add_instance($course, (array) $data);
1255  
1256          // Get the tool associated with this instance.
1257          return $DB->get_record('enrol_lti_tools', array('enrolid' => $instanceid));
1258      }
1259  
1260      /**
1261       * Helper function used to create an event.
1262       *
1263       * @param   array   $data
1264       * @return  stdClass
1265       */
1266      public function create_event($data = []) {
1267          global $CFG;
1268  
1269          require_once($CFG->dirroot . '/calendar/lib.php');
1270          $record = new \stdClass();
1271          $record->name = 'event name';
1272          $record->repeat = 0;
1273          $record->repeats = 0;
1274          $record->timestart = time();
1275          $record->timeduration = 0;
1276          $record->timesort = 0;
1277          $record->eventtype = 'user';
1278          $record->courseid = 0;
1279          $record->categoryid = 0;
1280  
1281          foreach ($data as $key => $value) {
1282              $record->$key = $value;
1283          }
1284  
1285          switch ($record->eventtype) {
1286              case 'user':
1287                  unset($record->categoryid);
1288                  unset($record->courseid);
1289                  unset($record->groupid);
1290                  break;
1291              case 'group':
1292                  unset($record->categoryid);
1293                  break;
1294              case 'course':
1295                  unset($record->categoryid);
1296                  unset($record->groupid);
1297                  break;
1298              case 'category':
1299                  unset($record->courseid);
1300                  unset($record->groupid);
1301                  break;
1302              case 'site':
1303                  unset($record->categoryid);
1304                  unset($record->courseid);
1305                  unset($record->groupid);
1306                  break;
1307          }
1308  
1309          $event = new calendar_event($record);
1310          $event->create($record);
1311  
1312          return $event->properties();
1313      }
1314  
1315      /**
1316       * Create a new course custom field category with the given name.
1317       *
1318       * @param   array $data Array with data['name'] of category
1319       * @return  \core_customfield\category_controller   The created category
1320       */
1321      public function create_custom_field_category($data) : \core_customfield\category_controller {
1322          return $this->get_plugin_generator('core_customfield')->create_category($data);
1323      }
1324  
1325      /**
1326       * Create a new custom field
1327       *
1328       * @param   array $data Array with 'name', 'shortname' and 'type' of the field
1329       * @return  \core_customfield\field_controller   The created field
1330       */
1331      public function create_custom_field($data) : \core_customfield\field_controller {
1332          global $DB;
1333          if (empty($data['categoryid']) && !empty($data['category'])) {
1334              $data['categoryid'] = $DB->get_field('customfield_category', 'id', ['name' => $data['category']]);
1335              unset($data['category']);
1336          }
1337          return $this->get_plugin_generator('core_customfield')->create_field($data);
1338      }
1339  
1340      /**
1341       * Create a new category for custom profile fields.
1342       *
1343       * @param array $data Array with 'name' and optionally 'sortorder'
1344       * @return \stdClass New category object
1345       */
1346      public function create_custom_profile_field_category(array $data): \stdClass {
1347          global $DB;
1348  
1349          // Pick next sortorder if not defined.
1350          if (!array_key_exists('sortorder', $data)) {
1351              $data['sortorder'] = (int)$DB->get_field_sql('SELECT MAX(sortorder) FROM {user_info_category}') + 1;
1352          }
1353  
1354          $category = (object)[
1355              'name' => $data['name'],
1356              'sortorder' => $data['sortorder']
1357          ];
1358          $category->id = $DB->insert_record('user_info_category', $category);
1359  
1360          return $category;
1361      }
1362  
1363      /**
1364       * Creates a new custom profile field.
1365       *
1366       * Optional fields are:
1367       *
1368       * categoryid (or use 'category' to specify by name). If you don't specify
1369       * either, it will add the field to a 'Testing' category, which will be created for you if
1370       * necessary.
1371       *
1372       * sortorder (if you don't specify this, it will pick the next one in the category).
1373       *
1374       * all the other database fields (if you don't specify this, it will pick sensible defaults
1375       * based on the data type).
1376       *
1377       * @param array $data Array with 'datatype', 'shortname', and 'name'
1378       * @return \stdClass Database object from the user_info_field table
1379       */
1380      public function create_custom_profile_field(array $data): \stdClass {
1381          global $DB, $CFG;
1382          require_once($CFG->dirroot . '/user/profile/lib.php');
1383  
1384          // Set up category if necessary.
1385          if (!array_key_exists('categoryid', $data)) {
1386              if (array_key_exists('category', $data)) {
1387                  $data['categoryid'] = $DB->get_field('user_info_category', 'id',
1388                          ['name' => $data['category']], MUST_EXIST);
1389              } else {
1390                  // Make up a 'Testing' category or use existing.
1391                  $data['categoryid'] = $DB->get_field('user_info_category', 'id', ['name' => 'Testing']);
1392                  if (!$data['categoryid']) {
1393                      $created = $this->create_custom_profile_field_category(['name' => 'Testing']);
1394                      $data['categoryid'] = $created->id;
1395                  }
1396              }
1397          }
1398  
1399          // Pick sort order if necessary.
1400          if (!array_key_exists('sortorder', $data)) {
1401              $data['sortorder'] = (int)$DB->get_field_sql(
1402                      'SELECT MAX(sortorder) FROM {user_info_field} WHERE categoryid = ?',
1403                      [$data['categoryid']]) + 1;
1404          }
1405  
1406          if ($data['datatype'] === 'menu' && isset($data['param1'])) {
1407              // Convert new lines to the proper character.
1408              $data['param1'] = str_replace('\n', "\n", $data['param1']);
1409          }
1410  
1411          // Defaults for other values.
1412          $defaults = [
1413              'description' => '',
1414              'descriptionformat' => 0,
1415              'required' => 0,
1416              'locked' => 0,
1417              'visible' => PROFILE_VISIBLE_ALL,
1418              'forceunique' => 0,
1419              'signup' => 0,
1420              'defaultdata' => '',
1421              'defaultdataformat' => 0,
1422              'param1' => '',
1423              'param2' => '',
1424              'param3' => '',
1425              'param4' => '',
1426              'param5' => ''
1427          ];
1428  
1429          // Type-specific defaults for other values.
1430          $typedefaults = [
1431              'text' => [
1432                  'param1' => 30,
1433                  'param2' => 2048
1434              ],
1435              'menu' => [
1436                  'param1' => "Yes\nNo",
1437                  'defaultdata' => 'No'
1438              ],
1439              'datetime' => [
1440                  'param1' => '2010',
1441                  'param2' => '2015',
1442                  'param3' => 1
1443              ],
1444              'checkbox' => [
1445                  'defaultdata' => 0
1446              ]
1447          ];
1448          foreach ($typedefaults[$data['datatype']] ?? [] as $field => $value) {
1449              $defaults[$field] = $value;
1450          }
1451  
1452          foreach ($defaults as $field => $value) {
1453              if (!array_key_exists($field, $data)) {
1454                  $data[$field] = $value;
1455              }
1456          }
1457  
1458          $data['id'] = $DB->insert_record('user_info_field', $data);
1459          return (object)$data;
1460      }
1461  
1462      /**
1463       * Create a new user, and enrol them in the specified course as the supplied role.
1464       *
1465       * @param   \stdClass   $course The course to enrol in
1466       * @param   string      $role The role to give within the course
1467       * @param   \stdClass   $userparams User parameters
1468       * @return  \stdClass   The created user
1469       */
1470      public function create_and_enrol($course, $role = 'student', $userparams = null, $enrol = 'manual',
1471              $timestart = 0, $timeend = 0, $status = null) {
1472          global $DB;
1473  
1474          $user = $this->create_user($userparams);
1475          $roleid = $DB->get_field('role', 'id', ['shortname' => $role ]);
1476  
1477          $this->enrol_user($user->id, $course->id, $roleid, $enrol, $timestart, $timeend, $status);
1478  
1479          return $user;
1480      }
1481  
1482      /**
1483       * Create a new last access record for a given user in a course.
1484       *
1485       * @param   \stdClass   $user The user
1486       * @param   \stdClass   $course The course the user accessed
1487       * @param   int         $timestamp The timestamp for when the user last accessed the course
1488       * @return  \stdClass   The user_lastaccess record
1489       */
1490      public function create_user_course_lastaccess(\stdClass $user, \stdClass $course, int $timestamp): \stdClass {
1491          global $DB;
1492  
1493          $record = [
1494              'userid' => $user->id,
1495              'courseid' => $course->id,
1496              'timeaccess' => $timestamp,
1497          ];
1498  
1499          $recordid = $DB->insert_record('user_lastaccess', $record);
1500  
1501          return $DB->get_record('user_lastaccess', ['id' => $recordid], '*', MUST_EXIST);
1502      }
1503  
1504      /**
1505       * Gets a default generator for a given component.
1506       *
1507       * @param string $component The component name, e.g. 'mod_forum' or 'core_question'.
1508       * @param string $classname The name of the class missing from the generators file.
1509       * @return component_generator_base The generator.
1510       */
1511      protected function get_default_plugin_generator(string $component, ?string $classname = null) {
1512          [$type, $plugin] = core_component::normalize_component($component);
1513  
1514          switch ($type) {
1515              case 'block':
1516                  return new default_block_generator($this, $plugin);
1517          }
1518  
1519          if (is_null($classname)) {
1520              throw new coding_exception("Component {$component} does not support " .
1521                  "generators yet. Missing tests/generator/lib.php.");
1522          }
1523  
1524          throw new coding_exception("Component {$component} does not support " .
1525              "data generators yet. Class {$classname} not found.");
1526      }
1527  
1528  }