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   * tool_generator course backend code.
  19   *
  20   * @package tool_generator
  21   * @copyright 2013 The Open University
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  /**
  28   * Backend code for the 'make large course' tool.
  29   *
  30   * @package tool_generator
  31   * @copyright 2013 The Open University
  32   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33   */
  34  class tool_generator_course_backend extends tool_generator_backend {
  35      /**
  36       * @var array Number of sections in course
  37       */
  38      private static $paramsections = array(1, 10, 100, 500, 1000, 2000);
  39      /**
  40       * @var array Number of assignments in course
  41       */
  42      private static $paramassignments = array(1, 10, 100, 500, 1000, 2000);
  43      /**
  44       * @var array Number of Page activities in course
  45       */
  46      private static $parampages = array(1, 50, 200, 1000, 5000, 10000);
  47      /**
  48       * @var array Number of students enrolled in course
  49       */
  50      private static $paramusers = array(1, 100, 1000, 10000, 50000, 100000);
  51      /**
  52       * Total size of small files: 1KB, 1MB, 10MB, 100MB, 1GB, 2GB.
  53       *
  54       * @var array Number of small files created in a single file activity
  55       */
  56      private static $paramsmallfilecount = array(1, 64, 128, 1024, 16384, 32768);
  57      /**
  58       * @var array Size of small files (to make the totals into nice numbers)
  59       */
  60      private static $paramsmallfilesize = array(1024, 16384, 81920, 102400, 65536, 65536);
  61      /**
  62       * Total size of big files: 8KB, 8MB, 80MB, 800MB, 8GB, 16GB.
  63       *
  64       * @var array Number of big files created as individual file activities
  65       */
  66      private static $parambigfilecount = array(1, 2, 5, 10, 10, 10);
  67      /**
  68       * @var array Size of each large file
  69       */
  70      private static $parambigfilesize = array(8192, 4194304, 16777216, 83886080,
  71              858993459, 1717986918);
  72      /**
  73       * @var array Number of forum discussions
  74       */
  75      private static $paramforumdiscussions = array(1, 10, 100, 500, 1000, 2000);
  76      /**
  77       * @var array Number of forum posts per discussion
  78       */
  79      private static $paramforumposts = array(2, 2, 5, 10, 10, 10);
  80  
  81      /**
  82       * @var string Course shortname
  83       */
  84      private $shortname;
  85  
  86      /**
  87       * @var string Course fullname.
  88       */
  89      private $fullname = "";
  90  
  91      /**
  92       * @var string Course summary.
  93       */
  94      private $summary = "";
  95  
  96      /**
  97       * @var string Course summary format, defaults to FORMAT_HTML.
  98       */
  99      private $summaryformat = FORMAT_HTML;
 100  
 101      /**
 102       * @var testing_data_generator Data generator
 103       */
 104      protected $generator;
 105  
 106      /**
 107       * @var stdClass Course object
 108       */
 109      private $course;
 110  
 111      /**
 112       * @var array Array from test user number (1...N) to userid in database
 113       */
 114      private $userids;
 115  
 116      /**
 117       * Constructs object ready to create course.
 118       *
 119       * @param string $shortname Course shortname
 120       * @param int $size Size as numeric index
 121       * @param bool $fixeddataset To use fixed or random data
 122       * @param int|bool $filesizelimit The max number of bytes for a generated file
 123       * @param bool $progress True if progress information should be displayed
 124       */
 125      public function __construct(
 126          $shortname,
 127          $size,
 128          $fixeddataset = false,
 129          $filesizelimit = false,
 130          $progress = true,
 131          $fullname = null,
 132          $summary = null,
 133          $summaryformat = FORMAT_HTML) {
 134  
 135          // Set parameters.
 136          $this->shortname = $shortname;
 137  
 138          // We can't allow fullname to be set to an empty string.
 139          if (empty($fullname)) {
 140              $this->fullname = get_string(
 141                  'fullname',
 142                  'tool_generator',
 143                  array(
 144                      'size' => get_string('shortsize_' . $size, 'tool_generator')
 145                  )
 146              );
 147          } else {
 148              $this->fullname = $fullname;
 149          }
 150  
 151          // Summary, on the other hand, should be empty-able.
 152          if (!is_null($summary)) {
 153              $this->summary = $summary;
 154              $this->summaryformat = $summaryformat;
 155          }
 156  
 157          parent::__construct($size, $fixeddataset, $filesizelimit, $progress);
 158      }
 159  
 160      /**
 161       * Returns the relation between users and course sizes.
 162       *
 163       * @return array
 164       */
 165      public static function get_users_per_size() {
 166          return self::$paramusers;
 167      }
 168  
 169      /**
 170       * Gets a list of size choices supported by this backend.
 171       *
 172       * @return array List of size (int) => text description for display
 173       */
 174      public static function get_size_choices() {
 175          $options = array();
 176          for ($size = self::MIN_SIZE; $size <= self::MAX_SIZE; $size++) {
 177              $options[$size] = get_string('coursesize_' . $size, 'tool_generator');
 178          }
 179          return $options;
 180      }
 181  
 182      /**
 183       * Checks that a shortname is available (unused).
 184       *
 185       * @param string $shortname Proposed course shortname
 186       * @return string An error message if the name is unavailable or '' if OK
 187       */
 188      public static function check_shortname_available($shortname) {
 189          global $DB;
 190          $fullname = $DB->get_field('course', 'fullname',
 191                  array('shortname' => $shortname), IGNORE_MISSING);
 192          if ($fullname !== false) {
 193              // I wanted to throw an exception here but it is not possible to
 194              // use strings from moodle.php in exceptions, and I didn't want
 195              // to duplicate the string in tool_generator, so I changed this to
 196              // not use exceptions.
 197              return get_string('shortnametaken', 'moodle', $fullname);
 198          }
 199          return '';
 200      }
 201  
 202      /**
 203       * Runs the entire 'make' process.
 204       *
 205       * @return int Course id
 206       */
 207      public function make() {
 208          global $DB, $CFG, $USER;
 209          require_once($CFG->dirroot . '/lib/phpunit/classes/util.php');
 210  
 211          raise_memory_limit(MEMORY_EXTRA);
 212  
 213          if ($this->progress && !CLI_SCRIPT) {
 214              echo html_writer::start_tag('ul');
 215          }
 216  
 217          $entirestart = microtime(true);
 218  
 219          // Get generator.
 220          $this->generator = phpunit_util::get_data_generator();
 221  
 222          // Make course.
 223          $this->course = $this->create_course();
 224  
 225          $this->create_assignments();
 226          $this->create_pages();
 227          $this->create_small_files();
 228          $this->create_big_files();
 229  
 230          // Create users as late as possible to reduce regarding in the gradebook.
 231          $this->create_users();
 232          $this->create_forum();
 233  
 234          // We are checking 'enroladminnewcourse' setting to decide to enrol admins or not.
 235          if (!empty($CFG->creatornewroleid) && !empty($CFG->enroladminnewcourse) && is_siteadmin($USER->id)) {
 236              // Deal with course creators - enrol them internally with default role.
 237              enrol_try_internal_enrol($this->course->id, $USER->id, $CFG->creatornewroleid);
 238          }
 239  
 240          // Log total time.
 241          $this->log('coursecompleted', round(microtime(true) - $entirestart, 1));
 242  
 243          if ($this->progress && !CLI_SCRIPT) {
 244              echo html_writer::end_tag('ul');
 245          }
 246  
 247          return $this->course->id;
 248      }
 249  
 250      /**
 251       * Creates the actual course.
 252       *
 253       * @return stdClass Course record
 254       */
 255      private function create_course() {
 256          $this->log('createcourse', $this->shortname);
 257          $courserecord = array(
 258              'shortname' => $this->shortname,
 259              'fullname' => $this->fullname,
 260              'numsections' => self::$paramsections[$this->size],
 261              'startdate' => usergetmidnight(time())
 262          );
 263          if (strlen($this->summary) > 0) {
 264              $courserecord['summary'] = $this->summary;
 265              $courserecord['summary_format'] = $this->summaryformat;
 266          }
 267  
 268          return $this->generator->create_course($courserecord, array('createsections' => true));
 269      }
 270  
 271      /**
 272       * Creates a number of user accounts and enrols them on the course.
 273       * Note: Existing user accounts that were created by this system are
 274       * reused if available.
 275       */
 276      private function create_users() {
 277          global $DB;
 278  
 279          // Work out total number of users.
 280          $count = self::$paramusers[$this->size];
 281  
 282          // Get existing users in order. We will 'fill up holes' in this up to
 283          // the required number.
 284          $this->log('checkaccounts', $count);
 285          $nextnumber = 1;
 286          $rs = $DB->get_recordset_select('user', $DB->sql_like('username', '?'),
 287                  array('tool_generator_%'), 'username', 'id, username');
 288          foreach ($rs as $rec) {
 289              // Extract number from username.
 290              $matches = array();
 291              if (!preg_match('~^tool_generator_([0-9]{6})$~', $rec->username, $matches)) {
 292                  continue;
 293              }
 294              $number = (int)$matches[1];
 295  
 296              // Create missing users in range up to this.
 297              if ($number != $nextnumber) {
 298                  $this->create_user_accounts($nextnumber, min($number - 1, $count));
 299              } else {
 300                  $this->userids[$number] = (int)$rec->id;
 301              }
 302  
 303              // Stop if we've got enough users.
 304              $nextnumber = $number + 1;
 305              if ($number >= $count) {
 306                  break;
 307              }
 308          }
 309          $rs->close();
 310  
 311          // Create users from end of existing range.
 312          if ($nextnumber <= $count) {
 313              $this->create_user_accounts($nextnumber, $count);
 314          }
 315  
 316          // Assign all users to course.
 317          $this->log('enrol', $count, true);
 318  
 319          $enrolplugin = enrol_get_plugin('manual');
 320          $instances = enrol_get_instances($this->course->id, true);
 321          foreach ($instances as $instance) {
 322              if ($instance->enrol === 'manual') {
 323                  break;
 324              }
 325          }
 326          if ($instance->enrol !== 'manual') {
 327              throw new coding_exception('No manual enrol plugin in course');
 328          }
 329          $role = $DB->get_record('role', array('shortname' => 'student'), '*', MUST_EXIST);
 330  
 331          for ($number = 1; $number <= $count; $number++) {
 332              // Enrol user.
 333              $enrolplugin->enrol_user($instance, $this->userids[$number], $role->id);
 334              $this->dot($number, $count);
 335          }
 336  
 337          // Sets the pointer at the beginning to be aware of the users we use.
 338          reset($this->userids);
 339  
 340          $this->end_log();
 341      }
 342  
 343      /**
 344       * Creates user accounts with a numeric range.
 345       *
 346       * @param int $first Number of first user
 347       * @param int $last Number of last user
 348       */
 349      private function create_user_accounts($first, $last) {
 350          global $CFG;
 351  
 352          $this->log('createaccounts', (object)array('from' => $first, 'to' => $last), true);
 353          $count = $last - $first + 1;
 354          $done = 0;
 355          for ($number = $first; $number <= $last; $number++, $done++) {
 356              // Work out username with 6-digit number.
 357              $textnumber = (string)$number;
 358              while (strlen($textnumber) < 6) {
 359                  $textnumber = '0' . $textnumber;
 360              }
 361              $username = 'tool_generator_' . $textnumber;
 362  
 363              // Create user account.
 364              $record = array('username' => $username, 'idnumber' => $number);
 365  
 366              // We add a user password if it has been specified.
 367              if (!empty($CFG->tool_generator_users_password)) {
 368                  $record['password'] = $CFG->tool_generator_users_password;
 369              }
 370  
 371              $user = $this->generator->create_user($record);
 372              $this->userids[$number] = (int)$user->id;
 373              $this->dot($done, $count);
 374          }
 375          $this->end_log();
 376      }
 377  
 378      /**
 379       * Creates a number of Assignment activities.
 380       */
 381      private function create_assignments() {
 382          // Set up generator.
 383          $assigngenerator = $this->generator->get_plugin_generator('mod_assign');
 384  
 385          // Create assignments.
 386          $number = self::$paramassignments[$this->size];
 387          $this->log('createassignments', $number, true);
 388          for ($i = 0; $i < $number; $i++) {
 389              $record = array('course' => $this->course);
 390              $options = array('section' => $this->get_target_section());
 391              $assigngenerator->create_instance($record, $options);
 392              $this->dot($i, $number);
 393          }
 394  
 395          $this->end_log();
 396      }
 397  
 398      /**
 399       * Creates a number of Page activities.
 400       */
 401      private function create_pages() {
 402          // Set up generator.
 403          $pagegenerator = $this->generator->get_plugin_generator('mod_page');
 404  
 405          // Create pages.
 406          $number = self::$parampages[$this->size];
 407          $this->log('createpages', $number, true);
 408          for ($i = 0; $i < $number; $i++) {
 409              $record = array('course' => $this->course);
 410              $options = array('section' => $this->get_target_section());
 411              $pagegenerator->create_instance($record, $options);
 412              $this->dot($i, $number);
 413          }
 414  
 415          $this->end_log();
 416      }
 417  
 418      /**
 419       * Creates one resource activity with a lot of small files.
 420       */
 421      private function create_small_files() {
 422          $count = self::$paramsmallfilecount[$this->size];
 423          $this->log('createsmallfiles', $count, true);
 424  
 425          // Create resource with default textfile only.
 426          $resourcegenerator = $this->generator->get_plugin_generator('mod_resource');
 427          $record = array('course' => $this->course,
 428                  'name' => get_string('smallfiles', 'tool_generator'));
 429          $options = array('section' => 0);
 430          $resource = $resourcegenerator->create_instance($record, $options);
 431  
 432          // Add files.
 433          $fs = get_file_storage();
 434          $context = context_module::instance($resource->cmid);
 435          $filerecord = array('component' => 'mod_resource', 'filearea' => 'content',
 436                  'contextid' => $context->id, 'itemid' => 0, 'filepath' => '/');
 437          for ($i = 0; $i < $count; $i++) {
 438              $filerecord['filename'] = 'smallfile' . $i . '.dat';
 439  
 440              // Generate random binary data (different for each file so it
 441              // doesn't compress unrealistically).
 442              $data = random_bytes_emulate($this->limit_filesize(self::$paramsmallfilesize[$this->size]));
 443  
 444              $fs->create_file_from_string($filerecord, $data);
 445              $this->dot($i, $count);
 446          }
 447  
 448          $this->end_log();
 449      }
 450  
 451      /**
 452       * Creates a number of resource activities with one big file each.
 453       */
 454      private function create_big_files() {
 455          // Work out how many files and how many blocks to use (up to 64KB).
 456          $count = self::$parambigfilecount[$this->size];
 457          $filesize = $this->limit_filesize(self::$parambigfilesize[$this->size]);
 458          $blocks = ceil($filesize / 65536);
 459          $blocksize = floor($filesize / $blocks);
 460  
 461          $this->log('createbigfiles', $count, true);
 462  
 463          // Prepare temp area.
 464          $tempfolder = make_temp_directory('tool_generator');
 465          $tempfile = $tempfolder . '/' . rand();
 466  
 467          // Create resources and files.
 468          $fs = get_file_storage();
 469          $resourcegenerator = $this->generator->get_plugin_generator('mod_resource');
 470          for ($i = 0; $i < $count; $i++) {
 471              // Create resource.
 472              $record = array('course' => $this->course,
 473                      'name' => get_string('bigfile', 'tool_generator', $i));
 474              $options = array('section' => $this->get_target_section());
 475              $resource = $resourcegenerator->create_instance($record, $options);
 476  
 477              // Write file.
 478              $handle = fopen($tempfile, 'w');
 479              if (!$handle) {
 480                  throw new coding_exception('Failed to open temporary file');
 481              }
 482              for ($j = 0; $j < $blocks; $j++) {
 483                  $data = random_bytes_emulate($blocksize);
 484                  fwrite($handle, $data);
 485                  $this->dot($i * $blocks + $j, $count * $blocks);
 486              }
 487              fclose($handle);
 488  
 489              // Add file.
 490              $context = context_module::instance($resource->cmid);
 491              $filerecord = array('component' => 'mod_resource', 'filearea' => 'content',
 492                      'contextid' => $context->id, 'itemid' => 0, 'filepath' => '/',
 493                      'filename' => 'bigfile' . $i . '.dat');
 494              $fs->create_file_from_pathname($filerecord, $tempfile);
 495          }
 496  
 497          unlink($tempfile);
 498          $this->end_log();
 499      }
 500  
 501      /**
 502       * Creates one forum activity with a bunch of posts.
 503       */
 504      private function create_forum() {
 505          global $DB;
 506  
 507          $discussions = self::$paramforumdiscussions[$this->size];
 508          $posts = self::$paramforumposts[$this->size];
 509          $totalposts = $discussions * $posts;
 510  
 511          $this->log('createforum', $totalposts, true);
 512  
 513          // Create empty forum.
 514          $forumgenerator = $this->generator->get_plugin_generator('mod_forum');
 515          $record = array('course' => $this->course,
 516                  'name' => get_string('pluginname', 'forum'));
 517          $options = array('section' => 0);
 518          $forum = $forumgenerator->create_instance($record, $options);
 519  
 520          // Add discussions and posts.
 521          $sofar = 0;
 522          for ($i = 0; $i < $discussions; $i++) {
 523              $record = array('forum' => $forum->id, 'course' => $this->course->id,
 524                      'userid' => $this->get_target_user());
 525              $discussion = $forumgenerator->create_discussion($record);
 526              $parentid = $DB->get_field('forum_posts', 'id', array('discussion' => $discussion->id), MUST_EXIST);
 527              $sofar++;
 528              for ($j = 0; $j < $posts - 1; $j++, $sofar++) {
 529                  $record = array('discussion' => $discussion->id,
 530                          'userid' => $this->get_target_user(), 'parent' => $parentid);
 531                  $forumgenerator->create_post($record);
 532                  $this->dot($sofar, $totalposts);
 533              }
 534          }
 535  
 536          $this->end_log();
 537      }
 538  
 539      /**
 540       * Gets a section number.
 541       *
 542       * Depends on $this->fixeddataset.
 543       *
 544       * @return int A section number from 1 to the number of sections
 545       */
 546      private function get_target_section() {
 547  
 548          if (!$this->fixeddataset) {
 549              $key = rand(1, self::$paramsections[$this->size]);
 550          } else {
 551              // Using section 1.
 552              $key = 1;
 553          }
 554  
 555          return $key;
 556      }
 557  
 558      /**
 559       * Gets a user id.
 560       *
 561       * Depends on $this->fixeddataset.
 562       *
 563       * @return int A user id for a random created user
 564       */
 565      private function get_target_user() {
 566  
 567          if (!$this->fixeddataset) {
 568              $userid = $this->userids[rand(1, self::$paramusers[$this->size])];
 569          } else if ($userid = current($this->userids)) {
 570              // Moving pointer to the next user.
 571              next($this->userids);
 572          } else {
 573              // Returning to the beginning if we reached the end.
 574              $userid = reset($this->userids);
 575          }
 576  
 577          return $userid;
 578      }
 579  
 580      /**
 581       * Restricts the binary file size if necessary
 582       *
 583       * @param int $length The total length
 584       * @return int The limited length if a limit was specified.
 585       */
 586      private function limit_filesize($length) {
 587  
 588          // Limit to $this->filesizelimit.
 589          if (is_numeric($this->filesizelimit) && $length > $this->filesizelimit) {
 590              $length = floor($this->filesizelimit);
 591          }
 592  
 593          return $length;
 594      }
 595  
 596  }