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