MDL-57898 customfield: Set the handler's parent context in course_create
[moodle.git] / course / lib.php
CommitLineData
d9cb06dc 1<?php
d9cb06dc 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Library of useful functions
19 *
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5dc361e1 22 * @package core_course
d9cb06dc 23 */
f9903ed0 24
df997f84
PS
25defined('MOODLE_INTERNAL') || die;
26
4e781c7b 27require_once($CFG->libdir.'/completionlib.php');
8bdc9cac 28require_once($CFG->libdir.'/filelib.php');
160e77f9 29require_once($CFG->libdir.'/datalib.php');
ee7084e9 30require_once($CFG->dirroot.'/course/format/lib.php');
f9903ed0 31
5dc361e1
SH
32define('COURSE_MAX_LOGS_PER_PAGE', 1000); // Records.
33define('COURSE_MAX_RECENT_PERIOD', 172800); // Two days, in seconds.
3b7bfbb5
FM
34
35/**
36 * Number of courses to display when summaries are included.
37 * @var int
38 * @deprecated since 2.4, use $CFG->courseswithsummarieslimit instead.
39 */
40define('COURSE_MAX_SUMMARIES_PER_PAGE', 10);
41
5dc361e1
SH
42// Max courses in log dropdown before switching to optional.
43define('COURSE_MAX_COURSES_PER_DROPDOWN', 1000);
44// Max users in log dropdown before switching to optional.
45define('COURSE_MAX_USERS_PER_DROPDOWN', 1000);
46define('FRONTPAGENEWS', '0');
5dc361e1 47define('FRONTPAGECATEGORYNAMES', '2');
5dc361e1 48define('FRONTPAGECATEGORYCOMBO', '4');
0fd26350 49define('FRONTPAGEENROLLEDCOURSELIST', '5');
5dc361e1
SH
50define('FRONTPAGEALLCOURSELIST', '6');
51define('FRONTPAGECOURSESEARCH', '7');
52// Important! Replaced with $CFG->frontpagecourselimit - maximum number of courses displayed on the frontpage.
6f24e48e 53define('EXCELROWS', 65535);
54define('FIRSTUSEDEXCELROW', 3);
60fdc714 55
89bfeee0 56define('MOD_CLASS_ACTIVITY', 0);
57define('MOD_CLASS_RESOURCE', 1);
58
6481a21f 59define('COURSE_TIMELINE_ALL', 'all');
d07373f2
DW
60define('COURSE_TIMELINE_PAST', 'past');
61define('COURSE_TIMELINE_INPROGRESS', 'inprogress');
62define('COURSE_TIMELINE_FUTURE', 'future');
3cfff885 63define('COURSE_FAVOURITES', 'favourites');
e6f03948 64define('COURSE_TIMELINE_HIDDEN', 'hidden');
2c1d19fd 65define('COURSE_DB_QUERY_LIMIT', 1000);
d07373f2 66
600149be 67function make_log_url($module, $url) {
68 switch ($module) {
bd7be234 69 case 'course':
d48f6068 70 if (strpos($url, 'report/') === 0) {
3ce3bb88 71 // there is only one report type, course reports are deprecated
d48f6068
PS
72 $url = "/$url";
73 break;
74 }
bd7be234 75 case 'file':
76 case 'login':
77 case 'lib':
78 case 'admin':
95d1d037 79 case 'category':
bd5d0ce5 80 case 'mnet course':
11003188 81 if (strpos($url, '../') === 0) {
82 $url = ltrim($url, '.');
83 } else {
84 $url = "/course/$url";
85 }
bd5d0ce5 86 break;
e662454a
AA
87 case 'calendar':
88 $url = "/calendar/$url";
89 break;
01d5d399 90 case 'user':
bd7be234 91 case 'blog':
11003188 92 $url = "/$module/$url";
600149be 93 break;
bd7be234 94 case 'upload':
11003188 95 $url = $url;
c80b7585 96 break;
38fb8190 97 case 'coursetags':
11003188 98 $url = '/'.$url;
38fb8190 99 break;
bd7be234 100 case 'library':
101 case '':
11003188 102 $url = '/';
de2dfe68 103 break;
4597d533 104 case 'message':
11003188 105 $url = "/message/$url";
106 break;
107 case 'notes':
108 $url = "/notes/$url";
4597d533 109 break;
b89e4ad8 110 case 'tag':
111 $url = "/tag/$url";
112 break;
dbcf271b 113 case 'role':
114 $url = '/'.$url;
115 break;
afd2efc0
AD
116 case 'grade':
117 $url = "/grade/$url";
118 break;
600149be 119 default:
11003188 120 $url = "/mod/$module/$url";
600149be 121 break;
122 }
11003188 123
124 //now let's sanitise urls - there might be some ugly nasties:-(
125 $parts = explode('?', $url);
126 $script = array_shift($parts);
127 if (strpos($script, 'http') === 0) {
128 $script = clean_param($script, PARAM_URL);
129 } else {
130 $script = clean_param($script, PARAM_PATH);
131 }
132
133 $query = '';
134 if ($parts) {
135 $query = implode('', $parts);
136 $query = str_replace('&amp;', '&', $query); // both & and &amp; are stored in db :-|
137 $parts = explode('&', $query);
138 $eq = urlencode('=');
139 foreach ($parts as $key=>$part) {
140 $part = urlencode(urldecode($part));
141 $part = str_replace($eq, '=', $part);
142 $parts[$key] = $part;
143 }
144 $query = '?'.implode('&amp;', $parts);
145 }
146
147 return $script.$query;
600149be 148}
149
92890025 150
c215b32b 151function build_mnet_logs_array($hostid, $course, $user=0, $date=0, $order="l.time ASC", $limitfrom='', $limitnum='',
152 $modname="", $modid=0, $modaction="", $groupid=0) {
cb6fec1f 153 global $CFG, $DB;
c215b32b 154
155 // It is assumed that $date is the GMT time of midnight for that day,
156 // and so the next 86400 seconds worth of logs are printed.
157
158 /// Setup for group handling.
238c0dd9 159
160 // TODO: I don't understand group/context/etc. enough to be able to do
c215b32b 161 // something interesting with it here
162 // What is the context of a remote course?
238c0dd9 163
c215b32b 164 /// If the group mode is separate, and this user does not have editing privileges,
165 /// then only the user's group can be viewed.
9a5e297b 166 //if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/course:managegroups', context_course::instance($course->id))) {
c215b32b 167 // $groupid = get_current_group($course->id);
168 //}
169 /// If this course doesn't have groups, no groupid can be specified.
170 //else if (!$course->groupmode) {
171 // $groupid = 0;
172 //}
cb6fec1f 173
c215b32b 174 $groupid = 0;
175
176 $joins = array();
92701024 177 $where = '';
c215b32b 178
cb6fec1f 179 $qry = "SELECT l.*, u.firstname, u.lastname, u.picture
180 FROM {mnet_log} l
181 LEFT JOIN {user} u ON l.userid = u.id
182 WHERE ";
183 $params = array();
184
185 $where .= "l.hostid = :hostid";
186 $params['hostid'] = $hostid;
c215b32b 187
188 // TODO: Is 1 really a magic number referring to the sitename?
cb6fec1f 189 if ($course != SITEID || $modid != 0) {
190 $where .= " AND l.course=:courseid";
191 $params['courseid'] = $course;
c215b32b 192 }
193
194 if ($modname) {
cb6fec1f 195 $where .= " AND l.module = :modname";
196 $params['modname'] = $modname;
c215b32b 197 }
198
199 if ('site_errors' === $modid) {
cb6fec1f 200 $where .= " AND ( l.action='error' OR l.action='infected' )";
c215b32b 201 } else if ($modid) {
238c0dd9 202 //TODO: This assumes that modids are the same across sites... probably
c215b32b 203 //not true
cb6fec1f 204 $where .= " AND l.cmid = :modid";
205 $params['modid'] = $modid;
c215b32b 206 }
207
208 if ($modaction) {
209 $firstletter = substr($modaction, 0, 1);
8086b083 210 if ($firstletter == '-') {
47586394 211 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false, true, true);
8086b083
PS
212 $params['modaction'] = '%'.substr($modaction, 1).'%';
213 } else {
214 $where .= " AND ".$DB->sql_like('l.action', ':modaction', false);
215 $params['modaction'] = '%'.$modaction.'%';
c215b32b 216 }
217 }
218
219 if ($user) {
cb6fec1f 220 $where .= " AND l.userid = :user";
221 $params['user'] = $user;
c215b32b 222 }
223
224 if ($date) {
225 $enddate = $date + 86400;
cb6fec1f 226 $where .= " AND l.time > :date AND l.time < :enddate";
227 $params['date'] = $date;
228 $params['enddate'] = $enddate;
c215b32b 229 }
230
231 $result = array();
cb6fec1f 232 $result['totalcount'] = $DB->count_records_sql("SELECT COUNT('x') FROM {mnet_log} l WHERE $where", $params);
c215b32b 233 if(!empty($result['totalcount'])) {
cb6fec1f 234 $where .= " ORDER BY $order";
235 $result['logs'] = $DB->get_records_sql("$qry $where", $params, $limitfrom, $limitnum);
c215b32b 236 } else {
237 $result['logs'] = array();
238 }
239 return $result;
240}
241
749ce98e
DW
242/**
243 * Checks the integrity of the course data.
244 *
245 * In summary - compares course_sections.sequence and course_modules.section.
246 *
247 * More detailed, checks that:
248 * - course_sections.sequence contains each module id not more than once in the course
249 * - for each moduleid from course_sections.sequence the field course_modules.section
250 * refers to the same section id (this means course_sections.sequence is more
251 * important if they are different)
252 * - ($fullcheck only) each module in the course is present in one of
253 * course_sections.sequence
254 * - ($fullcheck only) removes non-existing course modules from section sequences
255 *
256 * If there are any mismatches, the changes are made and records are updated in DB.
257 *
258 * Course cache is NOT rebuilt if there are any errors!
259 *
260 * This function is used each time when course cache is being rebuilt with $fullcheck = false
261 * and in CLI script admin/cli/fix_course_sequence.php with $fullcheck = true
262 *
263 * @param int $courseid id of the course
264 * @param array $rawmods result of funciton {@link get_course_mods()} - containst
265 * the list of enabled course modules in the course. Retrieved from DB if not specified.
266 * Argument ignored in cashe of $fullcheck, the list is retrieved form DB anyway.
267 * @param array $sections records from course_sections table for this course.
268 * Retrieved from DB if not specified
269 * @param bool $fullcheck Will add orphaned modules to their sections and remove non-existing
270 * course modules from sequences. Only to be used in site maintenance mode when we are
271 * sure that another user is not in the middle of the process of moving/removing a module.
272 * @param bool $checkonly Only performs the check without updating DB, outputs all errors as debug messages.
273 * @return array array of messages with found problems. Empty output means everything is ok
274 */
275function course_integrity_check($courseid, $rawmods = null, $sections = null, $fullcheck = false, $checkonly = false) {
276 global $DB;
277 $messages = array();
278 if ($sections === null) {
279 $sections = $DB->get_records('course_sections', array('course' => $courseid), 'section', 'id,section,sequence');
280 }
281 if ($fullcheck) {
282 // Retrieve all records from course_modules regardless of module type visibility.
283 $rawmods = $DB->get_records('course_modules', array('course' => $courseid), 'id', 'id,section');
284 }
285 if ($rawmods === null) {
286 $rawmods = get_course_mods($courseid);
287 }
288 if (!$fullcheck && (empty($sections) || empty($rawmods))) {
289 // If either of the arrays is empty, no modules are displayed anyway.
290 return true;
291 }
292 $debuggingprefix = 'Failed integrity check for course ['.$courseid.']. ';
293
294 // First make sure that each module id appears in section sequences only once.
295 // If it appears in several section sequences the last section wins.
296 // If it appears twice in one section sequence, the first occurence wins.
297 $modsection = array();
298 foreach ($sections as $sectionid => $section) {
299 $sections[$sectionid]->newsequence = $section->sequence;
300 if (!empty($section->sequence)) {
301 $sequence = explode(",", $section->sequence);
302 $sequenceunique = array_unique($sequence);
303 if (count($sequenceunique) != count($sequence)) {
304 // Some course module id appears in this section sequence more than once.
305 ksort($sequenceunique); // Preserve initial order of modules.
306 $sequence = array_values($sequenceunique);
307 $sections[$sectionid]->newsequence = join(',', $sequence);
308 $messages[] = $debuggingprefix.'Sequence for course section ['.
309 $sectionid.'] is "'.$sections[$sectionid]->sequence.'", must be "'.$sections[$sectionid]->newsequence.'"';
310 }
311 foreach ($sequence as $cmid) {
312 if (array_key_exists($cmid, $modsection) && isset($rawmods[$cmid])) {
313 // Some course module id appears to be in more than one section's sequences.
314 $wrongsectionid = $modsection[$cmid];
315 $sections[$wrongsectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$wrongsectionid]->newsequence. ','), ',');
316 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] must be removed from sequence of section ['.
317 $wrongsectionid.'] because it is also present in sequence of section ['.$sectionid.']';
318 }
319 $modsection[$cmid] = $sectionid;
320 }
321 }
322 }
323
324 // Add orphaned modules to their sections if they exist or to section 0 otherwise.
325 if ($fullcheck) {
326 foreach ($rawmods as $cmid => $mod) {
327 if (!isset($modsection[$cmid])) {
328 // This is a module that is not mentioned in course_section.sequence at all.
329 // Add it to the section $mod->section or to the last available section.
330 if ($mod->section && isset($sections[$mod->section])) {
331 $modsection[$cmid] = $mod->section;
332 } else {
333 $firstsection = reset($sections);
334 $modsection[$cmid] = $firstsection->id;
335 }
336 $sections[$modsection[$cmid]]->newsequence = trim($sections[$modsection[$cmid]]->newsequence.','.$cmid, ',');
337 $messages[] = $debuggingprefix.'Course module ['.$cmid.'] is missing from sequence of section ['.
e2e9cb6a 338 $modsection[$cmid].']';
749ce98e
DW
339 }
340 }
341 foreach ($modsection as $cmid => $sectionid) {
342 if (!isset($rawmods[$cmid])) {
343 // Section $sectionid refers to module id that does not exist.
344 $sections[$sectionid]->newsequence = trim(preg_replace("/,$cmid,/", ',', ','.$sections[$sectionid]->newsequence.','), ',');
345 $messages[] = $debuggingprefix.'Course module ['.$cmid.
346 '] does not exist but is present in the sequence of section ['.$sectionid.']';
347 }
348 }
349 }
350
351 // Update changed sections.
352 if (!$checkonly && !empty($messages)) {
353 foreach ($sections as $sectionid => $section) {
354 if ($section->newsequence !== $section->sequence) {
355 $DB->update_record('course_sections', array('id' => $sectionid, 'sequence' => $section->newsequence));
356 }
357 }
358 }
359
360 // Now make sure that all modules point to the correct sections.
361 foreach ($rawmods as $cmid => $mod) {
362 if (isset($modsection[$cmid]) && $modsection[$cmid] != $mod->section) {
363 if (!$checkonly) {
364 $DB->update_record('course_modules', array('id' => $cmid, 'section' => $modsection[$cmid]));
365 }
366 $messages[] = $debuggingprefix.'Course module ['.$cmid.
367 '] points to section ['.$mod->section.'] instead of ['.$modsection[$cmid].']';
368 }
369 }
370
371 return $messages;
372}
373
cb6fec1f 374/**
375 * For a given course, returns an array of course activity objects
376 * Each item in the array contains he following properties:
377 */
d897cae4 378function get_array_of_activities($courseid) {
d897cae4 379// cm - course module id
380// mod - name of the module (eg forum)
381// section - the number of the section (eg week or topic)
382// name - the name of the instance
5867bfb5 383// visible - is the instance visible or not
13534ef7 384// groupingid - grouping id
86aa7ccf 385// extra - contains extra string to include in any link
cb6fec1f 386 global $CFG, $DB;
8dddba42 387
a0c30e1b 388 $course = $DB->get_record('course', array('id'=>$courseid));
389
390 if (empty($course)) {
391 throw new moodle_exception('courseidnotfound');
392 }
393
d897cae4 394 $mod = array();
395
a0c30e1b 396 $rawmods = get_course_mods($courseid);
397 if (empty($rawmods)) {
dd97c328 398 return $mod; // always return array
d897cae4 399 }
8341055e 400 $courseformat = course_get_format($course);
d897cae4 401
8341055e
MG
402 if ($sections = $DB->get_records('course_sections', array('course' => $courseid),
403 'section ASC', 'id,section,sequence,visible')) {
749ce98e
DW
404 // First check and correct obvious mismatches between course_sections.sequence and course_modules.section.
405 if ($errormessages = course_integrity_check($courseid, $rawmods, $sections)) {
406 debugging(join('<br>', $errormessages));
407 $rawmods = get_course_mods($courseid);
8341055e
MG
408 $sections = $DB->get_records('course_sections', array('course' => $courseid),
409 'section ASC', 'id,section,sequence,visible');
749ce98e
DW
410 }
411 // Build array of activities.
d897cae4 412 foreach ($sections as $section) {
74666583 413 if (!empty($section->sequence)) {
d897cae4 414 $sequence = explode(",", $section->sequence);
415 foreach ($sequence as $seq) {
7af6281f 416 if (empty($rawmods[$seq])) {
417 continue;
418 }
8341055e
MG
419 // Adjust visibleoncoursepage, value in DB may not respect format availability.
420 $rawmods[$seq]->visibleoncoursepage = (!$rawmods[$seq]->visible
421 || $rawmods[$seq]->visibleoncoursepage
422 || empty($CFG->allowstealth)
423 || !$courseformat->allow_stealth_module_visibility($rawmods[$seq], $section)) ? 1 : 0;
424
425 // Create an object that will be cached.
b85b25eb 426 $mod[$seq] = new stdClass();
dd97c328 427 $mod[$seq]->id = $rawmods[$seq]->instance;
428 $mod[$seq]->cm = $rawmods[$seq]->id;
429 $mod[$seq]->mod = $rawmods[$seq]->modname;
adaeccb6 430
431 // Oh dear. Inconsistent names left here for backward compatibility.
dd97c328 432 $mod[$seq]->section = $section->section;
adaeccb6 433 $mod[$seq]->sectionid = $rawmods[$seq]->section;
434
435 $mod[$seq]->module = $rawmods[$seq]->module;
436 $mod[$seq]->added = $rawmods[$seq]->added;
437 $mod[$seq]->score = $rawmods[$seq]->score;
66b250fd 438 $mod[$seq]->idnumber = $rawmods[$seq]->idnumber;
dd97c328 439 $mod[$seq]->visible = $rawmods[$seq]->visible;
8341055e 440 $mod[$seq]->visibleoncoursepage = $rawmods[$seq]->visibleoncoursepage;
adaeccb6 441 $mod[$seq]->visibleold = $rawmods[$seq]->visibleold;
dd97c328 442 $mod[$seq]->groupmode = $rawmods[$seq]->groupmode;
443 $mod[$seq]->groupingid = $rawmods[$seq]->groupingid;
82bd6a5e 444 $mod[$seq]->indent = $rawmods[$seq]->indent;
445 $mod[$seq]->completion = $rawmods[$seq]->completion;
dd97c328 446 $mod[$seq]->extra = "";
adaeccb6 447 $mod[$seq]->completiongradeitemnumber =
448 $rawmods[$seq]->completiongradeitemnumber;
449 $mod[$seq]->completionview = $rawmods[$seq]->completionview;
450 $mod[$seq]->completionexpected = $rawmods[$seq]->completionexpected;
8c40662e 451 $mod[$seq]->showdescription = $rawmods[$seq]->showdescription;
8d1f33e1 452 $mod[$seq]->availability = $rawmods[$seq]->availability;
3869d774 453 $mod[$seq]->deletioninprogress = $rawmods[$seq]->deletioninprogress;
8dddba42 454
455 $modname = $mod[$seq]->mod;
456 $functionname = $modname."_get_coursemodule_info";
457
3a37b3f8 458 if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
459 continue;
460 }
461
8dddba42 462 include_once("$CFG->dirroot/mod/$modname/lib.php");
463
b3a89232 464 if ($hasfunction = function_exists($functionname)) {
9d361034 465 if ($info = $functionname($rawmods[$seq])) {
9d361034 466 if (!empty($info->icon)) {
467 $mod[$seq]->icon = $info->icon;
468 }
9a9012dc
PS
469 if (!empty($info->iconcomponent)) {
470 $mod[$seq]->iconcomponent = $info->iconcomponent;
471 }
1ea543df 472 if (!empty($info->name)) {
9a9012dc 473 $mod[$seq]->name = $info->name;
1ea543df 474 }
0d8b6a69 475 if ($info instanceof cached_cm_info) {
476 // When using cached_cm_info you can include three new fields
477 // that aren't available for legacy code
478 if (!empty($info->content)) {
479 $mod[$seq]->content = $info->content;
480 }
481 if (!empty($info->extraclasses)) {
482 $mod[$seq]->extraclasses = $info->extraclasses;
483 }
c443a1cd 484 if (!empty($info->iconurl)) {
4fcdb012
MG
485 // Convert URL to string as it's easier to store. Also serialized object contains \0 byte and can not be written to Postgres DB.
486 $url = new moodle_url($info->iconurl);
487 $mod[$seq]->iconurl = $url->out(false);
c443a1cd 488 }
0d8b6a69 489 if (!empty($info->onclick)) {
490 $mod[$seq]->onclick = $info->onclick;
491 }
492 if (!empty($info->customdata)) {
493 $mod[$seq]->customdata = $info->customdata;
494 }
495 } else {
496 // When using a stdclass, the (horrible) deprecated ->extra field
497 // is available for BC
498 if (!empty($info->extra)) {
499 $mod[$seq]->extra = $info->extra;
500 }
501 }
c9f6251e 502 }
503 }
b3a89232 504 // When there is no modname_get_coursemodule_info function,
505 // but showdescriptions is enabled, then we use the 'intro'
506 // and 'introformat' fields in the module table
507 if (!$hasfunction && $rawmods[$seq]->showdescription) {
508 if ($modvalues = $DB->get_record($rawmods[$seq]->modname,
509 array('id' => $rawmods[$seq]->instance), 'name, intro, introformat')) {
510 // Set content from intro and introformat. Filters are disabled
511 // because we filter it with format_text at display time
512 $mod[$seq]->content = format_module_intro($rawmods[$seq]->modname,
513 $modvalues, $rawmods[$seq]->id, false);
514
515 // To save making another query just below, put name in here
516 $mod[$seq]->name = $modvalues->name;
517 }
518 }
1ea543df 519 if (!isset($mod[$seq]->name)) {
9a9012dc 520 $mod[$seq]->name = $DB->get_field($rawmods[$seq]->modname, "name", array("id"=>$rawmods[$seq]->instance));
1ea543df 521 }
0d8b6a69 522
061e6b28 523 // Minimise the database size by unsetting default options when they are
524 // 'empty'. This list corresponds to code in the cm_info constructor.
525 foreach (array('idnumber', 'groupmode', 'groupingid',
526 'indent', 'completion', 'extra', 'extraclasses', 'iconurl', 'onclick', 'content',
527 'icon', 'iconcomponent', 'customdata', 'availability', 'completionview',
3869d774 528 'completionexpected', 'score', 'showdescription', 'deletioninprogress') as $property) {
0d8b6a69 529 if (property_exists($mod[$seq], $property) &&
530 empty($mod[$seq]->{$property})) {
531 unset($mod[$seq]->{$property});
532 }
533 }
adaeccb6 534 // Special case: this value is usually set to null, but may be 0
535 if (property_exists($mod[$seq], 'completiongradeitemnumber') &&
536 is_null($mod[$seq]->completiongradeitemnumber)) {
537 unset($mod[$seq]->completiongradeitemnumber);
538 }
d897cae4 539 }
540 }
541 }
542 }
543 return $mod;
544}
545
cb6fec1f 546/**
d57aa283
MG
547 * Returns the localised human-readable names of all used modules
548 *
549 * @param bool $plural if true returns the plural forms of the names
550 * @return array where key is the module name (component name without 'mod_') and
551 * the value is the human-readable string. Array sorted alphabetically by value
cb6fec1f 552 */
d57aa283
MG
553function get_module_types_names($plural = false) {
554 static $modnames = null;
555 global $DB, $CFG;
556 if ($modnames === null) {
557 $modnames = array(0 => array(), 1 => array());
558 if ($allmods = $DB->get_records("modules")) {
559 foreach ($allmods as $mod) {
560 if (file_exists("$CFG->dirroot/mod/$mod->name/lib.php") && $mod->visible) {
561 $modnames[0][$mod->name] = get_string("modulename", "$mod->name");
562 $modnames[1][$mod->name] = get_string("modulenameplural", "$mod->name");
563 }
13534ef7 564 }
2f1e464a
PS
565 core_collator::asort($modnames[0]);
566 core_collator::asort($modnames[1]);
c7da6f7a 567 }
7468bf01 568 }
d57aa283 569 return $modnames[(int)$plural];
7468bf01 570}
571
93d46f48
RK
572/**
573 * Set highlighted section. Only one section can be highlighted at the time.
574 *
575 * @param int $courseid course id
576 * @param int $marker highlight section with this number, 0 means remove higlightin
577 * @return void
578 */
579function course_set_marker($courseid, $marker) {
8341055e 580 global $DB, $COURSE;
93d46f48 581 $DB->set_field("course", "marker", $marker, array('id' => $courseid));
8341055e
MG
582 if ($COURSE && $COURSE->id == $courseid) {
583 $COURSE->marker = $marker;
584 }
585 if (class_exists('format_base')) {
586 format_base::reset_course_cache($courseid);
587 }
588 course_modinfo::clear_instance_cache($courseid);
93d46f48
RK
589}
590
cb6fec1f 591/**
7e85563d 592 * For a given course section, marks it visible or hidden,
cb6fec1f 593 * and does the same for every activity in that section
ebaa29d1
ARN
594 *
595 * @param int $courseid course id
596 * @param int $sectionnumber The section number to adjust
597 * @param int $visibility The new visibility
598 * @return array A list of resources which were hidden in the section
cb6fec1f 599 */
7d99d695 600function set_section_visible($courseid, $sectionnumber, $visibility) {
cb6fec1f 601 global $DB;
7d99d695 602
ebaa29d1 603 $resourcestotoggle = array();
cb6fec1f 604 if ($section = $DB->get_record("course_sections", array("course"=>$courseid, "section"=>$sectionnumber))) {
f26481c2 605 course_update_section($courseid, $section, array('visible' => $visibility));
ebaa29d1
ARN
606
607 // Determine which modules are visible for AJAX update
f26481c2 608 $modules = !empty($section->sequence) ? explode(',', $section->sequence) : array();
ebaa29d1
ARN
609 if (!empty($modules)) {
610 list($insql, $params) = $DB->get_in_or_equal($modules);
611 $select = 'id ' . $insql . ' AND visible = ?';
612 array_push($params, $visibility);
613 if (!$visibility) {
614 $select .= ' AND visibleold = 1';
615 }
616 $resourcestotoggle = $DB->get_fieldset_select('course_modules', 'id', $select, $params);
617 }
7d99d695 618 }
ebaa29d1 619 return $resourcestotoggle;
7d99d695 620}
ba2e5d73 621
59155a3f
ARN
622/**
623 * Retrieve all metadata for the requested modules
624 *
625 * @param object $course The Course
626 * @param array $modnames An array containing the list of modules and their
627 * names
a41b1d96 628 * @param int $sectionreturn The section to return to
59155a3f
ARN
629 * @return array A list of stdClass objects containing metadata about each
630 * module
631 */
923451c5 632function get_module_metadata($course, $modnames, $sectionreturn = null) {
9ca0420e 633 global $OUTPUT;
59155a3f
ARN
634
635 // get_module_metadata will be called once per section on the page and courses may show
636 // different modules to one another
637 static $modlist = array();
638 if (!isset($modlist[$course->id])) {
639 $modlist[$course->id] = array();
640 }
641
642 $return = array();
17079335
MG
643 $urlbase = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey()));
644 if ($sectionreturn !== null) {
645 $urlbase->param('sr', $sectionreturn);
646 }
59155a3f
ARN
647 foreach($modnames as $modname => $modnamestr) {
648 if (!course_allowed_module($course, $modname)) {
649 continue;
650 }
ad47d025 651 if (isset($modlist[$course->id][$modname])) {
59155a3f 652 // This module is already cached
9ca0420e 653 $return += $modlist[$course->id][$modname];
59155a3f
ARN
654 continue;
655 }
9ca0420e
MG
656 $modlist[$course->id][$modname] = array();
657
658 // Create an object for a default representation of this module type in the activity chooser. It will be used
659 // if module does not implement callback get_shortcuts() and it will also be passed to the callback if it exists.
660 $defaultmodule = new stdClass();
661 $defaultmodule->title = $modnamestr;
662 $defaultmodule->name = $modname;
663 $defaultmodule->link = new moodle_url($urlbase, array('add' => $modname));
664 $defaultmodule->icon = $OUTPUT->pix_icon('icon', '', $defaultmodule->name, array('class' => 'icon'));
665 $sm = get_string_manager();
666 if ($sm->string_exists('modulename_help', $modname)) {
667 $defaultmodule->help = get_string('modulename_help', $modname);
668 if ($sm->string_exists('modulename_link', $modname)) { // Link to further info in Moodle docs.
669 $link = get_string('modulename_link', $modname);
670 $linktext = get_string('morehelp');
671 $defaultmodule->help .= html_writer::tag('div',
672 $OUTPUT->doc_link($link, $linktext, true), array('class' => 'helpdoclink'));
673 }
59155a3f 674 }
9ca0420e
MG
675 $defaultmodule->archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
676
9ca0420e
MG
677 // Each module can implement callback modulename_get_shortcuts() in its lib.php and return the list
678 // of elements to be added to activity chooser.
679 $items = component_callback($modname, 'get_shortcuts', array($defaultmodule), null);
680 if ($items !== null) {
681 foreach ($items as $item) {
682 // Add all items to the return array. All items must have different links, use them as a key in the return array.
683 if (!isset($item->archetype)) {
684 $item->archetype = $defaultmodule->archetype;
685 }
686 if (!isset($item->icon)) {
687 $item->icon = $defaultmodule->icon;
688 }
689 // If plugin returned the only one item with the same link as default item - cache it as $modname,
690 // otherwise append the link url to the module name.
691 $item->name = (count($items) == 1 &&
692 $item->link->out() === $defaultmodule->link->out()) ? $modname : $modname . ':' . $item->link;
f418d899
JD
693
694 // If the module provides the helptext property, append it to the help text to match the look and feel
695 // of the default course modules.
696 if (isset($item->help) && isset($item->helplink)) {
697 $linktext = get_string('morehelp');
698 $item->help .= html_writer::tag('div',
699 $OUTPUT->doc_link($item->helplink, $linktext, true), array('class' => 'helpdoclink'));
700 }
9ca0420e
MG
701 $modlist[$course->id][$modname][$item->name] = $item;
702 }
703 $return += $modlist[$course->id][$modname];
9ca0420e
MG
704 // If get_shortcuts() callback is defined, the default module action is not added.
705 // It is a responsibility of the callback to add it to the return value unless it is not needed.
706 continue;
01e8bfd7
JO
707 }
708
4bebed40
AG
709 // The callback get_shortcuts() was not found, use the default item for the activity chooser.
710 $modlist[$course->id][$modname][$modname] = $defaultmodule;
711 $return[$modname] = $defaultmodule;
59155a3f
ARN
712 }
713
9ca0420e 714 core_collator::asort_objects_by_property($return, 'title');
59155a3f
ARN
715 return $return;
716}
717
8ed5dd63 718/**
719 * Return the course category context for the category with id $categoryid, except
720 * that if $categoryid is 0, return the system context.
721 *
722 * @param integer $categoryid a category id or 0.
5dc361e1 723 * @return context the corresponding context
8ed5dd63 724 */
725function get_category_or_system_context($categoryid) {
726 if ($categoryid) {
4658aec5 727 return context_coursecat::instance($categoryid, IGNORE_MISSING);
8ed5dd63 728 } else {
9a5e297b 729 return context_system::instance();
8ed5dd63 730 }
731}
732
cb6fec1f 733/**
4e0b6025
MG
734 * Returns full course categories trees to be used in html_writer::select()
735 *
442f12f8 736 * Calls {@link core_course_category::make_categories_list()} to build the tree and
4e0b6025
MG
737 * adds whitespace to denote nesting
738 *
442f12f8 739 * @return array array mapping course category id to the display name
cb6fec1f 740 */
0705ff84 741function make_categories_options() {
442f12f8 742 $cats = core_course_category::make_categories_list('', 0, ' / ');
0705ff84 743 foreach ($cats as $key => $value) {
a7a04f6d
MG
744 // Prefix the value with the number of spaces equal to category depth (number of separators in the value).
745 $cats[$key] = str_repeat('&nbsp;', substr_count($value, ' / ')). $value;
0705ff84 746 }
747 return $cats;
748}
c2cb4545 749
77eddcd5 750/**
751 * Print the buttons relating to course requests.
752 *
8e57a6df 753 * @param object $context current page context.
77eddcd5 754 */
8e57a6df 755function print_course_request_buttons($context) {
b4531207 756 global $CFG, $DB, $OUTPUT;
77eddcd5 757 if (empty($CFG->enablecourserequests)) {
758 return;
759 }
8e57a6df 760 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
77eddcd5 761 /// Print a button to request a new course
8e57a6df 762 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
77eddcd5 763 }
764 /// Print a button to manage pending requests
8e57a6df 765 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
5c2ed7e2 766 $disabled = !$DB->record_exists('course_request', array());
8e57a6df 767 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
77eddcd5 768 }
769}
770
5048e034 771/**
772 * Does the user have permission to edit things in this category?
773 *
774 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
775 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
776 */
777function can_edit_in_category($categoryid = 0) {
778 $context = get_category_or_system_context($categoryid);
779 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
780}
781
11b0c469 782/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
783
784function add_course_module($mod) {
cb6fec1f 785 global $DB;
11b0c469 786
e5dfd0f3 787 $mod->added = time();
53f4ad2c 788 unset($mod->id);
11b0c469 789
38b19bbc
MG
790 $cmid = $DB->insert_record("course_modules", $mod);
791 rebuild_course_cache($mod->course, true);
792 return $cmid;
11b0c469 793}
794
89b909f6
MG
795/**
796 * Creates a course section and adds it to the specified position
797 *
798 * @param int|stdClass $courseorid course id or course object
799 * @param int $position position to add to, 0 means to the end. If position is greater than
800 * number of existing secitons, the section is added to the end. This will become sectionnum of the
801 * new section. All existing sections at this or bigger position will be shifted down.
802 * @param bool $skipcheck the check has already been made and we know that the section with this position does not exist
803 * @return stdClass created section object
804 */
805function course_create_section($courseorid, $position = 0, $skipcheck = false) {
806 global $DB;
807 $courseid = is_object($courseorid) ? $courseorid->id : $courseorid;
808
809 // Find the last sectionnum among existing sections.
810 if ($skipcheck) {
811 $lastsection = $position - 1;
812 } else {
813 $lastsection = (int)$DB->get_field_sql('SELECT max(section) from {course_sections} WHERE course = ?', [$courseid]);
814 }
815
816 // First add section to the end.
817 $cw = new stdClass();
818 $cw->course = $courseid;
819 $cw->section = $lastsection + 1;
820 $cw->summary = '';
821 $cw->summaryformat = FORMAT_HTML;
822 $cw->sequence = '';
823 $cw->name = null;
824 $cw->visible = 1;
825 $cw->availability = null;
4ddf7c60 826 $cw->timemodified = time();
89b909f6
MG
827 $cw->id = $DB->insert_record("course_sections", $cw);
828
829 // Now move it to the specified position.
830 if ($position > 0 && $position <= $lastsection) {
831 $course = is_object($courseorid) ? $courseorid : get_course($courseorid);
832 move_section_to($course, $cw->section, $position, true);
833 $cw->section = $position;
834 }
835
836 core\event\course_section_created::create_from_section($cw)->trigger();
837
838 rebuild_course_cache($courseid, true);
839 return $cw;
840}
841
97928ddf 842/**
4ede27b2 843 * Creates missing course section(s) and rebuilds course cache
99e9f9a6 844 *
b46be6ad 845 * @param int|stdClass $courseorid course id or course object
4ede27b2
MG
846 * @param int|array $sections list of relative section numbers to create
847 * @return bool if there were any sections created
97928ddf 848 */
b46be6ad 849function course_create_sections_if_missing($courseorid, $sections) {
4ede27b2
MG
850 if (!is_array($sections)) {
851 $sections = array($sections);
852 }
b46be6ad 853 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
89b909f6
MG
854 if ($newsections = array_diff($sections, $existing)) {
855 foreach ($newsections as $sectionnum) {
856 course_create_section($courseorid, $sectionnum, true);
4ede27b2 857 }
89b909f6 858 return true;
4ede27b2 859 }
89b909f6 860 return false;
97928ddf 861}
52f14061 862
ece966f0 863/**
722e6ba9 864 * Adds an existing module to the section
ece966f0 865 *
722e6ba9
MG
866 * Updates both tables {course_sections} and {course_modules}
867 *
5523c344 868 * Note: This function does not use modinfo PROVIDED that the section you are
869 * adding the module to already exists. If the section does not exist, it will
870 * build modinfo if necessary and create the section.
871 *
722e6ba9 872 * @param int|stdClass $courseorid course id or course object
46453565 873 * @param int $cmid id of the module already existing in course_modules table
722e6ba9
MG
874 * @param int $sectionnum relative number of the section (field course_sections.section)
875 * If section does not exist it will be created
876 * @param int|stdClass $beforemod id or object with field id corresponding to the module
877 * before which the module needs to be included. Null for inserting in the
878 * end of the section
879 * @return int The course_sections ID where the module is inserted
ece966f0 880 */
46453565 881function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
722e6ba9
MG
882 global $DB, $COURSE;
883 if (is_object($beforemod)) {
884 $beforemod = $beforemod->id;
885 }
46453565
PS
886 if (is_object($courseorid)) {
887 $courseid = $courseorid->id;
888 } else {
889 $courseid = $courseorid;
890 }
46453565 891 // Do not try to use modinfo here, there is no guarantee it is valid!
5523c344 892 $section = $DB->get_record('course_sections',
893 array('course' => $courseid, 'section' => $sectionnum), '*', IGNORE_MISSING);
894 if (!$section) {
895 // This function call requires modinfo.
896 course_create_sections_if_missing($courseorid, $sectionnum);
897 $section = $DB->get_record('course_sections',
898 array('course' => $courseid, 'section' => $sectionnum), '*', MUST_EXIST);
899 }
900
722e6ba9 901 $modarray = explode(",", trim($section->sequence));
281d730e 902 if (empty($section->sequence)) {
46453565 903 $newsequence = "$cmid";
722e6ba9 904 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
46453565 905 $insertarray = array($cmid, $beforemod);
722e6ba9
MG
906 array_splice($modarray, $key[0], 1, $insertarray);
907 $newsequence = implode(",", $modarray);
908 } else {
46453565 909 $newsequence = "$section->sequence,$cmid";
722e6ba9
MG
910 }
911 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
46453565 912 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
b46be6ad
MG
913 if (is_object($courseorid)) {
914 rebuild_course_cache($courseorid->id, true);
915 } else {
916 rebuild_course_cache($courseorid, true);
917 }
722e6ba9 918 return $section->id; // Return course_sections ID that was used.
11b0c469 919}
920
9e533215
SL
921/**
922 * Change the group mode of a course module.
923 *
924 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
925 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
926 *
927 * @param int $id course module ID.
928 * @param int $groupmode the new groupmode value.
929 * @return bool True if the $groupmode was updated.
930 */
48e535bc 931function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 932 global $DB;
38b19bbc
MG
933 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
934 if ($cm->groupmode != $groupmode) {
935 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
936 rebuild_course_cache($cm->course, true);
937 }
938 return ($cm->groupmode != $groupmode);
3d575e6f 939}
940
177d4abf 941function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 942 global $DB;
38b19bbc
MG
943 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
944 if ($cm->idnumber != $idnumber) {
945 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
946 rebuild_course_cache($cm->course, true);
947 }
948 return ($cm->idnumber != $idnumber);
177d4abf 949}
4e781c7b 950
02f66c42 951/**
00a34234
FM
952 * Set the visibility of a module and inherent properties.
953 *
9e533215
SL
954 * Note: Do not forget to trigger the event \core\event\course_module_updated as it needs
955 * to be triggered manually, refer to {@link \core\event\course_module_updated::create_from_cm()}.
956 *
00a34234
FM
957 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
958 * has been moved to {@link set_section_visible()} which was the only place from which
959 * the parameter was used.
960 *
961 * @param int $id of the module
962 * @param int $visible state of the module
8341055e 963 * @param int $visibleoncoursepage state of the module on the course page
00a34234
FM
964 * @return bool false when the module was not found, true otherwise
965 */
8341055e 966function set_coursemodule_visible($id, $visible, $visibleoncoursepage = 1) {
f5e2602a 967 global $DB, $CFG;
0f078024 968 require_once($CFG->libdir.'/gradelib.php');
c5ceaeaf 969 require_once($CFG->dirroot.'/calendar/lib.php');
0f078024 970
cb6fec1f 971 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 972 return false;
973 }
40fcc261
AD
974
975 // Create events and propagate visibility to associated grade items if the value has changed.
976 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
8341055e 977 if ($cm->visible == $visible && $cm->visibleoncoursepage == $visibleoncoursepage) {
40fcc261
AD
978 return true;
979 }
980
cb6fec1f 981 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 982 return false;
983 }
8341055e
MG
984 if (($cm->visible != $visible) &&
985 ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename)))) {
dcd338ff 986 foreach($events as $event) {
48e535bc 987 if ($visible) {
379cd2d4
EL
988 $event = new calendar_event($event);
989 $event->toggle_visibility(true);
48e535bc 990 } else {
379cd2d4
EL
991 $event = new calendar_event($event);
992 $event->toggle_visibility(false);
48e535bc 993 }
dcd338ff 994 }
995 }
f5e2602a 996
00a34234
FM
997 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
998 // affect visibleold to allow for an original visibility restore. See set_section_visible().
999 $cminfo = new stdClass();
1000 $cminfo->id = $id;
1001 $cminfo->visible = $visible;
8341055e 1002 $cminfo->visibleoncoursepage = $visibleoncoursepage;
00a34234
FM
1003 $cminfo->visibleold = $visible;
1004 $DB->update_record('course_modules', $cminfo);
1005
1c73df9e
TH
1006 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
1007 // Note that this must be done after updating the row in course_modules, in case
1008 // the modules grade_item_update function needs to access $cm->visible.
8341055e
MG
1009 if ($cm->visible != $visible &&
1010 plugin_supports('mod', $modulename, FEATURE_CONTROLS_GRADE_VISIBILITY) &&
1c73df9e
TH
1011 component_callback_exists('mod_' . $modulename, 'grade_item_update')) {
1012 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1013 component_callback('mod_' . $modulename, 'grade_item_update', array($instance));
8341055e 1014 } else if ($cm->visible != $visible) {
1c73df9e
TH
1015 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1016 if ($grade_items) {
1017 foreach ($grade_items as $grade_item) {
1018 $grade_item->set_hidden(!$visible);
1019 }
1020 }
1021 }
1022
38b19bbc
MG
1023 rebuild_course_cache($cm->course, true);
1024 return true;
1acfbce5 1025}
1026
f59f89b4
MG
1027/**
1028 * Changes the course module name
1029 *
1030 * @param int $id course module id
1031 * @param string $name new value for a name
1032 * @return bool whether a change was made
1033 */
1034function set_coursemodule_name($id, $name) {
1035 global $CFG, $DB;
1036 require_once($CFG->libdir . '/gradelib.php');
1037
1038 $cm = get_coursemodule_from_id('', $id, 0, false, MUST_EXIST);
1039
1040 $module = new \stdClass();
1041 $module->id = $cm->instance;
1042
1043 // Escape strings as they would be by mform.
1044 if (!empty($CFG->formatstringstriptags)) {
1045 $module->name = clean_param($name, PARAM_TEXT);
1046 } else {
1047 $module->name = clean_param($name, PARAM_CLEANHTML);
1048 }
1049 if ($module->name === $cm->name || strval($module->name) === '') {
1050 return false;
1051 }
1052 if (\core_text::strlen($module->name) > 255) {
1053 throw new \moodle_exception('maximumchars', 'moodle', '', 255);
1054 }
1055
1056 $module->timemodified = time();
1057 $DB->update_record($cm->modname, $module);
1058 $cm->name = $module->name;
1059 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1060 rebuild_course_cache($cm->course, true);
1061
1062 // Attempt to update the grade item if relevant.
1063 $grademodule = $DB->get_record($cm->modname, array('id' => $cm->instance));
1064 $grademodule->cmidnumber = $cm->idnumber;
1065 $grademodule->modname = $cm->modname;
1066 grade_update_mod_grades($grademodule);
1067
9851111f 1068 // Update calendar events with the new name.
a85e191c 1069 course_module_update_calendar_events($cm->modname, $grademodule, $cm);
9851111f 1070
f59f89b4
MG
1071 return true;
1072}
1073
cb6fec1f 1074/**
7f7144fd 1075 * This function will handle the whole deletion process of a module. This includes calling
a347aee3
MN
1076 * the modules delete_instance function, deleting files, events, grades, conditional data,
1077 * the data in the course_module and course_sections table and adding a module deletion
1078 * event to the DB.
290130b3 1079 *
a347aee3 1080 * @param int $cmid the course module id
3869d774
JD
1081 * @param bool $async whether or not to try to delete the module using an adhoc task. Async also depends on a plugin hook.
1082 * @throws moodle_exception
5bcfd504 1083 * @since Moodle 2.5
290130b3 1084 */
3869d774
JD
1085function course_delete_module($cmid, $async = false) {
1086 // Check the 'course_module_background_deletion_recommended' hook first.
1087 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1088 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1089 // It's up to plugins to handle things like whether or not they are enabled.
1090 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1091 foreach ($pluginsfunction as $plugintype => $plugins) {
1092 foreach ($plugins as $pluginfunction) {
1093 if ($pluginfunction()) {
1094 return course_module_flag_for_async_deletion($cmid);
1095 }
1096 }
1097 }
1098 }
1099
63deb5c3 1100 global $CFG, $DB;
a347aee3 1101
f615fbab 1102 require_once($CFG->libdir.'/gradelib.php');
7f7144fd 1103 require_once($CFG->libdir.'/questionlib.php');
cae83708 1104 require_once($CFG->dirroot.'/blog/lib.php');
c5ceaeaf 1105 require_once($CFG->dirroot.'/calendar/lib.php');
f615fbab 1106
a347aee3
MN
1107 // Get the course module.
1108 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
290130b3 1109 return true;
1110 }
a347aee3
MN
1111
1112 // Get the module context.
1113 $modcontext = context_module::instance($cm->id);
1114
1115 // Get the course module name.
1116 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1117
1118 // Get the file location of the delete_instance function for this module.
1119 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1120
1121 // Include the file required to call the delete_instance function for this module.
1122 if (file_exists($modlib)) {
1123 require_once($modlib);
1124 } else {
9a9cb741
MN
1125 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1126 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
a347aee3
MN
1127 }
1128
9a9cb741 1129 $deleteinstancefunction = $modulename . '_delete_instance';
a347aee3 1130
9a9cb741
MN
1131 // Ensure the delete_instance function exists for this module.
1132 if (!function_exists($deleteinstancefunction)) {
1133 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1134 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1135 }
1136
ea88fd4e
MN
1137 // Allow plugins to use this course module before we completely delete it.
1138 if ($pluginsfunction = get_plugins_with_function('pre_course_module_delete')) {
1139 foreach ($pluginsfunction as $plugintype => $plugins) {
1140 foreach ($plugins as $pluginfunction) {
1141 $pluginfunction($cm);
1142 }
1143 }
1144 }
1145
7f7144fd
TB
1146 // Delete activity context questions and question categories.
1147 question_delete_activity($cm);
1148
9a9cb741 1149 // Call the delete_instance function, if it returns false throw an exception.
a347aee3 1150 if (!$deleteinstancefunction($cm->instance)) {
9a9cb741
MN
1151 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1152 "Cannot delete the module $modulename (instance).");
a347aee3
MN
1153 }
1154
1155 // Remove all module files in case modules forget to do that.
1156 $fs = get_file_storage();
1157 $fs->delete_area_files($modcontext->id);
1158
1159 // Delete events from calendar.
1160 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
70b62308 1161 $coursecontext = context_course::instance($cm->course);
dcd338ff 1162 foreach($events as $event) {
70b62308
MG
1163 $event->context = $coursecontext;
1164 $calendarevent = calendar_event::load($event);
c5ceaeaf 1165 $calendarevent->delete();
dcd338ff 1166 }
1167 }
a347aee3
MN
1168
1169 // Delete grade items, outcome items and grades attached to modules.
1170 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1171 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
f615fbab 1172 foreach ($grade_items as $grade_item) {
1173 $grade_item->delete('moddelete');
1174 }
f615fbab 1175 }
a347aee3 1176
c69a43f2
MG
1177 // Delete associated blogs and blog tag instances.
1178 blog_remove_associations_for_module($modcontext->id);
1179
46e12372
SM
1180 // Delete completion and availability data; it is better to do this even if the
1181 // features are not turned on, in case they were turned on previously (these will be
a347aee3 1182 // very quick on an empty table).
46e12372 1183 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
ede323e2 1184 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
e9f7c4a4 1185 'course' => $cm->course,
ede323e2 1186 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
06b3a6b2 1187
d9994071 1188 // Delete all tag instances associated with the instance of this module.
74fa9f76 1189 core_tag_tag::delete_instances('mod_' . $modulename, null, $modcontext->id);
dffcf46f 1190 core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
cc033d48 1191
56537316
FM
1192 // Notify the competency subsystem.
1193 \core_competency\api::hook_course_module_deleted($cm);
1194
a347aee3 1195 // Delete the context.
c592eea2 1196 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
a347aee3
MN
1197
1198 // Delete the module from the course_modules table.
1199 $DB->delete_records('course_modules', array('id' => $cm->id));
1200
1201 // Delete module from that section.
1202 if (!delete_mod_from_section($cm->id, $cm->section)) {
9a9cb741
MN
1203 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1204 "Cannot delete the module $modulename (instance) from section.");
a347aee3
MN
1205 }
1206
63deb5c3
AA
1207 // Trigger event for course module delete action.
1208 $event = \core\event\course_module_deleted::create(array(
1209 'courseid' => $cm->course,
1210 'context' => $modcontext,
1211 'objectid' => $cm->id,
1212 'other' => array(
1213 'modulename' => $modulename,
1214 'instanceid' => $cm->instance,
1215 )
1216 ));
1217 $event->add_record_snapshot('course_modules', $cm);
1218 $event->trigger();
38b19bbc 1219 rebuild_course_cache($cm->course, true);
11b0c469 1220}
1221
3869d774
JD
1222/**
1223 * Schedule a course module for deletion in the background using an adhoc task.
1224 *
1225 * This method should not be called directly. Instead, please use course_delete_module($cmid, true), to denote async deletion.
1226 * The real deletion of the module is handled by the task, which calls 'course_delete_module($cmid)'.
1227 *
1228 * @param int $cmid the course module id.
1229 * @return bool whether the module was successfully scheduled for deletion.
1230 * @throws \moodle_exception
1231 */
1232function course_module_flag_for_async_deletion($cmid) {
44eb1490 1233 global $CFG, $DB, $USER;
3869d774
JD
1234 require_once($CFG->libdir.'/gradelib.php');
1235 require_once($CFG->libdir.'/questionlib.php');
1236 require_once($CFG->dirroot.'/blog/lib.php');
1237 require_once($CFG->dirroot.'/calendar/lib.php');
1238
1239 // Get the course module.
1240 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
1241 return true;
1242 }
1243
1244 // We need to be reasonably certain the deletion is going to succeed before we background the process.
1245 // Make the necessary delete_instance checks, etc. before proceeding further. Throw exceptions if required.
1246
1247 // Get the course module name.
1248 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1249
1250 // Get the file location of the delete_instance function for this module.
1251 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1252
1253 // Include the file required to call the delete_instance function for this module.
1254 if (file_exists($modlib)) {
1255 require_once($modlib);
1256 } else {
1257 throw new \moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1258 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
1259 }
1260
1261 $deleteinstancefunction = $modulename . '_delete_instance';
1262
1263 // Ensure the delete_instance function exists for this module.
1264 if (!function_exists($deleteinstancefunction)) {
1265 throw new \moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1266 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1267 }
1268
1269 // We are going to defer the deletion as we can't be sure how long the module's pre_delete code will run for.
1270 $cm->deletioninprogress = '1';
1271 $DB->update_record('course_modules', $cm);
1272
1273 // Create an adhoc task for the deletion of the course module. The task takes an array of course modules for removal.
1274 $removaltask = new \core_course\task\course_delete_modules();
44eb1490
DM
1275 $removaltask->set_custom_data(array(
1276 'cms' => array($cm),
1277 'userid' => $USER->id,
1278 'realuserid' => \core\session\manager::get_realuser()->id
1279 ));
3869d774
JD
1280
1281 // Queue the task for the next run.
1282 \core\task\manager::queue_adhoc_task($removaltask);
1283
1284 // Reset the course cache to hide the module.
1285 rebuild_course_cache($cm->course, true);
1286}
1287
1288/**
1289 * Checks whether the given course has any course modules scheduled for adhoc deletion.
1290 *
1291 * @param int $courseid the id of the course.
1292 * @return bool true if the course contains any modules pending deletion, false otherwise.
1293 */
1294function course_modules_pending_deletion($courseid) {
1295 if (empty($courseid)) {
1296 return false;
1297 }
1298 $modinfo = get_fast_modinfo($courseid);
1299 foreach ($modinfo->get_cms() as $module) {
1300 if ($module->deletioninprogress == '1') {
1301 return true;
1302 }
1303 }
1304 return false;
1305}
1306
1307/**
1308 * Checks whether the course module, as defined by modulename and instanceid, is scheduled for deletion within the given course.
1309 *
1310 * @param int $courseid the course id.
1311 * @param string $modulename the module name. E.g. 'assign', 'book', etc.
1312 * @param int $instanceid the module instance id.
1313 * @return bool true if the course module is pending deletion, false otherwise.
1314 */
1315function course_module_instance_pending_deletion($courseid, $modulename, $instanceid) {
1316 if (empty($courseid) || empty($modulename) || empty($instanceid)) {
1317 return false;
1318 }
1319 $modinfo = get_fast_modinfo($courseid);
1320 $instances = $modinfo->get_instances_of($modulename);
1321 return isset($instances[$instanceid]) && $instances[$instanceid]->deletioninprogress;
1322}
1323
722e6ba9 1324function delete_mod_from_section($modid, $sectionid) {
cb6fec1f 1325 global $DB;
11b0c469 1326
722e6ba9 1327 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
11b0c469 1328
e5dfd0f3 1329 $modarray = explode(",", $section->sequence);
11b0c469 1330
722e6ba9 1331 if ($key = array_keys ($modarray, $modid)) {
11b0c469 1332 array_splice($modarray, $key[0], 1);
1333 $newsequence = implode(",", $modarray);
38b19bbc
MG
1334 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1335 rebuild_course_cache($section->course, true);
1336 return true;
11b0c469 1337 } else {
1338 return false;
1339 }
89adb174 1340
11b0c469 1341 }
7977cffd 1342 return false;
11b0c469 1343}
1344
e3658a6a
AG
1345/**
1346 * This function updates the calendar events from the information stored in the module table and the course
1347 * module table.
1348 *
1349 * @param string $modulename Module name
1350 * @param stdClass $instance Module object. Either the $instance or the $cm must be supplied.
1351 * @param stdClass $cm Course module object. Either the $instance or the $cm must be supplied.
1352 * @return bool Returns true if calendar events are updated.
1353 * @since Moodle 3.3.4
1354 */
1355function course_module_update_calendar_events($modulename, $instance = null, $cm = null) {
1356 global $DB;
1357
1358 if (isset($instance) || isset($cm)) {
1359
1360 if (!isset($instance)) {
1361 $instance = $DB->get_record($modulename, array('id' => $cm->instance), '*', MUST_EXIST);
1362 }
1363 if (!isset($cm)) {
1364 $cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course);
1365 }
a66de3ca
DW
1366 if (!empty($cm)) {
1367 course_module_calendar_event_update_process($instance, $cm);
1368 }
e3658a6a
AG
1369 return true;
1370 }
1371 return false;
1372}
1373
1374/**
1375 * Update all instances through out the site or in a course.
1376 *
1377 * @param string $modulename Module type to update.
1378 * @param integer $courseid Course id to update events. 0 for the whole site.
1379 * @return bool Returns True if the update was successful.
1380 * @since Moodle 3.3.4
1381 */
1382function course_module_bulk_update_calendar_events($modulename, $courseid = 0) {
1383 global $DB;
1384
1385 $instances = null;
1386 if ($courseid) {
1387 if (!$instances = $DB->get_records($modulename, array('course' => $courseid))) {
1388 return false;
1389 }
1390 } else {
1391 if (!$instances = $DB->get_records($modulename)) {
1392 return false;
1393 }
1394 }
1395
1396 foreach ($instances as $instance) {
a66de3ca
DW
1397 if ($cm = get_coursemodule_from_instance($modulename, $instance->id, $instance->course)) {
1398 course_module_calendar_event_update_process($instance, $cm);
1399 }
e3658a6a
AG
1400 }
1401 return true;
1402}
1403
1404/**
1405 * Calendar events for a module instance are updated.
1406 *
1407 * @param stdClass $instance Module instance object.
1408 * @param stdClass $cm Course Module object.
1409 * @since Moodle 3.3.4
1410 */
1411function course_module_calendar_event_update_process($instance, $cm) {
1412 // We need to call *_refresh_events() first because some modules delete 'old' events at the end of the code which
1413 // will remove the completion events.
1414 $refresheventsfunction = $cm->modname . '_refresh_events';
1415 if (function_exists($refresheventsfunction)) {
1416 call_user_func($refresheventsfunction, $cm->course, $instance, $cm);
1417 }
1418 $completionexpected = (!empty($cm->completionexpected)) ? $cm->completionexpected : null;
1419 \core_completion\api::update_completion_date_event($cm->id, $cm->modname, $instance, $completionexpected);
1420}
1421
3440ec12 1422/**
1423 * Moves a section within a course, from a position to another.
1424 * Be very careful: $section and $destination refer to section number,
1425 * not id!.
1426 *
1427 * @param object $course
1428 * @param int $section Section number (not id!!!)
1429 * @param int $destination
ca9cae84 1430 * @param bool $ignorenumsections
3440ec12 1431 * @return boolean Result
1432 */
ca9cae84 1433function move_section_to($course, $section, $destination, $ignorenumsections = false) {
3440ec12 1434/// Moves a whole course section up and down within the course
1435 global $USER, $DB;
1436
ca255392 1437 if (!$destination && $destination != 0) {
3440ec12 1438 return true;
1439 }
1440
850acb35
MG
1441 // compartibility with course formats using field 'numsections'
1442 $courseformatoptions = course_get_format($course)->get_format_options();
ca9cae84 1443 if ((!$ignorenumsections && array_key_exists('numsections', $courseformatoptions) &&
850acb35 1444 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3440ec12 1445 return false;
1446 }
1447
1448 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1449 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1450 'section ASC, id ASC', 'id, section')) {
1451 return false;
1452 }
1453
cf76b335 1454 $movedsections = reorder_sections($sections, $section, $destination);
3440ec12 1455
cf76b335 1456 // Update all sections. Do this in 2 steps to avoid breaking database
1457 // uniqueness constraint
1458 $transaction = $DB->start_delegated_transaction();
1459 foreach ($movedsections as $id => $position) {
1460 if ($sections[$id] !== $position) {
1461 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1462 }
1463 }
e7e0f8d2
DP
1464 foreach ($movedsections as $id => $position) {
1465 if ($sections[$id] !== $position) {
1466 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1467 }
3440ec12 1468 }
1469
15e2552f
RK
1470 // If we move the highlighted section itself, then just highlight the destination.
1471 // Adjust the higlighted section location if we move something over it either direction.
1472 if ($section == $course->marker) {
e7b6e6b9 1473 course_set_marker($course->id, $destination);
2365213f 1474 } elseif ($section > $course->marker && $course->marker >= $destination) {
e7b6e6b9 1475 course_set_marker($course->id, $course->marker+1);
2365213f 1476 } elseif ($section < $course->marker && $course->marker <= $destination) {
e7b6e6b9 1477 course_set_marker($course->id, $course->marker-1);
15e2552f
RK
1478 }
1479
cf76b335 1480 $transaction->allow_commit();
38b19bbc 1481 rebuild_course_cache($course->id, true);
3440ec12 1482 return true;
1483}
1484
ca9cae84
MG
1485/**
1486 * This method will delete a course section and may delete all modules inside it.
1487 *
1488 * No permissions are checked here, use {@link course_can_delete_section()} to
1489 * check if section can actually be deleted.
1490 *
1491 * @param int|stdClass $course
1492 * @param int|stdClass|section_info $section
1493 * @param bool $forcedeleteifnotempty if set to false section will not be deleted if it has modules in it.
3869d774 1494 * @param bool $async whether or not to try to delete the section using an adhoc task. Async also depends on a plugin hook.
ca9cae84
MG
1495 * @return bool whether section was deleted
1496 */
3869d774 1497function course_delete_section($course, $section, $forcedeleteifnotempty = true, $async = false) {
fa29c0c3
RK
1498 global $DB;
1499
1500 // Prepare variables.
1501 $courseid = (is_object($course)) ? $course->id : (int)$course;
1502 $sectionnum = (is_object($section)) ? $section->section : (int)$section;
1503 $section = $DB->get_record('course_sections', array('course' => $courseid, 'section' => $sectionnum));
1504 if (!$section) {
1505 // No section exists, can't proceed.
1506 return false;
1507 }
3869d774
JD
1508
1509 // Check the 'course_module_background_deletion_recommended' hook first.
1510 // Only use asynchronous deletion if at least one plugin returns true and if async deletion has been requested.
1511 // Both are checked because plugins should not be allowed to dictate the deletion behaviour, only support/decline it.
1512 // It's up to plugins to handle things like whether or not they are enabled.
1513 if ($async && $pluginsfunction = get_plugins_with_function('course_module_background_deletion_recommended')) {
1514 foreach ($pluginsfunction as $plugintype => $plugins) {
1515 foreach ($plugins as $pluginfunction) {
1516 if ($pluginfunction()) {
1517 return course_delete_section_async($section, $forcedeleteifnotempty);
1518 }
1519 }
1520 }
1521 }
1522
fa29c0c3
RK
1523 $format = course_get_format($course);
1524 $sectionname = $format->get_section_name($section);
1525
1526 // Delete section.
1527 $result = $format->delete_section($section, $forcedeleteifnotempty);
1528
1529 // Trigger an event for course section deletion.
1530 if ($result) {
1531 $context = context_course::instance($courseid);
1532 $event = \core\event\course_section_deleted::create(
3869d774
JD
1533 array(
1534 'objectid' => $section->id,
1535 'courseid' => $courseid,
1536 'context' => $context,
1537 'other' => array(
1538 'sectionnum' => $section->section,
1539 'sectionname' => $sectionname,
fa29c0c3 1540 )
3869d774
JD
1541 )
1542 );
fa29c0c3
RK
1543 $event->add_record_snapshot('course_sections', $section);
1544 $event->trigger();
1545 }
1546 return $result;
ca9cae84
MG
1547}
1548
3869d774
JD
1549/**
1550 * Course section deletion, using an adhoc task for deletion of the modules it contains.
1551 * 1. Schedule all modules within the section for adhoc removal.
1552 * 2. Move all modules to course section 0.
1553 * 3. Delete the resulting empty section.
1554 *
1555 * @param \stdClass $section the section to schedule for deletion.
1556 * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules.
1557 * @return bool true if the section was scheduled for deletion, false otherwise.
1558 */
1559function course_delete_section_async($section, $forcedeleteifnotempty = true) {
44eb1490 1560 global $DB, $USER;
3869d774
JD
1561
1562 // Objects only, and only valid ones.
1563 if (!is_object($section) || empty($section->id)) {
1564 return false;
1565 }
1566
1567 // Does the object currently exist in the DB for removal (check for stale objects).
1568 $section = $DB->get_record('course_sections', array('id' => $section->id));
1569 if (!$section || !$section->section) {
1570 // No section exists, or the section is 0. Can't proceed.
1571 return false;
1572 }
1573
1574 // Check whether the section can be removed.
1575 if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) {
1576 return false;
1577 }
1578
1579 $format = course_get_format($section->course);
1580 $sectionname = $format->get_section_name($section);
1581
1582 // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't
1583 // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice.
1584 $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?',
1585 [$section->course, $section->id, 1], '', 'id');
1586 $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]);
1587
1588 // Move all modules to section 0.
1589 $modules = $DB->get_records('course_modules', ['section' => $section->id], '');
1590 $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']);
1591 foreach ($modules as $mod) {
1592 moveto_module($mod, $sectionzero);
1593 }
1594
1595 // Create and queue an adhoc task for the deletion of the modules.
1596 $removaltask = new \core_course\task\course_delete_modules();
1597 $data = array(
44eb1490
DM
1598 'cms' => $affectedmods,
1599 'userid' => $USER->id,
1600 'realuserid' => \core\session\manager::get_realuser()->id
3869d774
JD
1601 );
1602 $removaltask->set_custom_data($data);
1603 \core\task\manager::queue_adhoc_task($removaltask);
1604
1605 // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object.
1606 // The refresh is needed because the section->sequence is now stale.
1607 $result = $format->delete_section($section->section, $forcedeleteifnotempty);
1608
1609 // Trigger an event for course section deletion.
1610 if ($result) {
1611 $context = \context_course::instance($section->course);
1612 $event = \core\event\course_section_deleted::create(
1613 array(
1614 'objectid' => $section->id,
1615 'courseid' => $section->course,
1616 'context' => $context,
1617 'other' => array(
1618 'sectionnum' => $section->section,
1619 'sectionname' => $sectionname,
1620 )
1621 )
1622 );
1623 $event->add_record_snapshot('course_sections', $section);
1624 $event->trigger();
1625 }
1626 rebuild_course_cache($section->course, true);
1627
1628 return $result;
1629}
1630
f26481c2
MG
1631/**
1632 * Updates the course section
1633 *
1634 * This function does not check permissions or clean values - this has to be done prior to calling it.
1635 *
1636 * @param int|stdClass $course
1637 * @param stdClass $section record from course_sections table - it will be updated with the new values
1638 * @param array|stdClass $data
1639 */
1640function course_update_section($course, $section, $data) {
1641 global $DB;
1642
1643 $courseid = (is_object($course)) ? $course->id : (int)$course;
1644
1645 // Some fields can not be updated using this method.
1646 $data = array_diff_key((array)$data, array('id', 'course', 'section', 'sequence'));
1647 $changevisibility = (array_key_exists('visible', $data) && (bool)$data['visible'] != (bool)$section->visible);
1648 if (array_key_exists('name', $data) && \core_text::strlen($data['name']) > 255) {
1649 throw new moodle_exception('maximumchars', 'moodle', '', 255);
1650 }
1651
1652 // Update record in the DB and course format options.
1653 $data['id'] = $section->id;
4ddf7c60 1654 $data['timemodified'] = time();
f26481c2
MG
1655 $DB->update_record('course_sections', $data);
1656 rebuild_course_cache($courseid, true);
1657 course_get_format($courseid)->update_section_format_options($data);
1658
1659 // Update fields of the $section object.
1660 foreach ($data as $key => $value) {
1661 if (property_exists($section, $key)) {
1662 $section->$key = $value;
1663 }
1664 }
1665
1666 // Trigger an event for course section update.
1667 $event = \core\event\course_section_updated::create(
1668 array(
1669 'objectid' => $section->id,
1670 'courseid' => $courseid,
1671 'context' => context_course::instance($courseid),
1672 'other' => array('sectionnum' => $section->section)
1673 )
1674 );
1675 $event->trigger();
1676
1677 // If section visibility was changed, hide the modules in this section too.
1678 if ($changevisibility && !empty($section->sequence)) {
1679 $modules = explode(',', $section->sequence);
1680 foreach ($modules as $moduleid) {
1681 if ($cm = get_coursemodule_from_id(null, $moduleid, $courseid)) {
1682 if ($data['visible']) {
1683 // As we unhide the section, we use the previously saved visibility stored in visibleold.
8341055e 1684 set_coursemodule_visible($moduleid, $cm->visibleold, $cm->visibleoncoursepage);
f26481c2
MG
1685 } else {
1686 // We hide the section, so we hide the module but we store the original state in visibleold.
8341055e 1687 set_coursemodule_visible($moduleid, 0, $cm->visibleoncoursepage);
f26481c2
MG
1688 $DB->set_field('course_modules', 'visibleold', $cm->visible, array('id' => $moduleid));
1689 }
1690 \core\event\course_module_updated::create_from_cm($cm)->trigger();
1691 }
1692 }
1693 }
1694}
1695
ca9cae84
MG
1696/**
1697 * Checks if the current user can delete a section (if course format allows it and user has proper permissions).
1698 *
1699 * @param int|stdClass $course
1700 * @param int|stdClass|section_info $section
1701 * @return bool
1702 */
1703function course_can_delete_section($course, $section) {
1704 if (is_object($section)) {
1705 $section = $section->section;
1706 }
1707 if (!$section) {
1708 // Not possible to delete 0-section.
1709 return false;
1710 }
1711 // Course format should allow to delete sections.
1712 if (!course_get_format($course)->can_delete_section($section)) {
1713 return false;
1714 }
1715 // Make sure user has capability to update course and move sections.
1716 $context = context_course::instance(is_object($course) ? $course->id : $course);
1717 if (!has_all_capabilities(array('moodle/course:movesections', 'moodle/course:update'), $context)) {
1718 return false;
1719 }
1720 // Make sure user has capability to delete each activity in this section.
1721 $modinfo = get_fast_modinfo($course);
1722 if (!empty($modinfo->sections[$section])) {
1723 foreach ($modinfo->sections[$section] as $cmid) {
1724 if (!has_capability('moodle/course:manageactivities', context_module::instance($cmid))) {
1725 return false;
1726 }
1727 }
1728 }
1729 return true;
1730}
1731
3440ec12 1732/**
1733 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1734 * an original position number and a target position number, rebuilds the array so that the
1735 * move is made without any duplication of section positions.
1736 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1737 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1738 *
1739 * @param array $sections
1740 * @param int $origin_position
1741 * @param int $target_position
1742 * @return array
1743 */
1744function reorder_sections($sections, $origin_position, $target_position) {
1745 if (!is_array($sections)) {
1746 return false;
1747 }
1748
1749 // We can't move section position 0
1750 if ($origin_position < 1) {
1751 echo "We can't move section position 0";
1752 return false;
1753 }
1754
1755 // Locate origin section in sections array
1756 if (!$origin_key = array_search($origin_position, $sections)) {
1757 echo "searched position not in sections array";
1758 return false; // searched position not in sections array
1759 }
1760
1761 // Extract origin section
1762 $origin_section = $sections[$origin_key];
1763 unset($sections[$origin_key]);
1764
1765 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1766 $found = false;
1767 $append_array = array();
1768 foreach ($sections as $id => $position) {
1769 if ($found) {
1770 $append_array[$id] = $position;
1771 unset($sections[$id]);
1772 }
1773 if ($position == $target_position) {
eb01aa2c
RT
1774 if ($target_position < $origin_position) {
1775 $append_array[$id] = $position;
1776 unset($sections[$id]);
1777 }
3440ec12 1778 $found = true;
1779 }
1780 }
1781
1782 // Append moved section
1783 $sections[$origin_key] = $origin_section;
1784
1785 // Append rest of array (if applicable)
1786 if (!empty($append_array)) {
1787 foreach ($append_array as $id => $position) {
1788 $sections[$id] = $position;
1789 }
1790 }
1791
1792 // Renumber positions
1793 $position = 0;
1794 foreach ($sections as $id => $p) {
1795 $sections[$id] = $position;
1796 $position++;
1797 }
1798
1799 return $sections;
1800
1801}
1802
cb6fec1f 1803/**
1804 * Move the module object $mod to the specified $section
1805 * If $beforemod exists then that is the module
1806 * before which $modid should be inserted
d55f05ef
MG
1807 *
1808 * @param stdClass|cm_info $mod
1809 * @param stdClass|section_info $section
1810 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1811 * before which the module needs to be included. Null for inserting in the
1812 * end of the section
1813 * @return int new value for module visibility (0 or 1)
cb6fec1f 1814 */
7977cffd 1815function moveto_module($mod, $section, $beforemod=NULL) {
a83dd077 1816 global $OUTPUT, $DB;
7977cffd 1817
d55f05ef
MG
1818 // Current module visibility state - return value of this function.
1819 $modvisible = $mod->visible;
1820
1821 // Remove original module from original section.
7977cffd 1822 if (! delete_mod_from_section($mod->id, $mod->section)) {
e6db3026 1823 echo $OUTPUT->notification("Could not delete module from existing section");
7977cffd 1824 }
1825
d55f05ef 1826 // If moving to a hidden section then hide module.
bb1592c8
CF
1827 if ($mod->section != $section->id) {
1828 if (!$section->visible && $mod->visible) {
d55f05ef
MG
1829 // Module was visible but must become hidden after moving to hidden section.
1830 $modvisible = 0;
bb1592c8
CF
1831 set_coursemodule_visible($mod->id, 0);
1832 // Set visibleold to 1 so module will be visible when section is made visible.
1833 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1834 }
1835 if ($section->visible && !$mod->visible) {
d55f05ef 1836 // Hidden module was moved to the visible section, restore the module visibility from visibleold.
bb1592c8 1837 set_coursemodule_visible($mod->id, $mod->visibleold);
d55f05ef 1838 $modvisible = $mod->visibleold;
bb1592c8 1839 }
7977cffd 1840 }
1841
d55f05ef 1842 // Add the module into the new section.
722e6ba9 1843 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
d55f05ef 1844 return $modvisible;
7977cffd 1845}
1846
f558b291
MG
1847/**
1848 * Returns the list of all editing actions that current user can perform on the module
1849 *
1850 * @param cm_info $mod The module to produce editing buttons for
1851 * @param int $indent The current indenting (default -1 means no move left-right actions)
1852 * @param int $sr The section to link back to (used for creating the links)
1853 * @return array array of action_link or pix_icon objects
1854 */
1855function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
8341055e 1856 global $COURSE, $SITE, $CFG;
94361e02 1857
3d575e6f 1858 static $str;
1859
9a5e297b
AA
1860 $coursecontext = context_course::instance($mod->course);
1861 $modcontext = context_module::instance($mod->id);
8341055e 1862 $courseformat = course_get_format($mod->get_course());
7749e187 1863
af189935
PS
1864 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1865 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1866
cf69a00a 1867 // No permission to edit anything.
af189935 1868 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
f558b291 1869 return array();
217a8ee9 1870 }
1871
af189935
PS
1872 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1873
3d575e6f 1874 if (!isset($str)) {
f558b291 1875 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
125c4c4c 1876 'editsettings', 'duplicate', 'modhide', 'makeavailable', 'makeunavailable', 'modshow'), 'moodle');
f558b291 1877 $str->assign = get_string('assignroles', 'role');
6dc5908e
ARN
1878 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1879 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1880 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1acfbce5 1881 }
94361e02 1882
af189935 1883 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
24e1eae4 1884
f558b291
MG
1885 if ($sr !== null) {
1886 $baseurl->param('sr', $sr);
7749e187
SH
1887 }
1888 $actions = array();
1889
a83d83e4
AN
1890 // Update.
1891 if ($hasmanageactivities) {
1892 $actions['update'] = new action_menu_link_secondary(
7a9a07d2 1893 new moodle_url($baseurl, array('update' => $mod->id)),
a83d83e4
AN
1894 new pix_icon('t/edit', $str->editsettings, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1895 $str->editsettings,
1896 array('class' => 'editing_update', 'data-action' => 'update')
7a9a07d2
ARN
1897 );
1898 }
1899
cf69a00a 1900 // Indent.
639d9904 1901 if ($hasmanageactivities && $indent >= 0) {
a83d83e4
AN
1902 $indentlimits = new stdClass();
1903 $indentlimits->min = 0;
1904 $indentlimits->max = 16;
7749e187
SH
1905 if (right_to_left()) { // Exchange arrows on RTL
1906 $rightarrow = 't/left';
1907 $leftarrow = 't/right';
1908 } else {
1909 $rightarrow = 't/right';
1910 $leftarrow = 't/left';
1911 }
1912
a83d83e4
AN
1913 if ($indent >= $indentlimits->max) {
1914 $enabledclass = 'hidden';
1915 } else {
1916 $enabledclass = '';
1917 }
1918 $actions['moveright'] = new action_menu_link_secondary(
1919 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
1920 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1921 $str->moveright,
8341055e
MG
1922 array('class' => 'editing_moveright ' . $enabledclass, 'data-action' => 'moveright',
1923 'data-keepopen' => true, 'data-sectionreturn' => $sr)
a83d83e4
AN
1924 );
1925
1926 if ($indent <= $indentlimits->min) {
1927 $enabledclass = 'hidden';
1928 } else {
1929 $enabledclass = '';
7749e187 1930 }
3665af78 1931 $actions['moveleft'] = new action_menu_link_secondary(
e282c679 1932 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
cf69a00a 1933 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
e282c679 1934 $str->moveleft,
8341055e
MG
1935 array('class' => 'editing_moveleft ' . $enabledclass, 'data-action' => 'moveleft',
1936 'data-keepopen' => true, 'data-sectionreturn' => $sr)
e282c679 1937 );
a83d83e4
AN
1938
1939 }
1940
8341055e 1941 // Hide/Show/Available/Unavailable.
a83d83e4 1942 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
8341055e
MG
1943 $allowstealth = !empty($CFG->allowstealth) && $courseformat->allow_stealth_module_visibility($mod, $mod->get_section_info());
1944
1945 $sectionvisible = $mod->get_section_info()->visible;
1946 // The module on the course page may be in one of the following states:
1947 // - Available and displayed on the course page ($displayedoncoursepage);
1948 // - Not available and not displayed on the course page ($unavailable);
1949 // - Available but not displayed on the course page ($stealth) - this can also be a visible activity in a hidden section.
1950 $displayedoncoursepage = $mod->visible && $mod->visibleoncoursepage && $sectionvisible;
1951 $unavailable = !$mod->visible;
1952 $stealth = $mod->visible && (!$mod->visibleoncoursepage || !$sectionvisible);
1953 if ($displayedoncoursepage) {
a83d83e4
AN
1954 $actions['hide'] = new action_menu_link_secondary(
1955 new moodle_url($baseurl, array('hide' => $mod->id)),
125c4c4c
MG
1956 new pix_icon('t/hide', $str->modhide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1957 $str->modhide,
a83d83e4
AN
1958 array('class' => 'editing_hide', 'data-action' => 'hide')
1959 );
8341055e
MG
1960 } else if (!$displayedoncoursepage && $sectionvisible) {
1961 // Offer to "show" only if the section is visible.
a83d83e4
AN
1962 $actions['show'] = new action_menu_link_secondary(
1963 new moodle_url($baseurl, array('show' => $mod->id)),
125c4c4c
MG
1964 new pix_icon('t/show', $str->modshow, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1965 $str->modshow,
a83d83e4
AN
1966 array('class' => 'editing_show', 'data-action' => 'show')
1967 );
7749e187 1968 }
8341055e
MG
1969
1970 if ($stealth) {
1971 // When making the "stealth" module unavailable we perform the same action as hiding the visible module.
1972 $actions['hide'] = new action_menu_link_secondary(
1973 new moodle_url($baseurl, array('hide' => $mod->id)),
1974 new pix_icon('t/unblock', $str->makeunavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1975 $str->makeunavailable,
1976 array('class' => 'editing_makeunavailable', 'data-action' => 'hide', 'data-sectionreturn' => $sr)
1977 );
1978 } else if ($unavailable && (!$sectionvisible || $allowstealth) && $mod->has_view()) {
1979 // Allow to make visually hidden module available in gradebook and other reports by making it a "stealth" module.
1980 // When the section is hidden it is an equivalent of "showing" the module.
1981 // Activities without the link (i.e. labels) can not be made available but hidden on course page.
1982 $action = $sectionvisible ? 'stealth' : 'show';
1983 $actions[$action] = new action_menu_link_secondary(
1984 new moodle_url($baseurl, array($action => $mod->id)),
1985 new pix_icon('t/block', $str->makeavailable, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1986 $str->makeavailable,
1987 array('class' => 'editing_makeavailable', 'data-action' => $action, 'data-sectionreturn' => $sr)
1988 );
1989 }
dc0dc7d5 1990 }
7749e187 1991
8a1a951f 1992 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
03c39daa 1993 if (has_all_capabilities($dupecaps, $coursecontext) &&
8341055e
MG
1994 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2) &&
1995 course_allowed_module($mod->get_course(), $mod->modname)) {
3665af78 1996 $actions['duplicate'] = new action_menu_link_secondary(
8645a28f 1997 new moodle_url($baseurl, array('duplicate' => $mod->id)),
cf69a00a 1998 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
e282c679 1999 $str->duplicate,
8341055e 2000 array('class' => 'editing_duplicate', 'data-action' => 'duplicate', 'data-sectionreturn' => $sr)
8645a28f
EL
2001 );
2002 }
7749e187 2003
cf69a00a 2004 // Groupmode.
9ac099a1 2005 if ($hasmanageactivities && !$mod->coursegroupmodeforce) {
ea191cf1 2006 if (plugin_supports('mod', $mod->modname, FEATURE_GROUPS, false)) {
9ac099a1
AN
2007 if ($mod->effectivegroupmode == SEPARATEGROUPS) {
2008 $nextgroupmode = VISIBLEGROUPS;
2009 $grouptitle = $str->groupsseparate;
2010 $actionname = 'groupsseparate';
8341055e 2011 $nextactionname = 'groupsvisible';
6272fce6 2012 $groupimage = 'i/groups';
9ac099a1
AN
2013 } else if ($mod->effectivegroupmode == VISIBLEGROUPS) {
2014 $nextgroupmode = NOGROUPS;
2015 $grouptitle = $str->groupsvisible;
2016 $actionname = 'groupsvisible';
8341055e 2017 $nextactionname = 'groupsnone';
6272fce6 2018 $groupimage = 'i/groupv';
9ac099a1
AN
2019 } else {
2020 $nextgroupmode = SEPARATEGROUPS;
2021 $grouptitle = $str->groupsnone;
2022 $actionname = 'groupsnone';
8341055e 2023 $nextactionname = 'groupsseparate';
6272fce6 2024 $groupimage = 'i/groupn';
9ac099a1
AN
2025 }
2026
2027 $actions[$actionname] = new action_menu_link_primary(
2028 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $nextgroupmode)),
ec7b5522 2029 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall')),
9ac099a1 2030 $grouptitle,
8341055e
MG
2031 array('class' => 'editing_'. $actionname, 'data-action' => $nextactionname,
2032 'aria-live' => 'assertive', 'data-sectionreturn' => $sr)
9ac099a1 2033 );
32d03b7b 2034 } else {
9ac099a1 2035 $actions['nogroupsupport'] = new action_menu_filler();
32d03b7b 2036 }
7977cffd 2037 }
2038
cf69a00a 2039 // Assign.
af189935 2040 if (has_capability('moodle/role:assign', $modcontext)){
3665af78 2041 $actions['assign'] = new action_menu_link_secondary(
f558b291 2042 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
cf69a00a 2043 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
e282c679 2044 $str->assign,
8341055e 2045 array('class' => 'editing_assign', 'data-action' => 'assignroles', 'data-sectionreturn' => $sr)
7749e187
SH
2046 );
2047 }
2048
a83d83e4
AN
2049 // Delete.
2050 if ($hasmanageactivities) {
2051 $actions['delete'] = new action_menu_link_secondary(
2052 new moodle_url($baseurl, array('delete' => $mod->id)),
2053 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
2054 $str->delete,
8341055e 2055 array('class' => 'editing_delete', 'data-action' => 'delete', 'data-sectionreturn' => $sr)
a83d83e4
AN
2056 );
2057 }
2058
f558b291 2059 return $actions;
90845098 2060}
2061
4657ba81
AN
2062/**
2063 * Returns the move action.
2064 *
2065 * @param cm_info $mod The module to produce a move button for
2066 * @param int $sr The section to link back to (used for creating the links)
2067 * @return The markup for the move action, or an empty string if not available.
2068 */
2069function course_get_cm_move(cm_info $mod, $sr = null) {
2070 global $OUTPUT;
2071
2072 static $str;
2073 static $baseurl;
2074
2075 $modcontext = context_module::instance($mod->id);
2076 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
2077
2078 if (!isset($str)) {
2079 $str = get_strings(array('move'));
2080 }
2081
2082 if (!isset($baseurl)) {
2083 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
2084
2085 if ($sr !== null) {
2086 $baseurl->param('sr', $sr);
2087 }
2088 }
2089
2090 if ($hasmanageactivities) {
2091 $pixicon = 'i/dragdrop';
2092
69353dce 2093 if (!course_ajax_enabled($mod->get_course())) {
4657ba81
AN
2094 // Override for course frontpage until we get drag/drop working there.
2095 $pixicon = 't/move';
2096 }
2097
2098 return html_writer::link(
2099 new moodle_url($baseurl, array('copy' => $mod->id)),
2100 $OUTPUT->pix_icon($pixicon, $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
8341055e 2101 array('class' => 'editing_move', 'data-action' => 'move', 'data-sectionreturn' => $sr)
4657ba81
AN
2102 );
2103 }
2104 return '';
2105}
2106
b61efafb 2107/**
264867fd 2108 * given a course object with shortname & fullname, this function will
b61efafb 2109 * truncate the the number of chars allowed and add ... if it was too long
2110 */
2111function course_format_name ($course,$max=100) {
264867fd 2112
9a5e297b 2113 $context = context_course::instance($course->id);
8ebbb06a 2114 $shortname = format_string($course->shortname, true, array('context' => $context));
9a5e297b 2115 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
d1e36240 2116 $str = $shortname.': '. $fullname;
2f1e464a 2117 if (core_text::strlen($str) <= $max) {
b61efafb 2118 return $str;
2119 }
2120 else {
2f1e464a 2121 return core_text::substr($str,0,$max-3).'...';
b61efafb 2122 }
2123}
2124
0705ff84 2125/**
9665ecd2
TH
2126 * Is the user allowed to add this type of module to this course?
2127 * @param object $course the course settings. Only $course->id is used.
2128 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
2129 * @return bool whether the current user is allowed to add this type of module to this course.
0705ff84 2130 */
9665ecd2 2131function course_allowed_module($course, $modname) {
9665ecd2
TH
2132 if (is_numeric($modname)) {
2133 throw new coding_exception('Function course_allowed_module no longer
2134 supports numeric module ids. Please update your code to pass the module name.');
0705ff84 2135 }
264867fd 2136
9665ecd2
TH
2137 $capability = 'mod/' . $modname . ':addinstance';
2138 if (!get_capability_info($capability)) {
2139 // Debug warning that the capability does not exist, but no more than once per page.
2140 static $warned = array();
2141 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
2142 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
2143 debugging('The module ' . $modname . ' does not define the standard capability ' .
2144 $capability , DEBUG_DEVELOPER);
2145 $warned[$modname] = 1;
2146 }
ddb0a19f 2147
9665ecd2
TH
2148 // If the capability does not exist, the module can always be added.
2149 return true;
0705ff84 2150 }
238c0dd9 2151
9665ecd2
TH
2152 $coursecontext = context_course::instance($course->id);
2153 return has_capability($capability, $coursecontext);
0705ff84 2154}
2155
cb6fec1f 2156/**
2157 * Efficiently moves many courses around while maintaining
2158 * sortorder in order.
2159 *
e92c39ca
PS
2160 * @param array $courseids is an array of course ids
2161 * @param int $categoryid
df997f84 2162 * @return bool success
cb6fec1f 2163 */
2164function move_courses($courseids, $categoryid) {
ed54cb41 2165 global $DB;
861efb19 2166
df997f84 2167 if (empty($courseids)) {
ed54cb41 2168 // Nothing to do.
5dc361e1 2169 return false;
df997f84 2170 }
264867fd 2171
ed54cb41 2172 if (!$category = $DB->get_record('course_categories', array('id' => $categoryid))) {
df997f84
PS
2173 return false;
2174 }
19f601d1 2175
df997f84 2176 $courseids = array_reverse($courseids);
9a5e297b 2177 $newparent = context_coursecat::instance($category->id);
df997f84 2178 $i = 1;
0cbe8111 2179
aec8fe2f 2180 list($where, $params) = $DB->get_in_or_equal($courseids);
3a11e2d2 2181 $dbcourses = $DB->get_records_select('course', 'id ' . $where, $params, '', 'id, category, shortname, fullname');
30fe1181
MG
2182 foreach ($dbcourses as $dbcourse) {
2183 $course = new stdClass();
2184 $course->id = $dbcourse->id;
2185 $course->category = $category->id;
2186 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2187 if ($category->visible == 0) {
2188 // Hide the course when moving into hidden category, do not update the visibleold flag - we want to get
2189 // to previous state if somebody unhides the category.
2190 $course->visible = 0;
2191 }
ed54cb41 2192
30fe1181 2193 $DB->update_record('course', $course);
ed54cb41 2194
3a11e2d2 2195 // Update context, so it can be passed to event.
30fe1181 2196 $context = context_course::instance($course->id);
3a11e2d2 2197 $context->update_moved($newparent);
30fe1181
MG
2198
2199 // Trigger a course updated event.
2200 $event = \core\event\course_updated::create(array(
2201 'objectid' => $course->id,
3a11e2d2 2202 'context' => context_course::instance($course->id),
30fe1181
MG
2203 'other' => array('shortname' => $dbcourse->shortname,
2204 'fullname' => $dbcourse->fullname)
2205 ));
30fe1181
MG
2206 $event->set_legacy_logdata(array($course->id, 'course', 'move', 'edit.php?id=' . $course->id, $course->id));
2207 $event->trigger();
0cbe8111 2208 }
df997f84 2209 fix_course_sortorder();
eabbfa82 2210 cache_helper::purge_by_event('changesincourse');
df997f84 2211
861efb19 2212 return true;
2213}
2214
ae628043 2215/**
ee7084e9 2216 * Returns the display name of the given section that the course prefers
7487c856 2217 *
ee7084e9
MG
2218 * Implementation of this function is provided by course format
2219 * @see format_base::get_section_name()
7487c856 2220 *
ee7084e9
MG
2221 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2222 * @param int|stdClass $section Section object from database or just field course_sections.section
2223 * @return string Display name that the course format prefers, e.g. "Week 2"
ae628043 2224 */
ee7084e9
MG
2225function get_section_name($courseorid, $section) {
2226 return course_get_format($courseorid)->get_section_name($section);
7487c856
SH
2227}
2228
2229/**
ee7084e9 2230 * Tells if current course format uses sections
1b048629 2231 *
7487c856 2232 * @param string $format Course format ID e.g. 'weeks' $course->format
ee7084e9 2233 * @return bool
7487c856 2234 */
7487c856 2235function course_format_uses_sections($format) {
ee7084e9
MG
2236 $course = new stdClass();
2237 $course->format = $format;
2238 return course_get_format($course)->uses_sections();
ae628043 2239}
2240
c0b5d925
DM
2241/**
2242 * Returns the information about the ajax support in the given source format
2243 *
2244 * The returned object's property (boolean)capable indicates that
2245 * the course format supports Moodle course ajax features.
c0b5d925
DM
2246 *
2247 * @param string $format
2248 * @return stdClass
2249 */
2250function course_format_ajax_support($format) {
ee7084e9
MG
2251 $course = new stdClass();
2252 $course->format = $format;
2253 return course_get_format($course)->supports_ajax();
c0b5d925
DM
2254}
2255
2585a68d 2256/**
2257 * Can the current user delete this course?
8b449a39 2258 * Course creators have exception,
2259 * 1 day after the creation they can sill delete the course.
2585a68d 2260 * @param int $courseid
2261 * @return boolean
2585a68d 2262 */
2263function can_delete_course($courseid) {
536c0865 2264 global $USER;
2585a68d 2265
9a5e297b 2266 $context = context_course::instance($courseid);
2585a68d 2267
8b449a39 2268 if (has_capability('moodle/course:delete', $context)) {
2269 return true;
2270 }
2271
2272 // hack: now try to find out if creator created this course recently (1 day)
2273 if (!has_capability('moodle/course:create', $context)) {
2274 return false;
2275 }
2276
2277 $since = time() - 60*60*24;
536c0865
AA
2278 $course = get_course($courseid);
2279
2280 if ($course->timecreated < $since) {
2281 return false; // Return if the course was not created in last 24 hours.
2282 }
2283
2284 $logmanger = get_log_manager();
59aebbed 2285 $readers = $logmanger->get_readers('\core\log\sql_reader');
536c0865
AA
2286 $reader = reset($readers);
2287
2288 if (empty($reader)) {
2289 return false; // No log reader found.
2290 }
8b449a39 2291
536c0865
AA
2292 // A proper reader.
2293 $select = "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since";
2294 $params = array('userid' => $USER->id, 'since' => $since, 'courseid' => $course->id, 'eventname' => '\core\event\course_created');
8b449a39 2295
536c0865 2296 return (bool)$reader->get_events_select_count($select, $params);
2585a68d 2297}
2298
bef12c99 2299/**
2300 * Save the Your name for 'Some role' strings.
2301 *
2302 * @param integer $courseid the id of this course.
2303 * @param array $data the data that came from the course settings form.
2304 */
2305function save_local_role_names($courseid, $data) {
2306 global $DB;
9a5e297b 2307 $context = context_course::instance($courseid);
bef12c99 2308
2309 foreach ($data as $fieldname => $value) {
df997f84 2310 if (strpos($fieldname, 'role_') !== 0) {
bef12c99 2311 continue;
2312 }
2313 list($ignored, $roleid) = explode('_', $fieldname);
2314
2315 // make up our mind whether we want to delete, update or insert
2316 if (!$value) {
2317 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2318
2319 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2320 $rolename->name = $value;
2321 $DB->update_record('role_names', $rolename);
2322
2323 } else {
2324 $rolename = new stdClass;
2325 $rolename->contextid = $context->id;
2326 $rolename->roleid = $roleid;
2327 $rolename->name = $value;
2328 $DB->insert_record('role_names', $rolename);
2329 }
29d4cc65 2330 // This will ensure the course contacts cache is purged..
442f12f8 2331 core_course_category::role_assignment_changed($roleid, $context);
bef12c99 2332 }
2333}
2585a68d 2334
d1f8c1bd
MG
2335/**
2336 * Returns options to use in course overviewfiles filemanager
2337 *
442f12f8 2338 * @param null|stdClass|core_course_list_element|int $course either object that has 'id' property or just the course id;
d1f8c1bd
MG
2339 * may be empty if course does not exist yet (course create form)
2340 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2341 * or null if overviewfiles are disabled
2342 */
2343function course_overviewfiles_options($course) {
2344 global $CFG;
2345 if (empty($CFG->courseoverviewfileslimit)) {
2346 return null;
2347 }
2348 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2349 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2350 $accepted_types = '*';
2351 } else {
2352 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2353 // Make sure extensions are prefixed with dot unless they are valid typegroups
2354 foreach ($accepted_types as $i => $type) {
2355 if (substr($type, 0, 1) !== '.') {
2356 require_once($CFG->libdir. '/filelib.php');
2357 if (!count(file_get_typegroup('extension', $type))) {
2358 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2359 $accepted_types[$i] = '.'. $type;
2360 $corrected = true;
2361 }
2362 }
2363 }
2364 if (!empty($corrected)) {
2365 set_config('courseoverviewfilesext', join(',', $accepted_types));
2366 }
2367 }
2368 $options = array(
2369 'maxfiles' => $CFG->courseoverviewfileslimit,
2370 'maxbytes' => $CFG->maxbytes,
2371 'subdirs' => 0,
2372 'accepted_types' => $accepted_types
2373 );
2374 if (!empty($course->id)) {
2375 $options['context'] = context_course::instance($course->id);
2376 } else if (is_int($course) && $course > 0) {
2377 $options['context'] = context_course::instance($course);
2378 }
2379 return $options;
2380}
2381
c3df0901 2382/**
df997f84
PS
2383 * Create a course and either return a $course object
2384 *
2385 * Please note this functions does not verify any access control,
2386 * the calling code is responsible for all validation (usually it is the form definition).
bfefa87e 2387 *
df997f84 2388 * @param array $editoroptions course description editor options
bfefa87e 2389 * @param object $data - all the data needed for an entry in the 'course' table
df997f84 2390 * @return object new course instance
bfefa87e 2391 */
df997f84 2392function create_course($data, $editoroptions = NULL) {
0d1e5456 2393 global $DB, $CFG;
bfefa87e 2394
df997f84
PS
2395 //check the categoryid - must be given for all new courses
2396 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
71b77297 2397
9930e426 2398 // Check if the shortname already exists.
df997f84
PS
2399 if (!empty($data->shortname)) {
2400 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
9930e426 2401 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
71b77297 2402 }
2403 }
2404
9930e426 2405 // Check if the idnumber already exists.
df997f84
PS
2406 if (!empty($data->idnumber)) {
2407 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
9930e426 2408 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
71b77297 2409 }
2410 }
2f48819b 2411
8643c576
DM
2412 if ($errorcode = course_validate_dates((array)$data)) {
2413 throw new moodle_exception($errorcode);
2414 }
2415
9a4231e9
S
2416 // Check if timecreated is given.
2417 $data->timecreated = !empty($data->timecreated) ? $data->timecreated : time();
df997f84 2418 $data->timemodified = $data->timecreated;
71b77297 2419
df997f84
PS
2420 // place at beginning of any category
2421 $data->sortorder = 0;
00f270bc 2422
df997f84
PS
2423 if ($editoroptions) {
2424 // summary text is updated later, we need context to store the files first
2425 $data->summary = '';
2426 $data->summary_format = FORMAT_HTML;
2427 }
2428
db1218a9
PS
2429 if (!isset($data->visible)) {
2430 // data not from form, add missing visibility info
54a01598 2431 $data->visible = $category->visible;
bfefa87e 2432 }
db1218a9 2433 $data->visibleold = $data->visible;
2585a68d 2434
df997f84 2435 $newcourseid = $DB->insert_record('course', $data);
9a5e297b 2436 $context = context_course::instance($newcourseid, MUST_EXIST);
bfefa87e 2437
df997f84
PS
2438 if ($editoroptions) {
2439 // Save the files used in the summary editor and store
64f93798 2440 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
df997f84
PS
2441 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2442 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2443 }
d1f8c1bd
MG
2444 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2445 // Save the course overviewfiles
2446 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2447 }
bfefa87e 2448
fc79ede5
MG
2449 // update course format options
2450 course_get_format($newcourseid)->update_course_format_options($data);
2451
2452 $course = course_get_format($newcourseid)->get_course();
bfefa87e 2453
df997f84 2454 fix_course_sortorder();
eabbfa82
MG
2455 // purge appropriate caches in case fix_course_sortorder() did not change anything
2456 cache_helper::purge_by_event('changesincourse');
bfefa87e 2457
2542cb54
MG
2458 // Trigger a course created event.
2459 $event = \core\event\course_created::create(array(
2460 'objectid' => $course->id,
2461 'context' => context_course::instance($course->id),
2462 'other' => array('shortname' => $course->shortname,
2463 'fullname' => $course->fullname)
2464 ));
16076f1e 2465
2542cb54
MG
2466 $event->trigger();
2467
2468 // Setup the blocks
2469 blocks_add_default_course_blocks($course);
2470
89b909f6
MG
2471 // Create default section and initial sections if specified (unless they've already been created earlier).
2472 // We do not want to call course_create_sections_if_missing() because to avoid creating course cache.
2473 $numsections = isset($data->numsections) ? $data->numsections : 0;
2474 $existingsections = $DB->get_fieldset_sql('SELECT section from {course_sections} WHERE course = ?', [$newcourseid]);
2475 $newsections = array_diff(range(0, $numsections), $existingsections);
2476 foreach ($newsections as $sectionnum) {
2477 course_create_section($newcourseid, $sectionnum, true);
2478 }
2542cb54 2479
df997f84 2480 // Save any custom role names.
e92c39ca 2481 save_local_role_names($course->id, (array)$data);
bfefa87e 2482
df997f84
PS
2483 // set up enrolments
2484 enrol_course_updated(true, $course, $data);
bef12c99 2485
0d1e5456 2486 // Update course tags.
74fa9f76
MG
2487 if (isset($data->tags)) {
2488 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
0d1e5456
MG
2489 }
2490
7a0162f1
DM
2491 // Save custom fields if there are any of them in the form.
2492 $handler = core_course\customfield\course_handler::create();
2f61fe97
JP
2493 // Make sure to set the handler's parent context first.
2494 $coursecatcontext = context_coursecat::instance($category->id);
2495 $handler->set_parent_context($coursecatcontext);
2496 // Save the custom field data.
7a0162f1
DM
2497 $data->id = $course->id;
2498 $handler->instance_form_save($data, true);
2499
df997f84 2500 return $course;
bfefa87e 2501}
2502
c3df0901 2503/**
df997f84
PS
2504 * Update a course.
2505 *
2506 * Please note this functions does not verify any access control,
2507 * the calling code is responsible for all validation (usually it is the form definition).
bfefa87e 2508 *
2509 * @param object $data - all the data needed for an entry in the 'course' table
df997f84
PS
2510 * @param array $editoroptions course description editor options
2511 * @return void
bfefa87e 2512 */
df997f84 2513function update_course($data, $editoroptions = NULL) {
0d1e5456 2514 global $DB, $CFG;
bfefa87e 2515
df997f84 2516 $data->timemodified = time();
ddb0a19f 2517
12b94016
SL
2518 // Prevent changes on front page course.
2519 if ($data->id == SITEID) {
2520 throw new moodle_exception('invalidcourse', 'error');
2521 }
2522
fc79ede5 2523 $oldcourse = course_get_format($data->id)->get_course();
9a5e297b 2524 $context = context_course::instance($oldcourse->id);
bfefa87e 2525
df997f84 2526 if ($editoroptions) {
64f93798 2527 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
71b77297 2528 }
d1f8c1bd
MG
2529 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2530 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2531 }
71b77297 2532
5536a561
FD
2533 // Check we don't have a duplicate shortname.
2534 if (!empty($data->shortname) && $oldcourse->shortname != $data->shortname) {
e1301685 2535 if ($DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data->shortname, $data->id))) {
5536a561
FD
2536 throw new moodle_exception('shortnametaken', '', '', $data->shortname);
2537 }
2538 }
2539
2540 // Check we don't have a duplicate idnumber.
2541 if (!empty($data->idnumber) && $oldcourse->idnumber != $data->idnumber) {
e1301685 2542 if ($DB->record_exists_sql('SELECT id from {course} WHERE idnumber = ? AND id <> ?', array($data->idnumber, $data->id))) {
5536a561
FD
2543 throw new moodle_exception('courseidnumbertaken', '', '', $data->idnumber);
2544 }
2545 }
2546
8643c576
DM
2547 if ($errorcode = course_validate_dates((array)$data)) {
2548 throw new moodle_exception($errorcode);
2549 }
2550
df997f84
PS
2551 if (!isset($data->category) or empty($data->category)) {
2552 // prevent nulls and 0 in category field
bfefa87e 2553 unset($data->category);
2554 }
b80a50f7 2555 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
bfefa87e 2556
db1218a9
PS
2557 if (!isset($data->visible)) {
2558 // data not from form, add missing visibility info
df997f84
PS
2559 $data->visible = $oldcourse->visible;
2560 }
bfefa87e 2561
df997f84
PS
2562 if ($data->visible != $oldcourse->visible) {
2563 // reset the visibleold flag when manually hiding/unhiding course
2564 $data->visibleold = $data->visible;
b55248d5 2565 $changesincoursecat = true;
df997f84 2566 } else {
a372aab5 2567 if ($movecat) {
df997f84
PS
2568 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2569 if (empty($newcategory->visible)) {
2570 // make sure when moving into hidden category the course is hidden automatically
2571 $data->visible = 0;
2572 }
a372aab5 2573 }
df997f84 2574 }
a372aab5 2575
019186b7
AT
2576 // Set newsitems to 0 if format does not support announcements.
2577 if (isset($data->format)) {
2578 $newcourseformat = course_get_format((object)['format' => $data->format]);
745f79da 2579 if (!$newcourseformat->supports_news()) {
019186b7
AT
2580 $data->newsitems = 0;
2581 }
2582 }
2583
7a0162f1
DM
2584 // Update custom fields if there are any of them in the form.
2585 $handler = core_course\customfield\course_handler::create();
2586 $handler->instance_form_save($data);
2587
df997f84 2588 // Update with the new data
487caf6b 2589 $DB->update_record('course', $data);
38b19bbc
MG
2590 // make sure the modinfo cache is reset
2591 rebuild_course_cache($data->id);
bfefa87e 2592
fc79ede5
MG
2593 // update course format options with full course data
2594 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2595
df997f84 2596 $course = $DB->get_record('course', array('id'=>$data->id));
bfefa87e 2597
df997f84 2598 if ($movecat) {
9a5e297b 2599 $newparent = context_coursecat::instance($course->category);
2c5b0eb7 2600 $context->update_moved($newparent);
df997f84 2601 }
3a11e2d2
RT
2602 $fixcoursesortorder = $movecat || (isset($data->sortorder) && ($oldcourse->sortorder != $data->sortorder));
2603 if ($fixcoursesortorder) {
24f824b9
MG
2604 fix_course_sortorder();
2605 }
2606
eabbfa82
MG
2607 // purge appropriate caches in case fix_course_sortorder() did not change anything
2608 cache_helper::purge_by_event('changesincourse');
b55248d5 2609 if ($changesincoursecat) {
b80a50f7
MG
2610 cache_helper::purge_by_event('changesincoursecat');
2611 }
bfefa87e 2612
df997f84
PS
2613 // Test for and remove blocks which aren't appropriate anymore
2614 blocks_remove_inappropriate($course);
bfefa87e 2615
df997f84
PS
2616 // Save any custom role names.
2617 save_local_role_names($course->id, $data);
2618
2619 // update enrol settings
2620 enrol_course_updated(false, $course, $data);
2621
0d1e5456 2622 // Update course tags.
74fa9f76
MG
2623 if (isset($data->tags)) {
2624 core_tag_tag::set_item_tags('core', 'course', $course->id, context_course::instance($course->id), $data->tags);
0d1e5456
MG
2625 }
2626
53a8e678
MN
2627 // Trigger a course updated event.
2628 $event = \core\event\course_updated::create(array(
2629 'objectid' => $course->id,
3a11e2d2 2630 'context' => context_course::instance($course->id),
53a8e678
MN
2631 'other' => array('shortname' => $course->shortname,
2632 'fullname' => $course->fullname)
2633 ));
3a11e2d2 2634
2bf2f359 2635 $event->set_legacy_logdata(array($course->id, 'course', 'update', 'edit.php?id=' . $course->id, $course->id));
53a8e678 2636 $event->trigger();
fc79ede5
MG
2637
2638 if ($oldcourse->format !== $course->format) {
2639 // Remove all options stored for the previous format
2640 // We assume that new course format migrated everything it needed watching trigger
2641 // 'course_updated' and in method format_XXX::update_course_format_options()
2642 $DB->delete_records('course_format_options',
2643 array('courseid' => $course->id, 'format' => $oldcourse->format));
2644 }
bfefa87e 2645}
2585a68d 2646
07ab0c80 2647/**
fcb4decd 2648 * Average number of participants
07ab0c80 2649 * @return integer
2650 */
2651function average_number_of_participants() {
fcb4decd 2652 global $DB, $SITE;
2653
2654 //count total of enrolments for visible course (except front page)
2655 $sql = 'SELECT COUNT(*) FROM (
2656 SELECT DISTINCT ue.userid, e.courseid
2657 FROM {user_enrolments} ue, {enrol} e, {course} c
516c5eca 2658 WHERE ue.enrolid = e.id
fcb4decd 2659 AND e.courseid <> :siteid
2660 AND c.id = e.courseid
9f247093 2661 AND c.visible = 1) total';
fcb4decd 2662 $params = array('siteid' => $SITE->id);
2663 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2664
2665
2666 //count total of visible courses (minus front page)
2667 $coursetotal = $DB->count_records('course', array('visible' => 1));
2668 $coursetotal = $coursetotal - 1 ;
2669
2670 //average of enrolment
2671 if (empty($coursetotal)) {
2672 $participantaverage = 0;
2673 } else {
2674 $participantaverage = $enrolmenttotal / $coursetotal;
2675 }
2676
2677 return $participantaverage;
07ab0c80 2678}
2679
2680/**
fcb4decd 2681 * Average number of course modules
07ab0c80 2682 * @return integer
2683 */
2684function average_number_of_courses_modules() {
fcb4decd 2685 global $DB, $SITE;
2686
2687 //count total of visible course module (except front page)
2688 $sql = 'SELECT COUNT(*) FROM (
2689 SELECT cm.course, cm.module
2690 FROM {course} c, {course_modules} cm
516c5eca 2691 WHERE c.id = cm.course
fcb4decd 2692 AND c.id <> :siteid
2693 AND cm.visible = 1
9f247093 2694 AND c.visible = 1) total';
fcb4decd 2695 $params = array('siteid' => $SITE->id);
2696 $moduletotal = $DB->count_records_sql($sql, $params);
2697
2698
2699 //count total of visible courses (minus front page)
2700 $coursetotal = $DB->count_records('course', array('visible' => 1));
2701 $coursetotal = $coursetotal - 1 ;
2702
2703 //average of course module
2704 if (empty($coursetotal)) {
2705 $coursemoduleaverage = 0;
2706 } else {
2707 $coursemoduleaverage = $moduletotal / $coursetotal;
2708 }
2709
2710 return $coursemoduleaverage;
07ab0c80 2711}
2712
8bdc9cac
SH
2713/**
2714 * This class pertains to course requests and contains methods associated with
2715 * create, approving, and removing course requests.
2716 *
64f93798
PS
2717 * Please note we do not allow embedded images here because there is no context
2718 * to store them with proper access control.
2719 *
8bdc9cac
SH
2720 * @copyright 2009 Sam Hemelryk
2721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2722 * @since Moodle 2.0
2723 *
2724 * @property-read int $id
2725 * @property-read string $fullname
2726 * @property-read string $shortname
2727 * @property-read string $summary
2728 * @property-read int $summaryformat
2729 * @property-read int $summarytrust
2730 * @property-read string $reason
2731 * @property-read int $requester
8bdc9cac
SH
2732 */
2733class course_request {
2734
2735 /**
2736 * This is the stdClass that stores the properties for the course request
7e85563d 2737 * and is externally accessed through the __get magic method
8bdc9cac
SH
2738 * @var stdClass
2739 */
2740 protected $properties;
2741
2742 /**
2743 * An array of options for the summary editor used by course request forms.
2744 * This is initially set by {@link summary_editor_options()}
2745 * @var array
2746 * @static
2747 */
2748 protected static $summaryeditoroptions;
2749
8bdc9cac
SH
2750 /**
2751 * Static function to prepare the summary editor for working with a course
2752 * request.
2753 *
2754 * @static
2755 * @param null|stdClass $data Optional, an object containing the default values
2756 * for the form, these may be modified when preparing the
2757 * editor so this should be called before creating the form
2758 * @return stdClass An object that can be used to set the default values for
2759 * an mforms form
2760 */
2761 public static function prepare($data=null) {
2762 if ($data === null) {
2763 $data = new stdClass;
2764 }
64f93798 2765 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
8bdc9cac
SH
2766 return $data;
2767 }
2768
2769 /**
2770 * Static function to create a new course request when passed an array of properties
2771 * for it.
2772 *
2773 * This function also handles saving any files that may have been used in the editor
2774 *
2775 * @static
2776 * @param stdClass $data
2777 * @return course_request The newly created course request
2778 */
2779 public static function create($data) {
2780 global $USER, $DB, $CFG;
2781 $data->requester = $USER->id;
64f93798 2782
d347f304 2783 // Setting the default category if none set.
59b9a140
FM
2784 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2785 $data->category = $CFG->defaultrequestcategory;
2786 }
2787
64f93798
PS
2788 // Summary is a required field so copy the text over
2789 $data->summary = $data->summary_editor['text'];
2790 $data->summaryformat = $data->summary_editor['format'];
2791
8bdc9cac 2792 $data->id = $DB->insert_record('course_request', $data);
64f93798 2793
8bdc9cac
SH
2794 // Create a new course_request object and return it
2795 $request = new course_request($data);
2796
2797 // Notify the admin if required.
adf176d7 2798 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
aa6c1ced 2799
8bdc9cac
SH
2800 $a = new stdClass;
2801 $a->link = "$CFG->wwwroot/course/pending.php";
2802 $a->user = fullname($USER);
2803 $subject = get_string('courserequest');
2804 $message = get_string('courserequestnotifyemail', 'admin', $a);
2805 foreach ($users as $user) {
2a63b636 2806 $request->notify($user, $USER, 'courserequested', $subject, $message);
8bdc9cac
SH
2807 }
2808 }
2809
2810 return $request;
2811 }
2812
2813 /**
2814 * Returns an array of options to use with a summary editor
2815 *
2816 * @uses course_request::$summaryeditoroptions
2817 * @return array An array of options to use with the editor
2818 */
2819 public static function summary_editor_options() {
2820 global $CFG;
2821 if (self::$summaryeditoroptions === null) {
64f93798 2822 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
8bdc9cac
SH
2823 }
2824 return self::$summaryeditoroptions;
2825 }
2826
8bdc9cac
SH
2827 /**
2828 * Loads the properties for this course request object. Id is required and if
2829 * only id is provided then we load the rest of the properties from the database
2830 *
2831 * @param stdClass|int $properties Either an object containing properties
2832 * or the course_request id to load
2833 */
2834 public function __construct($properties) {
2835 global $DB;
2836 if (empty($properties->id)) {
2837 if (empty($properties)) {
2838 throw new coding_exception('You must provide a course request id when creating a course_request object');
2839 }
2840 $id = $properties;
2841 $properties = new stdClass;
2842 $properties->id = (int)$id;
2843 unset($id);
2844 }
2845 if (empty($properties->requester)) {
2846 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2847 print_error('unknowncourserequest');
2848 }
2849 } else {
2850 $this->properties = $properties;
2851 }
2852 $this->properties->collision = null;
2853 }
2854
2855 /**
2856 * Returns the requested property
2857 *
2858 * @param string $key
2859 * @return mixed
2860 */
2861 public function __get($key) {
8bdc9cac
SH
2862 return $this->properties->$key;
2863 }
2864
2865 /**
2866 * Override this to ensure empty($request->blah) calls return a reliable answer...
2867 *
2868 * This is required because we define the __get method
2869 *
2870 * @param mixed $key
2871 * @return bool True is it not empty, false otherwise
2872 */
2873 public function __isset($key) {
2874 return (!empty($this->properties->$key));
2875 }
2876
2877 /**
2878 * Returns the user who requested this course
2879 *
2880 * Uses a static var to cache the results and cut down the number of db queries
2881 *
2882 * @staticvar array $requesters An array of cached users
2883 * @return stdClass The user who requested the course
2884 */
2885 public function get_requester() {
2886 global $DB;
2887 static $requesters= array();
2888 if (!array_key_exists($this->properties->requester, $requesters)) {
2889 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2890 }
2891 return $requesters[$this->properties->requester];
2892 }
2893
2894 /**
2895 * Checks that the shortname used by the course does not conflict with any other
2896 * courses that exist
2897 *
2898 * @param string|null $shortnamemark The string to append to the requests shortname
2899 * should a conflict be found
2900 * @return bool true is there is a conflict, false otherwise
2901 */
2902 public function check_shortname_collision($shortnamemark = '[*]') {
2903 global $DB;
2904
2905 if ($this->properties->collision !== null) {
2906 return $this->properties->collision;
2907 }
2908
2909 if (empty($this->properties->shortname)) {
2910 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2911 $this->properties->collision = false;
2912 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2913 if (!empty($shortnamemark)) {
2914 $this->properties->shortname .= ' '.$shortnamemark;
2915 }
2916 $this->properties->collision = true;
2917 } else {
2918 $this->properties->collision = false;
2919 }
2920 return $this->properties->collision;
2921 }
2922
2d8a275b
MG
2923 /**
2924 * Returns the category where this course request should be created
2925 *
2926 * Note that we don't check here that user has a capability to view
2927 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2928 * 'moodle/course:changecategory'
2929 *
442f12f8 2930 * @return core_course_category
2d8a275b
MG
2931 */
2932 public function get_category() {
2933 global $CFG;
2d8a275b
MG
2934 // If the category is not set, if the current user does not have the rights to change the category, or if the
2935 // category does not exist, we set the default category to the course to be approved.
2936 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2937 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
442f12f8
MG
2938 (!$category = core_course_category::get($this->properties->category, IGNORE_MISSING, true))) {
2939 $category = core_course_category::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2d8a275b
MG
2940 }
2941 if (!$category) {
442f12f8 2942 $category = core_course_category::get_default();
2d8a275b
MG
2943 }
2944 return $category;
2945 }
2946
8bdc9cac
SH
2947 /**
2948 * This function approves the request turning it into a course
2949 *
2950 * This function converts the course request into a course, at the same time
7e85563d 2951 * transferring any files used in the summary to the new course and then removing
8bdc9cac
SH
2952 * the course request and the files associated with it.
2953 *
2954 * @return int The id of the course that was created from this request
2955 */
2956 public function approve() {
2957 global $CFG, $DB, $USER;
70740405 2958
9f9d7bbe
AG
2959 require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
2960
70740405
PS
2961 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2962
8bdc9cac
SH
2963 $courseconfig = get_config('moodlecourse');
2964
2965 // Transfer appropriate settings
70740405
PS
2966 $data = clone($this->properties);
2967 unset($data->id);
2968 unset($data->reason);
2969 unset($data->requester);
8bdc9cac
SH
2970
2971 // Set category
2d8a275b 2972 $category = $this->get_category();
70740405 2973 $data->category = $category->id;
8bdc9cac 2974 // Set misc settings
70740405 2975 $data->requested = 1;
8bdc9cac
SH
2976
2977 // Apply course default settings
70740405 2978 $data->format = $courseconfig->format;
70740405
PS
2979 $data->newsitems = $courseconfig->newsitems;
2980 $data->showgrades = $courseconfig->showgrades;
2981 $data->showreports = $courseconfig->showreports;
2982 $data->maxbytes = $courseconfig->maxbytes;
2983 $data->groupmode = $courseconfig->groupmode;
2984 $data->groupmodeforce = $courseconfig->groupmodeforce;
2985 $data->visible = $courseconfig->visible;
2986 $data->visibleold = $data->visible;
2987 $data->lang = $courseconfig->lang;
f6b9b6b7 2988 $data->enablecompletion = $courseconfig->enablecompletion;
ca66f965 2989 $data->numsections = $courseconfig->numsections;
6363c9ad
FK
2990 $data->startdate = usergetmidnight(time());
2991 if ($courseconfig->courseenddateenabled) {
2992 $data->enddate = usergetmidnight(time()) + $courseconfig->courseduration;
2993 }
8bdc9cac 2994
9f9d7bbe
AG
2995 list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names(0, $data->fullname, $data->shortname);
2996
70740405 2997 $course = create_course($data);
1f364c87 2998 $context = context_course::instance($course->id, MUST_EXIST);
8bdc9cac 2999
70740405
PS
3000 // add enrol instances
3001 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
3002 if ($manual = enrol_get_plugin('manual')) {
3003 $manual->add_default_instance($course);
3004 }
8bdc9cac 3005 }
70740405
PS
3006
3007 // enrol the requester as teacher if necessary
3008 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
3009 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
3010 }
3011
3012 $this->delete();
3013
fbaea88f 3014 $a = new stdClass();
9a5e297b 3015 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
70740405 3016 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
880fc15b 3017 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a), $course->id);
70740405
PS
3018
3019 return $course->id;
8bdc9cac
SH
3020 }
3021
3022 /**
3023 * Reject a course request
3024 *
3025 * This function rejects a course request, emailing the requesting user the
3026 * provided notice and then removing the request from the database
3027 *
3028 * @param string $notice The message to display to the user
3029 */
3030 public function reject($notice) {
70740405
PS
3031 global $USER, $DB;
3032 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
8bdc9cac
SH
3033 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
3034 $this->delete();
3035 }
3036
3037 /**
3038 * Deletes the course request and any associated files
3039 */
3040 public function delete() {
3041 global $DB;
3042 $DB->delete_records('course_request', array('id' => $this->properties->id));
8bdc9cac
SH
3043 }
3044
3045 /**
3046 * Send a message from one user to another using events_trigger
3047 *
3048 * @param object $touser
3049 * @param object $fromuser
3050 * @param string $name
3051 * @param string $subject
3052 * @param string $message
880fc15b 3053 * @param int|null $courseid
8bdc9cac 3054 */
880fc15b 3055 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message, $courseid = null) {
cc350fd9 3056 $eventdata = new \core\message\message();
880fc15b 3057 $eventdata->courseid = empty($courseid) ? SITEID : $courseid;
a1708181 3058 $eventdata->component = 'moodle';
8bdc9cac
SH
3059 $eventdata->name = $name;
3060 $eventdata->userfrom = $fromuser;
3061 $eventdata->userto = $touser;
3062 $eventdata->subject = $subject;
3063 $eventdata->fullmessage = $message;
3064 $eventdata->fullmessageformat = FORMAT_PLAIN;
3065 $eventdata->fullmessagehtml = '';
3066 $eventdata->smallmessage = '';
a1708181 3067 $eventdata->notification = 1;
7c7d3afa 3068 message_send($eventdata);
8bdc9cac 3069 }
5c34c4ba 3070}
b1627a92
DC
3071
3072/**
3073 * Return a list of page types
3074 * @param string $pagetype current page type
9dd85edf
MG
3075 * @param context $parentcontext Block's parent context
3076 * @param context $currentcontext Current context of block
3077 * @return array array of page types
b1627a92 3078 */
b38e2e28 3079function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
9dd85edf
MG
3080 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
3081 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
3082 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3083 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
3084 );
3085 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
3086 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
3087 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
3088 } else {
3089 // Otherwise consider it a page inside a course even if $currentcontext is null
3090 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
3091 'course-*' => get_string('page-course-x', 'pagetype'),
3092 'course-view-*' => get_string('page-course-view-x', 'pagetype')
3093 );
b1627a92 3094 }
9dd85edf 3095 return $pagetypes;
af27c69e 3096}
ebaa29d1 3097
5720019d
ARN
3098/**
3099 * Determine whether course ajax should be enabled for the specified course
3100 *
924c34df 3101 * @param stdClass $course The course to test against
5720019d
ARN
3102 * @return boolean Whether course ajax is enabled or note
3103 */
3104function course_ajax_enabled($course) {
3105 global $CFG, $PAGE, $SITE;
3106
5720019d
ARN
3107 // The user must be editing for AJAX to be included
3108 if (!$PAGE->user_is_editing()) {
3109 return false;
3110 }
3111
3112 // Check that the theme suports
3113 if (!$PAGE->theme->enablecourseajax) {
3114 return false;
3115 }
3116
3117 // Check that the course format supports ajax functionality
3118 // The site 'format' doesn't have information on course format support
3119 if ($SITE->id !== $course->id) {
3120 $courseformatajaxsupport = course_format_ajax_support($course->format);
3121 if (!$courseformatajaxsupport->capable) {
3122 return false;
3123 }
3124 }
3125
3126 // All conditions have been met so course ajax should be enabled
3127 return true;
3128}
3129
ebaa29d1
ARN
3130/**
3131 * Include the relevant javascript and language strings for the resource
3132 * toolbox YUI module
3133 *
3134 * @param integer $id The ID of the course being applied to
7b061512
SH
3135 * @param array $usedmodules An array containing the names of the modules in use on the page
3136 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
924c34df 3137 * @param stdClass $config An object containing configuration parameters for ajax modules including:
ebaa29d1
ARN
3138 * * resourceurl The URL to post changes to for resource changes
3139 * * sectionurl The URL to post changes to for section changes
3140 * * pageparams Additional parameters to pass through in the post
7b061512 3141 * @return bool
ebaa29d1 3142 */
7b061512 3143function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
52973369 3144 global $CFG, $PAGE, $SITE;
ebaa29d1
ARN
3145
3146 // Ensure that ajax should be included
5720019d
ARN
3147 if (!course_ajax_enabled($course)) {
3148 return false;
ebaa29d1
ARN
3149 }
3150
3151 if (!$config) {
3152 $config = new stdClass();
3153 }
3154
3155 // The URL to use for resource changes
3156 if (!isset($config->resourceurl)) {
3157 $config->resourceurl = '/course/rest.php';
3158 }
3159
3160 // The URL to use for section changes
3161 if (!isset($config->sectionurl)) {
3162 $config->sectionurl = '/course/rest.php';
3163 }
3164
3165 // Any additional parameters which need to be included on page submission
3166 if (!isset($config->pageparams)) {
3167 $config->pageparams = array();
3168 }
3169
15e2552f 3170 // Include course dragdrop
47281f7e 3171 if (course_format_uses_sections($course->format)) {
c77582fe 3172 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
15e2552f
RK
3173 array(array(
3174 'courseid' => $course->id,
56838156 3175 'ajaxurl' => $config->sectionurl,
15e2552f
RK
3176 'config' => $config,
3177 )), null, true);
3178
c77582fe 3179 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
15e2552f
RK
3180 array(array(
3181 'courseid' => $course->id,
56838156 3182 'ajaxurl' => $config->resourceurl,
15e2552f
RK
3183 'config' => $config,
3184 )), null, true);
56838156
RK
3185 }
3186
ebaa29d1
ARN
3187 // Require various strings for the command toolbox
3188 $PAGE->requires->strings_for_js(array(
3189 'moveleft',
3190 'deletechecktype',
3191 'deletechecktypename',
7a9a07d2
ARN
3192 'edittitle',
3193 'edittitleinstructions',
ebaa29d1
ARN
3194 'show',
3195 'hide',
60cf0742
S
3196 'highlight',
3197 'highlightoff',
ebaa29d1
ARN
3198 'groupsnone',
3199 'groupsvisible',
3200 'groupsseparate',
3201 'clicktochangeinbrackets',
3202 'markthistopic',
3203 'markedthistopic',
15e2552f 3204 'movesection',
34bcc6a9
AN
3205 'movecoursemodule',
3206 'movecoursesection',
dd66b6ab 3207 'movecontent',
bbb483b2 3208 'tocontent',
34bcc6a9
AN
3209 'emptydragdropregion',
3210 'afterresource',
3211 'aftersection',
3212 'totopofsection',
ebaa29d1
ARN
3213 ), 'moodle');
3214
47281f7e
AN
3215 // Include section-specific strings for formats which support sections.
3216 if (course_format_uses_sections($course->format)) {
ebaa29d1
ARN
3217 $PAGE->requires->strings_for_js(array(
3218 'showfromothers',
3219 'hidefromothers',
3220 ), 'format_' . $course->format);
3221 }
3222
3223 // For confirming resource deletion we need the name of the module in question
7b061512 3224 foreach ($usedmodules as $module => $modname) {
ebaa29d1
ARN
3225 $PAGE->requires->string_for_js('pluginname', $module);
3226 }
3aaa1843 3227
32528f94 3228 // Load drag and drop upload AJAX.
52973369 3229 require_once($CFG->dirroot.'/course/dnduploadlib.php');
7b061512
SH
3230 dndupload_add_to_course($course, $enabledmodules);
3231
8341055e
MG
3232 $PAGE->requires->js_call_amd('core_course/actions', 'initCoursePage', array($course->format));
3233
5720019d 3234 return true;
ebaa29d1 3235}
5218b9bb 3236
3776335c
MG
3237/**
3238 * Returns the sorted list of available course formats, filtered by enabled if necessary
3239 *
3240 * @param bool $enabledonly return only formats that are enabled
3241 * @return array array of sorted format names
3242 */
3243function get_sorted_course_formats($enabledonly = false) {
3244 global $CFG;
bd3b3bba 3245 $formats = core_component::get_plugin_list('format');
3776335c
MG
3246
3247 if (!empty($CFG->format_plugins_sortorder)) {
3248 $order = explode(',', $CFG->format_plugins_sortorder);
3249 $order = array_merge(array_intersect($order, array_keys($formats)),
3250 array_diff(array_keys($formats), $order));
3251 } else {
3252 $order = array_keys($formats);
3253 }
3254 if (!$enabledonly) {
3255 return $order;
3256 }
3257 $sortedformats = array();
3258 foreach ($order as $formatname) {
3259 if (!get_config('format_'.$formatname, 'disabled')) {
3260 $sortedformats[] = $formatname;
3261 }
3262 }
3263 return $sortedformats;
3264}
3265
5218b9bb
DP
3266/**
3267 * The URL to use for the specified course (with section)
3268 *
ee7084e9
MG
3269 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3270 * @param int|stdClass $section Section object from database or just field course_sections.section
923451c5
MG
3271 * if omitted the course view page is returned
3272 * @param array $options options for view URL. At the moment core uses:
3273 * 'navigation' (bool) if true and section has no separate page, the function returns null
3274 * 'sr' (int) used by multipage formats to specify to which section to return
5218b9bb
DP
3275 * @return moodle_url The url of course
3276 */
ee7084e9
MG
3277function course_get_url($courseorid, $section = null, $options = array()) {
3278 return course_get_format($courseorid)->get_view_url($section, $options);
5218b9bb 3279}
dd5d933f 3280
dd5d933f
JM
3281/**
3282 * Create a module.
7cb0ea2c 3283 *
dd5d933f
JM
3284 * It includes:
3285 * - capability checks and other checks
3286 * - create the module from the module info
3287 *
3288 * @param object $module
3289 * @return object the created module info
b4b75872 3290 * @throws moodle_exception if user is not allowed to perform the action or module is not allowed in this course
dd5d933f
JM
3291 */
3292function create_module($moduleinfo) {
74df2951 3293 global $DB, $CFG;
80fe0c19
JM
3294
3295 require_once($CFG->dirroot . '/course/modlib.php');
3296
dd5d933f
JM
3297 // Check manadatory attributs.
3298 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3299 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3300 $mandatoryfields[] = 'introeditor';
3301 }
3302 foreach($mandatoryfields as $mandatoryfield) {
3303 if (!isset($moduleinfo->{$mandatoryfield})) {
3304 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3305 }
3306 }
3307
7cb0ea2c 3308 // Some additional checks (capability / existing instances).
74df2951 3309 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
dd5d933f
JM
3310 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3311
dd5d933f
JM
3312 // Add the module.
3313 $moduleinfo->module = $module->id;
3314 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3315
3316 return $moduleinfo;
3317}
3318
3319/**
3320 * Update a module.
7cb0ea2c 3321 *
dd5d933f 3322 * It includes:
7cb0ea2c 3323 * - capability and other checks
dd5d933f
JM
3324 * - update the module
3325 *
3326 * @param object $module
3327 * @return object the updated module info
b4b75872 3328 * @throws moodle_exception if current user is not allowed to update the module
dd5d933f
JM
3329 */
3330function update_module($moduleinfo) {
74df2951 3331 global $DB, $CFG;
80fe0c19
JM
3332
3333 require_once($CFG->dirroot . '/course/modlib.php');
dd5d933f
JM
3334
3335 // Check the course module exists.
3336 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3337
3338 // Check the course exists.
74df2951 3339 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
dd5d933f 3340
7cb0ea2c 3341 // Some checks (capaibility / existing instances).
dd5d933f
JM
3342 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3343
7cb0ea2c 3344 // Retrieve few information needed by update_moduleinfo.
dd5d933f
JM
3345 $moduleinfo->modulename = $cm->modname;
3346 if (!isset($moduleinfo->scale)) {
3347 $moduleinfo->scale = 0;
3348 }
3349 $moduleinfo->type = 'mod';
3350
7cb0ea2c 3351 // Update the module.
dd5d933f
JM
3352 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3353
3354 return $moduleinfo;
3355}
3a7e4a80 3356
6982618e 3357/**
0a3d81c2 3358 * Duplicate a module on the course for ajax.
6982618e 3359 *
0a3d81c2 3360 * @see mod_duplicate_module()
6982618e
AN
3361 * @param object $course The course
3362 * @param object $cm The course module to duplicate
0a3d81c2 3363 * @param int $sr The section to link back to (used for creating the links)
6982618e
AN
3364 * @throws moodle_exception if the plugin doesn't support duplication
3365 * @return Object containing:
3366 * - fullcontent: The HTML markup for the created CM
3367 * - cmid: The CMID of the newly created CM
3368 * - redirect: Whether to trigger a redirect following this change
3369 */
3370function mod_duplicate_activity($course, $cm, $sr = null) {
0a3d81c2
AA
3371 global $PAGE;
3372
3373 $newcm = duplicate_module($course, $cm);
3374
3375 $resp = new stdClass();
3376 if ($newcm) {