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