MDL-57268 auth_db: Unit tests for deletion from a large user set
[moodle.git] / course / lib.php
blob22627111e2ec2c91013dc14e23d7692d3a5c3981
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.
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/>.
17 /**
18 * Library of useful functions
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
25 defined('MOODLE_INTERNAL') || die;
27 require_once($CFG->libdir.'/completionlib.php');
28 require_once($CFG->libdir.'/filelib.php');
29 require_once($CFG->dirroot.'/course/format/lib.php');
31 define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
32 define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
34 /**
35 * Number of courses to display when summaries are included.
36 * @var int
37 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41 // Max courses in log dropdown before switching to optional.
42 define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
43 // Max users in log dropdown before switching to optional.
44 define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
45 define('FRONTPAGENEWS', '0');
46 define('FRONTPAGECATEGORYNAMES', '2');
47 define('FRONTPAGECATEGORYCOMBO', '4');
48 define('FRONTPAGEENROLLEDCOURSELIST', '5');
49 define('FRONTPAGEALLCOURSELIST', '6');
50 define('FRONTPAGECOURSESEARCH', '7');
51 // Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
52 define('EXCELROWS', 65535);
53 define('FIRSTUSEDEXCELROW', 3);
55 define('MOD_CLASS_ACTIVITY', 0);
56 define('MOD_CLASS_RESOURCE', 1);
58 function make_log_url($module, $url) {
59 switch ($module) {
60 case 'course':
61 if (strpos($url, 'report/') === 0) {
62 // there is only one report type, course reports are deprecated
63 $url = "/$url";
64 break;
66 case 'file':
67 case 'login':
68 case 'lib':
69 case 'admin':
70 case 'category':
71 case 'mnet course':
72 if (strpos($url, '../') === 0) {
73 $url = ltrim($url, '.');
74 } else {
75 $url = "/course/$url";
77 break;
78 case 'calendar':
79 $url = "/calendar/$url";
80 break;
81 case 'user':
82 case 'blog':
83 $url = "/$module/$url";
84 break;
85 case 'upload':
86 $url = $url;
87 break;
88 case 'coursetags':
89 $url = '/'.$url;
90 break;
91 case 'library':
92 case '':
93 $url = '/';
94 break;
95 case 'message':
96 $url = "/message/$url";
97 break;
98 case 'notes':
99 $url = "/notes/$url";
100 break;
101 case 'tag':
102 $url = "/tag/$url";
103 break;
104 case 'role':
105 $url = '/'.$url;
106 break;
107 case 'grade':
108 $url = "/grade/$url";
109 break;
110 default:
111 $url = "/mod/$module/$url";
112 break;
115 //now let's sanitise urls - there might be some ugly nasties:-(
116 $parts = explode('?', $url);
117 $script = array_shift($parts);
118 if (strpos($script, 'http') === 0) {
119 $script = clean_param($script, PARAM_URL);
120 } else {
121 $script = clean_param($script, PARAM_PATH);
124 $query = '';
125 if ($parts) {
126 $query = implode('', $parts);
127 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
128 $parts = explode('&', $query);
129 $eq = urlencode('=');
130 foreach ($parts as $key=>$part) {
131 $part = urlencode(urldecode($part));
132 $part = str_replace($eq, '=', $part);
133 $parts[$key] = $part;
135 $query = '?'.implode('&amp;', $parts);
138 return $script.$query;
142 function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
143 $modname="", $modid=0, $modaction="", $groupid=0) {
144 global $CFG, $DB;
146 // It is assumed that $date is the GMT time of midnight for that day,
147 // and so the next 86400 seconds worth of logs are printed.
149 /// Setup for group handling.
151 // TODO: I don't understand group/context/etc. enough to be able to do
152 // something interesting with it here
153 // What is the context of a remote course?
155 /// If the group mode is separate, and this user does not have editing privileges,
156 /// then only the user's group can be viewed.
157 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
158 // $groupid = get_current_group($course->id);
160 /// If this course doesn't have groups, no groupid can be specified.
161 //else if (!$course->groupmode) {
162 // $groupid = 0;
165 $groupid = 0;
167 $joins = array();
168 $where = '';
170 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
171 FROM {mnet_log} l
172 LEFT JOIN {user} u ON l.userid = u.id
173 WHERE ";
174 $params = array();
176 $where .= "l.hostid = :hostid";
177 $params['hostid'] = $hostid;
179 // TODO: Is 1 really a magic number referring to the sitename?
180 if ($course != SITEID || $modid != 0) {
181 $where .= " AND l.course=:courseid";
182 $params['courseid'] = $course;
185 if ($modname) {
186 $where .= " AND l.module = :modname";
187 $params['modname'] = $modname;
190 if ('site_errors' === $modid) {
191 $where .= " AND ( l.action='error' OR l.action='infected' )";
192 } else if ($modid) {
193 //TODO: This assumes that modids are the same across sites... probably
194 //not true
195 $where .= " AND l.cmid = :modid";
196 $params['modid'] = $modid;
199 if ($modaction) {
200 $firstletter = substr($modaction, 0, 1);
201 if ($firstletter == '-') {
202 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
203 $params['modaction'] = '%'.substr($modaction, 1).'%';
204 } else {
205 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
206 $params['modaction'] = '%'.$modaction.'%';
210 if ($user) {
211 $where .= " AND l.userid = :user";
212 $params['user'] = $user;
215 if ($date) {
216 $enddate = $date + 86400;
217 $where .= " AND l.time > :date AND l.time < :enddate";
218 $params['date'] = $date;
219 $params['enddate'] = $enddate;
222 $result = array();
223 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
224 if(!empty($result['totalcount'])) {
225 $where .= " ORDER BY $order";
226 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
227 } else {
228 $result['logs'] = array();
230 return $result;
234 * Checks the integrity of the course data.
236 * In summary - compares course_sections.sequence and course_modules.section.
238 * More detailed, checks that:
239 * - course_sections.sequence contains each module id not more than once in the course
240 * - for each moduleid from course_sections.sequence the field course_modules.section
241 * refers to the same section id (this means course_sections.sequence is more
242 * important if they are different)
243 * - ($fullcheck only) each module in the course is present in one of
244 * course_sections.sequence
245 * - ($fullcheck only) removes non-existing course modules from section sequences
247 * If there are any mismatches, the changes are made and records are updated in DB.
249 * Course cache is NOT rebuilt if there are any errors!
251 * This function is used each time when course cache is being rebuilt with $fullcheck = false
252 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
254 * @param int $courseid id of the course
255 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
256 * the list of enabled course modules in the course. Retrieved from DB if not specified.
257 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
258 * @param array $sections records from course_sections table for this course.
259 * Retrieved from DB if not specified
260 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
261 * course modules from sequences. Only to be used in site maintenance mode when we are
262 * sure that another user is not in the middle of the process of moving/removing a module.
263 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
264 * @return array array of messages with found problems. Empty output means everything is ok
266 function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
267 global $DB;
268 $messages = array();
269 if ($sections === null) {
270 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
272 if ($fullcheck) {
273 // Retrieve all records from course_modules regardless of module type visibility.
274 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
276 if ($rawmods === null) {
277 $rawmods = get_course_mods($courseid);
279 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
280 // If either of the arrays is empty, no modules are displayed anyway.
281 return true;
283 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
285 // First make sure that each module id appears in section sequences only once.
286 // If it appears in several section sequences the last section wins.
287 // If it appears twice in one section sequence, the first occurence wins.
288 $modsection = array();
289 foreach ($sections as $sectionid => $section) {
290 $sections[$sectionid]->newsequence = $section->sequence;
291 if (!empty($section->sequence)) {
292 $sequence = explode(",", $section->sequence);
293 $sequenceunique = array_unique($sequence);
294 if (count($sequenceunique) != count($sequence)) {
295 // Some course module id appears in this section sequence more than once.
296 ksort($sequenceunique); // Preserve initial order of modules.
297 $sequence = array_values($sequenceunique);
298 $sections[$sectionid]->newsequence = join(',', $sequence);
299 $messages[] = $debuggingprefix.'Sequence for course section ['.
300 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
302 foreach ($sequence as $cmid) {
303 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
304 // Some course module id appears to be in more than one section's sequences.
305 $wrongsectionid = $modsection[$cmid];
306 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
307 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
308 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
310 $modsection[$cmid] = $sectionid;
315 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
316 if ($fullcheck) {
317 foreach ($rawmods as $cmid => $mod) {
318 if (!isset($modsection[$cmid])) {
319 // This is a module that is not mentioned in course_section.sequence at all.
320 // Add it to the section $mod->section or to the last available section.
321 if ($mod->section && isset($sections[$mod->section])) {
322 $modsection[$cmid] = $mod->section;
323 } else {
324 $firstsection = reset($sections);
325 $modsection[$cmid] = $firstsection->id;
327 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
328 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
329 $modsection[$cmid].']';
332 foreach ($modsection as $cmid => $sectionid) {
333 if (!isset($rawmods[$cmid])) {
334 // Section $sectionid refers to module id that does not exist.
335 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
336 $messages[] = $debuggingprefix.'Course module ['.$cmid.
337 '] does not exist but is present in the sequence of section ['.$sectionid.']';
342 // Update changed sections.
343 if (!$checkonly && !empty($messages)) {
344 foreach ($sections as $sectionid => $section) {
345 if ($section->newsequence !== $section->sequence) {
346 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
351 // Now make sure that all modules point to the correct sections.
352 foreach ($rawmods as $cmid => $mod) {
353 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
354 if (!$checkonly) {
355 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
357 $messages[] = $debuggingprefix.'Course module ['.$cmid.
358 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
362 return $messages;
366 * For a given course, returns an array of course activity objects
367 * Each item in the array contains he following properties:
369 function get_array_of_activities($courseid) {
370 // cm - course module id
371 // mod - name of the module (eg forum)
372 // section - the number of the section (eg week or topic)
373 // name - the name of the instance
374 // visible - is the instance visible or not
375 // groupingid - grouping id
376 // extra - contains extra string to include in any link
377 global $CFG, $DB;
379 $course = $DB->get_record('course', array('id'=>$courseid));
381 if (empty($course)) {
382 throw new moodle_exception('courseidnotfound');
385 $mod = array();
387 $rawmods = get_course_mods($courseid);
388 if (empty($rawmods)) {
389 return $mod; // always return array
392 if ($sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence')) {
393 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
394 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
395 debugging(join('<br>', $errormessages));
396 $rawmods = get_course_mods($courseid);
397 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section ASC', 'id,section,sequence');
399 // Build array of activities.
400 foreach ($sections as $section) {
401 if (!empty($section->sequence)) {
402 $sequence = explode(",", $section->sequence);
403 foreach ($sequence as $seq) {
404 if (empty($rawmods[$seq])) {
405 continue;
407 $mod[$seq] = new stdClass();
408 $mod[$seq]->id = $rawmods[$seq]->instance;
409 $mod[$seq]->cm = $rawmods[$seq]->id;
410 $mod[$seq]->mod = $rawmods[$seq]->modname;
412 // Oh dear. Inconsistent names left here for backward compatibility.
413 $mod[$seq]->section = $section->section;
414 $mod[$seq]->sectionid = $rawmods[$seq]->section;
416 $mod[$seq]->module = $rawmods[$seq]->module;
417 $mod[$seq]->added = $rawmods[$seq]->added;
418 $mod[$seq]->score = $rawmods[$seq]->score;
419 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
420 $mod[$seq]->visible = $rawmods[$seq]->visible;
421 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
422 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
423 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
424 $mod[$seq]->indent = $rawmods[$seq]->indent;
425 $mod[$seq]->completion = $rawmods[$seq]->completion;
426 $mod[$seq]->extra = "";
427 $mod[$seq]->completiongradeitemnumber =
428 $rawmods[$seq]->completiongradeitemnumber;
429 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
430 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
431 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
432 $mod[$seq]->availability = $rawmods[$seq]->availability;
433 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
435 $modname = $mod[$seq]->mod;
436 $functionname = $modname."_get_coursemodule_info";
438 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
439 continue;
442 include_once("$CFG->dirroot/mod/$modname/lib.php");
444 if ($hasfunction = function_exists($functionname)) {
445 if ($info = $functionname($rawmods[$seq])) {
446 if (!empty($info->icon)) {
447 $mod[$seq]->icon = $info->icon;
449 if (!empty($info->iconcomponent)) {
450 $mod[$seq]->iconcomponent = $info->iconcomponent;
452 if (!empty($info->name)) {
453 $mod[$seq]->name = $info->name;
455 if ($info instanceof cached_cm_info) {
456 // When using cached_cm_info you can include three new fields
457 // that aren't available for legacy code
458 if (!empty($info->content)) {
459 $mod[$seq]->content = $info->content;
461 if (!empty($info->extraclasses)) {
462 $mod[$seq]->extraclasses = $info->extraclasses;
464 if (!empty($info->iconurl)) {
465 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
466 $url = new moodle_url($info->iconurl);
467 $mod[$seq]->iconurl = $url->out(false);
469 if (!empty($info->onclick)) {
470 $mod[$seq]->onclick = $info->onclick;
472 if (!empty($info->customdata)) {
473 $mod[$seq]->customdata = $info->customdata;
475 } else {
476 // When using a stdclass, the (horrible) deprecated ->extra field
477 // is available for BC
478 if (!empty($info->extra)) {
479 $mod[$seq]->extra = $info->extra;
484 // When there is no modname_get_coursemodule_info function,
485 // but showdescriptions is enabled, then we use the 'intro'
486 // and 'introformat' fields in the module table
487 if (!$hasfunction && $rawmods[$seq]->showdescription) {
488 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
489 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
490 // Set content from intro and introformat. Filters are disabled
491 // because we filter it with format_text at display time
492 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
493 $modvalues, $rawmods[$seq]->id, false);
495 // To save making another query just below, put name in here
496 $mod[$seq]->name = $modvalues->name;
499 if (!isset($mod[$seq]->name)) {
500 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
503 // Minimise the database size by unsetting default options when they are
504 // 'empty'. This list corresponds to code in the cm_info constructor.
505 foreach (array('idnumber', 'groupmode', 'groupingid',
506 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
507 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
508 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
509 if (property_exists($mod[$seq], $property) &&
510 empty($mod[$seq]->{$property})) {
511 unset($mod[$seq]->{$property});
514 // Special case: this value is usually set to null, but may be 0
515 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
516 is_null($mod[$seq]->completiongradeitemnumber)) {
517 unset($mod[$seq]->completiongradeitemnumber);
523 return $mod;
527 * Returns the localised human-readable names of all used modules
529 * @param bool $plural if true returns the plural forms of the names
530 * @return array where key is the module name (component name without 'mod_') and
531 * the value is the human-readable string. Array sorted alphabetically by value
533 function get_module_types_names($plural = false) {
534 static $modnames = null;
535 global $DB, $CFG;
536 if ($modnames === null) {
537 $modnames = array(0 => array(), 1 => array());
538 if ($allmods = $DB->get_records("modules")) {
539 foreach ($allmods as $mod) {
540 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
541 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
542 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
545 core_collator::asort($modnames[0]);
546 core_collator::asort($modnames[1]);
549 return $modnames[(int)$plural];
553 * Set highlighted section. Only one section can be highlighted at the time.
555 * @param int $courseid course id
556 * @param int $marker highlight section with this number, 0 means remove higlightin
557 * @return void
559 function course_set_marker($courseid, $marker) {
560 global $DB;
561 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
562 format_base::reset_course_cache($courseid);
566 * For a given course section, marks it visible or hidden,
567 * and does the same for every activity in that section
569 * @param int $courseid course id
570 * @param int $sectionnumber The section number to adjust
571 * @param int $visibility The new visibility
572 * @return array A list of resources which were hidden in the section
574 function set_section_visible($courseid, $sectionnumber, $visibility) {
575 global $DB;
577 $resourcestotoggle = array();
578 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
579 course_update_section($courseid, $section, array('visible' => $visibility));
581 // Determine which modules are visible for AJAX update
582 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
583 if (!empty($modules)) {
584 list($insql, $params) = $DB->get_in_or_equal($modules);
585 $select = 'id ' . $insql . ' AND visible = ?';
586 array_push($params, $visibility);
587 if (!$visibility) {
588 $select .= ' AND visibleold = 1';
590 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
593 return $resourcestotoggle;
597 * Retrieve all metadata for the requested modules
599 * @param object $course The Course
600 * @param array $modnames An array containing the list of modules and their
601 * names
602 * @param int $sectionreturn The section to return to
603 * @return array A list of stdClass objects containing metadata about each
604 * module
606 function get_module_metadata($course, $modnames, $sectionreturn = null) {
607 global $OUTPUT;
609 // get_module_metadata will be called once per section on the page and courses may show
610 // different modules to one another
611 static $modlist = array();
612 if (!isset($modlist[$course->id])) {
613 $modlist[$course->id] = array();
616 $return = array();
617 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
618 if ($sectionreturn !== null) {
619 $urlbase->param('sr', $sectionreturn);
621 foreach($modnames as $modname => $modnamestr) {
622 if (!course_allowed_module($course, $modname)) {
623 continue;
625 if (isset($modlist[$course->id][$modname])) {
626 // This module is already cached
627 $return += $modlist[$course->id][$modname];
628 continue;
630 $modlist[$course->id][$modname] = array();
632 // Create an object for a default representation of this module type in the activity chooser. It will be used
633 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
634 $defaultmodule = new stdClass();
635 $defaultmodule->title = $modnamestr;
636 $defaultmodule->name = $modname;
637 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
638 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
639 $sm = get_string_manager();
640 if ($sm->string_exists('modulename_help', $modname)) {
641 $defaultmodule->help = get_string('modulename_help', $modname);
642 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
643 $link = get_string('modulename_link', $modname);
644 $linktext = get_string('morehelp');
645 $defaultmodule->help .= html_writer::tag('div',
646 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
649 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
651 // Legacy support for callback get_types() - do not use any more, use get_shortcuts() instead!
652 $typescallbackexists = component_callback_exists($modname, 'get_types');
654 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
655 // of elements to be added to activity chooser.
656 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
657 if ($items !== null) {
658 foreach ($items as $item) {
659 // Add all items to the return array. All items must have different links, use them as a key in the return array.
660 if (!isset($item->archetype)) {
661 $item->archetype = $defaultmodule->archetype;
663 if (!isset($item->icon)) {
664 $item->icon = $defaultmodule->icon;
666 // If plugin returned the only one item with the same link as default item - cache it as $modname,
667 // otherwise append the link url to the module name.
668 $item->name = (count($items) == 1 &&
669 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
671 // If the module provides the helptext property, append it to the help text to match the look and feel
672 // of the default course modules.
673 if (isset($item->help) && isset($item->helplink)) {
674 $linktext = get_string('morehelp');
675 $item->help .= html_writer::tag('div',
676 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
678 $modlist[$course->id][$modname][$item->name] = $item;
680 $return += $modlist[$course->id][$modname];
681 if ($typescallbackexists) {
682 debugging('Both callbacks get_shortcuts() and get_types() are found in module ' . $modname .
683 '. Callback get_types() will be completely ignored', DEBUG_DEVELOPER);
685 // If get_shortcuts() callback is defined, the default module action is not added.
686 // It is a responsibility of the callback to add it to the return value unless it is not needed.
687 continue;
690 if ($typescallbackexists) {
691 debugging('Callback get_types() is found in module ' . $modname . ', this functionality is deprecated, ' .
692 'please use callback get_shortcuts() instead', DEBUG_DEVELOPER);
694 $types = component_callback($modname, 'get_types', array(), MOD_SUBTYPE_NO_CHILDREN);
695 if ($types !== MOD_SUBTYPE_NO_CHILDREN) {
696 // Legacy support for deprecated callback get_types(). To be removed in Moodle 3.5. TODO MDL-53697.
697 if (is_array($types) && count($types) > 0) {
698 $grouptitle = $modnamestr;
699 $icon = $OUTPUT->pix_icon('icon', '', $modname, array('class' => 'icon'));
700 foreach($types as $type) {
701 if ($type->typestr === '--') {
702 continue;
704 if (strpos($type->typestr, '--') === 0) {
705 $grouptitle = str_replace('--', '', $type->typestr);
706 continue;
708 // Set the Sub Type metadata.
709 $subtype = new stdClass();
710 $subtype->title = get_string('activitytypetitle', '',
711 (object)['activity' => $grouptitle, 'type' => $type->typestr]);
712 $subtype->type = str_replace('&amp;', '&', $type->type);
713 $typename = preg_replace('/.*type=/', '', $subtype->type);
714 $subtype->archetype = $type->modclass;
716 if (!empty($type->help)) {
717 $subtype->help = $type->help;
718 } else if (get_string_manager()->string_exists('help' . $subtype->name, $modname)) {
719 $subtype->help = get_string('help' . $subtype->name, $modname);
721 $subtype->link = new moodle_url($urlbase, array('add' => $modname, 'type' => $typename));
722 $subtype->name = $modname . ':' . $subtype->link;
723 $subtype->icon = $icon;
724 $modlist[$course->id][$modname][$subtype->name] = $subtype;
726 $return += $modlist[$course->id][$modname];
728 } else {
729 // Neither get_shortcuts() nor get_types() callbacks found, use the default item for the activity chooser.
730 $modlist[$course->id][$modname][$modname] = $defaultmodule;
731 $return[$modname] = $defaultmodule;
735 core_collator::asort_objects_by_property($return, 'title');
736 return $return;
740 * Return the course category context for the category with id $categoryid, except
741 * that if $categoryid is 0, return the system context.
743 * @param integer $categoryid a category id or 0.
744 * @return context the corresponding context
746 function get_category_or_system_context($categoryid) {
747 if ($categoryid) {
748 return context_coursecat::instance($categoryid, IGNORE_MISSING);
749 } else {
750 return context_system::instance();
755 * Returns full course categories trees to be used in html_writer::select()
757 * Calls {@link coursecat::make_categories_list()} to build the tree and
758 * adds whitespace to denote nesting
760 * @return array array mapping coursecat id to the display name
762 function make_categories_options() {
763 global $CFG;
764 require_once($CFG->libdir. '/coursecatlib.php');
765 $cats = coursecat::make_categories_list('', 0, ' / ');
766 foreach ($cats as $key => $value) {
767 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
768 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
770 return $cats;
774 * Print the buttons relating to course requests.
776 * @param object $context current page context.
778 function print_course_request_buttons($context) {
779 global $CFG, $DB, $OUTPUT;
780 if (empty($CFG->enablecourserequests)) {
781 return;
783 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
784 /// Print a button to request a new course
785 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
787 /// Print a button to manage pending requests
788 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
789 $disabled = !$DB->record_exists('course_request', array());
790 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
795 * Does the user have permission to edit things in this category?
797 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
798 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
800 function can_edit_in_category($categoryid = 0) {
801 $context = get_category_or_system_context($categoryid);
802 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
805 /// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
807 function add_course_module($mod) {
808 global $DB;
810 $mod->added = time();
811 unset($mod->id);
813 $cmid = $DB->insert_record("course_modules", $mod);
814 rebuild_course_cache($mod->course, true);
815 return $cmid;
819 * Creates missing course section(s) and rebuilds course cache
821 * @param int|stdClass $courseorid course id or course object
822 * @param int|array $sections list of relative section numbers to create
823 * @return bool if there were any sections created
825 function course_create_sections_if_missing($courseorid, $sections) {
826 global $DB;
827 if (!is_array($sections)) {
828 $sections = array($sections);
830 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
831 if (is_object($courseorid)) {
832 $courseorid = $courseorid->id;
834 $coursechanged = false;
835 foreach ($sections as $sectionnum) {
836 if (!in_array($sectionnum, $existing)) {
837 $cw = new stdClass();
838 $cw->course = $courseorid;
839 $cw->section = $sectionnum;
840 $cw->summary = '';
841 $cw->summaryformat = FORMAT_HTML;
842 $cw->sequence = '';
843 $id = $DB->insert_record("course_sections", $cw);
844 $coursechanged = true;
847 if ($coursechanged) {
848 rebuild_course_cache($courseorid, true);
850 return $coursechanged;
854 * Adds an existing module to the section
856 * Updates both tables {course_sections} and {course_modules}
858 * Note: This function does not use modinfo PROVIDED that the section you are
859 * adding the module to already exists. If the section does not exist, it will
860 * build modinfo if necessary and create the section.
862 * @param int|stdClass $courseorid course id or course object
863 * @param int $cmid id of the module already existing in course_modules table
864 * @param int $sectionnum relative number of the section (field course_sections.section)
865 * If section does not exist it will be created
866 * @param int|stdClass $beforemod id or object with field id corresponding to the module
867 * before which the module needs to be included. Null for inserting in the
868 * end of the section
869 * @return int The course_sections ID where the module is inserted
871 function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
872 global $DB, $COURSE;
873 if (is_object($beforemod)) {
874 $beforemod = $beforemod->id;
876 if (is_object($courseorid)) {
877 $courseid = $courseorid->id;
878 } else {
879 $courseid = $courseorid;
881 // Do not try to use modinfo here, there is no guarantee it is valid!
882 $section = $DB->get_record('course_sections',
883 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
884 if (!$section) {
885 // This function call requires modinfo.
886 course_create_sections_if_missing($courseorid, $sectionnum);
887 $section = $DB->get_record('course_sections',
888 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
891 $modarray = explode(",", trim($section->sequence));
892 if (empty($section->sequence)) {
893 $newsequence = "$cmid";
894 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
895 $insertarray = array($cmid, $beforemod);
896 array_splice($modarray, $key[0], 1, $insertarray);
897 $newsequence = implode(",", $modarray);
898 } else {
899 $newsequence = "$section->sequence,$cmid";
901 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
902 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
903 if (is_object($courseorid)) {
904 rebuild_course_cache($courseorid->id, true);
905 } else {
906 rebuild_course_cache($courseorid, true);
908 return $section->id; // Return course_sections ID that was used.
912 * Change the group mode of a course module.
914 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
915 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
917 * @param int $id course module ID.
918 * @param int $groupmode the new groupmode value.
919 * @return bool True if the $groupmode was updated.
921 function set_coursemodule_groupmode($id, $groupmode) {
922 global $DB;
923 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
924 if ($cm->groupmode != $groupmode) {
925 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
926 rebuild_course_cache($cm->course, true);
928 return ($cm->groupmode != $groupmode);
931 function set_coursemodule_idnumber($id, $idnumber) {
932 global $DB;
933 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
934 if ($cm->idnumber != $idnumber) {
935 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
936 rebuild_course_cache($cm->course, true);
938 return ($cm->idnumber != $idnumber);
942 * Set the visibility of a module and inherent properties.
944 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
945 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
947 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
948 * has been moved to {@link set_section_visible()} which was the only place from which
949 * the parameter was used.
951 * @param int $id of the module
952 * @param int $visible state of the module
953 * @return bool false when the module was not found, true otherwise
955 function set_coursemodule_visible($id, $visible) {
956 global $DB, $CFG;
957 require_once($CFG->libdir.'/gradelib.php');
958 require_once($CFG->dirroot.'/calendar/lib.php');
960 // Trigger developer's attention when using the previously removed argument.
961 if (func_num_args() > 2) {
962 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
963 has been removed.', DEBUG_DEVELOPER);
966 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
967 return false;
970 // Create events and propagate visibility to associated grade items if the value has changed.
971 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
972 if ($cm->visible == $visible) {
973 return true;
976 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
977 return false;
979 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
980 foreach($events as $event) {
981 if ($visible) {
982 $event = new calendar_event($event);
983 $event->toggle_visibility(true);
984 } else {
985 $event = new calendar_event($event);
986 $event->toggle_visibility(false);
991 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
992 // affect visibleold to allow for an original visibility restore. See set_section_visible().
993 $cminfo = new stdClass();
994 $cminfo->id = $id;
995 $cminfo->visible = $visible;
996 $cminfo->visibleold = $visible;
997 $DB->update_record('course_modules', $cminfo);
999 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1000 // Note that this must be done after updating the row in course_modules, in case
1001 // the modules grade_item_update function needs to access $cm->visible.
1002 if (plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1003 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1004 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1005 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
1006 } else {
1007 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1008 if ($grade_items) {
1009 foreach ($grade_items as $grade_item) {
1010 $grade_item->set_hidden(!$visible);
1015 rebuild_course_cache($cm->course, true);
1016 return true;
1020 * Changes the course module name
1022 * @param int $id course module id
1023 * @param string $name new value for a name
1024 * @return bool whether a change was made
1026 function set_coursemodule_name($id, $name) {
1027 global $CFG, $DB;
1028 require_once($CFG->libdir . '/gradelib.php');
1030 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1032 $module = new \stdClass();
1033 $module->id = $cm->instance;
1035 // Escape strings as they would be by mform.
1036 if (!empty($CFG->formatstringstriptags)) {
1037 $module->name = clean_param($name, PARAM_TEXT);
1038 } else {
1039 $module->name = clean_param($name, PARAM_CLEANHTML);
1041 if ($module->name === $cm->name || strval($module->name) === '') {
1042 return false;
1044 if (\core_text::strlen($module->name) > 255) {
1045 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1048 $module->timemodified = time();
1049 $DB->update_record($cm->modname, $module);
1050 $cm->name = $module->name;
1051 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1052 rebuild_course_cache($cm->course, true);
1054 // Attempt to update the grade item if relevant.
1055 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1056 $grademodule->cmidnumber = $cm->idnumber;
1057 $grademodule->modname = $cm->modname;
1058 grade_update_mod_grades($grademodule);
1060 // Update calendar events with the new name.
1061 $refresheventsfunction = $cm->modname . '_refresh_events';
1062 if (function_exists($refresheventsfunction)) {
1063 call_user_func($refresheventsfunction, $cm->course);
1066 return true;
1070 * This function will handle the whole deletion process of a module. This includes calling
1071 * the modules delete_instance function, deleting files, events, grades, conditional data,
1072 * the data in the course_module and course_sections table and adding a module deletion
1073 * event to the DB.
1075 * @param int $cmid the course module id
1076 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1077 * @throws moodle_exception
1078 * @since Moodle 2.5
1080 function course_delete_module($cmid, $async = false) {
1081 // Check the 'course_module_background_deletion_recommended' hook first.
1082 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1083 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1084 // It's up to plugins to handle things like whether or not they are enabled.
1085 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1086 foreach ($pluginsfunction as $plugintype => $plugins) {
1087 foreach ($plugins as $pluginfunction) {
1088 if ($pluginfunction()) {
1089 return course_module_flag_for_async_deletion($cmid);
1095 global $CFG, $DB;
1097 require_once($CFG->libdir.'/gradelib.php');
1098 require_once($CFG->libdir.'/questionlib.php');
1099 require_once($CFG->dirroot.'/blog/lib.php');
1100 require_once($CFG->dirroot.'/calendar/lib.php');
1102 // Get the course module.
1103 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1104 return true;
1107 // Get the module context.
1108 $modcontext = context_module::instance($cm->id);
1110 // Get the course module name.
1111 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1113 // Get the file location of the delete_instance function for this module.
1114 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1116 // Include the file required to call the delete_instance function for this module.
1117 if (file_exists($modlib)) {
1118 require_once($modlib);
1119 } else {
1120 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1121 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1124 $deleteinstancefunction = $modulename . '_delete_instance';
1126 // Ensure the delete_instance function exists for this module.
1127 if (!function_exists($deleteinstancefunction)) {
1128 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1129 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1132 // Allow plugins to use this course module before we completely delete it.
1133 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1134 foreach ($pluginsfunction as $plugintype => $plugins) {
1135 foreach ($plugins as $pluginfunction) {
1136 $pluginfunction($cm);
1141 // Delete activity context questions and question categories.
1142 question_delete_activity($cm);
1144 // Call the delete_instance function, if it returns false throw an exception.
1145 if (!$deleteinstancefunction($cm->instance)) {
1146 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1147 "Cannot delete the module $modulename (instance).");
1150 // Remove all module files in case modules forget to do that.
1151 $fs = get_file_storage();
1152 $fs->delete_area_files($modcontext->id);
1154 // Delete events from calendar.
1155 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
1156 foreach($events as $event) {
1157 $calendarevent = calendar_event::load($event->id);
1158 $calendarevent->delete();
1162 // Delete grade items, outcome items and grades attached to modules.
1163 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1164 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
1165 foreach ($grade_items as $grade_item) {
1166 $grade_item->delete('moddelete');
1170 // Delete completion and availability data; it is better to do this even if the
1171 // features are not turned on, in case they were turned on previously (these will be
1172 // very quick on an empty table).
1173 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1174 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1175 'course' => $cm->course,
1176 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
1178 // Delete all tag instances associated with the instance of this module.
1179 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
1180 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
1182 // Notify the competency subsystem.
1183 \core_competency\api::hook_course_module_deleted($cm);
1185 // Delete the context.
1186 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
1188 // Delete the module from the course_modules table.
1189 $DB->delete_records('course_modules', array('id' => $cm->id));
1191 // Delete module from that section.
1192 if (!delete_mod_from_section($cm->id, $cm->section)) {
1193 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1194 "Cannot delete the module $modulename (instance) from section.");
1197 // Trigger event for course module delete action.
1198 $event = \core\event\course_module_deleted::create(array(
1199 'courseid' => $cm->course,
1200 'context' => $modcontext,
1201 'objectid' => $cm->id,
1202 'other' => array(
1203 'modulename' => $modulename,
1204 'instanceid' => $cm->instance,
1207 $event->add_record_snapshot('course_modules', $cm);
1208 $event->trigger();
1209 rebuild_course_cache($cm->course, true);
1213 * Schedule a course module for deletion in the background using an adhoc task.
1215 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1216 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1218 * @param int $cmid the course module id.
1219 * @return bool whether the module was successfully scheduled for deletion.
1220 * @throws \moodle_exception
1222 function course_module_flag_for_async_deletion($cmid) {
1223 global $CFG, $DB, $USER;
1224 require_once($CFG->libdir.'/gradelib.php');
1225 require_once($CFG->libdir.'/questionlib.php');
1226 require_once($CFG->dirroot.'/blog/lib.php');
1227 require_once($CFG->dirroot.'/calendar/lib.php');
1229 // Get the course module.
1230 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1231 return true;
1234 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1235 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1237 // Get the course module name.
1238 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1240 // Get the file location of the delete_instance function for this module.
1241 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1243 // Include the file required to call the delete_instance function for this module.
1244 if (file_exists($modlib)) {
1245 require_once($modlib);
1246 } else {
1247 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1248 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1251 $deleteinstancefunction = $modulename . '_delete_instance';
1253 // Ensure the delete_instance function exists for this module.
1254 if (!function_exists($deleteinstancefunction)) {
1255 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1256 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1259 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1260 $cm->deletioninprogress = '1';
1261 $DB->update_record('course_modules', $cm);
1263 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1264 $removaltask = new \core_course\task\course_delete_modules();
1265 $removaltask->set_custom_data(array(
1266 'cms' => array($cm),
1267 'userid' => $USER->id,
1268 'realuserid' => \core\session\manager::get_realuser()->id
1271 // Queue the task for the next run.
1272 \core\task\manager::queue_adhoc_task($removaltask);
1274 // Reset the course cache to hide the module.
1275 rebuild_course_cache($cm->course, true);
1279 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1281 * @param int $courseid the id of the course.
1282 * @return bool true if the course contains any modules pending deletion, false otherwise.
1284 function course_modules_pending_deletion($courseid) {
1285 if (empty($courseid)) {
1286 return false;
1288 $modinfo = get_fast_modinfo($courseid);
1289 foreach ($modinfo->get_cms() as $module) {
1290 if ($module->deletioninprogress == '1') {
1291 return true;
1294 return false;
1298 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1300 * @param int $courseid the course id.
1301 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1302 * @param int $instanceid the module instance id.
1303 * @return bool true if the course module is pending deletion, false otherwise.
1305 function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1306 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1307 return false;
1309 $modinfo = get_fast_modinfo($courseid);
1310 $instances = $modinfo->get_instances_of($modulename);
1311 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1314 function delete_mod_from_section($modid, $sectionid) {
1315 global $DB;
1317 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
1319 $modarray = explode(",", $section->sequence);
1321 if ($key = array_keys ($modarray, $modid)) {
1322 array_splice($modarray, $key[0], 1);
1323 $newsequence = implode(",", $modarray);
1324 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1325 rebuild_course_cache($section->course, true);
1326 return true;
1327 } else {
1328 return false;
1332 return false;
1336 * Moves a section within a course, from a position to another.
1337 * Be very careful: $section and $destination refer to section number,
1338 * not id!.
1340 * @param object $course
1341 * @param int $section Section number (not id!!!)
1342 * @param int $destination
1343 * @param bool $ignorenumsections
1344 * @return boolean Result
1346 function move_section_to($course, $section, $destination, $ignorenumsections = false) {
1347 /// Moves a whole course section up and down within the course
1348 global $USER, $DB;
1350 if (!$destination && $destination != 0) {
1351 return true;
1354 // compartibility with course formats using field 'numsections'
1355 $courseformatoptions = course_get_format($course)->get_format_options();
1356 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
1357 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
1358 return false;
1361 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1362 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1363 'section ASC, id ASC', 'id, section')) {
1364 return false;
1367 $movedsections = reorder_sections($sections, $section, $destination);
1369 // Update all sections. Do this in 2 steps to avoid breaking database
1370 // uniqueness constraint
1371 $transaction = $DB->start_delegated_transaction();
1372 foreach ($movedsections as $id => $position) {
1373 if ($sections[$id] !== $position) {
1374 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1377 foreach ($movedsections as $id => $position) {
1378 if ($sections[$id] !== $position) {
1379 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1383 // If we move the highlighted section itself, then just highlight the destination.
1384 // Adjust the higlighted section location if we move something over it either direction.
1385 if ($section == $course->marker) {
1386 course_set_marker($course->id, $destination);
1387 } elseif ($section > $course->marker && $course->marker >= $destination) {
1388 course_set_marker($course->id, $course->marker+1);
1389 } elseif ($section < $course->marker && $course->marker <= $destination) {
1390 course_set_marker($course->id, $course->marker-1);
1393 $transaction->allow_commit();
1394 rebuild_course_cache($course->id, true);
1395 return true;
1399 * This method will delete a course section and may delete all modules inside it.
1401 * No permissions are checked here, use {@link course_can_delete_section()} to
1402 * check if section can actually be deleted.
1404 * @param int|stdClass $course
1405 * @param int|stdClass|section_info $section
1406 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
1407 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
1408 * @return bool whether section was deleted
1410 function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
1411 global $DB;
1413 // Prepare variables.
1414 $courseid = (is_object($course)) ? $course->id : (int)$course;
1415 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1416 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1417 if (!$section) {
1418 // No section exists, can't proceed.
1419 return false;
1422 // Check the 'course_module_background_deletion_recommended' hook first.
1423 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1424 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1425 // It's up to plugins to handle things like whether or not they are enabled.
1426 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1427 foreach ($pluginsfunction as $plugintype => $plugins) {
1428 foreach ($plugins as $pluginfunction) {
1429 if ($pluginfunction()) {
1430 return course_delete_section_async($section, $forcedeleteifnotempty);
1436 $format = course_get_format($course);
1437 $sectionname = $format->get_section_name($section);
1439 // Delete section.
1440 $result = $format->delete_section($section, $forcedeleteifnotempty);
1442 // Trigger an event for course section deletion.
1443 if ($result) {
1444 $context = context_course::instance($courseid);
1445 $event = \core\event\course_section_deleted::create(
1446 array(
1447 'objectid' => $section->id,
1448 'courseid' => $courseid,
1449 'context' => $context,
1450 'other' => array(
1451 'sectionnum' => $section->section,
1452 'sectionname' => $sectionname,
1456 $event->add_record_snapshot('course_sections', $section);
1457 $event->trigger();
1459 return $result;
1463 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1464 * 1. Schedule all modules within the section for adhoc removal.
1465 * 2. Move all modules to course section 0.
1466 * 3. Delete the resulting empty section.
1468 * @param \stdClass $section the section to schedule for deletion.
1469 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1470 * @return bool true if the section was scheduled for deletion, false otherwise.
1472 function course_delete_section_async($section, $forcedeleteifnotempty = true) {
1473 global $DB, $USER;
1475 // Objects only, and only valid ones.
1476 if (!is_object($section) || empty($section->id)) {
1477 return false;
1480 // Does the object currently exist in the DB for removal (check for stale objects).
1481 $section = $DB->get_record('course_sections', array('id' => $section->id));
1482 if (!$section || !$section->section) {
1483 // No section exists, or the section is 0. Can't proceed.
1484 return false;
1487 // Check whether the section can be removed.
1488 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1489 return false;
1492 $format = course_get_format($section->course);
1493 $sectionname = $format->get_section_name($section);
1495 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1496 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1497 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1498 [$section->course, $section->id, 1], '', 'id');
1499 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1501 // Move all modules to section 0.
1502 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1503 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1504 foreach ($modules as $mod) {
1505 moveto_module($mod, $sectionzero);
1508 // Create and queue an adhoc task for the deletion of the modules.
1509 $removaltask = new \core_course\task\course_delete_modules();
1510 $data = array(
1511 'cms' => $affectedmods,
1512 'userid' => $USER->id,
1513 'realuserid' => \core\session\manager::get_realuser()->id
1515 $removaltask->set_custom_data($data);
1516 \core\task\manager::queue_adhoc_task($removaltask);
1518 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1519 // The refresh is needed because the section->sequence is now stale.
1520 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1522 // Trigger an event for course section deletion.
1523 if ($result) {
1524 $context = \context_course::instance($section->course);
1525 $event = \core\event\course_section_deleted::create(
1526 array(
1527 'objectid' => $section->id,
1528 'courseid' => $section->course,
1529 'context' => $context,
1530 'other' => array(
1531 'sectionnum' => $section->section,
1532 'sectionname' => $sectionname,
1536 $event->add_record_snapshot('course_sections', $section);
1537 $event->trigger();
1539 rebuild_course_cache($section->course, true);
1541 return $result;
1545 * Updates the course section
1547 * This function does not check permissions or clean values - this has to be done prior to calling it.
1549 * @param int|stdClass $course
1550 * @param stdClass $section record from course_sections table - it will be updated with the new values
1551 * @param array|stdClass $data
1553 function course_update_section($course, $section, $data) {
1554 global $DB;
1556 $courseid = (is_object($course)) ? $course->id : (int)$course;
1558 // Some fields can not be updated using this method.
1559 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1560 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1561 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1562 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1565 // Update record in the DB and course format options.
1566 $data['id'] = $section->id;
1567 $DB->update_record('course_sections', $data);
1568 rebuild_course_cache($courseid, true);
1569 course_get_format($courseid)->update_section_format_options($data);
1571 // Update fields of the $section object.
1572 foreach ($data as $key => $value) {
1573 if (property_exists($section, $key)) {
1574 $section->$key = $value;
1578 // Trigger an event for course section update.
1579 $event = \core\event\course_section_updated::create(
1580 array(
1581 'objectid' => $section->id,
1582 'courseid' => $courseid,
1583 'context' => context_course::instance($courseid),
1584 'other' => array('sectionnum' => $section->section)
1587 $event->trigger();
1589 // If section visibility was changed, hide the modules in this section too.
1590 if ($changevisibility && !empty($section->sequence)) {
1591 $modules = explode(',', $section->sequence);
1592 foreach ($modules as $moduleid) {
1593 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1594 if ($data['visible']) {
1595 // As we unhide the section, we use the previously saved visibility stored in visibleold.
1596 set_coursemodule_visible($moduleid, $cm->visibleold);
1597 } else {
1598 // We hide the section, so we hide the module but we store the original state in visibleold.
1599 set_coursemodule_visible($moduleid, 0);
1600 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1602 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1609 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1611 * @param int|stdClass $course
1612 * @param int|stdClass|section_info $section
1613 * @return bool
1615 function course_can_delete_section($course, $section) {
1616 if (is_object($section)) {
1617 $section = $section->section;
1619 if (!$section) {
1620 // Not possible to delete 0-section.
1621 return false;
1623 // Course format should allow to delete sections.
1624 if (!course_get_format($course)->can_delete_section($section)) {
1625 return false;
1627 // Make sure user has capability to update course and move sections.
1628 $context = context_course::instance(is_object($course) ? $course->id : $course);
1629 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1630 return false;
1632 // Make sure user has capability to delete each activity in this section.
1633 $modinfo = get_fast_modinfo($course);
1634 if (!empty($modinfo->sections[$section])) {
1635 foreach ($modinfo->sections[$section] as $cmid) {
1636 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1637 return false;
1641 return true;
1645 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1646 * an original position number and a target position number, rebuilds the array so that the
1647 * move is made without any duplication of section positions.
1648 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1649 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1651 * @param array $sections
1652 * @param int $origin_position
1653 * @param int $target_position
1654 * @return array
1656 function reorder_sections($sections, $origin_position, $target_position) {
1657 if (!is_array($sections)) {
1658 return false;
1661 // We can't move section position 0
1662 if ($origin_position < 1) {
1663 echo "We can't move section position 0";
1664 return false;
1667 // Locate origin section in sections array
1668 if (!$origin_key = array_search($origin_position, $sections)) {
1669 echo "searched position not in sections array";
1670 return false; // searched position not in sections array
1673 // Extract origin section
1674 $origin_section = $sections[$origin_key];
1675 unset($sections[$origin_key]);
1677 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1678 $found = false;
1679 $append_array = array();
1680 foreach ($sections as $id => $position) {
1681 if ($found) {
1682 $append_array[$id] = $position;
1683 unset($sections[$id]);
1685 if ($position == $target_position) {
1686 if ($target_position < $origin_position) {
1687 $append_array[$id] = $position;
1688 unset($sections[$id]);
1690 $found = true;
1694 // Append moved section
1695 $sections[$origin_key] = $origin_section;
1697 // Append rest of array (if applicable)
1698 if (!empty($append_array)) {
1699 foreach ($append_array as $id => $position) {
1700 $sections[$id] = $position;
1704 // Renumber positions
1705 $position = 0;
1706 foreach ($sections as $id => $p) {
1707 $sections[$id] = $position;
1708 $position++;
1711 return $sections;
1716 * Move the module object $mod to the specified $section
1717 * If $beforemod exists then that is the module
1718 * before which $modid should be inserted
1720 * @param stdClass|cm_info $mod
1721 * @param stdClass|section_info $section
1722 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1723 * before which the module needs to be included. Null for inserting in the
1724 * end of the section
1725 * @return int new value for module visibility (0 or 1)
1727 function moveto_module($mod, $section, $beforemod=NULL) {
1728 global $OUTPUT, $DB;
1730 // Current module visibility state - return value of this function.
1731 $modvisible = $mod->visible;
1733 // Remove original module from original section.
1734 if (! delete_mod_from_section($mod->id, $mod->section)) {
1735 echo $OUTPUT->notification("Could not delete module from existing section");
1738 // If moving to a hidden section then hide module.
1739 if ($mod->section != $section->id) {
1740 if (!$section->visible && $mod->visible) {
1741 // Module was visible but must become hidden after moving to hidden section.
1742 $modvisible = 0;
1743 set_coursemodule_visible($mod->id, 0);
1744 // Set visibleold to 1 so module will be visible when section is made visible.
1745 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1747 if ($section->visible && !$mod->visible) {
1748 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
1749 set_coursemodule_visible($mod->id, $mod->visibleold);
1750 $modvisible = $mod->visibleold;
1754 // Add the module into the new section.
1755 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
1756 return $modvisible;
1760 * Returns the list of all editing actions that current user can perform on the module
1762 * @param cm_info $mod The module to produce editing buttons for
1763 * @param int $indent The current indenting (default -1 means no move left-right actions)
1764 * @param int $sr The section to link back to (used for creating the links)
1765 * @return array array of action_link or pix_icon objects
1767 function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1768 global $COURSE, $SITE;
1770 static $str;
1772 $coursecontext = context_course::instance($mod->course);
1773 $modcontext = context_module::instance($mod->id);
1775 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1776 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1778 // No permission to edit anything.
1779 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
1780 return array();
1783 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1785 if (!isset($str)) {
1786 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1787 'editsettings', 'duplicate', 'hide', 'show'), 'moodle');
1788 $str->assign = get_string('assignroles', 'role');
1789 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1790 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1791 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1794 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1796 if ($sr !== null) {
1797 $baseurl->param('sr', $sr);
1799 $actions = array();
1801 // Update.
1802 if ($hasmanageactivities) {
1803 $actions['update'] = new action_menu_link_secondary(
1804 new moodle_url($baseurl, array('update' => $mod->id)),
1805 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1806 $str->editsettings,
1807 array('class' => 'editing_update', 'data-action' => 'update')
1811 // Indent.
1812 if ($hasmanageactivities && $indent >= 0) {
1813 $indentlimits = new stdClass();
1814 $indentlimits->min = 0;
1815 $indentlimits->max = 16;
1816 if (right_to_left()) { // Exchange arrows on RTL
1817 $rightarrow = 't/left';
1818 $leftarrow = 't/right';
1819 } else {
1820 $rightarrow = 't/right';
1821 $leftarrow = 't/left';
1824 if ($indent >= $indentlimits->max) {
1825 $enabledclass = 'hidden';
1826 } else {
1827 $enabledclass = '';
1829 $actions['moveright'] = new action_menu_link_secondary(
1830 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1831 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1832 $str->moveright,
1833 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright', 'data-keepopen' => true)
1836 if ($indent <= $indentlimits->min) {
1837 $enabledclass = 'hidden';
1838 } else {
1839 $enabledclass = '';
1841 $actions['moveleft'] = new action_menu_link_secondary(
1842 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
1843 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1844 $str->moveleft,
1845 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft', 'data-keepopen' => true)
1850 // Hide/Show.
1851 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1852 if ($mod->visible) {
1853 $actions['hide'] = new action_menu_link_secondary(
1854 new moodle_url($baseurl, array('hide' => $mod->id)),
1855 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1856 $str->hide,
1857 array('class' => 'editing_hide', 'data-action' => 'hide')
1859 } else {
1860 $actions['show'] = new action_menu_link_secondary(
1861 new moodle_url($baseurl, array('show' => $mod->id)),
1862 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1863 $str->show,
1864 array('class' => 'editing_show', 'data-action' => 'show')
1869 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
1870 if (has_all_capabilities($dupecaps, $coursecontext) &&
1871 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1872 $actions['duplicate'] = new action_menu_link_secondary(
1873 new moodle_url($baseurl, array('duplicate' => $mod->id)),
1874 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1875 $str->duplicate,
1876 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sr' => $sr)
1880 // Groupmode.
1881 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
1882 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1883 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
1884 $nextgroupmode = VISIBLEGROUPS;
1885 $grouptitle = $str->groupsseparate;
1886 $actionname = 'groupsseparate';
1887 $groupimage = 'i/groups';
1888 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
1889 $nextgroupmode = NOGROUPS;
1890 $grouptitle = $str->groupsvisible;
1891 $actionname = 'groupsvisible';
1892 $groupimage = 'i/groupv';
1893 } else {
1894 $nextgroupmode = SEPARATEGROUPS;
1895 $grouptitle = $str->groupsnone;
1896 $actionname = 'groupsnone';
1897 $groupimage = 'i/groupn';
1900 $actions[$actionname] = new action_menu_link_primary(
1901 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
1902 new pix_icon($groupimage, null, 'moodle', array('class' => 'iconsmall')),
1903 $grouptitle,
1904 array('class' => 'editing_'. $actionname, 'data-action' => $actionname, 'data-nextgroupmode' => $nextgroupmode, 'aria-live' => 'assertive')
1906 } else {
1907 $actions['nogroupsupport'] = new action_menu_filler();
1911 // Assign.
1912 if (has_capability('moodle/role:assign', $modcontext)){
1913 $actions['assign'] = new action_menu_link_secondary(
1914 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
1915 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1916 $str->assign,
1917 array('class' => 'editing_assign', 'data-action' => 'assignroles')
1921 // Delete.
1922 if ($hasmanageactivities) {
1923 $actions['delete'] = new action_menu_link_secondary(
1924 new moodle_url($baseurl, array('delete' => $mod->id)),
1925 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1926 $str->delete,
1927 array('class' => 'editing_delete', 'data-action' => 'delete')
1931 return $actions;
1935 * Returns the move action.
1937 * @param cm_info $mod The module to produce a move button for
1938 * @param int $sr The section to link back to (used for creating the links)
1939 * @return The markup for the move action, or an empty string if not available.
1941 function course_get_cm_move(cm_info $mod, $sr = null) {
1942 global $OUTPUT;
1944 static $str;
1945 static $baseurl;
1947 $modcontext = context_module::instance($mod->id);
1948 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1950 if (!isset($str)) {
1951 $str = get_strings(array('move'));
1954 if (!isset($baseurl)) {
1955 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
1957 if ($sr !== null) {
1958 $baseurl->param('sr', $sr);
1962 if ($hasmanageactivities) {
1963 $pixicon = 'i/dragdrop';
1965 if (!course_ajax_enabled($mod->get_course())) {
1966 // Override for course frontpage until we get drag/drop working there.
1967 $pixicon = 't/move';
1970 return html_writer::link(
1971 new moodle_url($baseurl, array('copy' => $mod->id)),
1972 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1973 array('class' => 'editing_move', 'data-action' => 'move')
1976 return '';
1980 * given a course object with shortname & fullname, this function will
1981 * truncate the the number of chars allowed and add ... if it was too long
1983 function course_format_name ($course,$max=100) {
1985 $context = context_course::instance($course->id);
1986 $shortname = format_string($course->shortname, true, array('context' => $context));
1987 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1988 $str = $shortname.': '. $fullname;
1989 if (core_text::strlen($str) <= $max) {
1990 return $str;
1992 else {
1993 return core_text::substr($str,0,$max-3).'...';
1998 * Is the user allowed to add this type of module to this course?
1999 * @param object $course the course settings. Only $course->id is used.
2000 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2001 * @return bool whether the current user is allowed to add this type of module to this course.
2003 function course_allowed_module($course, $modname) {
2004 if (is_numeric($modname)) {
2005 throw new coding_exception('Function course_allowed_module no longer
2006 supports numeric module ids. Please update your code to pass the module name.');
2009 $capability = 'mod/' . $modname . ':addinstance';
2010 if (!get_capability_info($capability)) {
2011 // Debug warning that the capability does not exist, but no more than once per page.
2012 static $warned = array();
2013 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2014 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2015 debugging('The module ' . $modname . ' does not define the standard capability ' .
2016 $capability , DEBUG_DEVELOPER);
2017 $warned[$modname] = 1;
2020 // If the capability does not exist, the module can always be added.
2021 return true;
2024 $coursecontext = context_course::instance($course->id);
2025 return has_capability($capability, $coursecontext);
2029 * Efficiently moves many courses around while maintaining
2030 * sortorder in order.
2032 * @param array $courseids is an array of course ids
2033 * @param int $categoryid
2034 * @return bool success
2036 function move_courses($courseids, $categoryid) {
2037 global $DB;
2039 if (empty($courseids)) {
2040 // Nothing to do.
2041 return false;
2044 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
2045 return false;
2048 $courseids = array_reverse($courseids);
2049 $newparent = context_coursecat::instance($category->id);
2050 $i = 1;
2052 list($where, $params) = $DB->get_in_or_equal($courseids);
2053 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
2054 foreach ($dbcourses as $dbcourse) {
2055 $course = new stdClass();
2056 $course->id = $dbcourse->id;
2057 $course->category = $category->id;
2058 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2059 if ($category->visible == 0) {
2060 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2061 // to previous state if somebody unhides the category.
2062 $course->visible = 0;
2065 $DB->update_record('course', $course);
2067 // Update context, so it can be passed to event.
2068 $context = context_course::instance($course->id);
2069 $context->update_moved($newparent);
2071 // Trigger a course updated event.
2072 $event = \core\event\course_updated::create(array(
2073 'objectid' => $course->id,
2074 'context' => context_course::instance($course->id),
2075 'other' => array('shortname' => $dbcourse->shortname,
2076 'fullname' => $dbcourse->fullname)
2078 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2079 $event->trigger();
2081 fix_course_sortorder();
2082 cache_helper::purge_by_event('changesincourse');
2084 return true;
2088 * Returns the display name of the given section that the course prefers
2090 * Implementation of this function is provided by course format
2091 * @see format_base::get_section_name()
2093 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2094 * @param int|stdClass $section Section object from database or just field course_sections.section
2095 * @return string Display name that the course format prefers, e.g. "Week 2"
2097 function get_section_name($courseorid, $section) {
2098 return course_get_format($courseorid)->get_section_name($section);
2102 * Tells if current course format uses sections
2104 * @param string $format Course format ID e.g. 'weeks' $course->format
2105 * @return bool
2107 function course_format_uses_sections($format) {
2108 $course = new stdClass();
2109 $course->format = $format;
2110 return course_get_format($course)->uses_sections();
2114 * Returns the information about the ajax support in the given source format
2116 * The returned object's property (boolean)capable indicates that
2117 * the course format supports Moodle course ajax features.
2119 * @param string $format
2120 * @return stdClass
2122 function course_format_ajax_support($format) {
2123 $course = new stdClass();
2124 $course->format = $format;
2125 return course_get_format($course)->supports_ajax();
2129 * Can the current user delete this course?
2130 * Course creators have exception,
2131 * 1 day after the creation they can sill delete the course.
2132 * @param int $courseid
2133 * @return boolean
2135 function can_delete_course($courseid) {
2136 global $USER;
2138 $context = context_course::instance($courseid);
2140 if (has_capability('moodle/course:delete', $context)) {
2141 return true;
2144 // hack: now try to find out if creator created this course recently (1 day)
2145 if (!has_capability('moodle/course:create', $context)) {
2146 return false;
2149 $since = time() - 60*60*24;
2150 $course = get_course($courseid);
2152 if ($course->timecreated < $since) {
2153 return false; // Return if the course was not created in last 24 hours.
2156 $logmanger = get_log_manager();
2157 $readers = $logmanger->get_readers('\core\log\sql_reader');
2158 $reader = reset($readers);
2160 if (empty($reader)) {
2161 return false; // No log reader found.
2164 // A proper reader.
2165 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2166 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
2168 return (bool)$reader->get_events_select_count($select, $params);
2172 * Save the Your name for 'Some role' strings.
2174 * @param integer $courseid the id of this course.
2175 * @param array $data the data that came from the course settings form.
2177 function save_local_role_names($courseid, $data) {
2178 global $DB;
2179 $context = context_course::instance($courseid);
2181 foreach ($data as $fieldname => $value) {
2182 if (strpos($fieldname, 'role_') !== 0) {
2183 continue;
2185 list($ignored, $roleid) = explode('_', $fieldname);
2187 // make up our mind whether we want to delete, update or insert
2188 if (!$value) {
2189 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2191 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2192 $rolename->name = $value;
2193 $DB->update_record('role_names', $rolename);
2195 } else {
2196 $rolename = new stdClass;
2197 $rolename->contextid = $context->id;
2198 $rolename->roleid = $roleid;
2199 $rolename->name = $value;
2200 $DB->insert_record('role_names', $rolename);
2202 // This will ensure the course contacts cache is purged..
2203 coursecat::role_assignment_changed($roleid, $context);
2208 * Returns options to use in course overviewfiles filemanager
2210 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2211 * may be empty if course does not exist yet (course create form)
2212 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2213 * or null if overviewfiles are disabled
2215 function course_overviewfiles_options($course) {
2216 global $CFG;
2217 if (empty($CFG->courseoverviewfileslimit)) {
2218 return null;
2220 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2221 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2222 $accepted_types = '*';
2223 } else {
2224 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2225 // Make sure extensions are prefixed with dot unless they are valid typegroups
2226 foreach ($accepted_types as $i => $type) {
2227 if (substr($type, 0, 1) !== '.') {
2228 require_once($CFG->libdir. '/filelib.php');
2229 if (!count(file_get_typegroup('extension', $type))) {
2230 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2231 $accepted_types[$i] = '.'. $type;
2232 $corrected = true;
2236 if (!empty($corrected)) {
2237 set_config('courseoverviewfilesext', join(',', $accepted_types));
2240 $options = array(
2241 'maxfiles' => $CFG->courseoverviewfileslimit,
2242 'maxbytes' => $CFG->maxbytes,
2243 'subdirs' => 0,
2244 'accepted_types' => $accepted_types
2246 if (!empty($course->id)) {
2247 $options['context'] = context_course::instance($course->id);
2248 } else if (is_int($course) && $course > 0) {
2249 $options['context'] = context_course::instance($course);
2251 return $options;
2255 * Create a course and either return a $course object
2257 * Please note this functions does not verify any access control,
2258 * the calling code is responsible for all validation (usually it is the form definition).
2260 * @param array $editoroptions course description editor options
2261 * @param object $data - all the data needed for an entry in the 'course' table
2262 * @return object new course instance
2264 function create_course($data, $editoroptions = NULL) {
2265 global $DB, $CFG;
2267 //check the categoryid - must be given for all new courses
2268 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
2270 // Check if the shortname already exists.
2271 if (!empty($data->shortname)) {
2272 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
2273 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2277 // Check if the idnumber already exists.
2278 if (!empty($data->idnumber)) {
2279 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
2280 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2284 if ($errorcode = course_validate_dates((array)$data)) {
2285 throw new moodle_exception($errorcode);
2288 // Check if timecreated is given.
2289 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
2290 $data->timemodified = $data->timecreated;
2292 // place at beginning of any category
2293 $data->sortorder = 0;
2295 if ($editoroptions) {
2296 // summary text is updated later, we need context to store the files first
2297 $data->summary = '';
2298 $data->summary_format = FORMAT_HTML;
2301 if (!isset($data->visible)) {
2302 // data not from form, add missing visibility info
2303 $data->visible = $category->visible;
2305 $data->visibleold = $data->visible;
2307 $newcourseid = $DB->insert_record('course', $data);
2308 $context = context_course::instance($newcourseid, MUST_EXIST);
2310 if ($editoroptions) {
2311 // Save the files used in the summary editor and store
2312 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2313 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2314 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2316 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2317 // Save the course overviewfiles
2318 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2321 // update course format options
2322 course_get_format($newcourseid)->update_course_format_options($data);
2324 $course = course_get_format($newcourseid)->get_course();
2326 fix_course_sortorder();
2327 // purge appropriate caches in case fix_course_sortorder() did not change anything
2328 cache_helper::purge_by_event('changesincourse');
2330 // new context created - better mark it as dirty
2331 $context->mark_dirty();
2333 // Trigger a course created event.
2334 $event = \core\event\course_created::create(array(
2335 'objectid' => $course->id,
2336 'context' => context_course::instance($course->id),
2337 'other' => array('shortname' => $course->shortname,
2338 'fullname' => $course->fullname)
2341 $event->trigger();
2343 // Setup the blocks
2344 blocks_add_default_course_blocks($course);
2346 // Create a default section.
2347 course_create_sections_if_missing($course, 0);
2349 // Save any custom role names.
2350 save_local_role_names($course->id, (array)$data);
2352 // set up enrolments
2353 enrol_course_updated(true, $course, $data);
2355 // Update course tags.
2356 if (isset($data->tags)) {
2357 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2360 return $course;
2364 * Update a course.
2366 * Please note this functions does not verify any access control,
2367 * the calling code is responsible for all validation (usually it is the form definition).
2369 * @param object $data - all the data needed for an entry in the 'course' table
2370 * @param array $editoroptions course description editor options
2371 * @return void
2373 function update_course($data, $editoroptions = NULL) {
2374 global $DB, $CFG;
2376 $data->timemodified = time();
2378 // Prevent changes on front page course.
2379 if ($data->id == SITEID) {
2380 throw new moodle_exception('invalidcourse', 'error');
2383 $oldcourse = course_get_format($data->id)->get_course();
2384 $context = context_course::instance($oldcourse->id);
2386 if ($editoroptions) {
2387 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
2389 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2390 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2393 // Check we don't have a duplicate shortname.
2394 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
2395 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
2396 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2400 // Check we don't have a duplicate idnumber.
2401 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
2402 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
2403 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2407 if ($errorcode = course_validate_dates((array)$data)) {
2408 throw new moodle_exception($errorcode);
2411 if (!isset($data->category) or empty($data->category)) {
2412 // prevent nulls and 0 in category field
2413 unset($data->category);
2415 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
2417 if (!isset($data->visible)) {
2418 // data not from form, add missing visibility info
2419 $data->visible = $oldcourse->visible;
2422 if ($data->visible != $oldcourse->visible) {
2423 // reset the visibleold flag when manually hiding/unhiding course
2424 $data->visibleold = $data->visible;
2425 $changesincoursecat = true;
2426 } else {
2427 if ($movecat) {
2428 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2429 if (empty($newcategory->visible)) {
2430 // make sure when moving into hidden category the course is hidden automatically
2431 $data->visible = 0;
2436 // Update with the new data
2437 $DB->update_record('course', $data);
2438 // make sure the modinfo cache is reset
2439 rebuild_course_cache($data->id);
2441 // update course format options with full course data
2442 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2444 $course = $DB->get_record('course', array('id'=>$data->id));
2446 if ($movecat) {
2447 $newparent = context_coursecat::instance($course->category);
2448 $context->update_moved($newparent);
2450 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2451 if ($fixcoursesortorder) {
2452 fix_course_sortorder();
2455 // purge appropriate caches in case fix_course_sortorder() did not change anything
2456 cache_helper::purge_by_event('changesincourse');
2457 if ($changesincoursecat) {
2458 cache_helper::purge_by_event('changesincoursecat');
2461 // Test for and remove blocks which aren't appropriate anymore
2462 blocks_remove_inappropriate($course);
2464 // Save any custom role names.
2465 save_local_role_names($course->id, $data);
2467 // update enrol settings
2468 enrol_course_updated(false, $course, $data);
2470 // Update course tags.
2471 if (isset($data->tags)) {
2472 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
2475 // Trigger a course updated event.
2476 $event = \core\event\course_updated::create(array(
2477 'objectid' => $course->id,
2478 'context' => context_course::instance($course->id),
2479 'other' => array('shortname' => $course->shortname,
2480 'fullname' => $course->fullname)
2483 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
2484 $event->trigger();
2486 if ($oldcourse->format !== $course->format) {
2487 // Remove all options stored for the previous format
2488 // We assume that new course format migrated everything it needed watching trigger
2489 // 'course_updated' and in method format_XXX::update_course_format_options()
2490 $DB->delete_records('course_format_options',
2491 array('courseid' => $course->id, 'format' => $oldcourse->format));
2496 * Average number of participants
2497 * @return integer
2499 function average_number_of_participants() {
2500 global $DB, $SITE;
2502 //count total of enrolments for visible course (except front page)
2503 $sql = 'SELECT COUNT(*) FROM (
2504 SELECT DISTINCT ue.userid, e.courseid
2505 FROM {user_enrolments} ue, {enrol} e, {course} c
2506 WHERE ue.enrolid = e.id
2507 AND e.courseid <> :siteid
2508 AND c.id = e.courseid
2509 AND c.visible = 1) total';
2510 $params = array('siteid' => $SITE->id);
2511 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2514 //count total of visible courses (minus front page)
2515 $coursetotal = $DB->count_records('course', array('visible' => 1));
2516 $coursetotal = $coursetotal - 1 ;
2518 //average of enrolment
2519 if (empty($coursetotal)) {
2520 $participantaverage = 0;
2521 } else {
2522 $participantaverage = $enrolmenttotal / $coursetotal;
2525 return $participantaverage;
2529 * Average number of course modules
2530 * @return integer
2532 function average_number_of_courses_modules() {
2533 global $DB, $SITE;
2535 //count total of visible course module (except front page)
2536 $sql = 'SELECT COUNT(*) FROM (
2537 SELECT cm.course, cm.module
2538 FROM {course} c, {course_modules} cm
2539 WHERE c.id = cm.course
2540 AND c.id <> :siteid
2541 AND cm.visible = 1
2542 AND c.visible = 1) total';
2543 $params = array('siteid' => $SITE->id);
2544 $moduletotal = $DB->count_records_sql($sql, $params);
2547 //count total of visible courses (minus front page)
2548 $coursetotal = $DB->count_records('course', array('visible' => 1));
2549 $coursetotal = $coursetotal - 1 ;
2551 //average of course module
2552 if (empty($coursetotal)) {
2553 $coursemoduleaverage = 0;
2554 } else {
2555 $coursemoduleaverage = $moduletotal / $coursetotal;
2558 return $coursemoduleaverage;
2562 * This class pertains to course requests and contains methods associated with
2563 * create, approving, and removing course requests.
2565 * Please note we do not allow embedded images here because there is no context
2566 * to store them with proper access control.
2568 * @copyright 2009 Sam Hemelryk
2569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2570 * @since Moodle 2.0
2572 * @property-read int $id
2573 * @property-read string $fullname
2574 * @property-read string $shortname
2575 * @property-read string $summary
2576 * @property-read int $summaryformat
2577 * @property-read int $summarytrust
2578 * @property-read string $reason
2579 * @property-read int $requester
2581 class course_request {
2584 * This is the stdClass that stores the properties for the course request
2585 * and is externally accessed through the __get magic method
2586 * @var stdClass
2588 protected $properties;
2591 * An array of options for the summary editor used by course request forms.
2592 * This is initially set by {@link summary_editor_options()}
2593 * @var array
2594 * @static
2596 protected static $summaryeditoroptions;
2599 * Static function to prepare the summary editor for working with a course
2600 * request.
2602 * @static
2603 * @param null|stdClass $data Optional, an object containing the default values
2604 * for the form, these may be modified when preparing the
2605 * editor so this should be called before creating the form
2606 * @return stdClass An object that can be used to set the default values for
2607 * an mforms form
2609 public static function prepare($data=null) {
2610 if ($data === null) {
2611 $data = new stdClass;
2613 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
2614 return $data;
2618 * Static function to create a new course request when passed an array of properties
2619 * for it.
2621 * This function also handles saving any files that may have been used in the editor
2623 * @static
2624 * @param stdClass $data
2625 * @return course_request The newly created course request
2627 public static function create($data) {
2628 global $USER, $DB, $CFG;
2629 $data->requester = $USER->id;
2631 // Setting the default category if none set.
2632 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2633 $data->category = $CFG->defaultrequestcategory;
2636 // Summary is a required field so copy the text over
2637 $data->summary = $data->summary_editor['text'];
2638 $data->summaryformat = $data->summary_editor['format'];
2640 $data->id = $DB->insert_record('course_request', $data);
2642 // Create a new course_request object and return it
2643 $request = new course_request($data);
2645 // Notify the admin if required.
2646 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
2648 $a = new stdClass;
2649 $a->link = "$CFG->wwwroot/course/pending.php";
2650 $a->user = fullname($USER);
2651 $subject = get_string('courserequest');
2652 $message = get_string('courserequestnotifyemail', 'admin', $a);
2653 foreach ($users as $user) {
2654 $request->notify($user, $USER, 'courserequested', $subject, $message);
2658 return $request;
2662 * Returns an array of options to use with a summary editor
2664 * @uses course_request::$summaryeditoroptions
2665 * @return array An array of options to use with the editor
2667 public static function summary_editor_options() {
2668 global $CFG;
2669 if (self::$summaryeditoroptions === null) {
2670 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
2672 return self::$summaryeditoroptions;
2676 * Loads the properties for this course request object. Id is required and if
2677 * only id is provided then we load the rest of the properties from the database
2679 * @param stdClass|int $properties Either an object containing properties
2680 * or the course_request id to load
2682 public function __construct($properties) {
2683 global $DB;
2684 if (empty($properties->id)) {
2685 if (empty($properties)) {
2686 throw new coding_exception('You must provide a course request id when creating a course_request object');
2688 $id = $properties;
2689 $properties = new stdClass;
2690 $properties->id = (int)$id;
2691 unset($id);
2693 if (empty($properties->requester)) {
2694 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2695 print_error('unknowncourserequest');
2697 } else {
2698 $this->properties = $properties;
2700 $this->properties->collision = null;
2704 * Returns the requested property
2706 * @param string $key
2707 * @return mixed
2709 public function __get($key) {
2710 return $this->properties->$key;
2714 * Override this to ensure empty($request->blah) calls return a reliable answer...
2716 * This is required because we define the __get method
2718 * @param mixed $key
2719 * @return bool True is it not empty, false otherwise
2721 public function __isset($key) {
2722 return (!empty($this->properties->$key));
2726 * Returns the user who requested this course
2728 * Uses a static var to cache the results and cut down the number of db queries
2730 * @staticvar array $requesters An array of cached users
2731 * @return stdClass The user who requested the course
2733 public function get_requester() {
2734 global $DB;
2735 static $requesters= array();
2736 if (!array_key_exists($this->properties->requester, $requesters)) {
2737 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2739 return $requesters[$this->properties->requester];
2743 * Checks that the shortname used by the course does not conflict with any other
2744 * courses that exist
2746 * @param string|null $shortnamemark The string to append to the requests shortname
2747 * should a conflict be found
2748 * @return bool true is there is a conflict, false otherwise
2750 public function check_shortname_collision($shortnamemark = '[*]') {
2751 global $DB;
2753 if ($this->properties->collision !== null) {
2754 return $this->properties->collision;
2757 if (empty($this->properties->shortname)) {
2758 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2759 $this->properties->collision = false;
2760 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2761 if (!empty($shortnamemark)) {
2762 $this->properties->shortname .= ' '.$shortnamemark;
2764 $this->properties->collision = true;
2765 } else {
2766 $this->properties->collision = false;
2768 return $this->properties->collision;
2772 * Returns the category where this course request should be created
2774 * Note that we don't check here that user has a capability to view
2775 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2776 * 'moodle/course:changecategory'
2778 * @return coursecat
2780 public function get_category() {
2781 global $CFG;
2782 require_once($CFG->libdir.'/coursecatlib.php');
2783 // If the category is not set, if the current user does not have the rights to change the category, or if the
2784 // category does not exist, we set the default category to the course to be approved.
2785 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2786 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2787 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2788 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2790 if (!$category) {
2791 $category = coursecat::get_default();
2793 return $category;
2797 * This function approves the request turning it into a course
2799 * This function converts the course request into a course, at the same time
2800 * transferring any files used in the summary to the new course and then removing
2801 * the course request and the files associated with it.
2803 * @return int The id of the course that was created from this request
2805 public function approve() {
2806 global $CFG, $DB, $USER;
2808 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2810 $courseconfig = get_config('moodlecourse');
2812 // Transfer appropriate settings
2813 $data = clone($this->properties);
2814 unset($data->id);
2815 unset($data->reason);
2816 unset($data->requester);
2818 // Set category
2819 $category = $this->get_category();
2820 $data->category = $category->id;
2821 // Set misc settings
2822 $data->requested = 1;
2824 // Apply course default settings
2825 $data->format = $courseconfig->format;
2826 $data->newsitems = $courseconfig->newsitems;
2827 $data->showgrades = $courseconfig->showgrades;
2828 $data->showreports = $courseconfig->showreports;
2829 $data->maxbytes = $courseconfig->maxbytes;
2830 $data->groupmode = $courseconfig->groupmode;
2831 $data->groupmodeforce = $courseconfig->groupmodeforce;
2832 $data->visible = $courseconfig->visible;
2833 $data->visibleold = $data->visible;
2834 $data->lang = $courseconfig->lang;
2835 $data->enablecompletion = $courseconfig->enablecompletion;
2837 $course = create_course($data);
2838 $context = context_course::instance($course->id, MUST_EXIST);
2840 // add enrol instances
2841 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2842 if ($manual = enrol_get_plugin('manual')) {
2843 $manual->add_default_instance($course);
2847 // enrol the requester as teacher if necessary
2848 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2849 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2852 $this->delete();
2854 $a = new stdClass();
2855 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
2856 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2857 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
2859 return $course->id;
2863 * Reject a course request
2865 * This function rejects a course request, emailing the requesting user the
2866 * provided notice and then removing the request from the database
2868 * @param string $notice The message to display to the user
2870 public function reject($notice) {
2871 global $USER, $DB;
2872 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
2873 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2874 $this->delete();
2878 * Deletes the course request and any associated files
2880 public function delete() {
2881 global $DB;
2882 $DB->delete_records('course_request', array('id' => $this->properties->id));
2886 * Send a message from one user to another using events_trigger
2888 * @param object $touser
2889 * @param object $fromuser
2890 * @param string $name
2891 * @param string $subject
2892 * @param string $message
2893 * @param int|null $courseid
2895 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
2896 $eventdata = new \core\message\message();
2897 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
2898 $eventdata->component = 'moodle';
2899 $eventdata->name = $name;
2900 $eventdata->userfrom = $fromuser;
2901 $eventdata->userto = $touser;
2902 $eventdata->subject = $subject;
2903 $eventdata->fullmessage = $message;
2904 $eventdata->fullmessageformat = FORMAT_PLAIN;
2905 $eventdata->fullmessagehtml = '';
2906 $eventdata->smallmessage = '';
2907 $eventdata->notification = 1;
2908 message_send($eventdata);
2913 * Return a list of page types
2914 * @param string $pagetype current page type
2915 * @param context $parentcontext Block's parent context
2916 * @param context $currentcontext Current context of block
2917 * @return array array of page types
2919 function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
2920 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2921 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2922 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2923 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2925 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2926 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2927 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2928 } else {
2929 // Otherwise consider it a page inside a course even if $currentcontext is null
2930 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2931 'course-*' => get_string('page-course-x', 'pagetype'),
2932 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2935 return $pagetypes;
2939 * Determine whether course ajax should be enabled for the specified course
2941 * @param stdClass $course The course to test against
2942 * @return boolean Whether course ajax is enabled or note
2944 function course_ajax_enabled($course) {
2945 global $CFG, $PAGE, $SITE;
2947 // The user must be editing for AJAX to be included
2948 if (!$PAGE->user_is_editing()) {
2949 return false;
2952 // Check that the theme suports
2953 if (!$PAGE->theme->enablecourseajax) {
2954 return false;
2957 // Check that the course format supports ajax functionality
2958 // The site 'format' doesn't have information on course format support
2959 if ($SITE->id !== $course->id) {
2960 $courseformatajaxsupport = course_format_ajax_support($course->format);
2961 if (!$courseformatajaxsupport->capable) {
2962 return false;
2966 // All conditions have been met so course ajax should be enabled
2967 return true;
2971 * Include the relevant javascript and language strings for the resource
2972 * toolbox YUI module
2974 * @param integer $id The ID of the course being applied to
2975 * @param array $usedmodules An array containing the names of the modules in use on the page
2976 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
2977 * @param stdClass $config An object containing configuration parameters for ajax modules including:
2978 * * resourceurl The URL to post changes to for resource changes
2979 * * sectionurl The URL to post changes to for section changes
2980 * * pageparams Additional parameters to pass through in the post
2981 * @return bool
2983 function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
2984 global $CFG, $PAGE, $SITE;
2986 // Ensure that ajax should be included
2987 if (!course_ajax_enabled($course)) {
2988 return false;
2991 if (!$config) {
2992 $config = new stdClass();
2995 // The URL to use for resource changes
2996 if (!isset($config->resourceurl)) {
2997 $config->resourceurl = '/course/rest.php';
3000 // The URL to use for section changes
3001 if (!isset($config->sectionurl)) {
3002 $config->sectionurl = '/course/rest.php';
3005 // Any additional parameters which need to be included on page submission
3006 if (!isset($config->pageparams)) {
3007 $config->pageparams = array();
3010 // Include toolboxes
3011 $PAGE->requires->yui_module('moodle-course-toolboxes',
3012 'M.course.init_resource_toolbox',
3013 array(array(
3014 'courseid' => $course->id,
3015 'ajaxurl' => $config->resourceurl,
3016 'config' => $config,
3019 $PAGE->requires->yui_module('moodle-course-toolboxes',
3020 'M.course.init_section_toolbox',
3021 array(array(
3022 'courseid' => $course->id,
3023 'format' => $course->format,
3024 'ajaxurl' => $config->sectionurl,
3025 'config' => $config,
3029 // Include course dragdrop
3030 if (course_format_uses_sections($course->format)) {
3031 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
3032 array(array(
3033 'courseid' => $course->id,
3034 'ajaxurl' => $config->sectionurl,
3035 'config' => $config,
3036 )), null, true);
3038 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
3039 array(array(
3040 'courseid' => $course->id,
3041 'ajaxurl' => $config->resourceurl,
3042 'config' => $config,
3043 )), null, true);
3046 // Require various strings for the command toolbox
3047 $PAGE->requires->strings_for_js(array(
3048 'moveleft',
3049 'deletechecktype',
3050 'deletechecktypename',
3051 'edittitle',
3052 'edittitleinstructions',
3053 'show',
3054 'hide',
3055 'highlight',
3056 'highlightoff',
3057 'groupsnone',
3058 'groupsvisible',
3059 'groupsseparate',
3060 'clicktochangeinbrackets',
3061 'markthistopic',
3062 'markedthistopic',
3063 'movesection',
3064 'movecoursemodule',
3065 'movecoursesection',
3066 'movecontent',
3067 'tocontent',
3068 'emptydragdropregion',
3069 'afterresource',
3070 'aftersection',
3071 'totopofsection',
3072 ), 'moodle');
3074 // Include section-specific strings for formats which support sections.
3075 if (course_format_uses_sections($course->format)) {
3076 $PAGE->requires->strings_for_js(array(
3077 'showfromothers',
3078 'hidefromothers',
3079 ), 'format_' . $course->format);
3082 // For confirming resource deletion we need the name of the module in question
3083 foreach ($usedmodules as $module => $modname) {
3084 $PAGE->requires->string_for_js('pluginname', $module);
3087 // Load drag and drop upload AJAX.
3088 require_once($CFG->dirroot.'/course/dnduploadlib.php');
3089 dndupload_add_to_course($course, $enabledmodules);
3091 return true;
3095 * Returns the sorted list of available course formats, filtered by enabled if necessary
3097 * @param bool $enabledonly return only formats that are enabled
3098 * @return array array of sorted format names
3100 function get_sorted_course_formats($enabledonly = false) {
3101 global $CFG;
3102 $formats = core_component::get_plugin_list('format');
3104 if (!empty($CFG->format_plugins_sortorder)) {
3105 $order = explode(',', $CFG->format_plugins_sortorder);
3106 $order = array_merge(array_intersect($order, array_keys($formats)),
3107 array_diff(array_keys($formats), $order));
3108 } else {
3109 $order = array_keys($formats);
3111 if (!$enabledonly) {
3112 return $order;
3114 $sortedformats = array();
3115 foreach ($order as $formatname) {
3116 if (!get_config('format_'.$formatname, 'disabled')) {
3117 $sortedformats[] = $formatname;
3120 return $sortedformats;
3124 * The URL to use for the specified course (with section)
3126 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3127 * @param int|stdClass $section Section object from database or just field course_sections.section
3128 * if omitted the course view page is returned
3129 * @param array $options options for view URL. At the moment core uses:
3130 * 'navigation' (bool) if true and section has no separate page, the function returns null
3131 * 'sr' (int) used by multipage formats to specify to which section to return
3132 * @return moodle_url The url of course
3134 function course_get_url($courseorid, $section = null, $options = array()) {
3135 return course_get_format($courseorid)->get_view_url($section, $options);
3139 * Create a module.
3141 * It includes:
3142 * - capability checks and other checks
3143 * - create the module from the module info
3145 * @param object $module
3146 * @return object the created module info
3147 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
3149 function create_module($moduleinfo) {
3150 global $DB, $CFG;
3152 require_once($CFG->dirroot . '/course/modlib.php');
3154 // Check manadatory attributs.
3155 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3156 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3157 $mandatoryfields[] = 'introeditor';
3159 foreach($mandatoryfields as $mandatoryfield) {
3160 if (!isset($moduleinfo->{$mandatoryfield})) {
3161 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3165 // Some additional checks (capability / existing instances).
3166 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3167 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3169 // Add the module.
3170 $moduleinfo->module = $module->id;
3171 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3173 return $moduleinfo;
3177 * Update a module.
3179 * It includes:
3180 * - capability and other checks
3181 * - update the module
3183 * @param object $module
3184 * @return object the updated module info
3185 * @throws moodle_exception if current user is not allowed to update the module
3187 function update_module($moduleinfo) {
3188 global $DB, $CFG;
3190 require_once($CFG->dirroot . '/course/modlib.php');
3192 // Check the course module exists.
3193 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3195 // Check the course exists.
3196 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3198 // Some checks (capaibility / existing instances).
3199 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3201 // Retrieve few information needed by update_moduleinfo.
3202 $moduleinfo->modulename = $cm->modname;
3203 if (!isset($moduleinfo->scale)) {
3204 $moduleinfo->scale = 0;
3206 $moduleinfo->type = 'mod';
3208 // Update the module.
3209 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3211 return $moduleinfo;
3215 * Duplicate a module on the course for ajax.
3217 * @see mod_duplicate_module()
3218 * @param object $course The course
3219 * @param object $cm The course module to duplicate
3220 * @param int $sr The section to link back to (used for creating the links)
3221 * @throws moodle_exception if the plugin doesn't support duplication
3222 * @return Object containing:
3223 * - fullcontent: The HTML markup for the created CM
3224 * - cmid: The CMID of the newly created CM
3225 * - redirect: Whether to trigger a redirect following this change
3227 function mod_duplicate_activity($course, $cm, $sr = null) {
3228 global $PAGE;
3230 $newcm = duplicate_module($course, $cm);
3232 $resp = new stdClass();
3233 if ($newcm) {
3234 $courserenderer = $PAGE->get_renderer('core', 'course');
3235 $completioninfo = new completion_info($course);
3236 $modulehtml = $courserenderer->course_section_cm($course, $completioninfo,
3237 $newcm, null, array());
3239 $resp->fullcontent = $courserenderer->course_section_cm_list_item($course, $completioninfo, $newcm, $sr);
3240 $resp->cmid = $newcm->id;
3241 } else {
3242 // Trigger a redirect.
3243 $resp->redirect = true;
3245 return $resp;
3249 * Api to duplicate a module.
3251 * @param object $course course object.
3252 * @param object $cm course module object to be duplicated.
3253 * @since Moodle 2.8
3255 * @throws Exception
3256 * @throws coding_exception
3257 * @throws moodle_exception
3258 * @throws restore_controller_exception
3260 * @return cm_info|null cminfo object if we sucessfully duplicated the mod and found the new cm.
3262 function duplicate_module($course, $cm) {
3263 global $CFG, $DB, $USER;
3264 require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
3265 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
3266 require_once($CFG->libdir . '/filelib.php');
3268 $a = new stdClass();
3269 $a->modtype = get_string('modulename', $cm->modname);
3270 $a->modname = format_string($cm->name);
3272 if (!plugin_supports('mod', $cm->modname, FEATURE_BACKUP_MOODLE2)) {
3273 throw new moodle_exception('duplicatenosupport', 'error', '', $a);
3276 // Backup the activity.
3278 $bc = new backup_controller(backup::TYPE_1ACTIVITY, $cm->id, backup::FORMAT_MOODLE,
3279 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id);
3281 $backupid = $bc->get_backupid();
3282 $backupbasepath = $bc->get_plan()->get_basepath();
3284 $bc->execute_plan();
3286 $bc->destroy();
3288 // Restore the backup immediately.
3290 $rc = new restore_controller($backupid, $course->id,
3291 backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
3293 $cmcontext = context_module::instance($cm->id);
3294 if (!$rc->execute_precheck()) {
3295 $precheckresults = $rc->get_precheck_results();
3296 if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
3297 if (empty($CFG->keeptempdirectoriesonbackup)) {
3298 fulldelete($backupbasepath);
3303 $rc->execute_plan();
3305 // Now a bit hacky part follows - we try to get the cmid of the newly
3306 // restored copy of the module.
3307 $newcmid = null;
3308 $tasks = $rc->get_plan()->get_tasks();
3309 foreach ($tasks as $task) {
3310 if (is_subclass_of($task, 'restore_activity_task')) {
3311 if ($task->get_old_contextid() == $cmcontext->id) {
3312 $newcmid = $task->get_moduleid();
3313 break;
3318 // If we know the cmid of the new course module, let us move it
3319 // right below the original one. otherwise it will stay at the
3320 // end of the section.
3321 if ($newcmid) {
3322 $info = get_fast_modinfo($course);
3323 $newcm = $info->get_cm($newcmid);
3324 $section = $DB->get_record('course_sections', array('id' => $cm->section, 'course' => $cm->course));
3325 moveto_module($newcm, $section, $cm);
3326 moveto_module($cm, $section, $newcm);
3328 // Update calendar events with the duplicated module.
3329 $refresheventsfunction = $newcm->modname . '_refresh_events';
3330 if (function_exists($refresheventsfunction)) {
3331 call_user_func($refresheventsfunction, $newcm->course);
3334 // Trigger course module created event. We can trigger the event only if we know the newcmid.
3335 $event = \core\event\course_module_created::create_from_cm($newcm);
3336 $event->trigger();
3338 rebuild_course_cache($cm->course);
3340 $rc->destroy();
3342 if (empty($CFG->keeptempdirectoriesonbackup)) {
3343 fulldelete($backupbasepath);
3346 return isset($newcm) ? $newcm : null;
3350 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3351 * Sorts by descending order of time.
3353 * @param stdClass $a First object
3354 * @param stdClass $b Second object
3355 * @return int 0,1,-1 representing the order
3357 function compare_activities_by_time_desc($a, $b) {
3358 // Make sure the activities actually have a timestamp property.
3359 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3360 return 0;
3362 // We treat instances without timestamp as if they have a timestamp of 0.
3363 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3364 return 1;
3366 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3367 return -1;
3369 if ($a->timestamp == $b->timestamp) {
3370 return 0;
3372 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3376 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3377 * Sorts by ascending order of time.
3379 * @param stdClass $a First object
3380 * @param stdClass $b Second object
3381 * @return int 0,1,-1 representing the order
3383 function compare_activities_by_time_asc($a, $b) {
3384 // Make sure the activities actually have a timestamp property.
3385 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3386 return 0;
3388 // We treat instances without timestamp as if they have a timestamp of 0.
3389 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3390 return -1;
3392 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3393 return 1;
3395 if ($a->timestamp == $b->timestamp) {
3396 return 0;
3398 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3402 * Changes the visibility of a course.
3404 * @param int $courseid The course to change.
3405 * @param bool $show True to make it visible, false otherwise.
3406 * @return bool
3408 function course_change_visibility($courseid, $show = true) {
3409 $course = new stdClass;
3410 $course->id = $courseid;
3411 $course->visible = ($show) ? '1' : '0';
3412 $course->visibleold = $course->visible;
3413 update_course($course);
3414 return true;
3418 * Changes the course sortorder by one, moving it up or down one in respect to sort order.
3420 * @param stdClass|course_in_list $course
3421 * @param bool $up If set to true the course will be moved up one. Otherwise down one.
3422 * @return bool
3424 function course_change_sortorder_by_one($course, $up) {
3425 global $DB;
3426 $params = array($course->sortorder, $course->category);
3427 if ($up) {
3428 $select = 'sortorder < ? AND category = ?';
3429 $sort = 'sortorder DESC';
3430 } else {
3431 $select = 'sortorder > ? AND category = ?';
3432 $sort = 'sortorder ASC';
3434 fix_course_sortorder();
3435 $swapcourse = $DB->get_records_select('course', $select, $params, $sort, '*', 0, 1);
3436 if ($swapcourse) {
3437 $swapcourse = reset($swapcourse);
3438 $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $course->id));
3439 $DB->set_field('course', 'sortorder', $course->sortorder, array('id' => $swapcourse->id));
3440 // Finally reorder courses.
3441 fix_course_sortorder();
3442 cache_helper::purge_by_event('changesincourse');
3443 return true;
3445 return false;
3449 * Changes the sort order of courses in a category so that the first course appears after the second.
3451 * @param int|stdClass $courseorid The course to focus on.
3452 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
3453 * @return bool
3455 function course_change_sortorder_after_course($courseorid, $moveaftercourseid) {
3456 global $DB;
3458 if (!is_object($courseorid)) {
3459 $course = get_course($courseorid);
3460 } else {
3461 $course = $courseorid;
3464 if ((int)$moveaftercourseid === 0) {
3465 // We've moving the course to the start of the queue.
3466 $sql = 'SELECT sortorder
3467 FROM {course}
3468 WHERE category = :categoryid
3469 ORDER BY sortorder';
3470 $params = array(
3471 'categoryid' => $course->category
3473 $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
3475 $sql = 'UPDATE {course}
3476 SET sortorder = sortorder + 1
3477 WHERE category = :categoryid
3478 AND id <> :id';
3479 $params = array(
3480 'categoryid' => $course->category,
3481 'id' => $course->id,
3483 $DB->execute($sql, $params);
3484 $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
3485 } else if ($course->id === $moveaftercourseid) {
3486 // They're the same - moronic.
3487 debugging("Invalid move after course given.", DEBUG_DEVELOPER);
3488 return false;
3489 } else {
3490 // Moving this course after the given course. It could be before it could be after.
3491 $moveaftercourse = get_course($moveaftercourseid);
3492 if ($course->category !== $moveaftercourse->category) {
3493 debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
3494 return false;
3496 // Increment all courses in the same category that are ordered after the moveafter course.
3497 // This makes a space for the course we're moving.
3498 $sql = 'UPDATE {course}
3499 SET sortorder = sortorder + 1
3500 WHERE category = :categoryid
3501 AND sortorder > :sortorder';
3502 $params = array(
3503 'categoryid' => $moveaftercourse->category,
3504 'sortorder' => $moveaftercourse->sortorder
3506 $DB->execute($sql, $params);
3507 $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
3509 fix_course_sortorder();
3510 cache_helper::purge_by_event('changesincourse');
3511 return true;
3515 * Trigger course viewed event. This API function is used when course view actions happens,
3516 * usually in course/view.php but also in external functions.
3518 * @param stdClass $context course context object
3519 * @param int $sectionnumber section number
3520 * @since Moodle 2.9
3522 function course_view($context, $sectionnumber = 0) {
3524 $eventdata = array('context' => $context);
3526 if (!empty($sectionnumber)) {
3527 $eventdata['other']['coursesectionnumber'] = $sectionnumber;
3530 $event = \core\event\course_viewed::create($eventdata);
3531 $event->trigger();
3535 * Returns courses tagged with a specified tag.
3537 * @param core_tag_tag $tag
3538 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3539 * are displayed on the page and the per-page limit may be bigger
3540 * @param int $fromctx context id where the link was displayed, may be used by callbacks
3541 * to display items in the same context first
3542 * @param int $ctx context id where to search for records
3543 * @param bool $rec search in subcontexts as well
3544 * @param int $page 0-based number of page being displayed
3545 * @return \core_tag\output\tagindex
3547 function course_get_tagged_courses($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
3548 global $CFG, $PAGE;
3549 require_once($CFG->libdir . '/coursecatlib.php');
3551 $perpage = $exclusivemode ? $CFG->coursesperpage : 5;
3552 $displayoptions = array(
3553 'limit' => $perpage,
3554 'offset' => $page * $perpage,
3555 'viewmoreurl' => null,
3558 $courserenderer = $PAGE->get_renderer('core', 'course');
3559 $totalcount = coursecat::search_courses_count(array('tagid' => $tag->id, 'ctx' => $ctx, 'rec' => $rec));
3560 $content = $courserenderer->tagged_courses($tag->id, $exclusivemode, $ctx, $rec, $displayoptions);
3561 $totalpages = ceil($totalcount / $perpage);
3563 return new core_tag\output\tagindex($tag, 'core', 'course', $content,
3564 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
3568 * Implements callback inplace_editable() allowing to edit values in-place
3570 * @param string $itemtype
3571 * @param int $itemid
3572 * @param mixed $newvalue
3573 * @return \core\output\inplace_editable
3575 function core_course_inplace_editable($itemtype, $itemid, $newvalue) {
3576 if ($itemtype === 'activityname') {
3577 return \core_course\output\course_module_name::update($itemid, $newvalue);
3582 * Returns course modules tagged with a specified tag ready for output on tag/index.php page
3584 * This is a callback used by the tag area core/course_modules to search for course modules
3585 * tagged with a specific tag.
3587 * @param core_tag_tag $tag
3588 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
3589 * are displayed on the page and the per-page limit may be bigger
3590 * @param int $fromcontextid context id where the link was displayed, may be used by callbacks
3591 * to display items in the same context first
3592 * @param int $contextid context id where to search for records
3593 * @param bool $recursivecontext search in subcontexts as well
3594 * @param int $page 0-based number of page being displayed
3595 * @return \core_tag\output\tagindex
3597 function course_get_tagged_course_modules($tag, $exclusivemode = false, $fromcontextid = 0, $contextid = 0,
3598 $recursivecontext = 1, $page = 0) {
3599 global $OUTPUT;
3600 $perpage = $exclusivemode ? 20 : 5;
3602 // Build select query.
3603 $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
3604 $query = "SELECT cm.id AS cmid, c.id AS courseid, $ctxselect
3605 FROM {course_modules} cm
3606 JOIN {tag_instance} tt ON cm.id = tt.itemid
3607 JOIN {course} c ON cm.course = c.id
3608 JOIN {context} ctx ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
3609 WHERE tt.itemtype = :itemtype AND tt.tagid = :tagid AND tt.component = :component
3610 AND cm.deletioninprogress = 0
3611 AND c.id %COURSEFILTER% AND cm.id %ITEMFILTER%";
3613 $params = array('itemtype' => 'course_modules', 'tagid' => $tag->id, 'component' => 'core',
3614 'coursemodulecontextlevel' => CONTEXT_MODULE);
3615 if ($contextid) {
3616 $context = context::instance_by_id($contextid);
3617 $query .= $recursivecontext ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
3618 $params['contextid'] = $context->id;
3619 $params['path'] = $context->path.'/%';
3622 $query .= ' ORDER BY';
3623 if ($fromcontextid) {
3624 // In order-clause specify that modules from inside "fromctx" context should be returned first.
3625 $fromcontext = context::instance_by_id($fromcontextid);
3626 $query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
3627 $params['fromcontextid'] = $fromcontext->id;
3628 $params['frompath'] = $fromcontext->path.'/%';
3630 $query .= ' c.sortorder, cm.id';
3631 $totalpages = $page + 1;
3633 // Use core_tag_index_builder to build and filter the list of items.
3634 // Request one item more than we need so we know if next page exists.
3635 $builder = new core_tag_index_builder('core', 'course_modules', $query, $params, $page * $perpage, $perpage + 1);
3636 while ($item = $builder->has_item_that_needs_access_check()) {
3637 context_helper::preload_from_record($item);
3638 $courseid = $item->courseid;
3639 if (!$builder->can_access_course($courseid)) {
3640 $builder->set_accessible($item, false);
3641 continue;
3643 $modinfo = get_fast_modinfo($builder->get_course($courseid));
3644 // Set accessibility of this item and all other items in the same course.
3645 $builder->walk(function ($taggeditem) use ($courseid, $modinfo, $builder) {
3646 if ($taggeditem->courseid == $courseid) {
3647 $cm = $modinfo->get_cm($taggeditem->cmid);
3648 $builder->set_accessible($taggeditem, $cm->uservisible);
3653 $items = $builder->get_items();
3654 if (count($items) > $perpage) {
3655 $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
3656 array_pop($items);
3659 // Build the display contents.
3660 if ($items) {
3661 $tagfeed = new core_tag\output\tagfeed();
3662 foreach ($items as $item) {
3663 context_helper::preload_from_record($item);
3664 $course = $builder->get_course($item->courseid);
3665 $modinfo = get_fast_modinfo($course);
3666 $cm = $modinfo->get_cm($item->cmid);
3667 $courseurl = course_get_url($item->courseid, $cm->sectionnum);
3668 $cmname = $cm->get_formatted_name();
3669 if (!$exclusivemode) {
3670 $cmname = shorten_text($cmname, 100);
3672 $cmname = html_writer::link($cm->url?:$courseurl, $cmname);
3673 $coursename = format_string($course->fullname, true,
3674 array('context' => context_course::instance($item->courseid)));
3675 $coursename = html_writer::link($courseurl, $coursename);
3676 $icon = html_writer::empty_tag('img', array('src' => $cm->get_icon_url()));
3677 $tagfeed->add($icon, $cmname, $coursename);
3680 $content = $OUTPUT->render_from_template('core_tag/tagfeed',
3681 $tagfeed->export_for_template($OUTPUT));
3683 return new core_tag\output\tagindex($tag, 'core', 'course_modules', $content,
3684 $exclusivemode, $fromcontextid, $contextid, $recursivecontext, $page, $totalpages);
3689 * Return an object with the list of navigation options in a course that are avaialable or not for the current user.
3690 * This function also handles the frontpage course.
3692 * @param stdClass $context context object (it can be a course context or the system context for frontpage settings)
3693 * @param stdClass $course the course where the settings are being rendered
3694 * @return stdClass the navigation options in a course and their availability status
3695 * @since Moodle 3.2
3697 function course_get_user_navigation_options($context, $course = null) {
3698 global $CFG;
3700 $isloggedin = isloggedin();
3701 $isguestuser = isguestuser();
3702 $isfrontpage = $context->contextlevel == CONTEXT_SYSTEM;
3704 if ($isfrontpage) {
3705 $sitecontext = $context;
3706 } else {
3707 $sitecontext = context_system::instance();
3710 // Sets defaults for all options.
3711 $options = (object) [
3712 'badges' => false,
3713 'blogs' => false,
3714 'calendar' => false,
3715 'competencies' => false,
3716 'grades' => false,
3717 'notes' => false,
3718 'participants' => false,
3719 'search' => false,
3720 'tags' => false,
3723 $options->blogs = !empty($CFG->enableblogs) &&
3724 ($CFG->bloglevel == BLOG_GLOBAL_LEVEL ||
3725 ($CFG->bloglevel == BLOG_SITE_LEVEL and ($isloggedin and !$isguestuser)))
3726 && has_capability('moodle/blog:view', $sitecontext);
3728 $options->notes = !empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $context);
3730 // Frontpage settings?
3731 if ($isfrontpage) {
3732 if ($course->id == SITEID) {
3733 $options->participants = has_capability('moodle/site:viewparticipants', $sitecontext);
3734 } else {
3735 $options->participants = has_capability('moodle/course:viewparticipants', context_course::instance($course->id));
3738 $options->badges = !empty($CFG->enablebadges) && has_capability('moodle/badges:viewbadges', $sitecontext);
3739 $options->tags = !empty($CFG->usetags) && $isloggedin;
3740 $options->search = !empty($CFG->enableglobalsearch) && has_capability('moodle/search:query', $sitecontext);
3741 $options->calendar = $isloggedin;
3742 } else {
3743 $options->participants = has_capability('moodle/course:viewparticipants', $context);
3744 $options->badges = !empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) &&
3745 has_capability('moodle/badges:viewbadges', $context);
3746 // Add view grade report is permitted.
3747 $grades = false;
3749 if (has_capability('moodle/grade:viewall', $context)) {
3750 $grades = true;
3751 } else if (!empty($course->showgrades)) {
3752 $reports = core_component::get_plugin_list('gradereport');
3753 if (is_array($reports) && count($reports) > 0) { // Get all installed reports.
3754 arsort($reports); // User is last, we want to test it first.
3755 foreach ($reports as $plugin => $plugindir) {
3756 if (has_capability('gradereport/'.$plugin.':view', $context)) {
3757 // Stop when the first visible plugin is found.
3758 $grades = true;
3759 break;
3764 $options->grades = $grades;
3767 if (\core_competency\api::is_enabled()) {
3768 $capabilities = array('moodle/competency:coursecompetencyview', 'moodle/competency:coursecompetencymanage');
3769 $options->competencies = has_any_capability($capabilities, $context);
3771 return $options;
3775 * Return an object with the list of administration options in a course that are available or not for the current user.
3776 * This function also handles the frontpage settings.
3778 * @param stdClass $course course object (for frontpage it should be a clone of $SITE)
3779 * @param stdClass $context context object (course context)
3780 * @return stdClass the administration options in a course and their availability status
3781 * @since Moodle 3.2
3783 function course_get_user_administration_options($course, $context) {
3784 global $CFG;
3785 $isfrontpage = $course->id == SITEID;
3787 $options = new stdClass;
3788 $options->update = has_capability('moodle/course:update', $context);
3789 $options->filters = has_capability('moodle/filter:manage', $context) &&
3790 count(filter_get_available_in_context($context)) > 0;
3791 $options->reports = has_capability('moodle/site:viewreports', $context);
3792 $options->backup = has_capability('moodle/backup:backupcourse', $context);
3793 $options->restore = has_capability('moodle/restore:restorecourse', $context);
3794 $options->files = ($course->legacyfiles == 2 && has_capability('moodle/course:managefiles', $context));
3796 if (!$isfrontpage) {
3797 $options->tags = has_capability('moodle/course:tag', $context);
3798 $options->gradebook = has_capability('moodle/grade:manage', $context);
3799 $options->outcomes = !empty($CFG->enableoutcomes) && has_capability('moodle/course:update', $context);
3800 $options->badges = !empty($CFG->enablebadges);
3801 $options->import = has_capability('moodle/restore:restoretargetimport', $context);
3802 $options->publish = has_capability('moodle/course:publish', $context);
3803 $options->reset = has_capability('moodle/course:reset', $context);
3804 $options->roles = has_capability('moodle/role:switchroles', $context);
3805 } else {
3806 // Set default options to false.
3807 $listofoptions = array('tags', 'gradebook', 'outcomes', 'badges', 'import', 'publish', 'reset', 'roles', 'grades');
3809 foreach ($listofoptions as $option) {
3810 $options->$option = false;
3814 return $options;
3818 * Validates course start and end dates.
3820 * Checks that the end course date is not greater than the start course date.
3822 * $coursedata['startdate'] or $coursedata['enddate'] may not be set, it depends on the form and user input.
3824 * @param array $coursedata May contain startdate and enddate timestamps, depends on the user input.
3825 * @return mixed False if everything alright, error codes otherwise.
3827 function course_validate_dates($coursedata) {
3829 // If both start and end dates are set end date should be later than the start date.
3830 if (!empty($coursedata['startdate']) && !empty($coursedata['enddate']) &&
3831 ($coursedata['enddate'] < $coursedata['startdate'])) {
3832 return 'enddatebeforestartdate';
3835 // If start date is not set end date can not be set.
3836 if (empty($coursedata['startdate']) && !empty($coursedata['enddate'])) {
3837 return 'nostartdatenoenddate';
3840 return false;
3844 * Check for course updates in the given context level instances (only modules supported right Now)
3846 * @param stdClass $course course object
3847 * @param array $tocheck instances to check for updates
3848 * @param array $filter check only for updates in these areas
3849 * @return array list of warnings and instances with updates information
3850 * @since Moodle 3.2
3852 function course_check_updates($course, $tocheck, $filter = array()) {
3853 global $CFG, $DB;
3855 $instances = array();
3856 $warnings = array();
3857 $modulescallbacksupport = array();
3858 $modinfo = get_fast_modinfo($course);
3860 $supportedplugins = get_plugin_list_with_function('mod', 'check_updates_since');
3862 // Check instances.
3863 foreach ($tocheck as $instance) {
3864 if ($instance['contextlevel'] == 'module') {
3865 // Check module visibility.
3866 try {
3867 $cm = $modinfo->get_cm($instance['id']);
3868 } catch (Exception $e) {
3869 $warnings[] = array(
3870 'item' => 'module',
3871 'itemid' => $instance['id'],
3872 'warningcode' => 'cmidnotincourse',
3873 'message' => 'This module id does not belong to this course.'
3875 continue;
3878 if (!$cm->uservisible) {
3879 $warnings[] = array(
3880 'item' => 'module',
3881 'itemid' => $instance['id'],
3882 'warningcode' => 'nonuservisible',
3883 'message' => 'You don\'t have access to this module.'
3885 continue;
3887 if (empty($supportedplugins['mod_' . $cm->modname])) {
3888 $warnings[] = array(
3889 'item' => 'module',
3890 'itemid' => $instance['id'],
3891 'warningcode' => 'missingcallback',
3892 'message' => 'This module does not implement the check_updates_since callback: ' . $instance['contextlevel'],
3894 continue;
3896 // Retrieve the module instance.
3897 $instances[] = array(
3898 'contextlevel' => $instance['contextlevel'],
3899 'id' => $instance['id'],
3900 'updates' => call_user_func($cm->modname . '_check_updates_since', $cm, $instance['since'], $filter)
3903 } else {
3904 $warnings[] = array(
3905 'item' => 'contextlevel',
3906 'itemid' => $instance['id'],
3907 'warningcode' => 'contextlevelnotsupported',
3908 'message' => 'Context level not yet supported ' . $instance['contextlevel'],
3912 return array($instances, $warnings);
3916 * Check module updates since a given time.
3917 * This function checks for updates in the module config, file areas, completion, grades, comments and ratings.
3919 * @param cm_info $cm course module data
3920 * @param int $from the time to check
3921 * @param array $fileareas additional file ares to check
3922 * @param array $filter if we need to filter and return only selected updates
3923 * @return stdClass object with the different updates
3924 * @since Moodle 3.2
3926 function course_check_module_updates_since($cm, $from, $fileareas = array(), $filter = array()) {
3927 global $DB, $CFG, $USER;
3929 $context = $cm->context;
3930 $mod = $DB->get_record($cm->modname, array('id' => $cm->instance), '*', MUST_EXIST);
3932 $updates = new stdClass();
3933 $course = get_course($cm->course);
3934 $component = 'mod_' . $cm->modname;
3936 // Check changes in the module configuration.
3937 if (isset($mod->timemodified) and (empty($filter) or in_array('configuration', $filter))) {
3938 $updates->configuration = (object) array('updated' => false);
3939 if ($updates->configuration->updated = $mod->timemodified > $from) {
3940 $updates->configuration->timeupdated = $mod->timemodified;
3944 // Check for updates in files.
3945 if (plugin_supports('mod', $cm->modname, FEATURE_MOD_INTRO)) {
3946 $fileareas[] = 'intro';
3948 if (!empty($fileareas) and (empty($filter) or in_array('fileareas', $filter))) {
3949 $fs = get_file_storage();
3950 $files = $fs->get_area_files($context->id, $component, $fileareas, false, "filearea, timemodified DESC", false, $from);
3951 foreach ($fileareas as $filearea) {
3952 $updates->{$filearea . 'files'} = (object) array('updated' => false);
3954 foreach ($files as $file) {
3955 $updates->{$file->get_filearea() . 'files'}->updated = true;
3956 $updates->{$file->get_filearea() . 'files'}->itemids[] = $file->get_id();
3960 // Check completion.
3961 $supportcompletion = plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES);
3962 $supportcompletion = $supportcompletion or plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_TRACKS_VIEWS);
3963 if ($supportcompletion and (empty($filter) or in_array('completion', $filter))) {
3964 $updates->completion = (object) array('updated' => false);
3965 $completion = new completion_info($course);
3966 // Use wholecourse to cache all the modules the first time.
3967 $completiondata = $completion->get_data($cm, true);
3968 if ($updates->completion->updated = !empty($completiondata->timemodified) && $completiondata->timemodified > $from) {
3969 $updates->completion->timemodified = $completiondata->timemodified;
3973 // Check grades.
3974 $supportgrades = plugin_supports('mod', $cm->modname, FEATURE_GRADE_HAS_GRADE);
3975 $supportgrades = $supportgrades or plugin_supports('mod', $cm->modname, FEATURE_GRADE_OUTCOMES);
3976 if ($supportgrades and (empty($filter) or (in_array('gradeitems', $filter) or in_array('outcomes', $filter)))) {
3977 require_once($CFG->libdir . '/gradelib.php');
3978 $grades = grade_get_grades($course->id, 'mod', $cm->modname, $mod->id, $USER->id);
3980 if (empty($filter) or in_array('gradeitems', $filter)) {
3981 $updates->gradeitems = (object) array('updated' => false);
3982 foreach ($grades->items as $gradeitem) {
3983 foreach ($gradeitem->grades as $grade) {
3984 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
3985 $updates->gradeitems->updated = true;
3986 $updates->gradeitems->itemids[] = $gradeitem->id;
3992 if (empty($filter) or in_array('outcomes', $filter)) {
3993 $updates->outcomes = (object) array('updated' => false);
3994 foreach ($grades->outcomes as $outcome) {
3995 foreach ($outcome->grades as $grade) {
3996 if ($grade->datesubmitted > $from or $grade->dategraded > $from) {
3997 $updates->outcomes->updated = true;
3998 $updates->outcomes->itemids[] = $outcome->id;
4005 // Check comments.
4006 if (plugin_supports('mod', $cm->modname, FEATURE_COMMENT) and (empty($filter) or in_array('comments', $filter))) {
4007 $updates->comments = (object) array('updated' => false);
4008 require_once($CFG->dirroot . '/comment/lib.php');
4009 require_once($CFG->dirroot . '/comment/locallib.php');
4010 $manager = new comment_manager();
4011 $comments = $manager->get_component_comments_since($course, $context, $component, $from, $cm);
4012 if (!empty($comments)) {
4013 $updates->comments->updated = true;
4014 $updates->comments->itemids = array_keys($comments);
4018 // Check ratings.
4019 if (plugin_supports('mod', $cm->modname, FEATURE_RATE) and (empty($filter) or in_array('ratings', $filter))) {
4020 $updates->ratings = (object) array('updated' => false);
4021 require_once($CFG->dirroot . '/rating/lib.php');
4022 $manager = new rating_manager();
4023 $ratings = $manager->get_component_ratings_since($context, $component, $from);
4024 if (!empty($ratings)) {
4025 $updates->ratings->updated = true;
4026 $updates->ratings->itemids = array_keys($ratings);
4030 return $updates;