Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/course/ -> lib.php (source)

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 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   * Library of useful functions
  19   *
  20   * @copyright 1999 Martin Dougiamas  http://dougiamas.com
  21   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22   * @package core_course
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die;
  26  
  27  require_once($CFG->libdir.'/completionlib.php');
  28  require_once($CFG->libdir.'/filelib.php');
  29  require_once($CFG->libdir.'/datalib.php');
  30  require_once($CFG->dirroot.'/course/format/lib.php');
  31  
  32  define('COURSE_MAX_LOGS_PER_PAGE', 1000);       // Records.
  33  define('COURSE_MAX_RECENT_PERIOD', 172800);     // Two days, in seconds.
  34  
  35  /**
  36   * Number of courses to display when summaries are included.
  37   * @var int
  38   * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
  39   */
  40  define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
  41  
  42  // Max courses in log dropdown before switching to optional.
  43  define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
  44  // Max users in log dropdown before switching to optional.
  45  define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
  46  define('FRONTPAGENEWS', '0');
  47  define('FRONTPAGECATEGORYNAMES', '2');
  48  define('FRONTPAGECATEGORYCOMBO', '4');
  49  define('FRONTPAGEENROLLEDCOURSELIST', '5');
  50  define('FRONTPAGEALLCOURSELIST', '6');
  51  define('FRONTPAGECOURSESEARCH', '7');
  52  // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
  53  define('EXCELROWS', 65535);
  54  define('FIRSTUSEDEXCELROW', 3);
  55  
  56  define('MOD_CLASS_ACTIVITY', 0);
  57  define('MOD_CLASS_RESOURCE', 1);
  58  
  59  define('COURSE_TIMELINE_ALLINCLUDINGHIDDEN', 'allincludinghidden');
  60  define('COURSE_TIMELINE_ALL', 'all');
  61  define('COURSE_TIMELINE_PAST', 'past');
  62  define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
  63  define('COURSE_TIMELINE_FUTURE', 'future');
  64  define('COURSE_FAVOURITES', 'favourites');
  65  define('COURSE_TIMELINE_HIDDEN', 'hidden');
  66  define('COURSE_CUSTOMFIELD', 'customfield');
  67  define('COURSE_DB_QUERY_LIMIT', 1000);
  68  /** Searching for all courses that have no value for the specified custom field. */
  69  define('COURSE_CUSTOMFIELD_EMPTY', -1);
  70  
  71  function make_log_url($module, $url) {
  72      switch ($module) {
  73          case 'course':
  74              if (strpos($url, 'report/') === 0) {
  75                  // there is only one report type, course reports are deprecated
  76                  $url = "/$url";
  77                  break;
  78              }
  79          case 'file':
  80          case 'login':
  81          case 'lib':
  82          case 'admin':
  83          case 'category':
  84          case 'mnet course':
  85              if (strpos($url, '../') === 0) {
  86                  $url = ltrim($url, '.');
  87              } else {
  88                  $url = "/course/$url";
  89              }
  90              break;
  91          case 'calendar':
  92              $url = "/calendar/$url";
  93              break;
  94          case 'user':
  95          case 'blog':
  96              $url = "/$module/$url";
  97              break;
  98          case 'upload':
  99              $url = $url;
 100              break;
 101          case 'coursetags':
 102              $url = '/'.$url;
 103              break;
 104          case 'library':
 105          case '':
 106              $url = '/';
 107              break;
 108          case 'message':
 109              $url = "/message/$url";
 110              break;
 111          case 'notes':
 112              $url = "/notes/$url";
 113              break;
 114          case 'tag':
 115              $url = "/tag/$url";
 116              break;
 117          case 'role':
 118              $url = '/'.$url;
 119              break;
 120          case 'grade':
 121              $url = "/grade/$url";
 122              break;
 123          default:
 124              $url = "/mod/$module/$url";
 125              break;
 126      }
 127  
 128      //now let's sanitise urls - there might be some ugly nasties:-(
 129      $parts = explode('?', $url);
 130      $script = array_shift($parts);
 131      if (strpos($script, 'http') === 0) {
 132          $script = clean_param($script, PARAM_URL);
 133      } else {
 134          $script = clean_param($script, PARAM_PATH);
 135      }
 136  
 137      $query = '';
 138      if ($parts) {
 139          $query = implode('', $parts);
 140          $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
 141          $parts = explode('&', $query);
 142          $eq = urlencode('=');
 143          foreach ($parts as $key=>$part) {
 144              $part = urlencode(urldecode($part));
 145              $part = str_replace($eq, '=', $part);
 146              $parts[$key] = $part;
 147          }
 148          $query = '?'.implode('&amp;', $parts);
 149      }
 150  
 151      return $script.$query;
 152  }
 153  
 154  
 155  function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
 156                     $modname="", $modid=0, $modaction="", $groupid=0) {
 157      global $CFG, $DB;
 158  
 159      // It is assumed that $date is the GMT time of midnight for that day,
 160      // and so the next 86400 seconds worth of logs are printed.
 161  
 162      /// Setup for group handling.
 163  
 164      // TODO: I don't understand group/context/etc. enough to be able to do
 165      // something interesting with it here
 166      // What is the context of a remote course?
 167  
 168      /// If the group mode is separate, and this user does not have editing privileges,
 169      /// then only the user's group can be viewed.
 170      //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
 171      //    $groupid = get_current_group($course->id);
 172      //}
 173      /// If this course doesn't have groups, no groupid can be specified.
 174      //else if (!$course->groupmode) {
 175      //    $groupid = 0;
 176      //}
 177  
 178      $groupid = 0;
 179  
 180      $joins = array();
 181      $where = '';
 182  
 183      $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
 184                FROM {mnet_log} l
 185                 LEFT JOIN {user} u ON l.userid = u.id
 186                WHERE ";
 187      $params = array();
 188  
 189      $where .= "l.hostid = :hostid";
 190      $params['hostid'] = $hostid;
 191  
 192      // TODO: Is 1 really a magic number referring to the sitename?
 193      if ($course != SITEID || $modid != 0) {
 194          $where .= " AND l.course=:courseid";
 195          $params['courseid'] = $course;
 196      }
 197  
 198      if ($modname) {
 199          $where .= " AND l.module = :modname";
 200          $params['modname'] = $modname;
 201      }
 202  
 203      if ('site_errors' === $modid) {
 204          $where .= " AND ( l.action='error' OR l.action='infected' )";
 205      } else if ($modid) {
 206          //TODO: This assumes that modids are the same across sites... probably
 207          //not true
 208          $where .= " AND l.cmid = :modid";
 209          $params['modid'] = $modid;
 210      }
 211  
 212      if ($modaction) {
 213          $firstletter = substr($modaction, 0, 1);
 214          if ($firstletter == '-') {
 215              $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
 216              $params['modaction'] = '%'.substr($modaction, 1).'%';
 217          } else {
 218              $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
 219              $params['modaction'] = '%'.$modaction.'%';
 220          }
 221      }
 222  
 223      if ($user) {
 224          $where .= " AND l.userid = :user";
 225          $params['user'] = $user;
 226      }
 227  
 228      if ($date) {
 229          $enddate = $date + 86400;
 230          $where .= " AND l.time > :date AND l.time < :enddate";
 231          $params['date'] = $date;
 232          $params['enddate'] = $enddate;
 233      }
 234  
 235      $result = array();
 236      $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
 237      if(!empty($result['totalcount'])) {
 238          $where .= " ORDER BY $order";
 239          $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
 240      } else {
 241          $result['logs'] = array();
 242      }
 243      return $result;
 244  }
 245  
 246  /**
 247   * Checks the integrity of the course data.
 248   *
 249   * In summary - compares course_sections.sequence and course_modules.section.
 250   *
 251   * More detailed, checks that:
 252   * - course_sections.sequence contains each module id not more than once in the course
 253   * - for each moduleid from course_sections.sequence the field course_modules.section
 254   *   refers to the same section id (this means course_sections.sequence is more
 255   *   important if they are different)
 256   * - ($fullcheck only) each module in the course is present in one of
 257   *   course_sections.sequence
 258   * - ($fullcheck only) removes non-existing course modules from section sequences
 259   *
 260   * If there are any mismatches, the changes are made and records are updated in DB.
 261   *
 262   * Course cache is NOT rebuilt if there are any errors!
 263   *
 264   * This function is used each time when course cache is being rebuilt with $fullcheck = false
 265   * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
 266   *
 267   * @param int $courseid id of the course
 268   * @param array $rawmods result of funciton {@link get_course_mods()} - containst
 269   *     the list of enabled course modules in the course. Retrieved from DB if not specified.
 270   *     Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
 271   * @param array $sections records from course_sections table for this course.
 272   *     Retrieved from DB if not specified
 273   * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
 274   *     course modules from sequences. Only to be used in site maintenance mode when we are
 275   *     sure that another user is not in the middle of the process of moving/removing a module.
 276   * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
 277   * @return array array of messages with found problems. Empty output means everything is ok
 278   */
 279  function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
 280      global $DB;
 281      $messages = array();
 282      if ($sections === null) {
 283          $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
 284      }
 285      if ($fullcheck) {
 286          // Retrieve all records from course_modules regardless of module type visibility.
 287          $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
 288      }
 289      if ($rawmods === null) {
 290          $rawmods = get_course_mods($courseid);
 291      }
 292      if (!$fullcheck && (empty($sections) || empty($rawmods))) {
 293          // If either of the arrays is empty, no modules are displayed anyway.
 294          return true;
 295      }
 296      $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
 297  
 298      // First make sure that each module id appears in section sequences only once.
 299      // If it appears in several section sequences the last section wins.
 300      // If it appears twice in one section sequence, the first occurence wins.
 301      $modsection = array();
 302      foreach ($sections as $sectionid => $section) {
 303          $sections[$sectionid]->newsequence = $section->sequence;
 304          if (!empty($section->sequence)) {
 305              $sequence = explode(",", $section->sequence);
 306              $sequenceunique = array_unique($sequence);
 307              if (count($sequenceunique) != count($sequence)) {
 308                  // Some course module id appears in this section sequence more than once.
 309                  ksort($sequenceunique); // Preserve initial order of modules.
 310                  $sequence = array_values($sequenceunique);
 311                  $sections[$sectionid]->newsequence = join(',', $sequence);
 312                  $messages[] = $debuggingprefix.'Sequence for course section ['.
 313                          $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
 314              }
 315              foreach ($sequence as $cmid) {
 316                  if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
 317                      // Some course module id appears to be in more than one section's sequences.
 318                      $wrongsectionid = $modsection[$cmid];
 319                      $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
 320                      $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
 321                              $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
 322                  }
 323                  $modsection[$cmid] = $sectionid;
 324              }
 325          }
 326      }
 327  
 328      // Add orphaned modules to their sections if they exist or to section 0 otherwise.
 329      if ($fullcheck) {
 330          foreach ($rawmods as $cmid => $mod) {
 331              if (!isset($modsection[$cmid])) {
 332                  // This is a module that is not mentioned in course_section.sequence at all.
 333                  // Add it to the section $mod->section or to the last available section.
 334                  if ($mod->section && isset($sections[$mod->section])) {
 335                      $modsection[$cmid] = $mod->section;
 336                  } else {
 337                      $firstsection = reset($sections);
 338                      $modsection[$cmid] = $firstsection->id;
 339                  }
 340                  $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
 341                  $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
 342                          $modsection[$cmid].']';
 343              }
 344          }
 345          foreach ($modsection as $cmid => $sectionid) {
 346              if (!isset($rawmods[$cmid])) {
 347                  // Section $sectionid refers to module id that does not exist.
 348                  $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
 349                  $messages[] = $debuggingprefix.'Course module ['.$cmid.
 350                          '] does not exist but is present in the sequence of section ['.$sectionid.']';
 351              }
 352          }
 353      }
 354  
 355      // Update changed sections.
 356      if (!$checkonly && !empty($messages)) {
 357          foreach ($sections as $sectionid => $section) {
 358              if ($section->newsequence !== $section->sequence) {
 359                  $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
 360              }
 361          }
 362      }
 363  
 364      // Now make sure that all modules point to the correct sections.
 365      foreach ($rawmods as $cmid => $mod) {
 366          if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
 367              if (!$checkonly) {
 368                  $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
 369              }
 370              $messages[] = $debuggingprefix.'Course module ['.$cmid.
 371                      '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
 372          }
 373      }
 374  
 375      return $messages;
 376  }
 377  
 378  /**
 379   * For a given course, returns an array of course activity objects
 380   * Each item in the array contains he following properties:
 381   */
 382  function get_array_of_activities($courseid) {
 383  //  cm - course module id
 384  //  mod - name of the module (eg forum)
 385  //  section - the number of the section (eg week or topic)
 386  //  name - the name of the instance
 387  //  visible - is the instance visible or not
 388  //  groupingid - grouping id
 389  //  extra - contains extra string to include in any link
 390      global $CFG, $DB;
 391  
 392      $course = $DB->get_record('course', array('id'=>$courseid));
 393  
 394      if (empty($course)) {
 395          throw new moodle_exception('courseidnotfound');
 396      }
 397  
 398      $mod = array();
 399  
 400      $rawmods = get_course_mods($courseid);
 401      if (empty($rawmods)) {
 402          return $mod; // always return array
 403      }
 404      $courseformat = course_get_format($course);
 405  
 406      if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
 407              'section ASC', 'id,section,sequence,visible')) {
 408          // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
 409          if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
 410              debugging(join('<br>', $errormessages));
 411              $rawmods = get_course_mods($courseid);
 412              $sections = $DB->get_records('course_sections', array('course' => $courseid),
 413                  'section ASC', 'id,section,sequence,visible');
 414          }
 415          // Build array of activities.
 416         foreach ($sections as $section) {
 417             if (!empty($section->sequence)) {
 418                 $sequence = explode(",", $section->sequence);
 419                 foreach ($sequence as $seq) {
 420                     if (empty($rawmods[$seq])) {
 421                         continue;
 422                     }
 423                     // Adjust visibleoncoursepage, value in DB may not respect format availability.
 424                     $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
 425                             || $rawmods[$seq]->visibleoncoursepage
 426                             || empty($CFG->allowstealth)
 427                             || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
 428  
 429                     // Create an object that will be cached.
 430                     $mod[$seq] = new stdClass();
 431                     $mod[$seq]->id               = $rawmods[$seq]->instance;
 432                     $mod[$seq]->cm               = $rawmods[$seq]->id;
 433                     $mod[$seq]->mod              = $rawmods[$seq]->modname;
 434  
 435                      // Oh dear. Inconsistent names left here for backward compatibility.
 436                     $mod[$seq]->section          = $section->section;
 437                     $mod[$seq]->sectionid        = $rawmods[$seq]->section;
 438  
 439                     $mod[$seq]->module           = $rawmods[$seq]->module;
 440                     $mod[$seq]->added            = $rawmods[$seq]->added;
 441                     $mod[$seq]->score            = $rawmods[$seq]->score;
 442                     $mod[$seq]->idnumber         = $rawmods[$seq]->idnumber;
 443                     $mod[$seq]->visible          = $rawmods[$seq]->visible;
 444                     $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
 445                     $mod[$seq]->visibleold       = $rawmods[$seq]->visibleold;
 446                     $mod[$seq]->groupmode        = $rawmods[$seq]->groupmode;
 447                     $mod[$seq]->groupingid       = $rawmods[$seq]->groupingid;
 448                     $mod[$seq]->indent           = $rawmods[$seq]->indent;
 449                     $mod[$seq]->completion       = $rawmods[$seq]->completion;
 450                     $mod[$seq]->extra            = "";
 451                     $mod[$seq]->completiongradeitemnumber =
 452                             $rawmods[$seq]->completiongradeitemnumber;
 453                     $mod[$seq]->completionview   = $rawmods[$seq]->completionview;
 454                     $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
 455                     $mod[$seq]->showdescription  = $rawmods[$seq]->showdescription;
 456                     $mod[$seq]->availability = $rawmods[$seq]->availability;
 457                     $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
 458  
 459                     $modname = $mod[$seq]->mod;
 460                     $functionname = $modname."_get_coursemodule_info";
 461  
 462                     if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
 463                         continue;
 464                     }
 465  
 466                     include_once("$CFG->dirroot/mod/$modname/lib.php");
 467  
 468                     if ($hasfunction = function_exists($functionname)) {
 469                         if ($info = $functionname($rawmods[$seq])) {
 470                             if (!empty($info->icon)) {
 471                                 $mod[$seq]->icon = $info->icon;
 472                             }
 473                             if (!empty($info->iconcomponent)) {
 474                                 $mod[$seq]->iconcomponent = $info->iconcomponent;
 475                             }
 476                             if (!empty($info->name)) {
 477                                 $mod[$seq]->name = $info->name;
 478                             }
 479                             if ($info instanceof cached_cm_info) {
 480                                 // When using cached_cm_info you can include three new fields
 481                                 // that aren't available for legacy code
 482                                 if (!empty($info->content)) {
 483                                     $mod[$seq]->content = $info->content;
 484                                 }
 485                                 if (!empty($info->extraclasses)) {
 486                                     $mod[$seq]->extraclasses = $info->extraclasses;
 487                                 }
 488                                 if (!empty($info->iconurl)) {
 489                                     // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
 490                                     $url = new moodle_url($info->iconurl);
 491                                     $mod[$seq]->iconurl = $url->out(false);
 492                                 }
 493                                 if (!empty($info->onclick)) {
 494                                     $mod[$seq]->onclick = $info->onclick;
 495                                 }
 496                                 if (!empty($info->customdata)) {
 497                                     $mod[$seq]->customdata = $info->customdata;
 498                                 }
 499                             } else {
 500                                 // When using a stdclass, the (horrible) deprecated ->extra field
 501                                 // is available for BC
 502                                 if (!empty($info->extra)) {
 503                                     $mod[$seq]->extra = $info->extra;
 504                                 }
 505                             }
 506                         }
 507                     }
 508                     // When there is no modname_get_coursemodule_info function,
 509                     // but showdescriptions is enabled, then we use the 'intro'
 510                     // and 'introformat' fields in the module table
 511                     if (!$hasfunction && $rawmods[$seq]->showdescription) {
 512                         if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
 513                                 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
 514                             // Set content from intro and introformat. Filters are disabled
 515                             // because we  filter it with format_text at display time
 516                             $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
 517                                     $modvalues, $rawmods[$seq]->id, false);
 518  
 519                             // To save making another query just below, put name in here
 520                             $mod[$seq]->name = $modvalues->name;
 521                         }
 522                     }
 523                     if (!isset($mod[$seq]->name)) {
 524                         $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
 525                     }
 526  
 527                      // Minimise the database size by unsetting default options when they are
 528                      // 'empty'. This list corresponds to code in the cm_info constructor.
 529                      foreach (array('idnumber', 'groupmode', 'groupingid',
 530                              'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
 531                              'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
 532                              'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
 533                         if (property_exists($mod[$seq], $property) &&
 534                                 empty($mod[$seq]->{$property})) {
 535                             unset($mod[$seq]->{$property});
 536                         }
 537                     }
 538                     // Special case: this value is usually set to null, but may be 0
 539                     if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
 540                             is_null($mod[$seq]->completiongradeitemnumber)) {
 541                         unset($mod[$seq]->completiongradeitemnumber);
 542                     }
 543                 }
 544              }
 545          }
 546      }
 547      return $mod;
 548  }
 549  
 550  /**
 551   * Returns the localised human-readable names of all used modules
 552   *
 553   * @param bool $plural if true returns the plural forms of the names
 554   * @return array where key is the module name (component name without 'mod_') and
 555   *     the value is the human-readable string. Array sorted alphabetically by value
 556   */
 557  function get_module_types_names($plural = false) {
 558      static $modnames = null;
 559      global $DB, $CFG;
 560      if ($modnames === null) {
 561          $modnames = array(0 => array(), 1 => array());
 562          if ($allmods = $DB->get_records("modules")) {
 563              foreach ($allmods as $mod) {
 564                  if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
 565                      $modnames[0][$mod->name] = get_string("modulename", "$mod->name", null, true);
 566                      $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name", null, true);
 567                  }
 568              }
 569          }
 570      }
 571      return $modnames[(int)$plural];
 572  }
 573  
 574  /**
 575   * Set highlighted section. Only one section can be highlighted at the time.
 576   *
 577   * @param int $courseid course id
 578   * @param int $marker highlight section with this number, 0 means remove higlightin
 579   * @return void
 580   */
 581  function course_set_marker($courseid, $marker) {
 582      global $DB, $COURSE;
 583      $DB->set_field("course", "marker", $marker, array('id' => $courseid));
 584      if ($COURSE && $COURSE->id == $courseid) {
 585          $COURSE->marker = $marker;
 586      }
 587      if (class_exists('format_base')) {
 588          format_base::reset_course_cache($courseid);
 589      }
 590      course_modinfo::clear_instance_cache($courseid);
 591  }
 592  
 593  /**
 594   * For a given course section, marks it visible or hidden,
 595   * and does the same for every activity in that section
 596   *
 597   * @param int $courseid course id
 598   * @param int $sectionnumber The section number to adjust
 599   * @param int $visibility The new visibility
 600   * @return array A list of resources which were hidden in the section
 601   */
 602  function set_section_visible($courseid, $sectionnumber, $visibility) {
 603      global $DB;
 604  
 605      $resourcestotoggle = array();
 606      if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
 607          course_update_section($courseid, $section, array('visible' => $visibility));
 608  
 609          // Determine which modules are visible for AJAX update
 610          $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
 611          if (!empty($modules)) {
 612              list($insql, $params) = $DB->get_in_or_equal($modules);
 613              $select = 'id ' . $insql . ' AND visible = ?';
 614              array_push($params, $visibility);
 615              if (!$visibility) {
 616                  $select .= ' AND visibleold = 1';
 617              }
 618              $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
 619          }
 620      }
 621      return $resourcestotoggle;
 622  }
 623  
 624  /**
 625   * Return the course category context for the category with id $categoryid, except
 626   * that if $categoryid is 0, return the system context.
 627   *
 628   * @param integer $categoryid a category id or 0.
 629   * @return context the corresponding context
 630   */
 631  function get_category_or_system_context($categoryid) {
 632      if ($categoryid) {
 633          return context_coursecat::instance($categoryid, IGNORE_MISSING);
 634      } else {
 635          return context_system::instance();
 636      }
 637  }
 638  
 639  /**
 640   * Returns the list of full course categories to be used in html_writer::select()
 641   *
 642   * Calls {@see core_course_category::make_categories_list()} to build the list.
 643   *
 644   * @return array array mapping course category id to the display name
 645   */
 646  function make_categories_options() {
 647      return core_course_category::make_categories_list('', 0, ' / ');
 648  }
 649  
 650  /**
 651   * Print the buttons relating to course requests.
 652   *
 653   * @param context $context current page context.
 654   */
 655  function print_course_request_buttons($context) {
 656      global $CFG, $DB, $OUTPUT;
 657      if (empty($CFG->enablecourserequests)) {
 658          return;
 659      }
 660      if (course_request::can_request($context)) {
 661          // Print a button to request a new course.
 662          $params = [];
 663          if ($context instanceof context_coursecat) {
 664              $params['category'] = $context->instanceid;
 665          }
 666          echo $OUTPUT->single_button(new moodle_url('/course/request.php', $params),
 667              get_string('requestcourse'), 'get');
 668      }
 669      /// Print a button to manage pending requests
 670      if (has_capability('moodle/site:approvecourse', $context)) {
 671          $disabled = !$DB->record_exists('course_request', array());
 672          echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
 673      }
 674  }
 675  
 676  /**
 677   * Does the user have permission to edit things in this category?
 678   *
 679   * @param integer $categoryid The id of the category we are showing, or 0 for system context.
 680   * @return boolean has_any_capability(array(...), ...); in the appropriate context.
 681   */
 682  function can_edit_in_category($categoryid = 0) {
 683      $context = get_category_or_system_context($categoryid);
 684      return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
 685  }
 686  
 687  /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
 688  
 689  function add_course_module($mod) {
 690      global $DB;
 691  
 692      $mod->added = time();
 693      unset($mod->id);
 694  
 695      $cmid = $DB->insert_record("course_modules", $mod);
 696      rebuild_course_cache($mod->course, true);
 697      return $cmid;
 698  }
 699  
 700  /**
 701   * Creates a course section and adds it to the specified position
 702   *
 703   * @param int|stdClass $courseorid course id or course object
 704   * @param int $position position to add to, 0 means to the end. If position is greater than
 705   *        number of existing secitons, the section is added to the end. This will become sectionnum of the
 706   *        new section. All existing sections at this or bigger position will be shifted down.
 707   * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
 708   * @return stdClass created section object
 709   */
 710  function course_create_section($courseorid, $position = 0, $skipcheck = false) {
 711      global $DB;
 712      $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
 713  
 714      // Find the last sectionnum among existing sections.
 715      if ($skipcheck) {
 716          $lastsection = $position - 1;
 717      } else {
 718          $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
 719      }
 720  
 721      // First add section to the end.
 722      $cw = new stdClass();
 723      $cw->course   = $courseid;
 724      $cw->section  = $lastsection + 1;
 725      $cw->summary  = '';
 726      $cw->summaryformat = FORMAT_HTML;
 727      $cw->sequence = '';
 728      $cw->name = null;
 729      $cw->visible = 1;
 730      $cw->availability = null;
 731      $cw->timemodified = time();
 732      $cw->id = $DB->insert_record("course_sections", $cw);
 733  
 734      // Now move it to the specified position.
 735      if ($position > 0 && $position <= $lastsection) {
 736          $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
 737          move_section_to($course, $cw->section, $position, true);
 738          $cw->section = $position;
 739      }
 740  
 741      core\event\course_section_created::create_from_section($cw)->trigger();
 742  
 743      rebuild_course_cache($courseid, true);
 744      return $cw;
 745  }
 746  
 747  /**
 748   * Creates missing course section(s) and rebuilds course cache
 749   *
 750   * @param int|stdClass $courseorid course id or course object
 751   * @param int|array $sections list of relative section numbers to create
 752   * @return bool if there were any sections created
 753   */
 754  function course_create_sections_if_missing($courseorid, $sections) {
 755      if (!is_array($sections)) {
 756          $sections = array($sections);
 757      }
 758      $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
 759      if ($newsections = array_diff($sections, $existing)) {
 760          foreach ($newsections as $sectionnum) {
 761              course_create_section($courseorid, $sectionnum, true);
 762          }
 763          return true;
 764      }
 765      return false;
 766  }
 767  
 768  /**
 769   * Adds an existing module to the section
 770   *
 771   * Updates both tables {course_sections} and {course_modules}
 772   *
 773   * Note: This function does not use modinfo PROVIDED that the section you are
 774   * adding the module to already exists. If the section does not exist, it will
 775   * build modinfo if necessary and create the section.
 776   *
 777   * @param int|stdClass $courseorid course id or course object
 778   * @param int $cmid id of the module already existing in course_modules table
 779   * @param int $sectionnum relative number of the section (field course_sections.section)
 780   *     If section does not exist it will be created
 781   * @param int|stdClass $beforemod id or object with field id corresponding to the module
 782   *     before which the module needs to be included. Null for inserting in the
 783   *     end of the section
 784   * @return int The course_sections ID where the module is inserted
 785   */
 786  function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
 787      global $DB, $COURSE;
 788      if (is_object($beforemod)) {
 789          $beforemod = $beforemod->id;
 790      }
 791      if (is_object($courseorid)) {
 792          $courseid = $courseorid->id;
 793      } else {
 794          $courseid = $courseorid;
 795      }
 796      // Do not try to use modinfo here, there is no guarantee it is valid!
 797      $section = $DB->get_record('course_sections',
 798              array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
 799      if (!$section) {
 800          // This function call requires modinfo.
 801          course_create_sections_if_missing($courseorid, $sectionnum);
 802          $section = $DB->get_record('course_sections',
 803                  array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
 804      }
 805  
 806      $modarray = explode(",", trim($section->sequence));
 807      if (empty($section->sequence)) {
 808          $newsequence = "$cmid";
 809      } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
 810          $insertarray = array($cmid, $beforemod);
 811          array_splice($modarray, $key[0], 1, $insertarray);
 812          $newsequence = implode(",", $modarray);
 813      } else {
 814          $newsequence = "$section->sequence,$cmid";
 815      }
 816      $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
 817      $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
 818      if (is_object($courseorid)) {
 819          rebuild_course_cache($courseorid->id, true);
 820      } else {
 821          rebuild_course_cache($courseorid, true);
 822      }
 823      return $section->id;     // Return course_sections ID that was used.
 824  }
 825  
 826  /**
 827   * Change the group mode of a course module.
 828   *
 829   * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
 830   * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
 831   *
 832   * @param int $id course module ID.
 833   * @param int $groupmode the new groupmode value.
 834   * @return bool True if the $groupmode was updated.
 835   */
 836  function set_coursemodule_groupmode($id, $groupmode) {
 837      global $DB;
 838      $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
 839      if ($cm->groupmode != $groupmode) {
 840          $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
 841          rebuild_course_cache($cm->course, true);
 842      }
 843      return ($cm->groupmode != $groupmode);
 844  }
 845  
 846  function set_coursemodule_idnumber($id, $idnumber) {
 847      global $DB;
 848      $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
 849      if ($cm->idnumber != $idnumber) {
 850          $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
 851          rebuild_course_cache($cm->course, true);
 852      }
 853      return ($cm->idnumber != $idnumber);
 854  }
 855  
 856  /**
 857   * Set the visibility of a module and inherent properties.
 858   *
 859   * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
 860   * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
 861   *
 862   * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
 863   * has been moved to {@link set_section_visible()} which was the only place from which
 864   * the parameter was used.
 865   *
 866   * @param int $id of the module
 867   * @param int $visible state of the module
 868   * @param int $visibleoncoursepage state of the module on the course page
 869   * @return bool false when the module was not found, true otherwise
 870   */
 871  function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
 872      global $DB, $CFG;
 873      require_once($CFG->libdir.'/gradelib.php');
 874      require_once($CFG->dirroot.'/calendar/lib.php');
 875  
 876      if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
 877          return false;
 878      }
 879  
 880      // Create events and propagate visibility to associated grade items if the value has changed.
 881      // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
 882      if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
 883          return true;
 884      }
 885  
 886      if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
 887          return false;
 888      }
 889      if (($cm->visible != $visible) &&
 890              ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
 891          foreach($events as $event) {
 892              if ($visible) {
 893                  $event = new calendar_event($event);
 894                  $event->toggle_visibility(true);
 895              } else {
 896                  $event = new calendar_event($event);
 897                  $event->toggle_visibility(false);
 898              }
 899          }
 900      }
 901  
 902      // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
 903      // affect visibleold to allow for an original visibility restore. See set_section_visible().
 904      $cminfo = new stdClass();
 905      $cminfo->id = $id;
 906      $cminfo->visible = $visible;
 907      $cminfo->visibleoncoursepage = $visibleoncoursepage;
 908      $cminfo->visibleold = $visible;
 909      $DB->update_record('course_modules', $cminfo);
 910  
 911      // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
 912      // Note that this must be done after updating the row in course_modules, in case
 913      // the modules grade_item_update function needs to access $cm->visible.
 914      if ($cm->visible != $visible &&
 915              plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
 916              component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
 917          $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
 918          component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
 919      } else if ($cm->visible != $visible) {
 920          $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
 921          if ($grade_items) {
 922              foreach ($grade_items as $grade_item) {
 923                  $grade_item->set_hidden(!$visible);
 924              }
 925          }
 926      }
 927  
 928      rebuild_course_cache($cm->course, true);
 929      return true;
 930  }
 931  
 932  /**
 933   * Changes the course module name
 934   *
 935   * @param int $id course module id
 936   * @param string $name new value for a name
 937   * @return bool whether a change was made
 938   */
 939  function set_coursemodule_name($id, $name) {
 940      global $CFG, $DB;
 941      require_once($CFG->libdir . '/gradelib.php');
 942  
 943      $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
 944  
 945      $module = new \stdClass();
 946      $module->id = $cm->instance;
 947  
 948      // Escape strings as they would be by mform.
 949      if (!empty($CFG->formatstringstriptags)) {
 950          $module->name = clean_param($name, PARAM_TEXT);
 951      } else {
 952          $module->name = clean_param($name, PARAM_CLEANHTML);
 953      }
 954      if ($module->name === $cm->name || strval($module->name) === '') {
 955          return false;
 956      }
 957      if (\core_text::strlen($module->name) > 255) {
 958          throw new \moodle_exception('maximumchars', 'moodle', '', 255);
 959      }
 960  
 961      $module->timemodified = time();
 962      $DB->update_record($cm->modname, $module);
 963      $cm->name = $module->name;
 964      \core\event\course_module_updated::create_from_cm($cm)->trigger();
 965      rebuild_course_cache($cm->course, true);
 966  
 967      // Attempt to update the grade item if relevant.
 968      $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
 969      $grademodule->cmidnumber = $cm->idnumber;
 970      $grademodule->modname = $cm->modname;
 971      grade_update_mod_grades($grademodule);
 972  
 973      // Update calendar events with the new name.
 974      course_module_update_calendar_events($cm->modname, $grademodule, $cm);
 975  
 976      return true;
 977  }
 978  
 979  /**
 980   * This function will handle the whole deletion process of a module. This includes calling
 981   * the modules delete_instance function, deleting files, events, grades, conditional data,
 982   * the data in the course_module and course_sections table and adding a module deletion
 983   * event to the DB.
 984   *
 985   * @param int $cmid the course module id
 986   * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
 987   * @throws moodle_exception
 988   * @since Moodle 2.5
 989   */
 990  function course_delete_module($cmid, $async = false) {
 991      // Check the 'course_module_background_deletion_recommended' hook first.
 992      // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
 993      // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
 994      // It's up to plugins to handle things like whether or not they are enabled.
 995      if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
 996          foreach ($pluginsfunction as $plugintype => $plugins) {
 997              foreach ($plugins as $pluginfunction) {
 998                  if ($pluginfunction()) {
 999                      return course_module_flag_for_async_deletion($cmid);
1000                  }
1001              }
1002          }
1003      }
1004  
1005      global $CFG, $DB;
1006  
1007      require_once($CFG->libdir.'/gradelib.php');
1008      require_once($CFG->libdir.'/questionlib.php');
1009      require_once($CFG->dirroot.'/blog/lib.php');
1010      require_once($CFG->dirroot.'/calendar/lib.php');
1011  
1012      // Get the course module.
1013      if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1014          return true;
1015      }
1016  
1017      // Get the module context.
1018      $modcontext = context_module::instance($cm->id);
1019  
1020      // Get the course module name.
1021      $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1022  
1023      // Get the file location of the delete_instance function for this module.
1024      $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1025  
1026      // Include the file required to call the delete_instance function for this module.
1027      if (file_exists($modlib)) {
1028          require_once($modlib);
1029      } else {
1030          throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1031              "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1032      }
1033  
1034      $deleteinstancefunction = $modulename . '_delete_instance';
1035  
1036      // Ensure the delete_instance function exists for this module.
1037      if (!function_exists($deleteinstancefunction)) {
1038          throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1039              "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1040      }
1041  
1042      // Allow plugins to use this course module before we completely delete it.
1043      if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1044          foreach ($pluginsfunction as $plugintype => $plugins) {
1045              foreach ($plugins as $pluginfunction) {
1046                  $pluginfunction($cm);
1047              }
1048          }
1049      }
1050  
1051      question_delete_activity($cm);
1052  
1053      // Call the delete_instance function, if it returns false throw an exception.
1054      if (!$deleteinstancefunction($cm->instance)) {
1055          throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1056              "Cannot delete the module $modulename (instance).");
1057      }
1058  
1059      // Remove all module files in case modules forget to do that.
1060      $fs = get_file_storage();
1061      $fs->delete_area_files($modcontext->id);
1062  
1063      // Delete events from calendar.
1064      if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1065          $coursecontext = context_course::instance($cm->course);
1066          foreach($events as $event) {
1067              $event->context = $coursecontext;
1068              $calendarevent = calendar_event::load($event);
1069              $calendarevent->delete();
1070          }
1071      }
1072  
1073      // Delete grade items, outcome items and grades attached to modules.
1074      if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1075                                                     'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1076          foreach ($grade_items as $grade_item) {
1077              $grade_item->delete('moddelete');
1078          }
1079      }
1080  
1081      // Delete associated blogs and blog tag instances.
1082      blog_remove_associations_for_module($modcontext->id);
1083  
1084      // Delete completion and availability data; it is better to do this even if the
1085      // features are not turned on, in case they were turned on previously (these will be
1086      // very quick on an empty table).
1087      $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1088      $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1089                                                              'course' => $cm->course,
1090                                                              'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1091  
1092      // Delete all tag instances associated with the instance of this module.
1093      core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1094      core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1095  
1096      // Notify the competency subsystem.
1097      \core_competency\api::hook_course_module_deleted($cm);
1098  
1099      // Delete the context.
1100      context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1101  
1102      // Delete the module from the course_modules table.
1103      $DB->delete_records('course_modules', array('id' => $cm->id));
1104  
1105      // Delete module from that section.
1106      if (!delete_mod_from_section($cm->id, $cm->section)) {
1107          throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1108              "Cannot delete the module $modulename (instance) from section.");
1109      }
1110  
1111      // Trigger event for course module delete action.
1112      $event = \core\event\course_module_deleted::create(array(
1113          'courseid' => $cm->course,
1114          'context'  => $modcontext,
1115          'objectid' => $cm->id,
1116          'other'    => array(
1117              'modulename' => $modulename,
1118              'instanceid'   => $cm->instance,
1119          )
1120      ));
1121      $event->add_record_snapshot('course_modules', $cm);
1122      $event->trigger();
1123      rebuild_course_cache($cm->course, true);
1124  }
1125  
1126  /**
1127   * Schedule a course module for deletion in the background using an adhoc task.
1128   *
1129   * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1130   * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1131   *
1132   * @param int $cmid the course module id.
1133   * @return bool whether the module was successfully scheduled for deletion.
1134   * @throws \moodle_exception
1135   */
1136  function course_module_flag_for_async_deletion($cmid) {
1137      global $CFG, $DB, $USER;
1138      require_once($CFG->libdir.'/gradelib.php');
1139      require_once($CFG->libdir.'/questionlib.php');
1140      require_once($CFG->dirroot.'/blog/lib.php');
1141      require_once($CFG->dirroot.'/calendar/lib.php');
1142  
1143      // Get the course module.
1144      if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1145          return true;
1146      }
1147  
1148      // We need to be reasonably certain the deletion is going to succeed before we background the process.
1149      // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1150  
1151      // Get the course module name.
1152      $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1153  
1154      // Get the file location of the delete_instance function for this module.
1155      $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1156  
1157      // Include the file required to call the delete_instance function for this module.
1158      if (file_exists($modlib)) {
1159          require_once($modlib);
1160      } else {
1161          throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1162              "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1163      }
1164  
1165      $deleteinstancefunction = $modulename . '_delete_instance';
1166  
1167      // Ensure the delete_instance function exists for this module.
1168      if (!function_exists($deleteinstancefunction)) {
1169          throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1170              "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1171      }
1172  
1173      // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1174      $cm->deletioninprogress = '1';
1175      $DB->update_record('course_modules', $cm);
1176  
1177      // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1178      $removaltask = new \core_course\task\course_delete_modules();
1179      $removaltask->set_custom_data(array(
1180          'cms' => array($cm),
1181          'userid' => $USER->id,
1182          'realuserid' => \core\session\manager::get_realuser()->id
1183      ));
1184  
1185      // Queue the task for the next run.
1186      \core\task\manager::queue_adhoc_task($removaltask);
1187  
1188      // Reset the course cache to hide the module.
1189      rebuild_course_cache($cm->course, true);
1190  }
1191  
1192  /**
1193   * Checks whether the given course has any course modules scheduled for adhoc deletion.
1194   *
1195   * @param int $courseid the id of the course.
1196   * @param bool $onlygradable whether to check only gradable modules or all modules.
1197   * @return bool true if the course contains any modules pending deletion, false otherwise.
1198   */
1199  function course_modules_pending_deletion(int $courseid, bool $onlygradable = false) : bool {
1200      if (empty($courseid)) {
1201          return false;
1202      }
1203  
1204      if ($onlygradable) {
1205          // Fetch modules with grade items.
1206          if (!$coursegradeitems = grade_item::fetch_all(['itemtype' => 'mod', 'courseid' => $courseid])) {
1207              // Return early when there is none.
1208              return false;
1209          }
1210      }
1211  
1212      $modinfo = get_fast_modinfo($courseid);
1213      foreach ($modinfo->get_cms() as $module) {
1214          if ($module->deletioninprogress == '1') {
1215              if ($onlygradable) {
1216                  // Check if the module being deleted is in the list of course modules with grade items.
1217                  foreach ($coursegradeitems as $coursegradeitem) {
1218                      if ($coursegradeitem->itemmodule == $module->modname && $coursegradeitem->iteminstance == $module->instance) {
1219                          // The module being deleted is within the gradable  modules.
1220                          return true;
1221                      }
1222                  }
1223              } else {
1224                  return true;
1225              }
1226          }
1227      }
1228      return false;
1229  }
1230  
1231  /**
1232   * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1233   *
1234   * @param int $courseid the course id.
1235   * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1236   * @param int $instanceid the module instance id.
1237   * @return bool true if the course module is pending deletion, false otherwise.
1238   */
1239  function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1240      if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1241          return false;
1242      }
1243      $modinfo = get_fast_modinfo($courseid);
1244      $instances = $modinfo->get_instances_of($modulename);
1245      return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1246  }
1247  
1248  function delete_mod_from_section($modid, $sectionid) {
1249      global $DB;
1250  
1251      if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1252  
1253          $modarray = explode(",", $section->sequence);
1254  
1255          if ($key = array_keys ($modarray, $modid)) {
1256              array_splice($modarray, $key[0], 1);
1257              $newsequence = implode(",", $modarray);
1258              $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1259              rebuild_course_cache($section->course, true);
1260              return true;
1261          } else {
1262              return false;
1263          }
1264  
1265      }
1266      return false;
1267  }
1268  
1269  /**
1270   * This function updates the calendar events from the information stored in the module table and the course
1271   * module table.
1272   *
1273   * @param  string $modulename Module name
1274   * @param  stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1275   * @param  stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1276   * @return bool Returns true if calendar events are updated.
1277   * @since  Moodle 3.3.4
1278   */
1279  function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1280      global $DB;
1281  
1282      if (isset($instance) || isset($cm)) {
1283  
1284          if (!isset($instance)) {
1285              $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1286          }
1287          if (!isset($cm)) {
1288              $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1289          }
1290          if (!empty($cm)) {
1291              course_module_calendar_event_update_process($instance, $cm);
1292          }
1293          return true;
1294      }
1295      return false;
1296  }
1297  
1298  /**
1299   * Update all instances through out the site or in a course.
1300   *
1301   * @param  string  $modulename Module type to update.
1302   * @param  integer $courseid   Course id to update events. 0 for the whole site.
1303   * @return bool Returns True if the update was successful.
1304   * @since  Moodle 3.3.4
1305   */
1306  function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1307      global $DB;
1308  
1309      $instances = null;
1310      if ($courseid) {
1311          if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1312              return false;
1313          }
1314      } else {
1315          if (!$instances = $DB->get_records($modulename)) {
1316              return false;
1317          }
1318      }
1319  
1320      foreach ($instances as $instance) {
1321          if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1322              course_module_calendar_event_update_process($instance, $cm);
1323          }
1324      }
1325      return true;
1326  }
1327  
1328  /**
1329   * Calendar events for a module instance are updated.
1330   *
1331   * @param  stdClass $instance Module instance object.
1332   * @param  stdClass $cm Course Module object.
1333   * @since  Moodle 3.3.4
1334   */
1335  function course_module_calendar_event_update_process($instance, $cm) {
1336      // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1337      // will remove the completion events.
1338      $refresheventsfunction = $cm->modname . '_refresh_events';
1339      if (function_exists($refresheventsfunction)) {
1340          call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1341      }
1342      $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1343      \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1344  }
1345  
1346  /**
1347   * Moves a section within a course, from a position to another.
1348   * Be very careful: $section and $destination refer to section number,
1349   * not id!.
1350   *
1351   * @param object $course
1352   * @param int $section Section number (not id!!!)
1353   * @param int $destination
1354   * @param bool $ignorenumsections
1355   * @return boolean Result
1356   */
1357  function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1358  /// Moves a whole course section up and down within the course
1359      global $USER, $DB;
1360  
1361      if (!$destination && $destination != 0) {
1362          return true;
1363      }
1364  
1365      // compartibility with course formats using field 'numsections'
1366      $courseformatoptions = course_get_format($course)->get_format_options();
1367      if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1368              ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1369          return false;
1370      }
1371  
1372      // Get all sections for this course and re-order them (2 of them should now share the same section number)
1373      if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1374              'section ASC, id ASC', 'id, section')) {
1375          return false;
1376      }
1377  
1378      $movedsections = reorder_sections($sections, $section, $destination);
1379  
1380      // Update all sections. Do this in 2 steps to avoid breaking database
1381      // uniqueness constraint
1382      $transaction = $DB->start_delegated_transaction();
1383      foreach ($movedsections as $id => $position) {
1384          if ($sections[$id] !== $position) {
1385              $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1386          }
1387      }
1388      foreach ($movedsections as $id => $position) {
1389          if ($sections[$id] !== $position) {
1390              $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1391          }
1392      }
1393  
1394      // If we move the highlighted section itself, then just highlight the destination.
1395      // Adjust the higlighted section location if we move something over it either direction.
1396      if ($section == $course->marker) {
1397          course_set_marker($course->id, $destination);
1398      } elseif ($section > $course->marker && $course->marker >= $destination) {
1399          course_set_marker($course->id, $course->marker+1);
1400      } elseif ($section < $course->marker && $course->marker <= $destination) {
1401          course_set_marker($course->id, $course->marker-1);
1402      }
1403  
1404      $transaction->allow_commit();
1405      rebuild_course_cache($course->id, true);
1406      return true;
1407  }
1408  
1409  /**
1410   * This method will delete a course section and may delete all modules inside it.
1411   *
1412   * No permissions are checked here, use {@link course_can_delete_section()} to
1413   * check if section can actually be deleted.
1414   *
1415   * @param int|stdClass $course
1416   * @param int|stdClass|section_info $section
1417   * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1418   * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1419   * @return bool whether section was deleted
1420   */
1421  function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1422      global $DB;
1423  
1424      // Prepare variables.
1425      $courseid = (is_object($course)) ? $course->id : (int)$course;
1426      $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1427      $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1428      if (!$section) {
1429          // No section exists, can't proceed.
1430          return false;
1431      }
1432  
1433      // Check the 'course_module_background_deletion_recommended' hook first.
1434      // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1435      // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1436      // It's up to plugins to handle things like whether or not they are enabled.
1437      if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1438          foreach ($pluginsfunction as $plugintype => $plugins) {
1439              foreach ($plugins as $pluginfunction) {
1440                  if ($pluginfunction()) {
1441                      return course_delete_section_async($section, $forcedeleteifnotempty);
1442                  }
1443              }
1444          }
1445      }
1446  
1447      $format = course_get_format($course);
1448      $sectionname = $format->get_section_name($section);
1449  
1450      // Delete section.
1451      $result = $format->delete_section($section, $forcedeleteifnotempty);
1452  
1453      // Trigger an event for course section deletion.
1454      if ($result) {
1455          $context = context_course::instance($courseid);
1456          $event = \core\event\course_section_deleted::create(
1457              array(
1458                  'objectid' => $section->id,
1459                  'courseid' => $courseid,
1460                  'context' => $context,
1461                  'other' => array(
1462                      'sectionnum' => $section->section,
1463                      'sectionname' => $sectionname,
1464                  )
1465              )
1466          );
1467          $event->add_record_snapshot('course_sections', $section);
1468          $event->trigger();
1469      }
1470      return $result;
1471  }
1472  
1473  /**
1474   * Course section deletion, using an adhoc task for deletion of the modules it contains.
1475   * 1. Schedule all modules within the section for adhoc removal.
1476   * 2. Move all modules to course section 0.
1477   * 3. Delete the resulting empty section.
1478   *
1479   * @param \stdClass $section the section to schedule for deletion.
1480   * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1481   * @return bool true if the section was scheduled for deletion, false otherwise.
1482   */
1483  function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1484      global $DB, $USER;
1485  
1486      // Objects only, and only valid ones.
1487      if (!is_object($section) || empty($section->id)) {
1488          return false;
1489      }
1490  
1491      // Does the object currently exist in the DB for removal (check for stale objects).
1492      $section = $DB->get_record('course_sections', array('id' => $section->id));
1493      if (!$section || !$section->section) {
1494          // No section exists, or the section is 0. Can't proceed.
1495          return false;
1496      }
1497  
1498      // Check whether the section can be removed.
1499      if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1500          return false;
1501      }
1502  
1503      $format = course_get_format($section->course);
1504      $sectionname = $format->get_section_name($section);
1505  
1506      // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1507      // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1508      $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1509                                              [$section->course, $section->id, 1], '', 'id');
1510      $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1511  
1512      // Move all modules to section 0.
1513      $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1514      $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1515      foreach ($modules as $mod) {
1516          moveto_module($mod, $sectionzero);
1517      }
1518  
1519      // Create and queue an adhoc task for the deletion of the modules.
1520      $removaltask = new \core_course\task\course_delete_modules();
1521      $data = array(
1522          'cms' => $affectedmods,
1523          'userid' => $USER->id,
1524          'realuserid' => \core\session\manager::get_realuser()->id
1525      );
1526      $removaltask->set_custom_data($data);
1527      \core\task\manager::queue_adhoc_task($removaltask);
1528  
1529      // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1530      // The refresh is needed because the section->sequence is now stale.
1531      $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1532  
1533      // Trigger an event for course section deletion.
1534      if ($result) {
1535          $context = \context_course::instance($section->course);
1536          $event = \core\event\course_section_deleted::create(
1537              array(
1538                  'objectid' => $section->id,
1539                  'courseid' => $section->course,
1540                  'context' => $context,
1541                  'other' => array(
1542                      'sectionnum' => $section->section,
1543                      'sectionname' => $sectionname,
1544                  )
1545              )
1546          );
1547          $event->add_record_snapshot('course_sections', $section);
1548          $event->trigger();
1549      }
1550      rebuild_course_cache($section->course, true);
1551  
1552      return $result;
1553  }
1554  
1555  /**
1556   * Updates the course section
1557   *
1558   * This function does not check permissions or clean values - this has to be done prior to calling it.
1559   *
1560   * @param int|stdClass $course
1561   * @param stdClass $section record from course_sections table - it will be updated with the new values
1562   * @param array|stdClass $data
1563   */
1564  function course_update_section($course, $section, $data) {
1565      global $DB;
1566  
1567      $courseid = (is_object($course)) ? $course->id : (int)$course;
1568  
1569      // Some fields can not be updated using this method.
1570      $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1571      $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1572      if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1573          throw new moodle_exception('maximumchars', 'moodle', '', 255);
1574      }
1575  
1576      // Update record in the DB and course format options.
1577      $data['id'] = $section->id;
1578      $data['timemodified'] = time();
1579      $DB->update_record('course_sections', $data);
1580      rebuild_course_cache($courseid, true);
1581      course_get_format($courseid)->update_section_format_options($data);
1582  
1583      // Update fields of the $section object.
1584      foreach ($data as $key => $value) {
1585          if (property_exists($section, $key)) {
1586              $section->$key = $value;
1587          }
1588      }
1589  
1590      // Trigger an event for course section update.
1591      $event = \core\event\course_section_updated::create(
1592          array(
1593              'objectid' => $section->id,
1594              'courseid' => $courseid,
1595              'context' => context_course::instance($courseid),
1596              'other' => array('sectionnum' => $section->section)
1597          )
1598      );
1599      $event->trigger();
1600  
1601      // If section visibility was changed, hide the modules in this section too.
1602      if ($changevisibility && !empty($section->sequence)) {
1603          $modules = explode(',', $section->sequence);
1604          foreach ($modules as $moduleid) {
1605              if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1606                  if ($data['visible']) {
1607                      // As we unhide the section, we use the previously saved visibility stored in visibleold.
1608                      set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
1609                  } else {
1610                      // We hide the section, so we hide the module but we store the original state in visibleold.
1611                      set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
1612                      $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1613                  }
1614                  \core\event\course_module_updated::create_from_cm($cm)->trigger();
1615              }
1616          }
1617      }
1618  }
1619  
1620  /**
1621   * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1622   *
1623   * @param int|stdClass $course
1624   * @param int|stdClass|section_info $section
1625   * @return bool
1626   */
1627  function course_can_delete_section($course, $section) {
1628      if (is_object($section)) {
1629          $section = $section->section;
1630      }
1631      if (!$section) {
1632          // Not possible to delete 0-section.
1633          return false;
1634      }
1635      // Course format should allow to delete sections.
1636      if (!course_get_format($course)->can_delete_section($section)) {
1637          return false;
1638      }
1639      // Make sure user has capability to update course and move sections.
1640      $context = context_course::instance(is_object($course) ? $course->id : $course);
1641      if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1642          return false;
1643      }
1644      // Make sure user has capability to delete each activity in this section.
1645      $modinfo = get_fast_modinfo($course);
1646      if (!empty($modinfo->sections[$section])) {
1647          foreach ($modinfo->sections[$section] as $cmid) {
1648              if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1649                  return false;
1650              }
1651          }
1652      }
1653      return true;
1654  }
1655  
1656  /**
1657   * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1658   * an original position number and a target position number, rebuilds the array so that the
1659   * move is made without any duplication of section positions.
1660   * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1661   * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1662   *
1663   * @param array $sections
1664   * @param int $origin_position
1665   * @param int $target_position
1666   * @return array
1667   */
1668  function reorder_sections($sections, $origin_position, $target_position) {
1669      if (!is_array($sections)) {
1670          return false;
1671      }
1672  
1673      // We can't move section position 0
1674      if ($origin_position < 1) {
1675          echo "We can't move section position 0";
1676          return false;
1677      }
1678  
1679      // Locate origin section in sections array
1680      if (!$origin_key = array_search($origin_position, $sections)) {
1681          echo "searched position not in sections array";
1682          return false; // searched position not in sections array
1683      }
1684  
1685      // Extract origin section
1686      $origin_section = $sections[$origin_key];
1687      unset($sections[$origin_key]);
1688  
1689      // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1690      $found = false;
1691      $append_array = array();
1692      foreach ($sections as $id => $position) {
1693          if ($found) {
1694              $append_array[$id] = $position;
1695              unset($sections[$id]);
1696          }
1697          if ($position == $target_position) {
1698              if ($target_position < $origin_position) {
1699                  $append_array[$id] = $position;
1700                  unset($sections[$id]);
1701              }
1702              $found = true;
1703          }
1704      }
1705  
1706      // Append moved section
1707      $sections[$origin_key] = $origin_section;
1708  
1709      // Append rest of array (if applicable)
1710      if (!empty($append_array)) {
1711          foreach ($append_array as $id => $position) {
1712              $sections[$id] = $position;
1713          }
1714      }
1715  
1716      // Renumber positions
1717      $position = 0;
1718      foreach ($sections as $id => $p) {
1719          $sections[$id] = $position;
1720          $position++;
1721      }
1722  
1723      return $sections;
1724  
1725  }
1726  
1727  /**
1728   * Move the module object $mod to the specified $section
1729   * If $beforemod exists then that is the module
1730   * before which $modid should be inserted
1731   *
1732   * @param stdClass|cm_info $mod
1733   * @param stdClass|section_info $section
1734   * @param int|stdClass $beforemod id or object with field id corresponding to the module
1735   *     before which the module needs to be included. Null for inserting in the
1736   *     end of the section
1737   * @return int new value for module visibility (0 or 1)
1738   */
1739  function moveto_module($mod, $section, $beforemod=NULL) {
1740      global $OUTPUT, $DB;
1741  
1742      // Current module visibility state - return value of this function.
1743      $modvisible = $mod->visible;
1744  
1745      // Remove original module from original section.
1746      if (! delete_mod_from_section($mod->id, $mod->section)) {
1747          echo $OUTPUT->notification("Could not delete module from existing section");
1748      }
1749  
1750      // If moving to a hidden section then hide module.
1751      if ($mod->section != $section->id) {
1752          if (!$section->visible && $mod->visible) {
1753              // Module was visible but must become hidden after moving to hidden section.
1754              $modvisible = 0;
1755              set_coursemodule_visible($mod->id, 0);
1756              // Set visibleold to 1 so module will be visible when section is made visible.
1757              $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1758          }
1759          if ($section->visible && !$mod->visible) {
1760              // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1761              set_coursemodule_visible($mod->id, $mod->visibleold);
1762              $modvisible = $mod->visibleold;
1763          }
1764      }
1765  
1766      // Add the module into the new section.
1767      course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1768      return $modvisible;
1769  }
1770  
1771  /**
1772   * Returns the list of all editing actions that current user can perform on the module
1773   *
1774   * @param cm_info $mod The module to produce editing buttons for
1775   * @param int $indent The current indenting (default -1 means no move left-right actions)
1776   * @param int $sr The section to link back to (used for creating the links)
1777   * @return array array of action_link or pix_icon objects
1778   */
1779  function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1780      global $COURSE, $SITE, $CFG;
1781  
1782      static $str;
1783  
1784      $coursecontext = context_course::instance($mod->course);
1785      $modcontext = context_module::instance($mod->id);
1786      $courseformat = course_get_format($mod->get_course());
1787  
1788      $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1789      $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1790  
1791      // No permission to edit anything.
1792      if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1793          return array();
1794      }
1795  
1796      $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1797  
1798      if (!isset($str)) {
1799          $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1800              'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
1801          $str->assign         = get_string('assignroles', 'role');
1802          $str->groupsnone     = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1803          $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1804          $str->groupsvisible  = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1805      }
1806  
1807      $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1808  
1809      if ($sr !== null) {
1810          $baseurl->param('sr', $sr);
1811      }
1812      $actions = array();
1813  
1814      // Update.
1815      if ($hasmanageactivities) {
1816          $actions['update'] = new action_menu_link_secondary(
1817              new moodle_url($baseurl, array('update' => $mod->id)),
1818              new pix_icon('t/edit', '', 'moodle', array('class' => 'iconsmall')),
1819              $str->editsettings,
1820              array('class' => 'editing_update', 'data-action' => 'update')
1821          );
1822      }
1823  
1824      // Indent.
1825      if ($hasmanageactivities && $indent >= 0) {
1826          $indentlimits = new stdClass();
1827          $indentlimits->min = 0;
1828          $indentlimits->max = 16;
1829          if (right_to_left()) {   // Exchange arrows on RTL
1830              $rightarrow = 't/left';
1831              $leftarrow  = 't/right';
1832          } else {
1833              $rightarrow = 't/right';
1834              $leftarrow  = 't/left';
1835          }
1836  
1837          if ($indent >= $indentlimits->max) {
1838              $enabledclass = 'hidden';
1839          } else {
1840              $enabledclass = '';
1841          }
1842          $actions['moveright'] = new action_menu_link_secondary(
1843              new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1844              new pix_icon($rightarrow, '', 'moodle', array('class' => 'iconsmall')),
1845              $str->moveright,
1846              array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1847                  'data-keepopen' => true, 'data-sectionreturn' => $sr)
1848          );
1849  
1850          if ($indent <= $indentlimits->min) {
1851              $enabledclass = 'hidden';
1852          } else {
1853              $enabledclass = '';
1854          }
1855          $actions['moveleft'] = new action_menu_link_secondary(
1856              new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1857              new pix_icon($leftarrow, '', 'moodle', array('class' => 'iconsmall')),
1858              $str->moveleft,
1859              array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1860                  'data-keepopen' => true, 'data-sectionreturn' => $sr)
1861          );
1862  
1863      }
1864  
1865      // Hide/Show/Available/Unavailable.
1866      if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1867          $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1868  
1869          $sectionvisible = $mod->get_section_info()->visible;
1870          // The module on the course page may be in one of the following states:
1871          // - Available and displayed on the course page ($displayedoncoursepage);
1872          // - Not available and not displayed on the course page ($unavailable);
1873          // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1874          $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1875          $unavailable = !$mod->visible;
1876          $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1877          if ($displayedoncoursepage) {
1878              $actions['hide'] = new action_menu_link_secondary(
1879                  new moodle_url($baseurl, array('hide' => $mod->id)),
1880                  new pix_icon('t/hide', '', 'moodle', array('class' => 'iconsmall')),
1881                  $str->modhide,
1882                  array('class' => 'editing_hide', 'data-action' => 'hide')
1883              );
1884          } else if (!$displayedoncoursepage && $sectionvisible) {
1885              // Offer to "show" only if the section is visible.
1886              $actions['show'] = new action_menu_link_secondary(
1887                  new moodle_url($baseurl, array('show' => $mod->id)),
1888                  new pix_icon('t/show', '', 'moodle', array('class' => 'iconsmall')),
1889                  $str->modshow,
1890                  array('class' => 'editing_show', 'data-action' => 'show')
1891              );
1892          }
1893  
1894          if ($stealth) {
1895              // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1896              $actions['hide'] = new action_menu_link_secondary(
1897                  new moodle_url($baseurl, array('hide' => $mod->id)),
1898                  new pix_icon('t/unblock', '', 'moodle', array('class' => 'iconsmall')),
1899                  $str->makeunavailable,
1900                  array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1901              );
1902          } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1903              // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1904              // When the section is hidden it is an equivalent of "showing" the module.
1905              // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1906              $action = $sectionvisible ? 'stealth' : 'show';
1907              $actions[$action] = new action_menu_link_secondary(
1908                  new moodle_url($baseurl, array($action => $mod->id)),
1909                  new pix_icon('t/block', '', 'moodle', array('class' => 'iconsmall')),
1910                  $str->makeavailable,
1911                  array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1912              );
1913          }
1914      }
1915  
1916      // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1917      if (has_all_capabilities($dupecaps, $coursecontext) &&
1918              plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1919              course_allowed_module($mod->get_course(), $mod->modname)) {
1920          $actions['duplicate'] = new action_menu_link_secondary(
1921              new moodle_url($baseurl, array('duplicate' => $mod->id)),
1922              new pix_icon('t/copy', '', 'moodle', array('class' => 'iconsmall')),
1923              $str->duplicate,
1924              array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
1925          );
1926      }
1927  
1928      // Groupmode.
1929      if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1930          if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
1931              if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1932                  $nextgroupmode = VISIBLEGROUPS;
1933                  $grouptitle = $str->groupsseparate;
1934                  $actionname = 'groupsseparate';
1935                  $nextactionname = 'groupsvisible';
1936                  $groupimage = 'i/groups';
1937              } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1938                  $nextgroupmode = NOGROUPS;
1939                  $grouptitle = $str->groupsvisible;
1940                  $actionname = 'groupsvisible';
1941                  $nextactionname = 'groupsnone';
1942                  $groupimage = 'i/groupv';
1943              } else {
1944                  $nextgroupmode = SEPARATEGROUPS;
1945                  $grouptitle = $str->groupsnone;
1946                  $actionname = 'groupsnone';
1947                  $nextactionname = 'groupsseparate';
1948                  $groupimage = 'i/groupn';
1949              }
1950  
1951              $actions[$actionname] = new action_menu_link_primary(
1952                  new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1953                  new pix_icon($groupimage, '', 'moodle', array('class' => 'iconsmall')),
1954                  $grouptitle,
1955                  array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
1956                      'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
1957              );
1958          } else {
1959              $actions['nogroupsupport'] = new action_menu_filler();
1960          }
1961      }
1962  
1963      // Assign.
1964      if (has_capability('moodle/role:assign', $modcontext)){
1965          $actions['assign'] = new action_menu_link_secondary(
1966              new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1967              new pix_icon('t/assignroles', '', 'moodle', array('class' => 'iconsmall')),
1968              $str->assign,
1969              array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
1970          );
1971      }
1972  
1973      // Delete.
1974      if ($hasmanageactivities) {
1975          $actions['delete'] = new action_menu_link_secondary(
1976              new moodle_url($baseurl, array('delete' => $mod->id)),
1977              new pix_icon('t/delete', '', 'moodle', array('class' => 'iconsmall')),
1978              $str->delete,
1979              array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
1980          );
1981      }
1982  
1983      return $actions;
1984  }
1985  
1986  /**
1987   * Returns the move action.
1988   *
1989   * @param cm_info $mod The module to produce a move button for
1990   * @param int $sr The section to link back to (used for creating the links)
1991   * @return The markup for the move action, or an empty string if not available.
1992   */
1993  function course_get_cm_move(cm_info $mod, $sr = null) {
1994      global $OUTPUT;
1995  
1996      static $str;
1997      static $baseurl;
1998  
1999      $modcontext = context_module::instance($mod->id);
2000      $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2001  
2002      if (!isset($str)) {
2003          $str = get_strings(array('move'));
2004      }
2005  
2006      if (!isset($baseurl)) {
2007          $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2008  
2009          if ($sr !== null) {
2010              $baseurl->param('sr', $sr);
2011          }
2012      }
2013  
2014      if ($hasmanageactivities) {
2015          $pixicon = 'i/dragdrop';
2016  
2017          if (!course_ajax_enabled($mod->get_course())) {
2018              // Override for course frontpage until we get drag/drop working there.
2019              $pixicon = 't/move';
2020          }
2021  
2022          $attributes = [
2023              'class' => 'editing_move',
2024              'data-action' => 'move',
2025              'data-sectionreturn' => $sr,
2026              'title' => $str->move,
2027              'aria-label' => $str->move,
2028          ];
2029          return html_writer::link(
2030              new moodle_url($baseurl, ['copy' => $mod->id]),
2031              $OUTPUT->pix_icon($pixicon, '', 'moodle', ['class' => 'iconsmall']),
2032              $attributes
2033          );
2034      }
2035      return '';
2036  }
2037  
2038  /**
2039   * given a course object with shortname & fullname, this function will
2040   * truncate the the number of chars allowed and add ... if it was too long
2041   */
2042  function course_format_name ($course,$max=100) {
2043  
2044      $context = context_course::instance($course->id);
2045      $shortname = format_string($course->shortname, true, array('context' => $context));
2046      $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2047      $str = $shortname.': '. $fullname;
2048      if (core_text::strlen($str) <= $max) {
2049          return $str;
2050      }
2051      else {
2052          return core_text::substr($str,0,$max-3).'...';
2053      }
2054  }
2055  
2056  /**
2057   * Is the user allowed to add this type of module to this course?
2058   * @param object $course the course settings. Only $course->id is used.
2059   * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2060   * @param \stdClass $user the user to check, defaults to the global user if not provided.
2061   * @return bool whether the current user is allowed to add this type of module to this course.
2062   */
2063  function course_allowed_module($course, $modname, \stdClass $user = null) {
2064      global $USER;
2065      $user = $user ?? $USER;
2066      if (is_numeric($modname)) {
2067          throw new coding_exception('Function course_allowed_module no longer
2068                  supports numeric module ids. Please update your code to pass the module name.');
2069      }
2070  
2071      $capability = 'mod/' . $modname . ':addinstance';
2072      if (!get_capability_info($capability)) {
2073          // Debug warning that the capability does not exist, but no more than once per page.
2074          static $warned = array();
2075          $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2076          if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2077              debugging('The module ' . $modname . ' does not define the standard capability ' .
2078                      $capability , DEBUG_DEVELOPER);
2079              $warned[$modname] = 1;
2080          }
2081  
2082          // If the capability does not exist, the module can always be added.
2083          return true;
2084      }
2085  
2086      $coursecontext = context_course::instance($course->id);
2087      return has_capability($capability, $coursecontext, $user);
2088  }
2089  
2090  /**
2091   * Efficiently moves many courses around while maintaining
2092   * sortorder in order.
2093   *
2094   * @param array $courseids is an array of course ids
2095   * @param int $categoryid
2096   * @return bool success
2097   */
2098  function move_courses($courseids, $categoryid) {
2099      global $DB;
2100  
2101      if (empty($courseids)) {
2102          // Nothing to do.
2103          return false;
2104      }
2105  
2106      if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2107          return false;
2108      }
2109  
2110      $courseids = array_reverse($courseids);
2111      $newparent = context_coursecat::instance($category->id);
2112      $i = 1;
2113  
2114      list($where, $params) = $DB->get_in_or_equal($courseids);
2115      $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2116      foreach ($dbcourses as $dbcourse) {
2117          $course = new stdClass();
2118          $course->id = $dbcourse->id;
2119          $course->timemodified = time();
2120          $course->category  = $category->id;
2121          $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2122          if ($category->visible == 0) {
2123              // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2124              // to previous state if somebody unhides the category.
2125              $course->visible = 0;
2126          }
2127  
2128          $DB->update_record('course', $course);
2129  
2130          // Update context, so it can be passed to event.
2131          $context = context_course::instance($course->id);
2132          $context->update_moved($newparent);
2133  
2134          // Trigger a course updated event.
2135          $event = \core\event\course_updated::create(array(
2136              'objectid' => $course->id,
2137              'context' => context_course::instance($course->id),
2138              'other' => array('shortname' => $dbcourse->shortname,
2139                               'fullname' => $dbcourse->fullname,
2140                               'updatedfields' => array('category' => $category->id))
2141          ));
2142          $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2143          $event->trigger();
2144      }
2145      fix_course_sortorder();
2146      cache_helper::purge_by_event('changesincourse');
2147  
2148      return true;
2149  }
2150  
2151  /**
2152   * Returns the display name of the given section that the course prefers
2153   *
2154   * Implementation of this function is provided by course format
2155   * @see format_base::get_section_name()
2156   *
2157   * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2158   * @param int|stdClass $section Section object from database or just field course_sections.section
2159   * @return string Display name that the course format prefers, e.g. "Week 2"
2160   */
2161  function get_section_name($courseorid, $section) {
2162      return course_get_format($courseorid)->get_section_name($section);
2163  }
2164  
2165  /**
2166   * Tells if current course format uses sections
2167   *
2168   * @param string $format Course format ID e.g. 'weeks' $course->format
2169   * @return bool
2170   */
2171  function course_format_uses_sections($format) {
2172      $course = new stdClass();
2173      $course->format = $format;
2174      return course_get_format($course)->uses_sections();
2175  }
2176  
2177  /**
2178   * Returns the information about the ajax support in the given source format
2179   *
2180   * The returned object's property (boolean)capable indicates that
2181   * the course format supports Moodle course ajax features.
2182   *
2183   * @param string $format
2184   * @return stdClass
2185   */
2186  function course_format_ajax_support($format) {
2187      $course = new stdClass();
2188      $course->format = $format;
2189      return course_get_format($course)->supports_ajax();
2190  }
2191  
2192  /**
2193   * Can the current user delete this course?
2194   * Course creators have exception,
2195   * 1 day after the creation they can sill delete the course.
2196   * @param int $courseid
2197   * @return boolean
2198   */
2199  function can_delete_course($courseid) {
2200      global $USER;
2201  
2202      $context = context_course::instance($courseid);
2203  
2204      if (has_capability('moodle/course:delete', $context)) {
2205          return true;
2206      }
2207  
2208      // hack: now try to find out if creator created this course recently (1 day)
2209      if (!has_capability('moodle/course:create', $context)) {
2210          return false;
2211      }
2212  
2213      $since = time() - 60*60*24;
2214      $course = get_course($courseid);
2215  
2216      if ($course->timecreated < $since) {
2217          return false; // Return if the course was not created in last 24 hours.
2218      }
2219  
2220      $logmanger = get_log_manager();
2221      $readers = $logmanger->get_readers('\core\log\sql_reader');
2222      $reader = reset($readers);
2223  
2224      if (empty($reader)) {
2225          return false; // No log reader found.
2226      }
2227  
2228      // A proper reader.
2229      $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2230      $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2231  
2232      return (bool)$reader->get_events_select_count($select, $params);
2233  }
2234  
2235  /**
2236   * Save the Your name for 'Some role' strings.
2237   *
2238   * @param integer $courseid the id of this course.
2239   * @param array $data the data that came from the course settings form.
2240   */
2241  function save_local_role_names($courseid, $data) {
2242      global $DB;
2243      $context = context_course::instance($courseid);
2244  
2245      foreach ($data as $fieldname => $value) {
2246          if (strpos($fieldname, 'role_') !== 0) {
2247              continue;
2248          }
2249          list($ignored, $roleid) = explode('_', $fieldname);
2250  
2251          // make up our mind whether we want to delete, update or insert
2252          if (!$value) {
2253              $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2254  
2255          } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2256              $rolename->name = $value;
2257              $DB->update_record('role_names', $rolename);
2258  
2259          } else {
2260              $rolename = new stdClass;
2261              $rolename->contextid = $context->id;
2262              $rolename->roleid = $roleid;
2263              $rolename->name = $value;
2264              $DB->insert_record('role_names', $rolename);
2265          }
2266          // This will ensure the course contacts cache is purged..
2267          core_course_category::role_assignment_changed($roleid, $context);
2268      }
2269  }
2270  
2271  /**
2272   * Returns options to use in course overviewfiles filemanager
2273   *
2274   * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
2275   *     may be empty if course does not exist yet (course create form)
2276   * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2277   *     or null if overviewfiles are disabled
2278   */
2279  function course_overviewfiles_options($course) {
2280      global $CFG;
2281      if (empty($CFG->courseoverviewfileslimit)) {
2282          return null;
2283      }
2284      $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2285      if (in_array('*', $accepted_types) || empty($accepted_types)) {
2286          $accepted_types = '*';
2287      } else {
2288          // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2289          // Make sure extensions are prefixed with dot unless they are valid typegroups
2290          foreach ($accepted_types as $i => $type) {
2291              if (substr($type, 0, 1) !== '.') {
2292                  require_once($CFG->libdir. '/filelib.php');
2293                  if (!count(file_get_typegroup('extension', $type))) {
2294                      // It does not start with dot and is not a valid typegroup, this is most likely extension.
2295                      $accepted_types[$i] = '.'. $type;
2296                      $corrected = true;
2297                  }
2298              }
2299          }
2300          if (!empty($corrected)) {
2301              set_config('courseoverviewfilesext', join(',', $accepted_types));
2302          }
2303      }
2304      $options = array(
2305          'maxfiles' => $CFG->courseoverviewfileslimit,
2306          'maxbytes' => $CFG->maxbytes,
2307          'subdirs' => 0,
2308          'accepted_types' => $accepted_types
2309      );
2310      if (!empty($course->id)) {
2311          $options['context'] = context_course::instance($course->id);
2312      } else if (is_int($course) && $course > 0) {
2313          $options['context'] = context_course::instance($course);
2314      }
2315      return $options;
2316  }
2317  
2318  /**
2319   * Create a course and either return a $course object
2320   *
2321   * Please note this functions does not verify any access control,
2322   * the calling code is responsible for all validation (usually it is the form definition).
2323   *
2324   * @param array $editoroptions course description editor options
2325   * @param object $data  - all the data needed for an entry in the 'course' table
2326   * @return object new course instance
2327   */
2328  function create_course($data, $editoroptions = NULL) {
2329      global $DB, $CFG;
2330  
2331      //check the categoryid - must be given for all new courses
2332      $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2333  
2334      // Check if the shortname already exists.
2335      if (!empty($data->shortname)) {
2336          if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2337              throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2338          }
2339      }
2340  
2341      // Check if the idnumber already exists.
2342      if (!empty($data->idnumber)) {
2343          if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2344              throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2345          }
2346      }
2347  
2348      if (empty($CFG->enablecourserelativedates)) {
2349          // Make sure we're not setting the relative dates mode when the setting is disabled.
2350          unset($data->relativedatesmode);
2351      }
2352  
2353      if ($errorcode = course_validate_dates((array)$data)) {
2354          throw new moodle_exception($errorcode);
2355      }
2356  
2357      // Check if timecreated is given.
2358      $data->timecreated  = !empty($data->timecreated) ? $data->timecreated : time();
2359      $data->timemodified = $data->timecreated;
2360  
2361      // place at beginning of any category
2362      $data->sortorder = 0;
2363  
2364      if ($editoroptions) {
2365          // summary text is updated later, we need context to store the files first
2366          $data->summary = '';
2367          $data->summary_format = FORMAT_HTML;
2368      }
2369  
2370      if (!isset($data->visible)) {
2371          // data not from form, add missing visibility info
2372          $data->visible = $category->visible;
2373      }
2374      $data->visibleold = $data->visible;
2375  
2376      $newcourseid = $DB->insert_record('course', $data);
2377      $context = context_course::instance($newcourseid, MUST_EXIST);
2378  
2379      if ($editoroptions) {
2380          // Save the files used in the summary editor and store
2381          $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2382          $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2383          $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2384      }
2385      if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2386          // Save the course overviewfiles
2387          $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2388      }
2389  
2390      // update course format options
2391      course_get_format($newcourseid)->update_course_format_options($data);
2392  
2393      $course = course_get_format($newcourseid)->get_course();
2394  
2395      fix_course_sortorder();
2396      // purge appropriate caches in case fix_course_sortorder() did not change anything
2397      cache_helper::purge_by_event('changesincourse');
2398  
2399      // Trigger a course created event.
2400      $event = \core\event\course_created::create(array(
2401          'objectid' => $course->id,
2402          'context' => context_course::instance($course->id),
2403          'other' => array('shortname' => $course->shortname,
2404              'fullname' => $course->fullname)
2405      ));
2406  
2407      $event->trigger();
2408  
2409      // Setup the blocks
2410      blocks_add_default_course_blocks($course);
2411  
2412      // Create default section and initial sections if specified (unless they've already been created earlier).
2413      // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2414      $numsections = isset($data->numsections) ? $data->numsections : 0;
2415      $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2416      $newsections = array_diff(range(0, $numsections), $existingsections);
2417      foreach ($newsections as $sectionnum) {
2418          course_create_section($newcourseid, $sectionnum, true);
2419      }
2420  
2421      // Save any custom role names.
2422      save_local_role_names($course->id, (array)$data);
2423  
2424      // set up enrolments
2425      enrol_course_updated(true, $course, $data);
2426  
2427      // Update course tags.
2428      if (isset($data->tags)) {
2429          core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2430      }
2431  
2432      // Save custom fields if there are any of them in the form.
2433      $handler = core_course\customfield\course_handler::create();
2434      // Make sure to set the handler's parent context first.
2435      $coursecatcontext = context_coursecat::instance($category->id);
2436      $handler->set_parent_context($coursecatcontext);
2437      // Save the custom field data.
2438      $data->id = $course->id;
2439      $handler->instance_form_save($data, true);
2440  
2441      return $course;
2442  }
2443  
2444  /**
2445   * Update a course.
2446   *
2447   * Please note this functions does not verify any access control,
2448   * the calling code is responsible for all validation (usually it is the form definition).
2449   *
2450   * @param object $data  - all the data needed for an entry in the 'course' table
2451   * @param array $editoroptions course description editor options
2452   * @return void
2453   */
2454  function update_course($data, $editoroptions = NULL) {
2455      global $DB, $CFG;
2456  
2457      // Prevent changes on front page course.
2458      if ($data->id == SITEID) {
2459          throw new moodle_exception('invalidcourse', 'error');
2460      }
2461  
2462      $oldcourse = course_get_format($data->id)->get_course();
2463      $context   = context_course::instance($oldcourse->id);
2464  
2465      // Make sure we're not changing whatever the course's relativedatesmode setting is.
2466      unset($data->relativedatesmode);
2467  
2468      // Capture the updated fields for the log data.
2469      $updatedfields = [];
2470      foreach (get_object_vars($oldcourse) as $field => $value) {
2471          if ($field == 'summary_editor') {
2472              if (($data->$field)['text'] !== $value['text']) {
2473                  // The summary might be very long, we don't wan't to fill up the log record with the full text.
2474                  $updatedfields[$field] = '(updated)';
2475              }
2476          } else if ($field == 'tags' && isset($data->tags)) {
2477              // Tags might not have the same array keys, just check the values.
2478              if (array_values($data->$field) !== array_values($value)) {
2479                  $updatedfields[$field] = $data->$field;
2480              }
2481          } else {
2482              if (isset($data->$field) && $data->$field != $value) {
2483                  $updatedfields[$field] = $data->$field;
2484              }
2485          }
2486      }
2487  
2488      $data->timemodified = time();
2489  
2490      if ($editoroptions) {
2491          $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2492      }
2493      if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2494          $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2495      }
2496  
2497      // Check we don't have a duplicate shortname.
2498      if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2499          if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2500              throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2501          }
2502      }
2503  
2504      // Check we don't have a duplicate idnumber.
2505      if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2506          if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2507              throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2508          }
2509      }
2510  
2511      if ($errorcode = course_validate_dates((array)$data)) {
2512          throw new moodle_exception($errorcode);
2513      }
2514  
2515      if (!isset($data->category) or empty($data->category)) {
2516          // prevent nulls and 0 in category field
2517          unset($data->category);
2518      }
2519      $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2520  
2521      if (!isset($data->visible)) {
2522          // data not from form, add missing visibility info
2523          $data->visible = $oldcourse->visible;
2524      }
2525  
2526      if ($data->visible != $oldcourse->visible) {
2527          // reset the visibleold flag when manually hiding/unhiding course
2528          $data->visibleold = $data->visible;
2529          $changesincoursecat = true;
2530      } else {
2531          if ($movecat) {
2532              $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2533              if (empty($newcategory->visible)) {
2534                  // make sure when moving into hidden category the course is hidden automatically
2535                  $data->visible = 0;
2536              }
2537          }
2538      }
2539  
2540      // Set newsitems to 0 if format does not support announcements.
2541      if (isset($data->format)) {
2542          $newcourseformat = course_get_format((object)['format' => $data->format]);
2543          if (!$newcourseformat->supports_news()) {
2544              $data->newsitems = 0;
2545          }
2546      }
2547  
2548      // Update custom fields if there are any of them in the form.
2549      $handler = core_course\customfield\course_handler::create();
2550      $handler->instance_form_save($data);
2551  
2552      // Update with the new data
2553      $DB->update_record('course', $data);
2554      // make sure the modinfo cache is reset
2555      rebuild_course_cache($data->id);
2556  
2557      // update course format options with full course data
2558      course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2559  
2560      $course = $DB->get_record('course', array('id'=>$data->id));
2561  
2562      if ($movecat) {
2563          $newparent = context_coursecat::instance($course->category);
2564          $context->update_moved($newparent);
2565      }
2566      $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2567      if ($fixcoursesortorder) {
2568          fix_course_sortorder();
2569      }
2570  
2571      // purge appropriate caches in case fix_course_sortorder() did not change anything
2572      cache_helper::purge_by_event('changesincourse');
2573      if ($changesincoursecat) {
2574          cache_helper::purge_by_event('changesincoursecat');
2575      }
2576  
2577      // Test for and remove blocks which aren't appropriate anymore
2578      blocks_remove_inappropriate($course);
2579  
2580      // Save any custom role names.
2581      save_local_role_names($course->id, $data);
2582  
2583      // update enrol settings
2584      enrol_course_updated(false, $course, $data);
2585  
2586      // Update course tags.
2587      if (isset($data->tags)) {
2588          core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2589      }
2590  
2591      // Trigger a course updated event.
2592      $event = \core\event\course_updated::create(array(
2593          'objectid' => $course->id,
2594          'context' => context_course::instance($course->id),
2595          'other' => array('shortname' => $course->shortname,
2596                           'fullname' => $course->fullname,
2597                           'updatedfields' => $updatedfields)
2598      ));
2599  
2600      $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2601      $event->trigger();
2602  
2603      if ($oldcourse->format !== $course->format) {
2604          // Remove all options stored for the previous format
2605          // We assume that new course format migrated everything it needed watching trigger
2606          // 'course_updated' and in method format_XXX::update_course_format_options()
2607          $DB->delete_records('course_format_options',
2608                  array('courseid' => $course->id, 'format' => $oldcourse->format));
2609      }
2610  }
2611  
2612  /**
2613   * Calculate the average number of enrolled participants per course.
2614   *
2615   * This is intended for statistics purposes during the site registration. Only visible courses are taken into account.
2616   * Front page enrolments are excluded.
2617   *
2618   * @param bool $onlyactive Consider only active enrolments in enabled plugins and obey the enrolment time restrictions.
2619   * @param int $lastloginsince If specified, count only users who logged in after this timestamp.
2620   * @return float
2621   */
2622  function average_number_of_participants(bool $onlyactive = false, int $lastloginsince = null): float {
2623      global $DB;
2624  
2625      $params = [
2626          'siteid' => SITEID,
2627      ];
2628  
2629      $sql = "SELECT DISTINCT ue.userid, e.courseid
2630                FROM {user_enrolments} ue
2631                JOIN {enrol} e ON e.id = ue.enrolid
2632                JOIN {course} c ON c.id = e.courseid ";
2633  
2634      if ($onlyactive || $lastloginsince) {
2635          $sql .= "JOIN {user} u ON u.id = ue.userid ";
2636      }
2637  
2638      $sql .= "WHERE e.courseid <> :siteid
2639                 AND c.visible = 1 ";
2640  
2641      if ($onlyactive) {
2642          $sql .= "AND ue.status = :active
2643                   AND e.status = :enabled
2644                   AND ue.timestart < :now1
2645                   AND (ue.timeend = 0 OR ue.timeend > :now2) ";
2646  
2647          // Same as in the enrollib - the rounding should help caching in the database.
2648          $now = round(time(), -2);
2649  
2650          $params += [
2651              'active' => ENROL_USER_ACTIVE,
2652              'enabled' => ENROL_INSTANCE_ENABLED,
2653              'now1' => $now,
2654              'now2' => $now,
2655          ];
2656      }
2657  
2658      if ($lastloginsince) {
2659          $sql .= "AND u.lastlogin > :lastlogin ";
2660          $params['lastlogin'] = $lastloginsince;
2661      }
2662  
2663      $sql = "SELECT COUNT(*)
2664                FROM ($sql) total";
2665  
2666      $enrolmenttotal = $DB->count_records_sql($sql, $params);
2667  
2668      // Get the number of visible courses (exclude the front page).
2669      $coursetotal = $DB->count_records('course', ['visible' => 1]);
2670      $coursetotal = $coursetotal - 1;
2671  
2672      if (empty($coursetotal)) {
2673          $participantaverage = 0;
2674  
2675      } else {
2676          $participantaverage = $enrolmenttotal / $coursetotal;
2677      }
2678  
2679      return $participantaverage;
2680  }
2681  
2682  /**
2683   * Average number of course modules
2684   * @return integer
2685   */
2686  function average_number_of_courses_modules() {
2687      global $DB, $SITE;
2688  
2689      //count total of visible course module (except front page)
2690      $sql = 'SELECT COUNT(*) FROM (
2691          SELECT cm.course, cm.module
2692          FROM {course} c, {course_modules} cm
2693          WHERE c.id = cm.course
2694              AND c.id <> :siteid
2695              AND cm.visible = 1
2696              AND c.visible = 1) total';
2697      $params = array('siteid' => $SITE->id);
2698      $moduletotal = $DB->count_records_sql($sql, $params);
2699  
2700  
2701      //count total of visible courses (minus front page)
2702      $coursetotal = $DB->count_records('course', array('visible' => 1));
2703      $coursetotal = $coursetotal - 1 ;
2704  
2705      //average of course module
2706      if (empty($coursetotal)) {
2707          $coursemoduleaverage = 0;
2708      } else {
2709          $coursemoduleaverage = $moduletotal / $coursetotal;
2710      }
2711  
2712      return $coursemoduleaverage;
2713  }
2714  
2715  /**
2716   * This class pertains to course requests and contains methods associated with
2717   * create, approving, and removing course requests.
2718   *
2719   * Please note we do not allow embedded images here because there is no context
2720   * to store them with proper access control.
2721   *
2722   * @copyright 2009 Sam Hemelryk
2723   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2724   * @since Moodle 2.0
2725   *
2726   * @property-read int $id
2727   * @property-read string $fullname
2728   * @property-read string $shortname
2729   * @property-read string $summary
2730   * @property-read int $summaryformat
2731   * @property-read int $summarytrust
2732   * @property-read string $reason
2733   * @property-read int $requester
2734   */
2735  class course_request {
2736  
2737      /**
2738       * This is the stdClass that stores the properties for the course request
2739       * and is externally accessed through the __get magic method
2740       * @var stdClass
2741       */
2742      protected $properties;
2743  
2744      /**
2745       * An array of options for the summary editor used by course request forms.
2746       * This is initially set by {@link summary_editor_options()}
2747       * @var array
2748       * @static
2749       */
2750      protected static $summaryeditoroptions;
2751  
2752      /**
2753       * Static function to prepare the summary editor for working with a course
2754       * request.
2755       *
2756       * @static
2757       * @param null|stdClass $data Optional, an object containing the default values
2758       *                       for the form, these may be modified when preparing the
2759       *                       editor so this should be called before creating the form
2760       * @return stdClass An object that can be used to set the default values for
2761       *                   an mforms form
2762       */
2763      public static function prepare($data=null) {
2764          if ($data === null) {
2765              $data = new stdClass;
2766          }
2767          $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2768          return $data;
2769      }
2770  
2771      /**
2772       * Static function to create a new course request when passed an array of properties
2773       * for it.
2774       *
2775       * This function also handles saving any files that may have been used in the editor
2776       *
2777       * @static
2778       * @param stdClass $data
2779       * @return course_request The newly created course request
2780       */
2781      public static function create($data) {
2782          global $USER, $DB, $CFG;
2783          $data->requester = $USER->id;
2784  
2785          // Setting the default category if none set.
2786          if (empty($data->category) || !empty($CFG->lockrequestcategory)) {
2787              $data->category = $CFG->defaultrequestcategory;
2788          }
2789  
2790          // Summary is a required field so copy the text over
2791          $data->summary       = $data->summary_editor['text'];
2792          $data->summaryformat = $data->summary_editor['format'];
2793  
2794          $data->id = $DB->insert_record('course_request', $data);
2795  
2796          // Create a new course_request object and return it
2797          $request = new course_request($data);
2798  
2799          // Notify the admin if required.
2800          if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2801  
2802              $a = new stdClass;
2803              $a->link = "$CFG->wwwroot/course/pending.php";
2804              $a->user = fullname($USER);
2805              $subject = get_string('courserequest');
2806              $message = get_string('courserequestnotifyemail', 'admin', $a);
2807              foreach ($users as $user) {
2808                  $request->notify($user, $USER, 'courserequested', $subject, $message);
2809              }
2810          }
2811  
2812          return $request;
2813      }
2814  
2815      /**
2816       * Returns an array of options to use with a summary editor
2817       *
2818       * @uses course_request::$summaryeditoroptions
2819       * @return array An array of options to use with the editor
2820       */
2821      public static function summary_editor_options() {
2822          global $CFG;
2823          if (self::$summaryeditoroptions === null) {
2824              self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2825          }
2826          return self::$summaryeditoroptions;
2827      }
2828  
2829      /**
2830       * Loads the properties for this course request object. Id is required and if
2831       * only id is provided then we load the rest of the properties from the database
2832       *
2833       * @param stdClass|int $properties Either an object containing properties
2834       *                      or the course_request id to load
2835       */
2836      public function __construct($properties) {
2837          global $DB;
2838          if (empty($properties->id)) {
2839              if (empty($properties)) {
2840                  throw new coding_exception('You must provide a course request id when creating a course_request object');
2841              }
2842              $id = $properties;
2843              $properties = new stdClass;
2844              $properties->id = (int)$id;
2845              unset($id);
2846          }
2847          if (empty($properties->requester)) {
2848              if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2849                  print_error('unknowncourserequest');
2850              }
2851          } else {
2852              $this->properties = $properties;
2853          }
2854          $this->properties->collision = null;
2855      }
2856  
2857      /**
2858       * Returns the requested property
2859       *
2860       * @param string $key
2861       * @return mixed
2862       */
2863      public function __get($key) {
2864          return $this->properties->$key;
2865      }
2866  
2867      /**
2868       * Override this to ensure empty($request->blah) calls return a reliable answer...
2869       *
2870       * This is required because we define the __get method
2871       *
2872       * @param mixed $key
2873       * @return bool True is it not empty, false otherwise
2874       */
2875      public function __isset($key) {
2876          return (!empty($this->properties->$key));
2877      }
2878  
2879      /**
2880       * Returns the user who requested this course
2881       *
2882       * Uses a static var to cache the results and cut down the number of db queries
2883       *
2884       * @staticvar array $requesters An array of cached users
2885       * @return stdClass The user who requested the course
2886       */
2887      public function get_requester() {
2888          global $DB;
2889          static $requesters= array();
2890          if (!array_key_exists($this->properties->requester, $requesters)) {
2891              $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2892          }
2893          return $requesters[$this->properties->requester];
2894      }
2895  
2896      /**
2897       * Checks that the shortname used by the course does not conflict with any other
2898       * courses that exist
2899       *
2900       * @param string|null $shortnamemark The string to append to the requests shortname
2901       *                     should a conflict be found
2902       * @return bool true is there is a conflict, false otherwise
2903       */
2904      public function check_shortname_collision($shortnamemark = '[*]') {
2905          global $DB;
2906  
2907          if ($this->properties->collision !== null) {
2908              return $this->properties->collision;
2909          }
2910  
2911          if (empty($this->properties->shortname)) {
2912              debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2913              $this->properties->collision = false;
2914          } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2915              if (!empty($shortnamemark)) {
2916                  $this->properties->shortname .= ' '.$shortnamemark;
2917              }
2918              $this->properties->collision = true;
2919          } else {
2920              $this->properties->collision = false;
2921          }
2922          return $this->properties->collision;
2923      }
2924  
2925      /**
2926       * Checks user capability to approve a requested course
2927       *
2928       * If course was requested without category for some reason (might happen if $CFG->defaultrequestcategory is
2929       * misconfigured), we check capabilities 'moodle/site:approvecourse' and 'moodle/course:changecategory'.
2930       *
2931       * @return bool
2932       */
2933      public function can_approve() {
2934          global $CFG;
2935          $category = null;
2936          if ($this->properties->category) {
2937              $category = core_course_category::get($this->properties->category, IGNORE_MISSING);
2938          } else if ($CFG->defaultrequestcategory) {
2939              $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING);
2940          }
2941          if ($category) {
2942              return has_capability('moodle/site:approvecourse', $category->get_context());
2943          }
2944  
2945          // We can not determine the context where the course should be created. The approver should have
2946          // both capabilities to approve courses and change course category in the system context.
2947          return has_all_capabilities(['moodle/site:approvecourse', 'moodle/course:changecategory'], context_system::instance());
2948      }
2949  
2950      /**
2951       * Returns the category where this course request should be created
2952       *
2953       * Note that we don't check here that user has a capability to view
2954       * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2955       * 'moodle/course:changecategory'
2956       *
2957       * @return core_course_category
2958       */
2959      public function get_category() {
2960          global $CFG;
2961          if ($this->properties->category && ($category = core_course_category::get($this->properties->category, IGNORE_MISSING))) {
2962              return $category;
2963          } else if ($CFG->defaultrequestcategory &&
2964                  ($category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING))) {
2965              return $category;
2966          } else {
2967              return core_course_category::get_default();
2968          }
2969      }
2970  
2971      /**
2972       * This function approves the request turning it into a course
2973       *
2974       * This function converts the course request into a course, at the same time
2975       * transferring any files used in the summary to the new course and then removing
2976       * the course request and the files associated with it.
2977       *
2978       * @return int The id of the course that was created from this request
2979       */
2980      public function approve() {
2981          global $CFG, $DB, $USER;
2982  
2983          require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2984  
2985          $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2986  
2987          $courseconfig = get_config('moodlecourse');
2988  
2989          // Transfer appropriate settings
2990          $data = clone($this->properties);
2991          unset($data->id);
2992          unset($data->reason);
2993          unset($data->requester);
2994  
2995          // Set category
2996          $category = $this->get_category();
2997          $data->category = $category->id;
2998          // Set misc settings
2999          $data->requested = 1;
3000  
3001          // Apply course default settings
3002          $data->format             = $courseconfig->format;
3003          $data->newsitems          = $courseconfig->newsitems;
3004          $data->showgrades         = $courseconfig->showgrades;
3005          $data->showreports        = $courseconfig->showreports;
3006          $data->maxbytes           = $courseconfig->maxbytes;
3007          $data->groupmode          = $courseconfig->groupmode;
3008          $data->groupmodeforce     = $courseconfig->groupmodeforce;
3009          $data->visible            = $courseconfig->visible;
3010          $data->visibleold         = $data->visible;
3011          $data->lang               = $courseconfig->lang;
3012          $data->enablecompletion   = $courseconfig->enablecompletion;
3013          $data->numsections        = $courseconfig->numsections;
3014          $data->startdate          = usergetmidnight(time());
3015          if ($courseconfig->courseenddateenabled) {
3016              $data->enddate        = usergetmidnight(time()) + $courseconfig->courseduration;
3017          }
3018  
3019          list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
3020  
3021          $course = create_course($data);
3022          $context = context_course::instance($course->id, MUST_EXIST);
3023  
3024          // add enrol instances
3025          if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3026              if ($manual = enrol_get_plugin('manual')) {
3027                  $manual->add_default_instance($course);
3028              }
3029          }
3030  
3031          // enrol the requester as teacher if necessary
3032          if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3033              enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3034          }
3035  
3036          $this->delete();
3037  
3038          $a = new stdClass();
3039          $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
3040          $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
3041          $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
3042  
3043          return $course->id;
3044      }
3045  
3046      /**
3047       * Reject a course request
3048       *
3049       * This function rejects a course request, emailing the requesting user the
3050       * provided notice and then removing the request from the database
3051       *
3052       * @param string $notice The message to display to the user
3053       */
3054      public function reject($notice) {
3055          global $USER, $DB;
3056          $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
3057          $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3058          $this->delete();
3059      }
3060  
3061      /**
3062       * Deletes the course request and any associated files
3063       */
3064      public function delete() {
3065          global $DB;
3066          $DB->delete_records('course_request', array('id' => $this->properties->id));
3067      }
3068  
3069      /**
3070       * Send a message from one user to another using events_trigger
3071       *
3072       * @param object $touser
3073       * @param object $fromuser
3074       * @param string $name
3075       * @param string $subject
3076       * @param string $message
3077       * @param int|null $courseid
3078       */
3079      protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
3080          $eventdata = new \core\message\message();
3081          $eventdata->courseid          = empty($courseid) ? SITEID : $courseid;
3082          $eventdata->component         = 'moodle';
3083          $eventdata->name              = $name;
3084          $eventdata->userfrom          = $fromuser;
3085          $eventdata->userto            = $touser;
3086          $eventdata->subject           = $subject;
3087          $eventdata->fullmessage       = $message;
3088          $eventdata->fullmessageformat = FORMAT_PLAIN;
3089          $eventdata->fullmessagehtml   = '';
3090          $eventdata->smallmessage      = '';
3091          $eventdata->notification      = 1;
3092          message_send($eventdata);
3093      }
3094  
3095      /**
3096       * Checks if current user can request a course in this context
3097       *
3098       * @param context $context
3099       * @return bool
3100       */
3101      public static function can_request(context $context) {
3102          global $CFG;
3103          if (empty($CFG->enablecourserequests)) {
3104              return false;
3105          }
3106          if (has_capability('moodle/course:create', $context)) {
3107              return false;
3108          }
3109  
3110          if ($context instanceof context_system) {
3111              $defaultcontext = context_coursecat::instance($CFG->defaultrequestcategory, IGNORE_MISSING);
3112              return $defaultcontext &&
3113                  has_capability('moodle/course:request', $defaultcontext);
3114          } else if ($context instanceof context_coursecat) {
3115              if (!$CFG->lockrequestcategory || $CFG->defaultrequestcategory == $context->instanceid) {
3116                  return has_capability('moodle/course:request', $context);
3117              }
3118          }
3119          return false;
3120      }
3121  }
3122  
3123  /**
3124   * Return a list of page types
3125   * @param string $pagetype current page type
3126   * @param context $parentcontext Block's parent context
3127   * @param context $currentcontext Current context of block
3128   * @return array array of page types
3129   */
3130  function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
3131      if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3132          // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3133          $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3134              'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3135          );
3136      } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3137          // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3138          $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3139      } else {
3140          // Otherwise consider it a page inside a course even if $currentcontext is null
3141          $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3142              'course-*' => get_string('page-course-x', 'pagetype'),
3143              'course-view-*' => get_string('page-course-view-x', 'pagetype')
3144          );
3145      }
3146      return $pagetypes;
3147  }
3148  
3149  /**
3150   * Determine whether course ajax should be enabled for the specified course
3151   *
3152   * @param stdClass $course The course to test against
3153   * @return boolean Whether course ajax is enabled or note
3154   */
3155  function course_ajax_enabled($course) {
3156      global $CFG, $PAGE, $SITE;
3157  
3158      // The user must be editing for AJAX to be included
3159      if (!$PAGE->user_is_editing()) {
3160          return false;
3161      }
3162  
3163      // Check that the theme suports
3164      if (!$PAGE->theme->enablecourseajax) {
3165          return false;
3166      }
3167  
3168      // Check that the course format supports ajax functionality
3169      // The site 'format' doesn't have information on course format support
3170      if ($SITE->id !== $course->id) {
3171          $courseformatajaxsupport = course_format_ajax_support($course->format);
3172          if (!$courseformatajaxsupport->capable) {
3173              return false;
3174          }
3175      }
3176  
3177      // All conditions have been met so course ajax should be enabled
3178      return true;
3179  }
3180  
3181  /**
3182   * Include the relevant javascript and language strings for the resource
3183   * toolbox YUI module
3184   *
3185   * @param integer $id The ID of the course being applied to
3186   * @param array $usedmodules An array containing the names of the modules in use on the page
3187   * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
3188   * @param stdClass $config An object containing configuration parameters for ajax modules including:
3189   *          * resourceurl   The URL to post changes to for resource changes
3190   *          * sectionurl    The URL to post changes to for section changes
3191   *          * pageparams    Additional parameters to pass through in the post
3192   * @return bool
3193   */
3194  function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
3195      global $CFG, $PAGE, $SITE;
3196  
3197      // Ensure that ajax should be included
3198      if (!course_ajax_enabled($course)) {
3199          return false;
3200      }
3201  
3202      if (!$config) {
3203          $config = new stdClass();
3204      }
3205  
3206      // The URL to use for resource changes
3207      if (!isset($config->resourceurl)) {
3208          $config->resourceurl = '/course/rest.php';
3209      }
3210  
3211      // The URL to use for section changes
3212      if (!isset($config->sectionurl)) {
3213          $config->sectionurl = '/course/rest.php';
3214      }
3215  
3216      // Any additional parameters which need to be included on page submission
3217      if (!isset($config->pageparams)) {
3218          $config->pageparams = array();
3219      }
3220  
3221      // Include course dragdrop
3222      if (course_format_uses_sections($course->format)) {
3223          $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3224              array(array(
3225                  'courseid' => $course->id,
3226                  'ajaxurl' => $config->sectionurl,
3227                  'config' => $config,
3228              )), null, true);
3229  
3230          $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3231              array(array(
3232                  'courseid' => $course->id,
3233                  'ajaxurl' => $config->resourceurl,
3234                  'config' => $config,
3235              )), null, true);
3236      }
3237  
3238      // Require various strings for the command toolbox
3239      $PAGE->requires->strings_for_js(array(
3240              'moveleft',
3241              'deletechecktype',
3242              'deletechecktypename',
3243              'edittitle',
3244              'edittitleinstructions',
3245              'show',
3246              'hide',
3247              'highlight',
3248              'highlightoff',
3249              'groupsnone',
3250              'groupsvisible',
3251              'groupsseparate',
3252              'clicktochangeinbrackets',
3253              'markthistopic',
3254              'markedthistopic',
3255              'movesection',
3256              'movecoursemodule',
3257              'movecoursesection',
3258              'movecontent',
3259              'tocontent',
3260              'emptydragdropregion',
3261              'afterresource',
3262              'aftersection',
3263              'totopofsection',
3264          ), 'moodle');
3265  
3266      // Include section-specific strings for formats which support sections.
3267      if (course_format_uses_sections($course->format)) {
3268          $PAGE->requires->strings_for_js(array(
3269                  'showfromothers',
3270                  'hidefromothers',
3271              ), 'format_' . $course->format);
3272      }
3273  
3274      // For confirming resource deletion we need the name of the module in question
3275      foreach ($usedmodules as $module => $modname) {
3276          $PAGE->requires->string_for_js('pluginname', $module);
3277      }
3278  
3279      // Load drag and drop upload AJAX.
3280      require_once($CFG->dirroot.'/course/dnduploadlib.php');
3281      dndupload_add_to_course($course, $enabledmodules);
3282  
3283      $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3284  
3285      return true;
3286  }
3287  
3288  /**
3289   * Returns the sorted list of available course formats, filtered by enabled if necessary
3290   *
3291   * @param bool $enabledonly return only formats that are enabled
3292   * @return array array of sorted format names
3293   */
3294  function get_sorted_course_formats($enabledonly = false) {
3295      global $CFG;
3296      $formats = core_component::get_plugin_list('format');
3297  
3298      if (!empty($CFG->format_plugins_sortorder)) {
3299          $order = explode(',', $CFG->format_plugins_sortorder);
3300          $order = array_merge(array_intersect($order, array_keys($formats)),
3301                      array_diff(array_keys($formats), $order));
3302      } else {
3303          $order = array_keys($formats);
3304      }
3305      if (!$enabledonly) {
3306          return $order;
3307      }
3308      $sortedformats = array();
3309      foreach ($order as $formatname) {
3310          if (!get_config('format_'.$formatname, 'disabled')) {
3311              $sortedformats[] = $formatname;
3312          }
3313      }
3314      return $sortedformats;
3315  }
3316  
3317  /**
3318   * The URL to use for the specified course (with section)
3319   *
3320   * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3321   * @param int|stdClass $section Section object from database or just field course_sections.section
3322   *     if omitted the course view page is returned
3323   * @param array $options options for view URL. At the moment core uses:
3324   *     'navigation' (bool) if true and section has no separate page, the function returns null
3325   *     'sr' (int) used by multipage formats to specify to which section to return
3326   * @return moodle_url The url of course
3327   */
3328  function course_get_url($courseorid, $section = null, $options = array()) {
3329      return course_get_format($courseorid)->get_view_url($section, $options);
3330  }
3331  
3332  /**
3333   * Create a module.
3334   *
3335   * It includes:
3336   *      - capability checks and other checks
3337   *      - create the module from the module info
3338   *
3339   * @param object $module
3340   * @return object the created module info
3341   * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3342   */
3343  function create_module($moduleinfo) {
3344      global $DB, $CFG;
3345  
3346      require_once($CFG->dirroot . '/course/modlib.php');
3347  
3348      // Check manadatory attributs.
3349      $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3350      if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3351          $mandatoryfields[] = 'introeditor';
3352      }
3353      foreach($mandatoryfields as $mandatoryfield) {
3354          if (!isset($moduleinfo->{$mandatoryfield})) {
3355              throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3356          }
3357      }
3358  
3359      // Some additional checks (capability / existing instances).
3360      $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3361      list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3362  
3363      // Add the module.
3364      $moduleinfo->module = $module->id;
3365      $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3366  
3367      return $moduleinfo;
3368  }
3369  
3370  /**
3371   * Update a module.
3372   *
3373   * It includes:
3374   *      - capability and other checks
3375   *      - update the module
3376   *
3377   * @param object $module
3378   * @return object the updated module info
3379   * @throws moodle_exception if current user is not allowed to update the module
3380   */
3381  function update_module($moduleinfo) {
3382      global $DB, $CFG;
3383  
3384      require_once($CFG->dirroot . '/course/modlib.php');
3385  
3386      // Check the course module exists.
3387      $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3388  
3389      // Check the course exists.
3390      $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3391  
3392      // Some checks (capaibility / existing instances).
3393      list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3394  
3395      // Retrieve few information needed by update_moduleinfo.
3396      $moduleinfo->modulename = $cm->modname;
3397      if (!isset($moduleinfo->scale)) {
3398          $moduleinfo->scale = 0;
3399      }
3400      $moduleinfo->type = 'mod';
3401  
3402      // Update the module.
3403      list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3404  
3405      return $moduleinfo;
3406  }
3407  
3408  /**
3409   * Duplicate a module on the course for ajax.
3410   *
3411   * @see mod_duplicate_module()
3412   * @param object $course The course
3413   * @param object $cm The course module to duplicate
3414   * @param int $sr The section to link back to (used for creating the links)
3415   * @throws moodle_exception if the plugin doesn't support duplication
3416   * @return Object containing:
3417   * - fullcontent: The HTML markup for the created CM
3418   * - cmid: The CMID of the newly created CM
3419   * - redirect: Whether to trigger a redirect following this change
3420   */
3421  function mod_duplicate_activity($course, $cm, $sr = null) {
3422      global $PAGE;
3423  
3424      $newcm = duplicate_module($course, $cm);
3425  
3426      $resp = new stdClass();
3427      if ($newcm) {
3428          $courserenderer = $PAGE->get_renderer('core', 'course');
3429          $completioninfo = new completion_info($course);
3430          $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3431                  $newcm, null, array());
3432  
3433          $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3434          $resp->cmid = $newcm->id;
3435      } else {
3436          // Trigger a redirect.
3437          $resp->redirect = true;
3438      }
3439      return $resp;
3440  }
3441  
3442  /**
3443   * Api to duplicate a module.
3444   *
3445   * @param object $course course object.
3446   * @param object $cm course module object to be duplicated.
3447   * @since Moodle 2.8
3448   *
3449   * @throws Exception
3450   * @throws coding_exception
3451   * @throws moodle_exception
3452   * @throws restore_controller_exception
3453   *
3454   * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3455   */
3456  function duplicate_module($course, $cm) {
3457      global $CFG, $DB, $USER;
3458      require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3459      require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3460      require_once($CFG->libdir . '/filelib.php');
3461  
3462      $a          = new stdClass();
3463      $a->modtype = get_string('modulename', $cm->modname);
3464      $a->modname = format_string($cm->name);
3465  
3466      if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3467          throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3468      }
3469  
3470      // Backup the activity.
3471  
3472      $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3473              backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3474  
3475      $backupid       = $bc->get_backupid();
3476      $backupbasepath = $bc->get_plan()->get_basepath();
3477  
3478      $bc->execute_plan();
3479  
3480      $bc->destroy();
3481  
3482      // Restore the backup immediately.
3483  
3484      $rc = new restore_controller($backupid, $course->id,
3485              backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3486  
3487      // Make sure that the restore_general_groups setting is always enabled when duplicating an activity.
3488      $plan = $rc->get_plan();
3489      $groupsetting = $plan->get_setting('groups');
3490      if (empty($groupsetting->get_value())) {
3491          $groupsetting->set_value(true);
3492      }
3493  
3494      $cmcontext = context_module::instance($cm->id);
3495      if (!$rc->execute_precheck()) {
3496          $precheckresults = $rc->get_precheck_results();
3497          if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3498              if (empty($CFG->keeptempdirectoriesonbackup)) {
3499                  fulldelete($backupbasepath);
3500              }
3501          }
3502      }
3503  
3504      $rc->execute_plan();
3505  
3506      // Now a bit hacky part follows - we try to get the cmid of the newly
3507      // restored copy of the module.
3508      $newcmid = null;
3509      $tasks = $rc->get_plan()->get_tasks();
3510      foreach ($tasks as $task) {
3511          if (is_subclass_of($task, 'restore_activity_task')) {
3512              if ($task->get_old_contextid() == $cmcontext->id) {
3513                  $newcmid = $task->get_moduleid();
3514                  break;
3515              }
3516          }
3517      }
3518  
3519      $rc->destroy();
3520  
3521      if (empty($CFG->keeptempdirectoriesonbackup)) {
3522          fulldelete($backupbasepath);
3523      }
3524  
3525      // If we know the cmid of the new course module, let us move it
3526      // right below the original one. otherwise it will stay at the
3527      // end of the section.
3528      if ($newcmid) {
3529          // Proceed with activity renaming before everything else. We don't use APIs here to avoid
3530          // triggering a lot of create/update duplicated events.
3531          $newcm = get_coursemodule_from_id($cm->modname, $newcmid, $cm->course);
3532          // Add ' (copy)' to duplicates. Note we don't cleanup or validate lengths here. It comes
3533          // from original name that was valid, so the copy should be too.
3534          $newname = get_string('duplicatedmodule', 'moodle', $newcm->name);
3535          $DB->set_field($cm->modname, 'name', $newname, ['id' => $newcm->instance]);
3536  
3537          $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3538          $modarray = explode(",", trim($section->sequence));
3539          $cmindex = array_search($cm->id, $modarray);
3540          if ($cmindex !== false && $cmindex < count($modarray) - 1) {
3541              moveto_module($newcm, $section, $modarray[$cmindex + 1]);
3542          }
3543  
3544          // Update calendar events with the duplicated module.
3545          // The following line is to be removed in MDL-58906.
3546          course_module_update_calendar_events($newcm->modname, null, $newcm);
3547  
3548          // Trigger course module created event. We can trigger the event only if we know the newcmid.
3549          $newcm = get_fast_modinfo($cm->course)->get_cm($newcmid);
3550          $event = \core\event\course_module_created::create_from_cm($newcm);
3551          $event->trigger();
3552      }
3553  
3554      return isset($newcm) ? $newcm : null;
3555  }
3556  
3557  /**
3558   * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3559   * Sorts by descending order of time.
3560   *
3561   * @param stdClass $a First object
3562   * @param stdClass $b Second object
3563   * @return int 0,1,-1 representing the order
3564   */
3565  function compare_activities_by_time_desc($a, $b) {
3566      // Make sure the activities actually have a timestamp property.
3567      if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3568          return 0;
3569      }
3570      // We treat instances without timestamp as if they have a timestamp of 0.
3571      if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3572          return 1;
3573      }
3574      if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3575          return -1;
3576      }
3577      if ($a->timestamp == $b->timestamp) {
3578          return 0;
3579      }
3580      return ($a->timestamp > $b->timestamp) ? -1 : 1;
3581  }
3582  
3583  /**
3584   * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3585   * Sorts by ascending order of time.
3586   *
3587   * @param stdClass $a First object
3588   * @param stdClass $b Second object
3589   * @return int 0,1,-1 representing the order
3590   */
3591  function compare_activities_by_time_asc($a, $b) {
3592      // Make sure the activities actually have a timestamp property.
3593      if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3594        return 0;
3595      }
3596      // We treat instances without timestamp as if they have a timestamp of 0.
3597      if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3598          return -1;
3599      }
3600      if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3601          return 1;
3602      }
3603      if ($a->timestamp == $b->timestamp) {
3604          return 0;
3605      }
3606      return ($a->timestamp < $b->timestamp) ? -1 : 1;
3607  }
3608  
3609  /**
3610   * Changes the visibility of a course.
3611   *
3612   * @param int $courseid The course to change.
3613   * @param bool $show True to make it visible, false otherwise.
3614   * @return bool
3615   */
3616  function course_change_visibility($courseid, $show = true) {
3617      $course = new stdClass;
3618      $course->id = $courseid;
3619      $course->visible = ($show) ? '1' : '0';
3620      $course->visibleold = $course->visible;
3621      update_course($course);
3622      return true;
3623  }
3624  
3625  /**
3626   * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3627   *
3628   * @param stdClass|core_course_list_element $course
3629   * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3630   * @return bool
3631   */
3632  function course_change_sortorder_by_one($course, $up) {
3633      global $DB;
3634      $params = array($course->sortorder, $course->category);
3635      if ($up) {
3636          $select = 'sortorder < ? AND category = ?';
3637          $sort = 'sortorder DESC';
3638      } else {
3639          $select = 'sortorder > ? AND category = ?';
3640          $sort = 'sortorder ASC';
3641      }
3642      fix_course_sortorder();
3643      $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3644      if ($swapcourse) {
3645          $swapcourse = reset($swapcourse);
3646          $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3647          $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3648          // Finally reorder courses.
3649          fix_course_sortorder();
3650          cache_helper::purge_by_event('changesincourse');
3651          return true;
3652      }
3653      return false;
3654  }
3655  
3656  /**
3657   * Changes the sort order of courses in a category so that the first course appears after the second.
3658   *
3659   * @param int|stdClass $courseorid The course to focus on.
3660   * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3661   * @return bool
3662   */
3663  function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3664      global $DB;
3665  
3666      if (!is_object($courseorid)) {
3667          $course = get_course($courseorid);
3668      } else {
3669          $course = $courseorid;
3670      }
3671  
3672      if ((int)$moveaftercourseid === 0) {
3673          // We've moving the course to the start of the queue.
3674          $sql = 'SELECT sortorder
3675                        FROM {course}
3676                       WHERE category = :categoryid
3677                    ORDER BY sortorder';
3678          $params = array(
3679              'categoryid' => $course->category
3680          );
3681          $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3682  
3683          $sql = 'UPDATE {course}
3684                     SET sortorder = sortorder + 1
3685                   WHERE category = :categoryid
3686                     AND id <> :id';
3687          $params = array(
3688              'categoryid' => $course->category,
3689              'id' => $course->id,
3690          );
3691          $DB->execute($sql, $params);
3692          $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3693      } else if ($course->id === $moveaftercourseid) {
3694          // They're the same - moronic.
3695          debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3696          return false;
3697      } else {
3698          // Moving this course after the given course. It could be before it could be after.
3699          $moveaftercourse = get_course($moveaftercourseid);
3700          if ($course->category !== $moveaftercourse->category) {
3701              debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3702              return false;
3703          }
3704          // Increment all courses in the same category that are ordered after the moveafter course.
3705          // This makes a space for the course we're moving.
3706          $sql = 'UPDATE {course}
3707                         SET sortorder = sortorder + 1
3708                       WHERE category = :categoryid
3709                         AND sortorder > :sortorder';
3710          $params = array(
3711              'categoryid' => $moveaftercourse->category,
3712              'sortorder' => $moveaftercourse->sortorder
3713          );
3714          $DB->execute($sql, $params);
3715          $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3716      }
3717      fix_course_sortorder();
3718      cache_helper::purge_by_event('changesincourse');
3719      return true;
3720  }
3721  
3722  /**
3723   * Trigger course viewed event. This API function is used when course view actions happens,
3724   * usually in course/view.php but also in external functions.
3725   *
3726   * @param stdClass  $context course context object
3727   * @param int $sectionnumber section number
3728   * @since Moodle 2.9
3729   */
3730  function course_view($context, $sectionnumber = 0) {
3731  
3732      $eventdata = array('context' => $context);
3733  
3734      if (!empty($sectionnumber)) {
3735          $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3736      }
3737  
3738      $event = \core\event\course_viewed::create($eventdata);
3739      $event->trigger();
3740  
3741      user_accesstime_log($context->instanceid);
3742  }
3743  
3744  /**
3745   * Returns courses tagged with a specified tag.
3746   *
3747   * @param core_tag_tag $tag
3748   * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3749   *             are displayed on the page and the per-page limit may be bigger
3750   * @param int $fromctx context id where the link was displayed, may be used by callbacks
3751   *            to display items in the same context first
3752   * @param int $ctx context id where to search for records
3753   * @param bool $rec search in subcontexts as well
3754   * @param int $page 0-based number of page being displayed
3755   * @return \core_tag\output\tagindex
3756   */
3757  function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3758      global $CFG, $PAGE;
3759  
3760      $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3761      $displayoptions = array(
3762          'limit' => $perpage,
3763          'offset' => $page * $perpage,
3764          'viewmoreurl' => null,
3765      );
3766  
3767      $courserenderer = $PAGE->get_renderer('core', 'course');
3768      $totalcount = core_course_category::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3769      $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3770      $totalpages = ceil($totalcount / $perpage);
3771  
3772      return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3773              $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3774  }
3775  
3776  /**
3777   * Implements callback inplace_editable() allowing to edit values in-place
3778   *
3779   * @param string $itemtype
3780   * @param int $itemid
3781   * @param mixed $newvalue
3782   * @return \core\output\inplace_editable
3783   */
3784  function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3785      if ($itemtype === 'activityname') {
3786          return \core_course\output\course_module_name::update($itemid, $newvalue);
3787      }
3788  }
3789  
3790  /**
3791   * This function calculates the minimum and maximum cutoff values for the timestart of
3792   * the given event.
3793   *
3794   * It will return an array with two values, the first being the minimum cutoff value and
3795   * the second being the maximum cutoff value. Either or both values can be null, which
3796   * indicates there is no minimum or maximum, respectively.
3797   *
3798   * If a cutoff is required then the function must return an array containing the cutoff
3799   * timestamp and error string to display to the user if the cutoff value is violated.
3800   *
3801   * A minimum and maximum cutoff return value will look like:
3802   * [
3803   *     [1505704373, 'The date must be after this date'],
3804   *     [1506741172, 'The date must be before this date']
3805   * ]
3806   *
3807   * @param calendar_event $event The calendar event to get the time range for
3808   * @param stdClass $course The course object to get the range from
3809   * @return array Returns an array with min and max date.
3810   */
3811  function core_course_core_calendar_get_valid_event_timestart_range(\calendar_event $event, $course) {
3812      $mindate = null;
3813      $maxdate = null;
3814  
3815      if ($course->startdate) {
3816          $mindate = [
3817              $course->startdate,
3818              get_string('errorbeforecoursestart', 'calendar')
3819          ];
3820      }
3821  
3822      return [$mindate, $maxdate];
3823  }
3824  
3825  /**
3826   * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3827   *
3828   * This is a callback used by the tag area core/course_modules to search for course modules
3829   * tagged with a specific tag.
3830   *
3831   * @param core_tag_tag $tag
3832   * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3833   *             are displayed on the page and the per-page limit may be bigger
3834   * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3835   *            to display items in the same context first
3836   * @param int $contextid context id where to search for records
3837   * @param bool $recursivecontext search in subcontexts as well
3838   * @param int $page 0-based number of page being displayed
3839   * @return \core_tag\output\tagindex
3840   */
3841  function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3842                                            $recursivecontext = 1, $page = 0) {
3843      global $OUTPUT;
3844      $perpage = $exclusivemode ? 20 : 5;
3845  
3846      // Build select query.
3847      $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3848      $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3849                  FROM {course_modules} cm
3850                  JOIN {tag_instance} tt ON cm.id = tt.itemid
3851                  JOIN {course} c ON cm.course = c.id
3852                  JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3853                 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3854                  AND cm.deletioninprogress = 0
3855                  AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3856  
3857      $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3858          'coursemodulecontextlevel' => CONTEXT_MODULE);
3859      if ($contextid) {
3860          $context = context::instance_by_id($contextid);
3861          $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3862          $params['contextid'] = $context->id;
3863          $params['path'] = $context->path.'/%';
3864      }
3865  
3866      $query .= ' ORDER BY';
3867      if ($fromcontextid) {
3868          // In order-clause specify that modules from inside "fromctx" context should be returned first.
3869          $fromcontext = context::instance_by_id($fromcontextid);
3870          $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3871          $params['fromcontextid'] = $fromcontext->id;
3872          $params['frompath'] = $fromcontext->path.'/%';
3873      }
3874      $query .= ' c.sortorder, cm.id';
3875      $totalpages = $page + 1;
3876  
3877      // Use core_tag_index_builder to build and filter the list of items.
3878      // Request one item more than we need so we know if next page exists.
3879      $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3880      while ($item = $builder->has_item_that_needs_access_check()) {
3881          context_helper::preload_from_record($item);
3882          $courseid = $item->courseid;
3883          if (!$builder->can_access_course($courseid)) {
3884              $builder->set_accessible($item, false);
3885              continue;
3886          }
3887          $modinfo = get_fast_modinfo($builder->get_course($courseid));
3888          // Set accessibility of this item and all other items in the same course.
3889          $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3890              if ($taggeditem->courseid == $courseid) {
3891                  $cm = $modinfo->get_cm($taggeditem->cmid);
3892                  $builder->set_accessible($taggeditem, $cm->uservisible);
3893              }
3894          });
3895      }
3896  
3897      $items = $builder->get_items();
3898      if (count($items) > $perpage) {
3899          $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3900          array_pop($items);
3901      }
3902  
3903      // Build the display contents.
3904      if ($items) {
3905          $tagfeed = new core_tag\output\tagfeed();
3906          foreach ($items as $item) {
3907              context_helper::preload_from_record($item);
3908              $course = $builder->get_course($item->courseid);
3909              $modinfo = get_fast_modinfo($course);
3910              $cm = $modinfo->get_cm($item->cmid);
3911              $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3912              $cmname = $cm->get_formatted_name();
3913              if (!$exclusivemode) {
3914                  $cmname = shorten_text($cmname, 100);
3915              }
3916              $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3917              $coursename = format_string($course->fullname, true,
3918                      array('context' => context_course::instance($item->courseid)));
3919              $coursename = html_writer::link($courseurl, $coursename);
3920              $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3921              $tagfeed->add($icon, $cmname, $coursename);
3922          }
3923  
3924          $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3925                  $tagfeed->export_for_template($OUTPUT));
3926  
3927          return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3928                  $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3929      }
3930  }
3931  
3932  /**
3933   * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3934   * This function also handles the frontpage course.
3935   *
3936   * @param  stdClass $context context object (it can be a course context or the system context for frontpage settings)
3937   * @param  stdClass $course  the course where the settings are being rendered
3938   * @return stdClass          the navigation options in a course and their availability status
3939   * @since  Moodle 3.2
3940   */
3941  function course_get_user_navigation_options($context, $course = null) {
3942      global $CFG;
3943  
3944      $isloggedin = isloggedin();
3945      $isguestuser = isguestuser();
3946      $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3947  
3948      if ($isfrontpage) {
3949          $sitecontext = $context;
3950      } else {
3951          $sitecontext = context_system::instance();
3952      }
3953  
3954      // Sets defaults for all options.
3955      $options = (object) [
3956          'badges' => false,
3957          'blogs' => false,
3958          'calendar' => false,
3959          'competencies' => false,
3960          'grades' => false,
3961          'notes' => false,
3962          'participants' => false,
3963          'search' => false,
3964          'tags' => false,
3965      ];
3966  
3967      $options->blogs = !empty($CFG->enableblogs) &&
3968                          ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3969                          ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3970                          && has_capability('moodle/blog:view', $sitecontext);
3971  
3972      $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3973  
3974      // Frontpage settings?
3975      if ($isfrontpage) {
3976          // We are on the front page, so make sure we use the proper capability (site:viewparticipants).
3977          $options->participants = course_can_view_participants($sitecontext);
3978          $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3979          $options->tags = !empty($CFG->usetags) && $isloggedin;
3980          $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3981          $options->calendar = $isloggedin;
3982      } else {
3983          // We are in a course, so make sure we use the proper capability (course:viewparticipants).
3984          $options->participants = course_can_view_participants($context);
3985          $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3986                              has_capability('moodle/badges:viewbadges', $context);
3987          // Add view grade report is permitted.
3988          $grades = false;
3989  
3990          if (has_capability('moodle/grade:viewall', $context)) {
3991              $grades = true;
3992          } else if (!empty($course->showgrades)) {
3993              $reports = core_component::get_plugin_list('gradereport');
3994              if (is_array($reports) && count($reports) > 0) {  // Get all installed reports.
3995                  arsort($reports);   // User is last, we want to test it first.
3996                  foreach ($reports as $plugin => $plugindir) {
3997                      if (has_capability('gradereport/'.$plugin.':view', $context)) {
3998                          // Stop when the first visible plugin is found.
3999                          $grades = true;
4000                          break;
4001                      }
4002                  }
4003              }
4004          }
4005          $options->grades = $grades;
4006      }
4007  
4008      if (\core_competency\api::is_enabled()) {
4009          $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
4010          $options->competencies = has_any_capability($capabilities, $context);
4011      }
4012      return $options;
4013  }
4014  
4015  /**
4016   * Return an object with the list of administration options in a course that are available or not for the current user.
4017   * This function also handles the frontpage settings.
4018   *
4019   * @param  stdClass $course  course object (for frontpage it should be a clone of $SITE)
4020   * @param  stdClass $context context object (course context)
4021   * @return stdClass          the administration options in a course and their availability status
4022   * @since  Moodle 3.2
4023   */
4024  function course_get_user_administration_options($course, $context) {
4025      global $CFG;
4026      $isfrontpage = $course->id == SITEID;
4027      $completionenabled = $CFG->enablecompletion && $course->enablecompletion;
4028      $hascompletiontabs = count(core_completion\manager::get_available_completion_tabs($course, $context)) > 0;
4029      $options = new stdClass;
4030      $options->update = has_capability('moodle/course:update', $context);
4031      $options->editcompletion = $CFG->enablecompletion &&
4032                                 $course->enablecompletion &&
4033                                 ($options->update || $hascompletiontabs);
4034      $options->filters = has_capability('moodle/filter:manage', $context) &&
4035                          count(filter_get_available_in_context($context)) > 0;
4036      $options->reports = has_capability('moodle/site:viewreports', $context);
4037      $options->backup = has_capability('moodle/backup:backupcourse', $context);
4038      $options->restore = has_capability('moodle/restore:restorecourse', $context);
4039      $options->copy = \core_course\management\helper::can_copy_course($course->id);
4040      $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
4041  
4042      if (!$isfrontpage) {
4043          $options->tags = has_capability('moodle/course:tag', $context);
4044          $options->gradebook = has_capability('moodle/grade:manage', $context);
4045          $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
4046          $options->badges = !empty($CFG->enablebadges);
4047          $options->import = has_capability('moodle/restore:restoretargetimport', $context);
4048          $options->reset = has_capability('moodle/course:reset', $context);
4049          $options->roles = has_capability('moodle/role:switchroles', $context);
4050      } else {
4051          // Set default options to false.
4052          $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
4053  
4054          foreach ($listofoptions as $option) {
4055              $options->$option = false;
4056          }
4057      }
4058  
4059      return $options;
4060  }
4061  
4062  /**
4063   * Validates course start and end dates.
4064   *
4065   * Checks that the end course date is not greater than the start course date.
4066   *
4067   * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
4068   *
4069   * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
4070   * @return mixed False if everything alright, error codes otherwise.
4071   */
4072  function course_validate_dates($coursedata) {
4073  
4074      // If both start and end dates are set end date should be later than the start date.
4075      if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
4076              ($coursedata['enddate'] < $coursedata['startdate'])) {
4077          return 'enddatebeforestartdate';
4078      }
4079  
4080      // If start date is not set end date can not be set.
4081      if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
4082          return 'nostartdatenoenddate';
4083      }
4084  
4085      return false;
4086  }
4087  
4088  /**
4089   * Check for course updates in the given context level instances (only modules supported right Now)
4090   *
4091   * @param  stdClass $course  course object
4092   * @param  array $tocheck    instances to check for updates
4093   * @param  array $filter check only for updates in these areas
4094   * @return array list of warnings and instances with updates information
4095   * @since  Moodle 3.2
4096   */
4097  function course_check_updates($course, $tocheck, $filter = array()) {
4098      global $CFG, $DB;
4099  
4100      $instances = array();
4101      $warnings = array();
4102      $modulescallbacksupport = array();
4103      $modinfo = get_fast_modinfo($course);
4104  
4105      $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
4106  
4107      // Check instances.
4108      foreach ($tocheck as $instance) {
4109          if ($instance['contextlevel'] == 'module') {
4110              // Check module visibility.
4111              try {
4112                  $cm = $modinfo->get_cm($instance['id']);
4113              } catch (Exception $e) {
4114                  $warnings[] = array(
4115                      'item' => 'module',
4116                      'itemid' => $instance['id'],
4117                      'warningcode' => 'cmidnotincourse',
4118                      'message' => 'This module id does not belong to this course.'
4119                  );
4120                  continue;
4121              }
4122  
4123              if (!$cm->uservisible) {
4124                  $warnings[] = array(
4125                      'item' => 'module',
4126                      'itemid' => $instance['id'],
4127                      'warningcode' => 'nonuservisible',
4128                      'message' => 'You don\'t have access to this module.'
4129                  );
4130                  continue;
4131              }
4132              if (empty($supportedplugins['mod_' . $cm->modname])) {
4133                  $warnings[] = array(
4134                      'item' => 'module',
4135                      'itemid' => $instance['id'],
4136                      'warningcode' => 'missingcallback',
4137                      'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
4138                  );
4139                  continue;
4140              }
4141              // Retrieve the module instance.
4142              $instances[] = array(
4143                  'contextlevel' => $instance['contextlevel'],
4144                  'id' => $instance['id'],
4145                  'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
4146              );
4147  
4148          } else {
4149              $warnings[] = array(
4150                  'item' => 'contextlevel',
4151                  'itemid' => $instance['id'],
4152                  'warningcode' => 'contextlevelnotsupported',
4153                  'message' => 'Context level not yet supported ' . $instance['contextlevel'],
4154              );
4155          }
4156      }
4157      return array($instances, $warnings);
4158  }
4159  
4160  /**
4161   * This function classifies a course as past, in progress or future.
4162   *
4163   * This function may incur a DB hit to calculate course completion.
4164   * @param stdClass $course Course record
4165   * @param stdClass $user User record (optional - defaults to $USER).
4166   * @param completion_info $completioninfo Completion record for the user (optional - will be fetched if required).
4167   * @return string (one of COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_PAST)
4168   */
4169  function course_classify_for_timeline($course, $user = null, $completioninfo = null) {
4170      global $USER;
4171  
4172      if ($user == null) {
4173          $user = $USER;
4174      }
4175  
4176      $today = time();
4177      // End date past.
4178      if (!empty($course->enddate) && (course_classify_end_date($course) < $today)) {
4179          return COURSE_TIMELINE_PAST;
4180      }
4181  
4182      if ($completioninfo == null) {
4183          $completioninfo = new completion_info($course);
4184      }
4185  
4186      // Course was completed.
4187      if ($completioninfo->is_enabled() && $completioninfo->is_course_complete($user->id)) {
4188          return COURSE_TIMELINE_PAST;
4189      }
4190  
4191      // Start date not reached.
4192      if (!empty($course->startdate) && (course_classify_start_date($course) > $today)) {
4193          return COURSE_TIMELINE_FUTURE;
4194      }
4195  
4196      // Everything else is in progress.
4197      return COURSE_TIMELINE_INPROGRESS;
4198  }
4199  
4200  /**
4201   * This function calculates the end date to use for display classification purposes,
4202   * incorporating the grace period, if any.
4203   *
4204   * @param stdClass $course The course record.
4205   * @return int The new enddate.
4206   */
4207  function course_classify_end_date($course) {
4208      global $CFG;
4209      $coursegraceperiodafter = (empty($CFG->coursegraceperiodafter)) ? 0 : $CFG->coursegraceperiodafter;
4210      $enddate = (new \DateTimeImmutable())->setTimestamp($course->enddate)->modify("+{$coursegraceperiodafter} days");
4211      return $enddate->getTimestamp();
4212  }
4213  
4214  /**
4215   * This function calculates the start date to use for display classification purposes,
4216   * incorporating the grace period, if any.
4217   *
4218   * @param stdClass $course The course record.
4219   * @return int The new startdate.
4220   */
4221  function course_classify_start_date($course) {
4222      global $CFG;
4223      $coursegraceperiodbefore = (empty($CFG->coursegraceperiodbefore)) ? 0 : $CFG->coursegraceperiodbefore;
4224      $startdate = (new \DateTimeImmutable())->setTimestamp($course->startdate)->modify("-{$coursegraceperiodbefore} days");
4225      return $startdate->getTimestamp();
4226  }
4227  
4228  /**
4229   * Group a list of courses into either past, future, or in progress.
4230   *
4231   * The return value will be an array indexed by the COURSE_TIMELINE_* constants
4232   * with each value being an array of courses in that group.
4233   * E.g.
4234   * [
4235   *      COURSE_TIMELINE_PAST => [... list of past courses ...],
4236   *      COURSE_TIMELINE_FUTURE => [],
4237   *      COURSE_TIMELINE_INPROGRESS => []
4238   * ]
4239   *
4240   * @param array $courses List of courses to be grouped.
4241   * @return array
4242   */
4243  function course_classify_courses_for_timeline(array $courses) {
4244      return array_reduce($courses, function($carry, $course) {
4245          $classification = course_classify_for_timeline($course);
4246          array_push($carry[$classification], $course);
4247  
4248          return $carry;
4249      }, [
4250          COURSE_TIMELINE_PAST => [],
4251          COURSE_TIMELINE_FUTURE => [],
4252          COURSE_TIMELINE_INPROGRESS => []
4253      ]);
4254  }
4255  
4256  /**
4257   * Get the list of enrolled courses for the current user.
4258   *
4259   * This function returns a Generator. The courses will be loaded from the database
4260   * in chunks rather than a single query.
4261   *
4262   * @param int $limit Restrict result set to this amount
4263   * @param int $offset Skip this number of records from the start of the result set
4264   * @param string|null $sort SQL string for sorting
4265   * @param string|null $fields SQL string for fields to be returned
4266   * @param int $dbquerylimit The number of records to load per DB request
4267   * @param array $includecourses courses ids to be restricted
4268   * @param array $hiddencourses courses ids to be excluded
4269   * @return Generator
4270   */
4271  function course_get_enrolled_courses_for_logged_in_user(
4272      int $limit = 0,
4273      int $offset = 0,
4274      string $sort = null,
4275      string $fields = null,
4276      int $dbquerylimit = COURSE_DB_QUERY_LIMIT,
4277      array $includecourses = [],
4278      array $hiddencourses = []
4279  ) : Generator {
4280  
4281      $haslimit = !empty($limit);
4282      $recordsloaded = 0;
4283      $querylimit = (!$haslimit || $limit > $dbquerylimit) ? $dbquerylimit : $limit;
4284  
4285      while ($courses = enrol_get_my_courses($fields, $sort, $querylimit, $includecourses, false, $offset, $hiddencourses)) {
4286          yield from $courses;
4287  
4288          $recordsloaded += $querylimit;
4289  
4290          if (count($courses) < $querylimit) {
4291              break;
4292          }
4293          if ($haslimit && $recordsloaded >= $limit) {
4294              break;
4295          }
4296  
4297          $offset += $querylimit;
4298      }
4299  }
4300  
4301  /**
4302   * Search the given $courses for any that match the given $classification up to the specified
4303   * $limit.
4304   *
4305   * This function will return the subset of courses that match the classification as well as the
4306   * number of courses it had to process to build that subset.
4307   *
4308   * It is recommended that for larger sets of courses this function is given a Generator that loads
4309   * the courses from the database in chunks.
4310   *
4311   * @param array|Traversable $courses List of courses to process
4312   * @param string $classification One of the COURSE_TIMELINE_* constants
4313   * @param int $limit Limit the number of results to this amount
4314   * @return array First value is the filtered courses, second value is the number of courses processed
4315   */
4316  function course_filter_courses_by_timeline_classification(
4317      $courses,
4318      string $classification,
4319      int $limit = 0
4320  ) : array {
4321  
4322      if (!in_array($classification,
4323              [COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, COURSE_TIMELINE_INPROGRESS,
4324                  COURSE_TIMELINE_FUTURE, COURSE_TIMELINE_HIDDEN])) {
4325          $message = 'Classification must be one of COURSE_TIMELINE_ALLINCLUDINGHIDDEN, COURSE_TIMELINE_ALL, COURSE_TIMELINE_PAST, '
4326              . 'COURSE_TIMELINE_INPROGRESS or COURSE_TIMELINE_FUTURE';
4327          throw new moodle_exception($message);
4328      }
4329  
4330      $filteredcourses = [];
4331      $numberofcoursesprocessed = 0;
4332      $filtermatches = 0;
4333  
4334      foreach ($courses as $course) {
4335          $numberofcoursesprocessed++;
4336          $pref = get_user_preferences('block_myoverview_hidden_course_' . $course->id, 0);
4337  
4338          // Added as of MDL-63457 toggle viewability for each user.
4339          if ($classification == COURSE_TIMELINE_ALLINCLUDINGHIDDEN || ($classification == COURSE_TIMELINE_HIDDEN && $pref) ||
4340              (($classification == COURSE_TIMELINE_ALL || $classification == course_classify_for_timeline($course)) && !$pref)) {
4341              $filteredcourses[] = $course;
4342              $filtermatches++;
4343          }
4344  
4345          if ($limit && $filtermatches >= $limit) {
4346              // We've found the number of requested courses. No need to continue searching.
4347              break;
4348          }
4349      }
4350  
4351      // Return the number of filtered courses as well as the number of courses that were searched
4352      // in order to find the matching courses. This allows the calling code to do some kind of
4353      // pagination.
4354      return [$filteredcourses, $numberofcoursesprocessed];
4355  }
4356  
4357  /**
4358   * Search the given $courses for any that match the given $classification up to the specified
4359   * $limit.
4360   *
4361   * This function will return the subset of courses that are favourites as well as the
4362   * number of courses it had to process to build that subset.
4363   *
4364   * It is recommended that for larger sets of courses this function is given a Generator that loads
4365   * the courses from the database in chunks.
4366   *
4367   * @param array|Traversable $courses List of courses to process
4368   * @param array $favouritecourseids Array of favourite courses.
4369   * @param int $limit Limit the number of results to this amount
4370   * @return array First value is the filtered courses, second value is the number of courses processed
4371   */
4372  function course_filter_courses_by_favourites(
4373      $courses,
4374      $favouritecourseids,
4375      int $limit = 0
4376  ) : array {
4377  
4378      $filteredcourses = [];
4379      $numberofcoursesprocessed = 0;
4380      $filtermatches = 0;
4381  
4382      foreach ($courses as $course) {
4383          $numberofcoursesprocessed++;
4384  
4385          if (in_array($course->id, $favouritecourseids)) {
4386              $filteredcourses[] = $course;
4387              $filtermatches++;
4388          }
4389  
4390          if ($limit && $filtermatches >= $limit) {
4391              // We've found the number of requested courses. No need to continue searching.
4392              break;
4393          }
4394      }
4395  
4396      // Return the number of filtered courses as well as the number of courses that were searched
4397      // in order to find the matching courses. This allows the calling code to do some kind of
4398      // pagination.
4399      return [$filteredcourses, $numberofcoursesprocessed];
4400  }
4401  
4402  /**
4403   * Search the given $courses for any that have a $customfieldname value that matches the given
4404   * $customfieldvalue, up to the specified $limit.
4405   *
4406   * This function will return the subset of courses that matches the value as well as the
4407   * number of courses it had to process to build that subset.
4408   *
4409   * It is recommended that for larger sets of courses this function is given a Generator that loads
4410   * the courses from the database in chunks.
4411   *
4412   * @param array|Traversable $courses List of courses to process
4413   * @param string $customfieldname the shortname of the custom field to match against
4414   * @param string $customfieldvalue the value this custom field needs to match
4415   * @param int $limit Limit the number of results to this amount
4416   * @return array First value is the filtered courses, second value is the number of courses processed
4417   */
4418  function course_filter_courses_by_customfield(
4419      $courses,
4420      $customfieldname,
4421      $customfieldvalue,
4422      int $limit = 0
4423  ) : array {
4424      global $DB;
4425  
4426      if (!$courses) {
4427          return [[], 0];
4428      }
4429  
4430      // Prepare the list of courses to search through.
4431      $coursesbyid = [];
4432      foreach ($courses as $course) {
4433          $coursesbyid[$course->id] = $course;
4434      }
4435      if (!$coursesbyid) {
4436          return [[], 0];
4437      }
4438      list($csql, $params) = $DB->get_in_or_equal(array_keys($coursesbyid), SQL_PARAMS_NAMED);
4439  
4440      // Get the id of the custom field.
4441      $sql = "
4442         SELECT f.id
4443           FROM {customfield_field} f
4444           JOIN {customfield_category} cat ON cat.id = f.categoryid
4445          WHERE f.shortname = ?
4446            AND cat.component = 'core_course'
4447            AND cat.area = 'course'
4448      ";
4449      $fieldid = $DB->get_field_sql($sql, [$customfieldname]);
4450      if (!$fieldid) {
4451          return [[], 0];
4452      }
4453  
4454      // Get a list of courseids that match that custom field value.
4455      if ($customfieldvalue == COURSE_CUSTOMFIELD_EMPTY) {
4456          $comparevalue = $DB->sql_compare_text('cd.value');
4457          $sql = "
4458             SELECT c.id
4459               FROM {course} c
4460          LEFT JOIN {customfield_data} cd ON cd.instanceid = c.id AND cd.fieldid = :fieldid
4461              WHERE c.id $csql
4462                AND (cd.value IS NULL OR $comparevalue = '' OR $comparevalue = '0')
4463          ";
4464          $params['fieldid'] = $fieldid;
4465          $matchcourseids = $DB->get_fieldset_sql($sql, $params);
4466      } else {
4467          $comparevalue = $DB->sql_compare_text('value');
4468          $select = "fieldid = :fieldid AND $comparevalue = :customfieldvalue AND instanceid $csql";
4469          $params['fieldid'] = $fieldid;
4470          $params['customfieldvalue'] = $customfieldvalue;
4471          $matchcourseids = $DB->get_fieldset_select('customfield_data', 'instanceid', $select, $params);
4472      }
4473  
4474      // Prepare the list of courses to return.
4475      $filteredcourses = [];
4476      $numberofcoursesprocessed = 0;
4477      $filtermatches = 0;
4478  
4479      foreach ($coursesbyid as $course) {
4480          $numberofcoursesprocessed++;
4481  
4482          if (in_array($course->id, $matchcourseids)) {
4483              $filteredcourses[] = $course;
4484              $filtermatches++;
4485          }
4486  
4487          if ($limit && $filtermatches >= $limit) {
4488              // We've found the number of requested courses. No need to continue searching.
4489              break;
4490          }
4491      }
4492  
4493      // Return the number of filtered courses as well as the number of courses that were searched
4494      // in order to find the matching courses. This allows the calling code to do some kind of
4495      // pagination.
4496      return [$filteredcourses, $numberofcoursesprocessed];
4497  }
4498  
4499  /**
4500   * Check module updates since a given time.
4501   * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
4502   *
4503   * @param  cm_info $cm        course module data
4504   * @param  int $from          the time to check
4505   * @param  array $fileareas   additional file ares to check
4506   * @param  array $filter      if we need to filter and return only selected updates
4507   * @return stdClass object with the different updates
4508   * @since  Moodle 3.2
4509   */
4510  function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
4511      global $DB, $CFG, $USER;
4512  
4513      $context = $cm->context;
4514      $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
4515  
4516      $updates = new stdClass();
4517      $course = get_course($cm->course);
4518      $component = 'mod_' . $cm->modname;
4519  
4520      // Check changes in the module configuration.
4521      if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
4522          $updates->configuration = (object) array('updated' => false);
4523          if ($updates->configuration->updated = $mod->timemodified > $from) {
4524              $updates->configuration->timeupdated = $mod->timemodified;
4525          }
4526      }
4527  
4528      // Check for updates in files.
4529      if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
4530          $fileareas[] = 'intro';
4531      }
4532      if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
4533          $fs = get_file_storage();
4534          $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
4535          foreach ($fileareas as $filearea) {
4536              $updates->{$filearea . 'files'} = (object) array('updated' => false);
4537          }
4538          foreach ($files as $file) {
4539              $updates->{$file->get_filearea() . 'files'}->updated = true;
4540              $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
4541          }
4542      }
4543  
4544      // Check completion.
4545      $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
4546      $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
4547      if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
4548          $updates->completion = (object) array('updated' => false);
4549          $completion = new completion_info($course);
4550          // Use wholecourse to cache all the modules the first time.
4551          $completiondata = $completion->get_data($cm, true);
4552          if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
4553              $updates->completion->timemodified = $completiondata->timemodified;
4554          }
4555      }
4556  
4557      // Check grades.
4558      $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
4559      $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
4560      if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
4561          require_once($CFG->libdir . '/gradelib.php');
4562          $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
4563  
4564          if (empty($filter) or in_array('gradeitems', $filter)) {
4565              $updates->gradeitems = (object) array('updated' => false);
4566              foreach ($grades->items as $gradeitem) {
4567                  foreach ($gradeitem->grades as $grade) {
4568                      if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4569                          $updates->gradeitems->updated = true;
4570                          $updates->gradeitems->itemids[] = $gradeitem->id;
4571                      }
4572                  }
4573              }
4574          }
4575  
4576          if (empty($filter) or in_array('outcomes', $filter)) {
4577              $updates->outcomes = (object) array('updated' => false);
4578              foreach ($grades->outcomes as $outcome) {
4579                  foreach ($outcome->grades as $grade) {
4580                      if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
4581                          $updates->outcomes->updated = true;
4582                          $updates->outcomes->itemids[] = $outcome->id;
4583                      }
4584                  }
4585              }
4586          }
4587      }
4588  
4589      // Check comments.
4590      if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4591          $updates->comments = (object) array('updated' => false);
4592          require_once($CFG->dirroot . '/comment/lib.php');
4593          require_once($CFG->dirroot . '/comment/locallib.php');
4594          $manager = new comment_manager();
4595          $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4596          if (!empty($comments)) {
4597              $updates->comments->updated = true;
4598              $updates->comments->itemids = array_keys($comments);
4599          }
4600      }
4601  
4602      // Check ratings.
4603      if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4604          $updates->ratings = (object) array('updated' => false);
4605          require_once($CFG->dirroot . '/rating/lib.php');
4606          $manager = new rating_manager();
4607          $ratings = $manager->get_component_ratings_since($context, $component, $from);
4608          if (!empty($ratings)) {
4609              $updates->ratings->updated = true;
4610              $updates->ratings->itemids = array_keys($ratings);
4611          }
4612      }
4613  
4614      return $updates;
4615  }
4616  
4617  /**
4618   * Returns true if the user can view the participant page, false otherwise,
4619   *
4620   * @param context $context The context we are checking.
4621   * @return bool
4622   */
4623  function course_can_view_participants($context) {
4624      $viewparticipantscap = 'moodle/course:viewparticipants';
4625      if ($context->contextlevel == CONTEXT_SYSTEM) {
4626          $viewparticipantscap = 'moodle/site:viewparticipants';
4627      }
4628  
4629      return has_any_capability([$viewparticipantscap, 'moodle/course:enrolreview'], $context);
4630  }
4631  
4632  /**
4633   * Checks if a user can view the participant page, if not throws an exception.
4634   *
4635   * @param context $context The context we are checking.
4636   * @throws required_capability_exception
4637   */
4638  function course_require_view_participants($context) {
4639      if (!course_can_view_participants($context)) {
4640          $viewparticipantscap = 'moodle/course:viewparticipants';
4641          if ($context->contextlevel == CONTEXT_SYSTEM) {
4642              $viewparticipantscap = 'moodle/site:viewparticipants';
4643          }
4644          throw new required_capability_exception($context, $viewparticipantscap, 'nopermissions', '');
4645      }
4646  }
4647  
4648  /**
4649   * Return whether the user can download from the specified backup file area in the given context.
4650   *
4651   * @param string $filearea the backup file area. E.g. 'course', 'backup' or 'automated'.
4652   * @param \context $context
4653   * @param stdClass $user the user object. If not provided, the current user will be checked.
4654   * @return bool true if the user is allowed to download in the context, false otherwise.
4655   */
4656  function can_download_from_backup_filearea($filearea, \context $context, stdClass $user = null) {
4657      $candownload = false;
4658      switch ($filearea) {
4659          case 'course':
4660          case 'backup':
4661              $candownload = has_capability('moodle/backup:downloadfile', $context, $user);
4662              break;
4663          case 'automated':
4664              // Given the automated backups may contain userinfo, we restrict access such that only users who are able to
4665              // restore with userinfo are able to download the file. Users can't create these backups, so checking 'backup:userinfo'
4666              // doesn't make sense here.
4667              $candownload = has_capability('moodle/backup:downloadfile', $context, $user) &&
4668                             has_capability('moodle/restore:userinfo', $context, $user);
4669              break;
4670          default:
4671              break;
4672  
4673      }
4674      return $candownload;
4675  }
4676  
4677  /**
4678   * Get a list of hidden courses
4679   *
4680   * @param int|object|null $user User override to get the filter from. Defaults to current user
4681   * @return array $ids List of hidden courses
4682   * @throws coding_exception
4683   */
4684  function get_hidden_courses_on_timeline($user = null) {
4685      global $USER;
4686  
4687      if (empty($user)) {
4688          $user = $USER->id;
4689      }
4690  
4691      $preferences = get_user_preferences(null, null, $user);
4692      $ids = [];
4693      foreach ($preferences as $key => $value) {
4694          if (preg_match('/block_myoverview_hidden_course_(\d)+/', $key)) {
4695              $id = preg_split('/block_myoverview_hidden_course_/', $key);
4696              $ids[] = $id[1];
4697          }
4698      }
4699  
4700      return $ids;
4701  }
4702  
4703  /**
4704   * Returns a list of the most recently courses accessed by a user
4705   *
4706   * @param int $userid User id from which the courses will be obtained
4707   * @param int $limit Restrict result set to this amount
4708   * @param int $offset Skip this number of records from the start of the result set
4709   * @param string|null $sort SQL string for sorting
4710   * @return array
4711   */
4712  function course_get_recent_courses(int $userid = null, int $limit = 0, int $offset = 0, string $sort = null) {
4713  
4714      global $CFG, $USER, $DB;
4715  
4716      if (empty($userid)) {
4717          $userid = $USER->id;
4718      }
4719  
4720      $basefields = array('id', 'idnumber', 'summary', 'summaryformat', 'startdate', 'enddate', 'category',
4721              'shortname', 'fullname', 'timeaccess', 'component', 'visible');
4722  
4723      if (empty($sort)) {
4724          $sort = 'timeaccess DESC';
4725      } else {
4726          // The SQL string for sorting can define sorting by multiple columns.
4727          $rawsorts = explode(',', $sort);
4728          $sorts = array();
4729          // Validate and trim the sort parameters in the SQL string for sorting.
4730          foreach ($rawsorts as $rawsort) {
4731              $sort = trim($rawsort);
4732              $sortparams = explode(' ', $sort);
4733              // A valid sort statement can not have more than 2 params (ex. 'summary desc' or 'timeaccess').
4734              if (count($sortparams) > 2) {
4735                  throw new invalid_parameter_exception(
4736                      'Invalid structure of the sort parameter, allowed structure: fieldname [ASC|DESC].');
4737              }
4738              $sortfield = trim($sortparams[0]);
4739              // Validate the value which defines the field to sort by.
4740              if (!in_array($sortfield, $basefields)) {
4741                  throw new invalid_parameter_exception('Invalid field in the sort parameter, allowed fields: ' .
4742                      implode(', ', $basefields) . '.');
4743              }
4744              $sortdirection = isset($sortparams[1]) ? trim($sortparams[1]) : '';
4745              // Validate the value which defines the sort direction (if present).
4746              $allowedsortdirections = ['asc', 'desc'];
4747              if (!empty($sortdirection) && !in_array(strtolower($sortdirection), $allowedsortdirections)) {
4748                  throw new invalid_parameter_exception('Invalid sort direction in the sort parameter, allowed values: ' .
4749                      implode(', ', $allowedsortdirections) . '.');
4750              }
4751              $sorts[] = $sort;
4752          }
4753          $sort = implode(',', $sorts);
4754      }
4755  
4756      $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
4757  
4758      $coursefields = 'c.' .join(',', $basefields);
4759  
4760      // Ask the favourites service to give us the join SQL for favourited courses,
4761      // so we can include favourite information in the query.
4762      $usercontext = \context_user::instance($userid);
4763      $favservice = \core_favourites\service_factory::get_service_for_user_context($usercontext);
4764      list($favsql, $favparams) = $favservice->get_join_sql_by_type('core_course', 'courses', 'fav', 'ul.courseid');
4765  
4766      $sql = "SELECT $coursefields, $ctxfields
4767                FROM {course} c
4768                JOIN {context} ctx
4769                     ON ctx.contextlevel = :contextlevel
4770                     AND ctx.instanceid = c.id
4771                JOIN {user_lastaccess} ul
4772                     ON ul.courseid = c.id
4773              $favsql
4774           LEFT JOIN {enrol} eg ON eg.courseid = c.id AND eg.status = :statusenrolg AND eg.enrol = :guestenrol
4775               WHERE ul.userid = :userid
4776                 AND c.visible = :visible
4777                 AND (eg.id IS NOT NULL
4778                      OR EXISTS (SELECT e.id
4779                               FROM {enrol} e
4780                               JOIN {user_enrolments} ue ON ue.enrolid = e.id
4781                              WHERE e.courseid = c.id
4782                                AND e.status = :statusenrol
4783                                AND ue.status = :status
4784                                AND ue.userid = :userid2
4785                                AND ue.timestart < :now1
4786                                AND (ue.timeend = 0 OR ue.timeend > :now2)
4787                            ))
4788            ORDER BY $sort";
4789  
4790      $now = round(time(), -2); // Improves db caching.
4791      $params = ['userid' => $userid, 'contextlevel' => CONTEXT_COURSE, 'visible' => 1, 'status' => ENROL_USER_ACTIVE,
4792                 'statusenrol' => ENROL_INSTANCE_ENABLED, 'guestenrol' => 'guest', 'now1' => $now, 'now2' => $now,
4793                 'userid2' => $userid, 'statusenrolg' => ENROL_INSTANCE_ENABLED] + $favparams;
4794  
4795      $recentcourses = $DB->get_records_sql($sql, $params, $offset, $limit);
4796  
4797      // Filter courses if last access field is hidden.
4798      $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
4799  
4800      if ($userid != $USER->id && isset($hiddenfields['lastaccess'])) {
4801          $recentcourses = array_filter($recentcourses, function($course) {
4802              context_helper::preload_from_record($course);
4803              $context = context_course::instance($course->id, IGNORE_MISSING);
4804              // If last access was a hidden field, a user requesting info about another user would need permission to view hidden
4805              // fields.
4806              return has_capability('moodle/course:viewhiddenuserfields', $context);
4807          });
4808      }
4809  
4810      return $recentcourses;
4811  }
4812  
4813  /**
4814   * Calculate the course start date and offset for the given user ids.
4815   *
4816   * If the course is a fixed date course then the course start date will be returned.
4817   * If the course is a relative date course then the course date will be calculated and
4818   * and offset provided.
4819   *
4820   * The dates are returned as an array with the index being the user id. The array
4821   * contains the start date and start offset values for the user.
4822   *
4823   * If the user is not enrolled in the course then the course start date will be returned.
4824   *
4825   * If we have a course which starts on 1563244000 and 2 users, id 123 and 456, where the
4826   * former is enrolled in the course at 1563244693 and the latter is not enrolled then the
4827   * return value would look like:
4828   * [
4829   *      '123' => [
4830   *          'start' => 1563244693,
4831   *          'startoffset' => 693
4832   *      ],
4833   *      '456' => [
4834   *          'start' => 1563244000,
4835   *          'startoffset' => 0
4836   *      ]
4837   * ]
4838   *
4839   * @param stdClass $course The course to fetch dates for.
4840   * @param array $userids The list of user ids to get dates for.
4841   * @return array
4842   */
4843  function course_get_course_dates_for_user_ids(stdClass $course, array $userids): array {
4844      if (empty($course->relativedatesmode)) {
4845          // This course isn't set to relative dates so we can early return with the course
4846          // start date.
4847          return array_reduce($userids, function($carry, $userid) use ($course) {
4848              $carry[$userid] = [
4849                  'start' => $course->startdate,
4850                  'startoffset' => 0
4851              ];
4852              return $carry;
4853          }, []);
4854      }
4855  
4856      // We're dealing with a relative dates course now so we need to calculate some dates.
4857      $cache = cache::make('core', 'course_user_dates');
4858      $dates = [];
4859      $uncacheduserids = [];
4860  
4861      // Try fetching the values from the cache so that we don't need to do a DB request.
4862      foreach ($userids as $userid) {
4863          $cachekey = "{$course->id}_{$userid}";
4864          $cachedvalue = $cache->get($cachekey);
4865  
4866          if ($cachedvalue === false) {
4867              // Looks like we haven't seen this user for this course before so we'll have
4868              // to fetch it.
4869              $uncacheduserids[] = $userid;
4870          } else {
4871              [$start, $startoffset] = $cachedvalue;
4872              $dates[$userid] = [
4873                  'start' => $start,
4874                  'startoffset' => $startoffset
4875              ];
4876          }
4877      }
4878  
4879      if (!empty($uncacheduserids)) {
4880          // Load the enrolments for any users we haven't seen yet. Set the "onlyactive" param
4881          // to false because it filters out users with enrolment start times in the future which
4882          // we don't want.
4883          $enrolments = enrol_get_course_users($course->id, false, $uncacheduserids);
4884  
4885          foreach ($uncacheduserids as $userid) {
4886              // Find the user enrolment that has the earliest start date.
4887              $enrolment = array_reduce(array_values($enrolments), function($carry, $enrolment) use ($userid) {
4888                  // Only consider enrolments for this user if the user enrolment is active and the
4889                  // enrolment method is enabled.
4890                  if (
4891                      $enrolment->uestatus == ENROL_USER_ACTIVE &&
4892                      $enrolment->estatus == ENROL_INSTANCE_ENABLED &&
4893                      $enrolment->id == $userid
4894                  ) {
4895                      if (is_null($carry)) {
4896                          // Haven't found an enrolment yet for this user so use the one we just found.
4897                          $carry = $enrolment;
4898                      } else {
4899                          // We've already found an enrolment for this user so let's use which ever one
4900                          // has the earliest start time.
4901                          $carry = $carry->uetimestart < $enrolment->uetimestart ? $carry : $enrolment;
4902                      }
4903                  }
4904  
4905                  return $carry;
4906              }, null);
4907  
4908              if ($enrolment) {
4909                  // The course is in relative dates mode so we calculate the student's start
4910                  // date based on their enrolment start date.
4911                  $start = $course->startdate > $enrolment->uetimestart ? $course->startdate : $enrolment->uetimestart;
4912                  $startoffset = $start - $course->startdate;
4913              } else {
4914                  // The user is not enrolled in the course so default back to the course start date.
4915                  $start = $course->startdate;
4916                  $startoffset = 0;
4917              }
4918  
4919              $dates[$userid] = [
4920                  'start' => $start,
4921                  'startoffset' => $startoffset
4922              ];
4923  
4924              $cachekey = "{$course->id}_{$userid}";
4925              $cache->set($cachekey, [$start, $startoffset]);
4926          }
4927      }
4928  
4929      return $dates;
4930  }
4931  
4932  /**
4933   * Calculate the course start date and offset for the given user id.
4934   *
4935   * If the course is a fixed date course then the course start date will be returned.
4936   * If the course is a relative date course then the course date will be calculated and
4937   * and offset provided.
4938   *
4939   * The return array contains the start date and start offset values for the user.
4940   *
4941   * If the user is not enrolled in the course then the course start date will be returned.
4942   *
4943   * If we have a course which starts on 1563244000. If a user's enrolment starts on 1563244693
4944   * then the return would be:
4945   * [
4946   *      'start' => 1563244693,
4947   *      'startoffset' => 693
4948   * ]
4949   *
4950   * If the use was not enrolled then the return would be:
4951   * [
4952   *      'start' => 1563244000,
4953   *      'startoffset' => 0
4954   * ]
4955   *
4956   * @param stdClass $course The course to fetch dates for.
4957   * @param int $userid The user id to get dates for.
4958   * @return array
4959   */
4960  function course_get_course_dates_for_user_id(stdClass $course, int $userid): array {
4961      return (course_get_course_dates_for_user_ids($course, [$userid]))[$userid];
4962  }
4963  
4964  /**
4965   * Renders the course copy form for the modal on the course management screen.
4966   *
4967   * @param array $args
4968   * @return string $o Form HTML.
4969   */
4970  function course_output_fragment_new_base_form($args) {
4971  
4972      $serialiseddata = json_decode($args['jsonformdata'], true);
4973      $formdata = [];
4974      if (!empty($serialiseddata)) {
4975          parse_str($serialiseddata, $formdata);
4976      }
4977  
4978      $context = context_course::instance($args['courseid']);
4979      $copycaps = \core_course\management\helper::get_course_copy_capabilities();
4980      require_all_capabilities($copycaps, $context);
4981  
4982      $course = get_course($args['courseid']);
4983      $mform = new \core_backup\output\copy_form(
4984          null,
4985          array('course' => $course, 'returnto' => '', 'returnurl' => ''),
4986          'post', '', ['class' => 'ignoredirty'], true, $formdata);
4987  
4988      if (!empty($serialiseddata)) {
4989          // If we were passed non-empty form data we want the mform to call validation functions and show errors.
4990          $mform->is_validated();
4991      }
4992  
4993      ob_start();
4994      $mform->display();
4995      $o = ob_get_contents();
4996      ob_end_clean();
4997  
4998      return $o;
4999  }