MDL-40604 Fix 2 uses causing unit test failures
[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
f8311def 408 $brokenurl=(textlib::strlen($log->url)==100 && textlib::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 }
d57aa283
MG
1042 collatorlib::asort($modnames[0]);
1043 collatorlib::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');
1239 $cats = coursecat::make_categories_list();
0705ff84 1240 foreach ($cats as $key => $value) {
4e0b6025 1241 $cats[$key] = str_repeat('&nbsp;', coursecat::get($key)->depth - 1). $value;
0705ff84 1242 }
1243 return $cats;
1244}
c2cb4545 1245
77eddcd5 1246/**
1247 * Print the buttons relating to course requests.
1248 *
8e57a6df 1249 * @param object $context current page context.
77eddcd5 1250 */
8e57a6df 1251function print_course_request_buttons($context) {
b4531207 1252 global $CFG, $DB, $OUTPUT;
77eddcd5 1253 if (empty($CFG->enablecourserequests)) {
1254 return;
1255 }
8e57a6df 1256 if (!has_capability('moodle/course:create', $context) && has_capability('moodle/course:request', $context)) {
77eddcd5 1257 /// Print a button to request a new course
8e57a6df 1258 echo $OUTPUT->single_button(new moodle_url('/course/request.php'), get_string('requestcourse'), 'get');
77eddcd5 1259 }
1260 /// Print a button to manage pending requests
8e57a6df 1261 if ($context->contextlevel == CONTEXT_SYSTEM && has_capability('moodle/site:approvecourse', $context)) {
5c2ed7e2 1262 $disabled = !$DB->record_exists('course_request', array());
8e57a6df 1263 echo $OUTPUT->single_button(new moodle_url('/course/pending.php'), get_string('coursespending'), 'get', array('disabled' => $disabled));
77eddcd5 1264 }
1265}
1266
5048e034 1267/**
1268 * Does the user have permission to edit things in this category?
1269 *
1270 * @param integer $categoryid The id of the category we are showing, or 0 for system context.
1271 * @return boolean has_any_capability(array(...), ...); in the appropriate context.
1272 */
1273function can_edit_in_category($categoryid = 0) {
1274 $context = get_category_or_system_context($categoryid);
1275 return has_any_capability(array('moodle/category:manage', 'moodle/course:create'), $context);
1276}
1277
11b0c469 1278/// MODULE FUNCTIONS /////////////////////////////////////////////////////////////////
1279
1280function add_course_module($mod) {
cb6fec1f 1281 global $DB;
11b0c469 1282
e5dfd0f3 1283 $mod->added = time();
53f4ad2c 1284 unset($mod->id);
11b0c469 1285
38b19bbc
MG
1286 $cmid = $DB->insert_record("course_modules", $mod);
1287 rebuild_course_cache($mod->course, true);
1288 return $cmid;
11b0c469 1289}
1290
97928ddf 1291/**
4ede27b2 1292 * Creates missing course section(s) and rebuilds course cache
99e9f9a6 1293 *
b46be6ad 1294 * @param int|stdClass $courseorid course id or course object
4ede27b2
MG
1295 * @param int|array $sections list of relative section numbers to create
1296 * @return bool if there were any sections created
97928ddf 1297 */
b46be6ad 1298function course_create_sections_if_missing($courseorid, $sections) {
cb6fec1f 1299 global $DB;
4ede27b2
MG
1300 if (!is_array($sections)) {
1301 $sections = array($sections);
1302 }
b46be6ad
MG
1303 $existing = array_keys(get_fast_modinfo($courseorid)->get_section_info_all());
1304 if (is_object($courseorid)) {
1305 $courseorid = $courseorid->id;
1306 }
4ede27b2
MG
1307 $coursechanged = false;
1308 foreach ($sections as $sectionnum) {
1309 if (!in_array($sectionnum, $existing)) {
1310 $cw = new stdClass();
b46be6ad 1311 $cw->course = $courseorid;
4ede27b2
MG
1312 $cw->section = $sectionnum;
1313 $cw->summary = '';
1314 $cw->summaryformat = FORMAT_HTML;
1315 $cw->sequence = '';
1316 $id = $DB->insert_record("course_sections", $cw);
1317 $coursechanged = true;
1318 }
1319 }
1320 if ($coursechanged) {
b46be6ad 1321 rebuild_course_cache($courseorid, true);
4ede27b2
MG
1322 }
1323 return $coursechanged;
97928ddf 1324}
52f14061 1325
ece966f0 1326/**
722e6ba9 1327 * Adds an existing module to the section
ece966f0 1328 *
722e6ba9
MG
1329 * Updates both tables {course_sections} and {course_modules}
1330 *
1331 * @param int|stdClass $courseorid course id or course object
46453565 1332 * @param int $cmid id of the module already existing in course_modules table
722e6ba9
MG
1333 * @param int $sectionnum relative number of the section (field course_sections.section)
1334 * If section does not exist it will be created
1335 * @param int|stdClass $beforemod id or object with field id corresponding to the module
1336 * before which the module needs to be included. Null for inserting in the
1337 * end of the section
1338 * @return int The course_sections ID where the module is inserted
ece966f0 1339 */
46453565 1340function course_add_cm_to_section($courseorid, $cmid, $sectionnum, $beforemod = null) {
722e6ba9
MG
1341 global $DB, $COURSE;
1342 if (is_object($beforemod)) {
1343 $beforemod = $beforemod->id;
1344 }
46453565
PS
1345 if (is_object($courseorid)) {
1346 $courseid = $courseorid->id;
1347 } else {
1348 $courseid = $courseorid;
1349 }
b46be6ad 1350 course_create_sections_if_missing($courseorid, $sectionnum);
46453565
PS
1351 // Do not try to use modinfo here, there is no guarantee it is valid!
1352 $section = $DB->get_record('course_sections', array('course'=>$courseid, 'section'=>$sectionnum), '*', MUST_EXIST);
722e6ba9 1353 $modarray = explode(",", trim($section->sequence));
281d730e 1354 if (empty($section->sequence)) {
46453565 1355 $newsequence = "$cmid";
722e6ba9 1356 } else if ($beforemod && ($key = array_keys($modarray, $beforemod))) {
46453565 1357 $insertarray = array($cmid, $beforemod);
722e6ba9
MG
1358 array_splice($modarray, $key[0], 1, $insertarray);
1359 $newsequence = implode(",", $modarray);
1360 } else {
46453565 1361 $newsequence = "$section->sequence,$cmid";
722e6ba9
MG
1362 }
1363 $DB->set_field("course_sections", "sequence", $newsequence, array("id" => $section->id));
46453565 1364 $DB->set_field('course_modules', 'section', $section->id, array('id' => $cmid));
b46be6ad
MG
1365 if (is_object($courseorid)) {
1366 rebuild_course_cache($courseorid->id, true);
1367 } else {
1368 rebuild_course_cache($courseorid, true);
1369 }
722e6ba9 1370 return $section->id; // Return course_sections ID that was used.
11b0c469 1371}
1372
48e535bc 1373function set_coursemodule_groupmode($id, $groupmode) {
cb6fec1f 1374 global $DB;
38b19bbc
MG
1375 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,groupmode', MUST_EXIST);
1376 if ($cm->groupmode != $groupmode) {
1377 $DB->set_field('course_modules', 'groupmode', $groupmode, array('id' => $cm->id));
1378 rebuild_course_cache($cm->course, true);
1379 }
1380 return ($cm->groupmode != $groupmode);
3d575e6f 1381}
1382
177d4abf 1383function set_coursemodule_idnumber($id, $idnumber) {
cb6fec1f 1384 global $DB;
38b19bbc
MG
1385 $cm = $DB->get_record('course_modules', array('id' => $id), 'id,course,idnumber', MUST_EXIST);
1386 if ($cm->idnumber != $idnumber) {
1387 $DB->set_field('course_modules', 'idnumber', $idnumber, array('id' => $cm->id));
1388 rebuild_course_cache($cm->course, true);
1389 }
1390 return ($cm->idnumber != $idnumber);
177d4abf 1391}
4e781c7b 1392
02f66c42 1393/**
00a34234
FM
1394 * Set the visibility of a module and inherent properties.
1395 *
1396 * From 2.4 the parameter $prevstateoverrides has been removed, the logic it triggered
1397 * has been moved to {@link set_section_visible()} which was the only place from which
1398 * the parameter was used.
1399 *
1400 * @param int $id of the module
1401 * @param int $visible state of the module
1402 * @return bool false when the module was not found, true otherwise
1403 */
1404function set_coursemodule_visible($id, $visible) {
f5e2602a 1405 global $DB, $CFG;
0f078024
DM
1406 require_once($CFG->libdir.'/gradelib.php');
1407
00a34234
FM
1408 // Trigger developer's attention when using the previously removed argument.
1409 if (func_num_args() > 2) {
1410 debugging('Wrong number of arguments passed to set_coursemodule_visible(), $prevstateoverrides
1411 has been removed.', DEBUG_DEVELOPER);
1412 }
1413
cb6fec1f 1414 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
978abb42 1415 return false;
1416 }
40fcc261
AD
1417
1418 // Create events and propagate visibility to associated grade items if the value has changed.
1419 // Only do this if it's changed to avoid accidently overwriting manual showing/hiding of student grades.
1420 if ($cm->visible == $visible) {
1421 return true;
1422 }
1423
cb6fec1f 1424 if (!$modulename = $DB->get_field('modules', 'name', array('id'=>$cm->module))) {
978abb42 1425 return false;
1426 }
cb6fec1f 1427 if ($events = $DB->get_records('event', array('instance'=>$cm->instance, 'modulename'=>$modulename))) {
dcd338ff 1428 foreach($events as $event) {
48e535bc 1429 if ($visible) {
379cd2d4
EL
1430 $event = new calendar_event($event);
1431 $event->toggle_visibility(true);
48e535bc 1432 } else {
379cd2d4
EL
1433 $event = new calendar_event($event);
1434 $event->toggle_visibility(false);
48e535bc 1435 }
dcd338ff 1436 }
1437 }
f5e2602a 1438
40fcc261 1439 // Hide the associated grade items so the teacher doesn't also have to go to the gradebook and hide them there.
0f078024
DM
1440 $grade_items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$modulename, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course));
1441 if ($grade_items) {
1442 foreach ($grade_items as $grade_item) {
1443 $grade_item->set_hidden(!$visible);
1444 }
f5e2602a 1445 }
f685e830 1446
00a34234
FM
1447 // Updating visible and visibleold to keep them in sync. Only changing a section visibility will
1448 // affect visibleold to allow for an original visibility restore. See set_section_visible().
1449 $cminfo = new stdClass();
1450 $cminfo->id = $id;
1451 $cminfo->visible = $visible;
1452 $cminfo->visibleold = $visible;
1453 $DB->update_record('course_modules', $cminfo);
1454
38b19bbc
MG
1455 rebuild_course_cache($cm->course, true);
1456 return true;
1acfbce5 1457}
1458
cb6fec1f 1459/**
a347aee3
MN
1460 * This function will handles the whole deletion process of a module. This includes calling
1461 * the modules delete_instance function, deleting files, events, grades, conditional data,
1462 * the data in the course_module and course_sections table and adding a module deletion
1463 * event to the DB.
290130b3 1464 *
a347aee3
MN
1465 * @param int $cmid the course module id
1466 * @since 2.5
290130b3 1467 */
a347aee3
MN
1468function course_delete_module($cmid) {
1469 global $CFG, $DB, $USER;
1470
f615fbab 1471 require_once($CFG->libdir.'/gradelib.php');
cae83708 1472 require_once($CFG->dirroot.'/blog/lib.php');
f615fbab 1473
a347aee3
MN
1474 // Get the course module.
1475 if (!$cm = $DB->get_record('course_modules', array('id' => $cmid))) {
290130b3 1476 return true;
1477 }
a347aee3
MN
1478
1479 // Get the module context.
1480 $modcontext = context_module::instance($cm->id);
1481
1482 // Get the course module name.
1483 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module), MUST_EXIST);
1484
1485 // Get the file location of the delete_instance function for this module.
1486 $modlib = "$CFG->dirroot/mod/$modulename/lib.php";
1487
1488 // Include the file required to call the delete_instance function for this module.
1489 if (file_exists($modlib)) {
1490 require_once($modlib);
1491 } else {
9a9cb741
MN
1492 throw new moodle_exception('cannotdeletemodulemissinglib', '', '', null,
1493 "Cannot delete this module as the file mod/$modulename/lib.php is missing.");
a347aee3
MN
1494 }
1495
9a9cb741 1496 $deleteinstancefunction = $modulename . '_delete_instance';
a347aee3 1497
9a9cb741
MN
1498 // Ensure the delete_instance function exists for this module.
1499 if (!function_exists($deleteinstancefunction)) {
1500 throw new moodle_exception('cannotdeletemodulemissingfunc', '', '', null,
1501 "Cannot delete this module as the function {$modulename}_delete_instance is missing in mod/$modulename/lib.php.");
1502 }
1503
1504 // Call the delete_instance function, if it returns false throw an exception.
a347aee3 1505 if (!$deleteinstancefunction($cm->instance)) {
9a9cb741
MN
1506 throw new moodle_exception('cannotdeletemoduleinstance', '', '', null,
1507 "Cannot delete the module $modulename (instance).");
a347aee3
MN
1508 }
1509
1510 // Remove all module files in case modules forget to do that.
1511 $fs = get_file_storage();
1512 $fs->delete_area_files($modcontext->id);
1513
1514 // Delete events from calendar.
1515 if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) {
dcd338ff 1516 foreach($events as $event) {
0ea03696 1517 delete_event($event->id);
dcd338ff 1518 }
1519 }
a347aee3
MN
1520
1521 // Delete grade items, outcome items and grades attached to modules.
1522 if ($grade_items = grade_item::fetch_all(array('itemtype' => 'mod', 'itemmodule' => $modulename,
1523 'iteminstance' => $cm->instance, 'courseid' => $cm->course))) {
f615fbab 1524 foreach ($grade_items as $grade_item) {
1525 $grade_item->delete('moddelete');
1526 }
f615fbab 1527 }
a347aee3 1528
46e12372
SM
1529 // Delete completion and availability data; it is better to do this even if the
1530 // features are not turned on, in case they were turned on previously (these will be
a347aee3 1531 // very quick on an empty table).
46e12372
SM
1532 $DB->delete_records('course_modules_completion', array('coursemoduleid' => $cm->id));
1533 $DB->delete_records('course_modules_availability', array('coursemoduleid'=> $cm->id));
a8f84c28 1534 $DB->delete_records('course_modules_avail_fields', array('coursemoduleid' => $cm->id));
ede323e2
ARN
1535 $DB->delete_records('course_completion_criteria', array('moduleinstance' => $cm->id,
1536 'criteriatype' => COMPLETION_CRITERIA_TYPE_ACTIVITY));
06b3a6b2 1537
a347aee3 1538 // Delete the context.
c592eea2 1539 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
a347aee3
MN
1540
1541 // Delete the module from the course_modules table.
1542 $DB->delete_records('course_modules', array('id' => $cm->id));
1543
1544 // Delete module from that section.
1545 if (!delete_mod_from_section($cm->id, $cm->section)) {
9a9cb741
MN
1546 throw new moodle_exception('cannotdeletemodulefromsection', '', '', null,
1547 "Cannot delete the module $modulename (instance) from section.");
a347aee3
MN
1548 }
1549
1550 // Trigger a mod_deleted event with information about this module.
1551 $eventdata = new stdClass();
1552 $eventdata->modulename = $modulename;
1553 $eventdata->cmid = $cm->id;
1554 $eventdata->courseid = $cm->course;
1555 $eventdata->userid = $USER->id;
1556 events_trigger('mod_deleted', $eventdata);
1557
1558 add_to_log($cm->course, 'course', "delete mod",
1559 "view.php?id=$cm->course",
1560 "$modulename $cm->instance", $cm->id);
1561
38b19bbc 1562 rebuild_course_cache($cm->course, true);
11b0c469 1563}
1564
722e6ba9 1565function delete_mod_from_section($modid, $sectionid) {
cb6fec1f 1566 global $DB;
11b0c469 1567
722e6ba9 1568 if ($section = $DB->get_record("course_sections", array("id"=>$sectionid)) ) {
11b0c469 1569
e5dfd0f3 1570 $modarray = explode(",", $section->sequence);
11b0c469 1571
722e6ba9 1572 if ($key = array_keys ($modarray, $modid)) {
11b0c469 1573 array_splice($modarray, $key[0], 1);
1574 $newsequence = implode(",", $modarray);
38b19bbc
MG
1575 $DB->set_field("course_sections", "sequence", $newsequence, array("id"=>$section->id));
1576 rebuild_course_cache($section->course, true);
1577 return true;
11b0c469 1578 } else {
1579 return false;
1580 }
89adb174 1581
11b0c469 1582 }
7977cffd 1583 return false;
11b0c469 1584}
1585
3440ec12 1586/**
1587 * Moves a section within a course, from a position to another.
1588 * Be very careful: $section and $destination refer to section number,
1589 * not id!.
1590 *
1591 * @param object $course
1592 * @param int $section Section number (not id!!!)
1593 * @param int $destination
1594 * @return boolean Result
1595 */
1596function move_section_to($course, $section, $destination) {
1597/// Moves a whole course section up and down within the course
1598 global $USER, $DB;
1599
ca255392 1600 if (!$destination && $destination != 0) {
3440ec12 1601 return true;
1602 }
1603
850acb35
MG
1604 // compartibility with course formats using field 'numsections'
1605 $courseformatoptions = course_get_format($course)->get_format_options();
1606 if ((array_key_exists('numsections', $courseformatoptions) &&
1607 ($destination > $courseformatoptions['numsections'])) || ($destination < 1)) {
3440ec12 1608 return false;
1609 }
1610
1611 // Get all sections for this course and re-order them (2 of them should now share the same section number)
1612 if (!$sections = $DB->get_records_menu('course_sections', array('course' => $course->id),
1613 'section ASC, id ASC', 'id, section')) {
1614 return false;
1615 }
1616
cf76b335 1617 $movedsections = reorder_sections($sections, $section, $destination);
3440ec12 1618
cf76b335 1619 // Update all sections. Do this in 2 steps to avoid breaking database
1620 // uniqueness constraint
1621 $transaction = $DB->start_delegated_transaction();
1622 foreach ($movedsections as $id => $position) {
1623 if ($sections[$id] !== $position) {
1624 $DB->set_field('course_sections', 'section', -$position, array('id' => $id));
1625 }
1626 }
e7e0f8d2
DP
1627 foreach ($movedsections as $id => $position) {
1628 if ($sections[$id] !== $position) {
1629 $DB->set_field('course_sections', 'section', $position, array('id' => $id));
1630 }
3440ec12 1631 }
1632
15e2552f
RK
1633 // If we move the highlighted section itself, then just highlight the destination.
1634 // Adjust the higlighted section location if we move something over it either direction.
1635 if ($section == $course->marker) {
e7b6e6b9 1636 course_set_marker($course->id, $destination);
2365213f 1637 } elseif ($section > $course->marker && $course->marker >= $destination) {
e7b6e6b9 1638 course_set_marker($course->id, $course->marker+1);
2365213f 1639 } elseif ($section < $course->marker && $course->marker <= $destination) {
e7b6e6b9 1640 course_set_marker($course->id, $course->marker-1);
15e2552f
RK
1641 }
1642
cf76b335 1643 $transaction->allow_commit();
38b19bbc 1644 rebuild_course_cache($course->id, true);
3440ec12 1645 return true;
1646}
1647
1648/**
1649 * Reordering algorithm for course sections. Given an array of section->section indexed by section->id,
1650 * an original position number and a target position number, rebuilds the array so that the
1651 * move is made without any duplication of section positions.
1652 * Note: The target_position is the position AFTER WHICH the moved section will be inserted. If you want to
1653 * insert a section before the first one, you must give 0 as the target (section 0 can never be moved).
1654 *
1655 * @param array $sections
1656 * @param int $origin_position
1657 * @param int $target_position
1658 * @return array
1659 */
1660function reorder_sections($sections, $origin_position, $target_position) {
1661 if (!is_array($sections)) {
1662 return false;
1663 }
1664
1665 // We can't move section position 0
1666 if ($origin_position < 1) {
1667 echo "We can't move section position 0";
1668 return false;
1669 }
1670
1671 // Locate origin section in sections array
1672 if (!$origin_key = array_search($origin_position, $sections)) {
1673 echo "searched position not in sections array";
1674 return false; // searched position not in sections array
1675 }
1676
1677 // Extract origin section
1678 $origin_section = $sections[$origin_key];
1679 unset($sections[$origin_key]);
1680
1681 // Find offset of target position (stupid PHP's array_splice requires offset instead of key index!)
1682 $found = false;
1683 $append_array = array();
1684 foreach ($sections as $id => $position) {
1685 if ($found) {
1686 $append_array[$id] = $position;
1687 unset($sections[$id]);
1688 }
1689 if ($position == $target_position) {
eb01aa2c
RT
1690 if ($target_position < $origin_position) {
1691 $append_array[$id] = $position;
1692 unset($sections[$id]);
1693 }
3440ec12 1694 $found = true;
1695 }
1696 }
1697
1698 // Append moved section
1699 $sections[$origin_key] = $origin_section;
1700
1701 // Append rest of array (if applicable)
1702 if (!empty($append_array)) {
1703 foreach ($append_array as $id => $position) {
1704 $sections[$id] = $position;
1705 }
1706 }
1707
1708 // Renumber positions
1709 $position = 0;
1710 foreach ($sections as $id => $p) {
1711 $sections[$id] = $position;
1712 $position++;
1713 }
1714
1715 return $sections;
1716
1717}
1718
cb6fec1f 1719/**
1720 * Move the module object $mod to the specified $section
1721 * If $beforemod exists then that is the module
1722 * before which $modid should be inserted
1723 * All parameters are objects
1724 */
7977cffd 1725function moveto_module($mod, $section, $beforemod=NULL) {
a83dd077 1726 global $OUTPUT, $DB;
7977cffd 1727
1728/// Remove original module from original section
7977cffd 1729 if (! delete_mod_from_section($mod->id, $mod->section)) {
e6db3026 1730 echo $OUTPUT->notification("Could not delete module from existing section");
7977cffd 1731 }
1732
722e6ba9 1733 // if moving to a hidden section then hide module
bb1592c8
CF
1734 if ($mod->section != $section->id) {
1735 if (!$section->visible && $mod->visible) {
1736 // Set this in the object because it is sent as a response to ajax calls.
1737 $mod->visible = 0;
1738 set_coursemodule_visible($mod->id, 0);
1739 // Set visibleold to 1 so module will be visible when section is made visible.
1740 $DB->set_field('course_modules', 'visibleold', 1, array('id' => $mod->id));
1741 }
1742 if ($section->visible && !$mod->visible) {
1743 set_coursemodule_visible($mod->id, $mod->visibleold);
1744 // Set this in the object because it is sent as a response to ajax calls.
1745 $mod->visible = $mod->visibleold;
1746 }
7977cffd 1747 }
1748
1749/// Add the module into the new section
722e6ba9 1750 course_add_cm_to_section($section->course, $mod->id, $section->section, $beforemod);
7977cffd 1751 return true;
7977cffd 1752}
1753
f558b291
MG
1754/**
1755 * Returns the list of all editing actions that current user can perform on the module
1756 *
1757 * @param cm_info $mod The module to produce editing buttons for
1758 * @param int $indent The current indenting (default -1 means no move left-right actions)
1759 * @param int $sr The section to link back to (used for creating the links)
1760 * @return array array of action_link or pix_icon objects
1761 */
1762function course_get_cm_edit_actions(cm_info $mod, $indent = -1, $sr = null) {
1763 global $COURSE, $SITE;
94361e02 1764
3d575e6f 1765 static $str;
1766
9a5e297b
AA
1767 $coursecontext = context_course::instance($mod->course);
1768 $modcontext = context_module::instance($mod->id);
7749e187 1769
af189935
PS
1770 $editcaps = array('moodle/course:manageactivities', 'moodle/course:activityvisibility', 'moodle/role:assign');
1771 $dupecaps = array('moodle/backup:backuptargetimport', 'moodle/restore:restoretargetimport');
1772
1773 // no permission to edit anything
1774 if (!has_any_capability($editcaps, $modcontext) and !has_all_capabilities($dupecaps, $coursecontext)) {
f558b291 1775 return array();
217a8ee9 1776 }
1777
af189935
PS
1778 $hasmanageactivities = has_capability('moodle/course:manageactivities', $modcontext);
1779
3d575e6f 1780 if (!isset($str)) {
f558b291
MG
1781 $str = get_strings(array('delete', 'move', 'moveright', 'moveleft',
1782 'update', 'duplicate', 'hide', 'show', 'edittitle'), 'moodle');
1783 $str->assign = get_string('assignroles', 'role');
6dc5908e
ARN
1784 $str->groupsnone = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsnone"));
1785 $str->groupsseparate = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsseparate"));
1786 $str->groupsvisible = get_string('clicktochangeinbrackets', 'moodle', get_string("groupsvisible"));
1787 $str->forcedgroupsnone = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsnone"));
1788 $str->forcedgroupsseparate = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsseparate"));
1789 $str->forcedgroupsvisible = get_string('forcedmodeinbrackets', 'moodle', get_string("groupsvisible"));
1acfbce5 1790 }
94361e02 1791
af189935 1792 $baseurl = new moodle_url('/course/mod.php', array('sesskey' => sesskey()));
24e1eae4 1793
f558b291
MG
1794 if ($sr !== null) {
1795 $baseurl->param('sr', $sr);
7749e187
SH
1796 }
1797 $actions = array();
1798
7a9a07d2 1799 // AJAX edit title
9ecb50e6 1800 if ($mod->has_view() && $hasmanageactivities &&
f558b291
MG
1801 (($mod->course == $COURSE->id && course_ajax_enabled($COURSE)) ||
1802 ($mod->course == SITEID && course_ajax_enabled($SITE)))) {
1803 // we will not display link if we are on some other-course page (where we should not see this module anyway)
1804 $actions['title'] = new action_link(
7a9a07d2 1805 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 1806 new pix_icon('t/editstring', $str->edittitle, 'moodle', array('class' => 'iconsmall visibleifjs', 'title' => '')),
7a9a07d2
ARN
1807 null,
1808 array('class' => 'editing_title', 'title' => $str->edittitle)
1809 );
1810 }
1811
7749e187 1812 // leftright
af189935 1813 if ($hasmanageactivities) {
7749e187
SH
1814 if (right_to_left()) { // Exchange arrows on RTL
1815 $rightarrow = 't/left';
1816 $leftarrow = 't/right';
1817 } else {
1818 $rightarrow = 't/right';
1819 $leftarrow = 't/left';
1820 }
1821
1822 if ($indent > 0) {
f558b291 1823 $actions['moveleft'] = new action_link(
7749e187 1824 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '-1')),
aad982aa 1825 new pix_icon($leftarrow, $str->moveleft, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
1826 null,
1827 array('class' => 'editing_moveleft', 'title' => $str->moveleft)
1828 );
1829 }
1830 if ($indent >= 0) {
f558b291 1831 $actions['moveright'] = new action_link(
7749e187 1832 new moodle_url($baseurl, array('id' => $mod->id, 'indent' => '1')),
aad982aa 1833 new pix_icon($rightarrow, $str->moveright, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
1834 null,
1835 array('class' => 'editing_moveright', 'title' => $str->moveright)
1836 );
1837 }
dc0dc7d5 1838 }
7749e187
SH
1839
1840 // move
af189935 1841 if ($hasmanageactivities) {
f558b291
MG
1842 $actions['move'] = new action_link(
1843 new moodle_url($baseurl, array('copy' => $mod->id)),
1844 new pix_icon('t/move', $str->move, 'moodle', array('class' => 'iconsmall', 'title' => '')),
1845 null,
1846 array('class' => 'editing_move', 'title' => $str->move)
1847 );
7749e187
SH
1848 }
1849
1850 // Update
af189935 1851 if ($hasmanageactivities) {
f558b291 1852 $actions['update'] = new action_link(
af189935 1853 new moodle_url($baseurl, array('update' => $mod->id)),
aad982aa 1854 new pix_icon('t/edit', $str->update, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
1855 null,
1856 array('class' => 'editing_update', 'title' => $str->update)
1857 );
1858 }
7749e187 1859
8a1a951f 1860 // Duplicate (require both target import caps to be able to duplicate and backup2 support, see modduplicate.php)
f558b291
MG
1861 // note that restoring on front page is never allowed
1862 if ($mod->course != SITEID && has_all_capabilities($dupecaps, $coursecontext) &&
1863 plugin_supports('mod', $mod->modname, FEATURE_BACKUP_MOODLE2)) {
1864 $actions['duplicate'] = new action_link(
8645a28f 1865 new moodle_url($baseurl, array('duplicate' => $mod->id)),
aad982aa 1866 new pix_icon('t/copy', $str->duplicate, 'moodle', array('class' => 'iconsmall', 'title' => '')),
8645a28f
EL
1867 null,
1868 array('class' => 'editing_duplicate', 'title' => $str->duplicate)
1869 );
1870 }
7749e187
SH
1871
1872 // Delete
af189935 1873 if ($hasmanageactivities) {
f558b291 1874 $actions['delete'] = new action_link(
af189935 1875 new moodle_url($baseurl, array('delete' => $mod->id)),
aad982aa 1876 new pix_icon('t/delete', $str->delete, 'moodle', array('class' => 'iconsmall', 'title' => '')),
af189935
PS
1877 null,
1878 array('class' => 'editing_delete', 'title' => $str->delete)
1879 );
1880 }
7749e187
SH
1881
1882 // hideshow
217a8ee9 1883 if (has_capability('moodle/course:activityvisibility', $modcontext)) {
1884 if ($mod->visible) {
f558b291 1885 $actions['hide'] = new action_link(
7749e187 1886 new moodle_url($baseurl, array('hide' => $mod->id)),
aad982aa 1887 new pix_icon('t/hide', $str->hide, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
1888 null,
1889 array('class' => 'editing_hide', 'title' => $str->hide)
1890 );
217a8ee9 1891 } else {
f558b291 1892 $actions['show'] = new action_link(
7749e187 1893 new moodle_url($baseurl, array('show' => $mod->id)),
aad982aa 1894 new pix_icon('t/show', $str->show, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
1895 null,
1896 array('class' => 'editing_show', 'title' => $str->show)
1897 );
217a8ee9 1898 }
7977cffd 1899 }
530db4cd 1900
7749e187 1901 // groupmode
5c016ab3
MG
1902 if ($hasmanageactivities and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) {
1903 if ($mod->coursegroupmodeforce) {
1904 $modgroupmode = $mod->coursegroupmode;
1905 } else {
1906 $modgroupmode = $mod->groupmode;
1907 }
1908 if ($modgroupmode == SEPARATEGROUPS) {
f558b291 1909 $groupmode = NOGROUPS;
32d03b7b 1910 $grouptitle = $str->groupsseparate;
6dc5908e 1911 $forcedgrouptitle = $str->forcedgroupsseparate;
f558b291 1912 $actionname = 'groupsseparate';
7749e187 1913 $groupimage = 't/groups';
5c016ab3 1914 } else if ($modgroupmode == VISIBLEGROUPS) {
f558b291 1915 $groupmode = SEPARATEGROUPS;
32d03b7b 1916 $grouptitle = $str->groupsvisible;
6dc5908e 1917 $forcedgrouptitle = $str->forcedgroupsvisible;
f558b291 1918 $actionname = 'groupsvisible';
7749e187 1919 $groupimage = 't/groupv';
32d03b7b 1920 } else {
f558b291 1921 $groupmode = VISIBLEGROUPS;
32d03b7b 1922 $grouptitle = $str->groupsnone;
6dc5908e 1923 $forcedgrouptitle = $str->forcedgroupsnone;
f558b291 1924 $actionname = 'groupsnone';
7749e187 1925 $groupimage = 't/groupn';
32d03b7b 1926 }
5c016ab3 1927 if (!$mod->coursegroupmodeforce) {
f558b291 1928 $actions[$actionname] = new action_link(
7749e187 1929 new moodle_url($baseurl, array('id' => $mod->id, 'groupmode' => $groupmode)),
aad982aa 1930 new pix_icon($groupimage, $grouptitle, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187 1931 null,
f558b291 1932 array('class' => 'editing_'. $actionname, 'title' => $grouptitle)
7749e187 1933 );
3d575e6f 1934 } else {
f558b291 1935 $actions[$actionname] = new pix_icon($groupimage, $forcedgrouptitle, 'moodle', array('title' => $forcedgrouptitle, 'class' => 'iconsmall'));
3d575e6f 1936 }
7977cffd 1937 }
1938
7749e187 1939 // Assign
af189935 1940 if (has_capability('moodle/role:assign', $modcontext)){
f558b291
MG
1941 $actions['assign'] = new action_link(
1942 new moodle_url('/admin/roles/assign.php', array('contextid' => $modcontext->id)),
fbb207c5 1943 new pix_icon('t/assignroles', $str->assign, 'moodle', array('class' => 'iconsmall', 'title' => '')),
7749e187
SH
1944 null,
1945 array('class' => 'editing_assign', 'title' => $str->assign)
1946 );
1947 }
1948
f558b291 1949 return $actions;
90845098 1950}
1951
b61efafb 1952/**
264867fd 1953 * given a course object with shortname & fullname, this function will
b61efafb 1954 * truncate the the number of chars allowed and add ... if it was too long
1955 */
1956function course_format_name ($course,$max=100) {
264867fd 1957
9a5e297b 1958 $context = context_course::instance($course->id);
8ebbb06a 1959 $shortname = format_string($course->shortname, true, array('context' => $context));
9a5e297b 1960 $fullname = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
d1e36240 1961 $str = $shortname.': '. $fullname;
138c7678 1962 if (textlib::strlen($str) <= $max) {
b61efafb 1963 return $str;
1964 }
1965 else {
138c7678 1966 return textlib::substr($str,0,$max-3).'...';
b61efafb 1967 }
1968}
1969
0705ff84 1970/**
9665ecd2
TH
1971 * Is the user allowed to add this type of module to this course?
1972 * @param object $course the course settings. Only $course->id is used.
1973 * @param string $modname the module name. E.g. 'forum' or 'quiz'.
1974 * @return bool whether the current user is allowed to add this type of module to this course.
0705ff84 1975 */
9665ecd2 1976function course_allowed_module($course, $modname) {
9665ecd2
TH
1977 if (is_numeric($modname)) {
1978 throw new coding_exception('Function course_allowed_module no longer
1979 supports numeric module ids. Please update your code to pass the module name.');
0705ff84 1980 }
264867fd 1981
9665ecd2
TH
1982 $capability = 'mod/' . $modname . ':addinstance';
1983 if (!get_capability_info($capability)) {
1984 // Debug warning that the capability does not exist, but no more than once per page.
1985 static $warned = array();
1986 $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
1987 if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
1988 debugging('The module ' . $modname . ' does not define the standard capability ' .
1989 $capability , DEBUG_DEVELOPER);
1990 $warned[$modname] = 1;
1991 }
ddb0a19f 1992
9665ecd2
TH
1993 // If the capability does not exist, the module can always be added.
1994 return true;
0705ff84 1995 }
238c0dd9 1996
9665ecd2
TH
1997 $coursecontext = context_course::instance($course->id);
1998 return has_capability($capability, $coursecontext);
0705ff84 1999}
2000
cb6fec1f 2001/**
2002 * Efficiently moves many courses around while maintaining
2003 * sortorder in order.
2004 *
e92c39ca
PS
2005 * @param array $courseids is an array of course ids
2006 * @param int $categoryid
df997f84 2007 * @return bool success
cb6fec1f 2008 */
2009function move_courses($courseids, $categoryid) {
e6db3026 2010 global $CFG, $DB, $OUTPUT;
861efb19 2011
df997f84
PS
2012 if (empty($courseids)) {
2013 // nothing to do
2014 return;
2015 }
264867fd 2016
df997f84
PS
2017 if (!$category = $DB->get_record('course_categories', array('id'=>$categoryid))) {
2018 return false;
2019 }
19f601d1 2020
df997f84 2021 $courseids = array_reverse($courseids);
9a5e297b 2022 $newparent = context_coursecat::instance($category->id);
df997f84 2023 $i = 1;
0cbe8111 2024
df997f84
PS
2025 foreach ($courseids as $courseid) {
2026 if ($course = $DB->get_record('course', array('id'=>$courseid), 'id, category')) {
77bf97e3
MG
2027 $course = new stdClass();
2028 $course->id = $courseid;
df997f84
PS
2029 $course->category = $category->id;
2030 $course->sortorder = $category->sortorder + MAX_COURSES_IN_CATEGORY - $i++;
2031 if ($category->visible == 0) {
2032 // hide the course when moving into hidden category,
2033 // do not update the visibleold flag - we want to get to previous state if somebody unhides the category
2034 $course->visible = 0;
861efb19 2035 }
df997f84
PS
2036
2037 $DB->update_record('course', $course);
95d1d037 2038 add_to_log($course->id, "course", "move", "edit.php?id=$course->id", $course->id);
df997f84 2039
9a5e297b 2040 $context = context_course::instance($course->id);
2c5b0eb7 2041 $context->update_moved($newparent);
264867fd 2042 }
0cbe8111 2043 }
df997f84 2044 fix_course_sortorder();
eabbfa82 2045 cache_helper::purge_by_event('changesincourse');
df997f84 2046
861efb19 2047 return true;
2048}
2049
ae628043 2050/**
ee7084e9 2051 * Returns the display name of the given section that the course prefers
7487c856 2052 *
ee7084e9
MG
2053 * Implementation of this function is provided by course format
2054 * @see format_base::get_section_name()
7487c856 2055 *
ee7084e9
MG
2056 * @param int|stdClass $courseorid The course to get the section name for (object or just course id)
2057 * @param int|stdClass $section Section object from database or just field course_sections.section
2058 * @return string Display name that the course format prefers, e.g. "Week 2"
ae628043 2059 */
ee7084e9
MG
2060function get_section_name($courseorid, $section) {
2061 return course_get_format($courseorid)->get_section_name($section);
7487c856
SH
2062}
2063
2064/**
ee7084e9 2065 * Tells if current course format uses sections
1b048629 2066 *
7487c856 2067 * @param string $format Course format ID e.g. 'weeks' $course->format
ee7084e9 2068 * @return bool
7487c856 2069 */
7487c856 2070function course_format_uses_sections($format) {
ee7084e9
MG
2071 $course = new stdClass();
2072 $course->format = $format;
2073 return course_get_format($course)->uses_sections();
ae628043 2074}
2075
c0b5d925
DM
2076/**
2077 * Returns the information about the ajax support in the given source format
2078 *
2079 * The returned object's property (boolean)capable indicates that
2080 * the course format supports Moodle course ajax features.
2081 * The property (array)testedbrowsers can be used as a parameter for {@see ajaxenabled()}.
2082 *
2083 * @param string $format
2084 * @return stdClass
2085 */
2086function course_format_ajax_support($format) {
ee7084e9
MG
2087 $course = new stdClass();
2088 $course->format = $format;
2089 return course_get_format($course)->supports_ajax();
c0b5d925
DM
2090}
2091
2585a68d 2092/**
2093 * Can the current user delete this course?
8b449a39 2094 * Course creators have exception,
2095 * 1 day after the creation they can sill delete the course.
2585a68d 2096 * @param int $courseid
2097 * @return boolean
2585a68d 2098 */
2099function can_delete_course($courseid) {
8b449a39 2100 global $USER, $DB;
2585a68d 2101
9a5e297b 2102 $context = context_course::instance($courseid);
2585a68d 2103
8b449a39 2104 if (has_capability('moodle/course:delete', $context)) {
2105 return true;
2106 }
2107
2108 // hack: now try to find out if creator created this course recently (1 day)
2109 if (!has_capability('moodle/course:create', $context)) {
2110 return false;
2111 }
2112
2113 $since = time() - 60*60*24;
2114
2115 $params = array('userid'=>$USER->id, 'url'=>"view.php?id=$courseid", 'since'=>$since);
2116 $select = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
2117
2118 return $DB->record_exists_select('log', $select, $params);
2585a68d 2119}
2120
bef12c99 2121/**
2122 * Save the Your name for 'Some role' strings.
2123 *
2124 * @param integer $courseid the id of this course.
2125 * @param array $data the data that came from the course settings form.
2126 */
2127function save_local_role_names($courseid, $data) {
2128 global $DB;
9a5e297b 2129 $context = context_course::instance($courseid);
bef12c99 2130
2131 foreach ($data as $fieldname => $value) {
df997f84 2132 if (strpos($fieldname, 'role_') !== 0) {
bef12c99 2133 continue;
2134 }
2135 list($ignored, $roleid) = explode('_', $fieldname);
2136
2137 // make up our mind whether we want to delete, update or insert
2138 if (!$value) {
2139 $DB->delete_records('role_names', array('contextid' => $context->id, 'roleid' => $roleid));
2140
2141 } else if ($rolename = $DB->get_record('role_names', array('contextid' => $context->id, 'roleid' => $roleid))) {
2142 $rolename->name = $value;
2143 $DB->update_record('role_names', $rolename);
2144
2145 } else {
2146 $rolename = new stdClass;
2147 $rolename->contextid = $context->id;
2148 $rolename->roleid = $roleid;
2149 $rolename->name = $value;
2150 $DB->insert_record('role_names', $rolename);
2151 }
2152 }
2153}
2585a68d 2154
d1f8c1bd
MG
2155/**
2156 * Returns options to use in course overviewfiles filemanager
2157 *
2158 * @param null|stdClass|course_in_list|int $course either object that has 'id' property or just the course id;
2159 * may be empty if course does not exist yet (course create form)
2160 * @return array|null array of options such as maxfiles, maxbytes, accepted_types, etc.
2161 * or null if overviewfiles are disabled
2162 */
2163function course_overviewfiles_options($course) {
2164 global $CFG;
2165 if (empty($CFG->courseoverviewfileslimit)) {
2166 return null;
2167 }
2168 $accepted_types = preg_split('/\s*,\s*/', trim($CFG->courseoverviewfilesext), -1, PREG_SPLIT_NO_EMPTY);
2169 if (in_array('*', $accepted_types) || empty($accepted_types)) {
2170 $accepted_types = '*';
2171 } else {
2172 // Since config for $CFG->courseoverviewfilesext is a text box, human factor must be considered.
2173 // Make sure extensions are prefixed with dot unless they are valid typegroups
2174 foreach ($accepted_types as $i => $type) {
2175 if (substr($type, 0, 1) !== '.') {
2176 require_once($CFG->libdir. '/filelib.php');
2177 if (!count(file_get_typegroup('extension', $type))) {
2178 // It does not start with dot and is not a valid typegroup, this is most likely extension.
2179 $accepted_types[$i] = '.'. $type;
2180 $corrected = true;
2181 }
2182 }
2183 }
2184 if (!empty($corrected)) {
2185 set_config('courseoverviewfilesext', join(',', $accepted_types));
2186 }
2187 }
2188 $options = array(
2189 'maxfiles' => $CFG->courseoverviewfileslimit,
2190 'maxbytes' => $CFG->maxbytes,
2191 'subdirs' => 0,
2192 'accepted_types' => $accepted_types
2193 );
2194 if (!empty($course->id)) {
2195 $options['context'] = context_course::instance($course->id);
2196 } else if (is_int($course) && $course > 0) {
2197 $options['context'] = context_course::instance($course);
2198 }
2199 return $options;
2200}
2201
c3df0901 2202/**
df997f84
PS
2203 * Create a course and either return a $course object
2204 *
2205 * Please note this functions does not verify any access control,
2206 * the calling code is responsible for all validation (usually it is the form definition).
bfefa87e 2207 *
df997f84 2208 * @param array $editoroptions course description editor options
bfefa87e 2209 * @param object $data - all the data needed for an entry in the 'course' table
df997f84 2210 * @return object new course instance
bfefa87e 2211 */
df997f84
PS
2212function create_course($data, $editoroptions = NULL) {
2213 global $CFG, $DB;
bfefa87e 2214
df997f84
PS
2215 //check the categoryid - must be given for all new courses
2216 $category = $DB->get_record('course_categories', array('id'=>$data->category), '*', MUST_EXIST);
71b77297 2217
2218 //check if the shortname already exist
df997f84
PS
2219 if (!empty($data->shortname)) {
2220 if ($DB->record_exists('course', array('shortname' => $data->shortname))) {
71b77297 2221 throw new moodle_exception('shortnametaken');
2222 }
2223 }
2224
2225 //check if the id number already exist
df997f84
PS
2226 if (!empty($data->idnumber)) {
2227 if ($DB->record_exists('course', array('idnumber' => $data->idnumber))) {
71b77297 2228 throw new moodle_exception('idnumbertaken');
2229 }
2230 }
2f48819b 2231
df997f84
PS
2232 $data->timecreated = time();
2233 $data->timemodified = $data->timecreated;
71b77297 2234
df997f84
PS
2235 // place at beginning of any category
2236 $data->sortorder = 0;
00f270bc 2237
df997f84
PS
2238 if ($editoroptions) {
2239 // summary text is updated later, we need context to store the files first
2240 $data->summary = '';
2241 $data->summary_format = FORMAT_HTML;
2242 }
2243
db1218a9
PS
2244 if (!isset($data->visible)) {
2245 // data not from form, add missing visibility info
54a01598 2246 $data->visible = $category->visible;
bfefa87e 2247 }
db1218a9 2248 $data->visibleold = $data->visible;
2585a68d 2249
df997f84 2250 $newcourseid = $DB->insert_record('course', $data);
9a5e297b 2251 $context = context_course::instance($newcourseid, MUST_EXIST);
bfefa87e 2252
df997f84
PS
2253 if ($editoroptions) {
2254 // Save the files used in the summary editor and store
64f93798 2255 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
df997f84
PS
2256 $DB->set_field('course', 'summary', $data->summary, array('id'=>$newcourseid));
2257 $DB->set_field('course', 'summaryformat', $data->summary_format, array('id'=>$newcourseid));
2258 }
d1f8c1bd
MG
2259 if ($overviewfilesoptions = course_overviewfiles_options($newcourseid)) {
2260 // Save the course overviewfiles
2261 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2262 }
bfefa87e 2263
fc79ede5
MG
2264 // update course format options
2265 course_get_format($newcourseid)->update_course_format_options($data);
2266
2267 $course = course_get_format($newcourseid)->get_course();
bfefa87e 2268
df997f84
PS
2269 // Setup the blocks
2270 blocks_add_default_course_blocks($course);
bfefa87e 2271
4ede27b2
MG
2272 // Create a default section.
2273 course_create_sections_if_missing($course, 0);
bfefa87e 2274
df997f84 2275 fix_course_sortorder();
eabbfa82
MG
2276 // purge appropriate caches in case fix_course_sortorder() did not change anything
2277 cache_helper::purge_by_event('changesincourse');
bfefa87e 2278
df997f84 2279 // new context created - better mark it as dirty
1de02d62 2280 $context->mark_dirty();
bfefa87e 2281
df997f84 2282 // Save any custom role names.
e92c39ca 2283 save_local_role_names($course->id, (array)$data);
bfefa87e 2284
df997f84
PS
2285 // set up enrolments
2286 enrol_course_updated(true, $course, $data);
bef12c99 2287
df997f84 2288 add_to_log(SITEID, 'course', 'new', 'view.php?id='.$course->id, $data->fullname.' (ID '.$course->id.')');
2942a5cd 2289
df997f84
PS
2290 // Trigger events
2291 events_trigger('course_created', $course);
bfefa87e 2292
df997f84 2293 return $course;
bfefa87e 2294}
2295
c3df0901 2296/**
df997f84
PS
2297 * Update a course.
2298 *
2299 * Please note this functions does not verify any access control,
2300 * the calling code is responsible for all validation (usually it is the form definition).
bfefa87e 2301 *
2302 * @param object $data - all the data needed for an entry in the 'course' table
df997f84
PS
2303 * @param array $editoroptions course description editor options
2304 * @return void
bfefa87e 2305 */
df997f84
PS
2306function update_course($data, $editoroptions = NULL) {
2307 global $CFG, $DB;
bfefa87e 2308
df997f84 2309 $data->timemodified = time();
ddb0a19f 2310
fc79ede5 2311 $oldcourse = course_get_format($data->id)->get_course();
9a5e297b 2312 $context = context_course::instance($oldcourse->id);
bfefa87e 2313
df997f84 2314 if ($editoroptions) {
64f93798 2315 $data = file_postupdate_standard_editor($data, 'summary', $editoroptions, $context, 'course', 'summary', 0);
71b77297 2316 }
d1f8c1bd
MG
2317 if ($overviewfilesoptions = course_overviewfiles_options($data->id)) {
2318 $data = file_postupdate_standard_filemanager($data, 'overviewfiles', $overviewfilesoptions, $context, 'course', 'overviewfiles', 0);
2319 }
71b77297 2320
df997f84
PS
2321 if (!isset($data->category) or empty($data->category)) {
2322 // prevent nulls and 0 in category field
bfefa87e 2323 unset($data->category);
2324 }
b80a50f7 2325 $changesincoursecat = $movecat = (isset($data->category) and $oldcourse->category != $data->category);
bfefa87e 2326
db1218a9
PS
2327 if (!isset($data->visible)) {
2328 // data not from form, add missing visibility info
df997f84
PS
2329 $data->visible = $oldcourse->visible;
2330 }
bfefa87e 2331
df997f84
PS
2332 if ($data->visible != $oldcourse->visible) {
2333 // reset the visibleold flag when manually hiding/unhiding course
2334 $data->visibleold = $data->visible;
b55248d5 2335 $changesincoursecat = true;
df997f84 2336 } else {
a372aab5 2337 if ($movecat) {
df997f84
PS
2338 $newcategory = $DB->get_record('course_categories', array('id'=>$data->category));
2339 if (empty($newcategory->visible)) {
2340 // make sure when moving into hidden category the course is hidden automatically
2341 $data->visible = 0;
2342 }
a372aab5 2343 }
df997f84 2344 }
a372aab5 2345
df997f84
PS
2346 // Update with the new data
2347 $DB->update_record('course', $data);
38b19bbc
MG
2348 // make sure the modinfo cache is reset
2349 rebuild_course_cache($data->id);
bfefa87e 2350
fc79ede5
MG
2351 // update course format options with full course data
2352 course_get_format($data->id)->update_course_format_options($data, $oldcourse);
2353
df997f84 2354 $course = $DB->get_record('course', array('id'=>$data->id));
bfefa87e 2355
df997f84 2356 if ($movecat) {
9a5e297b 2357 $newparent = context_coursecat::instance($course->category);
2c5b0eb7 2358 $context->update_moved($newparent);
df997f84 2359 }
238c0dd9 2360
df997f84 2361 fix_course_sortorder();
eabbfa82
MG
2362 // purge appropriate caches in case fix_course_sortorder() did not change anything
2363 cache_helper::purge_by_event('changesincourse');
b55248d5 2364 if ($changesincoursecat) {
b80a50f7
MG
2365 cache_helper::purge_by_event('changesincoursecat');
2366 }
bfefa87e 2367
df997f84
PS
2368 // Test for and remove blocks which aren't appropriate anymore
2369 blocks_remove_inappropriate($course);
bfefa87e 2370
df997f84
PS
2371 // Save any custom role names.
2372 save_local_role_names($course->id, $data);
2373
2374 // update enrol settings
2375 enrol_course_updated(false, $course, $data);
2376
2377 add_to_log($course->id, "course", "update", "edit.php?id=$course->id", $course->id);
2378
2379 // Trigger events
2380 events_trigger('course_updated', $course);
fc79ede5
MG
2381
2382 if ($oldcourse->format !== $course->format) {
2383 // Remove all options stored for the previous format
2384 // We assume that new course format migrated everything it needed watching trigger
2385 // 'course_updated' and in method format_XXX::update_course_format_options()
2386 $DB->delete_records('course_format_options',
2387 array('courseid' => $course->id, 'format' => $oldcourse->format));
2388 }
bfefa87e 2389}
2585a68d 2390
07ab0c80 2391/**
fcb4decd 2392 * Average number of participants
07ab0c80 2393 * @return integer
2394 */
2395function average_number_of_participants() {
fcb4decd 2396 global $DB, $SITE;
2397
2398 //count total of enrolments for visible course (except front page)
2399 $sql = 'SELECT COUNT(*) FROM (
2400 SELECT DISTINCT ue.userid, e.courseid
2401 FROM {user_enrolments} ue, {enrol} e, {course} c
516c5eca 2402 WHERE ue.enrolid = e.id
fcb4decd 2403 AND e.courseid <> :siteid
2404 AND c.id = e.courseid
9f247093 2405 AND c.visible = 1) total';
fcb4decd 2406 $params = array('siteid' => $SITE->id);
2407 $enrolmenttotal = $DB->count_records_sql($sql, $params);
2408
2409
2410 //count total of visible courses (minus front page)
2411 $coursetotal = $DB->count_records('course', array('visible' => 1));
2412 $coursetotal = $coursetotal - 1 ;
2413
2414 //average of enrolment
2415 if (empty($coursetotal)) {
2416 $participantaverage = 0;
2417 } else {
2418 $participantaverage = $enrolmenttotal / $coursetotal;
2419 }
2420
2421 return $participantaverage;
07ab0c80 2422}
2423
2424/**
fcb4decd 2425 * Average number of course modules
07ab0c80 2426 * @return integer
2427 */
2428function average_number_of_courses_modules() {
fcb4decd 2429 global $DB, $SITE;
2430
2431 //count total of visible course module (except front page)
2432 $sql = 'SELECT COUNT(*) FROM (
2433 SELECT cm.course, cm.module
2434 FROM {course} c, {course_modules} cm
516c5eca 2435 WHERE c.id = cm.course
fcb4decd 2436 AND c.id <> :siteid
2437 AND cm.visible = 1
9f247093 2438 AND c.visible = 1) total';
fcb4decd 2439 $params = array('siteid' => $SITE->id);
2440 $moduletotal = $DB->count_records_sql($sql, $params);
2441
2442
2443 //count total of visible courses (minus front page)
2444 $coursetotal = $DB->count_records('course', array('visible' => 1));
2445 $coursetotal = $coursetotal - 1 ;
2446
2447 //average of course module
2448 if (empty($coursetotal)) {
2449 $coursemoduleaverage = 0;
2450 } else {
2451 $coursemoduleaverage = $moduletotal / $coursetotal;
2452 }
2453
2454 return $coursemoduleaverage;
07ab0c80 2455}
2456
8bdc9cac
SH
2457/**
2458 * This class pertains to course requests and contains methods associated with
2459 * create, approving, and removing course requests.
2460 *
64f93798
PS
2461 * Please note we do not allow embedded images here because there is no context
2462 * to store them with proper access control.
2463 *
8bdc9cac
SH
2464 * @copyright 2009 Sam Hemelryk
2465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2466 * @since Moodle 2.0
2467 *
2468 * @property-read int $id
2469 * @property-read string $fullname
2470 * @property-read string $shortname
2471 * @property-read string $summary
2472 * @property-read int $summaryformat
2473 * @property-read int $summarytrust
2474 * @property-read string $reason
2475 * @property-read int $requester
8bdc9cac
SH
2476 */
2477class course_request {
2478
2479 /**
2480 * This is the stdClass that stores the properties for the course request
7e85563d 2481 * and is externally accessed through the __get magic method
8bdc9cac
SH
2482 * @var stdClass
2483 */
2484 protected $properties;
2485
2486 /**
2487 * An array of options for the summary editor used by course request forms.
2488 * This is initially set by {@link summary_editor_options()}
2489 * @var array
2490 * @static
2491 */
2492 protected static $summaryeditoroptions;
2493
8bdc9cac
SH
2494 /**
2495 * Static function to prepare the summary editor for working with a course
2496 * request.
2497 *
2498 * @static
2499 * @param null|stdClass $data Optional, an object containing the default values
2500 * for the form, these may be modified when preparing the
2501 * editor so this should be called before creating the form
2502 * @return stdClass An object that can be used to set the default values for
2503 * an mforms form
2504 */
2505 public static function prepare($data=null) {
2506 if ($data === null) {
2507 $data = new stdClass;
2508 }
64f93798 2509 $data = file_prepare_standard_editor($data, 'summary', self::summary_editor_options());
8bdc9cac
SH
2510 return $data;
2511 }
2512
2513 /**
2514 * Static function to create a new course request when passed an array of properties
2515 * for it.
2516 *
2517 * This function also handles saving any files that may have been used in the editor
2518 *
2519 * @static
2520 * @param stdClass $data
2521 * @return course_request The newly created course request
2522 */
2523 public static function create($data) {
2524 global $USER, $DB, $CFG;
2525 $data->requester = $USER->id;
64f93798 2526
d347f304 2527 // Setting the default category if none set.
59b9a140
FM
2528 if (empty($data->category) || empty($CFG->requestcategoryselection)) {
2529 $data->category = $CFG->defaultrequestcategory;
2530 }
2531
64f93798
PS
2532 // Summary is a required field so copy the text over
2533 $data->summary = $data->summary_editor['text'];
2534 $data->summaryformat = $data->summary_editor['format'];
2535
8bdc9cac 2536 $data->id = $DB->insert_record('course_request', $data);
64f93798 2537
8bdc9cac
SH
2538 // Create a new course_request object and return it
2539 $request = new course_request($data);
2540
2541 // Notify the admin if required.
adf176d7 2542 if ($users = get_users_from_config($CFG->courserequestnotify, 'moodle/site:approvecourse')) {
aa6c1ced 2543
8bdc9cac
SH
2544 $a = new stdClass;
2545 $a->link = "$CFG->wwwroot/course/pending.php";
2546 $a->user = fullname($USER);
2547 $subject = get_string('courserequest');
2548 $message = get_string('courserequestnotifyemail', 'admin', $a);
2549 foreach ($users as $user) {
2a63b636 2550 $request->notify($user, $USER, 'courserequested', $subject, $message);
8bdc9cac
SH
2551 }
2552 }
2553
2554 return $request;
2555 }
2556
2557 /**
2558 * Returns an array of options to use with a summary editor
2559 *
2560 * @uses course_request::$summaryeditoroptions
2561 * @return array An array of options to use with the editor
2562 */
2563 public static function summary_editor_options() {
2564 global $CFG;
2565 if (self::$summaryeditoroptions === null) {
64f93798 2566 self::$summaryeditoroptions = array('maxfiles' => 0, 'maxbytes'=>0);
8bdc9cac
SH
2567 }
2568 return self::$summaryeditoroptions;
2569 }
2570
8bdc9cac
SH
2571 /**
2572 * Loads the properties for this course request object. Id is required and if
2573 * only id is provided then we load the rest of the properties from the database
2574 *
2575 * @param stdClass|int $properties Either an object containing properties
2576 * or the course_request id to load
2577 */
2578 public function __construct($properties) {
2579 global $DB;
2580 if (empty($properties->id)) {
2581 if (empty($properties)) {
2582 throw new coding_exception('You must provide a course request id when creating a course_request object');
2583 }
2584 $id = $properties;
2585 $properties = new stdClass;
2586 $properties->id = (int)$id;
2587 unset($id);
2588 }
2589 if (empty($properties->requester)) {
2590 if (!($this->properties = $DB->get_record('course_request', array('id' => $properties->id)))) {
2591 print_error('unknowncourserequest');
2592 }
2593 } else {
2594 $this->properties = $properties;
2595 }
2596 $this->properties->collision = null;
2597 }
2598
2599 /**
2600 * Returns the requested property
2601 *
2602 * @param string $key
2603 * @return mixed
2604 */
2605 public function __get($key) {
8bdc9cac
SH
2606 return $this->properties->$key;
2607 }
2608
2609 /**
2610 * Override this to ensure empty($request->blah) calls return a reliable answer...
2611 *
2612 * This is required because we define the __get method
2613 *
2614 * @param mixed $key
2615 * @return bool True is it not empty, false otherwise
2616 */
2617 public function __isset($key) {
2618 return (!empty($this->properties->$key));
2619 }
2620
2621 /**
2622 * Returns the user who requested this course
2623 *
2624 * Uses a static var to cache the results and cut down the number of db queries
2625 *
2626 * @staticvar array $requesters An array of cached users
2627 * @return stdClass The user who requested the course
2628 */
2629 public function get_requester() {
2630 global $DB;
2631 static $requesters= array();
2632 if (!array_key_exists($this->properties->requester, $requesters)) {
2633 $requesters[$this->properties->requester] = $DB->get_record('user', array('id'=>$this->properties->requester));
2634 }
2635 return $requesters[$this->properties->requester];
2636 }
2637
2638 /**
2639 * Checks that the shortname used by the course does not conflict with any other
2640 * courses that exist
2641 *
2642 * @param string|null $shortnamemark The string to append to the requests shortname
2643 * should a conflict be found
2644 * @return bool true is there is a conflict, false otherwise
2645 */
2646 public function check_shortname_collision($shortnamemark = '[*]') {
2647 global $DB;
2648
2649 if ($this->properties->collision !== null) {
2650 return $this->properties->collision;
2651 }
2652
2653 if (empty($this->properties->shortname)) {
2654 debugging('Attempting to check a course request shortname before it has been set', DEBUG_DEVELOPER);
2655 $this->properties->collision = false;
2656 } else if ($DB->record_exists('course', array('shortname' => $this->properties->shortname))) {
2657 if (!empty($shortnamemark)) {
2658 $this->properties->shortname .= ' '.$shortnamemark;
2659 }
2660 $this->properties->collision = true;
2661 } else {
2662 $this->properties->collision = false;
2663 }
2664 return $this->properties->collision;
2665 }
2666
2d8a275b
MG
2667 /**
2668 * Returns the category where this course request should be created
2669 *
2670 * Note that we don't check here that user has a capability to view
2671 * hidden categories if he has capabilities 'moodle/site:approvecourse' and
2672 * 'moodle/course:changecategory'
2673 *
2674 * @return coursecat
2675 */
2676 public function get_category() {
2677 global $CFG;
2678 require_once($CFG->libdir.'/coursecatlib.php');
2679 // If the category is not set, if the current user does not have the rights to change the category, or if the
2680 // category does not exist, we set the default category to the course to be approved.
2681 // The system level is used because the capability moodle/site:approvecourse is based on a system level.
2682 if (empty($this->properties->category) || !has_capability('moodle/course:changecategory', context_system::instance()) ||
2683 (!$category = coursecat::get($this->properties->category, IGNORE_MISSING, true))) {
2684 $category = coursecat::get($CFG->defaultrequestcategory, IGNORE_MISSING, true);
2685 }
2686 if (!$category) {
2687 $category = coursecat::get_default();
2688 }
2689 return $category;
2690 }
2691
8bdc9cac
SH
2692 /**
2693 * This function approves the request turning it into a course
2694 *
2695 * This function converts the course request into a course, at the same time
7e85563d 2696 * transferring any files used in the summary to the new course and then removing
8bdc9cac
SH
2697 * the course request and the files associated with it.
2698 *
2699 * @return int The id of the course that was created from this request
2700 */
2701 public function approve() {
2702 global $CFG, $DB, $USER;
70740405
PS
2703
2704 $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted'=>0), '*', MUST_EXIST);
2705
8bdc9cac
SH
2706 $courseconfig = get_config('moodlecourse');
2707
2708 // Transfer appropriate settings
70740405
PS
2709 $data = clone($this->properties);
2710 unset($data->id);
2711 unset($data->reason);
2712 unset($data->requester);
8bdc9cac
SH
2713
2714 // Set category
2d8a275b 2715 $category = $this->get_category();
70740405 2716 $data->category = $category->id;
8bdc9cac 2717 // Set misc settings
70740405 2718 $data->requested = 1;
8bdc9cac
SH
2719
2720 // Apply course default settings
70740405 2721 $data->format = $courseconfig->format;
70740405
PS
2722 $data->newsitems = $courseconfig->newsitems;
2723 $data->showgrades = $courseconfig->showgrades;
2724 $data->showreports = $courseconfig->showreports;
2725 $data->maxbytes = $courseconfig->maxbytes;
2726 $data->groupmode = $courseconfig->groupmode;
2727 $data->groupmodeforce = $courseconfig->groupmodeforce;
2728 $data->visible = $courseconfig->visible;
2729 $data->visibleold = $data->visible;
2730 $data->lang = $courseconfig->lang;
8bdc9cac 2731
70740405 2732 $course = create_course($data);
1f364c87 2733 $context = context_course::instance($course->id, MUST_EXIST);
8bdc9cac 2734
70740405
PS
2735 // add enrol instances
2736 if (!$DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
2737 if ($manual = enrol_get_plugin('manual')) {
2738 $manual->add_default_instance($course);
2739 }
8bdc9cac 2740 }
70740405
PS
2741
2742 // enrol the requester as teacher if necessary
2743 if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
2744 enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
2745 }
2746
2747 $this->delete();
2748
fbaea88f 2749 $a = new stdClass();
9a5e297b 2750 $a->name = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
70740405
PS
2751 $a->url = $CFG->wwwroot.'/course/view.php?id=' . $course->id;
2752 $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
2753
2754 return $course->id;
8bdc9cac
SH
2755 }
2756
2757 /**
2758 * Reject a course request
2759 *
2760 * This function rejects a course request, emailing the requesting user the
2761 * provided notice and then removing the request from the database
2762 *
2763 * @param string $notice The message to display to the user
2764 */
2765 public function reject($notice) {
70740405
PS
2766 global $USER, $DB;
2767 $user = $DB->get_record('user', array('id' => $this->properties->requester), '*', MUST_EXIST);
8bdc9cac
SH
2768 $this->notify($user, $USER, 'courserequestrejected', get_string('courserejectsubject'), get_string('courserejectemail', 'moodle', $notice));
2769 $this->delete();
2770 }
2771
2772 /**
2773 * Deletes the course request and any associated files
2774 */
2775 public function delete() {
2776 global $DB;
2777 $DB->delete_records('course_request', array('id' => $this->properties->id));
8bdc9cac
SH
2778 }
2779
2780 /**
2781 * Send a message from one user to another using events_trigger
2782 *
2783 * @param object $touser
2784 * @param object $fromuser
2785 * @param string $name
2786 * @param string $subject
2787 * @param string $message
2788 */
2789 protected function notify($touser, $fromuser, $name='courserequested', $subject, $message) {
fbaea88f 2790 $eventdata = new stdClass();
a1708181 2791 $eventdata->component = 'moodle';
8bdc9cac
SH
2792 $eventdata->name = $name;
2793 $eventdata->userfrom = $fromuser;
2794 $eventdata->userto = $touser;
2795 $eventdata->subject = $subject;
2796 $eventdata->fullmessage = $message;
2797 $eventdata->fullmessageformat = FORMAT_PLAIN;
2798 $eventdata->fullmessagehtml = '';
2799 $eventdata->smallmessage = '';
a1708181 2800 $eventdata->notification = 1;
7c7d3afa 2801 message_send($eventdata);
8bdc9cac 2802 }
5c34c4ba 2803}
b1627a92
DC
2804
2805/**
2806 * Return a list of page types
2807 * @param string $pagetype current page type
9dd85edf
MG
2808 * @param context $parentcontext Block's parent context
2809 * @param context $currentcontext Current context of block
2810 * @return array array of page types
b1627a92 2811 */
b38e2e28 2812function course_page_type_list($pagetype, $parentcontext, $currentcontext) {
9dd85edf
MG
2813 if ($pagetype === 'course-index' || $pagetype === 'course-index-category') {
2814 // For courses and categories browsing pages (/course/index.php) add option to show on ANY category page
2815 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2816 'course-index-*' => get_string('page-course-index-x', 'pagetype'),
2817 );
2818 } else if ($currentcontext && (!($coursecontext = $currentcontext->get_course_context(false)) || $coursecontext->instanceid == SITEID)) {
2819 // We know for sure that despite pagetype starts with 'course-' this is not a page in course context (i.e. /course/search.php, etc.)
2820 $pagetypes = array('*' => get_string('page-x', 'pagetype'));
2821 } else {
2822 // Otherwise consider it a page inside a course even if $currentcontext is null
2823 $pagetypes = array('*' => get_string('page-x', 'pagetype'),
2824 'course-*' => get_string('page-course-x', 'pagetype'),
2825 'course-view-*' => get_string('page-course-view-x', 'pagetype')
2826 );
b1627a92 2827 }
9dd85edf 2828 return $pagetypes;
af27c69e 2829}
ebaa29d1 2830
5720019d
ARN
2831/**
2832 * Determine whether course ajax should be enabled for the specified course
2833 *
924c34df 2834 * @param stdClass $course The course to test against
5720019d
ARN
2835 * @return boolean Whether course ajax is enabled or note
2836 */
2837function course_ajax_enabled($course) {
2838 global $CFG, $PAGE, $SITE;
2839
2840 // Ajax must be enabled globally
2841 if (!$CFG->enableajax) {
2842 return false;
2843 }
2844
2845 // The user must be editing for AJAX to be included
2846 if (!$PAGE->user_is_editing()) {
2847 return false;
2848 }
2849
2850 // Check that the theme suports
2851 if (!$PAGE->theme->enablecourseajax) {
2852 return false;
2853 }
2854
2855 // Check that the course format supports ajax functionality
2856 // The site 'format' doesn't have information on course format support
2857 if ($SITE->id !== $course->id) {
2858 $courseformatajaxsupport = course_format_ajax_support($course->format);
2859 if (!$courseformatajaxsupport->capable) {
2860 return false;
2861 }
2862 }
2863
2864 // All conditions have been met so course ajax should be enabled
2865 return true;
2866}
2867
ebaa29d1
ARN
2868/**
2869 * Include the relevant javascript and language strings for the resource
2870 * toolbox YUI module
2871 *
2872 * @param integer $id The ID of the course being applied to
7b061512
SH
2873 * @param array $usedmodules An array containing the names of the modules in use on the page
2874 * @param array $enabledmodules An array containing the names of the enabled (visible) modules on this site
924c34df 2875 * @param stdClass $config An object containing configuration parameters for ajax modules including:
ebaa29d1
ARN
2876 * * resourceurl The URL to post changes to for resource changes
2877 * * sectionurl The URL to post changes to for section changes
2878 * * pageparams Additional parameters to pass through in the post
7b061512 2879 * @return bool
ebaa29d1 2880 */
7b061512 2881function include_course_ajax($course, $usedmodules = array(), $enabledmodules = null, $config = null) {
924c34df 2882 global $PAGE, $SITE;
ebaa29d1
ARN
2883
2884 // Ensure that ajax should be included
5720019d
ARN
2885 if (!course_ajax_enabled($course)) {
2886 return false;
ebaa29d1
ARN
2887 }
2888
2889 if (!$config) {
2890 $config = new stdClass();
2891 }
2892
2893 // The URL to use for resource changes
2894 if (!isset($config->resourceurl)) {
2895 $config->resourceurl = '/course/rest.php';
2896 }
2897
2898 // The URL to use for section changes
2899 if (!isset($config->sectionurl)) {
2900 $config->sectionurl = '/course/rest.php';
2901 }
2902
2903 // Any additional parameters which need to be included on page submission
2904 if (!isset($config->pageparams)) {
2905 $config->pageparams = array();
2906 }
2907
2908 // Include toolboxes
2909 $PAGE->requires->yui_module('moodle-course-toolboxes',
2910 'M.course.init_resource_toolbox',
2911 array(array(
2912 'courseid' => $course->id,
2913 'ajaxurl' => $config->resourceurl,
2914 'config' => $config,
2915 ))
2916 );
2917 $PAGE->requires->yui_module('moodle-course-toolboxes',
2918 'M.course.init_section_toolbox',
2919 array(array(
2920 'courseid' => $course->id,
2921 'format' => $course->format,
2922 'ajaxurl' => $config->sectionurl,
2923 'config' => $config,
2924 ))
2925 );
2926
15e2552f 2927 // Include course dragdrop
5720019d 2928 if ($course->id != $SITE->id) {
c77582fe 2929 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_section_dragdrop',
15e2552f
RK
2930 array(array(
2931 'courseid' => $course->id,
56838156 2932 'ajaxurl' => $config->sectionurl,
15e2552f
RK
2933 'config' => $config,
2934 )), null, true);
2935
c77582fe 2936 $PAGE->requires->yui_module('moodle-course-dragdrop', 'M.course.init_resource_dragdrop',
15e2552f
RK
2937 array(array(
2938 'courseid' => $course->id,
56838156 2939 'ajaxurl' => $config->resourceurl,
15e2552f
RK
2940 'config' => $config,
2941 )), null, true);
56838156
RK
2942 }
2943
ebaa29d1
ARN
2944 // Require various strings for the command toolbox
2945 $PAGE->requires->strings_for_js(array(
2946 'moveleft',
2947 'deletechecktype',
2948 'deletechecktypename',
7a9a07d2
ARN
2949 'edittitle',
2950 'edittitleinstructions',
ebaa29d1
ARN
2951 'show',
2952 'hide',
2953 'groupsnone',
2954 'groupsvisible',
2955 'groupsseparate',
2956 'clicktochangeinbrackets',
2957 'markthistopic',
2958 'markedthistopic',
15e2552f
RK
2959 'move',
2960 'movesection',
ebaa29d1
ARN
2961 ), 'moodle');
2962
2963 // Include format-specific strings
5720019d 2964 if ($course->id != $SITE->id) {
ebaa29d1
ARN
2965 $PAGE->requires->strings_for_js(array(
2966 'showfromothers',
2967 'hidefromothers',
2968 ), 'format_' . $course->format);
2969 }
2970
2971 // For confirming resource deletion we need the name of the module in question
7b061512 2972 foreach ($usedmodules as $module => $modname) {
ebaa29d1
ARN
2973 $PAGE->requires->string_for_js('pluginname', $module);
2974 }
3aaa1843 2975
32528f94 2976 // Load drag and drop upload AJAX.
7b061512
SH
2977 dndupload_add_to_course($course, $enabledmodules);
2978
5720019d 2979 return true;
ebaa29d1 2980}
5218b9bb 2981
3776335c
MG
2982/**
2983 * Returns the sorted list of available course formats, filtered by enabled if necessary
2984 *
2985 * @param bool $enabledonly return only formats that are enabled
2986 * @return array array of sorted format names
2987 */
2988function get_sorted_course_formats($enabledonly = false) {
2989 global $CFG;
bd3b3bba 2990 $formats = core_component::get_plugin_list('format');
3776335c
MG
2991
2992 if (!empty($CFG->format_plugins_sortorder)) {
2993 $order = explode(',', $CFG->format_plugins_sortorder);
2994 $order = array_merge(array_intersect($order, array_keys($formats)),
2995 array_diff(array_keys($formats), $order));
2996 } else {
2997 $order = array_keys($formats);
2998 }
2999 if (!$enabledonly) {
3000 return $order;
3001 }
3002 $sortedformats = array();
3003 foreach ($order as $formatname) {
3004 if (!get_config('format_'.$formatname, 'disabled')) {
3005 $sortedformats[] = $formatname;
3006 }
3007 }
3008 return $sortedformats;
3009}
3010
5218b9bb
DP
3011/**
3012 * The URL to use for the specified course (with section)
3013 *
ee7084e9
MG
3014 * @param int|stdClass $courseorid The course to get the section name for (either object or just course id)
3015 * @param int|stdClass $section Section object from database or just field course_sections.section
923451c5
MG
3016 * if omitted the course view page is returned
3017 * @param array $options options for view URL. At the moment core uses:
3018 * 'navigation' (bool) if true and section has no separate page, the function returns null
3019 * 'sr' (int) used by multipage formats to specify to which section to return
5218b9bb
DP
3020 * @return moodle_url The url of course
3021 */
ee7084e9
MG
3022function course_get_url($courseorid, $section = null, $options = array()) {
3023 return course_get_format($courseorid)->get_view_url($section, $options);
5218b9bb 3024}
dd5d933f 3025
dd5d933f
JM
3026/**
3027 * Create a module.
7cb0ea2c 3028 *
dd5d933f
JM
3029 * It includes:
3030 * - capability checks and other checks
3031 * - create the module from the module info
3032 *
3033 * @param object $module
3034 * @return object the created module info
3035 */
3036function create_module($moduleinfo) {
80fe0c19
JM
3037 global $DB, $CFG;
3038
3039 require_once($CFG->dirroot . '/course/modlib.php');
3040
dd5d933f
JM
3041 // Check manadatory attributs.
3042 $mandatoryfields = array('modulename', 'course', 'section', 'visible');
3043 if (plugin_supports('mod', $moduleinfo->modulename, FEATURE_MOD_INTRO, true)) {
3044 $mandatoryfields[] = 'introeditor';
3045 }
3046 foreach($mandatoryfields as $mandatoryfield) {
3047 if (!isset($moduleinfo->{$mandatoryfield})) {
3048 throw new moodle_exception('createmodulemissingattribut', '', '', $mandatoryfield);
3049 }
3050 }
3051
7cb0ea2c 3052 // Some additional checks (capability / existing instances).
dd5d933f
JM
3053 $course = $DB->get_record('course', array('id'=>$moduleinfo->course), '*', MUST_EXIST);
3054 list($module, $context, $cw) = can_add_moduleinfo($course, $moduleinfo->modulename, $moduleinfo->section);
3055
3056 // Load module library.
3057 include_modulelib($module->name);
3058
3059 // Add the module.
3060 $moduleinfo->module = $module->id;
3061 $moduleinfo = add_moduleinfo($moduleinfo, $course, null);
3062
3063 return $moduleinfo;
3064}
3065
3066/**
3067 * Update a module.
7cb0ea2c 3068 *
dd5d933f 3069 * It includes:
7cb0ea2c 3070 * - capability and other checks
dd5d933f
JM
3071 * - update the module
3072 *
3073 * @param object $module
3074 * @return object the updated module info
3075 */
3076function update_module($moduleinfo) {
80fe0c19
JM
3077 global $DB, $CFG;
3078
3079 require_once($CFG->dirroot . '/course/modlib.php');
dd5d933f
JM
3080
3081 // Check the course module exists.
3082 $cm = get_coursemodule_from_id('', $moduleinfo->coursemodule, 0, false, MUST_EXIST);
3083
3084 // Check the course exists.
3085 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
3086
7cb0ea2c 3087 // Some checks (capaibility / existing instances).
dd5d933f
JM
3088 list($cm, $context, $module, $data, $cw) = can_update_moduleinfo($cm);
3089
7cb0ea2c 3090 // Load module library.
dd5d933f
JM
3091 include_modulelib($module->name);
3092
7cb0ea2c 3093 // Retrieve few information needed by update_moduleinfo.
dd5d933f
JM
3094 $moduleinfo->modulename = $cm->modname;
3095 if (!isset($moduleinfo->scale)) {
3096 $moduleinfo->scale = 0;
3097 }
3098 $moduleinfo->type = 'mod';
3099
7cb0ea2c 3100 // Update the module.
dd5d933f
JM
3101 list($cm, $moduleinfo) = update_moduleinfo($cm, $moduleinfo, $course, null);
3102
3103 return $moduleinfo;
3104}
3a7e4a80 3105
bf6b3c7a
AA
3106/**
3107 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3108 * Sorts by descending order of time.
3109 *
3110 * @param stdClass $a First object
3111 * @param stdClass $b Second object
3112 * @return int 0,1,-1 representing the order
3113 */
3114function compare_activities_by_time_desc($a, $b) {
3115 // Make sure the activities actually have a timestamp property.
3116 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3117 return 0;
3118 }
3119 // We treat instances without timestamp as if they have a timestamp of 0.
3120 if ((!property_exists($a, 'timestamp')) && (property_exists($b,'timestamp'))) {
3121 return 1;
3122 }
3123 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3124 return -1;
3125 }
3126 if ($a->timestamp == $b->timestamp) {
3127 return 0;
3128 }
3129 return ($a->timestamp > $b->timestamp) ? -1 : 1;
3130}
3131
3132/**
3133 * Compare two objects to find out their correct order based on timestamp (to be used by usort).
3134 * Sorts by ascending order of time.
3135 *
3136 * @param stdClass $a First object
3137 * @param stdClass $b Second object
3138 * @return int 0,1,-1 representing the order
3139 */
3140function compare_activities_by_time_asc($a, $b) {
3141 // Make sure the activities actually have a timestamp property.
3142 if ((!property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3143 return 0;
3144 }
3145 // We treat instances without timestamp as if they have a timestamp of 0.
3146 if ((!property_exists($a, 'timestamp')) && (property_exists($b, 'timestamp'))) {
3147 return -1;
3148 }
3149 if ((property_exists($a, 'timestamp')) && (!property_exists($b, 'timestamp'))) {
3150 return 1;
3151 }
3152 if ($a->timestamp == $b->timestamp) {
3153 return 0;
3154 }
3155 return ($a->timestamp < $b->timestamp) ? -1 : 1;
3156}